Search in sources :

Example 21 with GenericConfigException

use of org.apache.ofbiz.base.config.GenericConfigException 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 22 with GenericConfigException

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

the class XMLRPCClientEngine method serviceInvoker.

/*
     *  Invoke the remote XMLRPC SERVICE : This engine convert all value in IN mode to one struct.
     */
private Map<String, Object> serviceInvoker(ModelService modelService, Map<String, Object> context) throws GenericServiceException {
    if (modelService.location == null || modelService.invoke == null) {
        throw new GenericServiceException("Cannot locate service to invoke");
    }
    XmlRpcClientConfigImpl config = null;
    XmlRpcClient client = null;
    String serviceName = modelService.invoke;
    String engine = modelService.engineName;
    String url = null;
    String login = null;
    String password = null;
    String keyStoreComponent = null;
    String keyStoreName = null;
    String keyAlias = null;
    try {
        url = ServiceConfigUtil.getEngineParameter(engine, "url");
        if (Start.getInstance().getConfig().portOffset != 0) {
            String s = url.substring(url.lastIndexOf(":") + 1);
            Integer rpcPort = Integer.valueOf(s.substring(0, s.indexOf("/")));
            Integer port = rpcPort + Start.getInstance().getConfig().portOffset;
            url = url.replace(rpcPort.toString(), port.toString());
        }
        login = ServiceConfigUtil.getEngineParameter(engine, "login");
        password = ServiceConfigUtil.getEngineParameter(engine, "password");
        keyStoreComponent = ServiceConfigUtil.getEngineParameter(engine, "keyStoreComponent");
        keyStoreName = ServiceConfigUtil.getEngineParameter(engine, "keyStoreName");
        keyAlias = ServiceConfigUtil.getEngineParameter(engine, "keyAlias");
        config = new XmlRpcClientConfigImpl();
        config.setBasicUserName(login);
        config.setBasicPassword(password);
        config.setServerURL(new URL(url));
    } catch (MalformedURLException | GenericConfigException e) {
        throw new GenericServiceException("Cannot invoke service : engine parameters are not correct");
    }
    if (UtilValidate.isNotEmpty(keyStoreComponent) && UtilValidate.isNotEmpty(keyStoreName) && UtilValidate.isNotEmpty(keyAlias)) {
        client = new XmlRpcClient(config, keyStoreComponent, keyStoreName, keyAlias);
    } else {
        client = new XmlRpcClient(config);
    }
    List<ModelParam> inModelParamList = modelService.getInModelParamList();
    if (Debug.verboseOn()) {
        Debug.logVerbose("[XMLRPCClientEngine.invoke] : Parameter length - " + inModelParamList.size(), module);
        for (ModelParam p : inModelParamList) {
            Debug.logVerbose("[XMLRPCClientEngine.invoke} : Parameter: " + p.name + " (" + p.mode + ")", module);
        }
    }
    Map<String, Object> result = null;
    Map<String, Object> params = new HashMap<>();
    for (ModelParam modelParam : modelService.getModelParamList()) {
        // don't include OUT parameters in this list, only IN and INOUT
        if (ModelService.OUT_PARAM.equals(modelParam.mode) || modelParam.internal) {
            continue;
        }
        Object paramValue = context.get(modelParam.name);
        if (paramValue != null) {
            params.put(modelParam.name, paramValue);
        }
    }
    List<Map<String, Object>> listParams = UtilMisc.toList(params);
    try {
        result = UtilGenerics.cast(client.execute(serviceName, listParams.toArray()));
    } catch (XmlRpcException e) {
        result = ServiceUtil.returnError(e.getLocalizedMessage());
    }
    return result;
}
Also used : MalformedURLException(java.net.MalformedURLException) XmlRpcClient(org.apache.ofbiz.service.xmlrpc.XmlRpcClient) HashMap(java.util.HashMap) ModelParam(org.apache.ofbiz.service.ModelParam) XmlRpcClientConfigImpl(org.apache.xmlrpc.client.XmlRpcClientConfigImpl) URL(java.net.URL) GenericConfigException(org.apache.ofbiz.base.config.GenericConfigException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) HashMap(java.util.HashMap) Map(java.util.Map) XmlRpcException(org.apache.xmlrpc.XmlRpcException)

Example 23 with GenericConfigException

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

the class ServiceGroupReader method readConfig.

public static void readConfig() {
    List<ServiceGroups> serviceGroupsList = null;
    try {
        serviceGroupsList = ServiceConfigUtil.getServiceEngine().getServiceGroups();
    } catch (GenericConfigException e) {
        // FIXME: Refactor API so exceptions can be thrown and caught.
        Debug.logError(e, module);
        throw new RuntimeException(e.getMessage());
    }
    for (ServiceGroups serviceGroup : serviceGroupsList) {
        ResourceHandler handler = new MainResourceHandler(ServiceConfigUtil.getServiceEngineXmlFileName(), serviceGroup.getLoader(), serviceGroup.getLocation());
        addGroupDefinitions(handler);
    }
    // get all of the component resource group stuff, ie specified in each ofbiz-component.xml file
    for (ComponentConfig.ServiceResourceInfo componentResourceInfo : ComponentConfig.getAllServiceResourceInfos("group")) {
        addGroupDefinitions(componentResourceInfo.createResourceHandler());
    }
}
Also used : GenericConfigException(org.apache.ofbiz.base.config.GenericConfigException) MainResourceHandler(org.apache.ofbiz.base.config.MainResourceHandler) ComponentConfig(org.apache.ofbiz.base.component.ComponentConfig) ServiceGroups(org.apache.ofbiz.service.config.model.ServiceGroups) ResourceHandler(org.apache.ofbiz.base.config.ResourceHandler) MainResourceHandler(org.apache.ofbiz.base.config.MainResourceHandler)

Example 24 with GenericConfigException

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

the class ServiceGroupReader method addGroupDefinitions.

public static void addGroupDefinitions(ResourceHandler handler) {
    Element rootElement = null;
    try {
        rootElement = handler.getDocument().getDocumentElement();
    } catch (GenericConfigException e) {
        Debug.logError(e, module);
        return;
    }
    int numDefs = 0;
    for (Element group : UtilXml.childElementList(rootElement, "group")) {
        String groupName = group.getAttribute("name");
        if (groupName.isEmpty()) {
            Debug.logError("XML Parsing error: <group> element 'name' attribute null or empty", module);
            continue;
        }
        groupsCache.put(groupName, new GroupModel(group));
        numDefs++;
    }
    if (Debug.infoOn()) {
        String resourceLocation = handler.getLocation();
        try {
            resourceLocation = handler.getURL().toExternalForm();
        } catch (GenericConfigException e) {
            Debug.logError(e, "Could not get resource URL", module);
        }
        Debug.logInfo("Loaded [" + numDefs + "] Group definitions from " + resourceLocation, module);
    }
}
Also used : GenericConfigException(org.apache.ofbiz.base.config.GenericConfigException) Element(org.w3c.dom.Element)

Example 25 with GenericConfigException

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

the class SSLServerSocketFactory method createServerSocket.

public ServerSocket createServerSocket(int port) throws IOException {
    char[] passphrase = null;
    if (ksPass != null) {
        passphrase = ksPass.toCharArray();
    }
    KeyStore ks = null;
    if (keystore != null) {
        try (FileInputStream fis = new FileInputStream(keystore)) {
            ks = KeyStore.getInstance(ksType);
            ks.load(fis, passphrase);
        } catch (NoSuchAlgorithmException | IOException | KeyStoreException | CertificateException e) {
            Debug.logError(e, module);
            throw new IOException(e.getMessage());
        }
    }
    if (alias == null) {
        throw new IOException("SSL certificate alias cannot be null; MUST be set for SSLServerSocketFactory!");
    }
    javax.net.ssl.SSLServerSocketFactory factory = null;
    try {
        if (ks != null) {
            factory = SSLUtil.getSSLServerSocketFactory(ks, ksPass, alias);
        } else {
            factory = SSLUtil.getSSLServerSocketFactory(alias);
        }
    } catch (GeneralSecurityException | GenericConfigException e) {
        Debug.logError(e, "Error getting javax.net.ssl.SSLServerSocketFactory instance for Service Engine RMI calls: " + e.toString(), module);
        throw new IOException(e.toString());
    }
    if (factory == null) {
        throw new IOException("Unable to obtain SSLServerSocketFactory for provided KeyStore");
    }
    SSLServerSocket socket = (SSLServerSocket) factory.createServerSocket(port);
    socket.setNeedClientAuth(clientAuth);
    return socket;
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) SSLServerSocket(javax.net.ssl.SSLServerSocket) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) GenericConfigException(org.apache.ofbiz.base.config.GenericConfigException)

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