Exemple #1
0
  protected void onSetUpInTransaction() throws Exception {
    System.err.println("onSetUpInTransaction");
    super.onSetUpInTransaction();
    this.nodeService = (NodeService) super.applicationContext.getBean("dbNodeService");
    assertNotNull(this.nodeService);
    final FileFolderService fileFolderService =
        (FileFolderService) super.applicationContext.getBean("fileFolderService");
    assertNotNull(fileFolderService);
    this.formsService = (FormsService) super.applicationContext.getBean("FormsService");
    assertNotNull(this.formsService);
    final MutableAuthenticationService authenticationService =
        (MutableAuthenticationService) applicationContext.getBean("authenticationService");
    authenticationService.clearCurrentSecurityContext();
    final MutableAuthenticationDao authenticationDAO =
        (MutableAuthenticationDao) applicationContext.getBean("authenticationDao");

    // Create a workspace that contains the 'live' nodes
    final StoreRef testStoreRef =
        this.nodeService.createStore(
            StoreRef.PROTOCOL_WORKSPACE, "Test_" + System.currentTimeMillis());

    // Get a reference to the root node
    final NodeRef rootNodeRef = this.nodeService.getRootNode(testStoreRef);

    // Create an authenticate the user
    if (!authenticationDAO.userExists(AuthenticationUtil.getAdminUserName())) {
      authenticationService.createAuthentication(
          AuthenticationUtil.getAdminUserName(), "admin".toCharArray());
    }

    TestWithUserUtils.authenticateUser(
        AuthenticationUtil.getAdminUserName(), "admin", rootNodeRef, authenticationService);

    // set up a faces context
    final MockExternalContext ec =
        new MockExternalContext(
            new MockServletContext(), new MockHttpServletRequest(), new MockHttpServletResponse());
    final StaticWebApplicationContext ac = new StaticWebApplicationContext();
    ac.setParent(this.applicationContext);
    this.applicationContext = ac;
    ec.getApplicationMap()
        .put(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.applicationContext);
    new MockFacesContext(ec);

    final FileInfo folderInfo =
        fileFolderService.create(rootNodeRef, "test_form", WCMAppModel.TYPE_FORMFOLDER);
    final HashMap<QName, Serializable> props = new HashMap<QName, Serializable>();
    this.nodeService.addAspect(folderInfo.getNodeRef(), WCMAppModel.ASPECT_FORM, props);
    this.mockForm = new MockForm(folderInfo.getNodeRef(), this.formsService);
  }
 /** Searches for the node or nodes that match the path element for the given parent node */
 private List<NodeRef> getDirectDescendents(NodeRef pathRootNodeRef, String pathElement) {
   if (logger.isDebugEnabled()) {
     logger.debug(
         "Getting direct descendents: \n"
             + "   Path Root: "
             + pathRootNodeRef
             + "\n"
             + "   Path Element: "
             + pathElement);
   }
   List<NodeRef> results = null;
   // if this contains no wildcards, then we can fasttrack it
   if (!WildCard.containsWildcards(pathElement)) {
     // a specific name is required
     NodeRef foundNodeRef = fileFolderService.searchSimple(pathRootNodeRef, pathElement);
     if (foundNodeRef == null) {
       results = Collections.emptyList();
     } else {
       results = Collections.singletonList(foundNodeRef);
     }
   } else {
     // escape for the Lucene syntax search
     String escapedPathElement = SearchLanguageConversion.convertCifsToLucene(pathElement);
     // do the lookup
     List<org.alfresco.service.cmr.model.FileInfo> childInfos =
         fileFolderService.search(pathRootNodeRef, escapedPathElement, false);
     // convert to noderefs
     results = new ArrayList<NodeRef>(childInfos.size());
     for (org.alfresco.service.cmr.model.FileInfo info : childInfos) {
       results.add(info.getNodeRef());
     }
   }
   // done
   return results;
 }
  /**
   * 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
  public NodeRef createNode(
      Resource resource,
      RepositoryLocation targetLocation,
      String encoding,
      String mimetype,
      QName nodeType)
      throws IOException {
    NodeRef rootNode = nodeService.getRootNode(targetLocation.getStoreRef());
    final List<NodeRef> parentNodes =
        searchService.selectNodes(
            rootNode, targetLocation.getPath(), null, namespaceService, false);
    Assert.isTrue(parentNodes.size() == 1, "Target location leads to not 1 unique Node reference");

    final String fileName = resource.getFilename();
    final FileInfo fileInfo = fileFolderService.create(parentNodes.get(0), fileName, nodeType);
    final NodeRef nodeRef = fileInfo.getNodeRef();

    final ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    writer.putContent(resource.getInputStream());

    if (mimetype == null) {
      mimetype = guessMimetype(resource);
    }

    if (encoding == null) {
      encoding = guessEncoding(resource.getInputStream(), mimetype);
    }

    writer.setMimetype(mimetype);
    writer.setEncoding(encoding);

    return nodeRef;
  }
  /**
   * @param ruleAction
   * @param filename
   * @return
   */
  protected NodeRef createDestinationNode(
      String filename, NodeRef destinationParent, NodeRef target) {
    NodeRef destinationNode;
    FileInfo fileInfo =
        fileFolderService.create(destinationParent, filename, ContentModel.TYPE_CONTENT);
    destinationNode = fileInfo.getNodeRef();

    return destinationNode;
  }
  private void setFlags(FileInfo messageFileInfo) throws Exception {
    imapService.setFlags(messageFileInfo, flags, true);
    NodeRef messageNodeRef = messageFileInfo.getNodeRef();
    Map<QName, Serializable> props = nodeService.getProperties(messageNodeRef);

    assertTrue("Can't set SEEN flag", props.containsKey(ImapModel.PROP_FLAG_SEEN));
    assertTrue("Can't set FLAGGED flag", props.containsKey(ImapModel.PROP_FLAG_FLAGGED));
    assertTrue("Can't set ANSWERED flag", props.containsKey(ImapModel.PROP_FLAG_ANSWERED));
    assertTrue("Can't set DELETED flag", props.containsKey(ImapModel.PROP_FLAG_DELETED));
  }
  /**
   * Test attachment extraction with a TNEF message
   *
   * @throws Exception
   */
  public void testAttachmentExtraction() throws Exception {
    AuthenticationUtil.setRunAsUserSystem();
    /** Load a TNEF message */
    ClassPathResource fileResource = new ClassPathResource("imap/test-tnef-message.eml");
    assertNotNull("unable to find test resource test-tnef-message.eml", fileResource);
    InputStream is = new FileInputStream(fileResource.getFile());
    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()), is);

    /** Create a test node containing the message */
    String storePath = "workspace://SpacesStore";
    String companyHomePathInStore = "/app:company_home";
    StoreRef storeRef = new StoreRef(storePath);
    NodeRef storeRootNodeRef = nodeService.getRootNode(storeRef);

    List<NodeRef> nodeRefs =
        searchService.selectNodes(
            storeRootNodeRef, companyHomePathInStore, null, namespaceService, false);
    NodeRef companyHomeNodeRef = nodeRefs.get(0);

    FileInfo f1 =
        fileFolderService.create(
            companyHomeNodeRef, "ImapServiceImplTest", ContentModel.TYPE_FOLDER);
    FileInfo d2 =
        fileFolderService.create(f1.getNodeRef(), "ImapServiceImplTest", ContentModel.TYPE_FOLDER);
    FileInfo f2 =
        fileFolderService.create(
            f1.getNodeRef(), "test-tnef-message.eml", ContentModel.TYPE_CONTENT);

    ContentWriter writer = fileFolderService.getWriter(f2.getNodeRef());
    writer.putContent(new FileInputStream(fileResource.getFile()));

    NodeRef folder = imapService.extractAttachments(f1.getNodeRef(), f2.getNodeRef(), message);
    assertNotNull(folder);

    List<FileInfo> files = fileFolderService.listFiles(folder);
    assertTrue("three files not found", files.size() == 3);
  }
  @Test
  public void canPutFileWithResourceTag() throws ServletException, IOException {
    String fileName = "test_ALF-18821.txt";
    // VtiIfHeaderAction PUT handler expects the file to have already been created (in most cases)
    FileInfo createdFile = fileFolderService.create(docLib, fileName, ContentModel.TYPE_CONTENT);

    request =
        new MockHttpServletRequest(
            "PUT", "/alfresco/" + shortSiteId + "/documentLibrary/" + fileName);
    String fileContent = "This is the test file's content.";
    request.setContent(fileContent.getBytes());
    request.addHeader("If", "(<rt:792589C1-2E8F-410E-BC91-4EF42DA88D3C@00862604462>)");

    dispatcher.service(request, response);

    assertEquals(HttpServletResponse.SC_OK, response.getStatus());
    String retContent = fileFolderService.getReader(createdFile.getNodeRef()).getContentString();
    assertEquals(fileContent, retContent);
  }
  public void testSetFlag() throws Exception {
    NavigableMap<Long, FileInfo> fis =
        imapService.getFolderStatus(
                authenticationService.getCurrentUserName(),
                testImapFolderNodeRef,
                ImapViewMode.ARCHIVE)
            .search;
    if (fis != null && fis.size() > 0) {
      FileInfo messageFileInfo = fis.firstEntry().getValue();

      reauthenticate(USER_NAME, USER_PASSWORD);

      permissionService.setPermission(
          testImapFolderNodeRef, anotherUserName, PermissionService.WRITE, true);

      reauthenticate(anotherUserName, anotherUserName);

      imapService.setFlag(messageFileInfo, Flags.Flag.RECENT, true);

      Serializable prop =
          nodeService.getProperty(messageFileInfo.getNodeRef(), ImapModel.PROP_FLAG_RECENT);
      assertNotNull("Can't set RECENT flag", prop);
    }
  }
  /**
   * 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);
    }
  }
 public String getBoundaryValue(FileInfo messageFileInfo) {
   StringBuffer s = new StringBuffer();
   s.append("----=_Part_").append(messageFileInfo.getNodeRef().getId());
   return s.toString();
 }
Exemple #12
0
 private static void checkClustering(
     List<LoaderServerProxy> remoteServers, List<NodeRef> workingRootNodeRefs) throws Exception {
   List<String> problems = new ArrayList<String>(10);
   for (LoaderServerProxy remoteServer : remoteServers) {
     String ticket = remoteServer.ticket;
     for (NodeRef workingRootNodeRef : workingRootNodeRefs) {
       try {
         // Get the working root node.  If the cluster is correctly configured,
         // it will be available on all the servers.
         FileInfo fileInfo = remoteServer.fileFolderRemote.getFileInfo(ticket, workingRootNodeRef);
         if (fileInfo == null) {
           problems.add("Cannot find the working root node on server: " + remoteServer.rmiUrl);
           continue;
         }
         // Now look for and create a file against which to store some content
         String sampleFilename = "InitialSample.txt";
         String sampleContent = "Sample content";
         NodeRef sampleNodeRef =
             remoteServer.fileFolderRemote.searchSimple(
                 ticket, workingRootNodeRef, sampleFilename);
         if (sampleNodeRef == null) {
           FileInfo sampleFileInfo =
               remoteServer.fileFolderRemote.create(
                   ticket, workingRootNodeRef, sampleFilename, ContentModel.TYPE_CONTENT);
           sampleNodeRef = sampleFileInfo.getNodeRef();
           // Write some content
           byte[] bytes = sampleContent.getBytes("UTF-8");
           remoteServer.fileFolderRemote.putContent(ticket, sampleNodeRef, bytes, sampleFilename);
         }
         // Get the content and ensure that it is the same
         byte[] bytes = remoteServer.fileFolderRemote.getContent(ticket, sampleNodeRef);
         if (bytes == null) {
           problems.add("Sample content was not found on server: " + remoteServer.rmiUrl);
           continue;
         }
         String checkContent = new String(bytes, "UTF-8");
         if (!checkContent.equals(sampleContent)) {
           problems.add("The sample content differed from expected: " + remoteServer.rmiUrl);
           continue;
         }
       } catch (Throwable e) {
         System.err.println("ERROR: Failure whilst checking server: " + remoteServer.rmiUrl);
         e.printStackTrace();
         problems.add(e.getMessage());
       }
     }
   }
   // Check for issues
   if (problems.size() > 0) {
     StringBuilder sb = new StringBuilder();
     sb.append("\n")
         .append(
             "The working root node references could not be found on all the remote servers.\n")
         .append(
             "Please ensure that all the remote servers listed are active in a single cluster.");
     for (String problem : problems) {
       sb.append("\n").append("   ").append(problem);
     }
     throw new LoaderClientException(sb.toString());
   }
 }