/** this method is called when finish button is pressed applying the sign returned from applet */
  protected String finishImpl(FacesContext context, String outcome) throws Exception {
    SinekartaUtility su = SinekartaUtility.getCurrentInstance();

    // applicao firma ai documenti selezionati

    try {

      // invoking generic sign apply action
      Action documentDigitalSignatureApply =
          su.getActionService()
              .createAction(
                  DocumentDigitalSignatureApply.ACTION_NAME_DOCUMENT_DIGITAL_SIGNATURE_APPLY);
      documentDigitalSignatureApply.setParameterValue(
          DocumentDigitalSignatureApply.PARAM_CLIENT_AREA, su.getDataFromAppletSign());
      try {
        su.getActionService()
            .executeAction(documentDigitalSignatureApply, selectedDocumentNodeParent, false, false);
      } catch (Throwable t) {
        tracer.error("Unable to apply sign to document : " + t.getMessage(), t);
        throw new SignFailedException("Unable to apply sign to document : " + t.getMessage(), t);
      }

      su.getNodeService()
          .setProperty(selectedDocumentNodePdf, ContentModel.PROP_NAME, documentName);

    } catch (SignFailedException e) {
      tracer.error(e.getMessage(), e);
      throw e;
    } catch (Exception e) {
      tracer.error("Unable to apply sign to document : " + e.getMessage(), e);
      throw new SignFailedException("Unable to apply sign to document : " + e.getMessage(), e);
    }

    return outcome;
  }
  /**
   * preparing data to send to applet for sign process
   *
   * @param dataFromApplet encoded64 data received from applet certificate choice
   * @return the data to passa to sign applet
   */
  protected void prepareDataToAppletSign() {

    // calcolo impronte documenti selezionati
    SinekartaUtility su = SinekartaUtility.getCurrentInstance();

    try {

      // copio il file per la conversione
      NodeRef folder = su.getNodeService().getPrimaryParent(selectedDocumentNode).getParentRef();

      FileInfo newFile =
          su.getFileFolderService().copy(selectedDocumentNode, folder, documentNamePdf);

      selectedDocumentNodePdf = newFile.getNodeRef();

      // conversione documento in PDF/A
      Action documentToPDFA =
          su.getActionService().createAction(DocumentToPDFA.ACTION_NAME_DOCUMENT_TO_PDFA);
      try {
        su.getActionService().executeAction(documentToPDFA, selectedDocumentNodePdf, false, false);
      } catch (Throwable t) {
        tracer.error("Unable to execute PDF/A conversion : " + t.getMessage(), t);
        throw new SignFailedException("Unable to execute PDF/A conversion : " + t.getMessage(), t);
      }

      Action digitalSignaturePrepareAndAddDocument =
          su.getActionService()
              .createAction(
                  DocumentDigitalSignaturePrepareAndAddDocument
                      .ACTION_NAME_DOCUMENT_DIGITAL_SIGNATURE_PREPARE_AND_ADD_DOCUMENT);
      digitalSignaturePrepareAndAddDocument.setParameterValue(
          DocumentDigitalSignaturePrepareAndAddDocument.PARAM_SIGN_DESCRIPTION, description);
      digitalSignaturePrepareAndAddDocument.setParameterValue(
          DocumentDigitalSignaturePrepareAndAddDocument.PARAM_SIGN_LOCATION,
          Constants.SIGN_LOCATION_ITALY);
      digitalSignaturePrepareAndAddDocument.setParameterValue(
          DocumentDigitalSignaturePrepareAndAddDocument.PARAM_CLIENT_AREA,
          su.getDataFromAppletCertificateChoice());
      try {
        su.getActionService()
            .executeAction(
                digitalSignaturePrepareAndAddDocument, selectedDocumentNodePdf, false, false);
      } catch (Throwable t) {
        tracer.error("Unable to prepare data for document sign : " + t.getMessage(), t);
        throw new SignFailedException(
            "Unable to prepare data for document sign : " + t.getMessage(), t);
      }
      su.setDataToAppletSign(
          (String)
              digitalSignaturePrepareAndAddDocument.getParameterValue(
                  DocumentDigitalSignaturePrepareAndAddDocument.PARAM_RESULT));
    } catch (SignFailedException e) {
      tracer.error(e.getMessage(), e);
      throw e;
    } catch (Exception e) {
      tracer.error("Unable to calculate document fingerprint.", e);
      throw new SignFailedException(
          "Unable to calculate document fingerprint : " + e.getMessage(), e);
    }
  }
  @Override
  protected void executeImpl(Action action, NodeRef actionedUponNodeRef) {
    if (tracer.isDebugEnabled()) tracer.debug("DocumentAEMarkDocumentAdd action, execution init");

    String markArea = (String) action.getParameterValue(PARAM_MARK_AREA);
    if (markArea == null) {
      tracer.error("no markFileName specified for RCS mark prepare.");
      throw new MarkFailedException("no markFileName specified for RCS mark prepare.");
    }

    MarkDocumentArea markDocumentArea = MarkDocumentArea.fromBase64String(markArea);

    List<MarkDocument> docs = markDocumentArea.getDocuments();
    if (docs == null) {
      docs = new ArrayList<MarkDocument>();
      markDocumentArea.setDocuments(docs);
    }

    MarkDocument doc = new MarkDocument();
    doc.setNodeRefId(actionedUponNodeRef.getId());
    if (!docs.contains(doc)) docs.add(doc);

    action.setParameterValue(PARAM_RESULT, markDocumentArea.toBase64String());

    if (tracer.isDebugEnabled()) tracer.debug("DocumentAEMarkDocumentAdd action, execution end");
  }
Example #4
0
 @Override
 protected void executeImpl(Action action, NodeRef actionedUponNodeRef) {
   if (action.getParameterValue(PARAM).equals(PARAM_VALUE) == false) {
     throw new RuntimeException(
         "Unexpected parameter value.  Expected "
             + PARAM_VALUE
             + " actual "
             + action.getParameterValue(PARAM));
   }
   this.nodeService.addAspect(actionedUponNodeRef, ASPECT_RECORD, null);
 }
  /**
   * @see
   *     org.alfresco.repo.action.executer.TransformActionExecuter#doTransform(org.alfresco.service.cmr.action.Action,
   *     org.alfresco.service.cmr.repository.ContentReader,
   *     org.alfresco.service.cmr.repository.ContentWriter)
   */
  protected void doSplit(
      Action ruleAction, NodeRef actionedUponNodeRef, ContentReader contentReader) {
    Map<String, Object> options = new HashMap<String, Object>(INITIAL_OPTIONS);
    options.put(PARAM_DESTINATION_FOLDER, ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER));
    options.put(PARAM_SPLIT_AT_PAGE, ruleAction.getParameterValue(PARAM_SPLIT_AT_PAGE));

    try {
      this.action(ruleAction, actionedUponNodeRef, contentReader, options);
    } catch (AlfrescoRuntimeException e) {
      throw new AlfrescoRuntimeException(e.getMessage(), e);
    }
  }
  /**
   * @param ref The node representing the current document ref
   * @return Model map for email templates
   */
  @SuppressWarnings("unchecked")
  private Map<String, Object> createEmailTemplateModel(NodeRef ref, Action ruleAction) {
    Map<String, Object> model = new HashMap<String, Object>();

    NodeRef person = personService.getPerson(authService.getCurrentUserName());
    model.put("person", new TemplateNode(person, serviceRegistry, null));
    model.put("document", new TemplateNode(ref, serviceRegistry, null));
    NodeRef parent = serviceRegistry.getNodeService().getPrimaryParent(ref).getParentRef();
    model.put("space", new TemplateNode(parent, serviceRegistry, null));

    // current date/time is useful to have and isn't supplied by FreeMarker
    // by default
    model.put("date", new Date());

    // add custom method objects
    model.put("hasAspect", new HasAspectMethod());
    model.put("message", new I18NMessageMethod());
    model.put("dateCompare", new DateCompareMethod());
    model.put("url", new URLHelper(repoRemoteUrl));

    Map<String, Object> additionalParams =
        (Map<String, Object>) ruleAction.getParameterValue(PARAM_ADDITIONAL_INFO);

    if (additionalParams != null) {
      model.putAll(additionalParams);
    }

    return model;
  }
 /**
  * prepare data to pass to applet for certificate choice
  *
  * @return encoded64 string to pass to applet
  */
 protected void prepareDataToAppletCertificateChoice() {
   // calcolo impronte documenti selezionati
   SinekartaUtility su = SinekartaUtility.getCurrentInstance();
   // conversione documento in PDF/A
   Action digitalSignatureInit =
       su.getActionService()
           .createAction(DocumentDigitalSignatureInit.ACTION_NAME_DOCUMENT_DIGITAL_SIGNATURE_INIT);
   try {
     su.getActionService()
         .executeAction(digitalSignatureInit, selectedDocumentNodeParent, false, false);
   } catch (Throwable t) {
     tracer.error(
         "Unable to initialize digital signature alfresco action service : " + t.getMessage(), t);
     throw new SignFailedException(
         "Unable to initialize digital signature alfresco action service : " + t.getMessage(), t);
   }
   su.setDataToAppletCertificateChoice(
       (String) digitalSignatureInit.getParameterValue(DocumentDigitalSignatureInit.PARAM_RESULT));
 }
  /**
   * @see org.alfresco.repo.action.executer.ActionExecuter#execute(Action,
   *     org.alfresco.service.cmr.repository.NodeRef)
   */
  public void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef) {
    // First ensure that the actionedUponNodeRef is a workingCopy
    if (this.nodeService.exists(actionedUponNodeRef) == true
        && this.nodeService.hasAspect(actionedUponNodeRef, ContentModel.ASPECT_WORKING_COPY)
            == true) {
      // Get the version description
      String description = (String) ruleAction.getParameterValue(PARAM_DESCRIPTION);
      Map<String, Serializable> versionProperties = new HashMap<String, Serializable>(1);
      versionProperties.put(Version.PROP_DESCRIPTION, description);

      // determine whether the change is minor or major
      Boolean minorChange = (Boolean) ruleAction.getParameterValue(PARAM_MINOR_CHANGE);
      if (minorChange != null && minorChange.booleanValue() == false) {
        versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR);
      } else {
        versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MINOR);
      }

      // TODO determine whether the document should be kept checked out

      // Check the node in
      this.cociService.checkin(actionedUponNodeRef, versionProperties);
    }
  }
Example #9
0
 /**
  * Sends an invitation email.
  *
  * @param properties A Map containing the properties needed to send the email.
  */
 public void sendMail(Map<String, String> properties) {
   checkProperties(properties);
   ParameterCheck.mandatory("Properties", properties);
   NodeRef inviter = personService.getPerson(properties.get(wfVarInviterUserName));
   String inviteeName = properties.get(wfVarInviteeUserName);
   NodeRef invitee = personService.getPerson(inviteeName);
   Action mail = actionService.createAction(MailActionExecuter.NAME);
   mail.setParameterValue(MailActionExecuter.PARAM_FROM, getEmail(inviter));
   mail.setParameterValue(MailActionExecuter.PARAM_TO, getEmail(invitee));
   mail.setParameterValue(MailActionExecuter.PARAM_SUBJECT, buildSubject(properties));
   mail.setParameterValue(MailActionExecuter.PARAM_TEMPLATE, getEmailTemplateNodeRef());
   mail.setParameterValue(
       MailActionExecuter.PARAM_TEMPLATE_MODEL,
       (Serializable) buildMailTextModel(properties, inviter, invitee));
   mail.setParameterValue(MailActionExecuter.PARAM_IGNORE_SEND_FAILURE, true);
   actionService.executeAction(mail, getWorkflowPackage(properties));
 }
  /**
   * Send an email message
   *
   * @throws AlfrescoRuntimeExeption
   */
  @SuppressWarnings("unchecked")
  @Override
  protected void executeImpl(final Action ruleAction, final NodeRef actionedUponNodeRef) {
    try {
      MimeMessage message = javaMailSender.createMimeMessage();
      // use the true flag to indicate you need a multipart message
      MimeMessageHelper helper = new MimeMessageHelper(message, true);

      // set recipient
      String to = (String) ruleAction.getParameterValue(PARAM_TO);
      if (to != null && to.length() != 0) {
        helper.setTo(to);
      } else {
        // see if multiple recipients have been supplied - as a list of
        // authorities
        Serializable toManyMails = ruleAction.getParameterValue(PARAM_TO_MANY);
        List<String> recipients = new ArrayList<String>();
        if (toManyMails instanceof List) {
          for (String mailAdress : (List<String>) toManyMails) {
            if (validateAddress(mailAdress)) {
              recipients.add(mailAdress);
            }
          }
        } else if (toManyMails instanceof String) {
          if (validateAddress((String) toManyMails)) {
            recipients.add((String) toManyMails);
          }
        }
        if (recipients != null && recipients.size() > 0) {
          helper.setTo(recipients.toArray(new String[recipients.size()]));
        } else {
          // No recipients have been specified
          logger.error("No recipient has been specified for the mail action");
        }
      }

      // set subject line
      helper.setSubject((String) ruleAction.getParameterValue(PARAM_SUBJECT));

      // See if an email template has been specified
      String text = null;
      NodeRef templateRef = (NodeRef) ruleAction.getParameterValue(PARAM_TEMPLATE);
      if (templateRef != null) {
        // build the email template model
        Map<String, Object> model = createEmailTemplateModel(actionedUponNodeRef, ruleAction);

        // process the template against the model
        text = templateService.processTemplate("freemarker", templateRef.toString(), model);
      }

      // set the text body of the message
      if (text == null) {
        text = (String) ruleAction.getParameterValue(PARAM_TEXT);
      }
      // adding the boolean true to send as HTML
      helper.setText(text, true);
      FileFolderService fileFolderService = serviceRegistry.getFileFolderService();
      /* add inline images.
       * "action.parameters.images is a ,-delimited string, containing a map of images and resources, from this example:
      message.setText("my text <img src='cid:myLogo'>", true);
      message.addInline("myLogo", new ClassPathResource("img/mylogo.gif"));
      so the "images" param can look like this: headerLogo|images/headerLogoNodeRef,footerLogo|footerLogoNodeRef
       */
      String imageList = (String) ruleAction.getParameterValue(PARAM_IMAGES);
      System.out.println(imageList);
      String[] imageMap = imageList.split(","); // comma no spaces
      Map<String, String> images = new HashMap<String, String>();
      for (String image : imageMap) {
        System.out.println(image);
        String map[] = image.split("\\|");
        for (String key : map) {
          System.out.println(key);
        }

        System.out.println(map.length);

        images.put(map[0].trim(), map[1].trim());
        System.out.println(images.size());
        System.out.println("-" + map[0] + " " + map[1] + "-");
      }
      NodeRef imagesFolderNodeRef = (NodeRef) ruleAction.getParameterValue(PARAM_IMAGES_FOLDER);
      if (null != imagesFolderNodeRef) {
        ContentService contentService = serviceRegistry.getContentService();
        System.out.println("mapping");
        for (Map.Entry<String, String> entry : images.entrySet()) {
          System.out.println(
              entry.getKey()
                  + " "
                  + entry.getValue()
                  + " "
                  + ruleAction.getParameterValue(PARAM_IMAGES_FOLDER));
          NodeRef imageFile = fileFolderService.searchSimple(imagesFolderNodeRef, entry.getValue());
          if (null != imageFile) {
            ContentReader reader = contentService.getReader(imageFile, ContentModel.PROP_CONTENT);
            ByteArrayResource resource =
                new ByteArrayResource(IOUtils.toByteArray(reader.getContentInputStream()));
            helper.addInline(entry.getKey(), resource, reader.getMimetype());

          } else {
            logger.error("No image for " + entry.getKey());
          }
        }
      } else {
        logger.error("No images folder");
      }

      // set the from address
      NodeRef person = personService.getPerson(authService.getCurrentUserName());

      String fromActualUser = null;
      if (person != null) {
        fromActualUser = (String) nodeService.getProperty(person, ContentModel.PROP_EMAIL);
      }
      if (fromActualUser != null && fromActualUser.length() != 0) {
        helper.setFrom(fromActualUser);
      } else {
        String from = (String) ruleAction.getParameterValue(PARAM_FROM);
        if (from == null || from.length() == 0) {
          helper.setFrom(fromAddress);
        } else {
          helper.setFrom(from);
        }
      }
      NodeRef attachmentsFolder = (NodeRef) ruleAction.getParameterValue(PARAM_ATTCHMENTS_FOLDER);
      if (attachmentsFolder != null) {

        List<FileInfo> attachFiles = fileFolderService.listFiles(attachmentsFolder);
        if (attachFiles != null && attachFiles.size() > 0) {
          for (FileInfo attachFile : attachFiles) {
            ContentReader contentReader = fileFolderService.getReader(attachFile.getNodeRef());
            ByteArrayResource resource =
                new ByteArrayResource(IOUtils.toByteArray(contentReader.getContentInputStream()));
            helper.addAttachment(attachFile.getName(), resource, contentReader.getMimetype());
          }
        }
      }

      // Send the message unless we are in "testMode"
      javaMailSender.send(message);
    } catch (Exception e) {
      String toUser = (String) ruleAction.getParameterValue(PARAM_TO);
      if (toUser == null) {
        Object obj = ruleAction.getParameterValue(PARAM_TO_MANY);
        if (obj != null) {
          toUser = obj.toString();
        }
      }

      logger.error("Failed to send email to " + toUser, e);

      throw new AlfrescoRuntimeException("Failed to send email to:" + toUser, e);
    }
  }
  /** This is where the action is. */
  @Override
  protected void executeImpl(Action action, NodeRef someRef) {

    if (logger.isDebugEnabled()) logger.debug("enter executeImpl");

    // ReportingRoot reportingRoot = new ReportingRoot(someRef);
    // reportingHelper.initializeReportingRoot(reportingRoot);

    // get the frequency value (hourly, daily, weekly, monthly)
    String executionFrequency = (String) action.getParameterValue(EXECUTION_FREQUENCY);

    if (executionFrequency == null) executionFrequency = "hourly";

    // build a query to find all reportingContainer folders
    // having the executionFrequency, AND executionEnabled
    String query =
        "+@reporting\\:executionFrequency:\""
            + executionFrequency
            + "\" "
            + "+@reporting\\:executionEnabled:true";
    if (logger.isDebugEnabled()) logger.debug("executeImpl query=" + query);

    // build the query and execute. Find all relevant reportingContainers

    ResultSet results =
        searchService.query(
            StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, Constants.QUERYLANGUAGE, query);

    // cycle the resultset
    for (ResultSetRow resultRow : results) {
      NodeRef containerRef = resultRow.getChildAssocRef().getChildRef();

      ReportingContainer reportingContainer = new ReportingContainer(containerRef);
      reportingHelper.initializeReportingContainer(reportingContainer);

      logger.debug("Found container: " + reportingContainer.getName());

      // get its related ReportingRoot
      ReportingRoot reportingRoot =
          new ReportingRoot(reportingHelper.getReportingRoot(containerRef));
      reportingHelper.initializeReportingRoot(reportingRoot);

      // determine if execution of this container is allowed considering
      // the parent ReportingRoot
      if (reportingRoot.isGlobalExecutionEnabled()) {

        // Start a reportingContainerExecuter for the given noderef.
        // Pass the NodeRef of the ReportingRoot since we know who that is.
        Action customAction = actionService.createAction(ReportContainerExecutor.NAME);
        // action.setParameterValue(
        //		ReportContainerExecutor.REPORTING_CONTAINER_NODEREF, containerRef);

        actionService.executeAction(customAction, containerRef);
      } // end if reportingExecturinEnabled()
      {
        logger.warn(
            "Container execution of "
                + reportingContainer.getName()
                + " veto'd by ReportingRoot "
                + reportingRoot.getName());
      }
    } // end for ResultSetRow

    if (logger.isDebugEnabled()) logger.debug("exit executeImpl");
  }
  private void prepareAndSendEmail(final Action ruleAction, final NodeRef actionedUponNodeRef) {
    // Create the mime mail message
    MimeMessagePreparator mailPreparer =
        new MimeMessagePreparator() {
          @SuppressWarnings("unchecked")
          public void prepare(MimeMessage mimeMessage) throws MessagingException {
            if (logger.isDebugEnabled()) {
              logger.debug(ruleAction.getParameterValues());
            }

            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);

            // set header encoding if one has been supplied
            if (headerEncoding != null && headerEncoding.length() != 0) {
              mimeMessage.setHeader("Content-Transfer-Encoding", headerEncoding);
            }

            // set recipient
            String to = (String) ruleAction.getParameterValue(PARAM_TO);
            if (to != null && to.length() != 0) {
              message.setTo(to);
            } else {
              // see if multiple recipients have been supplied - as a list of authorities
              Serializable authoritiesValue = ruleAction.getParameterValue(PARAM_TO_MANY);
              List<String> authorities = null;
              if (authoritiesValue != null) {
                if (authoritiesValue instanceof String) {
                  authorities = new ArrayList<String>(1);
                  authorities.add((String) authoritiesValue);
                } else {
                  authorities = (List<String>) authoritiesValue;
                }
              }

              if (authorities != null && authorities.size() != 0) {
                List<String> recipients = new ArrayList<String>(authorities.size());
                for (String authority : authorities) {
                  AuthorityType authType = AuthorityType.getAuthorityType(authority);
                  if (authType.equals(AuthorityType.USER)) {
                    if (personService.personExists(authority) == true) {
                      NodeRef person = personService.getPerson(authority);
                      String address =
                          (String) nodeService.getProperty(person, ContentModel.PROP_EMAIL);
                      if (address != null && address.length() != 0 && validateAddress(address)) {
                        recipients.add(address);
                      }
                    }
                  } else if (authType.equals(AuthorityType.GROUP)
                      || authType.equals(AuthorityType.EVERYONE)) {
                    // Notify all members of the group
                    Set<String> users;
                    if (authType.equals(AuthorityType.GROUP)) {
                      users =
                          authorityService.getContainedAuthorities(
                              AuthorityType.USER, authority, false);
                    } else {
                      users = authorityService.getAllAuthorities(AuthorityType.USER);
                    }

                    for (String userAuth : users) {
                      if (personService.personExists(userAuth) == true) {
                        NodeRef person = personService.getPerson(userAuth);
                        String address =
                            (String) nodeService.getProperty(person, ContentModel.PROP_EMAIL);
                        if (address != null && address.length() != 0) {
                          recipients.add(address);
                        }
                      }
                    }
                  }
                }

                if (recipients.size() > 0) {
                  message.setTo(recipients.toArray(new String[recipients.size()]));
                } else {
                  // All recipients were invalid
                  throw new MailPreparationException(
                      "All recipients for the mail action were invalid");
                }
              } else {
                // No recipients have been specified
                throw new MailPreparationException(
                    "No recipient has been specified for the mail action");
              }
            }

            // from person
            NodeRef fromPerson = null;
            if (!authService.isCurrentUserTheSystemUser()) {
              fromPerson = personService.getPerson(authService.getCurrentUserName());
            }

            // set subject line
            message.setSubject((String) ruleAction.getParameterValue(PARAM_SUBJECT));

            // See if an email template has been specified
            String text = null;
            NodeRef templateRef = (NodeRef) ruleAction.getParameterValue(PARAM_TEMPLATE);
            if (templateRef != null) {
              Map<String, Object> suppliedModel = null;
              if (ruleAction.getParameterValue(PARAM_TEMPLATE_MODEL) != null) {
                Object m = ruleAction.getParameterValue(PARAM_TEMPLATE_MODEL);
                if (m instanceof Map) {
                  suppliedModel = (Map<String, Object>) m;
                } else {
                  logger.warn(
                      "Skipping unsupported email template model parameters of type "
                          + m.getClass().getName()
                          + " : "
                          + m.toString());
                }
              }

              // build the email template model
              Map<String, Object> model =
                  createEmailTemplateModel(actionedUponNodeRef, suppliedModel, fromPerson);

              // process the template against the model
              text = templateService.processTemplate("freemarker", templateRef.toString(), model);
            }

            // set the text body of the message

            boolean isHTML = false;
            if (text == null) {
              text = (String) ruleAction.getParameterValue(PARAM_TEXT);
            }

            if (text != null) {
              // Note: only simplistic match here - expects <html tag at the start of the text
              String htmlPrefix = "<html";
              if (text.length() >= htmlPrefix.length()
                  && text.substring(0, htmlPrefix.length()).equalsIgnoreCase(htmlPrefix)) {
                isHTML = true;
              }
            } else {
              text = (String) ruleAction.getParameterValue(PARAM_HTML);
              if (text != null) {
                // assume HTML
                isHTML = true;
              }
            }

            if (text != null) {
              message.setText(text, isHTML);
            }

            // set the from address
            String fromActualUser = null;
            if (fromPerson != null) {
              fromActualUser =
                  (String) nodeService.getProperty(fromPerson, ContentModel.PROP_EMAIL);
            }

            if (fromActualUser != null && fromActualUser.length() != 0) {
              message.setFrom(fromActualUser);
            } else {
              String from = (String) ruleAction.getParameterValue(PARAM_FROM);
              if (from == null || from.length() == 0) {
                message.setFrom(fromAddress);
              } else {
                message.setFrom(from);
              }
            }
          }
        };

    try {
      // Send the message unless we are in "testMode"
      if (!testMode) {
        javaMailSender.send(mailPreparer);
      } else {
        try {
          MimeMessage mimeMessage = javaMailSender.createMimeMessage();
          mailPreparer.prepare(mimeMessage);
          lastTestMessage = mimeMessage;
        } catch (Exception e) {
          System.err.println(e);
        }
      }
    } catch (MailException e) {
      String to = (String) ruleAction.getParameterValue(PARAM_TO);
      if (to == null) {
        Object obj = ruleAction.getParameterValue(PARAM_TO_MANY);
        if (obj != null) {
          to = obj.toString();
        }
      }

      // always log the failure
      logger.error("Failed to send email to " + to, e);

      // optionally ignore the throwing of the exception
      Boolean ignoreError = (Boolean) ruleAction.getParameterValue(PARAM_IGNORE_SEND_FAILURE);
      if (ignoreError == null || ignoreError.booleanValue() == false) {
        throw new AlfrescoRuntimeException("Failed to send email to:" + to, e);
      }
    }
  }
 private boolean sendAfterCommit(Action action) {
   Boolean sendAfterCommit = (Boolean) action.getParameterValue(PARAM_SEND_AFTER_COMMIT);
   return sendAfterCommit == null ? false : sendAfterCommit.booleanValue();
 }
  @Override
  protected void executeImpl(Action action, NodeRef actionedUponNodeRef) {

    pdfToolkitService.deletePagesFromPDF(actionedUponNodeRef, action.getParameterValues());
  }
  /**
   * @param reader
   * @param writer
   * @param options
   * @throws Exception
   */
  protected final void action(
      Action ruleAction,
      NodeRef actionedUponNodeRef,
      ContentReader reader,
      Map<String, Object> options) {
    PDDocument pdf = null;
    InputStream is = null;
    File tempDir = null;
    ContentWriter writer = null;

    try {
      // Get the split frequency
      int splitFrequency = 0;

      String splitFrequencyString = options.get(PARAM_SPLIT_AT_PAGE).toString();
      if (!splitFrequencyString.equals("")) {
        try {
          splitFrequency = Integer.valueOf(splitFrequencyString);
        } catch (NumberFormatException e) {
          throw new AlfrescoRuntimeException(e.getMessage(), e);
        }
      }

      // Get contentReader inputStream
      is = reader.getContentInputStream();
      // stream the document in
      pdf = PDDocument.load(is);
      // split the PDF and put the pages in a list
      Splitter splitter = new Splitter();
      // Need to adjust the input value to get the split at the right page
      splitter.setSplitAtPage(splitFrequency - 1);

      // Split the pages
      List<PDDocument> pdfs = splitter.split(pdf);

      // Start page split numbering at
      int page = 1;

      // build a temp dir, name based on the ID of the noderef we are
      // importing
      File alfTempDir = TempFileProvider.getTempDir();
      tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId());
      tempDir.mkdir();

      // FLAG: This is ugly.....get the first PDF.
      PDDocument firstPDF = (PDDocument) pdfs.remove(0);

      int pagesInFirstPDF = firstPDF.getNumberOfPages();

      String lastPage = "";
      String pg = "_pg";

      if (pagesInFirstPDF > 1) {
        pg = "_pgs";
        lastPage = "-" + pagesInFirstPDF;
      }

      String fileNameSansExt = getFilenameSansExt(actionedUponNodeRef, FILE_EXTENSION);
      firstPDF.save(
          tempDir
              + ""
              + File.separatorChar
              + fileNameSansExt
              + pg
              + page
              + lastPage
              + FILE_EXTENSION);

      try {
        firstPDF.close();
      } catch (IOException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
      }

      // FLAG: Like I said: "_UGLY_" ..... and it gets worse
      PDDocument secondPDF = null;

      Iterator<PDDocument> its = pdfs.iterator();

      int pagesInSecondPDF = 0;

      while (its.hasNext()) {
        if (secondPDF != null) {
          // Get the split document and save it into the temp dir with
          // new name
          PDDocument splitpdf = (PDDocument) its.next();

          int pagesInThisPDF = splitpdf.getNumberOfPages();
          pagesInSecondPDF = pagesInSecondPDF + pagesInThisPDF;

          PDFMergerUtility merger = new PDFMergerUtility();
          merger.appendDocument(secondPDF, splitpdf);
          merger.mergeDocuments();

          try {
            splitpdf.close();
          } catch (IOException e) {
            throw new AlfrescoRuntimeException(e.getMessage(), e);
          }

        } else {
          secondPDF = (PDDocument) its.next();

          pagesInSecondPDF = secondPDF.getNumberOfPages();
        }
      }

      if (pagesInSecondPDF > 1) {

        pg = "_pgs";
        lastPage = "-" + (pagesInSecondPDF + pagesInFirstPDF);

      } else {
        pg = "_pg";
        lastPage = "";
      }

      // This is where we should save the appended PDF
      // put together the name and save the PDF
      secondPDF.save(
          tempDir
              + ""
              + File.separatorChar
              + fileNameSansExt
              + pg
              + splitFrequency
              + lastPage
              + FILE_EXTENSION);

      for (File file : tempDir.listFiles()) {
        try {
          if (file.isFile()) {
            // Get a writer and prep it for putting it back into the
            // repo
            NodeRef destinationNode =
                createDestinationNode(
                    file.getName(),
                    (NodeRef) ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER),
                    actionedUponNodeRef);
            writer =
                serviceRegistry
                    .getContentService()
                    .getWriter(destinationNode, ContentModel.PROP_CONTENT, true);

            writer.setEncoding(reader.getEncoding()); // original
            // encoding
            writer.setMimetype(FILE_MIMETYPE);

            // Put it in the repo
            writer.putContent(file);

            // Clean up
            file.delete();
          }
        } catch (FileExistsException e) {
          throw new AlfrescoRuntimeException("Failed to process file.", e);
        }
      }
    } catch (COSVisitorException e) {
      throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (IOException e) {
      throw new AlfrescoRuntimeException(e.getMessage(), e);
    } finally {
      if (pdf != null) {
        try {
          pdf.close();
        } catch (IOException e) {
          throw new AlfrescoRuntimeException(e.getMessage(), e);
        }
      }
      if (is != null) {
        try {
          is.close();
        } catch (IOException e) {
          throw new AlfrescoRuntimeException(e.getMessage(), e);
        }
      }

      if (tempDir != null) {
        tempDir.delete();
      }
    }
  }
  @Override
  protected void executeImpl(Action action, NodeRef actionedUponNodeRef) {
    if (tracer.isDebugEnabled()) tracer.debug("DocumentAcquiring action, execution init");

    // the document has already the documentAcquiring aspect? if yes, nothing to do
    if (nodeService.hasAspect(actionedUponNodeRef, SinekartaModel.ASPECT_QNAME_DOCUMENT_ACQUIRING))
      return;

    // the document has the timestamp mark aspect? if yes, nothing to do
    if (nodeService.hasAspect(actionedUponNodeRef, SinekartaModel.ASPECT_QNAME_TIMESTAMP_MARK))
      return;

    // the node to add is an archive, we don't need any acquire processing
    if (nodeService.getType(actionedUponNodeRef).equals(SinekartaModel.TYPE_QNAME_ARCHIVE)) return;

    // Someone is rendering the document (by ie in share), the document must not be acquired
    // if the document is a child of an acquired document and is not to render, it's a working copy
    // for displaying
    if (nodeService.hasAspect(
        nodeService.getPrimaryParent(actionedUponNodeRef).getParentRef(),
        SinekartaModel.ASPECT_QNAME_DOCUMENT_ACQUIRING)) return; // &&
    // nodeService.hasAspect(actionedUponNodeRef,
    // org.alfresco.model.RenditionModel.ASPECT_HIDDEN_RENDITION))

    Integer documentTypeId = (Integer) action.getParameterValue(PARAM_DOCUMENT_TYPE);
    DocumentType documentType = null;
    if (documentTypeId != null) {
      try {
        documentType = sinekartaDao.getDocumentType(documentTypeId);
      } catch (Exception e) {
        tracer.error("wrong documentType for mark folder prepare.", e);
        throw new DocumentAcquiringException("wrong documentType for mark folder prepare.", e);
      }
    }

    Date documentDate = (Date) action.getParameterValue(PARAM_DOCUMENT_DATE);

    String documentLanguage = (String) action.getParameterValue(PARAM_DOCUMENT_LANGUAGE);

    // getting sinekarta admin user
    String sinekartaAdminUserId =
        NodeTools.getSinekartaAdminUserId(nodeService, searchService, companyHomePath);

    DocumentAcquiringWorker execAsSinekartaAdmin =
        new DocumentAcquiringWorker(
            nodeService,
            contentService,
            actionedUponNodeRef,
            actionService,
            documentType,
            documentDate,
            documentLanguage);

    // running core of action as sinekarta admin
    Boolean result = AuthenticationUtil.runAs(execAsSinekartaAdmin, sinekartaAdminUserId);
    if (!result) {
      tracer.error(
          "document acquiring failed, please verify if the document already exists on archive : "
              + execAsSinekartaAdmin.getKoReason());
      throw new DocumentAcquiringException(
          "document acquiring failed, please verify if the document already exists on archive : "
              + execAsSinekartaAdmin.getKoReason());
    }

    if (tracer.isDebugEnabled()) tracer.debug("DocumentAcquiring action, execution end");
  }
  @SuppressWarnings("unchecked")
  @Override
  protected void executeImpl(Action action, NodeRef actionedUponNodeRef) {
    Boolean isUnpublish = (Boolean) action.getParameterValue(PARAM_UNPUBLISH);
    boolean unpublish = ((isUnpublish != null) && isUnpublish);
    String publishChannelId = (String) action.getParameterValue(PARAM_PUBLISH_CHANNEL_ID);
    String publishChannelName = (String) action.getParameterValue(PARAM_PUBLISH_CHANNEL_NAME);
    String statusUpdate = (String) action.getParameterValue(PARAM_STATUS_UPDATE);
    List<String> statusUpdateChannelNames =
        buildStringList(action.getParameterValue(PARAM_STATUS_UPDATE_CHANNEL_NAMES));
    List<String> statusUpdateChannelIds =
        buildStringList(action.getParameterValue(PARAM_STATUS_UPDATE_CHANNEL_IDS));
    Boolean includeLinkInStatusUpdate =
        (Boolean) action.getParameterValue(PARAM_INCLUDE_LINK_IN_STATUS_UPDATE);
    boolean appendLink = ((includeLinkInStatusUpdate == null) || includeLinkInStatusUpdate);
    Date scheduledTime = (Date) action.getParameterValue(PARAM_SCHEDULED_TIME);
    String comment = (String) action.getParameterValue(PARAM_COMMENT);

    Channel publishChannel =
        publishChannelId == null
            ? channelService.getChannelByName(publishChannelName)
            : channelService.getChannelById(publishChannelId);
    if (publishChannel != null) {
      PublishingDetails details = publishingService.createPublishingDetails();
      details.setPublishChannelId(publishChannel.getId());
      List<NodeRef> nodes = setNodes(actionedUponNodeRef, unpublish, details);
      if (statusUpdateChannelNames != null) {
        for (String statusUpdateChannelName : statusUpdateChannelNames) {
          Channel statusUpdateChannel = channelService.getChannelByName(statusUpdateChannelName);
          if (statusUpdateChannel != null) {
            details.addStatusUpdateChannels(statusUpdateChannel.getId());
          }
        }
      }
      if (statusUpdateChannelIds != null) {
        for (String statusUpdateChannelId : statusUpdateChannelIds) {
          Channel statusUpdateChannel = channelService.getChannelById(statusUpdateChannelId);
          if (statusUpdateChannel != null) {
            details.addStatusUpdateChannels(statusUpdateChannel.getId());
          }
        }
      }
      if (!unpublish && !details.getStatusUpdateChannels().isEmpty()) {
        details.setStatusMessage(statusUpdate);
        if (appendLink) {
          NodeRef nodeToLinkTo =
              (NodeRef) action.getParameterValue(PARAM_NODE_TO_LINK_STATUS_UPDATE_TO);
          if (nodeToLinkTo == null) {
            // No node has been specified explicitly as being the one to link to
            // We'll make an assumption if only one node is being published...
            if (nodes.size() == 1) {
              nodeToLinkTo = nodes.get(0);
            }
          }
          if ((nodeToLinkTo != null) && nodes.contains(nodeToLinkTo)) {
            details.setStatusNodeToLinkTo(nodeToLinkTo);
          }
        }
      }
      if (scheduledTime != null) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(scheduledTime);
        details.setSchedule(cal);
      }
      details.setComment(comment);
      publishingService.scheduleNewEvent(details);
    } else {
      throw new AlfrescoRuntimeException(
          MSG_CHANNEL_NOT_FOUND,
          new Object[] {publishChannelId == null ? publishChannelName : publishChannelId});
    }
  }