private void markCascadeUpdate(NodeRef nodeRef) {
   Status status = nodeService.getNodeStatus(nodeRef);
   nodeService.setProperty(
       status.getNodeRef(),
       ContentModel.PROP_CASCADE_CRC,
       solrTrackingComponent.getCRC(status.getDbId()));
   nodeService.setProperty(status.getNodeRef(), ContentModel.PROP_CASCADE_TX, status.getDbTxnId());
 }
Ejemplo n.º 2
0
  public void updateStatus(NodeRef nodeRef, DownloadStatus status) {
    validateNode(nodeRef);

    nodeService.setProperty(nodeRef, DownloadModel.PROP_STATUS, status.getStatus().toString());
    nodeService.setProperty(nodeRef, DownloadModel.PROP_DONE, new Long(status.getDone()));
    nodeService.setProperty(nodeRef, DownloadModel.PROP_TOTAL, new Long(status.getTotal()));
    nodeService.setProperty(nodeRef, DownloadModel.PROP_FILES_ADDED, status.getFilesAdded());
    nodeService.setProperty(nodeRef, DownloadModel.PROP_TOTAL_FILES, status.getTotalFiles());
  }
  @Override
  public void updateCronExpression(String cronExpression) {
    ParameterCheck.mandatory("cronExpression", cronExpression);

    NodeRef updateStatusNode = _acavNodeService.getUpdateStatusNode();

    _nodeService.setProperty(updateStatusNode, AcavModel.PROP_UPDATE_CRON, cronExpression);

    _updateCronTriggerBean.setCronExpression(cronExpression);

    try {
      String jobName = _updateCronTriggerBean.getJobDetail().getName();
      String jobGroup = _updateCronTriggerBean.getJobDetail().getGroup();

      CronTrigger trigger = (CronTrigger) _updateCronTriggerBean.getTrigger();
      trigger.setJobName("kalle");

      _updateCronTriggerBean.destroy();

      _updateCronTriggerBean.getScheduler().rescheduleJob(jobName, jobGroup, trigger);
      _updateCronTriggerBean.afterPropertiesSet();
    } catch (Exception ex) {
      throw new RuntimeException(ex);
    }
  }
  public void testCheckOutCheckInWithAlteredWorkingCopyName() {
    // Check-out nodeRef using the locale fr_FR
    Locale.setDefault(Locale.FRANCE);
    NodeRef workingCopy =
        this.cociService.checkout(
            this.nodeRef,
            this.rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName("workingCopy"));
    assertNotNull(workingCopy);

    // Check that the working copy name has been set correctly
    String workingCopyName = (String) nodeService.getProperty(workingCopy, PROP_NAME_QNAME);
    assertEquals(
        "Working copy name not correct", "myDocument (Copie de Travail).doc", workingCopyName);

    // Alter the working copy name
    nodeService.setProperty(workingCopy, PROP_NAME_QNAME, "newName (Copie de Travail).doc");

    // Check-in using the locale en_GB
    Locale.setDefault(Locale.UK);
    Map<String, Serializable> versionProperties = new HashMap<String, Serializable>();
    versionProperties.put(Version.PROP_DESCRIPTION, "This is a test version");
    cociService.checkin(workingCopy, versionProperties);

    String name = (String) nodeService.getProperty(nodeRef, PROP_NAME_QNAME);
    assertEquals("File not renamed correctly.", "newName.doc", name);
  }
Ejemplo n.º 5
0
  /**
   * Actualitza el tamany de la sèrie.
   *
   * @param nodeRef
   * @param parentNodeRef
   */
  private void updateSerie(NodeService nodeService, NodeRef nodeRef, NodeRef serieNodeRef) {
    System.out.println(
        DateFormat.getInstance().format(new Date()) + " START: Recalcular tamany sèrie.");
    int tamany = 0;
    List<ChildAssociationRef> children = nodeService.getChildAssocs(serieNodeRef);

    for (ChildAssociationRef childAssoc : children) {
      NodeRef childNodeRef = childAssoc.getChildRef();

      if (nodeService.hasAspect(childNodeRef, expedientRM)) {
        Serializable tamanySerial = nodeService.getProperty(childNodeRef, tamanyExpedientRM);

        if (tamanySerial != null) {
          tamany = tamany + (Integer.parseInt((String) tamanySerial));
        }

      } else if (nodeService.hasAspect(childNodeRef, agregacioRM)) {
        Serializable tamanySerial = nodeService.getProperty(childNodeRef, tamanyAgregacioRM);

        if (tamanySerial != null) {
          tamany = tamany + (Integer.parseInt((String) tamanySerial));
        }
      }
    }

    nodeService.setProperty(serieNodeRef, tamanySerieRM, String.valueOf(tamany));
    Date now = new Date();
    System.out.println(
        DateFormat.getInstance().format(now) + " Update tamany sèrie: " + serieNodeRef);
    System.out.println(DateFormat.getInstance().format(now) + " END: Recalcular tamany sèrie.");
  }
Ejemplo n.º 6
0
  /**
   * Relink the content data from a new node to an existing node to preserve the version history.
   *
   * @param tempNodeRef temp nodeRef
   * @param nodeToMoveRef NodeRef
   * @param newParentNodeRef NodeRef
   * @param newName new name
   */
  public void relinkNode(
      NodeRef tempNodeRef, NodeRef nodeToMoveRef, NodeRef newParentNodeRef, String newName)
      throws FileNotFoundException, FileExistsException {
    // Get the properties for the old and new nodes
    org.alfresco.service.cmr.model.FileInfo tempFileInfo =
        fileFolderService.getFileInfo(tempNodeRef);
    org.alfresco.service.cmr.model.FileInfo fileToMoveInfo =
        fileFolderService.getFileInfo(nodeToMoveRef);

    // Save the current name of the old node
    String tempName = tempFileInfo.getName();

    try {
      // Rename operation will add or remove the sys:temporary aspect appropriately

      // rename temp file to the new name
      fileFolderService.rename(tempNodeRef, newName);

      // rename new file to old name
      fileFolderService.rename(nodeToMoveRef, tempName);
    } catch (org.alfresco.service.cmr.model.FileNotFoundException e) {
      throw new FileNotFoundException(e.getMessage());
    } catch (org.alfresco.service.cmr.model.FileExistsException e) {
      throw new FileExistsException(e.getMessage());
    }

    if (!tempFileInfo.isFolder() && !fileToMoveInfo.isFolder()) {
      // swap the content between the two
      ContentData oldContentData = tempFileInfo.getContentData();
      if (oldContentData == null) {
        String mimetype = mimetypeService.guessMimetype(tempName);
        oldContentData = ContentData.setMimetype(null, mimetype);
      }

      ContentData newContentData = fileToMoveInfo.getContentData();

      // Reset the mime type
      // TODO Pass the content along when guessing the mime type, so we're more accurate
      String mimetype = mimetypeService.guessMimetype(newName);
      newContentData = ContentData.setMimetype(newContentData, mimetype);

      nodeService.setProperty(tempNodeRef, ContentModel.PROP_CONTENT, newContentData);
      nodeService.setProperty(nodeToMoveRef, ContentModel.PROP_CONTENT, oldContentData);
    }
  }
Ejemplo n.º 7
0
  /** Monkeys with the created date on a wiki page */
  private void pushPageCreatedDateBack(String name, int daysAgo) throws Exception {
    NodeRef container = siteService.getContainer(SITE_SHORT_NAME_WIKI, "wiki");
    NodeRef node = nodeService.getChildByName(container, ContentModel.ASSOC_CONTAINS, name);

    Date created = (Date) nodeService.getProperty(node, ContentModel.PROP_CREATED);
    Date newCreated = new Date(created.getTime() - daysAgo * 24 * 60 * 60 * 1000);

    UserTransaction txn = transactionService.getUserTransaction();
    txn.begin();

    this.policyBehaviourFilter.disableBehaviour(ContentModel.ASPECT_AUDITABLE);
    internalNodeService.setProperty(node, ContentModel.PROP_CREATED, newCreated);
    this.policyBehaviourFilter.enableBehaviour(ContentModel.ASPECT_AUDITABLE);

    txn.commit();

    // Now chance something else on the node to have it re-indexed
    nodeService.setProperty(node, ContentModel.PROP_CREATED, newCreated);
    nodeService.setProperty(node, ContentModel.PROP_DESCRIPTION, "Forced change");
  }
  public void testCheckInWithNameChange() {
    // Check out the file
    NodeRef fileWorkingCopyNodeRef = cociService.checkout(fileNodeRef);
    // Make sure we can get the checked out node
    NodeRef fileWorkingCopyNodeRefCheck = cociService.getWorkingCopy(fileNodeRef);
    assertEquals("Working copy not found ", fileWorkingCopyNodeRef, fileWorkingCopyNodeRefCheck);

    // Rename the working copy
    nodeService.setProperty(fileWorkingCopyNodeRef, ContentModel.PROP_NAME, "renamed");

    // Check in
    cociService.checkin(fileWorkingCopyNodeRef, null);
  }
Ejemplo n.º 9
0
  public void testRenamePageWithEmptyTitle() throws Exception {
    JSONObject page;
    String name = System.currentTimeMillis() + "";
    String name2 = System.currentTimeMillis() + 1 + "";

    // Create a page
    page = createOrUpdatePage(name, name, null, Status.STATUS_OK);
    assertEquals("Incorrect JSON: " + page.toString(), true, page.has("title"));

    // Fetch it and check
    page = getPage(name, Status.STATUS_OK);
    assertEquals(name, page.getString("name"));
    assertEquals(name, page.getString("title"));

    // update title
    SiteInfo site = siteService.getSite(SITE_SHORT_NAME_WIKI);
    WikiPageInfo pageInfo = wikiService.getWikiPage(site.getShortName(), name);
    NodeRef pageRef = pageInfo.getNodeRef();
    nodeService.setProperty(pageRef, ContentModel.PROP_TITLE, "");

    // Fetch it and check
    page = getPage(name, Status.STATUS_OK);
    JSONArray versions = page.getJSONArray("versionhistory");

    int maxVersionIndex = versions.length() - 1;
    double vNum = Double.parseDouble(versions.getJSONObject(maxVersionIndex).getString("version"));
    String newTitle = versions.getJSONObject(maxVersionIndex).getString("title");
    for (int i = versions.length() - 2; i >= 0; i--) {
      JSONObject version = versions.getJSONObject(i);
      String ver = version.getString("version");
      if (Double.parseDouble(ver) > vNum) {
        maxVersionIndex = i;
        vNum = Double.parseDouble(ver);
        newTitle = versions.getJSONObject(maxVersionIndex).getString("title");
      }
    }
    assertEquals(name, page.getString("name"));
    assertEquals("", newTitle);

    renamePage(name, name2, Status.STATUS_OK);

    // Fetch it at the new address
    page = getPage(name2, Status.STATUS_OK);
    assertEquals(name2, page.getString("name"));
    assertEquals(name2, page.getString("title"));
  }
 /**
  * The second stage of the <code>NodeRef</code> repointing. Call this method to have any <code>
  * NodeRef</code> properties readjusted to reflect the copied node hierarchy. Only use this method
  * if it a requirement for the particular type or aspect that you are coding for.
  *
  * @param sourceNodeRef the source node
  * @param propertyQName the target node i.e. the copy of the source node
  * @param copyMap the full hierarchy copy map of source to copies
  * @see #recordNodeRefsForRepointing(NodeRef, Map, QName)
  */
 @SuppressWarnings("unchecked")
 public void repointNodeRefs(
     NodeRef sourceNodeRef,
     NodeRef targetNodeRef,
     QName propertyQName,
     Map<NodeRef, NodeRef> copyMap,
     NodeService nodeService) {
   String key = KEY_NODEREF_REPOINTING_PREFIX + propertyQName.toString();
   Map<NodeRef, Serializable> map = TransactionalResourceHelper.getMap(key);
   Serializable value = map.get(sourceNodeRef);
   if (value == null) {
     // Don't bother.  The source node did not have a NodeRef property
     return;
   }
   Serializable newValue = null;
   if (value instanceof Collection) {
     Collection<Serializable> oldList = (Collection<Serializable>) value;
     List<Serializable> newList = new ArrayList<Serializable>(oldList.size());
     for (Serializable oldListValue : oldList) {
       Serializable newListValue = oldListValue;
       if (oldListValue instanceof NodeRef) {
         newListValue = repointNodeRef(copyMap, (NodeRef) oldListValue);
       }
       // Put the value in the new list even though the new list might be discarded
       newList.add(newListValue);
       // Check if the value changed
       if (!newListValue.equals(oldListValue)) {
         // The value changed, so the new list will have to be set onto the target node
         newValue = (Serializable) newList;
       }
     }
   } else if (value instanceof NodeRef) {
     NodeRef newNodeRef = repointNodeRef(copyMap, (NodeRef) value);
     if (!newNodeRef.equals(value)) {
       // The value changed, so the new list will have to be set onto the target node
       newValue = newNodeRef;
     }
   } else {
     throw new IllegalStateException("Should only have Collections and NodeRef values");
   }
   // Fix the node property on the target, if necessary
   if (newValue != null) {
     nodeService.setProperty(targetNodeRef, propertyQName, newValue);
   }
 }
Ejemplo n.º 11
0
  /**
   * Actualitza el tamany de l'expedient.
   *
   * @param nodeRef
   * @param parentNodeRef
   */
  private void updateExpedient(NodeService nodeService, NodeRef docNodeRef, NodeRef expNodeRef) {
    System.out.println(
        DateFormat.getInstance().format(new Date()) + " START: Recalcular tamany expedient.");
    int tamany = 0;
    List<ChildAssociationRef> children = nodeService.getChildAssocs(expNodeRef);

    for (ChildAssociationRef childAssoc : children) {
      NodeRef childNodeRef = childAssoc.getChildRef();
      Serializable tamanySerial = nodeService.getProperty(childNodeRef, tamanyDocumentSimpleRM);

      if (tamanySerial != null && !"".equals(tamanySerial)) {
        tamany = tamany + (Integer.parseInt((String) tamanySerial));
      }
    }

    nodeService.setProperty(expNodeRef, tamanyExpedientRM, String.valueOf(tamany));
    Date now = new Date();
    System.out.println(
        DateFormat.getInstance().format(now) + " Update tamany expedient: " + expNodeRef);
    System.out.println(DateFormat.getInstance().format(now) + " END: Recalcular tamany expedient.");
  }
Ejemplo n.º 12
0
  /**
   * Actualitza el tamany del fons.
   *
   * @param nodeRef
   * @param parentNodeRef
   */
  private void updateFons(NodeService nodeService, NodeRef serieNodeRef, NodeRef fonsNodeRef) {
    System.out.println(
        DateFormat.getInstance().format(new Date()) + " START: Recalcular tamany fons.");
    int tamany = 0;
    List<ChildAssociationRef> children = nodeService.getChildAssocs(fonsNodeRef);

    for (ChildAssociationRef childAssoc : children) {
      NodeRef childNodeRef = childAssoc.getChildRef();
      Serializable tamanySerial = nodeService.getProperty(childNodeRef, tamanySerieRM);

      if (tamanySerial != null) {
        tamany = tamany + (Integer.parseInt((String) tamanySerial));
      }
    }

    nodeService.setProperty(fonsNodeRef, tamanyFonsRM, String.valueOf(tamany));
    Date now = new Date();
    System.out.println(
        DateFormat.getInstance().format(now) + " Update tamany fons: " + fonsNodeRef);
    System.out.println(DateFormat.getInstance().format(now) + " END: Recalcular tamany fons.");
  }
  /** Ensure that the node has a <b>fm:forum</b> child node otherwise create one */
  public void onAddAspect(NodeRef discussableNodeRef, QName aspectTypeQName) {
    String name = (String) this.nodeService.getProperty(discussableNodeRef, ContentModel.PROP_NAME);
    String forumName = I18NUtil.getMessage("discussion.discussion_for", new Object[] {name});

    NodeRef forumNodeRef = getForum(discussableNodeRef);

    if (forumNodeRef == null) {
      Map<QName, Serializable> forumProps = new HashMap<QName, Serializable>(1);
      forumProps.put(ContentModel.PROP_NAME, forumName);

      ChildAssociationRef childRef =
          nodeService.createNode(
              discussableNodeRef,
              ForumModel.ASSOC_DISCUSSION,
              QName.createQName(NamespaceService.FORUMS_MODEL_1_0_URI, "discussion"),
              ForumModel.TYPE_FORUM,
              forumProps);

      forumNodeRef = childRef.getChildRef();
    } else {
      // Just adjust the name
      nodeService.setProperty(forumNodeRef, ContentModel.PROP_NAME, forumName);
    }

    // apply the uifacets aspect
    Map<QName, Serializable> uiFacetsProps = new HashMap<QName, Serializable>(5);
    uiFacetsProps.put(ApplicationModel.PROP_ICON, "forum");
    this.nodeService.addAspect(forumNodeRef, ApplicationModel.ASPECT_UIFACETS, uiFacetsProps);

    // Done
    if (logger.isDebugEnabled()) {
      logger.debug(
          "Created forum node for discussion: \n"
              + "   Discussable Node: "
              + discussableNodeRef
              + "\n"
              + "   Forum Node:       "
              + forumNodeRef);
    }
  }
Ejemplo n.º 14
0
  private AlfrescoRuntimeException signFile(
      final NodeRef nodeRefToSign,
      final DigitalSigningDTO signingDTO,
      final File alfTempDir,
      final String alias,
      final KeyStore ks,
      final PrivateKey key,
      final Certificate[] chain) {
    final String fileNameToSign = fileFolderService.getFileInfo(nodeRefToSign).getName();

    File fileConverted = null;
    File tempDir = null;
    try {
      ContentReader fileToSignContentReader = getReader(nodeRefToSign);

      if (fileToSignContentReader != null) {
        String newName = null;

        // Check if document is PDF or transform it
        if (!MimetypeMap.MIMETYPE_PDF.equals(fileToSignContentReader.getMimetype())) {
          // Transform document in PDF document
          final ContentTransformer tranformer =
              contentTransformerRegistry.getTransformer(
                  fileToSignContentReader.getMimetype(),
                  fileToSignContentReader.getSize(),
                  MimetypeMap.MIMETYPE_PDF,
                  new TransformationOptions());

          if (tranformer != null) {

            tempDir = new File(alfTempDir.getPath() + File.separatorChar + nodeRefToSign.getId());
            if (tempDir != null) {
              tempDir.mkdir();
              fileConverted =
                  new File(tempDir, fileNameToSign + "_" + System.currentTimeMillis() + ".pdf");
              if (fileConverted != null) {
                final ContentWriter newDoc = new FileContentWriter(fileConverted);
                if (newDoc != null) {
                  newDoc.setMimetype(MimetypeMap.MIMETYPE_PDF);
                  tranformer.transform(fileToSignContentReader, newDoc);
                  fileToSignContentReader = new FileContentReader(fileConverted);

                  final String originalName =
                      (String) nodeService.getProperty(nodeRefToSign, ContentModel.PROP_NAME);

                  newName = originalName.substring(0, originalName.lastIndexOf(".")) + ".pdf";
                }
              }
            }
          } else {
            log.error(
                "["
                    + fileNameToSign
                    + "] No suitable converter found to convert the document in PDF.");
            return new AlfrescoRuntimeException(
                "["
                    + fileNameToSign
                    + "] No suitable converter found to convert the document in PDF.");
          }
        }

        // Convert PDF in PDF/A format
        final File pdfAFile = convertPdfToPdfA(fileToSignContentReader.getContentInputStream());

        final PdfReader reader = new PdfReader(new FileInputStream(pdfAFile));

        if (nodeRefToSign != null) {
          tempDir = new File(alfTempDir.getPath() + File.separatorChar + nodeRefToSign.getId());
          if (tempDir != null) {
            tempDir.mkdir();
            final File file = new File(tempDir, fileNameToSign);

            if (file != null) {
              final FileOutputStream fout = new FileOutputStream(file);
              final PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0');

              if (stp != null) {
                final PdfSignatureAppearance sap = stp.getSignatureAppearance();
                if (sap != null) {
                  sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
                  sap.setReason(signingDTO.getSignReason());
                  sap.setLocation(signingDTO.getSignLocation());
                  sap.setContact(signingDTO.getSignContact());
                  sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
                  sap.setImageScale(1);

                  // digital signature
                  if (signingDTO.getSigningField() != null
                      && !signingDTO.getSigningField().trim().equalsIgnoreCase("")) {
                    Image img = null;
                    if (signingDTO.getImage() != null) {
                      final ContentReader imageContentReader = getReader(signingDTO.getImage());
                      final AcroFields af = reader.getAcroFields();
                      if (af != null) {
                        final List<FieldPosition> positions =
                            af.getFieldPositions(signingDTO.getSigningField());
                        if (positions != null
                            && positions.size() > 0
                            && positions.get(0) != null
                            && positions.get(0).position != null) {
                          final BufferedImage newImg =
                              scaleImage(
                                  ImageIO.read(imageContentReader.getContentInputStream()),
                                  BufferedImage.TYPE_INT_RGB,
                                  Float.valueOf(positions.get(0).position.getWidth()).intValue(),
                                  Float.valueOf(positions.get(0).position.getHeight()).intValue());
                          img = Image.getInstance(newImg, null);
                        } else {
                          log.error(
                              "["
                                  + fileNameToSign
                                  + "] The field '"
                                  + signingDTO.getSigningField()
                                  + "' doesn't exist in the document.");
                          return new AlfrescoRuntimeException(
                              "["
                                  + fileNameToSign
                                  + "] The field '"
                                  + signingDTO.getSigningField()
                                  + "' doesn't exist in the document.");
                        }
                      }
                      if (img == null) {
                        img =
                            Image.getInstance(
                                ImageIO.read(imageContentReader.getContentInputStream()), null);
                      }
                      sap.setImage(img);
                    }
                    sap.setVisibleSignature(signingDTO.getSigningField());
                  } else {
                    int pageToSign = 1;
                    if (DigitalSigningDTO.PAGE_LAST.equalsIgnoreCase(
                        signingDTO.getPages().trim())) {
                      pageToSign = reader.getNumberOfPages();
                    } else if (DigitalSigningDTO.PAGE_SPECIFIC.equalsIgnoreCase(
                        signingDTO.getPages().trim())) {
                      if (signingDTO.getPageNumber() > 0
                          && signingDTO.getPageNumber() <= reader.getNumberOfPages()) {
                        pageToSign = signingDTO.getPageNumber();
                      } else {
                        throw new AlfrescoRuntimeException("Page number is out of bound.");
                      }
                    }
                    if (signingDTO.getImage() != null) {
                      final ContentReader imageContentReader = getReader(signingDTO.getImage());
                      // Resize image
                      final BufferedImage newImg =
                          scaleImage(
                              ImageIO.read(imageContentReader.getContentInputStream()),
                              BufferedImage.TYPE_INT_RGB,
                              signingDTO.getSignWidth(),
                              signingDTO.getSignHeight());
                      final Image img = Image.getInstance(newImg, null);
                      sap.setImage(img);
                    }
                    if (signingDTO.getPosition() != null
                        && !DigitalSigningDTO.POSITION_CUSTOM.equalsIgnoreCase(
                            signingDTO.getPosition().trim())) {
                      final Rectangle pageRect = reader.getPageSizeWithRotation(1);
                      sap.setVisibleSignature(
                          positionSignature(
                              signingDTO.getPosition(),
                              pageRect,
                              signingDTO.getSignWidth(),
                              signingDTO.getSignHeight(),
                              signingDTO.getxMargin(),
                              signingDTO.getyMargin()),
                          pageToSign,
                          null);
                    } else {
                      sap.setVisibleSignature(
                          new Rectangle(
                              signingDTO.getLocationX(),
                              signingDTO.getLocationY(),
                              signingDTO.getLocationX() + signingDTO.getSignWidth(),
                              signingDTO.getLocationY() - signingDTO.getSignHeight()),
                          pageToSign,
                          null);
                    }
                  }
                  stp.close();

                  NodeRef destinationNode = null;
                  NodeRef originalDoc = null;
                  boolean addAsNewVersion = false;
                  if (signingDTO.getDestinationFolder() == null) {
                    destinationNode = nodeRefToSign;
                    nodeService.addAspect(destinationNode, ContentModel.ASPECT_VERSIONABLE, null);
                    addAsNewVersion = true;
                  } else {
                    originalDoc = nodeRefToSign;
                    destinationNode =
                        createDestinationNode(
                            file.getName(), signingDTO.getDestinationFolder(), nodeRefToSign);
                  }

                  if (destinationNode != null) {

                    final ContentWriter writer =
                        contentService.getWriter(destinationNode, ContentModel.PROP_CONTENT, true);
                    if (writer != null) {
                      writer.setEncoding(fileToSignContentReader.getEncoding());
                      writer.setMimetype("application/pdf");
                      writer.putContent(file);
                      file.delete();

                      if (fileConverted != null) {
                        fileConverted.delete();
                      }

                      nodeService.addAspect(
                          destinationNode,
                          SigningModel.ASPECT_SIGNED,
                          new HashMap<QName, Serializable>());
                      nodeService.setProperty(
                          destinationNode, SigningModel.PROP_REASON, signingDTO.getSignReason());
                      nodeService.setProperty(
                          destinationNode,
                          SigningModel.PROP_LOCATION,
                          signingDTO.getSignLocation());
                      nodeService.setProperty(
                          destinationNode, SigningModel.PROP_SIGNATUREDATE, new java.util.Date());
                      nodeService.setProperty(
                          destinationNode,
                          SigningModel.PROP_SIGNEDBY,
                          AuthenticationUtil.getRunAsUser());

                      if (newName != null) {
                        nodeService.setProperty(destinationNode, ContentModel.PROP_NAME, newName);
                      }

                      final X509Certificate c = (X509Certificate) ks.getCertificate(alias);
                      nodeService.setProperty(
                          destinationNode, SigningModel.PROP_VALIDITY, c.getNotAfter());
                      nodeService.setProperty(
                          destinationNode, SigningModel.PROP_ORIGINAL_DOC, originalDoc);

                      if (!addAsNewVersion) {
                        if (!nodeService.hasAspect(originalDoc, SigningModel.ASPECT_ORIGINAL_DOC)) {
                          nodeService.addAspect(
                              originalDoc,
                              SigningModel.ASPECT_ORIGINAL_DOC,
                              new HashMap<QName, Serializable>());
                        }
                        nodeService.createAssociation(
                            originalDoc, destinationNode, SigningModel.PROP_RELATED_DOC);
                      }
                    }
                  } else {
                    log.error("[" + fileNameToSign + "] Destination node is not a valid NodeRef.");
                    return new AlfrescoRuntimeException(
                        "[" + fileNameToSign + "] Destination node is not a valid NodeRef.");
                  }
                } else {
                  log.error("[" + fileNameToSign + "] Unable to get PDF appearance signature.");
                  return new AlfrescoRuntimeException(
                      "[" + fileNameToSign + "] Unable to get PDF appearance signature.");
                }
              } else {
                log.error("[" + fileNameToSign + "] Unable to create PDF signature.");
                return new AlfrescoRuntimeException(
                    "[" + fileNameToSign + "] Unable to create PDF signature.");
              }
            }
          }
        } else {
          log.error("[" + fileNameToSign + "] Unable to get document to sign content.");
          return new AlfrescoRuntimeException(
              "[" + fileNameToSign + "] Unable to get document to sign content.");
        }

        if (pdfAFile != null) {
          pdfAFile.delete();
        }

        return null;

      } else {
        log.error("[" + fileNameToSign + "] The document has no content.");
        return new AlfrescoRuntimeException(
            "[" + fileNameToSign + "] The document has no content.");
      }
    } catch (KeyStoreException e) {
      log.error("[" + fileNameToSign + "] " + e);
      return new AlfrescoRuntimeException("[" + fileNameToSign + "] " + e.getMessage(), e);
    } catch (ContentIOException e) {
      log.error("[" + fileNameToSign + "] " + e);
      return new AlfrescoRuntimeException("[" + fileNameToSign + "] " + e.getMessage(), e);
    } catch (IOException e) {
      log.error("[" + fileNameToSign + "] " + e);
      return new AlfrescoRuntimeException("[" + fileNameToSign + "] " + e.getMessage(), e);
    } catch (DocumentException e) {
      log.error("[" + fileNameToSign + "] " + e);
      return new AlfrescoRuntimeException("[" + fileNameToSign + "] " + e.getMessage(), e);
    } finally {
      if (tempDir != null) {
        try {
          tempDir.delete();
        } catch (Exception ex) {
          log.error("[" + fileNameToSign + "] " + ex);
          return new AlfrescoRuntimeException("[" + fileNameToSign + "] " + ex.getMessage(), ex);
        }
      }
    }
  }
Ejemplo n.º 15
0
 public void setOutputPathPattern(final String opp) {
   final NodeService nodeService = this.getServiceRegistry().getNodeService();
   nodeService.setProperty(this.getNodeRef(), WCMAppModel.PROP_OUTPUT_PATH_PATTERN, opp);
 }
  /** Test checkIn */
  public void testCheckIn() {
    NodeRef workingCopy = checkout();

    // Test standard check-in
    Map<String, Serializable> versionProperties = new HashMap<String, Serializable>();
    versionProperties.put(Version.PROP_DESCRIPTION, "This is a test version");
    cociService.checkin(workingCopy, versionProperties);

    // Test check-in with content
    NodeRef workingCopy3 = checkout();

    nodeService.setProperty(workingCopy3, PROP_NAME_QNAME, TEST_VALUE_2);
    nodeService.setProperty(workingCopy3, PROP2_QNAME, TEST_VALUE_3);
    ContentWriter tempWriter =
        this.contentService.getWriter(workingCopy3, ContentModel.PROP_CONTENT, false);
    assertNotNull(tempWriter);
    tempWriter.putContent(CONTENT_2);
    String contentUrl = tempWriter.getContentUrl();
    Map<String, Serializable> versionProperties3 = new HashMap<String, Serializable>();
    versionProperties3.put(Version.PROP_DESCRIPTION, "description");
    versionProperties3.put(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR);
    NodeRef origNodeRef = cociService.checkin(workingCopy3, versionProperties3, contentUrl, true);
    assertNotNull(origNodeRef);

    // Check the checked in content
    ContentReader contentReader =
        this.contentService.getReader(origNodeRef, ContentModel.PROP_CONTENT);
    assertNotNull(contentReader);
    assertEquals(CONTENT_2, contentReader.getContentString());

    // Check that the version history is correct
    Version version = this.versionService.getCurrentVersion(origNodeRef);
    assertNotNull(version);
    assertEquals("description", version.getDescription());
    assertEquals(VersionType.MAJOR, version.getVersionType());
    NodeRef versionNodeRef = version.getFrozenStateNodeRef();
    assertNotNull(versionNodeRef);

    // Check the verioned content
    ContentReader versionContentReader =
        this.contentService.getReader(versionNodeRef, ContentModel.PROP_CONTENT);
    assertNotNull(versionContentReader);
    assertEquals(CONTENT_2, versionContentReader.getContentString());

    // Check that the name is not updated during the check-in
    assertEquals(TEST_VALUE_2, nodeService.getProperty(versionNodeRef, PROP_NAME_QNAME));
    assertEquals(TEST_VALUE_2, nodeService.getProperty(origNodeRef, PROP_NAME_QNAME));

    // Check that the other properties are updated during the check-in
    assertEquals(TEST_VALUE_3, nodeService.getProperty(versionNodeRef, PROP2_QNAME));
    assertEquals(TEST_VALUE_3, nodeService.getProperty(origNodeRef, PROP2_QNAME));

    // Cancel the check out after is has been left checked out
    cociService.cancelCheckout(workingCopy3);

    // Test keep checked out flag
    NodeRef workingCopy2 = checkout();
    Map<String, Serializable> versionProperties2 = new HashMap<String, Serializable>();
    versionProperties2.put(Version.PROP_DESCRIPTION, "Another version test");
    this.cociService.checkin(workingCopy2, versionProperties2, null, true);
    this.cociService.checkin(workingCopy2, new HashMap<String, Serializable>(), null, true);
  }
  /** On setup in transaction implementation */
  @Override
  protected void onSetUpInTransaction() throws Exception {
    // Set the services
    this.nodeService = (NodeService) this.applicationContext.getBean("nodeService");
    this.cociService =
        (CheckOutCheckInService) this.applicationContext.getBean("checkOutCheckInService");
    this.contentService = (ContentService) this.applicationContext.getBean("contentService");
    this.versionService = (VersionService) this.applicationContext.getBean("versionService");
    this.authenticationService =
        (MutableAuthenticationService) this.applicationContext.getBean("authenticationService");
    this.lockService = (LockService) this.applicationContext.getBean("lockService");
    this.transactionService =
        (TransactionService) this.applicationContext.getBean("transactionComponent");
    this.permissionService =
        (PermissionService) this.applicationContext.getBean("permissionService");
    this.copyService = (CopyService) this.applicationContext.getBean("copyService");

    // Authenticate as system to create initial test data set
    AuthenticationComponent authenticationComponent =
        (AuthenticationComponent) this.applicationContext.getBean("authenticationComponent");
    authenticationComponent.setSystemUserAsCurrentUser();

    // Create the store and get the root node reference
    this.storeRef =
        nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "Test_" + System.currentTimeMillis());
    this.rootNodeRef = nodeService.getRootNode(storeRef);

    // Create the node used for tests
    ChildAssociationRef childAssocRef =
        nodeService.createNode(
            rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName("test"),
            ContentModel.TYPE_CONTENT);
    this.nodeRef = childAssocRef.getChildRef();
    nodeService.addAspect(this.nodeRef, ContentModel.ASPECT_TITLED, null);
    nodeService.setProperty(this.nodeRef, ContentModel.PROP_NAME, TEST_VALUE_NAME);
    nodeService.setProperty(this.nodeRef, PROP2_QNAME, TEST_VALUE_2);

    // Add the initial content to the node
    ContentWriter contentWriter =
        this.contentService.getWriter(this.nodeRef, ContentModel.PROP_CONTENT, true);
    contentWriter.setMimetype("text/plain");
    contentWriter.setEncoding("UTF-8");
    contentWriter.putContent(CONTENT_1);

    // Add the lock and version aspects to the created node
    nodeService.addAspect(this.nodeRef, ContentModel.ASPECT_VERSIONABLE, null);
    nodeService.addAspect(this.nodeRef, ContentModel.ASPECT_LOCKABLE, null);

    // Create and authenticate the user
    this.userName = "******" + GUID.generate();
    TestWithUserUtils.createUser(
        this.userName, PWD, this.rootNodeRef, this.nodeService, this.authenticationService);
    TestWithUserUtils.authenticateUser(
        this.userName, PWD, this.rootNodeRef, this.authenticationService);
    this.userNodeRef = TestWithUserUtils.getCurrentUser(this.authenticationService);

    permissionService.setPermission(
        this.rootNodeRef, this.userName, PermissionService.ALL_PERMISSIONS, true);
    permissionService.setPermission(
        this.nodeRef, this.userName, PermissionService.ALL_PERMISSIONS, true);

    folderNodeRef =
        nodeService
            .createNode(
                rootNodeRef,
                ContentModel.ASSOC_CHILDREN,
                QName.createQName("test"),
                ContentModel.TYPE_FOLDER,
                Collections.<QName, Serializable>singletonMap(ContentModel.PROP_NAME, "folder"))
            .getChildRef();
    fileNodeRef =
        nodeService
            .createNode(
                folderNodeRef,
                ContentModel.ASSOC_CONTAINS,
                QName.createQName("test"),
                ContentModel.TYPE_CONTENT,
                Collections.<QName, Serializable>singletonMap(ContentModel.PROP_NAME, "file"))
            .getChildRef();
    contentWriter = this.contentService.getWriter(fileNodeRef, ContentModel.PROP_CONTENT, true);
    contentWriter.setMimetype("text/plain");
    contentWriter.setEncoding("UTF-8");
    contentWriter.putContent(CONTENT_1);
  }
Ejemplo n.º 18
0
  public void cancelDownload(NodeRef downloadNodeRef) {
    validateNode(downloadNodeRef);

    nodeService.setProperty(downloadNodeRef, DownloadModel.PROP_CANCELLED, true);
  }
Ejemplo n.º 19
0
  /** Listing */
  public void testOverallListing() throws Exception {
    JSONObject pages;
    JSONArray entries;

    // Initially, there are no events
    pages = getPages(null, null);
    assertEquals("Incorrect JSON: " + pages.toString(), true, pages.has("totalPages"));
    assertEquals(0, pages.getInt("totalPages"));

    // Add two links to get started with
    createOrUpdatePage(PAGE_TITLE_ONE, PAGE_CONTENTS_ONE, null, Status.STATUS_OK);
    createOrUpdatePage(PAGE_TITLE_TWO, PAGE_CONTENTS_TWO, null, Status.STATUS_OK);

    // Check again
    pages = getPages(null, null);

    // Should have two links
    assertEquals("Incorrect JSON: " + pages.toString(), true, pages.has("totalPages"));
    assertEquals(2, pages.getInt("totalPages"));

    entries = pages.getJSONArray("pages");
    assertEquals(2, entries.length());
    // Sorted by newest created first
    assertEquals(PAGE_TITLE_TWO, entries.getJSONObject(0).getString("title"));
    assertEquals(PAGE_TITLE_ONE, entries.getJSONObject(1).getString("title"));

    // Add a third, which is internal, and created by the other user
    this.authenticationComponent.setCurrentUser(USER_TWO);
    JSONObject page3 =
        createOrUpdatePage(PAGE_TITLE_THREE, PAGE_CONTENTS_THREE, null, Status.STATUS_OK);
    String name3 = PAGE_TITLE_THREE.replace(' ', '_');
    createOrUpdatePage(PAGE_TITLE_THREE, "UD" + PAGE_CONTENTS_THREE, null, Status.STATUS_OK);
    this.authenticationComponent.setCurrentUser(USER_ONE);

    // Check now, should have three links
    pages = getPages(null, null);
    assertEquals(3, pages.getInt("totalPages"));

    entries = pages.getJSONArray("pages");
    assertEquals(3, entries.length());
    assertEquals(PAGE_TITLE_THREE, entries.getJSONObject(0).getString("title"));
    assertEquals(PAGE_TITLE_TWO, entries.getJSONObject(1).getString("title"));
    assertEquals(PAGE_TITLE_ONE, entries.getJSONObject(2).getString("title"));

    // Ask for filtering by user
    pages = getPages(null, USER_ONE);
    assertEquals(2, pages.getInt("totalPages"));

    entries = pages.getJSONArray("pages");
    assertEquals(2, entries.length());
    assertEquals(PAGE_TITLE_TWO, entries.getJSONObject(0).getString("title"));
    assertEquals(PAGE_TITLE_ONE, entries.getJSONObject(1).getString("title"));

    pages = getPages(null, USER_TWO);
    assertEquals(1, pages.getInt("totalPages"));

    entries = pages.getJSONArray("pages");
    assertEquals(1, entries.length());
    assertEquals(PAGE_TITLE_THREE, entries.getJSONObject(0).getString("title"));

    // Ask for filtering by recently added docs
    pages = getPages("recentlyAdded", null);
    assertEquals(3, pages.getInt("totalPages"));

    entries = pages.getJSONArray("pages");
    assertEquals(3, entries.length());
    assertEquals(PAGE_TITLE_THREE, entries.getJSONObject(0).getString("title"));
    assertEquals(PAGE_TITLE_TWO, entries.getJSONObject(1).getString("title"));
    assertEquals(PAGE_TITLE_ONE, entries.getJSONObject(2).getString("title"));

    // Push one back into the past
    pushPageCreatedDateBack(name3, 10);

    pages = getPages("recentlyAdded", null);
    assertEquals(2, pages.getInt("totalPages"));

    entries = pages.getJSONArray("pages");
    assertEquals(2, entries.length());
    assertEquals(PAGE_TITLE_TWO, entries.getJSONObject(0).getString("title"));
    assertEquals(PAGE_TITLE_ONE, entries.getJSONObject(1).getString("title"));

    // Now for recently modified ones
    pages = getPages("recentlyModified", null);
    assertEquals(3, pages.getInt("totalPages"));

    entries = pages.getJSONArray("pages");
    assertEquals(3, entries.length());
    assertEquals(PAGE_TITLE_THREE, entries.getJSONObject(0).getString("title"));
    assertEquals(PAGE_TITLE_TWO, entries.getJSONObject(1).getString("title"));
    assertEquals(PAGE_TITLE_ONE, entries.getJSONObject(2).getString("title"));
    //       assertEquals(PAGE_TITLE_THREE, entries.getJSONObject(2).getString("title"));

    // Change the owner+creator of one of the pages to System, ensure that
    //  this doesn't break anything in the process
    String pageTwoName = entries.getJSONObject(1).getString("name");
    WikiPageInfo pageTwo = wikiService.getWikiPage(SITE_SHORT_NAME_WIKI, pageTwoName);
    nodeService.setProperty(
        pageTwo.getNodeRef(), ContentModel.PROP_OWNER, AuthenticationUtil.SYSTEM_USER_NAME);
    nodeService.setProperty(
        pageTwo.getNodeRef(), ContentModel.PROP_CREATOR, AuthenticationUtil.SYSTEM_USER_NAME);
    nodeService.setProperty(
        pageTwo.getNodeRef(), ContentModel.PROP_MODIFIER, AuthenticationUtil.SYSTEM_USER_NAME);

    // Check the listing still works (note - order will have changed)
    pages = getPages("recentlyModified", null);
    assertEquals(3, pages.getInt("totalPages"));

    entries = pages.getJSONArray("pages");
    assertEquals(3, entries.length());
    assertEquals(PAGE_TITLE_TWO, entries.getJSONObject(0).getString("title"));
    assertEquals(PAGE_TITLE_THREE, entries.getJSONObject(1).getString("title"));
    assertEquals(PAGE_TITLE_ONE, entries.getJSONObject(2).getString("title"));

    // Delete User Two, who owns the 3rd page, and ensure that this
    //  doesn't break anything
    this.authenticationComponent.setCurrentUser(AuthenticationUtil.getAdminUserName());
    personService.deletePerson(USER_TWO);
    this.authenticationComponent.setCurrentUser(USER_ONE);

    // Check the listing still works
    pages = getPages("recentlyModified", null);
    assertEquals(3, pages.getInt("totalPages"));

    entries = pages.getJSONArray("pages");
    assertEquals(3, entries.length());
    assertEquals(PAGE_TITLE_TWO, entries.getJSONObject(0).getString("title"));
    assertEquals(PAGE_TITLE_THREE, entries.getJSONObject(1).getString("title"));
    assertEquals(PAGE_TITLE_ONE, entries.getJSONObject(2).getString("title"));

    // Now hide the site, and remove the user from it, won't be allowed to see it
    this.authenticationComponent.setCurrentUser(AuthenticationUtil.getAdminUserName());
    SiteInfo site = siteService.getSite(SITE_SHORT_NAME_WIKI);
    site.setVisibility(SiteVisibility.PRIVATE);
    siteService.updateSite(site);
    siteService.removeMembership(SITE_SHORT_NAME_WIKI, USER_ONE);
    this.authenticationComponent.setCurrentUser(USER_ONE);

    sendRequest(new GetRequest(URL_WIKI_LIST), Status.STATUS_NOT_FOUND);
  }