Search in sources :

Example 21 with GenericTransactionException

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

the class GroovyEventHandler method invoke.

public String invoke(Event event, RequestMap requestMap, HttpServletRequest request, HttpServletResponse response) throws EventHandlerException {
    boolean beganTransaction = false;
    try {
        beganTransaction = TransactionUtil.begin();
        Map<String, Object> context = new HashMap<String, Object>();
        context.put("request", request);
        context.put("response", response);
        HttpSession session = request.getSession();
        context.put("session", session);
        context.put("dispatcher", request.getAttribute("dispatcher"));
        context.put("delegator", request.getAttribute("delegator"));
        context.put("security", request.getAttribute("security"));
        context.put("locale", UtilHttp.getLocale(request));
        context.put("timeZone", UtilHttp.getTimeZone(request));
        context.put("userLogin", session.getAttribute("userLogin"));
        context.put(ScriptUtil.PARAMETERS_KEY, UtilHttp.getCombinedMap(request, UtilMisc.toSet("delegator", "dispatcher", "security", "locale", "timeZone", "userLogin")));
        Object result = null;
        try {
            ScriptContext scriptContext = ScriptUtil.createScriptContext(context, protectedKeys);
            ScriptHelper scriptHelper = (ScriptHelper) scriptContext.getAttribute(ScriptUtil.SCRIPT_HELPER_KEY);
            if (scriptHelper != null) {
                context.put(ScriptUtil.SCRIPT_HELPER_KEY, scriptHelper);
            }
            Script script = InvokerHelper.createScript(GroovyUtil.getScriptClassFromLocation(event.path), GroovyUtil.getBinding(context));
            if (UtilValidate.isEmpty(event.invoke)) {
                result = script.run();
            } else {
                result = script.invokeMethod(event.invoke, EMPTY_ARGS);
            }
            if (result == null) {
                result = scriptContext.getAttribute(ScriptUtil.RESULT_KEY);
            }
        } catch (Exception e) {
            Debug.logWarning(e, "Error running event " + event.path + ": ", module);
            request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
            return "error";
        }
        // check the result
        if (result instanceof Map) {
            Map resultMap = (Map) result;
            String successMessage = (String) resultMap.get("_event_message_");
            if (successMessage != null) {
                request.setAttribute("_EVENT_MESSAGE_", successMessage);
            }
            String errorMessage = (String) resultMap.get("_error_message_");
            if (errorMessage != null) {
                request.setAttribute("_ERROR_MESSAGE_", errorMessage);
            }
            return (String) resultMap.get("_response_code_");
        }
        if (result != null && !(result instanceof String)) {
            throw new EventHandlerException("Event did not return a String result, it returned a " + result.getClass().getName());
        }
        return (String) result;
    } catch (Exception e) {
        throw new EventHandlerException("Groovy Event Error", e);
    } finally {
        try {
            TransactionUtil.commit(beganTransaction);
        } catch (GenericTransactionException e) {
            Debug.logError(e, module);
        }
    }
}
Also used : Script(groovy.lang.Script) HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) ScriptContext(javax.script.ScriptContext) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) ScriptHelper(org.apache.ofbiz.base.util.ScriptHelper) HashMap(java.util.HashMap) Map(java.util.Map) RequestMap(org.apache.ofbiz.webapp.control.ConfigXMLReader.RequestMap)

Example 22 with GenericTransactionException

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

the class OrderServices method runSubscriptionAutoReorders.

public static Map<String, Object> runSubscriptionAutoReorders(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    int count = 0;
    Map<String, Object> result = null;
    boolean beganTransaction = false;
    List<EntityExpr> exprs = UtilMisc.toList(EntityCondition.makeCondition("automaticExtend", EntityOperator.EQUALS, "Y"), EntityCondition.makeCondition("orderId", EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition("productId", EntityOperator.NOT_EQUAL, null));
    try {
        beganTransaction = TransactionUtil.begin();
    } catch (GenericTransactionException e1) {
        Debug.logError(e1, "[Delegator] Could not begin transaction: " + e1.toString(), module);
    }
    try (EntityListIterator eli = EntityQuery.use(delegator).from("Subscription").where(exprs).queryIterator()) {
        if (eli != null) {
            GenericValue subscription;
            while (((subscription = eli.next()) != null)) {
                Calendar endDate = Calendar.getInstance();
                endDate.setTime(UtilDateTime.nowTimestamp());
                // Check if today date + cancel period (if provided) is earlier than the thrudate
                int field = Calendar.MONTH;
                if (subscription.get("canclAutmExtTime") != null && subscription.get("canclAutmExtTimeUomId") != null) {
                    if ("TF_day".equals(subscription.getString("canclAutmExtTimeUomId"))) {
                        field = Calendar.DAY_OF_YEAR;
                    } else if ("TF_wk".equals(subscription.getString("canclAutmExtTimeUomId"))) {
                        field = Calendar.WEEK_OF_YEAR;
                    } else if ("TF_mon".equals(subscription.getString("canclAutmExtTimeUomId"))) {
                        field = Calendar.MONTH;
                    } else if ("TF_yr".equals(subscription.getString("canclAutmExtTimeUomId"))) {
                        field = Calendar.YEAR;
                    } else {
                        Debug.logWarning("Don't know anything about canclAutmExtTimeUomId [" + subscription.getString("canclAutmExtTimeUomId") + "], defaulting to month", module);
                    }
                    endDate.add(field, Integer.parseInt(subscription.getString("canclAutmExtTime")));
                }
                Calendar endDateSubscription = Calendar.getInstance();
                endDateSubscription.setTime(subscription.getTimestamp("thruDate"));
                if (endDate.before(endDateSubscription)) {
                    // nor expired yet.....
                    continue;
                }
                result = dispatcher.runSync("loadCartFromOrder", UtilMisc.toMap("orderId", subscription.get("orderId"), "userLogin", userLogin));
                if (ServiceUtil.isError(result)) {
                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result));
                }
                ShoppingCart cart = (ShoppingCart) result.get("shoppingCart");
                // remove former orderId from cart (would cause duplicate entry).
                // orderId is set by order-creation services (including store-specific prefixes, e.g.)
                cart.setOrderId(null);
                // only keep the orderitem with the related product.
                List<ShoppingCartItem> cartItems = cart.items();
                for (ShoppingCartItem shoppingCartItem : cartItems) {
                    if (!subscription.get("productId").equals(shoppingCartItem.getProductId())) {
                        cart.removeCartItem(shoppingCartItem, dispatcher);
                    }
                }
                CheckOutHelper helper = new CheckOutHelper(dispatcher, delegator, cart);
                // store the order
                Map<String, Object> createResp = helper.createOrder(userLogin);
                if (createResp != null && ServiceUtil.isError(createResp)) {
                    Debug.logError("Cannot create order for shopping list - " + subscription, module);
                } else {
                    String orderId = (String) createResp.get("orderId");
                    // authorize the payments
                    Map<String, Object> payRes = null;
                    try {
                        payRes = helper.processPayment(ProductStoreWorker.getProductStore(cart.getProductStoreId(), delegator), userLogin);
                    } catch (GeneralException e) {
                        Debug.logError(e, module);
                    }
                    if (payRes != null && ServiceUtil.isError(payRes)) {
                        Debug.logError("Payment processing problems with shopping list - " + subscription, module);
                    }
                    // remove the automatic extension flag
                    subscription.put("automaticExtend", "N");
                    subscription.store();
                    // send notification
                    if (orderId != null) {
                        dispatcher.runAsync("sendOrderPayRetryNotification", UtilMisc.toMap("orderId", orderId));
                    }
                    count++;
                }
            }
        }
    } catch (GenericServiceException e) {
        Debug.logError("Could call service to create cart", module);
        return ServiceUtil.returnError(e.toString());
    } catch (CartItemModifyException e) {
        Debug.logError("Could not modify cart: " + e.toString(), module);
        return ServiceUtil.returnError(e.toString());
    } catch (GenericEntityException e) {
        try {
            // only rollback the transaction if we started one...
            TransactionUtil.rollback(beganTransaction, "Error creating subscription auto-reorders", e);
        } catch (GenericEntityException e2) {
            Debug.logError(e2, "[Delegator] Could not rollback transaction: " + e2.toString(), module);
        }
        Debug.logError(e, "Error while creating new shopping list based automatic reorder" + e.toString(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "OrderShoppingListCreationError", UtilMisc.toMap("errorString", e.toString()), locale));
    } finally {
        try {
            // only commit the transaction if we started one... this will throw an exception if it fails
            TransactionUtil.commit(beganTransaction);
        } catch (GenericEntityException e) {
            Debug.logError(e, "Could not commit transaction for creating new shopping list based automatic reorder", module);
        }
    }
    return ServiceUtil.returnSuccess(UtilProperties.getMessage(resource, "OrderRunSubscriptionAutoReorders", UtilMisc.toMap("count", count), locale));
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GeneralException(org.apache.ofbiz.base.util.GeneralException) Calendar(com.ibm.icu.util.Calendar) CheckOutHelper(org.apache.ofbiz.order.shoppingcart.CheckOutHelper) Delegator(org.apache.ofbiz.entity.Delegator) ShoppingCart(org.apache.ofbiz.order.shoppingcart.ShoppingCart) CartItemModifyException(org.apache.ofbiz.order.shoppingcart.CartItemModifyException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) ShoppingCartItem(org.apache.ofbiz.order.shoppingcart.ShoppingCartItem) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr)

Example 23 with GenericTransactionException

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

the class UploadContentAndImage method uploadContentStuff.

public static String uploadContentStuff(HttpServletRequest request, HttpServletResponse response) {
    try {
        HttpSession session = request.getSession();
        GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
        ServletFileUpload dfu = new ServletFileUpload(new DiskFileItemFactory(10240, FileUtil.getFile("runtime/tmp")));
        List<FileItem> lst = null;
        try {
            lst = UtilGenerics.checkList(dfu.parseRequest(request));
        } catch (FileUploadException e4) {
            request.setAttribute("_ERROR_MESSAGE_", e4.getMessage());
            Debug.logError("[UploadContentAndImage.uploadContentAndImage] " + e4.getMessage(), module);
            return "error";
        }
        if (lst.size() == 0) {
            request.setAttribute("_ERROR_MESSAGE_", "No files uploaded");
            Debug.logWarning("[DataEvents.uploadImage] No files uploaded", module);
            return "error";
        }
        Map<String, Object> passedParams = new HashMap<String, Object>();
        FileItem fi = null;
        FileItem imageFi = null;
        byte[] imageBytes;
        passedParams.put("userLogin", userLogin);
        for (int i = 0; i < lst.size(); i++) {
            fi = lst.get(i);
            String fieldName = fi.getFieldName();
            if (fi.isFormField()) {
                String fieldStr = fi.getString();
                passedParams.put(fieldName, fieldStr);
            } else if (fieldName.startsWith("imageData")) {
                imageFi = fi;
                String fileName = fi.getName();
                passedParams.put("drObjectInfo", fileName);
                String contentType = fi.getContentType();
                passedParams.put("drMimeTypeId", contentType);
                imageBytes = imageFi.get();
                passedParams.put(fieldName, imageBytes);
                if (Debug.infoOn()) {
                    Debug.logInfo("[UploadContentAndImage]imageData: " + imageBytes.length, module);
                }
            }
        }
        if (Debug.infoOn()) {
            Debug.logInfo("[UploadContentAndImage]passedParams: " + passedParams, module);
        }
        // The number of multi form rows is retrieved
        int rowCount = UtilHttp.getMultiFormRowCount(request);
        if (rowCount < 1) {
            rowCount = 1;
        }
        TransactionUtil.begin();
        for (int i = 0; i < rowCount; i++) {
            String suffix = "_o_" + i;
            if (i == 0) {
                suffix = "";
            }
            String returnMsg = processContentUpload(passedParams, suffix, request);
            if ("error".equals(returnMsg)) {
                try {
                    TransactionUtil.rollback();
                } catch (GenericTransactionException e2) {
                    ServiceUtil.setMessages(request, e2.getMessage(), null, null);
                    return "error";
                }
                return "error";
            }
        }
        TransactionUtil.commit();
    } catch (GenericTransactionException | GenericServiceException e) {
        Debug.logError(e, "[UploadContentAndImage] ", module);
        request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
        try {
            TransactionUtil.rollback();
        } catch (GenericTransactionException e2) {
            request.setAttribute("_ERROR_MESSAGE_", e2.getMessage());
            return "error";
        }
        return "error";
    }
    return "success";
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 24 with GenericTransactionException

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

the class UploadContentAndImage method uploadContentAndImage.

public static String uploadContentAndImage(HttpServletRequest request, HttpServletResponse response) {
    try {
        Locale locale = UtilHttp.getLocale(request);
        LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
        Delegator delegator = (Delegator) request.getAttribute("delegator");
        HttpSession session = request.getSession();
        GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
        ServletFileUpload dfu = new ServletFileUpload(new DiskFileItemFactory(10240, FileUtil.getFile("runtime/tmp")));
        List<FileItem> lst = null;
        try {
            lst = UtilGenerics.checkList(dfu.parseRequest(request));
        } catch (FileUploadException e4) {
            request.setAttribute("_ERROR_MESSAGE_", e4.getMessage());
            Debug.logError("[UploadContentAndImage.uploadContentAndImage] " + e4.getMessage(), module);
            return "error";
        }
        if (lst.size() == 0) {
            String errMsg = UtilProperties.getMessage(UploadContentAndImage.err_resource, "uploadContentAndImage.no_files_uploaded", locale);
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            Debug.logWarning("[DataEvents.uploadImage] No files uploaded", module);
            return "error";
        }
        Map<String, Object> passedParams = new HashMap<String, Object>();
        FileItem fi = null;
        FileItem imageFi = null;
        byte[] imageBytes = {};
        for (int i = 0; i < lst.size(); i++) {
            fi = lst.get(i);
            String fieldName = fi.getFieldName();
            if (fi.isFormField()) {
                String fieldStr = fi.getString();
                passedParams.put(fieldName, fieldStr);
            } else if ("imageData".equals(fieldName)) {
                imageFi = fi;
                imageBytes = imageFi.get();
            }
        }
        if (Debug.infoOn()) {
            Debug.logInfo("[UploadContentAndImage]passedParams: " + passedParams, module);
        }
        TransactionUtil.begin();
        List<String> contentPurposeList = ContentWorker.prepContentPurposeList(passedParams);
        passedParams.put("contentPurposeList", contentPurposeList);
        String entityOperation = (String) passedParams.get("entityOperation");
        String passedContentId = (String) passedParams.get("ftlContentId");
        List<String> targetOperationList = ContentWorker.prepTargetOperationList(passedParams, entityOperation);
        passedParams.put("targetOperationList", targetOperationList);
        // Create or update FTL template
        Map<String, Object> ftlContext = new HashMap<String, Object>();
        ftlContext.put("userLogin", userLogin);
        ftlContext.put("contentId", passedParams.get("ftlContentId"));
        ftlContext.put("ownerContentId", passedParams.get("ownerContentId"));
        String contentTypeId = (String) passedParams.get("contentTypeId");
        ftlContext.put("contentTypeId", contentTypeId);
        ftlContext.put("statusId", passedParams.get("statusId"));
        ftlContext.put("contentPurposeList", UtilMisc.toList(passedParams.get("contentPurposeList")));
        ftlContext.put("contentPurposeList", contentPurposeList);
        ftlContext.put("targetOperationList", targetOperationList);
        ftlContext.put("contentName", passedParams.get("contentName"));
        ftlContext.put("dataTemplateTypeId", passedParams.get("dataTemplateTypeId"));
        ftlContext.put("description", passedParams.get("description"));
        ftlContext.put("privilegeEnumId", passedParams.get("privilegeEnumId"));
        String drid = (String) passedParams.get("dataResourceId");
        ftlContext.put("dataResourceId", drid);
        // inhibits persistence of DataResource, because it already exists
        ftlContext.put("dataResourceTypeId", null);
        String contentIdTo = (String) passedParams.get("contentIdTo");
        ftlContext.put("contentIdTo", contentIdTo);
        String contentAssocTypeId = (String) passedParams.get("contentAssocTypeId");
        // Don't post assoc at this time
        ftlContext.put("contentAssocTypeId", null);
        Map<String, Object> ftlResults = dispatcher.runSync("persistContentAndAssoc", ftlContext);
        if (ServiceUtil.isError(ftlResults)) {
            String errorMessage = ServiceUtil.getErrorMessage(ftlResults);
            request.setAttribute("_ERROR_MESSAGE_", errorMessage);
            Debug.logError(errorMessage, module);
            TransactionUtil.rollback();
            return "error";
        }
        String ftlContentId = (String) ftlResults.get("contentId");
        if (UtilValidate.isNotEmpty(contentIdTo)) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("fromDate", UtilDateTime.nowTimestamp());
            map.put("contentId", ftlContentId);
            map.put("contentIdTo", contentIdTo);
            map.put("userLogin", userLogin);
            if (UtilValidate.isEmpty(contentAssocTypeId) && UtilValidate.isEmpty(passedContentId) && UtilValidate.isNotEmpty(contentIdTo)) {
                // switch the association order because we are really not linking to the forum
                // but showing that this content is released to that forum.
                map.put("contentIdTo", ftlContentId);
                map.put("contentId", contentIdTo);
                map.put("contentAssocTypeId", "PUBLISH_RELEASE");
            } else if ("PUBLISH_LINK".equals(contentAssocTypeId)) {
                map.put("contentAssocTypeId", "PUBLISH_LINK");
                String publishOperation = (String) passedParams.get("publishOperation");
                if (UtilValidate.isEmpty(publishOperation)) {
                    publishOperation = "CONTENT_PUBLISH";
                }
                map.put("targetOperationList", StringUtil.split(publishOperation, "|"));
                map.put("targetOperationString", null);
            } else {
                map.put("contentAssocTypeId", contentAssocTypeId);
            }
            if (UtilValidate.isNotEmpty(map.get("contentAssocTypeId"))) {
                ftlResults = dispatcher.runSync("createContentAssoc", map);
                if (ServiceUtil.isError(ftlResults)) {
                    String errorMessage = ServiceUtil.getErrorMessage(ftlResults);
                    request.setAttribute("_ERROR_MESSAGE_", errorMessage);
                    Debug.logError(errorMessage, module);
                    TransactionUtil.rollback();
                    return "error";
                }
            }
        }
        if (UtilValidate.isEmpty(ftlContentId)) {
            ftlContentId = passedContentId;
        }
        String ftlDataResourceId = drid;
        if (Debug.infoOn())
            Debug.logInfo("[UploadContentAndImage]ftlContentId:" + ftlContentId, module);
        // Create or update summary text subContent
        if (passedParams.containsKey("summaryData")) {
            Map<String, Object> sumContext = new HashMap<String, Object>();
            sumContext.put("userLogin", userLogin);
            sumContext.put("contentId", passedParams.get("sumContentId"));
            sumContext.put("ownerContentId", ftlContentId);
            sumContext.put("contentTypeId", "DOCUMENT");
            sumContext.put("statusId", passedParams.get("statusId"));
            sumContext.put("contentPurposeList", UtilMisc.toList("SUMMARY"));
            sumContext.put("targetOperationList", targetOperationList);
            sumContext.put("contentName", passedParams.get("contentName"));
            sumContext.put("description", passedParams.get("description"));
            sumContext.put("privilegeEnumId", passedParams.get("privilegeEnumId"));
            sumContext.put("dataResourceId", passedParams.get("sumDataResourceId"));
            sumContext.put("dataResourceTypeId", "ELECTRONIC_TEXT");
            sumContext.put("contentIdTo", ftlContentId);
            sumContext.put("contentAssocTypeId", "SUB_CONTENT");
            sumContext.put("textData", passedParams.get("summaryData"));
            sumContext.put("mapKey", "SUMMARY");
            sumContext.put("dataTemplateTypeId", "NONE");
            Map<String, Object> sumResults = dispatcher.runSync("persistContentAndAssoc", sumContext);
            if (ServiceUtil.isError(ftlResults)) {
                String errorMessage = ServiceUtil.getErrorMessage(ftlResults);
                request.setAttribute("_ERROR_MESSAGE_", errorMessage);
                Debug.logError(errorMessage, module);
                TransactionUtil.rollback();
                return "error";
            }
        }
        // Create or update electronic text subContent
        if (passedParams.containsKey("textData")) {
            Map<String, Object> txtContext = new HashMap<String, Object>();
            txtContext.put("userLogin", userLogin);
            txtContext.put("contentId", passedParams.get("txtContentId"));
            txtContext.put("ownerContentId", ftlContentId);
            txtContext.put("contentTypeId", "DOCUMENT");
            txtContext.put("statusId", passedParams.get("statusId"));
            txtContext.put("contentPurposeList", UtilMisc.toList("MAIN_ARTICLE"));
            txtContext.put("targetOperationList", targetOperationList);
            txtContext.put("contentName", passedParams.get("contentName"));
            txtContext.put("description", passedParams.get("description"));
            txtContext.put("privilegeEnumId", passedParams.get("privilegeEnumId"));
            txtContext.put("dataResourceId", passedParams.get("txtDataResourceId"));
            txtContext.put("dataResourceTypeId", "ELECTRONIC_TEXT");
            txtContext.put("contentIdTo", ftlContentId);
            txtContext.put("contentAssocTypeId", "SUB_CONTENT");
            txtContext.put("textData", passedParams.get("textData"));
            txtContext.put("mapKey", "ARTICLE");
            txtContext.put("dataTemplateTypeId", "NONE");
            Map<String, Object> txtResults = dispatcher.runSync("persistContentAndAssoc", txtContext);
            if (ServiceUtil.isError(ftlResults)) {
                String errorMessage = ServiceUtil.getErrorMessage(ftlResults);
                request.setAttribute("_ERROR_MESSAGE_", errorMessage);
                Debug.logError(errorMessage, module);
                TransactionUtil.rollback();
                return "error";
            }
        }
        // Create or update image subContent
        Map<String, Object> imgContext = new HashMap<String, Object>();
        if (imageBytes.length > 0) {
            imgContext.put("userLogin", userLogin);
            imgContext.put("contentId", passedParams.get("imgContentId"));
            imgContext.put("ownerContentId", ftlContentId);
            imgContext.put("contentTypeId", "DOCUMENT");
            imgContext.put("statusId", passedParams.get("statusId"));
            imgContext.put("contentName", passedParams.get("contentName"));
            imgContext.put("description", passedParams.get("description"));
            imgContext.put("contentPurposeList", contentPurposeList);
            imgContext.put("privilegeEnumId", passedParams.get("privilegeEnumId"));
            imgContext.put("targetOperationList", targetOperationList);
            imgContext.put("dataResourceId", passedParams.get("imgDataResourceId"));
            String dataResourceTypeId = "IMAGE_OBJECT";
            imgContext.put("dataResourceTypeId", dataResourceTypeId);
            imgContext.put("contentIdTo", ftlContentId);
            imgContext.put("contentAssocTypeId", "SUB_CONTENT");
            imgContext.put("imageData", imageBytes);
            imgContext.put("mapKey", "IMAGE");
            imgContext.put("dataTemplateTypeId", "NONE");
            imgContext.put("rootDir", "rootDir");
            if (Debug.infoOn())
                Debug.logInfo("[UploadContentAndImage]imgContext " + imgContext, module);
            Map<String, Object> imgResults = dispatcher.runSync("persistContentAndAssoc", imgContext);
            if (ServiceUtil.isError(ftlResults)) {
                String errorMessage = ServiceUtil.getErrorMessage(ftlResults);
                request.setAttribute("_ERROR_MESSAGE_", errorMessage);
                Debug.logError(errorMessage, module);
                TransactionUtil.rollback();
                return "error";
            }
        }
        // Check for existing AUTHOR link
        String userLoginId = userLogin.getString("userLoginId");
        GenericValue authorContent = EntityQuery.use(delegator).from("Content").where("contentId", userLoginId).cache().queryOne();
        if (authorContent != null) {
            long currentAuthorAssocCount = EntityQuery.use(delegator).from("ContentAssoc").where("contentId", ftlContentId, "contentIdTo", userLoginId, "contentAssocTypeId", "AUTHOR").filterByDate().queryCount();
            if (currentAuthorAssocCount == 0) {
                // Don't want to bother with permission checking on this association
                GenericValue authorAssoc = delegator.makeValue("ContentAssoc");
                authorAssoc.set("contentId", ftlContentId);
                authorAssoc.set("contentIdTo", userLoginId);
                authorAssoc.set("contentAssocTypeId", "AUTHOR");
                authorAssoc.set("fromDate", UtilDateTime.nowTimestamp());
                authorAssoc.set("createdByUserLogin", userLoginId);
                authorAssoc.set("lastModifiedByUserLogin", userLoginId);
                authorAssoc.set("createdDate", UtilDateTime.nowTimestamp());
                authorAssoc.set("lastModifiedDate", UtilDateTime.nowTimestamp());
                authorAssoc.create();
            }
        }
        request.setAttribute("dataResourceId", ftlDataResourceId);
        request.setAttribute("drDataResourceId", ftlDataResourceId);
        request.setAttribute("contentId", ftlContentId);
        request.setAttribute("masterContentId", ftlContentId);
        request.setAttribute("contentIdTo", contentIdTo);
        String newTrail = passedParams.get("nodeTrailCsv") + "," + ftlContentId;
        request.setAttribute("nodeTrailCsv", newTrail);
        request.setAttribute("passedParams", passedParams);
        TransactionUtil.commit();
    } catch (GenericEntityException | GenericServiceException e) {
        Debug.logError(e, "[UploadContentAndImage] ", module);
        request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
        try {
            TransactionUtil.rollback();
        } catch (GenericTransactionException e2) {
            request.setAttribute("_ERROR_MESSAGE_", e2.getMessage());
            return "error";
        }
        return "error";
    }
    return "success";
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) 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) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 25 with GenericTransactionException

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

the class SurveyWrapper method getQuestionResponses.

public List<GenericValue> getQuestionResponses(GenericValue question, int startIndex, int number) throws SurveyWrapperException {
    List<GenericValue> resp = null;
    boolean beganTransaction = false;
    int maxRows = startIndex + number;
    try {
        beganTransaction = TransactionUtil.begin();
    } catch (GenericTransactionException gte) {
        Debug.logError(gte, "Unable to begin transaction", module);
    }
    try (EntityListIterator eli = this.getEli(question, maxRows)) {
        if (startIndex > 0 && number > 0) {
            resp = eli.getPartialList(startIndex, number);
        } else {
            resp = eli.getCompleteList();
        }
    } catch (GenericEntityException e) {
        try {
            // only rollback the transaction if we started one...
            TransactionUtil.rollback(beganTransaction, "Error getting survey question responses", 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);
        }
    }
    return resp;
}
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)

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