Search in sources :

Example 11 with DispatchContext

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

Example 12 with DispatchContext

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

the class SimpleServiceEngine method serviceInvoker.

// Invoke the simple method from a service context
private Map<String, Object> serviceInvoker(String localName, ModelService modelService, Map<String, ? extends Object> context) throws GenericServiceException {
    // static java service methods should be: public Map methodName(DispatchContext dctx, Map context)
    DispatchContext dctx = dispatcher.getLocalContext(localName);
    // check the package and method names
    if (modelService.location == null || modelService.invoke == null)
        throw new GenericServiceException("Cannot locate service to invoke (location or invoke name missing)");
    // get the classloader to use
    ClassLoader classLoader = null;
    if (dctx != null)
        classLoader = dctx.getClassLoader();
    // current thread's ClassLoader by default if null passed in
    try {
        return SimpleMethod.runSimpleService(this.getLocation(modelService), modelService.invoke, dctx, context, classLoader);
    } catch (MiniLangException e) {
        throw new GenericServiceException("Error running simple method [" + modelService.invoke + "] in XML file [" + modelService.location + "]: ", e);
    }
}
Also used : DispatchContext(org.apache.ofbiz.service.DispatchContext) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 13 with DispatchContext

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

the class JobManager method poll.

/**
 * Scans the JobSandbox entity and returns a list of jobs that are due to run.
 * Returns an empty list if there are no jobs due to run.
 * This method is called by the {@link JobPoller} polling thread.
 */
protected List<Job> poll(int limit) {
    assertIsRunning();
    // The rest of this method logs exceptions and does not throw them.
    // The idea is to keep the JobPoller working even when a database
    // connection is not available (possible on a saturated server).
    DispatchContext dctx = getDispatcher().getDispatchContext();
    if (dctx == null) {
        Debug.logWarning("Unable to locate DispatchContext object; not running job!", module);
        return Collections.emptyList();
    }
    // basic query
    List<EntityExpr> expressions = UtilMisc.toList(EntityCondition.makeCondition("runTime", EntityOperator.LESS_THAN_EQUAL_TO, UtilDateTime.nowTimestamp()), EntityCondition.makeCondition("startDateTime", EntityOperator.EQUALS, null), EntityCondition.makeCondition("cancelDateTime", EntityOperator.EQUALS, null), EntityCondition.makeCondition("runByInstanceId", EntityOperator.EQUALS, null));
    // limit to just defined pools
    List<String> pools = null;
    try {
        pools = getRunPools();
    } catch (GenericConfigException e) {
        Debug.logWarning(e, "Unable to get run pools - not running job: ", module);
        return Collections.emptyList();
    }
    List<EntityExpr> poolsExpr = UtilMisc.toList(EntityCondition.makeCondition("poolId", EntityOperator.EQUALS, null));
    if (!pools.isEmpty()) {
        for (String poolName : pools) {
            poolsExpr.add(EntityCondition.makeCondition("poolId", EntityOperator.EQUALS, poolName));
        }
    }
    List<Job> poll = new ArrayList<>(limit);
    // make the conditions
    EntityCondition baseCondition = EntityCondition.makeCondition(expressions);
    EntityCondition poolCondition = EntityCondition.makeCondition(poolsExpr, EntityOperator.OR);
    EntityCondition mainCondition = EntityCondition.makeCondition(UtilMisc.toList(baseCondition, poolCondition));
    boolean beganTransaction = false;
    try {
        beganTransaction = TransactionUtil.begin();
        if (!beganTransaction) {
            Debug.logWarning("Unable to poll JobSandbox for jobs; unable to begin transaction.", module);
            return poll;
        }
        try (EntityListIterator jobsIterator = EntityQuery.use(delegator).from("JobSandbox").where(mainCondition).orderBy("runTime").queryIterator()) {
            GenericValue jobValue = jobsIterator.next();
            while (jobValue != null) {
                // Claim ownership of this value. Using storeByCondition to avoid a race condition.
                List<EntityExpr> updateExpression = UtilMisc.toList(EntityCondition.makeCondition("jobId", EntityOperator.EQUALS, jobValue.get("jobId")), EntityCondition.makeCondition("runByInstanceId", EntityOperator.EQUALS, null));
                int rowsUpdated = delegator.storeByCondition("JobSandbox", UtilMisc.toMap("runByInstanceId", instanceId), EntityCondition.makeCondition(updateExpression));
                if (rowsUpdated == 1) {
                    poll.add(new PersistedServiceJob(dctx, jobValue, null));
                    if (poll.size() == limit) {
                        break;
                    }
                }
                jobValue = jobsIterator.next();
            }
        } catch (GenericEntityException e) {
            Debug.logWarning(e, module);
        }
        TransactionUtil.commit(beganTransaction);
    } catch (Throwable t) {
        String errMsg = "Exception thrown while polling JobSandbox: ";
        try {
            TransactionUtil.rollback(beganTransaction, errMsg, t);
        } catch (GenericEntityException e) {
            Debug.logWarning(e, "Exception thrown while rolling back transaction: ", module);
        }
        Debug.logWarning(t, errMsg, module);
        return Collections.emptyList();
    }
    if (poll.isEmpty()) {
        // No jobs to run, see if there are any jobs to purge
        Calendar cal = Calendar.getInstance();
        try {
            int daysToKeep = ServiceConfigUtil.getServiceEngine().getThreadPool().getPurgeJobDays();
            cal.add(Calendar.DAY_OF_YEAR, -daysToKeep);
        } catch (GenericConfigException e) {
            Debug.logWarning(e, "Unable to get purge job days: ", module);
            return Collections.emptyList();
        }
        Timestamp purgeTime = new Timestamp(cal.getTimeInMillis());
        List<EntityExpr> finExp = UtilMisc.toList(EntityCondition.makeCondition("finishDateTime", EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition("finishDateTime", EntityOperator.LESS_THAN, purgeTime));
        List<EntityExpr> canExp = UtilMisc.toList(EntityCondition.makeCondition("cancelDateTime", EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition("cancelDateTime", EntityOperator.LESS_THAN, purgeTime));
        EntityCondition doneCond = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition(canExp), EntityCondition.makeCondition(finExp)), EntityOperator.OR);
        mainCondition = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("runByInstanceId", instanceId), doneCond));
        beganTransaction = false;
        try {
            beganTransaction = TransactionUtil.begin();
            if (!beganTransaction) {
                Debug.logWarning("Unable to poll JobSandbox for jobs; unable to begin transaction.", module);
                return Collections.emptyList();
            }
            try (EntityListIterator jobsIterator = EntityQuery.use(delegator).from("JobSandbox").where(mainCondition).orderBy("jobId").queryIterator()) {
                GenericValue jobValue = jobsIterator.next();
                while (jobValue != null) {
                    poll.add(new PurgeJob(jobValue));
                    if (poll.size() == limit) {
                        break;
                    }
                    jobValue = jobsIterator.next();
                }
            } catch (GenericEntityException e) {
                Debug.logWarning(e, module);
            }
            TransactionUtil.commit(beganTransaction);
        } catch (Throwable t) {
            String errMsg = "Exception thrown while polling JobSandbox: ";
            try {
                TransactionUtil.rollback(beganTransaction, errMsg, t);
            } catch (GenericEntityException e) {
                Debug.logWarning(e, "Exception thrown while rolling back transaction: ", module);
            }
            Debug.logWarning(t, errMsg, module);
            return Collections.emptyList();
        }
    }
    return poll;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) Calendar(com.ibm.icu.util.Calendar) ArrayList(java.util.ArrayList) Timestamp(java.sql.Timestamp) DispatchContext(org.apache.ofbiz.service.DispatchContext) GenericConfigException(org.apache.ofbiz.base.config.GenericConfigException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr)

Example 14 with DispatchContext

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

the class GroupServiceModel method invoke.

/**
 * Invoker method to invoke this service
 * @param dispatcher ServiceDispatcher used for this invocation
 * @param localName Name of the LocalDispatcher used
 * @param context Context for this service (will use only valid parameters)
 * @return Map result Map
 * @throws GenericServiceException
 */
public Map<String, Object> invoke(ServiceDispatcher dispatcher, String localName, Map<String, Object> context) throws GenericServiceException {
    DispatchContext dctx = dispatcher.getLocalContext(localName);
    ModelService model = dctx.getModelService(getName());
    Map<String, Object> thisContext = model.makeValid(context, ModelService.IN_PARAM);
    Debug.logInfo("Running grouped service [" + serviceName + "]", module);
    if ("async".equals(getMode())) {
        List<String> requiredOut = model.getParameterNames(ModelService.OUT_PARAM, false);
        if (requiredOut.size() > 0) {
            Debug.logWarning("Grouped service (" + getName() + ") requested 'async' invocation; running sync because of required OUT parameters.", module);
            return dispatcher.runSync(localName, model, thisContext);
        }
        dispatcher.runAsync(localName, model, thisContext, false);
        return new HashMap<>();
    }
    return dispatcher.runSync(localName, model, thisContext);
}
Also used : DispatchContext(org.apache.ofbiz.service.DispatchContext) HashMap(java.util.HashMap) ModelService(org.apache.ofbiz.service.ModelService)

Aggregations

DispatchContext (org.apache.ofbiz.service.DispatchContext)14 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)11 HashMap (java.util.HashMap)7 GenericValue (org.apache.ofbiz.entity.GenericValue)6 ModelService (org.apache.ofbiz.service.ModelService)5 IOException (java.io.IOException)3 Locale (java.util.Locale)3 Map (java.util.Map)3 GeneralException (org.apache.ofbiz.base.util.GeneralException)3 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)3 ModelParam (org.apache.ofbiz.service.ModelParam)3 Writer (java.io.Writer)2 LinkedList (java.util.LinkedList)2 List (java.util.List)2 TimeZone (java.util.TimeZone)2 ScriptContext (javax.script.ScriptContext)2 HttpSession (javax.servlet.http.HttpSession)2 GenericConfigException (org.apache.ofbiz.base.config.GenericConfigException)2 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)2 ServiceAuthException (org.apache.ofbiz.service.ServiceAuthException)2