Search in sources :

Example 1 with GenericConfigException

use of org.apache.ofbiz.base.config.GenericConfigException in project ofbiz-framework by apache.

the class ModelServiceReader method getModelServices.

private Map<String, ModelService> getModelServices() {
    UtilTimer utilTimer = new UtilTimer();
    Document document;
    if (this.isFromURL) {
        document = getDocument(readerURL);
        if (document == null) {
            return null;
        }
    } else {
        try {
            document = handler.getDocument();
        } catch (GenericConfigException e) {
            Debug.logError(e, "Error getting XML document from resource", module);
            return null;
        }
    }
    Map<String, ModelService> modelServices = new HashMap<>();
    Element docElement = document.getDocumentElement();
    if (docElement == null) {
        return null;
    }
    docElement.normalize();
    String resourceLocation = handler.getLocation();
    try {
        resourceLocation = handler.getURL().toExternalForm();
    } catch (GenericConfigException e) {
        Debug.logError(e, "Could not get resource URL", module);
    }
    int i = 0;
    Node curChild = docElement.getFirstChild();
    if (curChild != null) {
        if (this.isFromURL) {
            utilTimer.timerString("Before start of service loop in file " + readerURL);
        } else {
            utilTimer.timerString("Before start of service loop in " + handler);
        }
        do {
            if (curChild.getNodeType() == Node.ELEMENT_NODE && "service".equals(curChild.getNodeName())) {
                i++;
                Element curServiceElement = (Element) curChild;
                String serviceName = UtilXml.checkEmpty(curServiceElement.getAttribute("name"));
                // check to see if service with same name has already been read
                if (modelServices.containsKey(serviceName)) {
                    Debug.logWarning("Service " + serviceName + " is defined more than once, " + "most recent will over-write previous definition(s)", module);
                }
                ModelService service = createModelService(curServiceElement, resourceLocation);
                modelServices.put(serviceName, service);
            }
        } while ((curChild = curChild.getNextSibling()) != null);
    } else {
        Debug.logWarning("No child nodes found.", module);
    }
    if (this.isFromURL) {
        utilTimer.timerString("Finished file " + readerURL + " - Total Services: " + i + " FINISHED");
        Debug.logInfo("Loaded [" + i + "] Services from " + readerURL, module);
    } else {
        utilTimer.timerString("Finished document in " + handler + " - Total Services: " + i + " FINISHED");
        Debug.logInfo("Loaded [" + i + "] Services from " + resourceLocation, module);
    }
    return modelServices;
}
Also used : GenericConfigException(org.apache.ofbiz.base.config.GenericConfigException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) UtilTimer(org.apache.ofbiz.base.util.UtilTimer) Document(org.w3c.dom.Document)

Example 2 with GenericConfigException

use of org.apache.ofbiz.base.config.GenericConfigException in project ofbiz-framework by apache.

the class ServiceDispatcher method runStartupServices.

// run startup services
private synchronized int runStartupServices() {
    if (!enableSvcs || jm == null) {
        return 0;
    }
    int servicesScheduled = 0;
    List<StartupService> startupServices = null;
    try {
        startupServices = ServiceConfigUtil.getServiceEngine().getStartupServices();
    } catch (GenericConfigException e) {
        Debug.logWarning(e, "Exception thrown while getting service config: ", module);
        return 0;
    }
    for (StartupService startupService : startupServices) {
        String serviceName = startupService.getName();
        String runtimeDataId = startupService.getRuntimeDataId();
        int runtimeDelay = startupService.getRuntimeDelay();
        String sendToPool = startupService.getRunInPool();
        if (UtilValidate.isEmpty(sendToPool)) {
            try {
                sendToPool = ServiceConfigUtil.getServiceEngine().getThreadPool().getSendToPool();
            } catch (GenericConfigException e) {
                Debug.logError(e, "Unable to get send pool in service [" + serviceName + "]: ", module);
            }
        }
        // current time + 1 sec delay + extended delay
        long runtime = System.currentTimeMillis() + 1000 + runtimeDelay;
        try {
            jm.schedule(sendToPool, serviceName, runtimeDataId, runtime);
        } catch (JobManagerException e) {
            Debug.logError(e, "Unable to schedule service [" + serviceName + "]", module);
        }
    }
    return servicesScheduled;
}
Also used : GenericConfigException(org.apache.ofbiz.base.config.GenericConfigException) StartupService(org.apache.ofbiz.service.config.model.StartupService) JobManagerException(org.apache.ofbiz.service.job.JobManagerException)

Example 3 with GenericConfigException

use of org.apache.ofbiz.base.config.GenericConfigException in project ofbiz-framework by apache.

the class ServiceDispatcher method checkAuth.

// checks if parameters were passed for authentication
private Map<String, Object> checkAuth(String localName, Map<String, Object> context, ModelService origService) throws ServiceAuthException, GenericServiceException {
    String service = null;
    try {
        service = ServiceConfigUtil.getServiceEngine().getAuthorization().getServiceName();
    } catch (GenericConfigException e) {
        throw new GenericServiceException(e.getMessage(), e);
    }
    if (service == null) {
        throw new GenericServiceException("No Authentication Service Defined");
    }
    if (service.equals(origService.name)) {
        // manually calling the auth service, don't continue...
        return context;
    }
    if (UtilValidate.isNotEmpty(context.get("login.username"))) {
        // check for a username/password, if there log the user in and make the userLogin object
        String username = (String) context.get("login.username");
        if (UtilValidate.isNotEmpty(context.get("login.password"))) {
            String password = (String) context.get("login.password");
            context.put("userLogin", getLoginObject(service, localName, username, password, (Locale) context.get("locale")));
            context.remove("login.password");
        } else {
            context.put("userLogin", getLoginObject(service, localName, username, null, (Locale) context.get("locale")));
        }
        context.remove("login.username");
    } else {
        // if a userLogin object is there, make sure the given username/password exists in our local database
        GenericValue userLogin = (GenericValue) context.get("userLogin");
        if (userLogin != null) {
            // Because of encrypted passwords we can't just pass in the encrypted version of the password from the data, so we'll do something different and not run the userLogin service...
            // The old way: GenericValue newUserLogin = getLoginObject(service, localName, userLogin.getString("userLoginId"), userLogin.getString("currentPassword"), (Locale) context.get("locale"));
            GenericValue newUserLogin = null;
            try {
                newUserLogin = this.getDelegator().findOne("UserLogin", true, "userLoginId", userLogin.get("userLoginId"));
            } catch (GenericEntityException e) {
                Debug.logError(e, "Error looking up service authentication UserLogin: " + e.toString(), module);
            // leave newUserLogin null, will be handled below
            }
            if (newUserLogin == null) {
                // uh oh, couldn't validate that one...
                // we'll have to remove it from the incoming context which will cause an auth error later if auth is required
                Debug.logInfo("Service auth failed for userLoginId [" + userLogin.get("userLoginId") + "] because UserLogin record not found.", module);
                context.remove("userLogin");
            } else if (newUserLogin.getString("currentPassword") != null && !newUserLogin.getString("currentPassword").equals(userLogin.getString("currentPassword"))) {
                // passwords didn't match, remove the userLogin for failed auth
                Debug.logInfo("Service auth failed for userLoginId [" + userLogin.get("userLoginId") + "] because UserLogin record currentPassword fields did not match; note that the UserLogin object passed into a service may need to have the currentPassword encrypted.", module);
                context.remove("userLogin");
            }
        }
    }
    // evaluate permissions for the service or throw exception if fail.
    DispatchContext dctx = this.getLocalContext(localName);
    if (UtilValidate.isNotEmpty(origService.permissionServiceName)) {
        Map<String, Object> permResp = origService.evalPermission(dctx, context);
        Boolean hasPermission = (Boolean) permResp.get("hasPermission");
        if (hasPermission == null) {
            throw new ServiceAuthException("ERROR: the permission-service [" + origService.permissionServiceName + "] did not return a result. Not running the service [" + origService.name + "]");
        }
        if (hasPermission.booleanValue()) {
            context.putAll(permResp);
            context = origService.makeValid(context, ModelService.IN_PARAM);
        } else {
            String message = (String) permResp.get("failMessage");
            if (UtilValidate.isEmpty(message)) {
                message = ServiceUtil.getErrorMessage(permResp);
            }
            if (UtilValidate.isEmpty(message)) {
                message = "You do not have permission to invoke the service [" + origService.name + "]";
            }
            throw new ServiceAuthException(message);
        }
    } else {
        if (!origService.evalPermissions(dctx, context)) {
            throw new ServiceAuthException("You do not have permission to invoke the service [" + origService.name + "]");
        }
    }
    return context;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) GenericConfigException(org.apache.ofbiz.base.config.GenericConfigException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException)

Example 4 with GenericConfigException

use of org.apache.ofbiz.base.config.GenericConfigException in project ofbiz-framework by apache.

the class ServiceUtil method purgeOldJobs.

public static Map<String, Object> purgeOldJobs(DispatchContext dctx, Map<String, ? extends Object> context) {
    Locale locale = (Locale) context.get("locale");
    Debug.logWarning("purgeOldJobs service invoked. This service is obsolete - the Job Scheduler will purge old jobs automatically.", module);
    String sendPool = null;
    Calendar cal = Calendar.getInstance();
    try {
        sendPool = ServiceConfigUtil.getServiceEngine().getThreadPool().getSendToPool();
        int daysToKeep = ServiceConfigUtil.getServiceEngine().getThreadPool().getPurgeJobDays();
        cal.add(Calendar.DAY_OF_YEAR, -daysToKeep);
    } catch (GenericConfigException e) {
        Debug.logWarning(e, "Exception thrown while getting service configuration: ", module);
        return returnError(UtilProperties.getMessage(ServiceUtil.resource, "ServiceExceptionThrownWhileGettingServiceConfiguration", UtilMisc.toMap("errorString", e), locale));
    }
    Delegator delegator = dctx.getDelegator();
    Timestamp purgeTime = new Timestamp(cal.getTimeInMillis());
    // create the conditions to query
    EntityCondition pool = EntityCondition.makeCondition("poolId", sendPool);
    List<EntityExpr> finExp = UtilMisc.toList(EntityCondition.makeCondition("finishDateTime", EntityOperator.NOT_EQUAL, null));
    finExp.add(EntityCondition.makeCondition("finishDateTime", EntityOperator.LESS_THAN, purgeTime));
    List<EntityExpr> canExp = UtilMisc.toList(EntityCondition.makeCondition("cancelDateTime", EntityOperator.NOT_EQUAL, null));
    canExp.add(EntityCondition.makeCondition("cancelDateTime", EntityOperator.LESS_THAN, purgeTime));
    EntityCondition cancelled = EntityCondition.makeCondition(canExp);
    EntityCondition finished = EntityCondition.makeCondition(finExp);
    EntityCondition doneCond = EntityCondition.makeCondition(UtilMisc.toList(cancelled, finished), EntityOperator.OR);
    // always suspend the current transaction; use the one internally
    Transaction parent = null;
    try {
        if (TransactionUtil.getStatus() != TransactionUtil.STATUS_NO_TRANSACTION) {
            parent = TransactionUtil.suspend();
        }
        // lookup the jobs - looping 1000 at a time to avoid problems with cursors
        // also, using unique transaction to delete as many as possible even with errors
        boolean noMoreResults = false;
        boolean beganTx1 = false;
        while (!noMoreResults) {
            // current list of records
            List<GenericValue> curList = null;
            try {
                // begin this transaction
                beganTx1 = TransactionUtil.begin();
                EntityQuery eq = EntityQuery.use(delegator).select("jobId").from("JobSandbox").where(EntityCondition.makeCondition(UtilMisc.toList(doneCond, pool))).cursorScrollInsensitive().maxRows(1000);
                try (EntityListIterator foundJobs = eq.queryIterator()) {
                    curList = foundJobs.getPartialList(1, 1000);
                }
            } catch (GenericEntityException e) {
                Debug.logError(e, "Cannot obtain job data from datasource", module);
                try {
                    TransactionUtil.rollback(beganTx1, e.getMessage(), e);
                } catch (GenericTransactionException e1) {
                    Debug.logWarning(e1, module);
                }
                return ServiceUtil.returnError(e.getMessage());
            } finally {
                try {
                    TransactionUtil.commit(beganTx1);
                } catch (GenericTransactionException e) {
                    Debug.logWarning(e, module);
                }
            }
            // remove each from the list in its own transaction
            if (UtilValidate.isNotEmpty(curList)) {
                for (GenericValue job : curList) {
                    String jobId = job.getString("jobId");
                    boolean beganTx2 = false;
                    try {
                        beganTx2 = TransactionUtil.begin();
                        job.remove();
                    } catch (GenericEntityException e) {
                        Debug.logInfo("Cannot remove job data for ID: " + jobId, module);
                        try {
                            TransactionUtil.rollback(beganTx2, e.getMessage(), e);
                        } catch (GenericTransactionException e1) {
                            Debug.logWarning(e1, module);
                        }
                    } finally {
                        try {
                            TransactionUtil.commit(beganTx2);
                        } catch (GenericTransactionException e) {
                            Debug.logWarning(e, module);
                        }
                    }
                }
            } else {
                noMoreResults = true;
            }
        }
        // Now JobSandbox data is cleaned up. Now process Runtime data and remove the whole data in single shot that is of no need.
        boolean beganTx3 = false;
        GenericValue runtimeData = null;
        List<GenericValue> runtimeDataToDelete = new LinkedList<>();
        long jobsandBoxCount = 0;
        try {
            // begin this transaction
            beganTx3 = TransactionUtil.begin();
            EntityQuery eq = EntityQuery.use(delegator).select("runtimeDataId").from("RuntimeData");
            try (EntityListIterator runTimeDataIt = eq.queryIterator()) {
                while ((runtimeData = runTimeDataIt.next()) != null) {
                    EntityCondition whereCondition = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("runtimeDataId", EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition("runtimeDataId", EntityOperator.EQUALS, runtimeData.getString("runtimeDataId"))), EntityOperator.AND);
                    jobsandBoxCount = EntityQuery.use(delegator).from("JobSandbox").where(whereCondition).queryCount();
                    if (BigDecimal.ZERO.compareTo(BigDecimal.valueOf(jobsandBoxCount)) == 0) {
                        runtimeDataToDelete.add(runtimeData);
                    }
                }
            }
            // Now we are ready to delete runtimeData, we can safely delete complete list that we have recently fetched i.e runtimeDataToDelete.
            delegator.removeAll(runtimeDataToDelete);
        } catch (GenericEntityException e) {
            Debug.logError(e, "Cannot obtain runtime data from datasource", module);
            try {
                TransactionUtil.rollback(beganTx3, e.getMessage(), e);
            } catch (GenericTransactionException e1) {
                Debug.logWarning(e1, module);
            }
            return ServiceUtil.returnError(e.getMessage());
        } finally {
            try {
                TransactionUtil.commit(beganTx3);
            } catch (GenericTransactionException e) {
                Debug.logWarning(e, module);
            }
        }
    } catch (GenericTransactionException e) {
        Debug.logError(e, "Unable to suspend transaction; cannot purge jobs!", module);
        return ServiceUtil.returnError(e.getMessage());
    } finally {
        if (parent != null) {
            try {
                TransactionUtil.resume(parent);
            } catch (GenericTransactionException e) {
                Debug.logWarning(e, module);
            }
        }
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) Calendar(com.ibm.icu.util.Calendar) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) Timestamp(java.sql.Timestamp) LinkedList(java.util.LinkedList) GenericConfigException(org.apache.ofbiz.base.config.GenericConfigException) Delegator(org.apache.ofbiz.entity.Delegator) Transaction(javax.transaction.Transaction) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr)

Example 5 with GenericConfigException

use of org.apache.ofbiz.base.config.GenericConfigException in project ofbiz-framework by apache.

the class GenericAsyncEngine method runAsync.

/**
 * @see org.apache.ofbiz.service.engine.GenericEngine#runAsync(java.lang.String, org.apache.ofbiz.service.ModelService, java.util.Map, org.apache.ofbiz.service.GenericRequester, boolean)
 */
public void runAsync(String localName, ModelService modelService, Map<String, Object> context, GenericRequester requester, boolean persist) throws GenericServiceException {
    DispatchContext dctx = dispatcher.getLocalContext(localName);
    Job job = null;
    if (persist) {
        // check for a delegator
        if (dispatcher.getDelegator() == null) {
            throw new GenericServiceException("No reference to delegator; cannot run persisted services.");
        }
        GenericValue jobV = null;
        // Build the value object(s).
        try {
            // Create the runtime data
            String dataId = dispatcher.getDelegator().getNextSeqId("RuntimeData");
            GenericValue runtimeData = dispatcher.getDelegator().makeValue("RuntimeData", "runtimeDataId", dataId);
            runtimeData.set("runtimeInfo", XmlSerializer.serialize(context));
            runtimeData.create();
            // Get the userLoginId out of the context
            String authUserLoginId = null;
            if (context.get("userLogin") != null) {
                GenericValue userLogin = (GenericValue) context.get("userLogin");
                authUserLoginId = userLogin.getString("userLoginId");
            }
            // Create the job info
            String jobId = dispatcher.getDelegator().getNextSeqId("JobSandbox");
            String jobName = Long.toString(System.currentTimeMillis());
            Map<String, Object> jFields = UtilMisc.toMap("jobId", jobId, "jobName", jobName, "runTime", UtilDateTime.nowTimestamp());
            jFields.put("poolId", ServiceConfigUtil.getServiceEngine().getThreadPool().getSendToPool());
            jFields.put("statusId", "SERVICE_PENDING");
            jFields.put("serviceName", modelService.name);
            jFields.put("loaderName", localName);
            jFields.put("maxRetry", Long.valueOf(modelService.maxRetry));
            jFields.put("runtimeDataId", dataId);
            if (UtilValidate.isNotEmpty(authUserLoginId)) {
                jFields.put("authUserLoginId", authUserLoginId);
            }
            jobV = dispatcher.getDelegator().makeValue("JobSandbox", jFields);
            jobV.create();
        } catch (GenericEntityException e) {
            throw new GenericServiceException("Unable to create persisted job", e);
        } catch (SerializeException e) {
            throw new GenericServiceException("Problem serializing service attributes", e);
        } catch (FileNotFoundException e) {
            throw new GenericServiceException("Problem serializing service attributes", e);
        } catch (IOException e) {
            throw new GenericServiceException("Problem serializing service attributes", e);
        } catch (GenericConfigException e) {
            throw new GenericServiceException("Problem serializing service attributes", e);
        }
        Debug.logInfo("Persisted job queued : " + jobV.getString("jobName"), module);
    } else {
        JobManager jMgr = dispatcher.getJobManager();
        if (jMgr != null) {
            String name = Long.toString(System.currentTimeMillis());
            String jobId = modelService.name + "." + name;
            job = new GenericServiceJob(dctx, jobId, name, modelService.name, context, requester);
            try {
                dispatcher.getJobManager().runJob(job);
            } catch (JobManagerException jse) {
                throw new GenericServiceException("Cannot run job.", jse);
            }
        } else {
            throw new GenericServiceException("Cannot get JobManager instance to invoke the job");
        }
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GenericServiceJob(org.apache.ofbiz.service.job.GenericServiceJob) SerializeException(org.apache.ofbiz.entity.serialize.SerializeException) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) JobManager(org.apache.ofbiz.service.job.JobManager) DispatchContext(org.apache.ofbiz.service.DispatchContext) GenericConfigException(org.apache.ofbiz.base.config.GenericConfigException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) JobManagerException(org.apache.ofbiz.service.job.JobManagerException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) Job(org.apache.ofbiz.service.job.Job) GenericServiceJob(org.apache.ofbiz.service.job.GenericServiceJob)

Aggregations

GenericConfigException (org.apache.ofbiz.base.config.GenericConfigException)27 Element (org.w3c.dom.Element)9 LinkedList (java.util.LinkedList)7 MainResourceHandler (org.apache.ofbiz.base.config.MainResourceHandler)7 ResourceHandler (org.apache.ofbiz.base.config.ResourceHandler)7 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)7 GenericValue (org.apache.ofbiz.entity.GenericValue)5 ComponentConfig (org.apache.ofbiz.base.component.ComponentConfig)4 UtilTimer (org.apache.ofbiz.base.util.UtilTimer)4 GenericEntityConfException (org.apache.ofbiz.entity.GenericEntityConfException)4 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)4 Document (org.w3c.dom.Document)4 Calendar (com.ibm.icu.util.Calendar)3 Timestamp (java.sql.Timestamp)3 HashMap (java.util.HashMap)3 DelegatorElement (org.apache.ofbiz.entity.config.model.DelegatorElement)3 IOException (java.io.IOException)2 URL (java.net.URL)2 ArrayList (java.util.ArrayList)2 Locale (java.util.Locale)2