Search in sources :

Example 16 with ModelService

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

the class ContentManagementServices method persistDataResourceAndDataMethod.

public static Map<String, Object> persistDataResourceAndDataMethod(DispatchContext dctx, Map<String, ? extends Object> rcontext) throws GenericServiceException, GenericEntityException, Exception {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Map<String, Object> context = UtilMisc.makeMapWritable(rcontext);
    Map<String, Object> result = new HashMap<String, Object>();
    Map<String, Object> newDrContext = new HashMap<String, Object>();
    GenericValue dataResource = delegator.makeValue("DataResource");
    dataResource.setPKFields(context);
    dataResource.setNonPKFields(context);
    dataResource.setAllFields(context, false, "dr", null);
    context.putAll(dataResource);
    GenericValue electronicText = delegator.makeValue("ElectronicText");
    electronicText.setPKFields(context);
    electronicText.setNonPKFields(context);
    String textData = (String) electronicText.get("textData");
    String dataResourceId = (String) dataResource.get("dataResourceId");
    String dataResourceTypeId = (String) dataResource.get("dataResourceTypeId");
    if (Debug.infoOn()) {
        Debug.logInfo("in persist... dataResourceId(0):" + dataResourceId, module);
    }
    // TODO: a temp hack because I don't want to bother with DataResource permissions at this time.
    context.put("skipPermissionCheck", "granted");
    boolean dataResourceExists = true;
    if (UtilValidate.isEmpty(dataResourceId)) {
        dataResourceExists = false;
    } else {
        try {
            GenericValue val = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).queryOne();
            if (val == null) {
                dataResourceExists = false;
            }
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.toString());
        }
    }
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    ModelService dataResourceModel = dispatcher.getDispatchContext().getModelService("updateDataResource");
    Map<String, Object> ctx = dataResourceModel.makeValid(dataResource, ModelService.IN_PARAM);
    newDrContext.putAll(ctx);
    newDrContext.put("userLogin", userLogin);
    newDrContext.put("skipPermissionCheck", context.get("skipPermissionCheck"));
    ByteBuffer imageDataBytes = (ByteBuffer) context.get("imageData");
    String mimeTypeId = (String) newDrContext.get("mimeTypeId");
    if (imageDataBytes != null && (mimeTypeId == null || (mimeTypeId.indexOf("image") >= 0) || (mimeTypeId.indexOf("application") >= 0))) {
        mimeTypeId = (String) context.get("_imageData_contentType");
        if ("IMAGE_OBJECT".equals(dataResourceTypeId)) {
            String fileName = (String) context.get("_imageData_fileName");
            newDrContext.put("objectInfo", fileName);
        }
        newDrContext.put("mimeTypeId", mimeTypeId);
    }
    if (!dataResourceExists) {
        // Create
        Map<String, Object> thisResult = dispatcher.runSync("createDataResource", newDrContext);
        if (ServiceUtil.isError(thisResult)) {
            throw (new Exception(ServiceUtil.getErrorMessage(thisResult)));
        }
        dataResourceId = (String) thisResult.get("dataResourceId");
        if (Debug.infoOn()) {
            Debug.logInfo("in persist... dataResourceId(0):" + dataResourceId, module);
        }
        dataResource = (GenericValue) thisResult.get("dataResource");
        Map<String, Object> fileContext = new HashMap<String, Object>();
        fileContext.put("userLogin", userLogin);
        if ("IMAGE_OBJECT".equals(dataResourceTypeId)) {
            if (imageDataBytes != null) {
                fileContext.put("dataResourceId", dataResourceId);
                fileContext.put("imageData", imageDataBytes);
                thisResult = dispatcher.runSync("createImage", fileContext);
                if (ServiceUtil.isError(thisResult)) {
                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(thisResult));
                }
            }
        } else if ("SHORT_TEXT".equals(dataResourceTypeId)) {
        } else if ("SURVEY".startsWith(dataResourceTypeId)) {
        } else if ("_FILE".indexOf(dataResourceTypeId) >= 0) {
            Map<String, Object> uploadImage = new HashMap<String, Object>();
            uploadImage.put("userLogin", userLogin);
            uploadImage.put("dataResourceId", dataResourceId);
            uploadImage.put("dataResourceTypeId", dataResourceTypeId);
            uploadImage.put("rootDir", context.get("objectInfo"));
            uploadImage.put("uploadedFile", imageDataBytes);
            uploadImage.put("_uploadedFile_fileName", (String) context.get("_imageData_fileName"));
            uploadImage.put("_uploadedFile_contentType", (String) context.get("_imageData_contentType"));
            thisResult = dispatcher.runSync("attachUploadToDataResource", uploadImage);
            if (ServiceUtil.isError(thisResult)) {
                return ServiceUtil.returnError(ServiceUtil.getErrorMessage(thisResult));
            }
        } else {
            // assume ELECTRONIC_TEXT
            if (UtilValidate.isNotEmpty(textData)) {
                fileContext.put("dataResourceId", dataResourceId);
                fileContext.put("textData", textData);
                thisResult = dispatcher.runSync("createElectronicText", fileContext);
                if (ServiceUtil.isError(thisResult)) {
                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(thisResult));
                }
            }
        }
    } else {
        // Update
        Map<String, Object> thisResult = dispatcher.runSync("updateDataResource", newDrContext);
        if (ServiceUtil.isError(thisResult)) {
            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(thisResult));
        }
        Map<String, Object> fileContext = new HashMap<String, Object>();
        fileContext.put("userLogin", userLogin);
        String forceElectronicText = (String) context.get("forceElectronicText");
        if ("IMAGE_OBJECT".equals(dataResourceTypeId)) {
            if (imageDataBytes != null || "true".equalsIgnoreCase(forceElectronicText)) {
                fileContext.put("dataResourceId", dataResourceId);
                fileContext.put("imageData", imageDataBytes);
                thisResult = dispatcher.runSync("updateImage", fileContext);
                if (ServiceUtil.isError(thisResult)) {
                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(thisResult));
                }
            }
        } else if ("SHORT_TEXT".equals(dataResourceTypeId)) {
        } else if ("SURVEY".startsWith(dataResourceTypeId)) {
        } else if ("_FILE".indexOf(dataResourceTypeId) >= 0) {
            Map<String, Object> uploadImage = new HashMap<String, Object>();
            uploadImage.put("userLogin", userLogin);
            uploadImage.put("dataResourceId", dataResourceId);
            uploadImage.put("dataResourceTypeId", dataResourceTypeId);
            uploadImage.put("rootDir", context.get("objectInfo"));
            uploadImage.put("uploadedFile", imageDataBytes);
            uploadImage.put("_uploadedFile_fileName", (String) context.get("_imageData_fileName"));
            uploadImage.put("_uploadedFile_contentType", (String) context.get("_imageData_contentType"));
            thisResult = dispatcher.runSync("attachUploadToDataResource", uploadImage);
            if (ServiceUtil.isError(thisResult)) {
                return ServiceUtil.returnError(ServiceUtil.getErrorMessage(thisResult));
            }
        } else {
            if (UtilValidate.isNotEmpty(textData) || "true".equalsIgnoreCase(forceElectronicText)) {
                fileContext.put("dataResourceId", dataResourceId);
                fileContext.put("textData", textData);
                thisResult = dispatcher.runSync("updateElectronicText", fileContext);
                if (ServiceUtil.isError(thisResult)) {
                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(thisResult));
                }
            }
        }
    }
    result.put("dataResourceId", dataResourceId);
    result.put("drDataResourceId", dataResourceId);
    context.put("dataResourceId", dataResourceId);
    return result;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) ByteBuffer(java.nio.ByteBuffer) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ServiceAuthException(org.apache.ofbiz.service.ServiceAuthException) ModelService(org.apache.ofbiz.service.ModelService) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 17 with ModelService

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

the class FinAccountServices method createFinAccountForStore.

public static Map<String, Object> createFinAccountForStore(DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    String productStoreId = (String) context.get("productStoreId");
    String finAccountTypeId = (String) context.get("finAccountTypeId");
    Locale locale = (Locale) context.get("locale");
    GenericValue productStore = ProductStoreWorker.getProductStore(productStoreId, delegator);
    try {
        // get the product store id and use it to generate a unique fin account code
        GenericValue productStoreFinAccountSetting = EntityQuery.use(delegator).from("ProductStoreFinActSetting").where("productStoreId", productStoreId, "finAccountTypeId", finAccountTypeId).cache().queryOne();
        if (productStoreFinAccountSetting == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingFinAccountSetting", UtilMisc.toMap("productStoreId", productStoreId, "finAccountTypeId", finAccountTypeId), locale));
        }
        Long accountCodeLength = productStoreFinAccountSetting.getLong("accountCodeLength");
        Long accountValidDays = productStoreFinAccountSetting.getLong("accountValidDays");
        Long pinCodeLength = productStoreFinAccountSetting.getLong("pinCodeLength");
        String requirePinCode = productStoreFinAccountSetting.getString("requirePinCode");
        // automatically set the parameters for the create fin account service
        ModelService createService = dctx.getModelService("createFinAccount");
        Map<String, Object> inContext = createService.makeValid(context, ModelService.IN_PARAM);
        Timestamp now = UtilDateTime.nowTimestamp();
        // now use our values
        String finAccountCode = null;
        if (UtilValidate.isNotEmpty(accountCodeLength)) {
            finAccountCode = FinAccountHelper.getNewFinAccountCode(accountCodeLength.intValue(), delegator);
            inContext.put("finAccountCode", finAccountCode);
        }
        // with pin codes, the account code becomes the ID and the pin becomes the code
        if ("Y".equalsIgnoreCase(requirePinCode)) {
            String pinCode = FinAccountHelper.getNewFinAccountCode(pinCodeLength.intValue(), delegator);
            inContext.put("finAccountPin", pinCode);
        }
        // set the dates/userlogin
        if (UtilValidate.isNotEmpty(accountValidDays)) {
            inContext.put("thruDate", UtilDateTime.getDayEnd(now, accountValidDays));
        }
        inContext.put("fromDate", now);
        inContext.put("userLogin", userLogin);
        // product store payToPartyId
        String payToPartyId = ProductStoreWorker.getProductStorePayToPartyId(productStoreId, delegator);
        inContext.put("organizationPartyId", payToPartyId);
        inContext.put("currencyUomId", productStore.get("defaultCurrencyUomId"));
        Map<String, Object> createResult = dispatcher.runSync("createFinAccount", inContext);
        if (ServiceUtil.isError(createResult)) {
            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(createResult));
        }
        Map<String, Object> result = ServiceUtil.returnSuccess();
        result.put("finAccountId", createResult.get("finAccountId"));
        result.put("finAccountCode", finAccountCode);
        return result;
    } catch (GenericEntityException | GenericServiceException ex) {
        return ServiceUtil.returnError(ex.getMessage());
    }
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) Timestamp(java.sql.Timestamp) ModelService(org.apache.ofbiz.service.ModelService) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 18 with ModelService

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

the class CompDocEvents method persistRootCompDoc.

/**
 * @param request
 * @param response
 * @return
 *
 * Creates the topmost Content entity of a Composite Document tree.
 * Also creates an "empty" Composite Document Instance Content entity.
 * Creates ContentRevision/Item records for each, as well.
 */
public static String persistRootCompDoc(HttpServletRequest request, HttpServletResponse response) {
    Map<String, Object> paramMap = UtilHttp.getParameterMap(request);
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    Locale locale = UtilHttp.getLocale(request);
    HttpSession session = request.getSession();
    // Security security = (Security)request.getAttribute("security");
    GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
    String contentId = (String) paramMap.get("contentId");
    if (UtilValidate.isNotEmpty(contentId)) {
        try {
            EntityQuery.use(delegator).from("Content").where("contentId", contentId).queryOne();
        } catch (GenericEntityException e) {
            Debug.logError(e, "Error running serviceName persistContentAndAssoc", module);
            String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.error_modelservice_for_srv_name", locale);
            request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg + " [" + "persistContentAndAssoc" + "]: " + e.toString());
            return "error";
        }
    }
    ModelService modelService = null;
    try {
        modelService = dispatcher.getDispatchContext().getModelService("persistContentAndAssoc");
    } catch (GenericServiceException e) {
        String errMsg = "Error getting model service for serviceName, 'persistContentAndAssoc'. " + e.toString();
        Debug.logError(errMsg, module);
        request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg + "</li>");
        return "error";
    }
    Map<String, Object> persistMap = modelService.makeValid(paramMap, ModelService.IN_PARAM);
    persistMap.put("userLogin", userLogin);
    try {
        Map<String, Object> persistResult = dispatcher.runSync("persistContentAndAssoc", persistMap);
        if (ServiceUtil.isError(persistResult)) {
            String errMsg = "Error running serviceName, 'persistContentAndAssoc'. " + ServiceUtil.getErrorMessage(persistResult);
            request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg + "</li>");
            Debug.logError(errMsg, module);
            return "error";
        }
        contentId = (String) persistResult.get("contentId");
        // request.setAttribute("contentId", contentId);
        for (Entry<String, Object> entry : persistResult.entrySet()) {
            Object obj = entry.getValue();
            Object val = persistResult.get(obj);
            request.setAttribute(obj.toString(), val);
        }
        // Update ContentRevision and ContentRevisonItem
        Map<String, Object> contentRevisionMap = new HashMap<String, Object>();
        contentRevisionMap.put("itemContentId", contentId);
        contentRevisionMap.put("contentId", contentId);
        contentRevisionMap.put("userLogin", userLogin);
        Map<String, Object> result = dispatcher.runSync("persistContentRevisionAndItem", contentRevisionMap);
        if (ServiceUtil.isError(result)) {
            String errMsg = "Error running serviceName, 'persistContentRevisionAndItem'. " + ServiceUtil.getErrorMessage(result);
            request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg + "</li>");
            Debug.logError(errMsg, module);
            return "error";
        }
        for (Entry<String, Object> entry : result.entrySet()) {
            Object obj = entry.getValue();
            Object val = result.get(obj);
            request.setAttribute(obj.toString(), val);
        }
    } catch (GenericServiceException e) {
        String errMsg = "Error running serviceName, 'persistContentAndAssoc'. " + e.toString();
        Debug.logError(errMsg, module);
        request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg + "</li>");
        return "error";
    }
    return "success";
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) ModelService(org.apache.ofbiz.service.ModelService) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 19 with ModelService

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

the class SOAPEventHandler 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 {
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    // first check for WSDL request
    String wsdlReq = request.getParameter("wsdl");
    if (wsdlReq == null) {
        wsdlReq = request.getParameter("WSDL");
    }
    if (wsdlReq != null) {
        String serviceName = RequestHandler.getOverrideViewUri(request.getPathInfo());
        DispatchContext dctx = dispatcher.getDispatchContext();
        String locationUri = this.getLocationURI(request);
        if (serviceName != null) {
            Document wsdl = null;
            try {
                wsdl = dctx.getWSDL(serviceName, locationUri);
            } catch (GenericServiceException e) {
                serviceName = null;
            } catch (WSDLException e) {
                sendError(response, "Unable to obtain WSDL", serviceName);
                throw new EventHandlerException("Unable to obtain WSDL", e);
            }
            if (wsdl != null) {
                try {
                    OutputStream os = response.getOutputStream();
                    response.setContentType("text/xml");
                    UtilXml.writeXmlDocument(os, wsdl);
                    response.flushBuffer();
                } catch (IOException e) {
                    throw new EventHandlerException(e);
                }
                return null;
            } else {
                sendError(response, "Unable to obtain WSDL", serviceName);
                throw new EventHandlerException("Unable to obtain WSDL");
            }
        }
        if (serviceName == null) {
            try {
                Writer writer = response.getWriter();
                StringBuilder sb = new StringBuilder();
                sb.append("<html><head><title>OFBiz SOAP/1.1 Services</title></head>");
                sb.append("<body>No such service.").append("<p>Services:<ul>");
                for (String scvName : dctx.getAllServiceNames()) {
                    ModelService model = dctx.getModelService(scvName);
                    if (model.export) {
                        sb.append("<li><a href=\"").append(locationUri).append("/").append(model.name).append("?wsdl\">");
                        sb.append(model.name).append("</a></li>");
                    }
                }
                sb.append("</ul></p></body></html>");
                writer.write(sb.toString());
                writer.flush();
                return null;
            } catch (Exception e) {
                sendError(response, "Unable to obtain WSDL", null);
                throw new EventHandlerException("Unable to obtain WSDL");
            }
        }
    }
    // not a wsdl request; invoke the service
    response.setContentType("text/xml");
    // request envelope
    SOAPEnvelope reqEnv = null;
    // get the service name and parameters
    try {
        InputStream inputStream = (InputStream) request.getInputStream();
        SOAPModelBuilder builder = (SOAPModelBuilder) OMXMLBuilderFactory.createSOAPModelBuilder(inputStream, "UTF-8");
        reqEnv = (SOAPEnvelope) builder.getDocumentElement();
        // log the request message
        if (Debug.verboseOn()) {
            try {
                Debug.logInfo("Request Message:\n" + reqEnv + "\n", module);
            } catch (Throwable t) {
            }
        }
    } catch (Exception e) {
        sendError(response, "Problem processing the service", null);
        throw new EventHandlerException("Cannot get the envelope", e);
    }
    if (Debug.verboseOn())
        Debug.logVerbose("[Processing]: SOAP Event", module);
    String serviceName = null;
    try {
        SOAPBody reqBody = reqEnv.getBody();
        validateSOAPBody(reqBody);
        OMElement serviceElement = reqBody.getFirstElement();
        serviceName = serviceElement.getLocalName();
        Map<String, Object> parameters = UtilGenerics.cast(SoapSerializer.deserialize(serviceElement.toString(), delegator));
        try {
            // verify the service is exported for remote execution and invoke it
            ModelService model = dispatcher.getDispatchContext().getModelService(serviceName);
            if (model == null) {
                sendError(response, "Problem processing the service", serviceName);
                Debug.logError("Could not find Service [" + serviceName + "].", module);
                return null;
            }
            if (!model.export) {
                sendError(response, "Problem processing the service", serviceName);
                Debug.logError("Trying to call Service [" + serviceName + "] that is not exported.", module);
                return null;
            }
            Map<String, Object> serviceResults = dispatcher.runSync(serviceName, parameters);
            if (Debug.verboseOn())
                Debug.logVerbose("[EventHandler] : Service invoked", module);
            createAndSendSOAPResponse(serviceResults, serviceName, response);
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
            if (UtilProperties.getPropertyAsBoolean("service", "secureSoapAnswer", true)) {
                sendError(response, "Problem processing the service, check your parameters.", serviceName);
            } else {
                if (e.getMessageList() == null) {
                    sendError(response, e.getMessage(), serviceName);
                } else {
                    sendError(response, e.getMessageList(), serviceName);
                }
                return null;
            }
        }
    } catch (Exception e) {
        sendError(response, e.getMessage(), serviceName);
        Debug.logError(e, module);
        return null;
    }
    return null;
}
Also used : LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) WSDLException(javax.wsdl.WSDLException) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) OMElement(org.apache.axiom.om.OMElement) IOException(java.io.IOException) SOAPEnvelope(org.apache.axiom.soap.SOAPEnvelope) Document(org.w3c.dom.Document) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) IOException(java.io.IOException) WSDLException(javax.wsdl.WSDLException) ModelService(org.apache.ofbiz.service.ModelService) DispatchContext(org.apache.ofbiz.service.DispatchContext) SOAPBody(org.apache.axiom.soap.SOAPBody) Delegator(org.apache.ofbiz.entity.Delegator) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) SOAPModelBuilder(org.apache.axiom.soap.SOAPModelBuilder) Writer(java.io.Writer)

Example 20 with ModelService

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

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