Search in sources :

Example 1 with ModelService

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

the class PromoServices method importPromoCodesFromFile.

public static Map<String, Object> importPromoCodesFromFile(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Locale locale = (Locale) context.get("locale");
    // check the uploaded file
    ByteBuffer fileBytes = (ByteBuffer) context.get("uploadedFile");
    if (fileBytes == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductPromoCodeImportUploadedFileNotValid", locale));
    }
    String encoding = System.getProperty("file.encoding");
    String file = Charset.forName(encoding).decode(fileBytes).toString();
    // get the createProductPromoCode Model
    ModelService promoModel;
    try {
        promoModel = dispatcher.getDispatchContext().getModelService("createProductPromoCode");
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    // make a temp context for invocations
    Map<String, Object> invokeCtx = promoModel.makeValid(context, ModelService.IN_PARAM);
    // read the bytes into a reader
    BufferedReader reader = new BufferedReader(new StringReader(file));
    List<Object> errors = new LinkedList<>();
    int lines = 0;
    String line;
    // read the uploaded file and process each line
    try {
        while ((line = reader.readLine()) != null) {
            // check to see if we should ignore this line
            if (line.length() > 0 && !line.startsWith("#")) {
                if (line.length() <= 20) {
                    // valid promo code
                    Map<String, Object> inContext = new HashMap<>();
                    inContext.putAll(invokeCtx);
                    inContext.put("productPromoCodeId", line);
                    Map<String, Object> result = dispatcher.runSync("createProductPromoCode", inContext);
                    if (result != null && ServiceUtil.isError(result)) {
                        errors.add(line + ": " + ServiceUtil.getErrorMessage(result));
                    }
                } else {
                    // not valid ignore and notify
                    errors.add(line + UtilProperties.getMessage(resource, "ProductPromoCodeInvalidCode", locale));
                }
                ++lines;
            }
        }
    } catch (IOException | GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            Debug.logError(e, module);
        }
    }
    // return errors or success
    if (errors.size() > 0) {
        return ServiceUtil.returnError(errors);
    } else if (lines == 0) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductPromoCodeImportEmptyFile", locale));
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) LinkedList(java.util.LinkedList) ModelService(org.apache.ofbiz.service.ModelService) BufferedReader(java.io.BufferedReader) StringReader(java.io.StringReader) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 2 with ModelService

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

the class ICalConverter method invokeService.

protected static Map<String, Object> invokeService(String serviceName, Map<String, ? extends Object> serviceMap, Map<String, Object> context) {
    LocalDispatcher dispatcher = (LocalDispatcher) context.get("dispatcher");
    Locale locale = (Locale) context.get("locale");
    Map<String, Object> localMap = new HashMap<>();
    try {
        ModelService modelService = null;
        modelService = dispatcher.getDispatchContext().getModelService(serviceName);
        for (ModelParam modelParam : modelService.getInModelParamList()) {
            if (serviceMap.containsKey(modelParam.name)) {
                Object value = serviceMap.get(modelParam.name);
                if (UtilValidate.isNotEmpty(modelParam.type)) {
                    value = ObjectType.simpleTypeConvert(value, modelParam.type, null, null, null, true);
                }
                localMap.put(modelParam.name, value);
            }
        }
    } catch (GeneralException e) {
        String errMsg = UtilProperties.getMessage("WorkEffortUiLabels", "WorkeffortErrorWhileCreatingServiceMapForService", UtilMisc.toMap("serviceName", serviceName), locale);
        Debug.logError(e, errMsg, module);
        return ServiceUtil.returnError(errMsg + e);
    }
    if (context.get("userLogin") != null) {
        localMap.put("userLogin", context.get("userLogin"));
    }
    localMap.put("locale", context.get("locale"));
    try {
        Map<String, Object> result = dispatcher.runSync(serviceName, localMap);
        if (ServiceUtil.isError(result)) {
            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result));
        }
        return result;
    } catch (GenericServiceException e) {
        String errMsg = UtilProperties.getMessage("WorkEffortUiLabels", "WorkeffortErrorWhileInvokingService", UtilMisc.toMap("serviceName", serviceName), locale);
        Debug.logError(e, errMsg, module);
        return ServiceUtil.returnError(errMsg + e);
    }
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GeneralException(org.apache.ofbiz.base.util.GeneralException) HashMap(java.util.HashMap) ModelParam(org.apache.ofbiz.service.ModelParam) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ModelService(org.apache.ofbiz.service.ModelService)

Example 3 with ModelService

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

the class ModelForm method addAutoFieldsFromService.

private void addAutoFieldsFromService(AutoFieldsService autoFieldsService, ModelReader entityModelReader, DispatchContext dispatchContext, Set<String> useWhenFields, List<ModelFormFieldBuilder> fieldBuilderList, Map<String, ModelFormFieldBuilder> fieldBuilderMap) {
    // read service def and auto-create fields
    ModelService modelService = null;
    try {
        modelService = dispatchContext.getModelService(autoFieldsService.serviceName);
    } catch (GenericServiceException e) {
        String errmsg = "Error finding Service with name " + autoFieldsService.serviceName + " for auto-fields-service in a form widget";
        Debug.logError(e, errmsg, module);
        throw new IllegalArgumentException(errmsg);
    }
    for (ModelParam modelParam : modelService.getInModelParamList()) {
        if (modelParam.internal) {
            // skip auto params that the service engine populates...
            continue;
        }
        if (modelParam.formDisplay) {
            if (UtilValidate.isNotEmpty(modelParam.entityName) && UtilValidate.isNotEmpty(modelParam.fieldName)) {
                ModelEntity modelEntity;
                try {
                    modelEntity = entityModelReader.getModelEntity(modelParam.entityName);
                    ModelField modelField = modelEntity.getField(modelParam.fieldName);
                    if (modelField != null) {
                        // okay, populate using the entity field info...
                        ModelFormFieldBuilder builder = new ModelFormFieldBuilder();
                        builder.setModelForm(this);
                        builder.setName(modelField.getName());
                        builder.setEntityName(modelEntity.getEntityName());
                        builder.setFieldName(modelField.getName());
                        builder.induceFieldInfoFromEntityField(modelEntity, modelField, autoFieldsService.defaultFieldType);
                        if (UtilValidate.isNotEmpty(autoFieldsService.mapName)) {
                            builder.setMapName(autoFieldsService.mapName);
                        }
                        builder.setRequiredField(!modelParam.optional);
                        addUpdateField(builder, useWhenFields, fieldBuilderList, fieldBuilderMap);
                        // continue to skip creating based on service param
                        continue;
                    }
                } catch (GenericEntityException e) {
                    Debug.logError(e, module);
                }
            }
            ModelFormFieldBuilder builder = new ModelFormFieldBuilder();
            builder.setModelForm(this);
            builder.setName(modelParam.name);
            builder.setServiceName(modelService.name);
            builder.setAttributeName(modelParam.name);
            builder.setTitle(modelParam.formLabel);
            builder.setRequiredField(!modelParam.optional);
            builder.induceFieldInfoFromServiceParam(modelService, modelParam, autoFieldsService.defaultFieldType);
            builder.setPosition(autoFieldsService.defaultPosition);
            if (UtilValidate.isNotEmpty(autoFieldsService.mapName)) {
                builder.setMapName(autoFieldsService.mapName);
            }
            addUpdateField(builder, useWhenFields, fieldBuilderList, fieldBuilderMap);
        }
    }
}
Also used : ModelField(org.apache.ofbiz.entity.model.ModelField) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ModelParam(org.apache.ofbiz.service.ModelParam) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity) ModelService(org.apache.ofbiz.service.ModelService)

Example 4 with ModelService

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

the class ScriptHelperImpl method runService.

public Map<String, ? extends Object> runService(String serviceName, Map<String, ? extends Object> inputMap, Map<String, ? extends Object> args) throws ScriptException {
    Assert.notNull("serviceName", serviceName, "args", args);
    boolean includeUserLogin = !"false".equals(args.get("includeUserLoginStr"));
    String requireNewTransactionStr = (String) args.get("requireNewTransaction");
    int transactionTimeout = -1;
    if (UtilValidate.isNotEmpty(requireNewTransactionStr)) {
        String timeoutStr = (String) args.get("transactionTimout");
        if (UtilValidate.isNotEmpty(timeoutStr)) {
            try {
                transactionTimeout = Integer.parseInt(timeoutStr);
            } catch (NumberFormatException e) {
                Debug.logWarning(e, "Setting timeout to 0 (default)", module);
                transactionTimeout = 0;
            }
        }
    }
    Map<String, Object> inMap = new HashMap<String, Object>(inputMap);
    if (includeUserLogin && !inMap.containsKey("userLogin")) {
        GenericValue userLogin = ctxHelper.getUserLogin();
        if (userLogin != null) {
            inMap.put("userLogin", userLogin);
        }
    }
    if (!inMap.containsKey("locale") && ctxHelper.getLocale() != null) {
        inMap.put("locale", ctxHelper.getLocale());
    }
    if (!inMap.containsKey("timeZone") && ctxHelper.getTimeZone() != null) {
        inMap.put("timeZone", ctxHelper.getTimeZone());
    }
    Map<String, Object> result = null;
    try {
        if (UtilValidate.isEmpty(requireNewTransactionStr) && transactionTimeout < 0) {
            result = ctxHelper.getDispatcher().runSync(serviceName, inMap);
        } else {
            ModelService modelService = ctxHelper.getDispatcher().getDispatchContext().getModelService(serviceName);
            boolean requireNewTransaction = modelService.requireNewTransaction;
            int timeout = modelService.transactionTimeout;
            if (UtilValidate.isNotEmpty(requireNewTransactionStr)) {
                requireNewTransaction = "true".equals(requireNewTransactionStr);
            }
            if (transactionTimeout >= 0) {
                timeout = transactionTimeout;
            }
            result = ctxHelper.getDispatcher().runSync(serviceName, inMap, timeout, requireNewTransaction);
        }
    } catch (GenericServiceException e) {
        String errMsg = "Error running script " + ctxHelper.getScriptName() + " [problem invoking the [" + serviceName + "] service: " + e.getMessage();
        Debug.logWarning(e, errMsg, module);
        throw new ScriptException(errMsg);
    }
    return result;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) ScriptException(javax.script.ScriptException) HashMap(java.util.HashMap) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ModelService(org.apache.ofbiz.service.ModelService)

Example 5 with ModelService

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

the class CallService method exec.

@Override
public boolean exec(MethodContext methodContext) throws MiniLangException {
    if (methodContext.isTraceOn()) {
        outputTraceMessage(methodContext, "Begin call-service.");
    }
    String serviceName = serviceNameFse.expandString(methodContext.getEnvMap());
    String errorCode = this.errorCode;
    if (errorCode.isEmpty()) {
        errorCode = simpleMethod.getDefaultErrorCode();
    }
    String successCode = this.successCode;
    if (successCode.isEmpty()) {
        successCode = simpleMethod.getDefaultSuccessCode();
    }
    Map<String, Object> inMap = inMapFma.get(methodContext.getEnvMap());
    if (inMap == null) {
        inMap = new HashMap<String, Object>();
    }
    // before invoking the service, clear messages
    if (methodContext.getMethodType() == MethodContext.EVENT) {
        methodContext.removeEnv(simpleMethod.getEventErrorMessageName());
        methodContext.removeEnv(simpleMethod.getEventEventMessageName());
        methodContext.removeEnv(simpleMethod.getEventResponseCodeName());
    } else {
        methodContext.removeEnv(simpleMethod.getServiceErrorMessageName());
        methodContext.removeEnv(simpleMethod.getServiceSuccessMessageName());
        methodContext.removeEnv(simpleMethod.getServiceResponseMessageName());
    }
    // add UserLogin to context if expected
    if (includeUserLogin) {
        GenericValue userLogin = methodContext.getUserLogin();
        if (userLogin != null && inMap.get("userLogin") == null) {
            inMap.put("userLogin", userLogin);
        }
    }
    // always add Locale to context unless null
    Locale locale = methodContext.getLocale();
    if (locale != null) {
        inMap.put("locale", locale);
    }
    // invoke the service
    Map<String, Object> result = null;
    try {
        ModelService modelService = methodContext.getDispatcher().getDispatchContext().getModelService(serviceName);
        int timeout = modelService.transactionTimeout;
        if (this.transactionTimeout >= 0) {
            timeout = this.transactionTimeout;
        }
        if (methodContext.isTraceOn()) {
            outputTraceMessage(methodContext, "Invoking service \"" + serviceName + "\", require-new-transaction = " + requireNewTransaction + ", transaction-timeout = " + timeout + ", IN attributes:", inMap.toString());
        }
        result = methodContext.getDispatcher().runSync(serviceName, inMap, timeout, requireNewTransaction);
    } catch (GenericServiceException e) {
        if (methodContext.isTraceOn()) {
            outputTraceMessage(methodContext, "Service engine threw an exception: " + e.getMessage());
        }
        String errMsg = "ERROR: Could not complete the " + simpleMethod.getShortDescription() + " process [problem invoking the [" + serviceName + "] service with the map named [" + inMapFma + "] containing [" + inMap + "]: " + e.getMessage() + "]";
        Debug.logError(e, errMsg, module);
        if (breakOnError) {
            if (methodContext.getMethodType() == MethodContext.EVENT) {
                methodContext.putEnv(simpleMethod.getEventErrorMessageName(), errMsg);
                methodContext.putEnv(simpleMethod.getEventResponseCodeName(), errorCode);
            } else {
                methodContext.putEnv(simpleMethod.getServiceErrorMessageName(), errMsg);
                methodContext.putEnv(simpleMethod.getServiceResponseMessageName(), errorCode);
            }
            if (methodContext.isTraceOn()) {
                outputTraceMessage(methodContext, "break-on-error set to \"true\", halting script execution. End call-service.");
            }
            return false;
        } else {
            if (methodContext.isTraceOn()) {
                outputTraceMessage(methodContext, "End call-service.");
            }
            return true;
        }
    }
    if (resultsToMapList != null) {
        if (methodContext.isTraceOn()) {
            outputTraceMessage(methodContext, "Processing " + resultsToMapList.size() + " <results-to-map> elements.");
        }
        for (String mapName : resultsToMapList) {
            methodContext.putEnv(mapName, UtilMisc.makeMapWritable(result));
        }
    }
    if (resultToFieldList != null) {
        if (methodContext.isTraceOn()) {
            outputTraceMessage(methodContext, "Processing " + resultToFieldList.size() + " <result-to-field> elements.");
        }
        for (ResultToField rtfDef : resultToFieldList) {
            rtfDef.exec(methodContext, result);
        }
    }
    if (resultToResultList != null) {
        if (methodContext.isTraceOn()) {
            outputTraceMessage(methodContext, "Processing " + resultToResultList.size() + " <result-to-result> elements.");
        }
        for (ResultToResult rtrDef : resultToResultList) {
            rtrDef.exec(methodContext, result);
        }
    }
    if (methodContext.getMethodType() == MethodContext.EVENT) {
        if (resultToRequestList != null) {
            if (methodContext.isTraceOn()) {
                outputTraceMessage(methodContext, "Processing " + resultToRequestList.size() + " <result-to-request> elements.");
            }
            for (ResultToRequest rtrDef : resultToRequestList) {
                rtrDef.exec(methodContext, result);
            }
        }
        if (resultToSessionList != null) {
            if (methodContext.isTraceOn()) {
                outputTraceMessage(methodContext, "Processing " + resultToSessionList.size() + " <result-to-session> elements.");
            }
            for (ResultToSession rtsDef : resultToSessionList) {
                rtsDef.exec(methodContext, result);
            }
        }
    }
    String errorPrefixStr = errorPrefix.getMessage(methodContext.getLoader(), methodContext);
    String errorSuffixStr = errorSuffix.getMessage(methodContext.getLoader(), methodContext);
    String successPrefixStr = successPrefix.getMessage(methodContext.getLoader(), methodContext);
    String successSuffixStr = successSuffix.getMessage(methodContext.getLoader(), methodContext);
    String messagePrefixStr = messagePrefix.getMessage(methodContext.getLoader(), methodContext);
    String messageSuffixStr = messageSuffix.getMessage(methodContext.getLoader(), methodContext);
    String errorMessage = null;
    List<String> errorMessageList = null;
    // See if there is a single message
    if (result.containsKey(ModelService.ERROR_MESSAGE)) {
        errorMessage = ServiceUtil.makeErrorMessage(result, messagePrefixStr, messageSuffixStr, errorPrefixStr, errorSuffixStr);
    } else if (result.containsKey(ModelService.ERROR_MESSAGE_LIST)) {
        errorMessageList = UtilGenerics.checkList(result.get(ModelService.ERROR_MESSAGE_LIST));
    }
    if ((UtilValidate.isNotEmpty(errorMessage) || UtilValidate.isNotEmpty(errorMessageList)) && breakOnError) {
        if (methodContext.getMethodType() == MethodContext.EVENT) {
            if (UtilValidate.isNotEmpty(errorMessage)) {
                if (Debug.verboseOn()) {
                    errorMessage += UtilProperties.getMessage(resource, "simpleMethod.error_show_service_name", UtilMisc.toMap("serviceName", serviceName, "methodName", simpleMethod.getMethodName()), locale);
                }
                methodContext.putEnv(simpleMethod.getEventErrorMessageName(), errorMessage);
            } else {
                if (Debug.verboseOn()) {
                    errorMessageList.add(UtilProperties.getMessage(resource, "simpleMethod.error_show_service_name", UtilMisc.toMap("serviceName", serviceName, "methodName", simpleMethod.getMethodName()), locale));
                }
                methodContext.putEnv(simpleMethod.getEventErrorMessageListName(), errorMessageList);
            }
        } else {
            ServiceUtil.addErrors(UtilMisc.<String, String>getListFromMap(methodContext.getEnvMap(), this.simpleMethod.getServiceErrorMessageListName()), UtilMisc.<String, String, Object>getMapFromMap(methodContext.getEnvMap(), this.simpleMethod.getServiceErrorMessageMapName()), result);
            Debug.logError(new Exception(errorMessage), module);
        }
    }
    String successMessage = ServiceUtil.makeSuccessMessage(result, messagePrefixStr, messageSuffixStr, successPrefixStr, successSuffixStr);
    if (UtilValidate.isNotEmpty(successMessage)) {
        if (methodContext.getMethodType() == MethodContext.EVENT) {
            methodContext.putEnv(simpleMethod.getEventEventMessageName(), successMessage);
        } else {
            methodContext.putEnv(simpleMethod.getServiceSuccessMessageName(), successMessage);
        }
    }
    String defaultMessageStr = defaultMessage.getMessage(methodContext.getLoader(), methodContext);
    if (UtilValidate.isEmpty(errorMessage) && UtilValidate.isEmpty(errorMessageList) && UtilValidate.isEmpty(successMessage) && UtilValidate.isNotEmpty(defaultMessageStr)) {
        if (methodContext.getMethodType() == MethodContext.EVENT) {
            methodContext.putEnv(simpleMethod.getEventEventMessageName(), defaultMessageStr);
        } else {
            methodContext.putEnv(simpleMethod.getServiceSuccessMessageName(), defaultMessageStr);
        }
    }
    String responseCode = result.containsKey(ModelService.RESPONSE_MESSAGE) ? (String) result.get(ModelService.RESPONSE_MESSAGE) : successCode;
    if (errorCode.equals(responseCode)) {
        if (methodContext.isTraceOn()) {
            outputTraceMessage(methodContext, "Service returned an error.");
        }
        if (breakOnError) {
            if (methodContext.getMethodType() == MethodContext.EVENT) {
                methodContext.putEnv(simpleMethod.getEventResponseCodeName(), responseCode);
            } else {
                methodContext.putEnv(simpleMethod.getServiceResponseMessageName(), responseCode);
            }
            if (methodContext.isTraceOn()) {
                outputTraceMessage(methodContext, "break-on-error set to \"true\", halting script execution. End call-service.");
            }
            return false;
        } else {
            if (methodContext.isTraceOn()) {
                outputTraceMessage(methodContext, "End call-service.");
            }
            return true;
        }
    } else {
        if (methodContext.isTraceOn()) {
            outputTraceMessage(methodContext, "Service ran successfully. End call-service.");
        }
        if (methodContext.getMethodType() == MethodContext.EVENT) {
            methodContext.putEnv(simpleMethod.getEventResponseCodeName(), responseCode);
        } else {
            methodContext.putEnv(simpleMethod.getServiceResponseMessageName(), responseCode);
        }
        return true;
    }
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) MiniLangException(org.apache.ofbiz.minilang.MiniLangException) ModelService(org.apache.ofbiz.service.ModelService) 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