Expand my Community achievements bar.

SOLVED

Error programmatically reading running workflow instances

Avatar

Level 5

Hello,

I wrote some code to programmatically read workflow instances.

I keep getting a null pointer exception when reading workflows instances when they are running.

However once they complete I can read them. Any help?

 

Thanks!

1 Accepted Solution

Avatar

Correct answer by
Level 10

The code is running well and writing out the data to a simple AEM GUI: 

Servlet code (note that it returns the first running WF)

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.rmi.ServerException;
import java.util.Dictionary;
 
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
//import org.apache.sling.commons.osgi.OsgiUtil;
import org.apache.sling.jcr.api.SlingRepository;
import org.apache.felix.scr.annotations.Reference;
import org.osgi.service.component.ComponentContext;
import javax.jcr.Session;
import javax.jcr.Node; 
//import org.json.simple.JSONObject;
import java.util.UUID;

//import javax.json.JsonArray; 
import javax.jcr.Session;

//Sling Imports
import org.apache.sling.api.resource.ResourceResolverFactory ; 
import org.apache.sling.api.resource.ResourceResolver; 
import org.apache.sling.api.resource.Resource; 

//Adobe CQ Workflow APIs
import com.day.cq.workflow.model.WorkflowModel ; 
import com.day.cq.workflow.WorkflowService ; 
import com.day.cq.workflow.WorkflowSession; 
import com.day.cq.workflow.exec.WorkflowData; 


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.json.simple.JSONObject;


 
@SlingServlet(paths="/bin/myWFServlet", methods = "GET", metatype=true)
public class HandleWorkflowData extends org.apache.sling.api.servlets.SlingAllMethodsServlet {
     private static final long serialVersionUID = 2598426539166789515L;
      
   //Inject a Sling ResourceResolverFactory
     @Reference
     private ResourceResolverFactory resolverFactory;
     
     private Session session;
     
     @Reference
     private WorkflowService workflowService;
     
     /** Default log. */
     protected final Logger log = LoggerFactory.getLogger(this.getClass());
     
     
           
     @Override
     protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServerException, IOException {
       
      try
      {
         
          String[] states = {"RUNNING"};
          
          ResourceResolver resourceResolver = resolverFactory.getAdministrativeResourceResolver(null);
            session = resourceResolver.adaptTo(Session.class);
          
            WorkflowSession wfSession = workflowService.getWorkflowSession(session);
            com.day.cq.workflow.exec.Workflow[] wf = wfSession.getWorkflows(states);
            log.info("********************* WORKFLOW COUNT: " + wf.length);
          
          
          
    
       
         
            
            String id = wf[0].getId();
            String state = wf[0].getState();
            WorkflowData wd = wf[0].getWorkflowData();
            String payload = (String) wd.getPayload();
        
            //Encode the submitted form data to JSON
          JSONObject obj=new JSONObject();
          obj.put("id",id);
          obj.put("state",state);
          obj.put("payload",payload);
         
           
             //Get the JSON formatted data    
          String jsonData = obj.toJSONString();
          
             //Return the JSON formatted data
         response.getWriter().write(jsonData);
      }
      catch(Exception e)
      {
          e.printStackTrace();
      }
    }
}

View solution in original post

10 Replies

Avatar

Level 10

Please post the code so we can see what you are doing

Avatar

Community Advisor
Can you please share what exactly your trying ??

Avatar

Level 9

 I guess, you are reading workflow instances information which does not exist in the instances folder (logs node after workflow completed). And, once workflow is completed, you are able to find it.

TheBigRed wrote...

Hello,

I wrote some code to programmatically read workflow instances.

I keep getting a null pointer exception when reading workflows instances when they are running.

However once they complete I can read them. Any help?

 

Thanks!

 

Avatar

Administrator

Hi

Please share the error message and the steps/code that is resulting into this.

And by the time, please try Jitendra's suggestion. Apart from that, please have a look at this post, it could guide you through writing a Servlet that runs Workflow:

Link:- http://stackoverflow.com/questions/15233798/cq5-programmatically-run-a-workflow

//

Here is the code with comments:

@Component@Service@Properties({@Property(name = "sling.servlet.paths", value = "/bin/runmodel"),@Property(name = "sling.servlet.methods", value = "GET")})public class RunWorkflowModel extends SlingSafeMethodsServlet {static private final Logger log = LoggerFactory.getLogger(RunWorkflowModel.class);@Referenceprivate WorkflowService workflowService;@Overrideprotected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {ResourceResolver resourceResolver = request.getResourceResolver();Session session = resourceResolver.adaptTo(Session.class);/* Get Parameters * @param path = path you want to run the workflow on * @param model = workflow model name you want to run.  Typically found in /etc/workflow/models */RequestParameterMap params = request.getRequestParameterMap();String path = params.getValue("path").getString();String model = params.getValue("model").getString();// Create a workflow session WorkflowSession wfSession = workflowService.getWorkflowSession(session);try {// Get the workflow modelWorkflowModel wfModel = wfSession.getModel(model);// Get the workflow data// The first param in the newWorkflowData method is the payloadType.  Just a fancy name to let it know what type of workflow it is working with.WorkflowData wfData = wfSession.newWorkflowData("JCR_PATH", path);// Run the Workflow.wfSession.startWorkflow(wfModel, wfData);} catch (WorkflowException ex) {response.getWriter().write("failed");log.error("Error starting workflow.", ex);}response.getWriter().write("success");}}

Here is the Ajax call

CQ.Ext.Ajax.request({url: "/bin/runmodel",method: "GET",params : {"path"  : "/content/path to item you want the workflow run on","model" : "/etc/workflow/models/name of model/jcr:content/model"},success: function() {console.log("success");},failure: function(response) {CQ.Notification.notifyFromResponse(response);}});

 

Thanks and Regards

Kautuk Sahni



Kautuk Sahni

Avatar

Level 5

smacdonald2008 wrote...

Please post the code so we can see what you are doing

 

String[] states = {"RUNNING"}; ResourceResolver resourceResolver = resolverFactory.getAdministrativeResourceResolver(null); session = resourceResolver.adaptTo(Session.class); WorkflowSession wfSession = workflowService.getWorkflowSession(session); Workflow[] wf = wfSession.getWorkflows(states); log.info("WORKFLOW COUNT: " + wf.length); out = response.getWriter(); out.flush(); JSONArray ja = new JSONArray(); for(int i=0; i<wf.length; i++){ JSONObject jo = new JSONObject(); String id = wf[i].getId(); String state = wf[i].getState(); WorkflowData wd = wf[i].getWorkflowData(); String payload = (String) wd.getPayload(); jo.put("id", id); jo.put("state", state); jo.put("payload", payload); log.info(jo.toString()); ja.put(i, jo); } out.print(ja);

Avatar

Level 10

OK - I will look into this code and get it working for you. 

Avatar

Level 5

smacdonald2008 wrote...

OK - I will look into this code and get it working for you. 

 


Thank you Scott! BTW this code resides on a servlet. I'm parsing the JSON

out on a client app that uses Apache HttpClient Library. It's when I'm parsing the JSON that I get the error.

Avatar

Level 10

I am starting work on this one - get it to work and then create a helpx article. These AEM APIs need to be all in community articles. 

Avatar

Level 10

This works - i sent an email to you. I will write a helpx article so ppl reading this thread in the future will know how to use the AEM Workflow API to get information about running AEM Workflows. I will post the article to this thread once I am done. 

Avatar

Correct answer by
Level 10

The code is running well and writing out the data to a simple AEM GUI: 

Servlet code (note that it returns the first running WF)

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.rmi.ServerException;
import java.util.Dictionary;
 
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
//import org.apache.sling.commons.osgi.OsgiUtil;
import org.apache.sling.jcr.api.SlingRepository;
import org.apache.felix.scr.annotations.Reference;
import org.osgi.service.component.ComponentContext;
import javax.jcr.Session;
import javax.jcr.Node; 
//import org.json.simple.JSONObject;
import java.util.UUID;

//import javax.json.JsonArray; 
import javax.jcr.Session;

//Sling Imports
import org.apache.sling.api.resource.ResourceResolverFactory ; 
import org.apache.sling.api.resource.ResourceResolver; 
import org.apache.sling.api.resource.Resource; 

//Adobe CQ Workflow APIs
import com.day.cq.workflow.model.WorkflowModel ; 
import com.day.cq.workflow.WorkflowService ; 
import com.day.cq.workflow.WorkflowSession; 
import com.day.cq.workflow.exec.WorkflowData; 


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.json.simple.JSONObject;


 
@SlingServlet(paths="/bin/myWFServlet", methods = "GET", metatype=true)
public class HandleWorkflowData extends org.apache.sling.api.servlets.SlingAllMethodsServlet {
     private static final long serialVersionUID = 2598426539166789515L;
      
   //Inject a Sling ResourceResolverFactory
     @Reference
     private ResourceResolverFactory resolverFactory;
     
     private Session session;
     
     @Reference
     private WorkflowService workflowService;
     
     /** Default log. */
     protected final Logger log = LoggerFactory.getLogger(this.getClass());
     
     
           
     @Override
     protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServerException, IOException {
       
      try
      {
         
          String[] states = {"RUNNING"};
          
          ResourceResolver resourceResolver = resolverFactory.getAdministrativeResourceResolver(null);
            session = resourceResolver.adaptTo(Session.class);
          
            WorkflowSession wfSession = workflowService.getWorkflowSession(session);
            com.day.cq.workflow.exec.Workflow[] wf = wfSession.getWorkflows(states);
            log.info("********************* WORKFLOW COUNT: " + wf.length);
          
          
          
    
       
         
            
            String id = wf[0].getId();
            String state = wf[0].getState();
            WorkflowData wd = wf[0].getWorkflowData();
            String payload = (String) wd.getPayload();
        
            //Encode the submitted form data to JSON
          JSONObject obj=new JSONObject();
          obj.put("id",id);
          obj.put("state",state);
          obj.put("payload",payload);
         
           
             //Get the JSON formatted data    
          String jsonData = obj.toJSONString();
          
             //Return the JSON formatted data
         response.getWriter().write(jsonData);
      }
      catch(Exception e)
      {
          e.printStackTrace();
      }
    }
}