Search in sources :

Example 6 with ModelService

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

the class SetServiceFields method exec.

@Override
public boolean exec(MethodContext methodContext) throws MiniLangException {
    Map<String, ? extends Object> fromMap = mapFma.get(methodContext.getEnvMap());
    if (fromMap == null) {
        if (Debug.verboseOn()) {
            Debug.logVerbose("The from map in set-service-field was not found with name: " + mapFma, module);
        }
        return true;
    }
    String serviceName = serviceNameFse.expandString(methodContext.getEnvMap());
    ModelService modelService = null;
    try {
        modelService = methodContext.getDispatcher().getDispatchContext().getModelService(serviceName);
    } catch (GenericServiceException e) {
        throw new MiniLangRuntimeException("Could not get service definition for service name \"" + serviceName + "\": " + e.getMessage(), this);
    }
    Map<String, Object> toMap = toMapFma.get(methodContext.getEnvMap());
    if (toMap == null) {
        toMap = new HashMap<String, Object>();
        toMapFma.put(methodContext.getEnvMap(), toMap);
    }
    List<Object> errorMessages = new LinkedList<Object>();
    Map<String, Object> validAttributes = modelService.makeValid(fromMap, mode, true, errorMessages, methodContext.getTimeZone(), methodContext.getLocale());
    if (errorMessages.size() > 0) {
        for (Object obj : errorMessages) {
            simpleMethod.addErrorMessage(methodContext, (String) obj);
        }
        throw new MiniLangRuntimeException("Errors encountered while setting service attributes for service name \"" + serviceName + "\"", this);
    }
    toMap.putAll(validAttributes);
    return true;
}
Also used : MiniLangRuntimeException(org.apache.ofbiz.minilang.MiniLangRuntimeException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) LinkedList(java.util.LinkedList) ModelService(org.apache.ofbiz.service.ModelService)

Example 7 with ModelService

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

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

the class ModelFormFieldBuilder method induceFieldInfoFromServiceParam.

private boolean induceFieldInfoFromServiceParam(String defaultFieldType, ModelReader entityModelReader, DispatchContext dispatchContext) {
    if (UtilValidate.isEmpty(this.getServiceName()) || UtilValidate.isEmpty(this.getAttributeName())) {
        return false;
    }
    try {
        ModelService modelService = dispatchContext.getModelService(this.getServiceName());
        ModelParam modelParam = modelService.getParam(this.getAttributeName());
        if (modelParam != null) {
            if (UtilValidate.isNotEmpty(modelParam.entityName) && UtilValidate.isNotEmpty(modelParam.fieldName)) {
                this.entityName = modelParam.entityName;
                this.fieldName = modelParam.fieldName;
                if (this.induceFieldInfoFromEntityField(defaultFieldType, entityModelReader)) {
                    return true;
                }
            }
            this.induceFieldInfoFromServiceParam(modelService, modelParam, defaultFieldType);
            return true;
        }
    } catch (GenericServiceException e) {
        Debug.logError(e, "error getting service parameter definition for auto-field with serviceName: " + this.getServiceName() + ", and attributeName: " + this.getAttributeName(), module);
    }
    return false;
}
Also used : ModelParam(org.apache.ofbiz.service.ModelParam) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ModelService(org.apache.ofbiz.service.ModelService)

Example 9 with ModelService

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

the class CoreEvents method runService.

/**
 * Run a service.
 *  Request Parameters which are used for this event:
 *  SERVICE_NAME      - Name of the service to invoke
 *
 * @param request HttpServletRequest
 * @param response HttpServletResponse
 * @return Response code string
 */
public static String runService(HttpServletRequest request, HttpServletResponse response) {
    // get the mode and service name
    String serviceName = request.getParameter("serviceName");
    String mode = request.getParameter("mode");
    Locale locale = UtilHttp.getLocale(request);
    if (UtilValidate.isEmpty(serviceName)) {
        String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.must_specify_service_name", locale);
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    if (UtilValidate.isEmpty(mode)) {
        mode = "sync";
    }
    // now do a security check
    Security security = (Security) request.getAttribute("security");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    // lookup the service definition to see if this service is externally available, if not require the SERVICE_INVOKE_ANY permission
    ModelService modelService = null;
    try {
        modelService = dispatcher.getDispatchContext().getModelService(serviceName);
    } catch (GenericServiceException e) {
        Debug.logError(e, "Error looking up ModelService for serviceName [" + serviceName + "]", module);
        String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.error_modelservice_for_srv_name", locale);
        request.setAttribute("_ERROR_MESSAGE_", errMsg + "[" + serviceName + "]: " + e.toString());
        return "error";
    }
    if (modelService == null) {
        String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.service_name_not_find", locale);
        request.setAttribute("_ERROR_MESSAGE_", errMsg + "[" + serviceName + "]");
        return "error";
    }
    if (!modelService.export && !security.hasPermission("SERVICE_INVOKE_ANY", request.getSession())) {
        String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.not_authorized_to_call", locale);
        request.setAttribute("_ERROR_MESSAGE_", errMsg + ".");
        return "error";
    }
    Debug.logInfo("Running service named [" + serviceName + "] from event with mode [" + mode + "]", module);
    // call the service via the ServiceEventHandler which
    // adapts an event to a service.
    Event event = new Event("service", mode, serviceName, false);
    try {
        return seh.invoke(event, null, request, response);
    } catch (EventHandlerException e) {
        String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.service_eventhandler_exception", locale);
        request.setAttribute("_ERROR_MESSAGE_", errMsg + ": " + e.getMessage());
        return "error";
    }
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) Event(org.apache.ofbiz.webapp.control.ConfigXMLReader.Event) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) Security(org.apache.ofbiz.security.Security) ModelService(org.apache.ofbiz.service.ModelService)

Example 10 with ModelService

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

the class CoreEvents method scheduleService.

/**
 * Schedule a service for a specific time or recurrence
 *  Request Parameters which are used for this service:
 *
 *  SERVICE_NAME      - Name of the service to invoke
 *  SERVICE_TIME      - First time the service will occur
 *  SERVICE_FREQUENCY - The type of recurrence (SECONDLY,MINUTELY,DAILY,etc)
 *  SERVICE_INTERVAL  - The interval of the frequency (every 5 minutes, etc)
 *
 * @param request HttpServletRequest
 * @param response HttpServletResponse
 * @return Response code string
 */
public static String scheduleService(HttpServletRequest request, HttpServletResponse response) {
    Security security = (Security) request.getAttribute("security");
    GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    // Delegator delegator = (Delegator) request.getAttribute("delegator");
    Locale locale = UtilHttp.getLocale(request);
    TimeZone timeZone = UtilHttp.getTimeZone(request);
    Map<String, Object> params = UtilHttp.getParameterMap(request);
    // get the schedule parameters
    String jobName = (String) params.remove("JOB_NAME");
    String serviceName = (String) params.remove("SERVICE_NAME");
    String poolName = (String) params.remove("POOL_NAME");
    String serviceTime = (String) params.remove("SERVICE_TIME");
    String serviceEndTime = (String) params.remove("SERVICE_END_TIME");
    String serviceFreq = (String) params.remove("SERVICE_FREQUENCY");
    String serviceIntr = (String) params.remove("SERVICE_INTERVAL");
    String serviceCnt = (String) params.remove("SERVICE_COUNT");
    String retryCnt = (String) params.remove("SERVICE_MAXRETRY");
    // the frequency map
    Map<String, Integer> freqMap = new HashMap<String, Integer>();
    freqMap.put("SECONDLY", Integer.valueOf(1));
    freqMap.put("MINUTELY", Integer.valueOf(2));
    freqMap.put("HOURLY", Integer.valueOf(3));
    freqMap.put("DAILY", Integer.valueOf(4));
    freqMap.put("WEEKLY", Integer.valueOf(5));
    freqMap.put("MONTHLY", Integer.valueOf(6));
    freqMap.put("YEARLY", Integer.valueOf(7));
    // some defaults
    long startTime = (new Date()).getTime();
    long endTime = 0;
    int maxRetry = -1;
    int count = 1;
    int interval = 1;
    int frequency = RecurrenceRule.DAILY;
    StringBuilder errorBuf = new StringBuilder();
    // make sure we passed a service
    if (serviceName == null) {
        String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.must_specify_service", locale);
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    // lookup the service definition to see if this service is externally available, if not require the SERVICE_INVOKE_ANY permission
    ModelService modelService = null;
    try {
        modelService = dispatcher.getDispatchContext().getModelService(serviceName);
    } catch (GenericServiceException e) {
        Debug.logError(e, "Error looking up ModelService for serviceName [" + serviceName + "]", module);
        String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.error_modelservice_for_srv_name", locale);
        request.setAttribute("_ERROR_MESSAGE_", errMsg + " [" + serviceName + "]: " + e.toString());
        return "error";
    }
    if (modelService == null) {
        String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.service_name_not_find", locale);
        request.setAttribute("_ERROR_MESSAGE_", errMsg + " [" + serviceName + "]");
        return "error";
    }
    // make the context valid; using the makeValid method from ModelService
    Map<String, Object> serviceContext = new HashMap<String, Object>();
    Iterator<String> ci = modelService.getInParamNames().iterator();
    while (ci.hasNext()) {
        String name = ci.next();
        // 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;
        Object value = request.getParameter(name);
        // if the parameter wasn't passed and no other value found, don't pass on the null
        if (value == null) {
            value = request.getAttribute(name);
        }
        if (value == null) {
            value = request.getSession().getAttribute(name);
        }
        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);
    }
    serviceContext = modelService.makeValid(serviceContext, ModelService.IN_PARAM, true, null, timeZone, locale);
    if (userLogin != null) {
        serviceContext.put("userLogin", userLogin);
    }
    if (locale != null) {
        serviceContext.put("locale", locale);
    }
    if (!modelService.export && !security.hasPermission("SERVICE_INVOKE_ANY", request.getSession())) {
        String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.not_authorized_to_call", locale);
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    // some conversions
    if (UtilValidate.isNotEmpty(serviceTime)) {
        try {
            Timestamp ts1 = Timestamp.valueOf(serviceTime);
            startTime = ts1.getTime();
        } catch (IllegalArgumentException e) {
            try {
                startTime = Long.parseLong(serviceTime);
            } catch (NumberFormatException nfe) {
                String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.invalid_format_time", locale);
                errorBuf.append(errMsg);
            }
        }
        if (startTime < (new Date()).getTime()) {
            String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.service_time_already_passed", locale);
            errorBuf.append(errMsg);
        }
    }
    if (UtilValidate.isNotEmpty(serviceEndTime)) {
        try {
            Timestamp ts1 = Timestamp.valueOf(serviceEndTime);
            endTime = ts1.getTime();
        } catch (IllegalArgumentException e) {
            try {
                endTime = Long.parseLong(serviceTime);
            } catch (NumberFormatException nfe) {
                String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.invalid_format_time", locale);
                errorBuf.append(errMsg);
            }
        }
        if (endTime < (new Date()).getTime()) {
            String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.service_time_already_passed", locale);
            errorBuf.append(errMsg);
        }
    }
    if (UtilValidate.isNotEmpty(serviceIntr)) {
        try {
            interval = Integer.parseInt(serviceIntr);
        } catch (NumberFormatException nfe) {
            String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.invalid_format_interval", locale);
            errorBuf.append(errMsg);
        }
    }
    if (UtilValidate.isNotEmpty(serviceCnt)) {
        try {
            count = Integer.parseInt(serviceCnt);
        } catch (NumberFormatException nfe) {
            String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.invalid_format_count", locale);
            errorBuf.append(errMsg);
        }
    }
    if (UtilValidate.isNotEmpty(serviceFreq)) {
        int parsedValue = 0;
        try {
            parsedValue = Integer.parseInt(serviceFreq);
            if (parsedValue > 0 && parsedValue < 8)
                frequency = parsedValue;
        } catch (NumberFormatException nfe) {
            parsedValue = 0;
        }
        if (parsedValue == 0) {
            if (!freqMap.containsKey(serviceFreq.toUpperCase())) {
                String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.invalid_format_frequency", locale);
                errorBuf.append(errMsg);
            } else {
                frequency = freqMap.get(serviceFreq.toUpperCase()).intValue();
            }
        }
    }
    if (UtilValidate.isNotEmpty(retryCnt)) {
        int parsedValue = -2;
        try {
            parsedValue = Integer.parseInt(retryCnt);
        } catch (NumberFormatException e) {
            parsedValue = -2;
        }
        if (parsedValue > -2) {
            maxRetry = parsedValue;
        } else {
            maxRetry = modelService.maxRetry;
        }
    } else {
        maxRetry = modelService.maxRetry;
    }
    // return the errors
    if (errorBuf.length() > 0) {
        request.setAttribute("_ERROR_MESSAGE_", errorBuf.toString());
        return "error";
    }
    Map<String, Object> syncServiceResult = null;
    // schedule service
    try {
        if (null != request.getParameter("_RUN_SYNC_") && "Y".equals(request.getParameter("_RUN_SYNC_"))) {
            syncServiceResult = dispatcher.runSync(serviceName, serviceContext);
        } else {
            dispatcher.schedule(jobName, poolName, serviceName, serviceContext, startTime, frequency, interval, count, endTime, maxRetry);
        }
    } catch (GenericServiceException e) {
        String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.service_dispatcher_exception", locale);
        request.setAttribute("_ERROR_MESSAGE_", errMsg + e.getMessage());
        return "error";
    }
    String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.service_scheduled", locale);
    request.setAttribute("_EVENT_MESSAGE_", errMsg);
    if (null != syncServiceResult) {
        request.getSession().setAttribute("_RUN_SYNC_RESULT_", syncServiceResult);
        return "sync_success";
    }
    return "success";
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) Security(org.apache.ofbiz.security.Security) Timestamp(java.sql.Timestamp) Date(java.util.Date) ModelService(org.apache.ofbiz.service.ModelService) TimeZone(java.util.TimeZone) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Aggregations

ModelService (org.apache.ofbiz.service.ModelService)38 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)33 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)28 HashMap (java.util.HashMap)24 GenericValue (org.apache.ofbiz.entity.GenericValue)22 Locale (java.util.Locale)20 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)19 Delegator (org.apache.ofbiz.entity.Delegator)17 ModelParam (org.apache.ofbiz.service.ModelParam)6 ServiceAuthException (org.apache.ofbiz.service.ServiceAuthException)6 LinkedList (java.util.LinkedList)5 Map (java.util.Map)5 GeneralException (org.apache.ofbiz.base.util.GeneralException)5 DispatchContext (org.apache.ofbiz.service.DispatchContext)5 IOException (java.io.IOException)4 BigDecimal (java.math.BigDecimal)4 Timestamp (java.sql.Timestamp)4 ByteBuffer (java.nio.ByteBuffer)3 TimeZone (java.util.TimeZone)3 HttpSession (javax.servlet.http.HttpSession)3