Search in sources :

Example 1 with ServiceAuthException

use of org.apache.ofbiz.service.ServiceAuthException 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 2 with ServiceAuthException

use of org.apache.ofbiz.service.ServiceAuthException in project ofbiz-framework by apache.

the class ContentManagementServices method changeLeafToNode.

public static Map<String, Object> changeLeafToNode(DispatchContext dctx, Map<String, ? extends Object> context) throws GenericServiceException {
    Map<String, Object> result = new HashMap<String, Object>();
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Map<String, Object> thisResult = new HashMap<String, Object>();
    String contentId = (String) context.get("contentId");
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    String userLoginId = userLogin.getString("userLoginId");
    Locale locale = (Locale) context.get("locale");
    try {
        GenericValue content = EntityQuery.use(delegator).from("Content").where("contentId", contentId).queryOne();
        if (content == null) {
            Debug.logError("content was null", module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentNoContentFound", UtilMisc.toMap("contentId", ""), locale));
        }
        String dataResourceId = content.getString("dataResourceId");
        content.set("dataResourceId", null);
        content.set("lastModifiedDate", UtilDateTime.nowTimestamp());
        content.set("lastModifiedByUserLogin", userLoginId);
        content.store();
        if (UtilValidate.isNotEmpty(dataResourceId)) {
            // add previous DataResource as part of new subcontent
            GenericValue contentClone = (GenericValue) content.clone();
            contentClone.set("dataResourceId", dataResourceId);
            content.set("lastModifiedDate", UtilDateTime.nowTimestamp());
            content.set("lastModifiedByUserLogin", userLoginId);
            content.set("createdDate", UtilDateTime.nowTimestamp());
            content.set("createdByUserLogin", userLoginId);
            contentClone.set("contentId", null);
            ModelService modelService = dctx.getModelService("persistContentAndAssoc");
            Map<String, Object> serviceIn = modelService.makeValid(contentClone, ModelService.IN_PARAM);
            serviceIn.put("userLogin", userLogin);
            serviceIn.put("contentIdTo", contentId);
            serviceIn.put("contentAssocTypeId", "SUB_CONTENT");
            serviceIn.put("sequenceNum", Long.valueOf(50));
            try {
                thisResult = dispatcher.runSync("persistContentAndAssoc", serviceIn);
                if (ServiceUtil.isError(thisResult)) {
                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(thisResult));
                }
            } catch (ServiceAuthException e) {
                return ServiceUtil.returnError(e.toString());
            }
            List<String> typeList = UtilMisc.toList("SUB_CONTENT");
            ContentManagementWorker.updateStatsTopDown(delegator, contentId, typeList);
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.toString());
    }
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) ServiceAuthException(org.apache.ofbiz.service.ServiceAuthException) Delegator(org.apache.ofbiz.entity.Delegator) HashMap(java.util.HashMap) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ModelService(org.apache.ofbiz.service.ModelService)

Example 3 with ServiceAuthException

use of org.apache.ofbiz.service.ServiceAuthException in project ofbiz-framework by apache.

the class ServiceEventHandler 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 {
    // 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;
    }
    // make 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);
    VisualTheme visualTheme = UtilHttp.getVisualTheme(request);
    HttpSession session = request.getSession();
    GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
    // get the service model to generate context
    ModelService model = null;
    try {
        model = dctx.getModelService(serviceName);
    } catch (GenericServiceException e) {
        throw new EventHandlerException("Problems getting the service model", e);
    }
    if (model == null) {
        throw new EventHandlerException("Problems getting the service model");
    }
    if (Debug.verboseOn()) {
        Debug.logVerbose("[Processing]: SERVICE Event", module);
        Debug.logVerbose("[Using delegator]: " + dispatcher.getDelegator().getDelegatorName(), module);
    }
    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
    Map<String, Object> multiPartMap = new HashMap<String, Object>();
    if (isMultiPart) {
        // get the http upload configuration
        String maxSizeStr = EntityUtilProperties.getPropertyValue("general", "http.upload.max.size", "-1", dctx.getDelegator());
        long maxUploadSize = -1;
        try {
            maxUploadSize = Long.parseLong(maxSizeStr);
        } catch (NumberFormatException e) {
            Debug.logError(e, "Unable to obtain the max upload size from general.properties; using default -1", module);
            maxUploadSize = -1;
        }
        // get the http size threshold configuration - files bigger than this will be
        // temporarly stored on disk during upload
        String sizeThresholdStr = EntityUtilProperties.getPropertyValue("general", "http.upload.max.sizethreshold", "10240", dctx.getDelegator());
        // 10K
        int sizeThreshold = 10240;
        try {
            sizeThreshold = Integer.parseInt(sizeThresholdStr);
        } catch (NumberFormatException e) {
            Debug.logError(e, "Unable to obtain the threshold size from general.properties; using default 10K", module);
            sizeThreshold = -1;
        }
        // directory used to temporarily store files that are larger than the configured size threshold
        String tmpUploadRepository = EntityUtilProperties.getPropertyValue("general", "http.upload.tmprepository", "runtime/tmp", dctx.getDelegator());
        String encoding = request.getCharacterEncoding();
        // check for multipart content types which may have uploaded items
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory(sizeThreshold, new File(tmpUploadRepository)));
        // create the progress listener and add it to the session
        FileUploadProgressListener listener = new FileUploadProgressListener();
        upload.setProgressListener(listener);
        session.setAttribute("uploadProgressListener", listener);
        if (encoding != null) {
            upload.setHeaderEncoding(encoding);
        }
        upload.setSizeMax(maxUploadSize);
        List<FileItem> uploadedItems = null;
        try {
            uploadedItems = UtilGenerics.<FileItem>checkList(upload.parseRequest(request));
        } catch (FileUploadException e) {
            throw new EventHandlerException("Problems reading uploaded data", e);
        }
        if (uploadedItems != null) {
            for (FileItem item : uploadedItems) {
                String fieldName = item.getFieldName();
                /*
                    Debug.logInfo("Item Info [" + fieldName + "] : " + item.getName() + " / " + item.getSize() + " / " +
                            item.getContentType() + " FF: " + item.isFormField(), module);
                    */
                if (item.isFormField() || item.getName() == null) {
                    if (multiPartMap.containsKey(fieldName)) {
                        Object mapValue = multiPartMap.get(fieldName);
                        if (mapValue instanceof List<?>) {
                            checkList(mapValue, Object.class).add(item.getString());
                        } else if (mapValue instanceof String) {
                            List<String> newList = new LinkedList<String>();
                            newList.add((String) mapValue);
                            newList.add(item.getString());
                            multiPartMap.put(fieldName, newList);
                        } else {
                            Debug.logWarning("Form field found [" + fieldName + "] which was not handled!", module);
                        }
                    } else {
                        if (encoding != null) {
                            try {
                                multiPartMap.put(fieldName, item.getString(encoding));
                            } catch (java.io.UnsupportedEncodingException uee) {
                                Debug.logError(uee, "Unsupported Encoding, using deafault", module);
                                multiPartMap.put(fieldName, item.getString());
                            }
                        } else {
                            multiPartMap.put(fieldName, item.getString());
                        }
                    }
                } else {
                    String fileName = item.getName();
                    if (fileName.indexOf('\\') > -1 || fileName.indexOf('/') > -1) {
                        // get just the file name IE and other browsers also pass in the local path
                        int lastIndex = fileName.lastIndexOf('\\');
                        if (lastIndex == -1) {
                            lastIndex = fileName.lastIndexOf('/');
                        }
                        if (lastIndex > -1) {
                            fileName = fileName.substring(lastIndex + 1);
                        }
                    }
                    multiPartMap.put(fieldName, ByteBuffer.wrap(item.get()));
                    multiPartMap.put("_" + fieldName + "_size", Long.valueOf(item.getSize()));
                    multiPartMap.put("_" + fieldName + "_fileName", fileName);
                    multiPartMap.put("_" + fieldName + "_contentType", item.getContentType());
                }
            }
        }
    }
    // store the multi-part map as an attribute so we can access the parameters
    request.setAttribute("multiPartMap", multiPartMap);
    Map<String, Object> rawParametersMap = UtilHttp.getCombinedMap(request);
    Set<String> urlOnlyParameterNames = UtilHttp.getUrlOnlyParameterMap(request).keySet();
    // we have a service and the model; build the context
    Map<String, Object> serviceContext = new HashMap<String, Object>();
    for (ModelParam modelParam : model.getInModelParamList()) {
        String name = modelParam.name;
        // don't include userLogin, that's taken care of below
        if ("userLogin".equals(name))
            continue;
        // don't include locale, that is also taken care of below
        if ("locale".equals(name))
            continue;
        // don't include timeZone, that is also taken care of below
        if ("timeZone".equals(name))
            continue;
        // don't include theme, that is also taken care of below
        if ("visualTheme".equals(name))
            continue;
        Object value = null;
        if (UtilValidate.isNotEmpty(modelParam.stringMapPrefix)) {
            Map<String, Object> paramMap = UtilHttp.makeParamMapWithPrefix(request, multiPartMap, modelParam.stringMapPrefix, null);
            value = paramMap;
            if (Debug.verboseOn())
                Debug.logVerbose("Set [" + modelParam.name + "]: " + paramMap, module);
        } else if (UtilValidate.isNotEmpty(modelParam.stringListSuffix)) {
            List<Object> paramList = UtilHttp.makeParamListWithSuffix(request, multiPartMap, modelParam.stringListSuffix, null);
            value = paramList;
        } else {
            // first check the multi-part map
            value = multiPartMap.get(name);
            // next check attributes; do this before parameters so that attribute which can be changed by code can override parameters which can't
            if (UtilValidate.isEmpty(value)) {
                Object tempVal = request.getAttribute(UtilValidate.isEmpty(modelParam.requestAttributeName) ? name : modelParam.requestAttributeName);
                if (tempVal != null) {
                    value = tempVal;
                }
            }
            // check the request parameters
            if (UtilValidate.isEmpty(value)) {
                ServiceEventHandler.checkSecureParameter(requestMap, urlOnlyParameterNames, name, session, serviceName, dctx.getDelegator());
                // if the service modelParam has allow-html="any" then get this direct from the request instead of in the parameters Map so there will be no canonicalization possibly messing things up
                if ("any".equals(modelParam.allowHtml)) {
                    value = request.getParameter(name);
                } else {
                    // use the rawParametersMap from UtilHttp in order to also get pathInfo parameters, do canonicalization, etc
                    value = rawParametersMap.get(name);
                }
                // 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, name, locale);
                }
            }
            // then session
            if (UtilValidate.isEmpty(value)) {
                Object tempVal = request.getSession().getAttribute(UtilValidate.isEmpty(modelParam.sessionAttributeName) ? name : modelParam.sessionAttributeName);
                if (tempVal != null) {
                    value = tempVal;
                }
            }
            // no field found
            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(name, value);
    }
    // get only the parameters for this service - converted to proper type
    // TODO: pass in a list for error messages, like could not convert type or not a proper X, return immediately with messages if there are any
    List<Object> errorMessages = new LinkedList<Object>();
    serviceContext = model.makeValid(serviceContext, ModelService.IN_PARAM, true, errorMessages, timeZone, locale);
    if (errorMessages.size() > 0) {
        // uh-oh, had some problems...
        request.setAttribute("_ERROR_MESSAGE_LIST_", errorMessages);
        return "error";
    }
    // 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);
    }
    // include the Theme object
    if (visualTheme != null) {
        serviceContext.put("visualTheme", visualTheme);
    }
    // invoke the service
    Map<String, Object> result = null;
    try {
        if (ASYNC.equalsIgnoreCase(mode)) {
            dispatcher.runAsync(serviceName, serviceContext);
        } else {
            result = dispatcher.runSync(serviceName, serviceContext);
        }
    } catch (ServiceAuthException e) {
        // not logging since the service engine already did
        request.setAttribute("_ERROR_MESSAGE_", e.getNonNestedMessage());
        return "error";
    } catch (ServiceValidationException e) {
        // not logging since the service engine already did
        request.setAttribute("serviceValidationException", e);
        if (e.getMessageList() != null) {
            request.setAttribute("_ERROR_MESSAGE_LIST_", e.getMessageList());
        } else {
            request.setAttribute("_ERROR_MESSAGE_", e.getNonNestedMessage());
        }
        return "error";
    } catch (GenericServiceException e) {
        Debug.logError(e, "Service invocation error", module);
        throw new EventHandlerException("Service invocation error", e.getNested());
    }
    String responseString = null;
    if (result == null) {
        responseString = ModelService.RESPOND_SUCCESS;
    } else {
        if (!result.containsKey(ModelService.RESPONSE_MESSAGE)) {
            responseString = ModelService.RESPOND_SUCCESS;
        } else {
            responseString = (String) result.get(ModelService.RESPONSE_MESSAGE);
        }
        // set the messages in the request; this will be picked up by messages.ftl and displayed
        request.setAttribute("_ERROR_MESSAGE_LIST_", result.get(ModelService.ERROR_MESSAGE_LIST));
        request.setAttribute("_ERROR_MESSAGE_MAP_", result.get(ModelService.ERROR_MESSAGE_MAP));
        request.setAttribute("_ERROR_MESSAGE_", result.get(ModelService.ERROR_MESSAGE));
        request.setAttribute("_EVENT_MESSAGE_LIST_", result.get(ModelService.SUCCESS_MESSAGE_LIST));
        request.setAttribute("_EVENT_MESSAGE_", result.get(ModelService.SUCCESS_MESSAGE));
        // set the results in the request
        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)) {
                request.setAttribute(resultKey, resultValue);
            }
        }
    }
    if (Debug.verboseOn())
        Debug.logVerbose("[Event Return]: " + responseString, module);
    return responseString;
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) DispatchContext(org.apache.ofbiz.service.DispatchContext) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) UtilGenerics.checkList(org.apache.ofbiz.base.util.UtilGenerics.checkList) 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) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) LinkedList(java.util.LinkedList) ModelService(org.apache.ofbiz.service.ModelService) FileItem(org.apache.commons.fileupload.FileItem) TimeZone(java.util.TimeZone) VisualTheme(org.apache.ofbiz.widget.renderer.VisualTheme) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map) RequestMap(org.apache.ofbiz.webapp.control.ConfigXMLReader.RequestMap) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 4 with ServiceAuthException

use of org.apache.ofbiz.service.ServiceAuthException in project ofbiz-framework by apache.

the class UploadContentAndImage method processContentUpload.

public static String processContentUpload(Map<String, Object> passedParams, String suffix, HttpServletRequest request) throws GenericServiceException {
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    HttpSession session = request.getSession();
    GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
    Map<String, Object> ftlContext = new HashMap<String, Object>();
    String contentPurposeString = (String) passedParams.get("contentPurposeString" + suffix);
    if (UtilValidate.isEmpty(contentPurposeString)) {
        contentPurposeString = (String) passedParams.get("contentPurposeString");
    }
    List<String> contentPurposeList = StringUtil.split(contentPurposeString, "|");
    ftlContext.put("contentPurposeList", contentPurposeList);
    String targetOperationString = (String) passedParams.get("targetOperationString" + suffix);
    if (UtilValidate.isEmpty(targetOperationString)) {
        targetOperationString = (String) passedParams.get("targetOperationString");
    }
    List<String> targetOperationList = StringUtil.split(targetOperationString, "|");
    ftlContext.put("targetOperationList", targetOperationList);
    ftlContext.put("userLogin", userLogin);
    Object objSequenceNum = passedParams.get("caSequenceNum");
    if (objSequenceNum != null) {
        if (objSequenceNum instanceof String) {
            Long sequenceNum = null;
            try {
                sequenceNum = Long.valueOf((String) objSequenceNum);
            } catch (NumberFormatException e) {
                String msg = "Caught an exception : " + e.toString();
                Debug.logError(e, msg);
                request.setAttribute("_ERROR_MESSAGE_", msg);
                List<String> errorMsgList = UtilGenerics.checkList(request.getAttribute("_EVENT_MESSAGE_LIST_"));
                if (errorMsgList == null) {
                    errorMsgList = new LinkedList<String>();
                    request.setAttribute("errorMessageList", errorMsgList);
                }
                errorMsgList.add(msg);
                return "error";
            }
            passedParams.put("caSequenceNum", sequenceNum);
        }
    }
    ModelEntity modelEntity = delegator.getModelEntity("ContentAssocDataResourceViewFrom");
    List<String> fieldNames = modelEntity.getAllFieldNames();
    Map<String, Object> ftlContext2 = new HashMap<String, Object>();
    Map<String, Object> ftlContext3 = new HashMap<String, Object>();
    for (String keyName : fieldNames) {
        Object obj = passedParams.get(keyName + suffix);
        ftlContext2.put(keyName, obj);
    }
    if (Debug.infoOn()) {
        Debug.logInfo("[UploadContentStuff]ftlContext2:" + ftlContext2, module);
    }
    List<Object> errorMessages = new LinkedList<Object>();
    Locale loc = Locale.getDefault();
    try {
        SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "contentIn", ftlContext2, ftlContext3, errorMessages, loc);
        SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "contentOut", ftlContext3, ftlContext, errorMessages, loc);
        ftlContext3 = new HashMap<String, Object>();
        SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "dataResourceIn", ftlContext2, ftlContext3, errorMessages, loc);
        SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "dataResourceOut", ftlContext3, ftlContext, errorMessages, loc);
        ftlContext3 = new HashMap<String, Object>();
        SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "contentAssocIn", ftlContext2, ftlContext3, errorMessages, loc);
        SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "contentAssocOut", ftlContext3, ftlContext, errorMessages, loc);
    } catch (MiniLangException e) {
        throw new GenericServiceException(e.getMessage());
    }
    ftlContext.put("textData", passedParams.get("textData" + suffix));
    byte[] bytes = (byte[]) passedParams.get("imageData" + suffix);
    ftlContext.put("imageData", bytes);
    if (Debug.infoOn()) {
        Debug.logInfo("[UploadContentStuff]ftlContext:" + ftlContext, module);
    }
    Map<String, Object> ftlResults = null;
    try {
        ftlResults = dispatcher.runSync("persistContentAndAssoc", ftlContext);
    } catch (ServiceAuthException e) {
        String msg = e.getMessage();
        request.setAttribute("_ERROR_MESSAGE_", msg);
        List<String> errorMsgList = UtilGenerics.checkList(request.getAttribute("_EVENT_MESSAGE_LIST_"));
        if (Debug.infoOn()) {
            Debug.logInfo("[UploadContentStuff]errorMsgList:" + errorMsgList, module);
        }
        if (Debug.infoOn()) {
            Debug.logInfo("[UploadContentStuff]msg:" + msg, module);
        }
        if (errorMsgList == null) {
            errorMsgList = new LinkedList<String>();
            request.setAttribute("errorMessageList", errorMsgList);
        }
        errorMsgList.add(msg);
        return "error";
    }
    if (ServiceUtil.isError(ftlResults)) {
        String msg = ServiceUtil.getErrorMessage(ftlResults);
        request.setAttribute("_ERROR_MESSAGE_", msg);
        List<String> errorMsgList = UtilGenerics.checkList(request.getAttribute("_EVENT_MESSAGE_LIST_"));
        if (errorMsgList == null) {
            errorMsgList = new LinkedList<String>();
            request.setAttribute("errorMessageList", errorMsgList);
        }
        errorMsgList.add(msg);
        return "error";
    }
    String returnedContentId = (String) ftlResults.get("contentId");
    if (Debug.infoOn()) {
        Debug.logInfo("returnedContentId:" + returnedContentId, module);
    }
    request.setAttribute("contentId" + suffix, ftlResults.get("contentId"));
    request.setAttribute("caContentIdTo" + suffix, ftlResults.get("contentIdTo"));
    request.setAttribute("caContentIdStart" + suffix, ftlResults.get("contentIdTo"));
    request.setAttribute("caContentAssocTypeId" + suffix, ftlResults.get("contentAssocTypeId"));
    request.setAttribute("caFromDate" + suffix, ftlResults.get("fromDate"));
    request.setAttribute("drDataResourceId" + suffix, ftlResults.get("dataResourceId"));
    request.setAttribute("caContentId" + suffix, ftlResults.get("contentId"));
    String caContentIdTo = (String) passedParams.get("caContentIdTo");
    if (UtilValidate.isNotEmpty(caContentIdTo)) {
        Map<String, Object> resequenceContext = new HashMap<String, Object>();
        resequenceContext.put("contentIdTo", caContentIdTo);
        resequenceContext.put("userLogin", userLogin);
        try {
            ftlResults = dispatcher.runSync("resequence", resequenceContext);
            if (ServiceUtil.isError(ftlResults)) {
                String errorMessage = ServiceUtil.getErrorMessage(ftlResults);
                request.setAttribute("_ERROR_MESSAGE_", errorMessage);
                Debug.logError(errorMessage, module);
                return "error";
            }
        } catch (ServiceAuthException e) {
            String msg = e.getMessage();
            request.setAttribute("_ERROR_MESSAGE_", msg);
            List<String> errorMsgList = UtilGenerics.checkList(request.getAttribute("_EVENT_MESSAGE_LIST_"));
            if (Debug.infoOn()) {
                Debug.logInfo("[UploadContentStuff]errorMsgList:" + errorMsgList, module);
            }
            if (Debug.infoOn()) {
                Debug.logInfo("[UploadContentStuff]msg:" + msg, module);
            }
            if (errorMsgList == null) {
                errorMsgList = new LinkedList<String>();
                request.setAttribute("errorMessageList", errorMsgList);
            }
            errorMsgList.add(msg);
            return "error";
        }
    }
    return "success";
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) ServiceAuthException(org.apache.ofbiz.service.ServiceAuthException) HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) LinkedList(java.util.LinkedList) Delegator(org.apache.ofbiz.entity.Delegator) MiniLangException(org.apache.ofbiz.minilang.MiniLangException) LinkedList(java.util.LinkedList) List(java.util.List) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity)

Aggregations

HashMap (java.util.HashMap)4 Locale (java.util.Locale)4 GenericValue (org.apache.ofbiz.entity.GenericValue)4 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)4 ServiceAuthException (org.apache.ofbiz.service.ServiceAuthException)4 LinkedList (java.util.LinkedList)3 List (java.util.List)3 HttpSession (javax.servlet.http.HttpSession)3 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)3 ModelService (org.apache.ofbiz.service.ModelService)3 Map (java.util.Map)2 TimeZone (java.util.TimeZone)2 Delegator (org.apache.ofbiz.entity.Delegator)2 DispatchContext (org.apache.ofbiz.service.DispatchContext)2 ModelParam (org.apache.ofbiz.service.ModelParam)2 ServiceValidationException (org.apache.ofbiz.service.ServiceValidationException)2 RequestMap (org.apache.ofbiz.webapp.control.ConfigXMLReader.RequestMap)2 File (java.io.File)1 FileItem (org.apache.commons.fileupload.FileItem)1 FileUploadException (org.apache.commons.fileupload.FileUploadException)1