public String getPersonDescription() {
   ContentService cs =
       Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getContentService();
   ContentReader reader = cs.getReader(this.person.getNodeRef(), ContentModel.PROP_PERSONDESC);
   if (reader != null && reader.exists()) {
     return Utils.stripUnsafeHTMLTags(reader.getContentString()).replace("\r\n", "<p>");
   } else {
     return null;
   }
 }
Ejemplo n.º 2
0
  /**
   * @param actionedUponNodeRef
   * @return
   */
  protected ContentReader getReader(NodeRef nodeRef) {
    // First check that the node is a sub-type of content
    QName typeQName = nodeService.getType(nodeRef);
    if (dictionaryService.isSubClass(typeQName, ContentModel.TYPE_CONTENT) == false) {
      // it is not content, so can't transform
      return null;
    }

    // Get the content reader
    ContentReader contentReader = contentService.getReader(nodeRef, ContentModel.PROP_CONTENT);

    return contentReader;
  }
  /**
   * 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);
    }
  }
  @Override
  protected Map<String, Object> executeImpl(
      SiteInfo site,
      String pageTitle,
      WebScriptRequest req,
      JSONObject json,
      Status status,
      Cache cache) {
    Map<String, Object> model = new HashMap<>();

    // Grab the version string
    Map<String, String> templateVars = req.getServiceMatch().getTemplateVars();
    String versionId = templateVars.get("versionId");
    if (versionId == null) {
      String error = "No versionId supplied";
      throw new WebScriptException(Status.STATUS_BAD_REQUEST, error);
    }

    // Try to find the page
    WikiPageInfo page = wikiService.getWikiPage(site.getShortName(), pageTitle);
    if (page == null) {
      String message = "The Wiki Page could not be found";
      status.setCode(Status.STATUS_NOT_FOUND);
      status.setMessage(message);

      // Return an empty string though
      model.put(PARAM_CONTENT, "");
      return model;
    }

    // Fetch the version history for the node
    VersionHistory versionHistory = null;
    Version version = null;
    try {
      versionHistory = versionService.getVersionHistory(page.getNodeRef());
    } catch (AspectMissingException e) {
    }

    if (versionHistory == null) {
      // Not been versioned, return an empty string
      model.put(PARAM_CONTENT, "");
      return model;
    }

    // Fetch the version by either ID or Label
    Matcher m = LABEL_PATTERN.matcher(versionId);
    if (m.matches()) {
      // It's a version label like 2.3
      try {
        version = versionHistory.getVersion(versionId);
      } catch (VersionDoesNotExistException e) {
      }
    } else {
      // It's a version ID like ed00bac1-f0da-4042-8598-45a0d39cb74d
      // (The ID is usually part of the NodeRef of the frozen node, but we
      //  don't assume to be able to just generate the full NodeRef)
      for (Version v : versionHistory.getAllVersions()) {
        if (v.getFrozenStateNodeRef().getId().equals(versionId)) {
          version = v;
        }
      }
    }

    // Did we find the right version in the end?
    String contents;
    if (version != null) {
      ContentReader reader =
          contentService.getReader(version.getFrozenStateNodeRef(), ContentModel.PROP_CONTENT);
      if (reader != null) {
        contents = reader.getContentString();
      } else {
        // No content was stored in the version history
        contents = "";
      }
    } else {
      // No warning of the missing version, just return an empty string
      contents = "";
    }

    // All done
    model.put(PARAM_CONTENT, contents);
    model.put("page", page);
    model.put("site", site);
    model.put("siteId", site.getShortName());
    return model;
  }
Ejemplo n.º 5
0
  /**
   * Streams the content on a given node's content property to the response of the web script.
   *
   * @param req Request
   * @param res Response
   * @param nodeRef The node reference
   * @param propertyQName The content property name
   * @param attach Indicates whether the content should be streamed as an attachment or not
   * @param attachFileName Optional file name to use when attach is <code>true</code>
   * @throws IOException
   */
  public void streamContent(
      WebScriptRequest req,
      WebScriptResponse res,
      NodeRef nodeRef,
      QName propertyQName,
      boolean attach,
      String attachFileName,
      Map<String, Object> model)
      throws IOException {
    if (logger.isDebugEnabled())
      logger.debug(
          "Retrieving content from node ref "
              + nodeRef.toString()
              + " (property: "
              + propertyQName.toString()
              + ") (attach: "
              + attach
              + ")");

    // TODO
    // This was commented out to accomadate records management permissions.  We need to review how
    // we cope with this
    // hard coded permission checked.

    // check that the user has at least READ_CONTENT access - else redirect to the login page
    //        if (permissionService.hasPermission(nodeRef, PermissionService.READ_CONTENT) ==
    // AccessStatus.DENIED)
    //        {
    //            throw new WebScriptException(HttpServletResponse.SC_FORBIDDEN, "Permission
    // denied");
    //        }

    // check If-Modified-Since header and set Last-Modified header as appropriate
    Date modified = (Date) nodeService.getProperty(nodeRef, ContentModel.PROP_MODIFIED);
    if (modified != null) {
      long modifiedSince = -1;
      String modifiedSinceStr = req.getHeader("If-Modified-Since");
      if (modifiedSinceStr != null) {
        try {
          modifiedSince = dateFormat.parse(modifiedSinceStr).getTime();
        } catch (Throwable e) {
          if (logger.isInfoEnabled())
            logger.info(
                "Browser sent badly-formatted If-Modified-Since header: " + modifiedSinceStr);
        }

        if (modifiedSince > 0L) {
          // round the date to the ignore millisecond value which is not supplied by header
          long modDate = (modified.getTime() / 1000L) * 1000L;
          if (modDate <= modifiedSince) {
            res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            return;
          }
        }
      }
    }

    // get the content reader
    ContentReader reader = contentService.getReader(nodeRef, propertyQName);
    if (reader == null || !reader.exists()) {
      throw new WebScriptException(
          HttpServletResponse.SC_NOT_FOUND,
          "Unable to locate content for node ref "
              + nodeRef
              + " (property: "
              + propertyQName.toString()
              + ")");
    }

    // Stream the content
    streamContentImpl(
        req,
        res,
        reader,
        nodeRef,
        propertyQName,
        attach,
        modified,
        modified == null ? null : String.valueOf(modified.getTime()),
        attachFileName,
        model);
  }
Ejemplo n.º 6
0
  public void testEagerCleanupOnCommit() throws Exception {
    eagerCleaner.setEagerOrphanCleanup(true);
    // Create a new file
    RetryingTransactionCallback<NodeRef> makeContentCallback =
        new RetryingTransactionCallback<NodeRef>() {
          public NodeRef execute() throws Throwable {
            // Create some content
            StoreRef storeRef =
                nodeService.createStore("test", "testEagerCleanupOnCommit-" + GUID.generate());
            NodeRef rootNodeRef = nodeService.getRootNode(storeRef);
            Map<QName, Serializable> properties =
                Collections.singletonMap(ContentModel.PROP_NAME, (Serializable) "test.txt");
            NodeRef contentNodeRef =
                nodeService
                    .createNode(
                        rootNodeRef,
                        ContentModel.ASSOC_CHILDREN,
                        ContentModel.ASSOC_CHILDREN,
                        ContentModel.TYPE_CONTENT,
                        properties)
                    .getChildRef();
            ContentWriter writer =
                contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, true);
            writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
            writer.putContent("INITIAL CONTENT");
            // Done
            return contentNodeRef;
          }
        };
    final NodeRef contentNodeRef =
        transactionService.getRetryingTransactionHelper().doInTransaction(makeContentCallback);
    ContentReader contentReader =
        contentService.getReader(contentNodeRef, ContentModel.PROP_CONTENT);
    assertTrue("Expect content to exist", contentReader.exists());

    // Now update the node, but force a failure i.e. txn rollback
    final List<String> newContentUrls = new ArrayList<String>();
    RetryingTransactionCallback<String> failUpdateCallback =
        new RetryingTransactionCallback<String>() {
          public String execute() throws Throwable {
            ContentWriter writer =
                contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, true);
            writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
            writer.putContent("CONTENT FOR FAIL");
            // This will have updated the metadata, so we can fail now
            newContentUrls.add(writer.getContentUrl());
            // Done
            throw new RuntimeException("FAIL");
          }
        };
    try {
      transactionService.getRetryingTransactionHelper().doInTransaction(failUpdateCallback);
      fail("Transaction was meant to fail");
    } catch (RuntimeException e) {
      if (e.getMessage().equals("FAIL")) {
        // Expected
      } else {
        // Ooops
        throw e;
      }
    }
    // Make sure that the new content is not there
    // The original content must still be there
    assertEquals("Expected one content URL to play with", 1, newContentUrls.size());
    ContentReader readerMissing = contentService.getRawReader(newContentUrls.get(0));
    assertFalse("Newly created content should have been removed.", readerMissing.exists());
    assertTrue("Original content should still be there.", contentReader.exists());

    // Now update the node successfully
    RetryingTransactionCallback<String> successUpdateCallback =
        new RetryingTransactionCallback<String>() {
          public String execute() throws Throwable {
            ContentWriter writer =
                contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, true);
            writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
            writer.putContent("CONTENT FOR SUCCESS");
            // Done
            return writer.getContentUrl();
          }
        };
    String newContentUrl =
        transactionService.getRetryingTransactionHelper().doInTransaction(successUpdateCallback);
    // Make sure that the new content is there
    // The original content was disposed of
    ContentReader contentReaderNew = contentService.getRawReader(newContentUrl);
    assertTrue("Newly created content should be present.", contentReaderNew.exists());
    assertFalse("Original content should have been removed.", contentReader.exists());

    // Now delete the node
    RetryingTransactionCallback<Object> deleteNodeCallback =
        new RetryingTransactionCallback<Object>() {
          public Object execute() throws Throwable {
            nodeService.deleteNode(contentNodeRef);
            // Done
            return null;
          }
        };
    transactionService.getRetryingTransactionHelper().doInTransaction(deleteNodeCallback);
    // The new content must have disappeared
    assertFalse("Newly created content should be removed.", contentReaderNew.exists());
  }