Search in sources :

Example 21 with ModelService

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

the class AbstractJmsListener method runService.

/**
 * Runs the service defined in the MapMessage
 * @param message
 * @return Map
 */
protected Map<String, Object> runService(MapMessage message) {
    Map<String, ? extends Object> context = null;
    String serviceName = null;
    String xmlContext = null;
    try {
        serviceName = message.getString("serviceName");
        xmlContext = message.getString("serviceContext");
        if (serviceName == null || xmlContext == null) {
            Debug.logError("Message received is not an OFB service message. Ignored!", module);
            return null;
        }
        Object o = XmlSerializer.deserialize(xmlContext, dispatcher.getDelegator());
        if (Debug.verboseOn())
            Debug.logVerbose("De-Serialized Context --> " + o, module);
        if (ObjectType.instanceOf(o, "java.util.Map"))
            context = UtilGenerics.checkMap(o);
    } catch (JMSException je) {
        Debug.logError(je, "Problems reading message.", module);
    } catch (Exception e) {
        Debug.logError(e, "Problems deserializing the service context.", module);
    }
    try {
        ModelService model = dispatcher.getDispatchContext().getModelService(serviceName);
        if (!model.export) {
            Debug.logWarning("Attempt to invoke a non-exported service: " + serviceName, module);
            return null;
        }
    } catch (GenericServiceException e) {
        Debug.logError(e, "Unable to get ModelService for service : " + serviceName, module);
    }
    if (Debug.verboseOn())
        Debug.logVerbose("Running service: " + serviceName, module);
    Map<String, Object> result = null;
    if (context != null) {
        try {
            result = dispatcher.runSync(serviceName, context);
        } catch (GenericServiceException gse) {
            Debug.logError(gse, "Problems with service invocation.", module);
        }
    }
    return result;
}
Also used : JMSException(javax.jms.JMSException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) JMSException(javax.jms.JMSException) ModelService(org.apache.ofbiz.service.ModelService)

Example 22 with ModelService

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

the class OrderServices method createAlsoBoughtProductAssocsForOrder.

public static Map<String, Object> createAlsoBoughtProductAssocsForOrder(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    String orderId = (String) context.get("orderId");
    OrderReadHelper orh = new OrderReadHelper(delegator, orderId);
    List<GenericValue> orderItems = orh.getOrderItems();
    Map<String, Object> serviceResult = new HashMap<String, Object>();
    // In order to improve efficiency a little bit, we will always create the ProductAssoc records
    // with productId < productIdTo when the two are compared.  This way when checking for an existing
    // record we don't have to check both possible combinations of productIds
    Set<String> productIdSet = new TreeSet<>();
    if (orderItems != null) {
        for (GenericValue orderItem : orderItems) {
            String productId = orderItem.getString("productId");
            if (productId != null) {
                GenericValue parentProduct = ProductWorker.getParentProduct(productId, delegator);
                if (parentProduct != null) {
                    productId = parentProduct.getString("productId");
                }
                productIdSet.add(productId);
            }
        }
    }
    Set<String> productIdToSet = new TreeSet<>(productIdSet);
    for (String productId : productIdSet) {
        productIdToSet.remove(productId);
        for (String productIdTo : productIdToSet) {
            EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("productId", productId), EntityCondition.makeCondition("productIdTo", productIdTo), EntityCondition.makeCondition("productAssocTypeId", "ALSO_BOUGHT"), EntityCondition.makeCondition("fromDate", EntityOperator.LESS_THAN_EQUAL_TO, UtilDateTime.nowTimestamp()), EntityCondition.makeCondition("thruDate", null)));
            GenericValue existingProductAssoc = null;
            try {
                // No point in using the cache because of the filterByDateExpr
                existingProductAssoc = EntityQuery.use(delegator).from("ProductAssoc").where(cond).orderBy("fromDate DESC").queryFirst();
            } catch (GenericEntityException e) {
                Debug.logError(e, module);
            }
            try {
                if (existingProductAssoc != null) {
                    BigDecimal newQuantity = existingProductAssoc.getBigDecimal("quantity");
                    if (newQuantity == null || newQuantity.compareTo(BigDecimal.ZERO) < 0) {
                        newQuantity = BigDecimal.ZERO;
                    }
                    newQuantity = newQuantity.add(BigDecimal.ONE);
                    ModelService updateProductAssoc = dctx.getModelService("updateProductAssoc");
                    Map<String, Object> updateCtx = updateProductAssoc.makeValid(context, ModelService.IN_PARAM, true, null);
                    updateCtx.putAll(updateProductAssoc.makeValid(existingProductAssoc, ModelService.IN_PARAM));
                    updateCtx.put("quantity", newQuantity);
                    serviceResult = dispatcher.runSync("updateProductAssoc", updateCtx);
                    if (ServiceUtil.isError(serviceResult)) {
                        return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
                    }
                } else {
                    Map<String, Object> createCtx = new HashMap<>();
                    createCtx.put("userLogin", context.get("userLogin"));
                    createCtx.put("productId", productId);
                    createCtx.put("productIdTo", productIdTo);
                    createCtx.put("productAssocTypeId", "ALSO_BOUGHT");
                    createCtx.put("fromDate", UtilDateTime.nowTimestamp());
                    createCtx.put("quantity", BigDecimal.ONE);
                    serviceResult = dispatcher.runSync("createProductAssoc", createCtx);
                    if (ServiceUtil.isError(serviceResult)) {
                        return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
                    }
                }
            } catch (GenericServiceException e) {
                Debug.logError(e, module);
            }
        }
    }
    return ServiceUtil.returnSuccess();
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) BigDecimal(java.math.BigDecimal) ModelService(org.apache.ofbiz.service.ModelService) Delegator(org.apache.ofbiz.entity.Delegator) TreeSet(java.util.TreeSet) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 23 with ModelService

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

the class CompDocServices method persistRootCompDoc.

/**
 * 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.
 * @param dctx the dispatch context
 * @param context the context
 * @return Creates the topmost Content entity of a Composite Document tree
 */
public static Map<String, Object> persistRootCompDoc(DispatchContext dctx, Map<String, ? extends Object> context) {
    Map<String, Object> result = new HashMap<String, Object>();
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Locale locale = (Locale) context.get("locale");
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    String contentId = (String) context.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);
            return ServiceUtil.returnError(UtilProperties.getMessage(CoreEvents.err_resource, "ContentNoContentFound", UtilMisc.toMap("contentId", contentId), locale));
        }
    }
    ModelService modelService = null;
    try {
        modelService = dispatcher.getDispatchContext().getModelService("persistContentAndAssoc");
    } catch (GenericServiceException e) {
        Debug.logError("Error getting model service for serviceName, 'persistContentAndAssoc'. " + e.toString(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.error_modelservice_for_srv_name", locale));
    }
    Map<String, Object> persistMap = modelService.makeValid(context, ModelService.IN_PARAM);
    persistMap.put("userLogin", userLogin);
    try {
        Map<String, Object> persistContentResult = dispatcher.runSync("persistContentAndAssoc", persistMap);
        if (ServiceUtil.isError(persistContentResult)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentContentCreatingError", UtilMisc.toMap("serviceName", "persistContentAndAssoc"), locale), null, null, persistContentResult);
        }
        contentId = (String) persistContentResult.get("contentId");
        result.putAll(persistContentResult);
        Map<String, Object> contentRevisionMap = new HashMap<String, Object>();
        contentRevisionMap.put("itemContentId", contentId);
        contentRevisionMap.put("contentId", contentId);
        contentRevisionMap.put("userLogin", userLogin);
        Map<String, Object> persistRevResult = dispatcher.runSync("persistContentRevisionAndItem", contentRevisionMap);
        if (ServiceUtil.isError(persistRevResult)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentContentCreatingError", UtilMisc.toMap("serviceName", "persistContentRevisionAndItem"), locale), null, null, persistRevResult);
        }
        result.putAll(persistRevResult);
        return result;
    } catch (GenericServiceException e) {
        Debug.logError(e, "Error running serviceName, 'persistContentAndAssoc'. " + e.toString(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentContentCreatingError", UtilMisc.toMap("serviceName", "persistContentAndAssoc"), locale) + e.toString());
    }
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) Delegator(org.apache.ofbiz.entity.Delegator) HashMap(java.util.HashMap) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ModelService(org.apache.ofbiz.service.ModelService)

Example 24 with ModelService

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

the class OrderTestServices method createTestSalesOrders.

public static Map<String, Object> createTestSalesOrders(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Integer numberOfOrders = (Integer) context.get("numberOfOrders");
    int numberOfOrdersInt = numberOfOrders.intValue();
    for (int i = 1; i <= numberOfOrdersInt; i++) {
        try {
            ModelService modelService = dctx.getModelService("createTestSalesOrderSingle");
            Map<String, Object> outputMap = dispatcher.runSync("createTestSalesOrderSingle", modelService.makeValid(context, ModelService.IN_PARAM));
            if (ServiceUtil.isError(outputMap)) {
                return ServiceUtil.returnError(ServiceUtil.getErrorMessage(outputMap));
            }
            String orderId = (String) outputMap.get("orderId");
            Debug.logInfo("Test sales order with id [" + orderId + "] has been processed.", module);
        } catch (GenericServiceException e) {
            String errMsg = "Error calling createTestSalesOrderSingle: " + e.toString();
            Debug.logError(e, errMsg, module);
        }
    }
    return ServiceUtil.returnSuccess();
}
Also used : LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ModelService(org.apache.ofbiz.service.ModelService)

Example 25 with ModelService

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

the class ContentWorker method renderContentAsText.

public static void renderContentAsText(LocalDispatcher dispatcher, GenericValue content, Appendable out, Map<String, Object> templateContext, Locale locale, String mimeTypeId, boolean cache, List<GenericValue> webAnalytics) throws GeneralException, IOException {
    // if the content has a service attached run the service
    Delegator delegator = dispatcher.getDelegator();
    // Kept for backward compatibility
    String serviceName = content.getString("serviceName");
    GenericValue custMethod = null;
    if (UtilValidate.isNotEmpty(content.getString("customMethodId"))) {
        custMethod = EntityQuery.use(delegator).from("CustomMethod").where("customMethodId", content.get("customMethodId")).cache().queryOne();
    }
    if (custMethod != null)
        serviceName = custMethod.getString("customMethodName");
    if (dispatcher != null && UtilValidate.isNotEmpty(serviceName)) {
        DispatchContext dctx = dispatcher.getDispatchContext();
        ModelService service = dctx.getModelService(serviceName);
        if (service != null) {
            // put all requestParameters into templateContext to use them as IN service parameters
            Map<String, Object> tempTemplateContext = new HashMap<String, Object>();
            tempTemplateContext.putAll(UtilGenerics.<String, Object>checkMap(templateContext.get("requestParameters")));
            tempTemplateContext.putAll(templateContext);
            Map<String, Object> serviceCtx = service.makeValid(tempTemplateContext, ModelService.IN_PARAM);
            Map<String, Object> serviceRes;
            try {
                serviceRes = dispatcher.runSync(serviceName, serviceCtx);
                if (ServiceUtil.isError(serviceRes)) {
                    String errorMessage = ServiceUtil.getErrorMessage(serviceRes);
                    Debug.logError(errorMessage, module);
                    throw new GeneralException(errorMessage);
                }
            } catch (GenericServiceException e) {
                Debug.logError(e, module);
                throw e;
            }
            templateContext.putAll(serviceRes);
        }
    }
    String contentId = content.getString("contentId");
    if (templateContext == null) {
        templateContext = new HashMap<String, Object>();
    }
    // create the content facade
    ContentMapFacade facade = new ContentMapFacade(dispatcher, content, templateContext, locale, mimeTypeId, cache);
    // If this content is decorating something then tell the facade about it in order to maintain the chain of decoration
    ContentMapFacade decoratedContent = (ContentMapFacade) templateContext.get("decoratedContent");
    if (decoratedContent != null) {
        facade.setDecoratedContent(decoratedContent);
    }
    // look for a content decorator
    String contentDecoratorId = content.getString("decoratorContentId");
    // Check that the decoratorContent is not the same as the current content
    if (contentId.equals(contentDecoratorId)) {
        Debug.logError("[" + contentId + "] decoratorContentId is the same as contentId, ignoring.", module);
        contentDecoratorId = null;
    }
    // check to see if the decorator has already been run
    boolean isDecorated = Boolean.TRUE.equals(templateContext.get("_IS_DECORATED_"));
    if (!isDecorated && UtilValidate.isNotEmpty(contentDecoratorId)) {
        // if there is a decorator content; do not render this content;
        // instead render the decorator
        GenericValue decorator = EntityQuery.use(delegator).from("Content").where("contentId", contentDecoratorId).cache(cache).queryOne();
        if (decorator == null) {
            throw new GeneralException("No decorator content found for decorator contentId [" + contentDecoratorId + "]");
        }
        // render the decorator
        ContentMapFacade decFacade = new ContentMapFacade(dispatcher, decorator, templateContext, locale, mimeTypeId, cache);
        decFacade.setDecoratedContent(facade);
        facade.setIsDecorated(true);
        // decorated content
        templateContext.put("decoratedContent", facade);
        // decorator content
        templateContext.put("thisContent", decFacade);
        ContentWorker.renderContentAsText(dispatcher, contentDecoratorId, out, templateContext, locale, mimeTypeId, null, null, cache);
    } else {
        // get the data resource info
        String templateDataResourceId = content.getString("templateDataResourceId");
        String dataResourceId = content.getString("dataResourceId");
        if (UtilValidate.isEmpty(dataResourceId)) {
            Debug.logError("No dataResourceId found for contentId: " + content.getString("contentId"), module);
            return;
        }
        // set this content facade in the context
        templateContext.put("thisContent", facade);
        templateContext.put("contentId", contentId);
        // now if no template; just render the data
        if (UtilValidate.isEmpty(templateDataResourceId) || templateContext.containsKey("ignoreTemplate")) {
            if (UtilValidate.isEmpty(contentId)) {
                Debug.logError("No content ID found.", module);
                return;
            }
            if (UtilValidate.isNotEmpty(webAnalytics)) {
                DataResourceWorker.renderDataResourceAsText(dispatcher, delegator, dataResourceId, out, templateContext, locale, mimeTypeId, cache, webAnalytics);
            } else {
                DataResourceWorker.renderDataResourceAsText(dispatcher, dataResourceId, out, templateContext, locale, mimeTypeId, cache);
            }
        // there is a template; render the data and then the template
        } else {
            Writer dataWriter = new StringWriter();
            DataResourceWorker.renderDataResourceAsText(dispatcher, dataResourceId, dataWriter, templateContext, locale, mimeTypeId, cache);
            String textData = dataWriter.toString();
            if (textData != null) {
                textData = textData.trim();
            }
            String mimeType;
            try {
                mimeType = DataResourceWorker.getDataResourceMimeType(delegator, dataResourceId, null);
            } catch (GenericEntityException e) {
                throw new GeneralException(e.getMessage());
            }
            // This part is using an xml file as the input data and an ftl or xsl file to present it.
            if (UtilValidate.isNotEmpty(mimeType)) {
                if (mimeType.toLowerCase().indexOf("xml") >= 0) {
                    GenericValue dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).cache().queryOne();
                    GenericValue templateDataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", templateDataResourceId).cache().queryOne();
                    if ("FTL".equals(templateDataResource.getString("dataTemplateTypeId"))) {
                        StringReader sr = new StringReader(textData);
                        try {
                            NodeModel nodeModel = NodeModel.parse(new InputSource(sr));
                            templateContext.put("doc", nodeModel);
                        } catch (SAXException e) {
                            throw new GeneralException(e.getMessage());
                        } catch (ParserConfigurationException e2) {
                            throw new GeneralException(e2.getMessage());
                        }
                    } else {
                        templateContext.put("docFile", DataResourceWorker.getContentFile(dataResource.getString("dataResourceTypeId"), dataResource.getString("objectInfo"), (String) templateContext.get("contextRoot")).getAbsoluteFile().toString());
                    }
                } else {
                    // must be text
                    templateContext.put("textData", textData);
                }
            } else {
                templateContext.put("textData", textData);
            }
            // render the template
            DataResourceWorker.renderDataResourceAsText(dispatcher, templateDataResourceId, out, templateContext, locale, mimeTypeId, cache);
        }
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) InputSource(org.xml.sax.InputSource) GeneralException(org.apache.ofbiz.base.util.GeneralException) HashMap(java.util.HashMap) ModelService(org.apache.ofbiz.service.ModelService) SAXException(org.xml.sax.SAXException) DispatchContext(org.apache.ofbiz.service.DispatchContext) NodeModel(freemarker.ext.dom.NodeModel) Delegator(org.apache.ofbiz.entity.Delegator) StringWriter(java.io.StringWriter) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) StringReader(java.io.StringReader) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) StringWriter(java.io.StringWriter) Writer(java.io.Writer)

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