Search in sources :

Example 1 with RuntimeEnvironmentBuilder

use of org.kie.api.runtime.manager.RuntimeEnvironmentBuilder in project jbpm by kiegroup.

the class ExecutionErrorHandlingRuntimeManagerTest method createEnvironment.

private RuntimeEnvironment createEnvironment() {
    ExecutionErrorStorage storage = new ExecutionErrorStorage() {

        private List<ExecutionError> errors = new ArrayList<>();

        @Override
        public ExecutionError store(ExecutionError error) {
            this.errors.add(error);
            return error;
        }

        @Override
        public List<ExecutionError> listByProcessInstance(Long processInstanceId, Integer page, Integer pageSize) {
            return errors;
        }

        @Override
        public List<ExecutionError> listByDeployment(String deploymentId, Integer page, Integer pageSize) {
            return errors;
        }

        @Override
        public List<ExecutionError> listByActivity(String activityName, Integer page, Integer pageSize) {
            return errors;
        }

        @Override
        public List<ExecutionError> list(Integer page, Integer pageSize) {
            return errors;
        }

        @Override
        public ExecutionError get(String errorId) {
            return errors.stream().filter(err -> err.getErrorId().equals(errorId)).findFirst().get();
        }

        @Override
        public void acknowledge(String user, String... errorIds) {
            for (String errorId : errorIds) {
                ExecutionError error = get(errorId);
                error.setAcknowledged(true);
                error.setAcknowledgedBy(user);
                error.setAcknowledgedAt(new Date());
            }
        }
    };
    RuntimeEnvironmentBuilder environmentBuilder = RuntimeEnvironmentBuilder.Factory.get().newDefaultBuilder().entityManagerFactory(emf).userGroupCallback(userGroupCallback).addAsset(ResourceFactory.newClassPathResource("BPMN2-BrokenScriptTask.bpmn2"), ResourceType.BPMN2).addAsset(ResourceFactory.newClassPathResource("BPMN2-UserTaskWithRollback.bpmn2"), ResourceType.BPMN2).addAsset(ResourceFactory.newClassPathResource("BPMN2-UserTaskCustomTask.bpmn2"), ResourceType.BPMN2);
    if (testName.getMethodName().contains("InMemoryStorage")) {
        environmentBuilder.addEnvironmentEntry("ExecutionErrorStorage", storage);
    }
    return environmentBuilder.get();
}
Also used : ExecutionError(org.kie.internal.runtime.error.ExecutionError) ExecutionErrorStorage(org.kie.internal.runtime.error.ExecutionErrorStorage) List(java.util.List) ArrayList(java.util.ArrayList) Date(java.util.Date) RuntimeEnvironmentBuilder(org.kie.api.runtime.manager.RuntimeEnvironmentBuilder)

Example 2 with RuntimeEnvironmentBuilder

use of org.kie.api.runtime.manager.RuntimeEnvironmentBuilder in project jbpm by kiegroup.

the class JBPMHelper method loadStatefulKnowledgeSession.

@Deprecated
public static StatefulKnowledgeSession loadStatefulKnowledgeSession(KieBase kbase, int sessionId) {
    Properties properties = getProperties();
    String persistenceEnabled = properties.getProperty("persistence.enabled", "false");
    RuntimeEnvironmentBuilder builder = null;
    if ("true".equals(persistenceEnabled)) {
        String dialect = properties.getProperty("persistence.persistenceunit.dialect", "org.hibernate.dialect.H2Dialect");
        Map<String, String> map = new HashMap<String, String>();
        map.put("hibernate.dialect", dialect);
        EntityManagerFactory emf = Persistence.createEntityManagerFactory(properties.getProperty("persistence.persistenceunit.name", "org.jbpm.persistence.jpa"), map);
        builder = RuntimeEnvironmentBuilder.Factory.get().newDefaultBuilder().entityManagerFactory(emf).addEnvironmentEntry(EnvironmentName.TRANSACTION_MANAGER, com.arjuna.ats.jta.TransactionManager.transactionManager());
    } else {
        builder = RuntimeEnvironmentBuilder.Factory.get().newDefaultInMemoryBuilder();
    }
    builder.knowledgeBase(kbase);
    RuntimeManager manager = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(builder.get());
    return (StatefulKnowledgeSession) manager.getRuntimeEngine(EmptyContext.get()).getKieSession();
}
Also used : HashMap(java.util.HashMap) EntityManagerFactory(javax.persistence.EntityManagerFactory) StatefulKnowledgeSession(org.kie.internal.runtime.StatefulKnowledgeSession) RuntimeManager(org.kie.api.runtime.manager.RuntimeManager) Properties(java.util.Properties) RuntimeEnvironmentBuilder(org.kie.api.runtime.manager.RuntimeEnvironmentBuilder)

Example 3 with RuntimeEnvironmentBuilder

use of org.kie.api.runtime.manager.RuntimeEnvironmentBuilder in project jbpm by kiegroup.

the class JbpmJUnitBaseTestCase method createRuntimeManager.

/**
 * Creates default configuration of <code>RuntimeManager</code> with given <code>strategy</code> and all
 * <code>resources</code> being added to knowledge base.
 * <br/>
 * There should be only one <code>RuntimeManager</code> created during single test.
 * @param strategy - selected strategy of those that are supported
 * @param resources - resources that shall be added to knowledge base
 * @param identifier - identifies the runtime manager
 * @return new instance of RuntimeManager
 */
protected RuntimeManager createRuntimeManager(Strategy strategy, Map<String, ResourceType> resources, String identifier) {
    if (manager != null) {
        throw new IllegalStateException("There is already one RuntimeManager active");
    }
    RuntimeEnvironmentBuilder builder = null;
    if (!setupDataSource) {
        builder = RuntimeEnvironmentBuilder.Factory.get().newEmptyBuilder().addConfiguration("drools.processSignalManagerFactory", DefaultSignalManagerFactory.class.getName()).addConfiguration("drools.processInstanceManagerFactory", DefaultProcessInstanceManagerFactory.class.getName()).registerableItemsFactory(new SimpleRegisterableItemsFactory() {

            @Override
            public Map<String, WorkItemHandler> getWorkItemHandlers(RuntimeEngine runtime) {
                Map<String, WorkItemHandler> handlers = new HashMap<String, WorkItemHandler>();
                handlers.putAll(super.getWorkItemHandlers(runtime));
                handlers.putAll(customHandlers);
                return handlers;
            }

            @Override
            public List<ProcessEventListener> getProcessEventListeners(RuntimeEngine runtime) {
                List<ProcessEventListener> listeners = super.getProcessEventListeners(runtime);
                listeners.addAll(customProcessListeners);
                return listeners;
            }

            @Override
            public List<AgendaEventListener> getAgendaEventListeners(RuntimeEngine runtime) {
                List<AgendaEventListener> listeners = super.getAgendaEventListeners(runtime);
                listeners.addAll(customAgendaListeners);
                return listeners;
            }

            @Override
            public List<TaskLifeCycleEventListener> getTaskListeners() {
                List<TaskLifeCycleEventListener> listeners = super.getTaskListeners();
                listeners.addAll(customTaskListeners);
                return listeners;
            }
        });
    } else if (sessionPersistence) {
        builder = RuntimeEnvironmentBuilder.Factory.get().newDefaultBuilder().entityManagerFactory(emf).registerableItemsFactory(new DefaultRegisterableItemsFactory() {

            @Override
            public Map<String, WorkItemHandler> getWorkItemHandlers(RuntimeEngine runtime) {
                Map<String, WorkItemHandler> handlers = new HashMap<String, WorkItemHandler>();
                handlers.putAll(super.getWorkItemHandlers(runtime));
                handlers.putAll(customHandlers);
                return handlers;
            }

            @Override
            public List<ProcessEventListener> getProcessEventListeners(RuntimeEngine runtime) {
                List<ProcessEventListener> listeners = super.getProcessEventListeners(runtime);
                listeners.addAll(customProcessListeners);
                return listeners;
            }

            @Override
            public List<AgendaEventListener> getAgendaEventListeners(RuntimeEngine runtime) {
                List<AgendaEventListener> listeners = super.getAgendaEventListeners(runtime);
                listeners.addAll(customAgendaListeners);
                return listeners;
            }

            @Override
            public List<TaskLifeCycleEventListener> getTaskListeners() {
                List<TaskLifeCycleEventListener> listeners = super.getTaskListeners();
                listeners.addAll(customTaskListeners);
                return listeners;
            }
        });
    } else {
        builder = RuntimeEnvironmentBuilder.Factory.get().newDefaultInMemoryBuilder().entityManagerFactory(emf).registerableItemsFactory(new DefaultRegisterableItemsFactory() {

            @Override
            public Map<String, WorkItemHandler> getWorkItemHandlers(RuntimeEngine runtime) {
                Map<String, WorkItemHandler> handlers = new HashMap<String, WorkItemHandler>();
                handlers.putAll(super.getWorkItemHandlers(runtime));
                handlers.putAll(customHandlers);
                return handlers;
            }

            @Override
            public List<ProcessEventListener> getProcessEventListeners(RuntimeEngine runtime) {
                List<ProcessEventListener> listeners = super.getProcessEventListeners(runtime);
                listeners.addAll(customProcessListeners);
                return listeners;
            }

            @Override
            public List<AgendaEventListener> getAgendaEventListeners(RuntimeEngine runtime) {
                List<AgendaEventListener> listeners = super.getAgendaEventListeners(runtime);
                listeners.addAll(customAgendaListeners);
                return listeners;
            }

            @Override
            public List<TaskLifeCycleEventListener> getTaskListeners() {
                List<TaskLifeCycleEventListener> listeners = super.getTaskListeners();
                listeners.addAll(customTaskListeners);
                return listeners;
            }
        });
    }
    builder.userGroupCallback(userGroupCallback);
    for (Entry<String, Object> envEntry : customEnvironmentEntries.entrySet()) {
        builder.addEnvironmentEntry(envEntry.getKey(), envEntry.getValue());
    }
    for (Map.Entry<String, ResourceType> entry : resources.entrySet()) {
        builder.addAsset(ResourceFactory.newClassPathResource(entry.getKey()), entry.getValue());
    }
    return createRuntimeManager(strategy, resources, builder.get(), identifier);
}
Also used : RuntimeEngine(org.kie.api.runtime.manager.RuntimeEngine) DefaultRegisterableItemsFactory(org.jbpm.runtime.manager.impl.DefaultRegisterableItemsFactory) HashMap(java.util.HashMap) ProcessEventListener(org.kie.api.event.process.ProcessEventListener) ResourceType(org.kie.api.io.ResourceType) DefaultProcessInstanceManagerFactory(org.jbpm.process.instance.impl.DefaultProcessInstanceManagerFactory) RuntimeEnvironmentBuilder(org.kie.api.runtime.manager.RuntimeEnvironmentBuilder) WorkItemHandler(org.kie.api.runtime.process.WorkItemHandler) AgendaEventListener(org.kie.api.event.rule.AgendaEventListener) SimpleRegisterableItemsFactory(org.jbpm.runtime.manager.impl.SimpleRegisterableItemsFactory) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) HashMap(java.util.HashMap) TaskLifeCycleEventListener(org.kie.api.task.TaskLifeCycleEventListener)

Example 4 with RuntimeEnvironmentBuilder

use of org.kie.api.runtime.manager.RuntimeEnvironmentBuilder in project jbpm by kiegroup.

the class ProcessKModuleMain method createRuntimeManager.

private static RuntimeManager createRuntimeManager() {
    cleanupSingletonSessionId();
    JBPMHelper.startH2Server();
    JBPMHelper.setupDataSource();
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("org.jbpm.persistence.jpa");
    RuntimeEnvironmentBuilder builder = RuntimeEnvironmentBuilder.Factory.get().newClasspathKmoduleDefaultBuilder().entityManagerFactory(emf).userGroupCallback(new JBossUserGroupCallbackImpl("classpath:/usergroups.properties"));
    return RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(builder.get(), "com.sample:example:1.0");
}
Also used : JBossUserGroupCallbackImpl(org.jbpm.services.task.identity.JBossUserGroupCallbackImpl) EntityManagerFactory(javax.persistence.EntityManagerFactory) RuntimeEnvironmentBuilder(org.kie.api.runtime.manager.RuntimeEnvironmentBuilder)

Example 5 with RuntimeEnvironmentBuilder

use of org.kie.api.runtime.manager.RuntimeEnvironmentBuilder in project jbpm by kiegroup.

the class KModuleDeploymentService method boostrapRuntimeEnvironmentBuilder.

/**
 * This creates and fills a {@link RuntimeEnvironmentBuilder} instance, which is later used when creating services.
 * </p>
 * A lot of the logic here is used to process the information in the {@link DeploymentDescriptor} instance, which is
 * part of the {@link DeploymentUnit}.
 *
 * @param deploymentUnit The {@link KModuleDeploymentUnit}, which is filled by the method
 * @param deployedUnit The {@link DeployedUnit}, which is also filled by the method
 * @param kieContainer The {@link KieContainer}, which contains information needed to fill the above two arguments
 * @param mode The {@link MergeMode} used to resolve conflicts in the {@link DeploymentDescriptor}.
 * @return A {@link RuntimeEnvironmentBuilder} instance ready for use
 */
protected RuntimeEnvironmentBuilder boostrapRuntimeEnvironmentBuilder(KModuleDeploymentUnit deploymentUnit, DeployedUnit deployedUnit, KieContainer kieContainer, MergeMode mode) {
    DeploymentDescriptor descriptor = deploymentUnit.getDeploymentDescriptor();
    if (descriptor == null || ((DeploymentDescriptorImpl) descriptor).isEmpty()) {
        // skip empty descriptors as its default can override settings
        DeploymentDescriptorManager descriptorManager = new DeploymentDescriptorManager("org.jbpm.domain");
        List<DeploymentDescriptor> descriptorHierarchy = descriptorManager.getDeploymentDescriptorHierarchy(kieContainer);
        descriptor = merger.merge(descriptorHierarchy, mode);
        deploymentUnit.setDeploymentDescriptor(descriptor);
    } else if (descriptor != null && !deploymentUnit.isDeployed()) {
        DeploymentDescriptorManager descriptorManager = new DeploymentDescriptorManager("org.jbpm.domain");
        List<DeploymentDescriptor> descriptorHierarchy = descriptorManager.getDeploymentDescriptorHierarchy(kieContainer);
        descriptorHierarchy.add(0, descriptor);
        descriptor = merger.merge(descriptorHierarchy, mode);
        deploymentUnit.setDeploymentDescriptor(descriptor);
    }
    // first set on unit the strategy
    deploymentUnit.setStrategy(descriptor.getRuntimeStrategy());
    // setting up runtime environment via builder
    RuntimeEnvironmentBuilder builder = null;
    if (descriptor.getPersistenceMode() == PersistenceMode.NONE) {
        builder = RuntimeEnvironmentBuilder.Factory.get().newDefaultInMemoryBuilder();
    } else {
        builder = RuntimeEnvironmentBuilder.Factory.get().newDefaultBuilder();
    }
    // populate various properties of the builder
    EntityManagerFactory emf = EntityManagerFactoryManager.get().getOrCreate(descriptor.getPersistenceUnit());
    builder.entityManagerFactory(emf);
    Map<String, Object> contaxtParams = new HashMap<String, Object>();
    contaxtParams.put("entityManagerFactory", emf);
    contaxtParams.put("classLoader", kieContainer.getClassLoader());
    // process object models that are globally configured (environment entries, session configuration)
    for (NamedObjectModel model : descriptor.getEnvironmentEntries()) {
        Object entry = getInstanceFromModel(model, kieContainer, contaxtParams);
        builder.addEnvironmentEntry(model.getName(), entry);
    }
    for (NamedObjectModel model : descriptor.getConfiguration()) {
        Object entry = getInstanceFromModel(model, kieContainer, contaxtParams);
        builder.addConfiguration(model.getName(), (String) entry);
    }
    ObjectMarshallingStrategy[] mStrategies = new ObjectMarshallingStrategy[descriptor.getMarshallingStrategies().size() + 1];
    int index = 0;
    for (ObjectModel model : descriptor.getMarshallingStrategies()) {
        Object strategy = getInstanceFromModel(model, kieContainer, contaxtParams);
        mStrategies[index] = (ObjectMarshallingStrategy) strategy;
        index++;
    }
    // lastly add the main default strategy
    mStrategies[index] = new SerializablePlaceholderResolverStrategy(ClassObjectMarshallingStrategyAcceptor.DEFAULT);
    builder.addEnvironmentEntry(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES, mStrategies);
    builder.addEnvironmentEntry("KieDeploymentDescriptor", descriptor);
    builder.addEnvironmentEntry("KieContainer", kieContainer);
    if (executorService != null) {
        builder.addEnvironmentEntry("ExecutorService", executorService);
    }
    if (identityProvider != null) {
        builder.addEnvironmentEntry(EnvironmentName.IDENTITY_PROVIDER, identityProvider);
    }
    // populate all assets with roles for this deployment unit
    List<String> requiredRoles = descriptor.getRequiredRoles(DeploymentDescriptor.TYPE_VIEW);
    if (requiredRoles != null && !requiredRoles.isEmpty()) {
        for (DeployedAsset desc : deployedUnit.getDeployedAssets()) {
            if (desc instanceof ProcessAssetDesc) {
                ((ProcessAssetDesc) desc).setRoles(requiredRoles);
            }
        }
    }
    // Classes 3: classes added from descriptor
    List<String> remoteableClasses = descriptor.getClasses();
    if (remoteableClasses != null && !remoteableClasses.isEmpty()) {
        for (String className : remoteableClasses) {
            Class descriptorClass = null;
            try {
                descriptorClass = kieContainer.getClassLoader().loadClass(className);
                logger.debug("Loaded {} into the classpath from deployment descriptor {}", className, kieContainer.getReleaseId().toExternalForm());
            } catch (ClassNotFoundException cnfe) {
                throw new IllegalArgumentException("Class " + className + " not found in the project");
            } catch (NoClassDefFoundError e) {
                throw new IllegalArgumentException("Class " + className + " not found in the project");
            }
            addClassToDeployedUnit(descriptorClass, (DeployedUnitImpl) deployedUnit);
        }
    }
    return builder;
}
Also used : SerializablePlaceholderResolverStrategy(org.drools.core.marshalling.impl.SerializablePlaceholderResolverStrategy) ObjectModel(org.kie.internal.runtime.conf.ObjectModel) NamedObjectModel(org.kie.internal.runtime.conf.NamedObjectModel) HashMap(java.util.HashMap) ObjectMarshallingStrategy(org.kie.api.marshalling.ObjectMarshallingStrategy) DeployedAsset(org.jbpm.services.api.model.DeployedAsset) DeploymentDescriptor(org.kie.internal.runtime.conf.DeploymentDescriptor) DeploymentDescriptorManager(org.jbpm.runtime.manager.impl.deploy.DeploymentDescriptorManager) RuntimeEnvironmentBuilder(org.kie.api.runtime.manager.RuntimeEnvironmentBuilder) NamedObjectModel(org.kie.internal.runtime.conf.NamedObjectModel) ProcessAssetDesc(org.jbpm.kie.services.impl.model.ProcessAssetDesc) EntityManagerFactory(javax.persistence.EntityManagerFactory) List(java.util.List)

Aggregations

RuntimeEnvironmentBuilder (org.kie.api.runtime.manager.RuntimeEnvironmentBuilder)10 HashMap (java.util.HashMap)5 RuntimeManager (org.kie.api.runtime.manager.RuntimeManager)4 ArrayList (java.util.ArrayList)3 List (java.util.List)3 EntityManagerFactory (javax.persistence.EntityManagerFactory)3 ServicesAwareAuditEventBuilder (org.jbpm.kie.services.impl.audit.ServicesAwareAuditEventBuilder)3 AbstractKieServicesBaseTest (org.jbpm.kie.test.util.AbstractKieServicesBaseTest)3 AbstractAuditLogger (org.jbpm.process.audit.AbstractAuditLogger)3 Test (org.junit.Test)3 RuntimeEngine (org.kie.api.runtime.manager.RuntimeEngine)3 Map (java.util.Map)2 JBossUserGroupCallbackImpl (org.jbpm.services.task.identity.JBossUserGroupCallbackImpl)2 ResourceType (org.kie.api.io.ResourceType)2 KieSession (org.kie.api.runtime.KieSession)2 ProcessInstance (org.kie.api.runtime.process.ProcessInstance)2 Date (java.util.Date)1 Properties (java.util.Properties)1 DependencyFilter (org.appformer.maven.support.DependencyFilter)1 InternalKieModule (org.drools.compiler.kie.builder.impl.InternalKieModule)1