Search in sources :

Example 46 with Database

use of org.wso2.carbon.humantask.core.db.Database in project carbon-business-process by wso2.

the class ProcessManagementServiceSkeleton method processQuery.

/**
 * Query processes based on a {@link org.apache.ode.bpel.common.ProcessFilter} criteria. This is
 * implemented in memory rather than via database calls since the processes
 * are managed by the {@link org.apache.ode.bpel.iapi.ProcessStore} object and we don't want to make
 * this needlessly complicated.
 *
 * @param filter              process filter
 * @param tenantsProcessStore Current Tenant's process store
 * @return ProcessConf collection
 * @throws ProcessManagementException if an error occurred while processing query
 */
private Collection<ProcessConf> processQuery(ProcessFilter filter, TenantProcessStoreImpl tenantsProcessStore) throws ProcessManagementException {
    Map<QName, ProcessConfigurationImpl> processes = tenantsProcessStore.getProcessConfigMap();
    if (log.isDebugEnabled()) {
        for (Map.Entry<QName, ProcessConfigurationImpl> process : processes.entrySet()) {
            log.debug("Process " + process.getKey() + " in state " + process.getValue());
        }
    }
    Set<QName> pids = processes.keySet();
    // Name filter can be implemented using only the PIDs.
    if (filter != null && filter.getNameFilter() != null) {
        // adding escape sequences to [\^$.|?*+(){} characters
        String nameFilter = filter.getNameFilter().replace("\\", "\\\\").replace("]", "\\]").replace("[", "\\[").replace("^", "\\^").replace("$", "\\$").replace("|", "\\|").replace("?", "\\?").replace(".", "\\.").replace("+", "\\+").replace("(", "\\(").replace(")", "\\)").replace("{", "\\{").replace("}", "\\}").replace("*", ".*");
        final Pattern pattern = Pattern.compile(nameFilter + "(-\\d*)?");
        CollectionsX.remove_if(pids, new MemberOfFunction<QName>() {

            @Override
            public boolean isMember(QName o) {
                return !pattern.matcher(o.getLocalPart()).matches();
            }
        });
    }
    if (filter != null && filter.getNamespaceFilter() != null) {
        // adding escape sequences to [\^$.|?*+(){} characters
        String namespaceFilter = filter.getNamespaceFilter().replace("\\", "\\\\").replace("]", "\\]").replace("[", "\\[").replace("^", "\\^").replace("$", "\\$").replace("|", "\\|").replace("?", "\\?").replace(".", "\\.").replace("+", "\\+").replace("(", "\\(").replace(")", "\\)").replace("{", "\\{").replace("}", "\\}").replace("*", ".*");
        final Pattern pattern = Pattern.compile(namespaceFilter);
        CollectionsX.remove_if(pids, new MemberOfFunction<QName>() {

            @Override
            public boolean isMember(QName o) {
                String ns = o.getNamespaceURI() == null ? "" : o.getNamespaceURI();
                return !pattern.matcher(ns).matches();
            }
        });
    }
    // Now we need the process conf objects, we need to be
    // careful since someone could have deleted them by now
    List<ProcessConf> confs = new LinkedList<ProcessConf>();
    for (QName pid : pids) {
        ProcessConf pConf = tenantsProcessStore.getProcessConfiguration(pid);
        if (pConf != null) {
            confs.add(pConf);
        }
    }
    if (filter != null) {
        // Specific filter for deployment date.
        if (filter.getDeployedDateFilter() != null) {
            for (final String ddf : filter.getDeployedDateFilter()) {
                final Date dd;
                try {
                    dd = ISO8601DateParser.parse(Filter.getDateWithoutOp(ddf));
                } catch (ParseException e) {
                    // Should never happen.
                    String errMsg = "Exception while parsing date";
                    log.error(errMsg, e);
                    throw new ProcessManagementException(errMsg, e);
                }
                CollectionsX.remove_if(confs, new MemberOfFunction<ProcessConf>() {

                    @Override
                    public boolean isMember(ProcessConf o) {
                        if (ddf.startsWith("=")) {
                            return !o.getDeployDate().equals(dd);
                        }
                        if (ddf.startsWith("<=")) {
                            return o.getDeployDate().getTime() > dd.getTime();
                        }
                        if (ddf.startsWith(">=")) {
                            return o.getDeployDate().getTime() < dd.getTime();
                        }
                        if (ddf.startsWith("<")) {
                            return o.getDeployDate().getTime() >= dd.getTime();
                        }
                        return ddf.startsWith(">") && (o.getDeployDate().getTime() <= dd.getTime());
                    }
                });
            }
        }
        // Ordering
        if (filter.getOrders() != null) {
            ComparatorChain cChain = new ComparatorChain();
            for (String key : filter.getOrders()) {
                boolean ascending = true;
                String orderKey = key;
                if (key.startsWith("+") || key.startsWith("-")) {
                    orderKey = key.substring(1, key.length());
                    if (key.startsWith("-")) {
                        ascending = false;
                    }
                }
                Comparator c;
                if ("name".equals(orderKey)) {
                    c = new Comparator<ProcessConf>() {

                        public int compare(ProcessConf o1, ProcessConf o2) {
                            return o1.getProcessId().getLocalPart().compareTo(o2.getProcessId().getLocalPart());
                        }
                    };
                } else if ("namespace".equals(orderKey)) {
                    c = new Comparator<ProcessConf>() {

                        public int compare(ProcessConf o1, ProcessConf o2) {
                            String ns1 = o1.getProcessId().getNamespaceURI() == null ? "" : o1.getProcessId().getNamespaceURI();
                            String ns2 = o2.getProcessId().getNamespaceURI() == null ? "" : o2.getProcessId().getNamespaceURI();
                            return ns1.compareTo(ns2);
                        }
                    };
                } else if ("version".equals(orderKey)) {
                    c = new Comparator<ProcessConf>() {

                        public int compare(ProcessConf o1, ProcessConf o2) {
                            return (int) (o1.getVersion() - o2.getVersion());
                        }
                    };
                } else if ("deployed".equals(orderKey)) {
                    c = new Comparator<ProcessConf>() {

                        public int compare(ProcessConf o1, ProcessConf o2) {
                            return o1.getDeployDate().compareTo(o2.getDeployDate());
                        }
                    };
                } else if ("status".equals(orderKey)) {
                    c = new Comparator<ProcessConf>() {

                        public int compare(ProcessConf o1, ProcessConf o2) {
                            return o1.getState().compareTo(o2.getState());
                        }
                    };
                } else {
                    // unrecognized
                    if (log.isDebugEnabled()) {
                        log.debug("unrecognized order key" + orderKey);
                    }
                    continue;
                }
                cChain.addComparator(c, !ascending);
            }
            Collections.sort(confs, cChain);
        }
    }
    return confs;
}
Also used : Pattern(java.util.regex.Pattern) ComparatorChain(org.apache.commons.collections.comparators.ComparatorChain) QName(javax.xml.namespace.QName) ProcessConf(org.apache.ode.bpel.iapi.ProcessConf) ProcessConfigurationImpl(org.wso2.carbon.bpel.core.ode.integration.store.ProcessConfigurationImpl) LinkedList(java.util.LinkedList) Date(java.util.Date) ProcessManagementException(org.wso2.carbon.bpel.skeleton.ode.integration.mgt.services.ProcessManagementException) Comparator(java.util.Comparator) ParseException(java.text.ParseException) Map(java.util.Map)

Example 47 with Database

use of org.wso2.carbon.humantask.core.db.Database in project carbon-business-process by wso2.

the class Database method createActivitiMetaDataTable.

/**
 * during the start up of the server this method will create BPS_BPMN_DEPLOYMENT_METADATA table
 * if it doesn't exist in the activiti database.
 *
 * @throws org.wso2.carbon.bpmn.core.exception.BPMNMetaDataTableCreationException
 */
private void createActivitiMetaDataTable() throws BPMNMetaDataTableCreationException {
    BPMNDatabaseCreator bpmnDatabaseCreator = new BPMNDatabaseCreator(getDataSource());
    String bpmnDeploymentMetaDataQuery = "SELECT * FROM " + BPMNConstants.BPS_BPMN_DEPLOYMENT_METADATA_TABLE;
    if (!bpmnDatabaseCreator.isDatabaseStructureCreated(bpmnDeploymentMetaDataQuery)) {
        try {
            bpmnDatabaseCreator.createRegistryDatabase();
        } catch (Exception e) {
            String errMsg = "Error creating BPS_BPMN_DEPLOYMENT_METADATA table";
            throw new BPMNMetaDataTableCreationException(errMsg, e);
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("BPS_BPMN_DEPLOYMENT_METADATA table already exists. Using the old table.");
        }
    }
}
Also used : BPMNMetaDataTableCreationException(org.wso2.carbon.bpmn.core.exception.BPMNMetaDataTableCreationException) BPMNDatabaseCreator(org.wso2.carbon.bpmn.core.utils.BPMNDatabaseCreator) BPMNMetaDataTableCreationException(org.wso2.carbon.bpmn.core.exception.BPMNMetaDataTableCreationException) DatabaseConfigurationException(org.wso2.carbon.bpmn.core.exception.DatabaseConfigurationException) NamingException(javax.naming.NamingException)

Example 48 with Database

use of org.wso2.carbon.humantask.core.db.Database in project carbon-business-process by wso2.

the class TenantRepository method fixDeployments.

/**
 * Information about BPMN deployments are recorded in 3 places:
 * Activiti database, Registry and the file system (deployment folder).
 * If information about a particular deployment is not recorded in all these 3 places, BPS may not work correctly.
 * Therefore, this method checks whether deployments are recorded in all these places and undeploys packages, if
 * they are missing in few places in an inconsistent way.
 * <p/>
 * As there are 3 places, there are 8 ways a package can be placed. These cases are handled as follows:
 * (1) Whenever a package is not in the deployment folder, it is undeploye (this covers 4 combinations).
 * (2) If a package is in all 3 places, it is a proper deployment and it is left untouched.
 * (3) If a package is only in the deployment folder, it is a new deployment. This will be handled by the deployer.
 * (4) If a package is in the deployment folder AND it is in either registry or Activiti DB (but not both), then it is an inconsistent deployment. This will be undeployed.
 */
// public void fixDeployments() {
// 
// // get all deployments in the deployment folder
// List<String> fileArchiveNames = new ArrayList<String>();
// File[] fileDeployments = repoFolder.listFiles();
// if (fileDeployments != null) {
// for (File fileDeployment : fileDeployments) {
// String deploymentName = FilenameUtils.getBaseName(fileDeployment.getName());
// fileArchiveNames.add(deploymentName);
// }
// } else {
// log.error("File deployments returned null for tenant" + tenantId);
// }
// 
// 
// // get all deployments in the Activiti DB
// List<String> activitiDeploymentNames = new ArrayList<String>();
// ProcessEngine engine = BPMNServerHolder.getInstance().getEngine();
// RepositoryService repositoryService = engine.getRepositoryService();
// List<Deployment> tenantDeployments =
// repositoryService.createDeploymentQuery().deploymentTenantId(tenantId.toString())
// .list();
// for (Deployment deployment : tenantDeployments) {
// String deploymentName = deployment.getName();
// activitiDeploymentNames.add(deploymentName);
// }
// 
// // get all deployments in the registry
// List<String> metaDataDeploymentNames = new ArrayList<String>();
// List<DeploymentMetaDataModel> deploymentMetaDataModelList =
// activitiDAO.selectAllDeploymentModel();
// 
// int deploymentMetaDataModelListSize = deploymentMetaDataModelList.size();
// 
// for (int i = 0; i < deploymentMetaDataModelListSize; i++) {
// DeploymentMetaDataModel deploymentMetaDataModel =
// deploymentMetaDataModelList.get(i);
// 
// if (deploymentMetaDataModel != null) {
// String deploymentMetadataName = deploymentMetaDataModel.getPackageName();
// metaDataDeploymentNames.add(deploymentMetadataName);
// }
// }
// 
// // construct the union of all deployments
// Set<String> allDeploymentNames = new HashSet<String>();
// allDeploymentNames.addAll(fileArchiveNames);
// allDeploymentNames.addAll(activitiDeploymentNames);
// allDeploymentNames.addAll(metaDataDeploymentNames);
// 
// for (String deploymentName : allDeploymentNames) {
// 
// if (!(fileArchiveNames.contains(deploymentName))) {
// if (log.isDebugEnabled()) {
// log.debug(deploymentName +
// " has been removed from the deployment folder. Undeploying the package...");
// }
// undeploy(deploymentName, true);
// } else {
// if (activitiDeploymentNames.contains(deploymentName) &&
// !metaDataDeploymentNames.contains(deploymentName)) {
// if (log.isDebugEnabled()) {
// log.debug(deploymentName +
// " is missing in the registry. Undeploying the package to avoid inconsistencies...");
// }
// undeploy(deploymentName, true);
// }
// 
// if (!activitiDeploymentNames.contains(deploymentName) &&
// metaDataDeploymentNames.contains(deploymentName)) {
// if (log.isDebugEnabled()) {
// log.debug(deploymentName +
// " is missing in the BPS database. Undeploying the package to avoid inconsistencies...");
// }
// undeploy(deploymentName, true);
// }
// }
// }
// }
public void fixDeployments() throws BPSFault {
    // get all deployments in the deployment folder
    List<String> fileArchiveNames = new ArrayList<String>();
    File[] fileDeployments = repoFolder.listFiles();
    for (File fileDeployment : fileDeployments) {
        String deploymentName = FilenameUtils.getBaseName(fileDeployment.getName());
        fileArchiveNames.add(deploymentName);
    }
    // get all deployments in the Activiti DB
    List<String> activitiDeploymentNames = new ArrayList<String>();
    ProcessEngine engine = BPMNServerHolder.getInstance().getEngine();
    RepositoryService repositoryService = engine.getRepositoryService();
    List<Deployment> tenantDeployments = repositoryService.createDeploymentQuery().deploymentTenantId(tenantId.toString()).list();
    for (Deployment deployment : tenantDeployments) {
        String deploymentName = deployment.getName();
        activitiDeploymentNames.add(deploymentName);
    }
    // get all deployments in the registry
    List<String> registryDeploymentNames = new ArrayList<String>();
    try {
        RegistryService registryService = BPMNServerHolder.getInstance().getRegistryService();
        Registry tenantRegistry = registryService.getConfigSystemRegistry(tenantId);
        String deploymentRegistryPath = BPMNConstants.BPMN_REGISTRY_PATH;
        if (tenantRegistry.resourceExists(deploymentRegistryPath)) {
            Collection registryDeployments = (Collection) tenantRegistry.get(deploymentRegistryPath);
            String[] deploymentPaths = registryDeployments.getChildren();
            for (String deploymentPath : deploymentPaths) {
                String deploymentName = deploymentPath.substring(deploymentPath.lastIndexOf("/") + 1, deploymentPath.length());
                registryDeploymentNames.add(deploymentName);
            }
        }
    } catch (RegistryException e) {
        String msg = "Failed to obtain BPMN deployments from the Registry.";
        log.error(msg, e);
        throw new BPSFault(msg, e);
    }
    // construct the union of all deployments
    Set<String> allDeploymentNames = new HashSet<String>();
    allDeploymentNames.addAll(fileArchiveNames);
    allDeploymentNames.addAll(activitiDeploymentNames);
    allDeploymentNames.addAll(registryDeploymentNames);
    for (String deploymentName : allDeploymentNames) {
        try {
            if (!(fileArchiveNames.contains(deploymentName))) {
                if (log.isDebugEnabled()) {
                    log.debug(deploymentName + " has been removed from the deployment folder. Undeploying the package...");
                }
                undeploy(deploymentName, true);
            } else {
                if (activitiDeploymentNames.contains(deploymentName) && !registryDeploymentNames.contains(deploymentName)) {
                    if (log.isDebugEnabled()) {
                        log.debug(deploymentName + " is missing in the registry. Undeploying the package to avoid inconsistencies...");
                    }
                    undeploy(deploymentName, true);
                }
                if (!activitiDeploymentNames.contains(deploymentName) && registryDeploymentNames.contains(deploymentName)) {
                    if (log.isDebugEnabled()) {
                        log.debug(deploymentName + " is missing in the BPS database. Undeploying the package to avoid inconsistencies...");
                    }
                    undeploy(deploymentName, true);
                }
            }
        } catch (BPSFault e) {
            String msg = "Failed undeploy inconsistent deployment: " + deploymentName;
            log.error(msg, e);
            throw new BPSFault(msg, e);
        }
    }
}
Also used : ArrayList(java.util.ArrayList) Deployment(org.activiti.engine.repository.Deployment) Registry(org.wso2.carbon.registry.api.Registry) RegistryException(org.wso2.carbon.registry.api.RegistryException) BPSFault(org.wso2.carbon.bpmn.core.BPSFault) Collection(org.wso2.carbon.registry.api.Collection) RegistryService(org.wso2.carbon.registry.api.RegistryService) File(java.io.File) ProcessEngine(org.activiti.engine.ProcessEngine) RepositoryService(org.activiti.engine.RepositoryService) HashSet(java.util.HashSet)

Example 49 with Database

use of org.wso2.carbon.humantask.core.db.Database in project carbon-business-process by wso2.

the class InstanceManagementServiceSkeleton method getPaginatedInstanceList.

/**
 * Get paginated instance list
 *
 * @param filter Instance tFilter
 * @param order  The field on which to be ordered
 * @param limit  The maximum number of instances to be fetched
 * @param page   The page number
 * @return Instances that are filtered through "tFilter", ordered by "order" that fits into
 * 'page'th page
 * @throws InstanceManagementException When an error occurs
 */
public PaginatedInstanceList getPaginatedInstanceList(String filter, final String order, final int limit, final int page) throws InstanceManagementException {
    String tFilter = filter;
    final PaginatedInstanceList instanceList = new PaginatedInstanceList();
    Integer tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    TenantProcessStoreImpl tenantProcessStore = (TenantProcessStoreImpl) bpelServer.getMultiTenantProcessStore().getTenantsProcessStore(tenantId);
    if (tenantProcessStore.getProcessConfigMap().size() <= 0) {
        instanceList.setPages(0);
        return instanceList;
    }
    if (!tFilter.contains(" pid=")) {
        tFilter = tFilter + getTenantsProcessList(tenantProcessStore.getProcessConfigMap().keySet());
    }
    if (log.isDebugEnabled()) {
        log.debug("Instance Filter:" + tFilter);
    }
    final InstanceFilter instanceFilter = new InstanceFilter(tFilter, order, limit);
    try {
        BpelDatabase bpelDb = bpelServer.getODEBPELServer().getBpelDb();
        bpelDb.exec(new BpelDatabase.Callable<Object>() {

            public Object run(BpelDAOConnection conn) throws InstanceManagementException {
                Collection<ProcessInstanceDAO> instances = conn.instanceQuery(instanceFilter);
                int pageNum = page;
                if (pageNum < 0 || pageNum == Integer.MAX_VALUE) {
                    pageNum = 0;
                }
                int startIndexOfCurrentPage = pageNum * BPELConstants.ITEMS_PER_PAGE;
                int endIndexOfCurrentPage = (pageNum + 1) * BPELConstants.ITEMS_PER_PAGE;
                int instanceListSize = instances.size();
                int pages = (int) Math.ceil((double) instanceListSize / BPELConstants.ITEMS_PER_PAGE);
                instanceList.setPages(pages);
                ProcessInstanceDAO[] instanceArray = instances.toArray(new ProcessInstanceDAO[instanceListSize]);
                for (int i = startIndexOfCurrentPage; (i < endIndexOfCurrentPage && i < instanceListSize); i++) {
                    instanceList.addInstance(createLimitedInstanceInfoObject(instanceArray[i]));
                }
                return null;
            }
        });
    } catch (Exception e) {
        String errMsg = "Error querying instances from database. Instance Filter:" + instanceFilter.toString();
        log.error(errMsg, e);
        throw new InstanceManagementException(errMsg, e);
    }
    return instanceList;
}
Also used : InstanceFilter(org.apache.ode.bpel.common.InstanceFilter) BpelDatabase(org.apache.ode.bpel.engine.BpelDatabase) BpelDAOConnection(org.apache.ode.bpel.dao.BpelDAOConnection) TenantProcessStoreImpl(org.wso2.carbon.bpel.core.ode.integration.store.TenantProcessStoreImpl) ProcessNotFoundException(org.apache.ode.bpel.pmapi.ProcessNotFoundException) InstanceManagementException(org.wso2.carbon.bpel.skeleton.ode.integration.mgt.services.InstanceManagementException) ProcessingException(org.apache.ode.bpel.pmapi.ProcessingException) PaginatedInstanceList(org.wso2.carbon.bpel.skeleton.ode.integration.mgt.services.types.PaginatedInstanceList) InstanceManagementException(org.wso2.carbon.bpel.skeleton.ode.integration.mgt.services.InstanceManagementException) ProcessInstanceDAO(org.apache.ode.bpel.dao.ProcessInstanceDAO) Collection(java.util.Collection)

Example 50 with Database

use of org.wso2.carbon.humantask.core.db.Database in project carbon-business-process by wso2.

the class InstanceManagementServiceSkeleton method getInstanceCountByState.

private Long getInstanceCountByState(String processList, String instanceState) throws InstanceManagementException {
    if (isProcessListEmpty(processList)) {
        return (long) 0;
    }
    final List<Long> instanceCountList = new ArrayList<Long>();
    StringBuilder filter = new StringBuilder();
    if (!isProcessListEmpty(processList)) {
        filter.append(processList);
    }
    filter.append("status=");
    filter.append(instanceState);
    final InstanceFilter instanceFilter = new InstanceFilter(filter.toString(), null, Integer.MAX_VALUE);
    try {
        BpelDatabase bpelDb = bpelServer.getODEBPELServer().getBpelDb();
        bpelDb.exec(new BpelDatabase.Callable<Object>() {

            public Object run(BpelDAOConnection conn) throws AxisFault {
                instanceCountList.add(conn.instanceCount(instanceFilter));
                return null;
            }
        });
    } catch (Exception e) {
        String errMsg = "Error querying instances from database. Filter: " + instanceFilter.toString();
        log.error(errMsg, e);
        throw new InstanceManagementException(errMsg, e);
    }
    return instanceCountList.get(0);
}
Also used : AxisFault(org.apache.axis2.AxisFault) InstanceFilter(org.apache.ode.bpel.common.InstanceFilter) BpelDatabase(org.apache.ode.bpel.engine.BpelDatabase) ArrayList(java.util.ArrayList) BpelDAOConnection(org.apache.ode.bpel.dao.BpelDAOConnection) ProcessNotFoundException(org.apache.ode.bpel.pmapi.ProcessNotFoundException) InstanceManagementException(org.wso2.carbon.bpel.skeleton.ode.integration.mgt.services.InstanceManagementException) ProcessingException(org.apache.ode.bpel.pmapi.ProcessingException) InstanceManagementException(org.wso2.carbon.bpel.skeleton.ode.integration.mgt.services.InstanceManagementException)

Aggregations

SQLException (java.sql.SQLException)29 PreparedStatement (java.sql.PreparedStatement)28 Connection (java.sql.Connection)24 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)23 ResultSet (java.sql.ResultSet)16 ArrayList (java.util.ArrayList)13 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)12 Map (java.util.Map)6 DeviceMgtPluginException (org.wso2.iot.sampledevice.plugin.exception.DeviceMgtPluginException)6 HashMap (java.util.HashMap)5 BpelDatabase (org.apache.ode.bpel.engine.BpelDatabase)5 File (java.io.File)4 InstanceFilter (org.apache.ode.bpel.common.InstanceFilter)4 BpelDAOConnection (org.apache.ode.bpel.dao.BpelDAOConnection)4 InstanceManagementException (org.wso2.carbon.bpel.skeleton.ode.integration.mgt.services.InstanceManagementException)4 Device (org.wso2.carbon.device.mgt.common.Device)4 IOException (java.io.IOException)3 Collection (java.util.Collection)3 DataSource (javax.sql.DataSource)3 ProcessInstanceDAO (org.apache.ode.bpel.dao.ProcessInstanceDAO)3