private void updateFavouriteNodes(
      String userName, Type type, Map<PersonFavouriteKey, PersonFavourite> favouriteNodes) {
    PrefKeys prefKeys = getPrefKeys(type);

    Map<String, Serializable> preferences = new HashMap<String, Serializable>(1);

    StringBuilder values = new StringBuilder();
    for (PersonFavourite node : favouriteNodes.values()) {
      NodeRef nodeRef = node.getNodeRef();

      values.append(nodeRef.toString());
      values.append(",");

      // ISO8601 string format: PreferenceService works with strings only for dates it seems
      StringBuilder sb = new StringBuilder(prefKeys.getAlfrescoPrefKey());
      sb.append(nodeRef.toString());
      sb.append(".createdAt");
      String createdAtKey = sb.toString();
      Date createdAt = node.getCreatedAt();
      if (createdAt != null) {
        String createdAtStr = ISO8601DateFormat.format(createdAt);
        preferences.put(createdAtKey, createdAtStr);
      }
    }

    if (values.length() > 1) {
      values.delete(values.length() - 1, values.length());
    }

    preferences.put(prefKeys.getSharePrefKey(), values.toString());
    preferenceService.setPreferences(userName, preferences);
  }
  private Map<QName, Serializable> getAndAssertProperties(NodeRef nodeRef, String versionLabel) {
    assertNotNull("NodeRef of document is NULL!", nodeRef);

    Map<QName, Serializable> properties = nodeService.getProperties(nodeRef);

    assertNotNull(
        ("Properties must not be NULL! NodeRef = '" + nodeRef.toString() + "'"), properties);
    assertFalse(
        ("Version specific properties can't be found! NodeRef = '" + nodeRef.toString() + "'"),
        properties.isEmpty());
    assertEquals(versionLabel, properties.get(ContentModel.PROP_VERSION_LABEL));

    return properties;
  }
  /** @return Returns true if the pattern is present, otherwise false. */
  public boolean like(
      NodeRef nodeRef, QName propertyQName, String sqlLikePattern, boolean includeFTS) {
    if (propertyQName == null) {
      throw new IllegalArgumentException("Property QName is mandatory for the like expression");
    }

    StringBuilder sb = new StringBuilder(sqlLikePattern.length() * 3);

    if (includeFTS) {
      // convert the SQL-like pattern into a Lucene-compatible string
      String pattern =
          SearchLanguageConversion.convertXPathLikeToLucene(sqlLikePattern.toLowerCase());

      // build Lucene search string specific to the node
      sb = new StringBuilder();
      sb.append("+ID:\"").append(nodeRef.toString()).append("\" +(");
      // FTS or attribute matches
      if (includeFTS) {
        sb.append("TEXT:(").append(pattern).append(") ");
      }
      if (propertyQName != null) {
        sb.append(" @")
            .append(
                SearchLanguageConversion.escapeLuceneQuery(
                    QName.createQName(
                            propertyQName.getNamespaceURI(),
                            ISO9075.encode(propertyQName.getLocalName()))
                        .toString()))
            .append(":(")
            .append(pattern)
            .append(")");
      }
      sb.append(")");

      ResultSet resultSet = null;
      try {
        resultSet = this.query(nodeRef.getStoreRef(), "lucene", sb.toString());
        boolean answer = resultSet.length() > 0;
        return answer;
      } finally {
        if (resultSet != null) {
          resultSet.close();
        }
      }
    } else {
      // convert the SQL-like pattern into a Lucene-compatible string
      String pattern =
          SearchLanguageConversion.convertXPathLikeToRegex(sqlLikePattern.toLowerCase());

      Serializable property = nodeService.getProperty(nodeRef, propertyQName);
      if (property == null) {
        return false;
      } else {
        String propertyString =
            DefaultTypeConverter.INSTANCE.convert(
                String.class, nodeService.getProperty(nodeRef, propertyQName));
        return propertyString.toLowerCase().matches(pattern);
      }
    }
  }
  /**
   * @see
   *     org.alfresco.service.cmr.coci.CheckOutCheckInService#getWorkingCopy(org.alfresco.service.cmr.repository.NodeRef)
   */
  public NodeRef getWorkingCopy(NodeRef nodeRef) {
    NodeRef workingCopy = null;

    // Do a search to find the working copy document
    ResultSet resultSet = null;

    try {
      resultSet =
          this.searchService.query(
              nodeRef.getStoreRef(),
              SearchService.LANGUAGE_LUCENE,
              "+ASPECT:\""
                  + ContentModel.ASPECT_WORKING_COPY.toString()
                  + "\" +@\\{http\\://www.alfresco.org/model/content/1.0\\}"
                  + ContentModel.PROP_COPY_REFERENCE.getLocalName()
                  + ":\""
                  + nodeRef.toString()
                  + "\"");
      if (resultSet.getNodeRefs().size() != 0) {
        workingCopy = resultSet.getNodeRef(0);
      }
    } finally {
      if (resultSet != null) {
        resultSet.close();
      }
    }

    return workingCopy;
  }
Example #5
0
  /* (non-Javadoc)
   * @see org.alfresco.service.cmr.view.Exporter#startNode(org.alfresco.service.cmr.repository.NodeRef)
   */
  public void startNode(NodeRef nodeRef) {
    try {
      AttributesImpl attrs = new AttributesImpl();

      Path path = nodeService.getPath(nodeRef);
      if (path.size() > 1) {
        // a child name does not exist for root
        Path.ChildAssocElement pathElement = (Path.ChildAssocElement) path.last();
        QName childQName = pathElement.getRef().getQName();
        attrs.addAttribute(
            NamespaceService.REPOSITORY_VIEW_1_0_URI,
            CHILDNAME_LOCALNAME,
            CHILDNAME_QNAME.toPrefixString(),
            null,
            toPrefixString(childQName));
      }

      QName type = nodeService.getType(nodeRef);
      contentHandler.startElement(
          type.getNamespaceURI(), type.getLocalName(), toPrefixString(type), attrs);
    } catch (SAXException e) {
      throw new ExporterException(
          "Failed to process start node event - node ref " + nodeRef.toString(), e);
    }
  }
 /**
  * @param task
  * @return
  */
 private Object getPackageItemValues(WorkflowTask task) {
   List<NodeRef> items = workflowService.getPackageContents(task.getId());
   ArrayList<String> results = new ArrayList<String>(items.size());
   for (NodeRef item : items) {
     results.add(item.toString());
   }
   return results;
 }
Example #7
0
 /* (non-Javadoc)
  * @see org.alfresco.service.cmr.view.Exporter#endACL(org.alfresco.service.cmr.repository.NodeRef)
  */
 public void endACL(NodeRef nodeRef) {
   try {
     contentHandler.endElement(
         ACL_QNAME.getNamespaceURI(), ACL_QNAME.getLocalName(), toPrefixString(ACL_QNAME));
   } catch (SAXException e) {
     throw new ExporterException(
         "Failed to process end ACL event - node ref " + nodeRef.toString());
   }
 }
Example #8
0
  private Map<String, String> buildArgs(
      Map<String, String> properties, NodeRef inviter, NodeRef invitee) {
    String params = buildUrlParamString(properties);
    String serverPath = properties.get(wfVarServerPath);
    String acceptLink = serverPath + properties.get(wfVarAcceptUrl) + params;
    String rejectLink = serverPath + properties.get(wfVarRejectUrl) + params;

    Map<String, String> args = new HashMap<String, String>();
    args.put("inviteePersonRef", invitee.toString());
    args.put("inviterPersonRef", inviter.toString());
    args.put("siteName", getSiteName(properties));
    args.put("inviteeSiteRole", getRoleName(properties));
    args.put("inviteeUserName", properties.get(wfVarInviteeUserName));
    args.put("inviteeGenPassword", properties.get(wfVarInviteeGenPassword));
    args.put("acceptLink", acceptLink);
    args.put("rejectLink", rejectLink);
    return args;
  }
Example #9
0
 /* (non-Javadoc)
  * @see org.alfresco.service.cmr.view.Exporter#endNode(org.alfresco.service.cmr.repository.NodeRef)
  */
 public void endNode(NodeRef nodeRef) {
   try {
     QName type = nodeService.getType(nodeRef);
     contentHandler.endElement(type.getNamespaceURI(), type.getLocalName(), toPrefixString(type));
   } catch (SAXException e) {
     throw new ExporterException(
         "Failed to process end node event - node ref " + nodeRef.toString(), e);
   }
 }
Example #10
0
  public List<Folder> getFolders() {
    List<Folder> folders = new ArrayList<>();

    NodeRef rootFolder = repository.getRootHome();

    // for (rootFolder.children)

    folders.add(new Folder(rootFolder.toString()));
    folders.add(new Folder("fofolder"));

    return folders;
  }
 private void processTemplate(
     RenderingContext context, NodeRef templateNode, Object model, Writer out) {
   String templateType = getTemplateType();
   String template = context.getCheckedParam(PARAM_TEMPLATE, String.class);
   if (template != null) {
     templateService.processTemplateString(templateType, template, model, out);
   } else if (templateNode != null) {
     templateService.processTemplate(templateType, templateNode.toString(), model, out);
   } else {
     throwTemplateParamsNotFoundException();
   }
 }
Example #12
0
 /* (non-Javadoc)
  * @see org.alfresco.service.cmr.view.Exporter#endAspect(org.alfresco.service.cmr.repository.NodeRef, org.alfresco.service.namespace.QName)
  */
 public void endAspect(NodeRef nodeRef, QName aspect) {
   try {
     contentHandler.endElement(
         aspect.getNamespaceURI(), aspect.getLocalName(), toPrefixString(aspect));
   } catch (SAXException e) {
     throw new ExporterException(
         "Failed to process end aspect event - node ref "
             + nodeRef.toString()
             + "; aspect "
             + toPrefixString(aspect),
         e);
   }
 }
  /** @return Returns true if the pattern is present, otherwise false. */
  public boolean contains(
      NodeRef nodeRef,
      QName propertyQName,
      String googleLikePattern,
      SearchParameters.Operator defaultOperator) {
    ResultSet resultSet = null;
    try {
      // build Lucene search string specific to the node
      StringBuilder sb = new StringBuilder();
      sb.append("+ID:\"")
          .append(nodeRef.toString())
          .append("\" +(TEXT:(")
          .append(googleLikePattern.toLowerCase())
          .append(") ");
      if (propertyQName != null) {
        sb.append(" OR @")
            .append(
                SearchLanguageConversion.escapeLuceneQuery(
                    QName.createQName(
                            propertyQName.getNamespaceURI(),
                            ISO9075.encode(propertyQName.getLocalName()))
                        .toString()));
        sb.append(":(").append(googleLikePattern.toLowerCase()).append(")");
      } else {
        for (QName key : nodeService.getProperties(nodeRef).keySet()) {
          sb.append(" OR @")
              .append(
                  SearchLanguageConversion.escapeLuceneQuery(
                      QName.createQName(key.getNamespaceURI(), ISO9075.encode(key.getLocalName()))
                          .toString()));
          sb.append(":(").append(googleLikePattern.toLowerCase()).append(")");
        }
      }
      sb.append(")");

      SearchParameters sp = new SearchParameters();
      sp.setLanguage(SearchService.LANGUAGE_LUCENE);
      sp.setQuery(sb.toString());
      sp.setDefaultOperator(defaultOperator);
      sp.addStore(nodeRef.getStoreRef());

      resultSet = this.query(sp);
      boolean answer = resultSet.length() > 0;
      return answer;
    } finally {
      if (resultSet != null) {
        resultSet.close();
      }
    }
  }
Example #14
0
  /* (non-Javadoc)
   * @see org.alfresco.service.cmr.view.Exporter#permission(org.alfresco.service.cmr.repository.NodeRef, org.alfresco.service.cmr.security.AccessPermission)
   */
  public void permission(NodeRef nodeRef, AccessPermission permission) {
    try {
      // output access control entry
      AttributesImpl attrs = new AttributesImpl();
      attrs.addAttribute(
          NamespaceService.REPOSITORY_VIEW_1_0_URI,
          ACCESS_LOCALNAME,
          ACCESS_QNAME.toPrefixString(),
          null,
          permission.getAccessStatus().toString());
      contentHandler.startElement(
          ACE_QNAME.getNamespaceURI(), ACE_QNAME.getLocalName(), toPrefixString(ACE_QNAME), attrs);

      // output authority
      contentHandler.startElement(
          AUTHORITY_QNAME.getNamespaceURI(),
          AUTHORITY_QNAME.getLocalName(),
          toPrefixString(AUTHORITY_QNAME),
          EMPTY_ATTRIBUTES);
      String authority = permission.getAuthority();
      contentHandler.characters(authority.toCharArray(), 0, authority.length());
      contentHandler.endElement(
          AUTHORITY_QNAME.getNamespaceURI(),
          AUTHORITY_QNAME.getLocalName(),
          toPrefixString(AUTHORITY_QNAME));

      // output permission
      contentHandler.startElement(
          PERMISSION_QNAME.getNamespaceURI(),
          PERMISSION_QNAME.getLocalName(),
          toPrefixString(PERMISSION_QNAME),
          EMPTY_ATTRIBUTES);
      String strPermission = permission.getPermission();
      contentHandler.characters(strPermission.toCharArray(), 0, strPermission.length());
      contentHandler.endElement(
          PERMISSION_QNAME.getNamespaceURI(),
          PERMISSION_QNAME.getLocalName(),
          toPrefixString(PERMISSION_QNAME));

      // end access control entry
      contentHandler.endElement(
          ACE_QNAME.getNamespaceURI(), ACE_QNAME.getLocalName(), toPrefixString(ACE_QNAME));
    } catch (SAXException e) {
      throw new ExporterException(
          "Failed to process permission event - node ref "
              + nodeRef.toString()
              + "; permission "
              + permission);
    }
  }
  public void testBasicCommitContent() throws Exception {
    startNewTransaction();
    TransferManifestNormalNode node = null;

    try {
      String transferId = ftTransferReceiver.start("1234", true, ftTransferReceiver.getVersion());

      try {
        node = createContentNode(companytHome, "firstNode.txt");
        staticNodes.add(node);
        // set the root
        NodeRef parentRef = node.getPrimaryParentAssoc().getParentRef();

        String snapshot = createSnapshot(staticNodes, false);
        assertEquals(parentRef, this.companytHome);
        ftTransferReceiver.setFileTransferRootNodeFileFileSystem(parentRef.toString());
        ftTransferReceiver.saveSnapshot(
            transferId, new ByteArrayInputStream(snapshot.getBytes("UTF-8")));
        ftTransferReceiver.saveContent(
            transferId, node.getUuid(), new ByteArrayInputStream(dummyContentBytes));
        ftTransferReceiver.commit(transferId);

      } catch (Exception ex) {
        ftTransferReceiver.end(transferId);
        throw ex;
      }
    } finally {
      endTransaction();
    }
    // check that the temporary folder where orphan are put in do not exist anymore
    File tempFolder =
        new File(ftTransferReceiver.getDefaultReceivingroot() + "/" + "T_V_R_1234432123478");
    assertFalse(tempFolder.exists());
    // check that content exist
    // get the name of the node
    String nodeName = (String) node.getProperties().get(ContentModel.PROP_NAME);
    File transferedNode = new File(ftTransferReceiver.getDefaultReceivingroot() + "/" + nodeName);
    assertTrue(transferedNode.exists());
    // check content itself
    byte byteArray[] = readBytesFromFile(transferedNode);
    // transform to string
    ByteArrayOutputStream bs = new ByteArrayOutputStream();

    bs.write(byteArray, 0, byteArray.length);
    String content = bs.toString();
    assertEquals(content, dummyContent);
  }
  /*
   * Extract favourite nodes of the given type from the comma-separated list in "nodes".
   */
  private Map<PersonFavouriteKey, PersonFavourite> extractFavouriteNodes(
      String userName, Type type, String nodes) {
    PrefKeys prefKeys = getPrefKeys(type);
    Map<PersonFavouriteKey, PersonFavourite> favouriteNodes =
        new HashMap<PersonFavouriteKey, PersonFavourite>();

    StringTokenizer st = new StringTokenizer(nodes, ",");
    while (st.hasMoreTokens()) {
      String nodeRefStr = st.nextToken();
      nodeRefStr = nodeRefStr.trim();
      if (!NodeRef.isNodeRef((String) nodeRefStr)) {
        continue;
      }

      NodeRef nodeRef = new NodeRef((String) nodeRefStr);

      if (!nodeService.exists(nodeRef)) {
        continue;
      }

      if (permissionService.hasPermission(nodeRef, PermissionService.READ_PROPERTIES)
          == AccessStatus.DENIED) {
        continue;
      }

      // get createdAt for this favourited node
      // use ISO8601
      StringBuilder builder = new StringBuilder(prefKeys.getAlfrescoPrefKey());
      builder.append(nodeRef.toString());
      builder.append(".createdAt");
      String prefKey = builder.toString();
      String createdAtStr = (String) preferenceService.getPreference(userName, prefKey);
      Date createdAt = (createdAtStr != null ? ISO8601DateFormat.parse(createdAtStr) : null);

      String name = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_NAME);

      PersonFavourite personFavourite =
          new PersonFavourite(userName, nodeRef, type, name, createdAt);
      PersonFavouriteKey key = personFavourite.getKey();
      favouriteNodes.put(key, personFavourite);
    }

    return favouriteNodes;
  }
Example #17
0
  /* (non-Javadoc)
   * @see org.alfresco.service.cmr.view.Exporter#startReference(org.alfresco.service.cmr.repository.NodeRef, org.alfresco.service.namespace.QName)
   */
  public void startReference(NodeRef nodeRef, QName childName) {
    try {
      // determine format of reference e.g. node or path based
      ReferenceType referenceFormat = referenceType;
      if (nodeRef.equals(nodeService.getRootNode(nodeRef.getStoreRef()))) {
        referenceFormat = ReferenceType.PATHREF;
      }

      // output reference
      AttributesImpl attrs = new AttributesImpl();
      if (referenceFormat.equals(ReferenceType.PATHREF)) {
        Path path = createPath(context.getExportParent(), context.getExportParent(), nodeRef);
        attrs.addAttribute(
            NamespaceService.REPOSITORY_VIEW_1_0_URI,
            PATHREF_LOCALNAME,
            PATHREF_QNAME.toPrefixString(),
            null,
            path.toPrefixString(namespaceService));
      } else {
        attrs.addAttribute(
            NamespaceService.REPOSITORY_VIEW_1_0_URI,
            NODEREF_LOCALNAME,
            NODEREF_QNAME.toPrefixString(),
            null,
            nodeRef.toString());
      }
      if (childName != null) {
        attrs.addAttribute(
            NamespaceService.REPOSITORY_VIEW_1_0_URI,
            CHILDNAME_LOCALNAME,
            CHILDNAME_QNAME.toPrefixString(),
            null,
            childName.toPrefixString(namespaceService));
      }
      contentHandler.startElement(
          REFERENCE_QNAME.getNamespaceURI(),
          REFERENCE_LOCALNAME,
          toPrefixString(REFERENCE_QNAME),
          attrs);
    } catch (SAXException e) {
      throw new ExporterException("Failed to process start reference", e);
    }
  }
Example #18
0
 /* (non-Javadoc)
  * @see org.alfresco.service.cmr.view.Exporter#startACL(org.alfresco.service.cmr.repository.NodeRef)
  */
 public void startACL(NodeRef nodeRef) {
   try {
     AttributesImpl attrs = new AttributesImpl();
     boolean inherit = permissionService.getInheritParentPermissions(nodeRef);
     if (!inherit) {
       attrs.addAttribute(
           NamespaceService.REPOSITORY_VIEW_1_0_URI,
           INHERITPERMISSIONS_LOCALNAME,
           INHERITPERMISSIONS_QNAME.toPrefixString(),
           null,
           "false");
     }
     contentHandler.startElement(
         ACL_QNAME.getNamespaceURI(), ACL_QNAME.getLocalName(), toPrefixString(ACL_QNAME), attrs);
   } catch (SAXException e) {
     throw new ExporterException(
         "Failed to process start ACL event - node ref " + nodeRef.toString());
   }
 }
  private CMISRendition createRendition(NodeRef nodeRef, String thumbnailName, String kind) {
    ThumbnailDefinition details =
        thumbnailService.getThumbnailRegistry().getThumbnailDefinition(thumbnailName);
    NodeRef thumbnailNodeRef =
        thumbnailService.createThumbnail(
            nodeRef,
            ContentModel.PROP_CONTENT,
            details.getMimetype(),
            details.getTransformationOptions(),
            details.getName());

    CMISRenditionImpl rendition = new CMISRenditionImpl();
    rendition.setStreamId(thumbnailNodeRef.toString());
    rendition.setKind(kind);
    rendition.setMimeType(details.getMimetype());
    if (details.getTransformationOptions() instanceof ImageTransformationOptions) {
      ImageTransformationOptions imageOptions =
          (ImageTransformationOptions) details.getTransformationOptions();
      rendition.setWidth(imageOptions.getResizeOptions().getWidth());
      rendition.setHeight(imageOptions.getResizeOptions().getHeight());
    }

    return rendition;
  }
Example #20
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);
  }
  /**
   * 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);
    }
  }
Example #22
0
  public void testMNT11660() throws Exception {
    FormUIGet formUIGet =
        (FormUIGetExtend) ctx.getBean("webscript.org.alfresco.test.components.form.form.get");
    assertNotNull("'FormUIGetExtend' bean for test is null.", formUIGet);

    ConfigSource configSource = new ClassPathConfigSource("test-config-custom-forms.xml");
    XMLConfigService svc = new XMLConfigService(configSource);
    svc.initConfig();

    formUIGet.setConfigService(svc);

    GetRequest requestWithAspect =
        new GetRequest(
            "/test/components/form?htmlid=template_default-formContainer&itemKind=node&itemId="
                + folderWithAspect.toString()
                + "&formId=null&mode=view");
    Response rspFormWithAspect =
        server.submitRequest(
            requestWithAspect.getMethod(),
            requestWithAspect.getFullUri(),
            requestWithAspect.getHeaders(),
            requestWithAspect.getBody(),
            requestWithAspect.getEncoding(),
            requestWithAspect.getType());

    assertEquals(
        "The status of response is " + rspFormWithAspect.getStatus(),
        200,
        rspFormWithAspect.getStatus());

    String contentWithAspect = rspFormWithAspect.getContentAsString();
    log.info(
        "Response form for node with dublincore aspect status is "
            + rspFormWithAspect.getStatus()
            + " content is "
            + contentWithAspect);
    assertNotNull("Response content for 'contentWithAspect' is null", contentWithAspect);
    assertTrue(
        "Return the following content: " + contentWithAspect, contentWithAspect.contains("My Set"));

    GetRequest requestWithoutAspect =
        new GetRequest(
            "/test/components/form?htmlid=template_default-formContainer&itemKind=node&itemId="
                + folderWithoutAspect.toString()
                + "&formId=null&mode=view");
    Response rspFormWithoutAspect =
        server.submitRequest(
            requestWithoutAspect.getMethod(),
            requestWithoutAspect.getFullUri(),
            requestWithoutAspect.getHeaders(),
            requestWithoutAspect.getBody(),
            requestWithoutAspect.getEncoding(),
            requestWithoutAspect.getType());

    assertEquals(
        "The status of response is " + rspFormWithoutAspect.getStatus(),
        200,
        rspFormWithoutAspect.getStatus());

    String contentWithoutAspect = rspFormWithoutAspect.getContentAsString();
    log.info(
        "Response form for node without aspect status is "
            + rspFormWithoutAspect.getStatus()
            + " content is "
            + contentWithoutAspect);
    assertNotNull("Response content for 'contentWithoutAspect' is null", contentWithoutAspect);
    assertFalse(
        "Return the following content: " + contentWithoutAspect,
        contentWithoutAspect.contains("My Set"));
  }
Example #23
0
  @SuppressWarnings("unchecked")
  @Override
  public Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    String reqContentAsString;
    try {
      reqContentAsString = req.getContent().getContent();
    } catch (IOException iox) {
      throw new WebScriptException(
          Status.STATUS_BAD_REQUEST, "Could not read content from req.", iox);
    }

    String actionName = null;
    List<NodeRef> targetNodeRefs = null;
    Map<String, Serializable> actionParams = new HashMap<String, Serializable>(3);

    try {
      JSONObject jsonObj = new JSONObject(new JSONTokener(reqContentAsString));

      // Get the action name
      if (jsonObj.has(PARAM_NAME) == true) {
        actionName = jsonObj.getString(PARAM_NAME);
      }

      // Get the target references
      if (jsonObj.has(PARAM_NODE_REF) == true) {
        NodeRef nodeRef = new NodeRef(jsonObj.getString(PARAM_NODE_REF));
        targetNodeRefs = new ArrayList<NodeRef>(1);
        targetNodeRefs.add(nodeRef);
      }
      if (jsonObj.has(PARAM_NODE_REFS) == true) {
        JSONArray jsonArray = jsonObj.getJSONArray(PARAM_NODE_REFS);
        if (jsonArray.length() != 0) {
          targetNodeRefs = new ArrayList<NodeRef>(jsonArray.length());
          for (int i = 0; i < jsonArray.length(); i++) {
            NodeRef nodeRef = new NodeRef(jsonArray.getString(i));
            targetNodeRefs.add(nodeRef);
          }
        }
      }

      // params are optional.
      if (jsonObj.has(PARAM_PARAMS)) {
        JSONObject paramsObj = jsonObj.getJSONObject(PARAM_PARAMS);
        for (Iterator iter = paramsObj.keys(); iter.hasNext(); ) {
          Object nextKey = iter.next();
          String nextKeyString = (String) nextKey;
          Object nextValue = paramsObj.get(nextKeyString);

          // Check for date values
          if (nextValue instanceof JSONObject) {
            if (((JSONObject) nextValue).has("iso8601") == true) {
              String dateStringValue = ((JSONObject) nextValue).getString("iso8601");
              nextValue = ISO8601DateFormat.parse(dateStringValue);
            }
          }

          actionParams.put(nextKeyString, (Serializable) nextValue);
        }
      }
    } catch (JSONException exception) {
      throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Unable to parse request JSON.");
    }

    // validate input: check for mandatory params.
    // Some RM actions can be posted without a nodeRef.
    if (actionName == null) {
      throw new WebScriptException(
          Status.STATUS_BAD_REQUEST, "A mandatory parameter has not been provided in URL");
    }

    // Check that all the nodes provided exist and build report string
    StringBuffer targetNodeRefsString = new StringBuffer(30);
    boolean firstTime = true;
    for (NodeRef targetNodeRef : targetNodeRefs) {
      if (nodeService.exists(targetNodeRef) == false) {
        throw new WebScriptException(
            Status.STATUS_NOT_FOUND,
            "The targetNode does not exist (" + targetNodeRef.toString() + ")");
      }

      // Build the string
      if (firstTime == true) {
        firstTime = false;
      } else {
        targetNodeRefsString.append(", ");
      }
      targetNodeRefsString.append(targetNodeRef.toString());
    }

    // Proceed to execute the specified action on the specified node.
    if (logger.isDebugEnabled()) {
      StringBuilder msg = new StringBuilder();
      msg.append("Executing Record Action ")
          .append(actionName)
          .append(", (")
          .append(targetNodeRefsString.toString())
          .append("), ")
          .append(actionParams);
      logger.debug(msg.toString());
    }

    Map<String, Object> model = new HashMap<String, Object>();
    if (targetNodeRefs.isEmpty()) {
      RecordsManagementActionResult result =
          this.rmActionService.executeRecordsManagementAction(actionName, actionParams);
      if (result.getValue() != null) {
        model.put("result", result.getValue().toString());
      }
    } else {
      Map<NodeRef, RecordsManagementActionResult> resultMap =
          this.rmActionService.executeRecordsManagementAction(
              targetNodeRefs, actionName, actionParams);
      Map<String, String> results = new HashMap<String, String>(resultMap.size());
      for (NodeRef nodeRef : resultMap.keySet()) {
        Object value = resultMap.get(nodeRef).getValue();
        if (value != null) {
          results.put(nodeRef.toString(), resultMap.get(nodeRef).getValue().toString());
        }
      }
      model.put("results", results);
    }

    model.put(
        "message",
        "Successfully queued action [" + actionName + "] on " + targetNodeRefsString.toString());

    return model;
  }