org.kie.api.runtime.process.WorkItemHandler Java Examples

The following examples show how to use org.kie.api.runtime.process.WorkItemHandler. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CustomWorkItemHandlerTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testRegisterHandlerWithKsessionUsingConfiguration() {
    KieBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    Properties props = new Properties();
    props.setProperty("drools.workItemHandlers", "CustomWorkItemHandlers.conf");
    KieSessionConfiguration config = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(props);
    
    KieSession ksession = kbase.newKieSession(config, EnvironmentFactory.newEnvironment());
    assertNotNull(ksession);
    // this test would fail on creation of the work item manager if injecting session is not supported
    WorkItemManager manager = ksession.getWorkItemManager();
    assertNotNull(manager);
    
    Map<String, WorkItemHandler> handlers = ((SessionConfiguration)config).getWorkItemHandlers();
    assertNotNull(handlers);
    assertEquals(1, handlers.size());
    assertTrue(handlers.containsKey("Custom"));
}
 
Example #2
Source File: SessionConfigurationImpl.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private void initWorkItemHandlers(Map<String, Object> params) {
    this.workItemHandlers = new HashMap<String, WorkItemHandler>();

    // split on each space
    String locations[] = this.chainedProperties.getProperty( "drools.workItemHandlers", "" ).split( "\\s" );

    // load each SemanticModule
    for ( String factoryLocation : locations ) {
        // trim leading/trailing spaces and quotes
        factoryLocation = factoryLocation.trim();
        if ( factoryLocation.startsWith( "\"" ) ) {
            factoryLocation = factoryLocation.substring( 1 );
        }
        if ( factoryLocation.endsWith( "\"" ) ) {
            factoryLocation = factoryLocation.substring( 0,
                                                         factoryLocation.length() - 1 );
        }
        if ( !factoryLocation.equals( "" ) ) {
            loadWorkItemHandlers( factoryLocation, params );
        }
    }
}
 
Example #3
Source File: LightWorkItemManager.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public void internalAbortWorkItem(String id) {
    WorkItemImpl workItem = (WorkItemImpl) workItems.get(id);
    // work item may have been aborted
    if (workItem != null) {
        workItem.setCompleteDate(new Date());
        WorkItemHandler handler = this.workItemHandlers.get(workItem.getName());
        if (handler != null) {
            
            ProcessInstance processInstance = processInstanceManager.getProcessInstance(workItem.getProcessInstanceId());
            Transition<?> transition = new TransitionToAbort(Collections.emptyList());
            eventSupport.fireBeforeWorkItemTransition(processInstance, workItem, transition, null);
            
            handler.abortWorkItem(workItem, this);
            workItem.setPhaseId(ID);
            workItem.setPhaseStatus(STATUS);
            eventSupport.fireAfterWorkItemTransition(processInstance, workItem, transition, null);
        } else {
            workItems.remove( workItem.getId() );
            throw new WorkItemHandlerNotFoundException(workItem.getName() );
        }
        workItems.remove(workItem.getId());
    }
}
 
Example #4
Source File: OneProcessPerThreadTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
   public void testMultiThreadProcessInstanceWorkItem() throws Exception {
   	final ConcurrentHashMap<String, Long> workItems = new ConcurrentHashMap<String, Long>();
   	
       try {
           final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
           kbuilder.add(ResourceFactory.newClassPathResource("BPMN2-MultiThreadServiceProcess.bpmn"), ResourceType.BPMN2 );
           KieBase kbase = kbuilder.newKieBase();
           
           KieSession ksession = createStatefulKnowledgeSession(kbase);
           
           ksession.getWorkItemManager().registerWorkItemHandler("Log", new WorkItemHandler() {
			public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
				Long threadId = (Long) workItem.getParameter("id");
				workItems.put(workItem.getProcessInstanceId(), threadId);
			}
			public void abortWorkItem(WorkItem arg0, WorkItemManager arg1) {
			}
           });

           startThreads(ksession);
           
           assertEquals(THREAD_COUNT, workItems.size());
       } catch ( Throwable t ) {
           t.printStackTrace();
           fail( "Should not raise any exception: " + t.getMessage() );
       }
       
       int i = 0;
       while(started.get() > done.get() ) { 
           logger.info("{} > {}", started, done );
           Thread.sleep(10*1000);
           if( ++i > 10 ) { 
               fail("Not all threads completed.");
           }
       }
}
 
Example #5
Source File: SessionConfigurationImpl.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void loadWorkItemHandlers(String location, Map<String, Object> params) {
    String content = ConfFileUtils.URLContentsToString( ConfFileUtils.getURL( location,
                                                                              null,
                                                                              RuleBaseConfiguration.class ) );
    Map<String, WorkItemHandler> workItemHandlers = (Map<String, WorkItemHandler>) MVELSafeHelper.getEvaluator().eval( content,
                                                                                              params );
    this.workItemHandlers.putAll( workItemHandlers );
}
 
Example #6
Source File: SessionConfigurationImpl.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public Map<String, WorkItemHandler> getWorkItemHandlers(Map<String, Object> params) {
    
    if ( this.workItemHandlers == null ) {
        initWorkItemHandlers(params);
    }
    return this.workItemHandlers;
}
 
Example #7
Source File: SessionConfigurationImpl.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public Map<String, WorkItemHandler> getWorkItemHandlers() {

        if ( this.workItemHandlers == null ) {
            initWorkItemHandlers(new HashMap<String, Object>());
        }
        return this.workItemHandlers;

    }
 
Example #8
Source File: StatefulKnowledgeSessionImpl.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public WorkItemManager getWorkItemManager() {
    if (workItemManager == null) {
        workItemManager = config.getWorkItemManagerFactory().createWorkItemManager(this.getKnowledgeRuntime());
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("ksession", this.getKnowledgeRuntime());
        Map<String, WorkItemHandler> workItemHandlers = config.getWorkItemHandlers(params);
        if (workItemHandlers != null) {
            for (Map.Entry<String, WorkItemHandler> entry : workItemHandlers.entrySet()) {
                workItemManager.registerWorkItemHandler(entry.getKey(),
                                                        entry.getValue());
            }
        }
    }
    return workItemManager;
}
 
Example #9
Source File: DefaultWorkItemManager.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public void dispose() {
    if (workItemHandlers != null) {
        for (Map.Entry<String, WorkItemHandler> handlerEntry : workItemHandlers.entrySet()) {
            if (handlerEntry.getValue() instanceof Closeable) {
                ((Closeable) handlerEntry.getValue()).close();
            }
        }
    }
}
 
Example #10
Source File: CachedWorkItemHandlerConfig.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public WorkItemHandler forName(String name) {
    WorkItemHandler workItemHandler = workItemHandlers.get(name);
    if (workItemHandler == null) {
        throw new NoSuchElementException(name);
    } else {
        return workItemHandler;
    }
}
 
Example #11
Source File: DefaultWorkItemManager.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private void retryWorkItem(WorkItem workItem) {
    if (workItem != null) {
        WorkItemHandler handler = this.workItemHandlers.get(workItem.getName());
        if (handler != null) {
            handler.executeWorkItem(workItem, this);
        } else throw new WorkItemHandlerNotFoundException(workItem.getName() );
    }
}
 
Example #12
Source File: DefaultWorkItemManager.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public void internalAbortWorkItem(String id) {
    WorkItemImpl workItem = (WorkItemImpl) workItems.get(id);
    // work item may have been aborted
    if (workItem != null) {
        WorkItemHandler handler = this.workItemHandlers.get(workItem.getName());
        if (handler != null) {
            handler.abortWorkItem(workItem, this);
        } else {
            workItems.remove( workItem.getId() );
            throw new WorkItemHandlerNotFoundException(workItem.getName() );
        }
        workItems.remove(workItem.getId());
    }
}
 
Example #13
Source File: DefaultWorkItemManager.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public void internalExecuteWorkItem(WorkItem workItem) {
    ((WorkItemImpl) workItem).setId(UUID.randomUUID().toString());
    internalAddWorkItem(workItem);
    WorkItemHandler handler = this.workItemHandlers.get(workItem.getName());
    if (handler != null) {
        handler.executeWorkItem(workItem, this);
    } else throw new WorkItemHandlerNotFoundException(workItem.getName() );
}
 
Example #14
Source File: LightWorkItemManager.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public void internalExecuteWorkItem(WorkItem workItem) {
    ((WorkItemImpl) workItem).setId(UUID.randomUUID().toString());
    internalAddWorkItem(workItem);
    WorkItemHandler handler = this.workItemHandlers.get(workItem.getName());
    if (handler != null) {
        ProcessInstance processInstance = processInstanceManager.getProcessInstance(workItem.getProcessInstanceId());
        Transition<?> transition = new TransitionToActive();
        eventSupport.fireBeforeWorkItemTransition(processInstance, workItem, transition, null);
        
        handler.executeWorkItem(workItem, this);
        
        eventSupport.fireAfterWorkItemTransition(processInstance, workItem, transition, null);
    } else throw new WorkItemHandlerNotFoundException(workItem.getName() );
}
 
Example #15
Source File: LightWorkItemManager.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private void retryWorkItem(WorkItem workItem) {
    if (workItem != null) {
        WorkItemHandler handler = this.workItemHandlers.get(workItem.getName());
        if (handler != null) {
            handler.executeWorkItem(workItem, this);
        } else throw new WorkItemHandlerNotFoundException(workItem.getName() );
    }
}
 
Example #16
Source File: InjectionHelper.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private static void wireWIHs(BeanCreator beanCreator, BeanCreator fallbackBeanCreator, ClassLoader cl, List<WorkItemHandlerModel> wihModels, KieSession kSession) { 
	 for (WorkItemHandlerModel wihModel : wihModels) {
        WorkItemHandler wih;
        try {
            wih = beanCreator.createBean(cl, wihModel.getType(), wihModel.getQualifierModel());
        } catch (Exception e) {
            try {
                wih = fallbackBeanCreator.createBean(cl, wihModel.getType(), wihModel.getQualifierModel() );
            } catch (Exception ex) {
                throw new RuntimeException("Cannot instance WorkItemHandler " + wihModel.getType(), e);
            }
        }
        kSession.getWorkItemManager().registerWorkItemHandler(wihModel.getName(), wih );
    }
}
 
Example #17
Source File: LightWorkItemManager.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void transitionWorkItem(String id, Transition<?> transition) {
    WorkItem workItem = workItems.get(id);
    // work item may have been aborted
    if (workItem != null) {
                    
        WorkItemHandler handler = this.workItemHandlers.get(workItem.getName());
        if (handler != null) {
            ProcessInstance processInstance = processInstanceManager.getProcessInstance(workItem.getProcessInstanceId());
            eventSupport.fireBeforeWorkItemTransition(processInstance, workItem, transition, null);
            
            try {
                handler.transitionToPhase(workItem, this, transition);
            } catch (UnsupportedOperationException e) {
                workItem.setResults((Map<String, Object>)transition.data()); 
                workItem.setPhaseId(Complete.ID);
                workItem.setPhaseStatus(Complete.STATUS);
                completePhase.apply(workItem, transition);
                internalCompleteWorkItem(workItem);                                        
            }
            
            eventSupport.fireAfterWorkItemTransition(processInstance, workItem, transition, null);
        } else {
            throw new WorkItemHandlerNotFoundException(workItem.getName() );
        }
            
    } else {
        throw new WorkItemNotFoundException("Work Item (" + id + ") does not exist", id);
    }
}
 
Example #18
Source File: LightWorkItemManager.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public void dispose() {
    if (workItemHandlers != null) {
        for (Map.Entry<String, WorkItemHandler> handlerEntry : workItemHandlers.entrySet()) {
            if (handlerEntry.getValue() instanceof Closeable) {
                ((Closeable) handlerEntry.getValue()).close();
            }
        }
    }
}
 
Example #19
Source File: LightWorkItemManager.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public void registerWorkItemHandler(String workItemName, WorkItemHandler handler) {
    this.workItemHandlers.put(workItemName, handler);
}
 
Example #20
Source File: SignallingTaskHandlerDecorator.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public SignallingTaskHandlerDecorator(WorkItemHandler originalTaskHandler, String eventType) {
    super(originalTaskHandler);
    this.eventType = eventType;
}
 
Example #21
Source File: SignallingTaskHandlerDecorator.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public SignallingTaskHandlerDecorator(Class<? extends WorkItemHandler> originalTaskHandlerClass, String eventType, int exceptionCountLimit) {
    super(originalTaskHandlerClass);
    this.eventType = eventType;
    this.exceptionCountLimit = exceptionCountLimit;
}
 
Example #22
Source File: SignallingTaskHandlerDecorator.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public SignallingTaskHandlerDecorator(WorkItemHandler originalTaskHandler, String eventType, int exceptionCountLimit) {
    super(originalTaskHandler);
    this.eventType = eventType;
    this.exceptionCountLimit = exceptionCountLimit;
}
 
Example #23
Source File: CachedWorkItemHandlerConfig.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public CachedWorkItemHandlerConfig register(String name, WorkItemHandler handler) {
    workItemHandlers.put(name, handler);
    return this;
}
 
Example #24
Source File: ServiceTaskDescriptor.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public ClassOrInterfaceDeclaration classDeclaration() {
    String unqualifiedName = StaticJavaParser.parseName(mangledName).removeQualifier().asString();
    ClassOrInterfaceDeclaration cls = new ClassOrInterfaceDeclaration()
            .setName(unqualifiedName)
            .setModifiers(Modifier.Keyword.PUBLIC)
            .addImplementedType(WorkItemHandler.class.getCanonicalName());
    ClassOrInterfaceType serviceType = new ClassOrInterfaceType(null, interfaceName);
    FieldDeclaration serviceField = new FieldDeclaration()
            .addVariable(new VariableDeclarator(serviceType, "service"));
    cls.addMember(serviceField);

    // executeWorkItem method
    BlockStmt executeWorkItemBody = new BlockStmt();
    MethodDeclaration executeWorkItem = new MethodDeclaration()
            .setModifiers(Modifier.Keyword.PUBLIC)
            .setType(void.class)
            .setName("executeWorkItem")
            .setBody(executeWorkItemBody)
            .addParameter(WorkItem.class.getCanonicalName(), "workItem")
            .addParameter(WorkItemManager.class.getCanonicalName(), "workItemManager");

    MethodCallExpr callService = new MethodCallExpr(new NameExpr("service"), operationName);

    for (Map.Entry<String, String> paramEntry : parameters.entrySet()) {
        MethodCallExpr getParamMethod = new MethodCallExpr(new NameExpr("workItem"), "getParameter").addArgument(new StringLiteralExpr(paramEntry.getKey()));
        callService.addArgument(new CastExpr(new ClassOrInterfaceType(null, paramEntry.getValue()), getParamMethod));
    }
    MethodCallExpr completeWorkItem = completeWorkItem(executeWorkItemBody, callService);

    executeWorkItemBody.addStatement(completeWorkItem);

    // abortWorkItem method
    BlockStmt abortWorkItemBody = new BlockStmt();
    MethodDeclaration abortWorkItem = new MethodDeclaration()
            .setModifiers(Modifier.Keyword.PUBLIC)
            .setType(void.class)
            .setName("abortWorkItem")
            .setBody(abortWorkItemBody)
            .addParameter(WorkItem.class.getCanonicalName(), "workItem")
            .addParameter(WorkItemManager.class.getCanonicalName(), "workItemManager");

    // getName method
    MethodDeclaration getName = new MethodDeclaration()
            .setModifiers(Modifier.Keyword.PUBLIC)
            .setType(String.class)
            .setName("getName")
            .setBody(new BlockStmt().addStatement(new ReturnStmt(new StringLiteralExpr(mangledName))));
    cls.addMember(executeWorkItem)
            .addMember(abortWorkItem)
            .addMember(getName);

    return cls;
}
 
Example #25
Source File: CommandBasedStatefulKnowledgeSession.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public WorkItemManager getWorkItemManager() {
    if ( workItemManager == null ) {
        workItemManager = new WorkItemManager() {
            public void completeWorkItem(String id,
                                         Map<String, Object> results, 
                                         Policy<?>... policies) {
                CompleteWorkItemCommand command = new CompleteWorkItemCommand();
                command.setWorkItemId( id );
                command.setResults( results );
                runner.execute( command );
            }

            public void abortWorkItem(String id, Policy<?>... policies) {
                AbortWorkItemCommand command = new AbortWorkItemCommand();
                command.setWorkItemId( id );
                runner.execute( command );
            }

            public void registerWorkItemHandler(String workItemName,
                                                WorkItemHandler handler) {
                RegisterWorkItemHandlerCommand command = new RegisterWorkItemHandlerCommand();
                command.setWorkItemName( workItemName );
                command.setHandler( handler );
                runner.execute( command );
            }

            public WorkItem getWorkItem(String id) {
                GetWorkItemCommand command = new GetWorkItemCommand();
                command.setWorkItemId( id );
                return runner.execute( command );
            }

            public void clear() {
                throw new UnsupportedOperationException();
            }

            public Set<WorkItem> getWorkItems() {
                throw new UnsupportedOperationException();
            }

            public void internalAbortWorkItem(String id) {
                throw new UnsupportedOperationException();
            }

            public void internalAddWorkItem(WorkItem workItem) {
                throw new UnsupportedOperationException();
            }

            public void internalExecuteWorkItem(WorkItem workItem) {
                throw new UnsupportedOperationException();
            }

            @Override
            public void signalEvent(String type, Object event) {
                SignalEventCommand command = new SignalEventCommand(type, event);
                runner.execute(command);
            }

            @Override
            public void signalEvent(String type, Object event, String processInstanceId) {
                SignalEventCommand command = new SignalEventCommand(processInstanceId, type, event);
                runner.execute(command);
            }

            @Override
            public void dispose() {
                // no-op
            }

            @Override
            public void retryWorkItem( String workItemID, Map<String, Object> params ) {
               ReTryWorkItemCommand command = new ReTryWorkItemCommand(workItemID,params);
                runner.execute( command );
            }

            @Override
            public void internalCompleteWorkItem(WorkItem workItem) {
                
            }
        };
    }
    return workItemManager;
}
 
Example #26
Source File: FluentCommandFactoryServiceImpl.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public FluentCommandFactoryServiceImpl newRegisterWorkItemHandlerCommand(WorkItemHandler handler, String workItemName) {
    commands.add( factory.newRegisterWorkItemHandlerCommand( handler, workItemName ) );
    return this;
}
 
Example #27
Source File: RegisterWorkItemHandlerCommand.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public void setHandler(WorkItemHandler handler) {
    this.handler = handler;
}
 
Example #28
Source File: RegisterWorkItemHandlerCommand.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public WorkItemHandler getHandler() {
    return handler;
}
 
Example #29
Source File: RegisterWorkItemHandlerCommand.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public RegisterWorkItemHandlerCommand(String workItemName, WorkItemHandler handler) {
    this.handler = handler;
    this.workItemName = workItemName;
}
 
Example #30
Source File: DefaultWorkItemManager.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public void registerWorkItemHandler(String workItemName, WorkItemHandler handler) {
    this.workItemHandlers.put(workItemName, handler);
}