Search in sources :

Example 11 with GenericTransactionException

use of org.apache.ofbiz.entity.transaction.GenericTransactionException in project ofbiz-framework by apache.

the class ServiceUtil method purgeOldJobs.

public static Map<String, Object> purgeOldJobs(DispatchContext dctx, Map<String, ? extends Object> context) {
    Locale locale = (Locale) context.get("locale");
    Debug.logWarning("purgeOldJobs service invoked. This service is obsolete - the Job Scheduler will purge old jobs automatically.", module);
    String sendPool = null;
    Calendar cal = Calendar.getInstance();
    try {
        sendPool = ServiceConfigUtil.getServiceEngine().getThreadPool().getSendToPool();
        int daysToKeep = ServiceConfigUtil.getServiceEngine().getThreadPool().getPurgeJobDays();
        cal.add(Calendar.DAY_OF_YEAR, -daysToKeep);
    } catch (GenericConfigException e) {
        Debug.logWarning(e, "Exception thrown while getting service configuration: ", module);
        return returnError(UtilProperties.getMessage(ServiceUtil.resource, "ServiceExceptionThrownWhileGettingServiceConfiguration", UtilMisc.toMap("errorString", e), locale));
    }
    Delegator delegator = dctx.getDelegator();
    Timestamp purgeTime = new Timestamp(cal.getTimeInMillis());
    // create the conditions to query
    EntityCondition pool = EntityCondition.makeCondition("poolId", sendPool);
    List<EntityExpr> finExp = UtilMisc.toList(EntityCondition.makeCondition("finishDateTime", EntityOperator.NOT_EQUAL, null));
    finExp.add(EntityCondition.makeCondition("finishDateTime", EntityOperator.LESS_THAN, purgeTime));
    List<EntityExpr> canExp = UtilMisc.toList(EntityCondition.makeCondition("cancelDateTime", EntityOperator.NOT_EQUAL, null));
    canExp.add(EntityCondition.makeCondition("cancelDateTime", EntityOperator.LESS_THAN, purgeTime));
    EntityCondition cancelled = EntityCondition.makeCondition(canExp);
    EntityCondition finished = EntityCondition.makeCondition(finExp);
    EntityCondition doneCond = EntityCondition.makeCondition(UtilMisc.toList(cancelled, finished), EntityOperator.OR);
    // always suspend the current transaction; use the one internally
    Transaction parent = null;
    try {
        if (TransactionUtil.getStatus() != TransactionUtil.STATUS_NO_TRANSACTION) {
            parent = TransactionUtil.suspend();
        }
        // lookup the jobs - looping 1000 at a time to avoid problems with cursors
        // also, using unique transaction to delete as many as possible even with errors
        boolean noMoreResults = false;
        boolean beganTx1 = false;
        while (!noMoreResults) {
            // current list of records
            List<GenericValue> curList = null;
            try {
                // begin this transaction
                beganTx1 = TransactionUtil.begin();
                EntityQuery eq = EntityQuery.use(delegator).select("jobId").from("JobSandbox").where(EntityCondition.makeCondition(UtilMisc.toList(doneCond, pool))).cursorScrollInsensitive().maxRows(1000);
                try (EntityListIterator foundJobs = eq.queryIterator()) {
                    curList = foundJobs.getPartialList(1, 1000);
                }
            } catch (GenericEntityException e) {
                Debug.logError(e, "Cannot obtain job data from datasource", module);
                try {
                    TransactionUtil.rollback(beganTx1, e.getMessage(), e);
                } catch (GenericTransactionException e1) {
                    Debug.logWarning(e1, module);
                }
                return ServiceUtil.returnError(e.getMessage());
            } finally {
                try {
                    TransactionUtil.commit(beganTx1);
                } catch (GenericTransactionException e) {
                    Debug.logWarning(e, module);
                }
            }
            // remove each from the list in its own transaction
            if (UtilValidate.isNotEmpty(curList)) {
                for (GenericValue job : curList) {
                    String jobId = job.getString("jobId");
                    boolean beganTx2 = false;
                    try {
                        beganTx2 = TransactionUtil.begin();
                        job.remove();
                    } catch (GenericEntityException e) {
                        Debug.logInfo("Cannot remove job data for ID: " + jobId, module);
                        try {
                            TransactionUtil.rollback(beganTx2, e.getMessage(), e);
                        } catch (GenericTransactionException e1) {
                            Debug.logWarning(e1, module);
                        }
                    } finally {
                        try {
                            TransactionUtil.commit(beganTx2);
                        } catch (GenericTransactionException e) {
                            Debug.logWarning(e, module);
                        }
                    }
                }
            } else {
                noMoreResults = true;
            }
        }
        // Now JobSandbox data is cleaned up. Now process Runtime data and remove the whole data in single shot that is of no need.
        boolean beganTx3 = false;
        GenericValue runtimeData = null;
        List<GenericValue> runtimeDataToDelete = new LinkedList<>();
        long jobsandBoxCount = 0;
        try {
            // begin this transaction
            beganTx3 = TransactionUtil.begin();
            EntityQuery eq = EntityQuery.use(delegator).select("runtimeDataId").from("RuntimeData");
            try (EntityListIterator runTimeDataIt = eq.queryIterator()) {
                while ((runtimeData = runTimeDataIt.next()) != null) {
                    EntityCondition whereCondition = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("runtimeDataId", EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition("runtimeDataId", EntityOperator.EQUALS, runtimeData.getString("runtimeDataId"))), EntityOperator.AND);
                    jobsandBoxCount = EntityQuery.use(delegator).from("JobSandbox").where(whereCondition).queryCount();
                    if (BigDecimal.ZERO.compareTo(BigDecimal.valueOf(jobsandBoxCount)) == 0) {
                        runtimeDataToDelete.add(runtimeData);
                    }
                }
            }
            // Now we are ready to delete runtimeData, we can safely delete complete list that we have recently fetched i.e runtimeDataToDelete.
            delegator.removeAll(runtimeDataToDelete);
        } catch (GenericEntityException e) {
            Debug.logError(e, "Cannot obtain runtime data from datasource", module);
            try {
                TransactionUtil.rollback(beganTx3, e.getMessage(), e);
            } catch (GenericTransactionException e1) {
                Debug.logWarning(e1, module);
            }
            return ServiceUtil.returnError(e.getMessage());
        } finally {
            try {
                TransactionUtil.commit(beganTx3);
            } catch (GenericTransactionException e) {
                Debug.logWarning(e, module);
            }
        }
    } catch (GenericTransactionException e) {
        Debug.logError(e, "Unable to suspend transaction; cannot purge jobs!", module);
        return ServiceUtil.returnError(e.getMessage());
    } finally {
        if (parent != null) {
            try {
                TransactionUtil.resume(parent);
            } catch (GenericTransactionException e) {
                Debug.logWarning(e, module);
            }
        }
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) Calendar(com.ibm.icu.util.Calendar) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) Timestamp(java.sql.Timestamp) LinkedList(java.util.LinkedList) GenericConfigException(org.apache.ofbiz.base.config.GenericConfigException) Delegator(org.apache.ofbiz.entity.Delegator) Transaction(javax.transaction.Transaction) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr)

Example 12 with GenericTransactionException

use of org.apache.ofbiz.entity.transaction.GenericTransactionException in project ofbiz-framework by apache.

the class WebToolsServices method entityExportAll.

public static Map<String, Object> entityExportAll(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    Locale locale = (Locale) context.get("locale");
    // mandatory
    String outpath = (String) context.get("outpath");
    Timestamp fromDate = (Timestamp) context.get("fromDate");
    Integer txTimeout = (Integer) context.get("txTimeout");
    if (txTimeout == null) {
        txTimeout = Integer.valueOf(7200);
    }
    List<String> results = new LinkedList<String>();
    if (UtilValidate.isNotEmpty(outpath)) {
        File outdir = new File(outpath);
        if (!outdir.exists()) {
            outdir.mkdir();
        }
        if (outdir.isDirectory() && outdir.canWrite()) {
            Set<String> passedEntityNames;
            try {
                ModelReader reader = delegator.getModelReader();
                Collection<String> ec = reader.getEntityNames();
                passedEntityNames = new TreeSet<String>(ec);
            } catch (Exception exc) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityImportErrorRetrievingEntityNames", locale));
            }
            int fileNumber = 1;
            for (String curEntityName : passedEntityNames) {
                long numberWritten = 0;
                ModelEntity me = delegator.getModelEntity(curEntityName);
                if (me instanceof ModelViewEntity) {
                    results.add("[" + fileNumber + "] [vvv] " + curEntityName + " skipping view entity");
                    continue;
                }
                List<EntityCondition> conds = new LinkedList<EntityCondition>();
                if (UtilValidate.isNotEmpty(fromDate)) {
                    conds.add(EntityCondition.makeCondition("createdStamp", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
                }
                EntityQuery eq = EntityQuery.use(delegator).from(curEntityName).where(conds).orderBy(me.getPkFieldNames());
                try {
                    boolean beganTx = TransactionUtil.begin();
                    // Don't bother writing the file if there's nothing to put into it
                    try (EntityListIterator values = eq.queryIterator()) {
                        GenericValue value = values.next();
                        if (value != null) {
                            try (PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(outdir, curEntityName + ".xml")), "UTF-8")))) {
                                writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                                writer.println("<entity-engine-xml>");
                                do {
                                    value.writeXmlText(writer, "");
                                    numberWritten++;
                                    if (numberWritten % 500 == 0) {
                                        TransactionUtil.commit(beganTx);
                                        beganTx = TransactionUtil.begin();
                                    }
                                } while ((value = values.next()) != null);
                                writer.println("</entity-engine-xml>");
                            } catch (UnsupportedEncodingException | FileNotFoundException e) {
                                results.add("[" + fileNumber + "] [xxx] Error when writing " + curEntityName + ": " + e);
                            }
                            results.add("[" + fileNumber + "] [" + numberWritten + "] " + curEntityName + " wrote " + numberWritten + " records");
                        } else {
                            results.add("[" + fileNumber + "] [---] " + curEntityName + " has no records, not writing file");
                        }
                        TransactionUtil.commit(beganTx);
                    } catch (GenericEntityException entityEx) {
                        results.add("[" + fileNumber + "] [xxx] Error when writing " + curEntityName + ": " + entityEx);
                        continue;
                    }
                    fileNumber++;
                } catch (GenericTransactionException e) {
                    Debug.logError(e, module);
                    results.add(e.getLocalizedMessage());
                }
            }
        } else {
            results.add("Path not found or no write access.");
        }
    } else {
        results.add("No path specified, doing nothing.");
    }
    // send the notification
    Map<String, Object> resp = UtilMisc.<String, Object>toMap("results", results);
    return resp;
}
Also used : Locale(java.util.Locale) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) FileNotFoundException(java.io.FileNotFoundException) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) Timestamp(java.sql.Timestamp) BufferedWriter(java.io.BufferedWriter) ModelReader(org.apache.ofbiz.entity.model.ModelReader) ModelViewEntity(org.apache.ofbiz.entity.model.ModelViewEntity) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity) PrintWriter(java.io.PrintWriter) GenericValue(org.apache.ofbiz.entity.GenericValue) UnsupportedEncodingException(java.io.UnsupportedEncodingException) LinkedList(java.util.LinkedList) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) FileNotFoundException(java.io.FileNotFoundException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) SAXException(org.xml.sax.SAXException) GeneralException(org.apache.ofbiz.base.util.GeneralException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) FileOutputStream(java.io.FileOutputStream) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) OutputStreamWriter(java.io.OutputStreamWriter) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) File(java.io.File)

Example 13 with GenericTransactionException

use of org.apache.ofbiz.entity.transaction.GenericTransactionException in project ofbiz-framework by apache.

the class ServiceMultiEventHandler method invoke.

/**
 * @see org.apache.ofbiz.webapp.event.EventHandler#invoke(ConfigXMLReader.Event, ConfigXMLReader.RequestMap, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
public String invoke(Event event, RequestMap requestMap, HttpServletRequest request, HttpServletResponse response) throws EventHandlerException {
    // TODO: consider changing this to use the new UtilHttp.parseMultiFormData method
    // make sure we have a valid reference to the Service Engine
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    if (dispatcher == null) {
        throw new EventHandlerException("The local service dispatcher is null");
    }
    DispatchContext dctx = dispatcher.getDispatchContext();
    if (dctx == null) {
        throw new EventHandlerException("Dispatch context cannot be found");
    }
    // get the details for the service(s) to call
    String mode = SYNC;
    String serviceName = null;
    if (UtilValidate.isEmpty(event.path)) {
        mode = SYNC;
    } else {
        mode = event.path;
    }
    // we only support SYNC mode in this handler
    if (!SYNC.equals(mode)) {
        throw new EventHandlerException("Async mode is not supported");
    }
    // nake sure we have a defined service to call
    serviceName = event.invoke;
    if (serviceName == null) {
        throw new EventHandlerException("Service name (eventMethod) cannot be null");
    }
    if (Debug.verboseOn())
        Debug.logVerbose("[Set mode/service]: " + mode + "/" + serviceName, module);
    // some needed info for when running the service
    Locale locale = UtilHttp.getLocale(request);
    TimeZone timeZone = UtilHttp.getTimeZone(request);
    HttpSession session = request.getSession();
    GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
    // get the service model to generate context(s)
    ModelService modelService = null;
    try {
        modelService = dctx.getModelService(serviceName);
    } catch (GenericServiceException e) {
        throw new EventHandlerException("Problems getting the service model", e);
    }
    if (modelService == null) {
        throw new EventHandlerException("Problems getting the service model");
    }
    if (Debug.verboseOn())
        Debug.logVerbose("[Processing]: SERVICE Event", module);
    if (Debug.verboseOn())
        Debug.logVerbose("[Using delegator]: " + dispatcher.getDelegator().getDelegatorName(), module);
    // check if we are using per row submit
    boolean useRowSubmit = request.getParameter("_useRowSubmit") == null ? false : "Y".equalsIgnoreCase(request.getParameter("_useRowSubmit"));
    // check if we are to also look in a global scope (no delimiter)
    boolean checkGlobalScope = request.getParameter("_checkGlobalScope") == null ? true : !"N".equalsIgnoreCase(request.getParameter("_checkGlobalScope"));
    // The number of multi form rows is retrieved
    int rowCount = UtilHttp.getMultiFormRowCount(request);
    if (rowCount < 1) {
        throw new EventHandlerException("No rows to process");
    }
    // some default message settings
    String errorPrefixStr = UtilProperties.getMessage("DefaultMessagesUiLabels", "service.error.prefix", locale);
    String errorSuffixStr = UtilProperties.getMessage("DefaultMessagesUiLabels", "service.error.suffix", locale);
    String messagePrefixStr = UtilProperties.getMessage("DefaultMessagesUiLabels", "service.message.prefix", locale);
    String messageSuffixStr = UtilProperties.getMessage("DefaultMessagesUiLabels", "service.message.suffix", locale);
    // prepare the error message and success message lists
    List<Object> errorMessages = new LinkedList<Object>();
    List<String> successMessages = new LinkedList<String>();
    // Check the global-transaction attribute of the event from the controller to see if the
    // event should be wrapped in a transaction
    String requestUri = RequestHandler.getRequestUri(request.getPathInfo());
    ConfigXMLReader.ControllerConfig controllerConfig;
    try {
        controllerConfig = ConfigXMLReader.getControllerConfig(ConfigXMLReader.getControllerConfigURL(servletContext));
    } catch (WebAppConfigurationException e) {
        throw new EventHandlerException(e);
    }
    boolean eventGlobalTransaction;
    try {
        eventGlobalTransaction = controllerConfig.getRequestMapMap().get(requestUri).event.globalTransaction;
    } catch (WebAppConfigurationException e) {
        throw new EventHandlerException(e);
    }
    Set<String> urlOnlyParameterNames = UtilHttp.getUrlOnlyParameterMap(request).keySet();
    // big try/finally to make sure commit or rollback are run
    boolean beganTrans = false;
    String returnString = null;
    try {
        if (eventGlobalTransaction) {
            // start the global transaction
            try {
                beganTrans = TransactionUtil.begin(modelService.transactionTimeout * rowCount);
            } catch (GenericTransactionException e) {
                throw new EventHandlerException("Problem starting multi-service global transaction", e);
            }
        }
        // now loop throw the rows and prepare/invoke the service for each
        for (int i = 0; i < rowCount; i++) {
            String curSuffix = UtilHttp.getMultiRowDelimiter() + i;
            boolean rowSelected = false;
            if (UtilValidate.isNotEmpty(request.getAttribute(UtilHttp.getRowSubmitPrefix() + i))) {
                rowSelected = request.getAttribute(UtilHttp.getRowSubmitPrefix() + i) == null ? false : "Y".equalsIgnoreCase((String) request.getAttribute(UtilHttp.getRowSubmitPrefix() + i));
            } else {
                rowSelected = request.getParameter(UtilHttp.getRowSubmitPrefix() + i) == null ? false : "Y".equalsIgnoreCase(request.getParameter(UtilHttp.getRowSubmitPrefix() + i));
            }
            // make sure we are to process this row
            if (useRowSubmit && !rowSelected) {
                continue;
            }
            // build the context
            Map<String, Object> serviceContext = new HashMap<String, Object>();
            for (ModelParam modelParam : modelService.getInModelParamList()) {
                String paramName = modelParam.name;
                // don't include userLogin, that's taken care of below
                if ("userLogin".equals(paramName))
                    continue;
                // don't include locale, that is also taken care of below
                if ("locale".equals(paramName))
                    continue;
                // don't include timeZone, that is also taken care of below
                if ("timeZone".equals(paramName))
                    continue;
                Object value = null;
                if (UtilValidate.isNotEmpty(modelParam.stringMapPrefix)) {
                    Map<String, Object> paramMap = UtilHttp.makeParamMapWithPrefix(request, modelParam.stringMapPrefix, curSuffix);
                    value = paramMap;
                } else if (UtilValidate.isNotEmpty(modelParam.stringListSuffix)) {
                    List<Object> paramList = UtilHttp.makeParamListWithSuffix(request, modelParam.stringListSuffix, null);
                    value = paramList;
                } else {
                    // check attributes; do this before parameters so that attribute which can be changed by code can override parameters which can't
                    value = request.getAttribute(paramName + curSuffix);
                    // first check for request parameters
                    if (value == null) {
                        String name = paramName + curSuffix;
                        ServiceEventHandler.checkSecureParameter(requestMap, urlOnlyParameterNames, name, session, serviceName, dctx.getDelegator());
                        String[] paramArr = request.getParameterValues(name);
                        if (paramArr != null) {
                            if (paramArr.length > 1) {
                                value = Arrays.asList(paramArr);
                            } else {
                                value = paramArr[0];
                            }
                        }
                    }
                    // if the parameter wasn't passed and no other value found, check the session
                    if (value == null) {
                        value = session.getAttribute(paramName + curSuffix);
                    }
                    // now check global scope
                    if (value == null) {
                        if (checkGlobalScope) {
                            String[] gParamArr = request.getParameterValues(paramName);
                            if (gParamArr != null) {
                                if (gParamArr.length > 1) {
                                    value = Arrays.asList(gParamArr);
                                } else {
                                    value = gParamArr[0];
                                }
                            }
                            if (value == null) {
                                value = request.getAttribute(paramName);
                            }
                            if (value == null) {
                                value = session.getAttribute(paramName);
                            }
                        }
                    }
                    // make any composite parameter data (e.g., from a set of parameters {name_c_date, name_c_hour, name_c_minutes})
                    if (value == null) {
                        value = UtilHttp.makeParamValueFromComposite(request, paramName + curSuffix, locale);
                    }
                    if (value == null) {
                        // still null, give up for this one
                        continue;
                    }
                    if (value instanceof String && ((String) value).length() == 0) {
                        // interpreting empty fields as null values for each in back end handling...
                        value = null;
                    }
                }
                // set even if null so that values will get nulled in the db later on
                serviceContext.put(paramName, value);
            // Debug.logInfo("In ServiceMultiEventHandler got value [" + value + "] for input parameter [" + paramName + "] for service [" + serviceName + "]", module);
            }
            // get only the parameters for this service - converted to proper type
            serviceContext = modelService.makeValid(serviceContext, ModelService.IN_PARAM, true, null, timeZone, locale);
            // include the UserLogin value object
            if (userLogin != null) {
                serviceContext.put("userLogin", userLogin);
            }
            // include the Locale object
            if (locale != null) {
                serviceContext.put("locale", locale);
            }
            // include the TimeZone object
            if (timeZone != null) {
                serviceContext.put("timeZone", timeZone);
            }
            // Debug.logInfo("ready to call " + serviceName + " with context " + serviceContext, module);
            // invoke the service
            Map<String, Object> result = null;
            try {
                result = dispatcher.runSync(serviceName, serviceContext);
            } catch (ServiceAuthException e) {
                // not logging since the service engine already did
                errorMessages.add(messagePrefixStr + "Service invocation error on row (" + i + "): " + e.getNonNestedMessage());
            } catch (ServiceValidationException e) {
                // not logging since the service engine already did
                request.setAttribute("serviceValidationException", e);
                List<String> errors = e.getMessageList();
                if (errors != null) {
                    for (String message : errors) {
                        errorMessages.add("Service invocation error on row (" + i + "): " + message);
                    }
                } else {
                    errorMessages.add(messagePrefixStr + "Service invocation error on row (" + i + "): " + e.getNonNestedMessage());
                }
            } catch (GenericServiceException e) {
                Debug.logError(e, "Service invocation error", module);
                errorMessages.add(messagePrefixStr + "Service invocation error on row (" + i + "): " + e.getNested() + messageSuffixStr);
            }
            if (result == null) {
                returnString = ModelService.RESPOND_SUCCESS;
            } else {
                // check for an error message
                String errorMessage = ServiceUtil.makeErrorMessage(result, messagePrefixStr, messageSuffixStr, "", "");
                if (UtilValidate.isNotEmpty(errorMessage)) {
                    errorMessages.add(errorMessage);
                }
                // get the success messages
                if (UtilValidate.isNotEmpty(result.get(ModelService.SUCCESS_MESSAGE))) {
                    String newSuccessMessage = (String) result.get(ModelService.SUCCESS_MESSAGE);
                    if (!successMessages.contains(newSuccessMessage)) {
                        successMessages.add(newSuccessMessage);
                    }
                }
                if (UtilValidate.isNotEmpty(result.get(ModelService.SUCCESS_MESSAGE_LIST))) {
                    List<String> newSuccessMessages = UtilGenerics.<String>checkList(result.get(ModelService.SUCCESS_MESSAGE_LIST));
                    for (int j = 0; j < newSuccessMessages.size(); j++) {
                        String newSuccessMessage = newSuccessMessages.get(j);
                        if (!successMessages.contains(newSuccessMessage)) {
                            successMessages.add(newSuccessMessage);
                        }
                    }
                }
            }
            // set the results in the request
            if ((result != null) && (result.entrySet() != null)) {
                for (Map.Entry<String, Object> rme : result.entrySet()) {
                    String resultKey = rme.getKey();
                    Object resultValue = rme.getValue();
                    if (resultKey != null && !ModelService.RESPONSE_MESSAGE.equals(resultKey) && !ModelService.ERROR_MESSAGE.equals(resultKey) && !ModelService.ERROR_MESSAGE_LIST.equals(resultKey) && !ModelService.ERROR_MESSAGE_MAP.equals(resultKey) && !ModelService.SUCCESS_MESSAGE.equals(resultKey) && !ModelService.SUCCESS_MESSAGE_LIST.equals(resultKey)) {
                        // set the result to request w/ and w/o a suffix to handle both cases: to have the result in each iteration and to prevent its overriding
                        request.setAttribute(resultKey + curSuffix, resultValue);
                        request.setAttribute(resultKey, resultValue);
                    }
                }
            }
        }
    } finally {
        if (errorMessages.size() > 0) {
            if (eventGlobalTransaction) {
                // rollback the global transaction
                try {
                    TransactionUtil.rollback(beganTrans, "Error in multi-service event handling: " + errorMessages.toString(), null);
                } catch (GenericTransactionException e) {
                    Debug.logError(e, "Could not rollback multi-service global transaction", module);
                }
            }
            errorMessages.add(0, errorPrefixStr);
            errorMessages.add(errorSuffixStr);
            StringBuilder errorBuf = new StringBuilder();
            for (Object em : errorMessages) {
                errorBuf.append(em + "\n");
            }
            request.setAttribute("_ERROR_MESSAGE_", errorBuf.toString());
            returnString = "error";
        } else {
            if (eventGlobalTransaction) {
                // commit the global transaction
                try {
                    TransactionUtil.commit(beganTrans);
                } catch (GenericTransactionException e) {
                    Debug.logError(e, "Could not commit multi-service global transaction", module);
                    throw new EventHandlerException("Commit multi-service global transaction failed");
                }
            }
            if (successMessages.size() > 0) {
                request.setAttribute("_EVENT_MESSAGE_LIST_", successMessages);
            }
            returnString = "success";
        }
    }
    return returnString;
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) WebAppConfigurationException(org.apache.ofbiz.webapp.control.WebAppConfigurationException) DispatchContext(org.apache.ofbiz.service.DispatchContext) LinkedList(java.util.LinkedList) List(java.util.List) GenericValue(org.apache.ofbiz.entity.GenericValue) ServiceAuthException(org.apache.ofbiz.service.ServiceAuthException) ServiceValidationException(org.apache.ofbiz.service.ServiceValidationException) HttpSession(javax.servlet.http.HttpSession) ModelParam(org.apache.ofbiz.service.ModelParam) LinkedList(java.util.LinkedList) ModelService(org.apache.ofbiz.service.ModelService) TimeZone(java.util.TimeZone) ConfigXMLReader(org.apache.ofbiz.webapp.control.ConfigXMLReader) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) HashMap(java.util.HashMap) Map(java.util.Map) RequestMap(org.apache.ofbiz.webapp.control.ConfigXMLReader.RequestMap)

Example 14 with GenericTransactionException

use of org.apache.ofbiz.entity.transaction.GenericTransactionException in project ofbiz-framework by apache.

the class WorldPayEvents method worldPayNotify.

/**
 * WorldPay notification
 */
public static String worldPayNotify(HttpServletRequest request, HttpServletResponse response) {
    Locale locale = UtilHttp.getLocale(request);
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
    Map<String, Object> parametersMap = UtilHttp.getParameterMap(request);
    String orderId = request.getParameter("cartId");
    for (String name : parametersMap.keySet()) {
        String value = request.getParameter(name);
        Debug.logError("### Param: " + name + " => " + value, module);
    }
    // get the user
    if (userLogin == null) {
        String userLoginId = "system";
        try {
            userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", userLoginId).queryOne();
        } catch (GenericEntityException e) {
            Debug.logError(e, "Cannot get UserLogin for: " + userLoginId + "; cannot continue", module);
            request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resourceErr, "worldPayEvents.problemsGettingAuthenticationUser", locale));
            return "error";
        }
    }
    // get the order header
    GenericValue orderHeader = null;
    if (UtilValidate.isNotEmpty(orderId)) {
        try {
            orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne();
        } catch (GenericEntityException e) {
            Debug.logError(e, "Cannot get the order header for order: " + orderId, module);
            request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resourceErr, "worldPayEvents.problemsGettingOrderHeader", locale));
            return "error";
        }
    } else {
        Debug.logError("WorldPay did not callback with a valid orderId!", module);
        request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resourceErr, "worldPayEvents.noValidOrderIdReturned", locale));
        return "error";
    }
    if (orderHeader == null) {
        Debug.logError("Cannot get the order header for order: " + orderId, module);
        request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resourceErr, "worldPayEvents.problemsGettingOrderHeader", locale));
        return "error";
    }
    // get the transaction status
    String paymentStatus = request.getParameter("transStatus");
    // attempt to start a transaction
    boolean okay = true;
    boolean beganTransaction = false;
    try {
        beganTransaction = TransactionUtil.begin();
        // authorized
        if ("Y".equals(paymentStatus)) {
            okay = OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId);
        // cancelled
        } else if ("C".equals(paymentStatus)) {
            okay = OrderChangeHelper.cancelOrder(dispatcher, userLogin, orderId);
        }
        if (okay) {
            // set the payment preference
            okay = setPaymentPreferences(delegator, dispatcher, userLogin, orderId, request);
        }
    } catch (Exception e) {
        String errMsg = "Error handling WorldPay notification";
        Debug.logError(e, errMsg, module);
        try {
            TransactionUtil.rollback(beganTransaction, errMsg, e);
        } catch (GenericTransactionException gte2) {
            Debug.logError(gte2, "Unable to rollback transaction", module);
        }
    } finally {
        if (!okay) {
            try {
                TransactionUtil.rollback(beganTransaction, "Failure in processing WorldPay callback", null);
            } catch (GenericTransactionException gte) {
                Debug.logError(gte, "Unable to rollback transaction", module);
            }
        } else {
            try {
                TransactionUtil.commit(beganTransaction);
            } catch (GenericTransactionException gte) {
                Debug.logError(gte, "Unable to commit transaction", module);
            }
        }
    }
    if (okay) {
        // call the email confirm service
        Map<String, Object> emailContext = UtilMisc.toMap("orderId", orderId, "userLogin", userLogin);
        try {
            dispatcher.runSync("sendOrderConfirmation", emailContext);
        } catch (GenericServiceException e) {
            Debug.logError(e, "Problems sending email confirmation", module);
        }
    }
    return "success";
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) IOException(java.io.IOException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException)

Example 15 with GenericTransactionException

use of org.apache.ofbiz.entity.transaction.GenericTransactionException in project ofbiz-framework by apache.

the class PayPalEvents method payPalIPN.

/**
 * PayPal Call-Back Event
 * @throws IOException
 */
public static String payPalIPN(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Locale locale = UtilHttp.getLocale(request);
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    // get the product store
    GenericValue productStore = ProductStoreWorker.getProductStore(request);
    if (productStore == null) {
        Debug.logError("ProductStore is null", module);
        request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resourceErr, "payPalEvents.problemsGettingMerchantConfiguration", locale));
        return "error";
    }
    // get the payment properties file
    GenericValue paymentConfig = ProductStoreWorker.getProductStorePaymentSetting(delegator, productStore.getString("productStoreId"), "EXT_PAYPAL", null, true);
    String configString = null;
    String paymentGatewayConfigId = null;
    if (paymentConfig != null) {
        paymentGatewayConfigId = paymentConfig.getString("paymentGatewayConfigId");
        configString = paymentConfig.getString("paymentPropertiesPath");
    }
    if (configString == null) {
        configString = "payment.properties";
    }
    // get the confirm URL
    String confirmUrl = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "confirmUrl", configString, "payment.paypal.confirm");
    // get the redirect URL
    String redirectUrl = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "redirectUrl", configString, "payment.paypal.redirect");
    if (UtilValidate.isEmpty(confirmUrl) || UtilValidate.isEmpty(redirectUrl)) {
        Debug.logError("Payment properties is not configured properly, no confirm URL defined!", module);
        request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resourceErr, "payPalEvents.problemsGettingMerchantConfiguration", locale));
        return "error";
    }
    // first verify this is valid from PayPal
    Map<String, Object> parametersMap = UtilHttp.getParameterMap(request);
    parametersMap.put("cmd", "_notify-validate");
    // send off the confirm request
    String confirmResp = null;
    String str = UtilHttp.urlEncodeArgs(parametersMap);
    URL u = new URL(redirectUrl);
    URLConnection uc = u.openConnection();
    uc.setDoOutput(true);
    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    try (BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
        PrintWriter pw = new PrintWriter(new OutputStreamWriter(uc.getOutputStream(), "UTF-8"))) {
        pw.println(str);
        confirmResp = in.readLine();
        Debug.logError("PayPal Verification Response: " + confirmResp, module);
    } catch (IOException e) {
        Debug.logError(e, "Problems sending verification message.", module);
    }
    Debug.logInfo("Got verification from PayPal, processing..", module);
    boolean verified = false;
    for (String name : parametersMap.keySet()) {
        String value = request.getParameter(name);
        Debug.logError("### Param: " + name + " => " + value, module);
        if (UtilValidate.isNotEmpty(name) && "payer_status".equalsIgnoreCase(name) && UtilValidate.isNotEmpty(value) && "verified".equalsIgnoreCase(value)) {
            verified = true;
        }
    }
    if (!verified) {
        Debug.logError("###### PayPal did not verify this request, need investigation!", module);
    }
    // get the system user
    GenericValue userLogin = null;
    try {
        userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", "system").queryOne();
    } catch (GenericEntityException e) {
        Debug.logError(e, "Cannot get UserLogin for: system; cannot continue", module);
        request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resourceErr, "payPalEvents.problemsGettingAuthenticationUser", locale));
        return "error";
    }
    // get the orderId
    String orderId = request.getParameter("invoice");
    // get the order header
    GenericValue orderHeader = null;
    if (UtilValidate.isNotEmpty(orderId)) {
        try {
            orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne();
        } catch (GenericEntityException e) {
            Debug.logError(e, "Cannot get the order header for order: " + orderId, module);
            request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resourceErr, "payPalEvents.problemsGettingOrderHeader", locale));
            return "error";
        }
    } else {
        Debug.logError("PayPal did not callback with a valid orderId!", module);
        request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resourceErr, "payPalEvents.noValidOrderIdReturned", locale));
        return "error";
    }
    if (orderHeader == null) {
        Debug.logError("Cannot get the order header for order: " + orderId, module);
        request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resourceErr, "payPalEvents.problemsGettingOrderHeader", locale));
        return "error";
    }
    // get the transaction status
    String paymentStatus = request.getParameter("payment_status");
    // attempt to start a transaction
    boolean okay = true;
    boolean beganTransaction = false;
    try {
        beganTransaction = TransactionUtil.begin();
        if ("Completed".equals(paymentStatus)) {
            okay = OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId);
        } else if ("Failed".equals(paymentStatus) || "Denied".equals(paymentStatus)) {
            okay = OrderChangeHelper.cancelOrder(dispatcher, userLogin, orderId);
        }
        if (okay) {
            // set the payment preference
            okay = setPaymentPreferences(delegator, dispatcher, userLogin, orderId, request);
        }
    } catch (Exception e) {
        String errMsg = "Error handling PayPal notification";
        Debug.logError(e, errMsg, module);
        try {
            TransactionUtil.rollback(beganTransaction, errMsg, e);
        } catch (GenericTransactionException gte2) {
            Debug.logError(gte2, "Unable to rollback transaction", module);
        }
    } finally {
        if (!okay) {
            try {
                TransactionUtil.rollback(beganTransaction, "Failure in processing PayPal callback", null);
            } catch (GenericTransactionException gte) {
                Debug.logError(gte, "Unable to rollback transaction", module);
            }
        } else {
            try {
                TransactionUtil.commit(beganTransaction);
            } catch (GenericTransactionException gte) {
                Debug.logError(gte, "Unable to commit transaction", module);
            }
        }
    }
    if (okay) {
        // call the email confirm service
        Map<String, String> emailContext = UtilMisc.toMap("orderId", orderId);
        try {
            dispatcher.runSync("sendOrderConfirmation", emailContext);
        } catch (GenericServiceException e) {
            Debug.logError(e, "Problems sending email confirmation", module);
        }
    }
    return "success";
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) InputStreamReader(java.io.InputStreamReader) IOException(java.io.IOException) URL(java.net.URL) URLConnection(java.net.URLConnection) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ParseException(java.text.ParseException) IOException(java.io.IOException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) BufferedReader(java.io.BufferedReader) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) OutputStreamWriter(java.io.OutputStreamWriter) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) PrintWriter(java.io.PrintWriter)

Aggregations

GenericTransactionException (org.apache.ofbiz.entity.transaction.GenericTransactionException)49 GenericValue (org.apache.ofbiz.entity.GenericValue)37 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)35 Delegator (org.apache.ofbiz.entity.Delegator)24 Locale (java.util.Locale)18 EntityListIterator (org.apache.ofbiz.entity.util.EntityListIterator)18 HashMap (java.util.HashMap)14 Timestamp (java.sql.Timestamp)13 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)12 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)12 Transaction (javax.transaction.Transaction)11 Map (java.util.Map)10 IOException (java.io.IOException)9 LinkedList (java.util.LinkedList)9 GeneralException (org.apache.ofbiz.base.util.GeneralException)6 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)5 ModelEntity (org.apache.ofbiz.entity.model.ModelEntity)5 EntityQuery (org.apache.ofbiz.entity.util.EntityQuery)5 HttpSession (javax.servlet.http.HttpSession)4 List (java.util.List)3