cancel
Showing results for 
Search instead for 
Did you mean: 

How to use REST API along with activiti?

prasad1
Champ in-the-making
Champ in-the-making
How to start a process instance using POST request. I am mainly concerned about its code implementation. As with the GET request we can provide the attribute-values in query string and paste it over browser but POST data are hidden and needs some sort of interface that will send such data. The user guide mentions something about JSON and JAVA API calls. Do I need to write a JAVA code to create a process instance using REST API?

Here's where I got confused:

To get the process definitions:
Get Process Definition

Returns details about a deployed process definition.

Request: [b]GET[/b] /process-definition/{processDefinitionId}
API: ProcessEngines.getProcessEngine(configuredProcessEngineName).getProcessService().createProcessDefinitionQuery().processDefinitionId(processDefinitionId)
Response:
{
  "id": "financialReport:1",
  "key": "financialReport",
  "version": 1,
  "name": "Monthly financial report",
  "resourceName": "org/activiti/examples/bpmn/usertask/FinancialReportProcess.bpmn20.xml",
  "deploymentId": "10",
  "startFormResourceKey": null
}

But to create a process instance:

Request: [b]POST[/b] /process-instance
{
  "processDefinitionId":"financialReport:1:1700",
  "businessKey":"order-4711"
}

API: ProcessEngines.getProcessEngine(configuredProcessEngineName).getRuntimeService().startProcessInstanceById(processDefinitionId[, businessKey][, variables])
Response:
{
  "id": "217",
  "processDefinitionId": "financialReport:1:1700",
  "activityNames": ["writeReportTask"],
  "ended": true
}


Could someone please elaborate the process to use a REST API in creating a process instance. I am newbie in REST as well as ACTIVITI architecture.
Thank you in advance.
18 REPLIES 18

frederikherema1
Star Contributor
Star Contributor
The REST-principle (http://en.wikipedia.org/wiki/REST) is explained here. To "Create" (start) a process-instance, a POST is the HTTP-method to use…

Rest can indeed be used in a browser, but most of the time, the browser does something with this response (not just showing JSON, but render UI). With javascript, you can easilly formulate a http-request to a rest-endpoint using POST without having an actual form with input-parameters.

hamepal
Champ in-the-making
Champ in-the-making
@frederikheremans
  Thanks for the reply…  Smiley Happy
  it would be really nice of you, if you can provide a working code snippet of client side for sending (POST) REST request.


Thanks in advance…  Smiley Wink

prasad1
Champ in-the-making
Champ in-the-making
I tried making a REST call using JavaScript. This is the code I run.
function sendPost()
    {
       
        var data = [{"processDefinitionId":"restprocessid:1:1425"}];
        var xhr = new XMLHttpRequest();
        var url = "http://localhost:8080/activiti-rest/service/process-instance";
        xhr.open("POST", url, true);
        //The following line tells the REST service to use the DELETE method instead of the POST method.  This is
        //an architectural implementation due to the limits of clients supporting GET and POST methods, but
        //not necessarily PUT and DELETE methods.
        xhr.setRequestHeader("X-Method-Override","DELETE");

        xhr.onreadystatechange = function() {
        if (xhr.readyState==4 && xhr.status==200) {
        //check for an error message contained in the REST response. 
        //If xhr.responseText is blank, update was successful.
        alert("SUCCESS");
        }
        else
        {
            alert("ERROR in RESPONSE: "+xhr.status+" , "+xhr.responseText);
        }
        }
       
        try {
        xhr.send (JSON.stringify(data));
        }
        catch(ex)
        {
            alert("Exception"+ex.message);
        }
       
    }

I run sendPost method in onclick event of button.

I am getting the following exceptions in CATALINA.OUT

11:17:07,304  ERROR [extensions.webscripts.AbstractRuntime] Exception from executeScript - redirecting to status template error: 05200003 Script url /process-instance does not support the method OPTIONS
org.springframework.extensions.webscripts.WebScriptException: 05200003 Script url /process-instance does not support the method OPTIONS
at org.springframework.extensions.webscripts.AbstractRuntime.executeScript(AbstractRuntime.java:159)
at org.springframework.extensions.webscripts.servlet.WebScriptServlet.service(WebScriptServlet.java:118)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:636)

I run the same process over activiti-explorer I got the correct output in CATALINA.OUT.
I have attached my XML file(process definition) along with this post.

Could you suggest me what am I missing in the REST call?

prasad1
Champ in-the-making
Champ in-the-making
I fixed the code using solution in some other thread. I was sending 'processDefinitionId' instead of 'processDefinitionKey'. I am now able to make a REST call. But I am facing new issue while sending more variables to the process.
Here is my activiti diagram:
[img]http://static.inky.ws/thumb/411/thumb.jpg[/img]

I have added a groovy script as 

print $myVar
and in the REST call I added the parameter myVar as


function sendPost()
    {
         try {
          
            var xhr = new XMLHttpRequest();
            var url = "http://localhost:8080/activiti-rest/service/process-instance";
            xhr.open("POST", url, true,"kermit","kermit");
          
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.onreadystatechange = function() {
            if (xhr.readyState==4 && xhr.status==200) {
            //check for an error message contained in the REST response. 
            //If xhr.responseText is blank, update was successful.
            alert("SUCCESS");
            }
            else
            {
                alert("ERROR in RESPONSE: "+xhr.status+" , "+xhr.responseText);
            }
        }
      [color=#FF0000] xhr.send("processDefinitionKey=restprocessid&myVar=man"); //working[/color]  // REST CALL
     }
        catch(ex)
        {
            alert("Exception"+ex.message);
        }
       
    }


I am getting the following error on browser:
ERROR in RESPONSE: 500 , {
    "status" :
  {
    "code" : 500,
    "name" : "Internal Error",
    "description" : "An error inside the HTTP server which prevented it from fulfilling the request."
  }, 
 
  "message" : "05200032 Wrapped Exception (with status template): problem evaluating script: javax.script.ScriptException: groovy.lang.MissingPropertyException: No such property: myVar for class: Script12", 
  "exception" : "org.springframework.extensions.webscripts.WebScriptException - 05200032 Wrapped Exception (with status template): problem evaluating script: javax.script.ScriptException: groovy.lang.MissingPropertyException: No such property: myVar for class: Script12",
 
  "callstack" :
  [
     ""      ,"[color=#FF0000]groovy.lang.MissingPropertyException: No such property: myVar for class: Script12"[/color]
      ,"org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:49)"
      ,"org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:49)"
      ,"org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:239)"
      ,"Script12.run(Script12.groovy:1)"
      ,"org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.eval(GroovyScriptEngineImpl.java:315)"
      ,"org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.eval(GroovyScriptEngineImpl.java:111)"
      ,"javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:233)"
      ,"org.activiti.engine.impl.scripting.ScriptingEngines.evaluate(ScriptingEngines.java:70)"
      ,"org.activiti.engine.impl.bpmn.behavior.ScriptTaskActivityBehavior.execute(ScriptTaskActivityBehavior.java:43)"
      ,"org.activiti.engine.impl.pvm.runtime.AtomicOperationActivityExecute.execute(AtomicOperationActivityExecute.java:40)"
      ,"org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:76)"
      ,"org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:481)"
      ,"org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionNotifyListenerStart.eventNotificationsCompleted(AtomicOperatio
nTransitionNotifyListenerStart.java:48)"
      ,"org.activiti.engine.impl.pvm.runtime.AbstractEventAtomicOperation.execute(AbstractEventAtomicOperation.java:52)"

If I remove the parameter myVar in the rest call, the function works correctly in this case. What is wrong with this way of REST call?

frederikherema1
Star Contributor
Star Contributor
Try sending the parameter "myVar_type=string" along with your myVar value…

prasad1
Champ in-the-making
Champ in-the-making
I tried working around with parameters as below but no use.

processDefinitionKey=myprocess&myVar_type=prasad

What is type in this? Is type a specific keyword such as string, integer, etc? Where can I find information regarding allowed types?
Can you give me an example for this?

Small snippet of error:

"status" :
  {
    "code" : 500,
    "name" : "Internal Error",
    "description" : "An error inside the HTTP server which prevented it from fulfilling the request."
  }, 
 
  "message" : "05210009 Wrapped Exception (with status template): problem evaluating script: javax.script.ScriptException: groovy.lang.MissingPropertyException: No such property: myVar for class: Script9", 
  "exception" : "org.springframework.extensions.webscripts.WebScriptException - 05210009 Wrapped Exception (with status template): problem evaluating script: javax.script.ScriptException: groovy.lang.MissingPropertyException: No such property: myVar for class: Script9",

what is this about BusinessKey? I found something over here http://forums.activiti.org/en/viewtopic.php?f=6&t=1672. Do I need to be concerned about this? If yes, how?

My main objective is to send a string value to a script task.
This is my Jersey client code:

public static void main(String[] args) {
  // TODO Auto-generated method stub
  Client client = Client.create();
  client.addFilter(new HTTPBasicAuthFilter("kermit", "kermit"));
  WebResource webResource = client.resource("http://localhost:8080/activiti-rest/service/process-instance");
 
   MultivaluedMap formData = new MultivaluedMapImpl();
    formData.add("processDefinitionKey", "restprocessid");
    formData.add("myVar_type", "Integer");
    formData.add("myVar", "2");
    ClientResponse response = webResource.type("application/x-www-form-urlencoded").post(ClientResponse.class, formData);
    System.out.println(response.toString());
    
}

I am getting the exceptions as described above. Can anyone please guide me.

frederikherema1
Star Contributor
Star Contributor
I meant:

processDefinitionKey=myprocess&myVar=prasad&myVar_type=string

prasad1
Champ in-the-making
Champ in-the-making
This did not work too.  Smiley Sad
I used the following parameters
processDefinitionKey=restprocessid&input=prasad&input_type=string
However I still getting HTTP/1.1 500 Internal Server Error as follows:
Snippet of error:


{
    "status" :
  {
    "code" : 500,
    "name" : "Internal Error",
    "description" : "An error inside the HTTP server which prevented it from fulfilling the request."
  }, 
 
  "message" : "05220009 Wrapped Exception (with status template): problem evaluating script: javax.script.ScriptException: [color=#FF0000]groovy.lang.MissingPropertyException: No such property: input for class: Script10",  [/color]
  "exception" : "org.springframework.extensions.webscripts.WebScriptException - 05220009 Wrapped Exception (with status template): problem evaluating script: javax.script.ScriptException: groovy.lang.MissingPropertyException: No such property: input for class: Script10",
 
  "callstack" :
  [
     ""      ,"groovy.lang.MissingPropertyException: No such property: input for class: Script10"
      ,"org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:49)"
      ,"org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:49)"
      ,"org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:239)"
      ,"Script10.run(Script10.groovy:1)"
:
:

I tried sending the same parameters using AJAX via post parameters, but no use.

ronald_van_kuij
Champ on-the-rise
Champ on-the-rise
Look at what the errors says… Does your 'Script10 class' have a field called input?