Search in sources :

Example 96 with LocalDispatcher

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

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

the class FindServices method performFind.

/**
 * performFind
 *
 * This is a generic method that expects entity data affixed with special suffixes
 * to indicate their purpose in formulating an SQL query statement.
 */
public static Map<String, Object> performFind(DispatchContext dctx, Map<String, ?> context) {
    String entityName = (String) context.get("entityName");
    String orderBy = (String) context.get("orderBy");
    // Input
    Map<String, ?> inputFields = checkMap(context.get("inputFields"), String.class, Object.class);
    String noConditionFind = (String) context.get("noConditionFind");
    String distinct = (String) context.get("distinct");
    List<String> fieldList = UtilGenerics.<String>checkList(context.get("fieldList"));
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    Delegator delegator = dctx.getDelegator();
    if (UtilValidate.isEmpty(noConditionFind)) {
        // try finding in inputFields Map
        noConditionFind = (String) inputFields.get("noConditionFind");
    }
    if (UtilValidate.isEmpty(noConditionFind)) {
        // Use configured default
        noConditionFind = EntityUtilProperties.getPropertyValue("widget", "widget.defaultNoConditionFind", delegator);
    }
    String filterByDate = (String) context.get("filterByDate");
    if (UtilValidate.isEmpty(filterByDate)) {
        // try finding in inputFields Map
        filterByDate = (String) inputFields.get("filterByDate");
    }
    Timestamp filterByDateValue = (Timestamp) context.get("filterByDateValue");
    String fromDateName = (String) context.get("fromDateName");
    if (UtilValidate.isEmpty(fromDateName)) {
        // try finding in inputFields Map
        fromDateName = (String) inputFields.get("fromDateName");
    }
    String thruDateName = (String) context.get("thruDateName");
    if (UtilValidate.isEmpty(thruDateName)) {
        // try finding in inputFields Map
        thruDateName = (String) inputFields.get("thruDateName");
    }
    Integer viewSize = (Integer) context.get("viewSize");
    Integer viewIndex = (Integer) context.get("viewIndex");
    Integer maxRows = null;
    if (viewSize != null && viewIndex != null) {
        maxRows = viewSize * (viewIndex + 1);
    }
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Map<String, Object> prepareResult = null;
    try {
        prepareResult = dispatcher.runSync("prepareFind", UtilMisc.toMap("entityName", entityName, "orderBy", orderBy, "inputFields", inputFields, "filterByDate", filterByDate, "noConditionFind", noConditionFind, "filterByDateValue", filterByDateValue, "userLogin", userLogin, "fromDateName", fromDateName, "thruDateName", thruDateName, "locale", context.get("locale"), "timeZone", context.get("timeZone")));
    } catch (GenericServiceException gse) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonFindErrorPreparingConditions", UtilMisc.toMap("errorString", gse.getMessage()), locale));
    }
    EntityConditionList<EntityCondition> exprList = UtilGenerics.cast(prepareResult.get("entityConditionList"));
    List<String> orderByList = checkList(prepareResult.get("orderByList"), String.class);
    Map<String, Object> executeResult = null;
    try {
        executeResult = dispatcher.runSync("executeFind", UtilMisc.toMap("entityName", entityName, "orderByList", orderByList, "fieldList", fieldList, "entityConditionList", exprList, "noConditionFind", noConditionFind, "distinct", distinct, "locale", context.get("locale"), "timeZone", context.get("timeZone"), "maxRows", maxRows));
    } catch (GenericServiceException gse) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonFindErrorRetrieveIterator", UtilMisc.toMap("errorString", gse.getMessage()), locale));
    }
    if (executeResult.get("listIt") == null) {
        if (Debug.verboseOn()) {
            Debug.logVerbose("No list iterator found for query string + [" + prepareResult.get("queryString") + "]", module);
        }
    }
    Map<String, Object> results = ServiceUtil.returnSuccess();
    results.put("listIt", executeResult.get("listIt"));
    results.put("listSize", executeResult.get("listSize"));
    results.put("queryString", prepareResult.get("queryString"));
    results.put("queryStringMap", prepareResult.get("queryStringMap"));
    return results;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) Timestamp(java.sql.Timestamp) Delegator(org.apache.ofbiz.entity.Delegator) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 98 with LocalDispatcher

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

the class NotificationServices method sendNotification.

/**
 * This will use the {@link #prepareNotification(DispatchContext, Map) prepareNotification(DispatchContext, Map)}
 * method to generate the body of the notification message to send
 * and then deliver it via the "sendMail" service.
 * <p>
 * If the "body" parameter is already specified, the message body generation
 * phase will be skipped and the notification will be sent with the
 * specified body instead. This can be used to combine both service
 * calls in a decoupled manner if other steps are required between
 * generating the message body and sending the notification.
 *
 * @param ctx   The dispatching context of the service
 * @param context The map containing all the fields associated with
 * the sevice
 * @return A Map with the service response messages in it
 */
public static Map<String, Object> sendNotification(DispatchContext ctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = ctx.getDispatcher();
    Locale locale = (Locale) context.get("locale");
    Map<String, Object> result = null;
    try {
        // see whether the optional 'body' attribute was specified or needs to be processed
        // nulls are handled the same as not specified
        String body = (String) context.get("body");
        if (body == null) {
            // prepare the body of the notification email
            Map<String, Object> bodyResult = prepareNotification(ctx, context);
            // ensure the body was generated successfully
            if (bodyResult.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_SUCCESS)) {
                body = (String) bodyResult.get("body");
            } else {
                // otherwise just report the error
                Debug.logError("prepareNotification failed: " + bodyResult.get(ModelService.ERROR_MESSAGE), module);
                body = null;
            }
        }
        // make sure we have a valid body before sending
        if (body != null) {
            // retain only the required attributes for the sendMail service
            Map<String, Object> emailContext = new LinkedHashMap<>();
            emailContext.put("sendTo", context.get("sendTo"));
            emailContext.put("body", body);
            emailContext.put("sendCc", context.get("sendCc"));
            emailContext.put("sendBcc", context.get("sendBcc"));
            emailContext.put("sendFrom", context.get("sendFrom"));
            emailContext.put("subject", context.get("subject"));
            emailContext.put("sendVia", context.get("sendVia"));
            emailContext.put("sendType", context.get("sendType"));
            emailContext.put("contentType", context.get("contentType"));
            // pass on to the sendMail service
            result = dispatcher.runSync("sendMail", emailContext);
        } else {
            Debug.logError("Invalid email body; null is not allowed", module);
            result = ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonNotifyEmailInvalidBody", locale));
        }
    } catch (GenericServiceException serviceException) {
        Debug.logError(serviceException, "Error sending email", module);
        result = ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonNotifyEmailDeliveryError", locale));
    }
    return result;
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) LinkedHashMap(java.util.LinkedHashMap)

Example 99 with LocalDispatcher

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

the class EntityEcaAction method runAction.

public void runAction(DispatchContext dctx, Map<String, ? extends Object> context, GenericEntity newValue) throws GenericEntityException {
    try {
        // pull out context parameters needed for this service.
        Map<String, Object> actionContext = dctx.getModelService(serviceName).makeValid(context, ModelService.IN_PARAM);
        // if value-attr is specified, insert the value object in that attr name
        if (!valueAttr.isEmpty()) {
            actionContext.put(valueAttr, newValue);
        }
        // Debug.logInfo("Running Entity ECA action service " + this.serviceName + " triggered by entity: " + value.getEntityName(), module);
        // Debug.logInfo("Running Entity ECA action service " + this.serviceName + "; value=" + value + "; actionContext=" + actionContext, module);
        // setup the run-as-user
        GenericValue userLoginToRunAs = null;
        if (!this.runAsUser.isEmpty()) {
            userLoginToRunAs = dctx.getDelegator().findOne("UserLogin", UtilMisc.toMap("userLoginId", this.runAsUser), true);
            if (userLoginToRunAs != null) {
                actionContext.put("userLogin", userLoginToRunAs);
            }
        }
        LocalDispatcher dispatcher = dctx.getDispatcher();
        if ("sync".equals(this.serviceMode)) {
            Map<String, Object> actionResult = dispatcher.runSync(this.serviceName, actionContext);
            if (ServiceUtil.isError(actionResult)) {
                throw new GenericServiceException("Error running Entity ECA action service: " + ServiceUtil.getErrorMessage(actionResult));
            }
            // use the result to update the context fields.
            if (resultToValue) {
                newValue.setNonPKFields(actionResult);
            }
        } else if ("async".equals(this.serviceMode)) {
            dispatcher.runAsync(serviceName, actionContext, persist);
        }
    } catch (GenericServiceException e) {
        // check abortOnError and rollbackOnError
        if (rollbackOnError) {
            String errMsg = "Entity ECA action service failed and rollback-on-error is true, so setting rollback only.";
            Debug.logError(errMsg, module);
            TransactionUtil.setRollbackOnly(errMsg, e);
        }
        if (this.abortOnError) {
            throw new EntityEcaException("Error running Entity ECA action service: " + e.toString(), e);
        } else {
            Debug.logError(e, "Error running Entity ECA action service", module);
        }
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 100 with LocalDispatcher

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

the class RmiServiceContainer method start.

public boolean start() throws ContainerException {
    // get the container config
    ContainerConfig.Configuration cfg = ContainerConfig.getConfiguration(containerName, configFile);
    ContainerConfig.Configuration.Property initialCtxProp = cfg.getProperty("use-initial-context");
    ContainerConfig.Configuration.Property lookupHostProp = cfg.getProperty("bound-host");
    ContainerConfig.Configuration.Property lookupPortProp = cfg.getProperty("bound-port");
    ContainerConfig.Configuration.Property lookupNameProp = cfg.getProperty("bound-name");
    ContainerConfig.Configuration.Property delegatorProp = cfg.getProperty("delegator-name");
    ContainerConfig.Configuration.Property clientProp = cfg.getProperty("client-factory");
    ContainerConfig.Configuration.Property serverProp = cfg.getProperty("server-factory");
    // check the required lookup-name property
    if (lookupNameProp == null || UtilValidate.isEmpty(lookupNameProp.value)) {
        throw new ContainerException("Invalid lookup-name defined in container configuration");
    } else {
        this.name = lookupNameProp.value;
    }
    // check the required delegator-name property
    if (delegatorProp == null || UtilValidate.isEmpty(delegatorProp.value)) {
        throw new ContainerException("Invalid delegator-name defined in container configuration");
    }
    String useCtx = initialCtxProp == null || initialCtxProp.value == null ? "false" : initialCtxProp.value;
    String host = lookupHostProp == null || lookupHostProp.value == null ? "localhost" : lookupHostProp.value;
    String port = lookupPortProp == null || lookupPortProp.value == null ? "1099" : lookupPortProp.value;
    if (Start.getInstance().getConfig().portOffset != 0) {
        Integer portValue = Integer.valueOf(port);
        portValue += Start.getInstance().getConfig().portOffset;
        port = portValue.toString();
    }
    String keystore = ContainerConfig.getPropertyValue(cfg, "ssl-keystore", null);
    String ksType = ContainerConfig.getPropertyValue(cfg, "ssl-keystore-type", "JKS");
    String ksPass = ContainerConfig.getPropertyValue(cfg, "ssl-keystore-pass", null);
    String ksAlias = ContainerConfig.getPropertyValue(cfg, "ssl-keystore-alias", null);
    boolean clientAuth = ContainerConfig.getPropertyValue(cfg, "ssl-client-auth", false);
    // setup the factories
    RMIClientSocketFactory csf = null;
    RMIServerSocketFactory ssf = null;
    // get the classloader
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    // load the factories
    if (clientProp != null && UtilValidate.isNotEmpty(clientProp.value)) {
        try {
            Class<?> c = loader.loadClass(clientProp.value);
            csf = (RMIClientSocketFactory) c.newInstance();
        } catch (Exception e) {
            throw new ContainerException(e);
        }
    }
    if (serverProp != null && UtilValidate.isNotEmpty(serverProp.value)) {
        try {
            Class<?> c = loader.loadClass(serverProp.value);
            ssf = (RMIServerSocketFactory) c.newInstance();
        } catch (Exception e) {
            throw new ContainerException(e);
        }
    }
    // set the client auth flag on our custom SSL socket factory
    if (ssf != null && ssf instanceof org.apache.ofbiz.service.rmi.socket.ssl.SSLServerSocketFactory) {
        ((org.apache.ofbiz.service.rmi.socket.ssl.SSLServerSocketFactory) ssf).setNeedClientAuth(clientAuth);
        ((org.apache.ofbiz.service.rmi.socket.ssl.SSLServerSocketFactory) ssf).setKeyStoreAlias(ksAlias);
        if (keystore != null) {
            ((org.apache.ofbiz.service.rmi.socket.ssl.SSLServerSocketFactory) ssf).setKeyStore(keystore, ksType, ksPass);
        }
    }
    // get the delegator for this container
    Delegator delegator = DelegatorFactory.getDelegator(delegatorProp.value);
    // create the LocalDispatcher
    LocalDispatcher dispatcher = ServiceContainer.getLocalDispatcher(name, delegator);
    // create the RemoteDispatcher
    try {
        remote = new RemoteDispatcherImpl(dispatcher, csf, ssf);
    } catch (RemoteException e) {
        throw new ContainerException("Unable to start the RMI dispatcher", e);
    }
    if (!"true".equalsIgnoreCase(useCtx)) {
        // bind RMIDispatcher to RMI Naming (Must be JRMP protocol)
        try {
            Naming.rebind("//" + host + ":" + port + "/" + name, remote);
        } catch (RemoteException e) {
            throw new ContainerException("Unable to bind RMIDispatcher to RMI on " + "//host[" + host + "]:port[" + port + "]/name[" + name + "] - with remote=" + remote, e);
        } catch (java.net.MalformedURLException e) {
            throw new ContainerException("Invalid URL for binding", e);
        }
    } else {
        // bind RMIDispatcher to InitialContext (must be RMI protocol not IIOP)
        try {
            InitialContext ic = new InitialContext();
            ic.rebind(name, remote);
        } catch (NamingException e) {
            throw new ContainerException("Unable to bind RMIDispatcher to JNDI", e);
        }
        // check JNDI
        try {
            InitialContext ic = new InitialContext();
            Object o = ic.lookup(name);
            if (o == null) {
                throw new NamingException("Object came back null");
            }
        } catch (NamingException e) {
            throw new ContainerException("Unable to lookup bound objects", e);
        }
    }
    return true;
}
Also used : LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) RMIClientSocketFactory(java.rmi.server.RMIClientSocketFactory) ContainerConfig(org.apache.ofbiz.base.container.ContainerConfig) ContainerException(org.apache.ofbiz.base.container.ContainerException) RMIServerSocketFactory(java.rmi.server.RMIServerSocketFactory) NamingException(javax.naming.NamingException) ContainerException(org.apache.ofbiz.base.container.ContainerException) NamingException(javax.naming.NamingException) RemoteException(java.rmi.RemoteException) InitialContext(javax.naming.InitialContext) Delegator(org.apache.ofbiz.entity.Delegator) RemoteException(java.rmi.RemoteException)

Aggregations

LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)427 GenericValue (org.apache.ofbiz.entity.GenericValue)356 Delegator (org.apache.ofbiz.entity.Delegator)324 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)321 Locale (java.util.Locale)296 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)270 HashMap (java.util.HashMap)214 BigDecimal (java.math.BigDecimal)135 GeneralException (org.apache.ofbiz.base.util.GeneralException)87 Timestamp (java.sql.Timestamp)81 LinkedList (java.util.LinkedList)79 IOException (java.io.IOException)59 Map (java.util.Map)51 HttpSession (javax.servlet.http.HttpSession)49 OrderReadHelper (org.apache.ofbiz.order.order.OrderReadHelper)28 ModelService (org.apache.ofbiz.service.ModelService)28 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)24 ShoppingCart (org.apache.ofbiz.order.shoppingcart.ShoppingCart)23 Security (org.apache.ofbiz.security.Security)20 ByteBuffer (java.nio.ByteBuffer)19