Starting a JBPM6 Process using Rest API

2,422 views
Skip to first unread message

SATISH POLASI

unread,
Oct 21, 2014, 2:46:28 PM10/21/14
to jbpm-...@googlegroups.com
Hi,

I have a requirement to build a JBPM business process, deploy and invoke the process from external application.
As part of the JBPM examples I deployed the evaluation process and trying to start the process from my external application and here is the code I have written to invoke it.

public String postService(String urlpath, Map<String, Object> parameters) throws DataServiceException{

    log.debug("JBPMHelper.postService()<urlpath="+urlpath+", username="+username+", parameters="+parameters+">");

        HttpClient httpclient = new HttpClient();

        //String restUrl = baseURL.concat(urlpath);

        PostMethod theMethod = new PostMethod("http://localhost:8080/jbpm-console/rest/runtime/org.jbpm:Evaluation:1.0/withvars/process/evaluation/start");

        if(null != parameters && !parameters.isEmpty()){

        NameValuePair data[] = new NameValuePair[parameters.size()+2];

Set<String> keys = parameters.keySet();

int count = 0;

for (String key : keys) {

data[count]= new NameValuePair(key, ""+parameters.get(key));

log.info("Key"+ data[count]);

count++;

}

data[parameters.size()] = new NameValuePair(JBPMConstants.J_USERNAME, user);

data[parameters.size()+1] = new NameValuePair(JBPMConstants.J_PASSWORD, password);

theMethod.setRequestBody(data);

theMethod.addRequestHeader(JBPMConstants.CONTENT_TYPE, "application/xml");

        }

        String responseString = null;

        log.info("JBPMWSTest.postService()<restUrl = "+restUrl+", theMethod="+theMethod+">");

        try {

        httpclient.executeMethod(theMethod);

        InputStream is = theMethod.getResponseBodyAsStream();

        responseString = convertStreamToString(is);

//        }

        } catch (HttpException e) {

        throw new DataServiceException(e);

} catch (IOException e) {

throw new DataServiceException(e);

} catch (DataServiceException dse) {

throw new DataServiceException(dse.getMessage());

}finally {

        theMethod.releaseConnection();

        }

return responseString;

    }

When I execute it I am getting the following reponse string <html><head><title>Error</title></head><body>Validation fails.</body></html>

I tested the same URL "http://localhost:8080/jbpm-console/rest/runtime/org.jbpm:Evaluation:1.0/withvars/process/evaluation/start" from Google Chrome Rest Client and it is executing successfully withe the below response back

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
 <process-instance-with-vars>
<status>
SUCCESS
</status>
<variables />
 <processInstance>
<process-id>
evaluation
</process-id>
<id>
16
</id>
<state>
1
</state>
 </processInstance>
 </process-instance-with-vars>

Any help is greatly appreciated.

Thanks,
Satish.

Yu Zhou

unread,
Nov 30, 2014, 9:49:08 PM11/30/14
to jbpm-...@googlegroups.com

import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.DefaultHttpClient;
import org.drools.core.util.KieFunctions;
import org.jbpm.services.task.wih.LocalHTWorkItemHandler;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.manager.RuntimeEngine;
import org.kie.api.runtime.process.ProcessInstance;
import org.kie.api.runtime.process.WorkflowProcessInstance;
import org.kie.api.task.TaskService;
import org.kie.api.task.model.TaskSummary;
import org.kie.services.client.api.RemoteRestRuntimeEngineFactory;
import org.kie.services.client.api.RemoteRuntimeEngineFactory;
import org.kie.services.client.serialization.jaxb.impl.process.JaxbProcessInstanceResponse;
import org.springframework.http.HttpEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import beans.FinanceBean;

import com.sun.xml.xsom.impl.util.Uri;

class PostParam implements Serializable {
 private String para1;
 private String para2;

 public String getPara1() {
  return para1;
 }

 public void setPara1(String para1) {
  this.para1 = para1;
 }

 public String getPara2() {
  return para2;
 }

 public void setPara2(String para2) {
  this.para2 = para2;
 }
}

class ThreadTTT implements Runnable {
 ThreadTTT(RestTemplate restTemplate) {
  this.restTemplate = restTemplate;
 }

 RestTemplate restTemplate;

 @Override
 public void run() {
  for (int i = 0; i < 1; i++) {
   /*
    * MultiValueMap<String, Object> map = new
    * LinkedMultiValueMap<String, Object>(); map.add("paramBean", new
    * PostParam());
    */
   //List messageConverters = new ArrayList();
   //messageConverters.add(new MappingJackson2HttpMessageConverter());
   //restTemplate.setMessageConverters(messageConverters);
   
   MultiValueMap<String,String> entity = new LinkedMultiValueMap<String,String>();
   String url = "http://localhost:8080/jbpm-console/rest/runtime/{deploymentId}/process/{processDefId}/start?map_param1=sdfd";
   /*   UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(url);
   uriBuilder.queryParam("map_param1", "xdf111");*/
   JaxbProcessInstanceResponse result = restTemplate
     .postForObject(url, entity, JaxbProcessInstanceResponse.class,
       "com.demo.testProject:testProject:1.0",
       "testProject.testProcess",
       "ttsss");
   System.out.println(result.getId());
  }
 }

}

public class Test {

 /**
  * @param args
  * @throws MalformedURLException
  */
 public static void main(String[] args) throws MalformedURLException {

//  HttpHost host = new HttpHost("localhost", 8080, "http");
//  RestTemplate restTemplate = new RestTemplate(
//    new HttpComponentsClientHttpRequestFactoryBasicAuth(host));
//
//  HttpComponentsClientHttpRequestFactory requestFactory = (HttpComponentsClientHttpRequestFactory) restTemplate
//    .getRequestFactory();
//  DefaultHttpClient httpClient = (DefaultHttpClient) requestFactory
//    .getHttpClient();
//  requestFactory.setConnectTimeout(50000000);
//  requestFactory.setReadTimeout(50000000);
//  httpClient.getCredentialsProvider().setCredentials(
//    new AuthScope("localhost", 8080, AuthScope.ANY_REALM),
//    new UsernamePasswordCredentials("krisv", "krisv"));
//  new Thread(new ThreadTTT(restTemplate)).start();
//  //new Thread(new ThreadTTT(restTemplate)).start();

  /// Setup the factory class with the necessary information to
  // communicate with the REST services
  RemoteRestRuntimeEngineFactory restSessionFactory =
    RemoteRestRuntimeEngineFactory.newBuilder()
    .addDeploymentId("eyas:eyasWeb:1.0")
    .addUrl(new URL("http://localhost:8080/jbpm-console/"))
    .addUserName("krisv")
    .addPassword("krisv")
    .addTimeout(50000)
    .addExtraJaxbClasses(FinanceBean.class)
    .build();
  
   // Create KieSession and TaskService instances and use them
   RuntimeEngine engine = restSessionFactory.newRuntimeEngine();
   KieSession ksession = engine.getKieSession();
   Map<String, Object> params = new HashMap<String, Object>();
   //ksession.getWorkItemManager().registerWorkItemHandler();
   /*org.kie.api.runtime.process.WorkItemManager
    wm = ksession.getWorkItemManager();
   LocalHTWorkItemHandler handler = new LocalHTWorkItemHandler();*/
   
   //wm.registerWorkItemHandler("local", handler);
   //params.put("employee", "krisv");
   //params.put("reason","Yearly performance evaluation");
   //params.put("param1", "krisv");
   FinanceBean bean = new FinanceBean();
   bean.setCostFee(8.1f);
   bean.setCostType("ddd");
   params.put("finance", bean);
   //KieFunctions.greaterThan(number, value)
   try {
    WorkflowProcessInstance processInstance = (WorkflowProcessInstance)
      ksession.startProcess("eyasWeb.finance", params); // ProcessInstance
    //processInstance =  ksession.startProcess("com.sample.evaluation");
    long procId = processInstance.getId();
    String taskUserId = "krisv";
    TaskService taskService = engine.getTaskService();
    List<TaskSummary> tasks = taskService .getTasksAssignedAsPotentialOwner("jary",
      "en-UK");
    long taskId = -1;
   
    for (TaskSummary task : tasks) {
     if (task.getProcessInstanceId() == procId){
      taskId = task.getId();
      taskService.start(taskId, "jary");
      //taskService.claim(taskId, "jary");
      taskService.complete(taskId, "jary", new HashMap<String,Object>());
      //processInstance.getNodeInstance(11).set
      taskService.execute(arg0)
     }
    }
  
    if (taskId == -1) {
     throw new IllegalStateException("Unable to find task for " + "krisv" +
       " in process instance " + procId);
    }
    taskService.start(taskId, taskUserId);
   }
   catch (Exception e) { e.printStackTrace(); }
 }
  
 /*public static void startProcessAndHandleTaskViaRestRemoteJavaAPI( URL
   instanceUrl, String deploymentId, String user, String password) {
  
   // the serverRestUrl should contain a URL similar to
  //"http://localhost:8080/jbpm-console/"
  
   // Setup the factory class with the necessarry information to
   //communicate with the REST services
   RemoteRuntimeEngineFactory restSessionFactory =
     new RemoteRestRuntimeFactory( deploymentId, instanceUrl, user, password);
  
   // Create KieSession and TaskService instances and use them
   RemoteRuntimeEngine engine = restSessionFactory.newRuntimeEngine();
   KieSession ksession = engine.getKieSession(); TaskService taskService
   = engine.getTaskService(); // Each opertion on a KieSession,
   TaskService or AuditLogService // (client) instance // sends a
   request for the operation to the server side and waits for // the
   response // If something goes wrong on the server side, the client
   will throw an // exception. ProcessInstance processInstance =
   ksession .startProcess("com.burns.reactor.maintenance.cycle"); long
   procId = processInstance.getId(); String taskUserId = user;
   taskService = engine.getTaskService(); List<TaskSummary> tasks =
   taskService.getTasksAssignedAsPotentialOwner( user, "en-UK"); long
   taskId = -1; for (TaskSummary task : tasks) { if
   (task.getProcessInstanceId() == procId) { taskId = task.getId(); } }
  
   if (taskId == -1) { throw new
   IllegalStateException("Unable to find task for " + user +
   " in process instance " + procId); } taskService.start(taskId,
   taskUserId);
 }*/
}

Satish Polasi

unread,
Jan 14, 2015, 3:07:44 PM1/14/15
to jbpm-...@googlegroups.com
Hi Yu Zhou,

Thank you for the response and the code snippet. when i try to execute the code snippet as java application it is failing with the bellow message. I really appreciate, if you can guide me where I am doing wrong. 

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/protocol/HttpContext

at org.kie.services.client.api.RemoteRestRuntimeEngineFactoryBuilderImpl.<init>(RemoteRestRuntimeEngineFactoryBuilderImpl.java:21)

at org.kie.services.client.api.RemoteRestRuntimeEngineFactory.newBuilder(RemoteRestRuntimeEngineFactory.java:101)

at edu.ucla.its.opus.ar.helper.JBPMHelper.createProcess(JBPMHelper.java:206)

at edu.ucla.its.opus.ar.helper.JBPMHelper.main(JBPMHelper.java:244)

Caused by: java.lang.ClassNotFoundException: org.apache.http.protocol.HttpContext

at java.net.URLClassLoader$1.run(URLClassLoader.java:366)

at java.net.URLClassLoader$1.run(URLClassLoader.java:355)

at java.security.AccessController.doPrivileged(Native Method)

at java.net.URLClassLoader.findClass(URLClassLoader.java:354)

at java.lang.ClassLoader.loadClass(ClassLoader.java:424)

at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)

at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

... 4 more

zyd...@gmail.com

unread,
Jan 15, 2015, 12:27:00 AM1/15/15
to Satish Polasi, jbpm-usage
Download the misssing libarary from apache!
http Common


--
You received this message because you are subscribed to a topic in the Google Groups "jBPM Usage" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/jbpm-usage/7NmtWcLl88Y/unsubscribe.
To unsubscribe from this group and all its topics, send an email to jbpm-usage+...@googlegroups.com.
To post to this group, send email to jbpm-...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/jbpm-usage/d38cbdb8-39c9-4094-bf03-4b7ce133ebe5%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Satish Polasi

unread,
Jan 16, 2015, 12:03:16 PM1/16/15
to jbpm-...@googlegroups.com, satish...@gmail.com
Hi Yu Zhou,

Thank you for providing me the direction. It worked.

Thanks,
Satish.

Pankaj Lochan Patro

unread,
Jan 19, 2015, 7:15:34 PM1/19/15
to jbpm-...@googlegroups.com
Hi Yu Zhou,


I saw solution which you had given for REST API,
This works well for me,

Just i am curious to know, i had issue in passing XML data into the process, similar to like below java object input which i see in this post,
 FinanceBean bean = new FinanceBean();
   bean.setCostFee(8.1f);
   bean.setCostType("ddd");
   params.put("finance", bean);
   //KieFunctions.greaterThan(number, value)
   try { 
    WorkflowProcessInstance processInstance = (WorkflowProcessInstance)
      ksession.startProcess("eyasWeb.finance", params);

Could you please suggest how xml data or any other data (like org.w3c.dom.Element inputs) can be passed into the process for invocation.


Thanks,
Pankaj

zyd...@gmail.com

unread,
Jan 19, 2015, 9:12:42 PM1/19/15
to Pankaj Lochan Patro, jbpm-usage
Just dont know what is the special "XML data" what u said,
consider it as plain string value? Is tha OK? 


 
Date: 2015-01-20 08:15
Subject: Re: Starting a JBPM6 Process using Rest API
--
You received this message because you are subscribed to a topic in the Google Groups "jBPM Usage" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/jbpm-usage/7NmtWcLl88Y/unsubscribe.
To unsubscribe from this group and all its topics, send an email to jbpm-usage+...@googlegroups.com.
To post to this group, send email to jbpm-...@googlegroups.com.

Pankaj Lochan Patro

unread,
Jan 20, 2015, 2:05:27 PM1/20/15
to jbpm-...@googlegroups.com, plp...@gmail.com
Yes XML inputs will be in the form of String data,? 

Pankaj Lochan Patro

unread,
Jan 22, 2015, 6:55:04 PM1/22/15
to jbpm-...@googlegroups.com, plp...@gmail.com
One more query on top of REST API, in jBPM version 6.1

I am looking for update operations, 
like i want to perform setXXX() operations via RestAPI to jBPM process, Refer code below-
which throws me --> 
Exception in thread "main" java.lang.UnsupportedOperationException: The .setPriority(..) method is not supported on the remote api.
at org.kie.services.client.api.command.AbstractRemoteCommandObject.execute(AbstractRemoteCommandObject.java:99)
at org.jbpm.services.task.impl.command.CommandBasedTaskService.setPriority(CommandBasedTaskService.java:523)

code snippet:-
RemoteRuntimeEngine engine = null;
try {
engine = RemoteRestRuntimeEngineFactory.newBuilder()
.addUserName(username).addPassword(username)
.addDeploymentId("org.jbpm:Evaluation:1.0")
.build().newRuntimeEngine();
InternalTaskService  taskService = (InternalTaskService ) engine.getTaskService();
taskService.setPriority(tasksId, 1);
taskService.setExpirationDate(tasksId, new Date());
taskService.setOutput(tasksId, "userName", mapData);
} catch (InsufficientInfoToBuildException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}


How to achieve set functionality? I am using jBPM 6.1 APIs.
Reply all
Reply to author
Forward
0 new messages