In this tutorial, we try to call a public REST service from a task in Bonita. We will modify the tutorial Getting a target resource based on the client request to create a simple service that return the user's information in XML format. Then, we'll create a business process using Bonita with a simple task. On this task, we create a connector that calls this service and parser the user's information.
package forthREST; import org.restlet.resource.Get; import org.restlet.resource.ServerResource; public class UserResource extends ServerResource { @Get public String toString() { String uid = (String) getRequestAttributes().get("uid"); if (uid.equals("123")){ return "<users>" + "<user>" + "<id>"+uid+"</id>" + "<name>John</name>" + "</user>" + "</users>"; } return "No information found."; } }
<users><user><id>123</id><name>John</name></user></users>
On this part, we'll create a simple business process that accesses to the user resource provided by the REST service above. We'll use the Groovy script connector to retrieved the name of user 123.
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; //the response is in XML, so we parse the XML bodyAsString DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource inputSource = new InputSource(); inputSource.setCharacterStream(new StringReader(bodyAsString)); Document userDataDocument = documentBuilder.parse(inputSource); //get the root element users Node usersNode = userDataDocument.getDocumentElement(); //get the childs nodes of the node users (the list contains one child which is user) NodeList usersChildNodes = usersNode.getChildNodes(); //get the first child (which is user) Node userNode = usersChildNodes.item(0); //get the childs of user NodeList userChildNodes = userNode.getChildNodes(); String userName=""; //search for the child node "name" for (int i=0; i<userChildNodes.getLength(); i++) { Node node = userChildNodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { String key = node.getNodeName(); if(key.equals("name")) { String value = node.getTextContent(); userName=value; break; } } } return userName;