Expand my Community achievements bar.

Guidelines for the Responsible Use of Generative AI in the Experience Cloud Community.
SOLVED

Capturing workflow comments from previous step to be sent as email notification to next participant step user.

Avatar

Level 2

Capturing workflow  comments from previous step to be sent as email notification to next participant step user.

My Code is as below. I am always getting the workflow comments from start.

My requirement is  : Once first participant comment has been passed to the next participant step then this step shoudl be skiped to capture next steps comments to following participant step user.

My Workflow is with multiple participant steps attached  along with this question.

My Custom Workflow code is Pasted below.

Your help in this regard is really helpfull.

 

CODE:

 

package au.com.****.workflow;

   
//This is a component so it can provide or consume services
@Component
   
    
@Service
  
@Properties({
    @Property(name = Constants.SERVICE_DESCRIPTION, value = "Send Email workflow process implementation."),
    @Property(name = Constants.SERVICE_VENDOR, value = "BTES"),
    @Property(name = "process.label", value = "Send Email Workflow Process") })
public class SendEmailWorkProcess implements WorkflowProcess {


    /**
     * Default log.
     */
    protected final Logger log = LoggerFactory.getLogger(SendEmailWorkProcess.class);
    private static final String DEFAULT_CHARSET = "utf-8";

    /**
     * resource resolver factory.
     */
    @Reference
    private ResourceResolverFactory resourceResolverFactory;

 

    @Reference(policy = ReferencePolicy.STATIC)
    private ResourceResolverFactory resolverFactory;

    //Inject a MessageGatewayService
    @Reference
    private MessageGatewayService messageGatewayService;
    private String someproperty = "";
    private String currentassignee = "";

    public void execute(WorkItem item, WorkflowSession wfsession, MetaDataMap metaData) throws WorkflowException {

 

        MetaDataMap workflowMetaDataMap = item.getWorkflowData().getMetaDataMap();
        Node submitNode = null;
        ResourceResolver resolver;
        try {
            resolver = resourceResolverFactory.getResourceResolver(Collections.singletonMap("user.jcr.session", (Object) wfsession.getSession()));
        } catch (final Exception e) {
            throw new com.day.cq.workflow.WorkflowException("could not get resource resolver", e);
        }

        try {
            log.info("Here in execute method of SendEmailWorkProcess");    //ensure that the execute method is invoked


            HistoryItem previousHistoryItem;
            log.info("SendEmailWorkProcess 1");    //ensure that the execute method is invoke

            String stepType;

            log.info("SendEmailWorkProcess 2");    //ensure that the execute method is invoked

            List<HistoryItem> history = wfsession.getHistory(item.getWorkflow());
            log.info("SendEmailWorkProcess  "+history.toArray().length);    //ensure that the execute method is invoked

            Iterator<HistoryItem> historyIterator = history.iterator();


            while (historyIterator.hasNext()) {

                previousHistoryItem = historyIterator.next();

                stepType = previousHistoryItem.getWorkItem().getNode().getType();

                log.info("\n stepType : " + "\n" + stepType);

                if (stepType != null && stepType.equals(WorkflowNode.TYPE_PARTICIPANT)) {
                    someproperty = previousHistoryItem.getWorkItem().getMetaDataMap().get("comment", String.class);
                    String currentassignee = previousHistoryItem.getWorkItem().getCurrentAssignee();
                    log.info("\n comment : " + "\n" + someproperty);
                    log.info("\n Current Assignee : " + "\n" + previousHistoryItem.getWorkItem().getCurrentAssignee());

                    String template = getEmailTemplate(metaData, wfsession);
                    if (template != null) {
                        // get the string substitutes
                        Map<String, String> valuesMap = new HashMap<String, String>();
                        valuesMap.put("comments", someproperty);
                        valuesMap.put("currentassignee", currentassignee);
                        StrSubstitutor substitutor = new StrSubstitutor(valuesMap);
                        final HtmlEmail email = createEmail(template, substitutor);
                        messageGatewayService.getGateway(HtmlEmail.class).send(email);
                        log.info("Email was sent.");
                    } else {
                        log.warn("Did not send email. No email template defined");
                    }

                    log.info("\nInside send email code section 3...");
                    
                    break;
                } else {

                    log.info("\nNo Step type or someproperty Found...");

                }
                
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private String getEmailTemplate(MetaDataMap workflowMetaDataMap, WorkflowSession session) {
        String template = workflowMetaDataMap.get("template", String.class);
        if (template == null) {
            // load mail template
            String templatePath = workflowMetaDataMap.get("PROCESS_ARGS", String.class);
            log.info("templatePath***************"+templatePath);
            template = loadTemplate(session.getSession(), templatePath);
        }
        log.debug("Loaded template: {}", template);
        return template;
    }


    @SuppressWarnings("rawtypes")
    private HtmlEmail createEmail(final String template, final StrSubstitutor substitutor) {
        final HtmlEmail email = new HtmlEmail();
        try {

            final CountingInputStream in = new CountingInputStream(
                    new ByteArrayInputStream(template.getBytes(DEFAULT_CHARSET)));
            final InternetHeaders iHdrs = new InternetHeaders(in);
            final Map<String, String[]> hdrs = new HashMap<String, String[]>();
            final Enumeration e = iHdrs.getAllHeaders();
            while (e.hasMoreElements()) {
                final Header hdr = (Header) e.nextElement();
                final String name = hdr.getName();
                log.debug("Header: {} = {}", name, hdr.getValue());
                hdrs.put(name, iHdrs.getHeader(name));
            }

            // use the counting stream reader to read the mail body
            String templateBody = template.substring(in.getCount());

            // create email
            email.setCharset(DEFAULT_CHARSET);

            //Set the mail values
            String emailToRecipients = "snayakar@btes.com.au";
            String emailCcRecipients = "reyanshsn@gmail.com";

            log.info("\nInside send email code section 2...");

            email.addTo(emailToRecipients);
            email.addCc(emailCcRecipients);
            email.setSubject("AEM SendEmailWorkProcess Step");
            email.setFrom("snayakar@btes.com.au");

            // set subject
            //final String[] ret = hdrs.remove("subject");
            //final String subject = (ret == null ? "" : ret[0]);
            final String subject = "Fast Publish Workflow Process";
            log.info("Email subject: " + subject);
            if (!StringUtils.isEmpty(subject)) {
                email.setSubject(substitutor.replace(subject));
            }

            // set message body
            templateBody = substitutor.replace(templateBody);
            log.debug("Substituted mail body: {}", templateBody);
            email.setMsg(templateBody);

            IOUtils.closeQuietly(in);
        } catch (Exception e) {
            log.error("Create email: ", e.getMessage());
        }
        return email;
    }


    /**
     * Loads the mail templates from the repository.
     *
     * @param path    mail templates root path
     * @param session session
     * @param charSet The character set
     * @return a reader to the template or <code>null</code> if not valid.
     */
    public String loadTemplate(final Session session, final String path) {
        InputStream is = null;
        try {
            final Node content = session.getNode(path + "/" + JcrConstants.JCR_CONTENT);
            is = content.getProperty(JcrConstants.JCR_DATA).getBinary().getStream();
            final InputStreamReader r = new InputStreamReader(is, DEFAULT_CHARSET);
            final StringWriter w = new StringWriter();
            IOUtils.copy(r, w);
            return w.toString();
        } catch (final Exception e) {
            log.error("Error while loading mail template {}:{}", path, e.toString());
        } finally {
            IOUtils.closeQuietly(is);
        }
        return null;
    }
}

1 Accepted Solution

Avatar

Correct answer by
Employee

Here is a simple snippet that I whipped together to get the previous steps comment from within the execute method:

    public void execute(WorkItem item, WorkflowSession session, MetaDataMap args) throws WorkflowException {
        // Get the current workflow
        List<HistoryItem> historyList = session.getHistory(item.getWorkflow());
        int listSize = historyList.size();
        HistoryItem lastItem = historyList.get(listSize-1);
        String comment = lastItem.getComment();
        if(comment != null && comment.length() > 0) {
            log.debug("Previous Workflow Comment = " + comment);
        } else {
            log.debug("Previous Workflow Comment = null or ''");
        }
    }

View solution in original post

4 Replies

Avatar

Correct answer by
Employee

Here is a simple snippet that I whipped together to get the previous steps comment from within the execute method:

    public void execute(WorkItem item, WorkflowSession session, MetaDataMap args) throws WorkflowException {
        // Get the current workflow
        List<HistoryItem> historyList = session.getHistory(item.getWorkflow());
        int listSize = historyList.size();
        HistoryItem lastItem = historyList.get(listSize-1);
        String comment = lastItem.getComment();
        if(comment != null && comment.length() > 0) {
            log.debug("Previous Workflow Comment = " + comment);
        } else {
            log.debug("Previous Workflow Comment = null or ''");
        }
    }

Avatar

Level 1

And can you help me about set comment to workflow on code ?

Many thanks !

Avatar

Level 1

I resolve this with set metadata "startComment" property !