Search in sources :

Example 26 with GenericTransactionException

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

the class SurveyWrapper method getOptionResult.

private Map<String, Object> getOptionResult(GenericValue question) throws SurveyWrapperException {
    Map<String, Object> result = new HashMap<>();
    long total = 0;
    boolean beganTransaction = false;
    try {
        beganTransaction = TransactionUtil.begin();
    } catch (GenericTransactionException gte) {
        Debug.logError(gte, "Unable to begin transaction", module);
    }
    try (EntityListIterator eli = this.getEli(question, -1)) {
        if (eli != null) {
            GenericValue value;
            while (((value = eli.next()) != null)) {
                String optionId = value.getString("surveyOptionSeqId");
                if (UtilValidate.isNotEmpty(optionId)) {
                    Long optCount = (Long) result.remove(optionId);
                    if (optCount == null) {
                        optCount = Long.valueOf(1);
                    } else {
                        optCount = Long.valueOf(1 + optCount.longValue());
                    }
                    result.put(optionId, optCount);
                    // increment the count
                    total++;
                }
            }
        }
    } catch (GenericEntityException e) {
        try {
            // only rollback the transaction if we started one...
            TransactionUtil.rollback(beganTransaction, "Error getting survey question responses Option result", e);
        } catch (GenericEntityException e2) {
            Debug.logError(e2, "Could not rollback transaction: " + e2.toString(), module);
        }
        throw new SurveyWrapperException(e);
    } finally {
        try {
            // only commit the transaction if we started one...
            TransactionUtil.commit(beganTransaction);
        } catch (GenericEntityException e) {
            throw new SurveyWrapperException(e);
        }
    }
    result.put("_total", Long.valueOf(total));
    return result;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) HashMap(java.util.HashMap) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator)

Example 27 with GenericTransactionException

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

the class SurveyWrapper method getNumberResult.

private double[] getNumberResult(GenericValue question, int type) throws SurveyWrapperException {
    double[] result = { 0, 0, 0 };
    // index 0 = total responses
    // index 1 = tally
    // index 2 = average
    boolean beganTransaction = false;
    try {
        beganTransaction = TransactionUtil.begin();
    } catch (GenericTransactionException gte) {
        Debug.logError(gte, "Unable to begin transaction", module);
    }
    try (EntityListIterator eli = this.getEli(question, -1)) {
        if (eli != null) {
            GenericValue value;
            while (((value = eli.next()) != null)) {
                switch(type) {
                    case 1:
                        Long n = value.getLong("numericResponse");
                        if (UtilValidate.isNotEmpty(n)) {
                            result[1] += n.longValue();
                        }
                        break;
                    case 2:
                        Double c = value.getDouble("currencyResponse");
                        if (UtilValidate.isNotEmpty(c)) {
                            result[1] += (((double) Math.round((c.doubleValue() - c.doubleValue()) * 100)) / 100);
                        }
                        break;
                    case 3:
                        Double f = value.getDouble("floatResponse");
                        if (UtilValidate.isNotEmpty(f)) {
                            result[1] += f.doubleValue();
                        }
                        break;
                }
                // increment the count
                result[0]++;
            }
        }
    } catch (GenericEntityException e) {
        try {
            // only rollback the transaction if we started one...
            TransactionUtil.rollback(beganTransaction, "Error getting survey question responses Number result", e);
        } catch (GenericEntityException e2) {
            Debug.logError(e2, "Could not rollback transaction: " + e2.toString(), module);
        }
        throw new SurveyWrapperException(e);
    } finally {
        try {
            // only commit the transaction if we started one...
            TransactionUtil.commit(beganTransaction);
        } catch (GenericEntityException e) {
            throw new SurveyWrapperException(e);
        }
    }
    // average
    switch(type) {
        case 1:
            if (result[0] > 0) {
                result[2] = result[1] / ((long) result[0]);
            }
            break;
        case 2:
            if (result[0] > 0) {
                result[2] = (((double) Math.round((result[1] / result[0]) * 100)) / 100);
            }
            break;
        case 3:
            if (result[0] > 0) {
                result[2] = result[1] / (long) result[0];
            }
            break;
    }
    return result;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator)

Example 28 with GenericTransactionException

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

the class PayPalServices method payPalCheckoutUpdate.

public static Map<String, Object> payPalCheckoutUpdate(DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    HttpServletRequest request = (HttpServletRequest) context.get("request");
    HttpServletResponse response = (HttpServletResponse) context.get("response");
    Map<String, Object> paramMap = UtilHttp.getParameterMap(request);
    String token = (String) paramMap.get("TOKEN");
    WeakReference<ShoppingCart> weakCart = tokenCartMap.get(new TokenWrapper(token));
    ShoppingCart cart = null;
    if (weakCart != null) {
        cart = weakCart.get();
    }
    if (cart == null) {
        Debug.logError("Could locate the ShoppingCart for token " + token, module);
        return ServiceUtil.returnSuccess();
    }
    // Since most if not all of the shipping estimate codes requires a persisted contactMechId we'll create one and
    // then delete once we're done, now is not the time to worry about updating everything
    String contactMechId = null;
    Map<String, Object> inMap = new HashMap<String, Object>();
    inMap.put("address1", paramMap.get("SHIPTOSTREET"));
    inMap.put("address2", paramMap.get("SHIPTOSTREET2"));
    inMap.put("city", paramMap.get("SHIPTOCITY"));
    String countryGeoCode = (String) paramMap.get("SHIPTOCOUNTRY");
    String countryGeoId = PayPalServices.getCountryGeoIdFromGeoCode(countryGeoCode, delegator);
    if (countryGeoId == null) {
        return ServiceUtil.returnSuccess();
    }
    inMap.put("countryGeoId", countryGeoId);
    inMap.put("stateProvinceGeoId", parseStateProvinceGeoId((String) paramMap.get("SHIPTOSTATE"), countryGeoId, delegator));
    inMap.put("postalCode", paramMap.get("SHIPTOZIP"));
    try {
        GenericValue userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", "system").cache().queryOne();
        inMap.put("userLogin", userLogin);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    boolean beganTransaction = false;
    Transaction parentTransaction = null;
    try {
        parentTransaction = TransactionUtil.suspend();
        beganTransaction = TransactionUtil.begin();
    } catch (GenericTransactionException e1) {
        Debug.logError(e1, module);
    }
    try {
        Map<String, Object> outMap = dispatcher.runSync("createPostalAddress", inMap);
        contactMechId = (String) outMap.get("contactMechId");
    } catch (GenericServiceException e) {
        Debug.logError(e.getMessage(), module);
        return ServiceUtil.returnSuccess();
    }
    try {
        TransactionUtil.commit(beganTransaction);
        if (parentTransaction != null)
            TransactionUtil.resume(parentTransaction);
    } catch (GenericTransactionException e) {
        Debug.logError(e, module);
    }
    // clone the cart so we can modify it temporarily
    CheckOutHelper coh = new CheckOutHelper(dispatcher, delegator, cart);
    String oldShipAddress = cart.getShippingContactMechId();
    coh.setCheckOutShippingAddress(contactMechId);
    ShippingEstimateWrapper estWrapper = new ShippingEstimateWrapper(dispatcher, cart, 0);
    int line = 0;
    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "CallbackResponse");
    for (GenericValue shipMethod : estWrapper.getShippingMethods()) {
        BigDecimal estimate = estWrapper.getShippingEstimate(shipMethod);
        // Check that we have a valid estimate (allowing zero value estimates for now)
        if (estimate == null || estimate.compareTo(BigDecimal.ZERO) < 0) {
            continue;
        }
        cart.setAllShipmentMethodTypeId(shipMethod.getString("shipmentMethodTypeId"));
        cart.setAllCarrierPartyId(shipMethod.getString("partyId"));
        try {
            coh.calcAndAddTax();
        } catch (GeneralException e) {
            Debug.logError(e, module);
            continue;
        }
        String estimateLabel = shipMethod.getString("partyId") + " - " + shipMethod.getString("description");
        encoder.add("L_SHIPINGPOPTIONLABEL" + line, estimateLabel);
        encoder.add("L_SHIPPINGOPTIONAMOUNT" + line, estimate.setScale(2, RoundingMode.HALF_UP).toPlainString());
        // Just make this first one default for now
        encoder.add("L_SHIPPINGOPTIONISDEFAULT" + line, line == 0 ? "true" : "false");
        encoder.add("L_TAXAMT" + line, cart.getTotalSalesTax().setScale(2, RoundingMode.HALF_UP).toPlainString());
        line++;
    }
    String responseMsg = null;
    try {
        responseMsg = encoder.encode();
    } catch (PayPalException e) {
        Debug.logError(e, module);
    }
    if (responseMsg != null) {
        try {
            response.setContentLength(responseMsg.getBytes("UTF-8").length);
        } catch (UnsupportedEncodingException e) {
            Debug.logError(e, module);
        }
        try (Writer writer = response.getWriter()) {
            writer.write(responseMsg);
        } catch (IOException e) {
            Debug.logError(e, module);
        }
    }
    // Remove the temporary ship address
    try {
        GenericValue postalAddress = EntityQuery.use(delegator).from("PostalAddress").where("contactMechId", contactMechId).queryOne();
        postalAddress.remove();
        GenericValue contactMech = EntityQuery.use(delegator).from("ContactMech").where("contactMechId", contactMechId).queryOne();
        contactMech.remove();
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    coh.setCheckOutShippingAddress(oldShipAddress);
    return ServiceUtil.returnSuccess();
}
Also used : LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) WeakHashMap(java.util.WeakHashMap) HttpServletRequest(javax.servlet.http.HttpServletRequest) NVPEncoder(com.paypal.sdk.core.nvp.NVPEncoder) GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) HttpServletResponse(javax.servlet.http.HttpServletResponse) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) CheckOutHelper(org.apache.ofbiz.order.shoppingcart.CheckOutHelper) PayPalException(com.paypal.sdk.exceptions.PayPalException) BigDecimal(java.math.BigDecimal) Delegator(org.apache.ofbiz.entity.Delegator) ShoppingCart(org.apache.ofbiz.order.shoppingcart.ShoppingCart) Transaction(javax.transaction.Transaction) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ShippingEstimateWrapper(org.apache.ofbiz.order.shoppingcart.shipping.ShippingEstimateWrapper) Writer(java.io.Writer)

Example 29 with GenericTransactionException

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

the class ContentEvents method updateAllContentKeywords.

/**
 * Updates/adds keywords for all contents
 *
 * @param request HTTPRequest object for the current request
 * @param response HTTPResponse object for the current request
 * @return String specifying the exit status of this event
 */
public static String updateAllContentKeywords(HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    Security security = (Security) request.getAttribute("security");
    String updateMode = "CREATE";
    String errMsg = null;
    String doAll = request.getParameter("doAll");
    // check permissions before moving on...
    if (!security.hasEntityPermission("CONTENTMGR", "_" + updateMode, request.getSession())) {
        Map<String, String> messageMap = UtilMisc.toMap("updateMode", updateMode);
        errMsg = UtilProperties.getMessage(resource, "contentevents.not_sufficient_permissions", messageMap, UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    int numConts = 0;
    int errConts = 0;
    boolean beganTx = false;
    EntityQuery contentQuery = EntityQuery.use(delegator).from("Content");
    try {
        // begin the transaction
        beganTx = TransactionUtil.begin(7200);
        if (Debug.infoOn()) {
            long count = contentQuery.queryCount();
            Debug.logInfo("========== Found " + count + " contents to index ==========", module);
        }
        GenericValue content;
        try (EntityListIterator entityListIterator = contentQuery.queryIterator()) {
            while ((content = entityListIterator.next()) != null) {
                ContentKeywordIndex.indexKeywords(content, "Y".equals(doAll));
                numConts++;
                if (numConts % 500 == 0) {
                    Debug.logInfo("Keywords indexed for " + numConts + " so far", module);
                }
            }
        } catch (GenericEntityException e) {
            errMsg = "[ContentEvents.updateAllContentKeywords] Could not create content-keyword (write error); message: " + e.getMessage();
            Debug.logWarning(errMsg, module);
            errConts++;
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
        }
    } catch (GenericEntityException gee) {
        Debug.logWarning(gee, gee.getMessage(), module);
        Map<String, String> messageMap = UtilMisc.toMap("gee", gee.toString());
        errMsg = UtilProperties.getMessage(resource, "contentevents.error_getting_content_list", messageMap, UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        try {
            TransactionUtil.rollback(beganTx, gee.getMessage(), gee);
        } catch (GenericTransactionException e1) {
            Debug.logError(e1, module);
        }
        return "error";
    }
    // commit the transaction
    try {
        TransactionUtil.commit(beganTx);
    } catch (GenericTransactionException e) {
        Debug.logError(e, module);
    }
    if (errConts == 0) {
        Map<String, String> messageMap = UtilMisc.toMap("numConts", Integer.toString(numConts));
        errMsg = UtilProperties.getMessage(resource, "contentevents.keyword_creation_complete_for_contents", messageMap, UtilHttp.getLocale(request));
        request.setAttribute("_EVENT_MESSAGE_", errMsg);
        return "success";
    } else {
        Map<String, String> messageMap = UtilMisc.toMap("numConts", Integer.toString(numConts));
        messageMap.put("errConts", Integer.toString(errConts));
        errMsg = UtilProperties.getMessage(resource, "contentevents.keyword_creation_complete_for_contents_with_errors", messageMap, UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) Security(org.apache.ofbiz.security.Security) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) Map(java.util.Map)

Example 30 with GenericTransactionException

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

the class EntitySaxReader method endElement.

public void endElement(String namespaceURI, String localName, String fullNameString) throws SAXException {
    if (Debug.verboseOn())
        Debug.logVerbose("endElement: localName=" + localName + ", fullName=" + fullNameString + ", numberRead=" + numberRead, module);
    if ("entity-engine-xml".equals(fullNameString)) {
        return;
    }
    if ("entity-engine-transform-xml".equals(fullNameString)) {
        // transform file & parse it, then return
        URL templateUrl = null;
        try {
            templateUrl = FlexibleLocation.resolveLocation(templatePath.toString());
        } catch (MalformedURLException e) {
            throw new SAXException("Could not find transform template with resource path [" + templatePath + "]; error was: " + e.toString());
        }
        if (templateUrl == null) {
            throw new SAXException("Could not find transform template with resource path: " + templatePath);
        } else {
            try {
                BufferedReader templateReader = new BufferedReader(new InputStreamReader(templateUrl.openStream(), UtilIO.getUtf8()));
                StringWriter outWriter = new StringWriter();
                Configuration config = FreeMarkerWorker.newConfiguration();
                config.setObjectWrapper(FreeMarkerWorker.getDefaultOfbizWrapper());
                config.setSetting("datetime_format", "yyyy-MM-dd HH:mm:ss.SSS");
                Template template = new Template("FMImportFilter", templateReader, config);
                NodeModel nodeModel = NodeModel.wrap(this.rootNodeForTemplate);
                Map<String, Object> context = new HashMap<String, Object>();
                TemplateHashModel staticModels = FreeMarkerWorker.getDefaultOfbizWrapper().getStaticModels();
                context.put("Static", staticModels);
                context.put("doc", nodeModel);
                template.process(context, outWriter);
                String s = outWriter.toString();
                if (Debug.verboseOn())
                    Debug.logVerbose("transformed xml: " + s, module);
                EntitySaxReader reader = new EntitySaxReader(delegator);
                reader.setUseTryInsertMethod(this.useTryInsertMethod);
                try {
                    reader.setTransactionTimeout(this.transactionTimeout);
                } catch (GenericTransactionException e1) {
                    Debug.logWarning("couldn't set tx timeout, hopefully shouldn't be a big deal", module);
                }
                numberRead += reader.parse(s);
            } catch (TemplateException | IOException e) {
                throw new SAXException("Error storing value", e);
            }
        }
        return;
    }
    if (isParseForTemplate) {
        this.currentNodeForTemplate = this.currentNodeForTemplate.getParentNode();
        return;
    }
    // Test if end action tag, set action to default
    if (actionTags.contains(fullNameString)) {
        setAction(Action.CREATE_UPDATE);
        return;
    }
    if (currentValue != null) {
        if (currentFieldName != null) {
            if (UtilValidate.isNotEmpty(currentFieldValue)) {
                if (currentValue.getModelEntity().isField(currentFieldName.toString())) {
                    ModelEntity modelEntity = currentValue.getModelEntity();
                    ModelField modelField = modelEntity.getField(currentFieldName.toString());
                    String type = modelField.getType();
                    if (type != null && "blob".equals(type)) {
                        byte[] binData = Base64.base64Decode((new String(currentFieldValue)).getBytes());
                        currentValue.setBytes(currentFieldName.toString(), binData);
                    } else {
                        currentValue.setString(currentFieldName.toString(), new String(currentFieldValue));
                    }
                } else {
                    Debug.logWarning("Ignoring invalid field name [" + currentFieldName + "] found for the entity: " + currentValue.getEntityName() + " with value=" + currentFieldValue, module);
                }
                currentFieldValue = null;
            }
            currentFieldName = null;
        } else {
            // before we write currentValue check to see if PK is there, if not and it is one field, generate it from a sequence using the entity name
            if (!currentValue.containsPrimaryKey()) {
                if (currentValue.getModelEntity().getPksSize() == 1) {
                    ModelField modelField = currentValue.getModelEntity().getOnlyPk();
                    String newSeq = delegator.getNextSeqId(currentValue.getEntityName());
                    currentValue.setString(modelField.getName(), newSeq);
                } else {
                    throw new SAXException("Cannot store value with incomplete primary key with more than 1 primary key field: " + currentValue);
                }
            }
            try {
                boolean exist = true;
                boolean skip = false;
                // It's necessary to check also for specific action CREATE and DELETE to ensure it's OK
                if (Action.CREATE == currentAction || Action.DELETE == currentAction || Debug.verboseOn()) {
                    GenericHelper helper = delegator.getEntityHelper(currentValue.getEntityName());
                    if (currentValue.containsPrimaryKey()) {
                        try {
                            helper.findByPrimaryKey(currentValue.getPrimaryKey());
                        } catch (GenericEntityNotFoundException e) {
                            exist = false;
                        }
                    }
                    if (Action.CREATE == currentAction && exist) {
                        skip = true;
                    } else if (Action.DELETE == currentAction && !exist) {
                        skip = true;
                    }
                }
                if (!skip) {
                    if (this.useTryInsertMethod && !this.checkDataOnly) {
                        if (Action.DELETE == currentAction) {
                            currentValue.remove();
                        } else {
                            currentValue.create();
                        }
                    } else {
                        if (Action.DELETE == currentAction) {
                            valuesToDelete.add(currentValue);
                            if (valuesToDelete.size() >= valuesPerWrite) {
                                delegator.removeAll(valuesToDelete);
                                valuesToDelete.clear();
                            }
                        } else {
                            valuesToWrite.add(currentValue);
                            if (valuesToWrite.size() >= valuesPerWrite) {
                                writeValues(valuesToWrite);
                                valuesToWrite.clear();
                            }
                        }
                    }
                }
                numberRead++;
                if (Debug.verboseOn())
                    countValue(skip, exist);
                if ((numberRead % valuesPerMessage) == 0) {
                    Debug.logImportant("Another " + valuesPerMessage + " values imported: now up to " + numberRead, module);
                }
                currentValue = null;
            } catch (GenericEntityException e) {
                String errMsg = "Error performing action " + currentAction;
                Debug.logError(e, errMsg, module);
                throw new SAXException(errMsg, e);
            }
        }
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) Configuration(freemarker.template.Configuration) HashMap(java.util.HashMap) URL(java.net.URL) SAXException(org.xml.sax.SAXException) Template(freemarker.template.Template) NodeModel(freemarker.ext.dom.NodeModel) StringWriter(java.io.StringWriter) TemplateHashModel(freemarker.template.TemplateHashModel) ModelField(org.apache.ofbiz.entity.model.ModelField) GenericEntityNotFoundException(org.apache.ofbiz.entity.GenericEntityNotFoundException) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity) InputStreamReader(java.io.InputStreamReader) TemplateException(freemarker.template.TemplateException) IOException(java.io.IOException) GenericHelper(org.apache.ofbiz.entity.datasource.GenericHelper) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) BufferedReader(java.io.BufferedReader) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException)

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