Activiti BPM Tutorial – Web Services

Start Activiti REST Server in Main

package com.nuke.main;

import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.identity.User;
import org.activiti.rest.service.application.ActivitiRestServicesApplication;
import org.restlet.Component;
import org.restlet.data.Protocol;

import com.nuke.activiti.CustomProcessEngineConfig;

public class ExpenseProcessRESTMain {
	
	private static final String filename = "/Users/tmichels/Documents/workspace-sts-3.5.0.M21/nucleus-workflow/src/main/resources/diagrams/expense_process.bpmn";
	
	public static void main(String[] args) throws Exception {
		ProcessEngineConfiguration engineConfig = CustomProcessEngineConfig.createStandaloneInMemProcessEngineConfiguration();
	    ProcessEngine processEngine = engineConfig.buildProcessEngine();
	    
	    User newUser = processEngine.getIdentityService().newUser("kermit");
	    newUser.setPassword("kermit");
	    processEngine.getIdentityService().saveUser(newUser);

	    processEngine.getRepositoryService().createDeployment()
	    	.addInputStream("expense_process.bpmn",
				new FileInputStream(filename)).deploy();
	    
	    Map variableMap1 = new HashMap();
		variableMap1.put("employee", "Jack");
		variableMap1.put("amount", 111);
		
		processEngine.getRuntimeService().startProcessInstanceByKey("expenseProcess", variableMap1);
		
		Component component = new Component();
	    component.getServers().add(Protocol.HTTP, 8182);
	    ActivitiRestServicesApplication restApplication = new ActivitiRestServicesApplication();
	    // Attach the Activiti REST-application and start
	    component.getDefaultHost().attach("/activiti-rest",
	    		restApplication);
	    component.start();
	}
}

Create Activiti REST Server in web.xml

<?xml version="1.0" encoding="UTF-8"?>  
<web-app id="WebApp_ID" version="2.4"  
            xmlns="http://java.sun.com/xml/ns/j2ee"  
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
            xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee  
                 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
  
  <display-name>Activiti REST</display-name>
   
  <listener>
    <listener-class>org.activiti.rest.common.servlet.ActivitiServletContextListener</listener-class>
  </listener> 
  
  <!-- Restlet adapter -->  
  <servlet>  
    <servlet-name>RestletServlet</servlet-name>  
    <servlet-class>org.restlet.ext.servlet.ServerServlet</servlet-class>
    <init-param>
      <!-- Application class name -->
      <param-name>org.restlet.application</param-name>
      <param-value>org.activiti.rest.service.application.ActivitiRestServicesApplication</param-value>
    </init-param>
  </servlet>
  
  <!-- Catch all requests -->  
  <servlet-mapping>  
    <servlet-name>RestletServlet</servlet-name>  
    <url-pattern>/service/*</url-pattern>  
  </servlet-mapping>  
</web-app>

Activiti REST Client

package com.nuke.activiti.client;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;
import org.restlet.data.ChallengeScheme;
import org.restlet.data.MediaType;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.ClientResource;

public class ActivitiRestClient {

	private static String REST_URI = "http://localhost:8081/activiti-rest-api/service";
	private static Logger logger = Logger.getLogger(ActivitiRestClient.class);

	private static ClientResource getClientResource(String uri) {
		ClientResource clientResource = new ClientResource(uri);
		clientResource.setChallengeResponse(ChallengeScheme.HTTP_BASIC,
				"kermit", "kermit");
		return clientResource;
	}

	public static String getUnderwritingQueueProcessId() throws IOException,
			JSONException {
		String uri = REST_URI + "/repository/process-definitions";
		System.out.println("URI: " + uri);
		Representation response = getClientResource(uri).get(
				MediaType.APPLICATION_JSON);
		JSONObject object = new JSONObject(response.getText());
		if (object != null) {
			JSONArray arr = (JSONArray) object.get("data");
			for (int i = 0; i < arr.length(); i++) {
				JSONObject jsonObject = (JSONObject) arr.get(i);
				if (jsonObject.get("key").equals("underwritingQueue")) {
					logger.info("Returning processDefinitionId "
							+ jsonObject.get("id"));
					return (String) jsonObject.get("id");
				}
			}
		}
		return null;
	}

	public static String addLoanToUnderwritingQueue(String processDefinitionId)
			throws Exception {
		String uri = REST_URI + "/runtime/process-instances";
		JSONStringer jsRequest = new JSONStringer();
		jsRequest.object().key("processDefinitionId")
				.value(processDefinitionId).key("variables").array().object()
				.key("name").value("LoanId").key("value").value("132312")
				.endObject().endArray();
		jsRequest.endObject();
		Representation rep = new StringRepresentation(jsRequest.toString(),
				MediaType.APPLICATION_JSON);
		System.out.println("REP: " + rep.toString());
		JSONObject jsObj = new JSONObject(getClientResource(uri).post(rep)
				.getText());
		logger.info("Returning processId " + jsObj.getString("id"));
		return jsObj.getString("id");
	}

	public static String getQueueTask(String processInstanceId)
			throws Exception {
		String uri = REST_URI + "/tasks?candidate=kermit";
		Representation response = getClientResource(uri).get(
				MediaType.APPLICATION_JSON);
		JSONObject object = new JSONObject(response.getText());
		if (object != null) {
			JSONArray arr = (JSONArray) object.get("data");
			for (int i = 0; i < arr.length(); i++) {
				JSONObject ob = (JSONObject) arr.get(i);
				if (ob.get("processInstanceId").equals(processInstanceId)) {
					logger.info("Returning taskId " + ob.get("id"));
					return (String) ob.get("id");
				}
			}
		}
		return null;
	}

	public static String claimQueueTask(String taskId) throws Exception {
		String uri = REST_URI + "/task/" + taskId + "/claim";
		Representation response = getClientResource(uri).put("{}",
				MediaType.APPLICATION_JSON);
		JSONObject object = new JSONObject(response.getText());
		System.out.println("OBJECT: " + object.toString());
		logger.info("Claimed task " + taskId + " " + object.get("success"));
		return object.get("success").toString();
	}
	
	public static String completeTask(String taskId)
			throws Exception {
		String uri = REST_URI + "/task/" + taskId + "/complete";
		Representation response = getClientResource(uri).put(
				"{disposition:complete}", MediaType.APPLICATION_JSON);
		JSONObject object = new JSONObject(response.getText());
		logger.info("Completed task " + taskId + " " + object.getString("success"));
		return object.getString("success");
	}
	
	@SuppressWarnings("unused")
	public static int getTasks(String status, String candidate)
			throws Exception {
		String uri = REST_URI + "/tasks?" + status + "=" + candidate;
		Representation response = getClientResource(uri).get(
				MediaType.APPLICATION_JSON);
		JSONObject object = new JSONObject(response.getText());
		if (object != null) {
			JSONArray arr = (JSONArray) object.get("data");
			logger.info("Tasklist " + candidate + " " + status + " size " + arr.length());
			return arr.length();
		}
		return -1;
	}
}

Activiti REST Client Test

package com.nuke.activiti.client;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import org.junit.Test;

import com.nuke.activiti.common.AbstractTest;


public class ActivitiRestClientTest extends AbstractTest {
	
	@Test
	public void restAPITest() throws Exception {
		String underwritingLoanDefinitionId = ActivitiRestClient.getUnderwritingQueueProcessId();
		assertNotNull(underwritingLoanDefinitionId);
		String processInstanceId = ActivitiRestClient.addLoanToUnderwritingQueue(underwritingLoanDefinitionId);
		assertNotNull(processInstanceId);
		String taskId = ActivitiRestClient.getQueueTask(processInstanceId);
		assertNotNull(taskId);
		assertEquals("true", ActivitiRestClient.claimQueueTask(taskId));
		assertEquals(4, ActivitiRestClient.getTasks("candidate","kermit"));
		assertEquals(6, ActivitiRestClient.getTasks("assignee","kermit"));
		assertEquals("true", ActivitiRestClient.completeTask(taskId));
		assertEquals(0, ActivitiRestClient.getTasks("assignee","kermit"));
	}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: