Ejemplo n.º 1
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);
    }
  }
Ejemplo n.º 2
0
  @Override
  public IAfSysObject moveTo(String specific, String newName) throws AfException {

    if (isNew()) {
      throw new AfException("this object is new, you can not move it");
    }

    NodeService nodeService = ServiceHelper.getNodeService(afSession);

    NodeRef newParent = getSpecifiedNode(specific);
    if (newParent == null || !(nodeService.exists(newParent))) {
      throw new AfException("the folder " + specific + " you specified does not exist");
    }

    IAfType folderType = AFCHelper.getNodeType(afSession, newParent);
    if (!(folderType.isSubTypeOf("cm:folder") || folderType.getName().equals("cm:folder"))) {
      // parent is a doc
      throw new AfException("you can not move object into a document");
    }

    String objName = (newName == null) ? getObjectName() : newName;
    QName nodeName = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, objName);
    ChildAssociationRef child = nodeService.moveNode(nodeRef, newParent, getAssType(), nodeName);

    IAfSysObject doc = (IAfSysObject) afSession.getObject(new AfID(child.getChildRef().getId()));

    doc.setObjectName(objName);
    doc.save();

    return doc;
  }
  /** @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);
      }
    }
  }
  public void testCheckOutCheckInWithTranslatableAspect() {
    // Create a node to be used as the translation
    NodeRef translationNodeRef =
        nodeService
            .createNode(
                rootNodeRef,
                ContentModel.ASSOC_CHILDREN,
                QName.createQName("translation"),
                ContentModel.TYPE_CONTENT)
            .getChildRef();

    nodeService.addAspect(
        this.nodeRef,
        QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "translatable"),
        null);
    nodeService.createAssociation(
        this.nodeRef,
        translationNodeRef,
        QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "translations"));

    // Check it out
    NodeRef workingCopy =
        cociService.checkout(
            this.nodeRef,
            this.rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName("workingCopy"));

    // Check it back in again
    Map<String, Serializable> versionProperties = new HashMap<String, Serializable>();
    versionProperties.put(Version.PROP_DESCRIPTION, "This is a test version");
    cociService.checkin(workingCopy, versionProperties);
  }
  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);
  }
  /**
   * @param storeValue
   * @param rootPath
   * @param context
   * @param nodeService
   * @param searchService
   * @param namespaceService
   * @param tenantService
   * @param m_transactionService
   */
  private void initializeRootNode(
      String storeValue,
      String rootPath,
      WebApplicationContext context,
      NodeService nodeService,
      SearchService searchService,
      NamespaceService namespaceService,
      TenantService tenantService,
      TransactionService m_transactionService) {

    // Use the system user as the authenticated context for the filesystem initialization

    AuthenticationContext authComponent =
        (AuthenticationContext) context.getBean("authenticationContext");
    authComponent.setSystemUserAsCurrentUser();

    // Wrap the initialization in a transaction

    UserTransaction tx = m_transactionService.getUserTransaction(true);

    try {
      // Start the transaction

      if (tx != null) tx.begin();

      StoreRef storeRef = new StoreRef(storeValue);

      if (nodeService.exists(storeRef) == false) {
        throw new RuntimeException("No store for path: " + storeRef);
      }

      NodeRef storeRootNodeRef = nodeService.getRootNode(storeRef);

      List<NodeRef> nodeRefs =
          searchService.selectNodes(storeRootNodeRef, rootPath, null, namespaceService, false);

      if (nodeRefs.size() > 1) {
        throw new RuntimeException(
            "Multiple possible children for : \n"
                + "   path: "
                + rootPath
                + "\n"
                + "   results: "
                + nodeRefs);
      } else if (nodeRefs.size() == 0) {
        throw new RuntimeException("Node is not found for : \n" + "   root path: " + rootPath);
      }

      defaultRootNode = nodeRefs.get(0);

      // Commit the transaction
      if (tx != null) tx.commit();
    } catch (Exception ex) {
      logger.error(ex);
    } finally {
      // Clear the current system user

      authComponent.clearCurrentSecurityContext();
    }
  }
 public void setFavoriteAssociations(NodeRef person, QName associtation, String type) {
   logger.debug("InFavoriteAssociationSpider.setFavoriteAssociations");
   if (null
       != preferenceService.getPreference(
           (String) nodeService.getProperty(person, ContentModel.PROP_USERNAME), type)) {
     String favorite_documents =
         preferenceService
             .getPreference(
                 (String) nodeService.getProperty(person, ContentModel.PROP_USERNAME), type)
             .toString();
     if (!favorite_documents.isEmpty()) {
       List<NodeRef> favoriteRefs = new ArrayList<>();
       for (String favorite : favorite_documents.split(",")) {
         try {
           NodeRef favoriteRef = new NodeRef(favorite);
           nodeService.getProperties(favoriteRef);
           favoriteRefs.add(favoriteRef); // new NodeRef(favorite));
         } catch (InvalidNodeRefException e) {
           // Got bad node, skipping.
         }
       }
       nodeService.setAssociations(person, associtation, favoriteRefs);
     } else {
       nodeService.setAssociations(person, associtation, new ArrayList<NodeRef>());
     }
   }
 }
Ejemplo n.º 8
0
  @Override
  public IAfSysObject copyTo(String specific, String newName) throws AfException {
    if (isNew()) {
      throw new AfException("this object is new, you can not do copy action");
    }

    NodeService nodeService = ServiceHelper.getNodeService(afSession);
    NodeRef parent = getSpecifiedNode(specific);

    if (parent == null || !nodeService.exists(parent)) {
      throw new AfException("the folder " + specific + " you specified not exist");
    }

    IAfType folderType = AFCHelper.getNodeType(afSession, parent);
    if (!(folderType.isSubTypeOf("cm:folder") || folderType.getName().equals("cm:folder"))) {
      // parent is a doc
      throw new AfException("you can not copy object into a document");
    }

    CopyService copyService = ServiceHelper.getCopyService(afSession);

    String objName = (newName == null) ? getObjectName() : newName;
    QName nodeName = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, objName);
    NodeRef ref = copyService.copyAndRename(nodeRef, parent, getAssType(), nodeName, true);

    IAfSysObject object = (IAfSysObject) afSession.getObject(new AfID(ref.getId()));

    object.setObjectName(objName);
    object.save();

    return object;
  }
Ejemplo n.º 9
0
    public NodeRef doWork() throws Exception {
      // Get company home / root for the tenant domain
      // Do this as the System user in case the tenant user does not have permission

      // Connect to the repo and ensure that the store exists
      if (!nodeService.exists(storeRef)) {
        throw new AlfrescoRuntimeException(
            "Store not created prior to application startup: " + storeRef);
      }
      NodeRef storeRootNodeRef = nodeService.getRootNode(storeRef);

      // Find the root node for this device
      List<NodeRef> nodeRefs =
          searchService.selectNodes(storeRootNodeRef, rootPath, null, namespaceService, false);

      if (nodeRefs.size() > 1) {
        throw new AlfrescoRuntimeException(
            "Multiple possible roots for device: \n"
                + "   root path: "
                + rootPath
                + "\n"
                + "   results: "
                + nodeRefs);
      } else if (nodeRefs.size() == 0) {
        // nothing found
        throw new AlfrescoRuntimeException(
            "No root found for device: \n" + "   root path: " + rootPath);
      } else {
        // we found a node
        rootNodeRef = nodeRefs.get(0);
      }

      return rootNodeRef;
    }
Ejemplo n.º 10
0
  public boolean nodeMatches(NodeRef nodeRef, Set<QName> expectedTypes, Set<QName> excludedTypes) {
    if (!nodeService.exists(nodeRef)) {
      throw new EntityNotFoundException(nodeRef.getId());
    }

    QName type = nodeService.getType(nodeRef);

    Set<QName> allExpectedTypes = new HashSet<QName>();
    if (expectedTypes != null) {
      for (QName expectedType : expectedTypes) {
        allExpectedTypes.addAll(dictionaryService.getSubTypes(expectedType, true));
      }
    }

    Set<QName> allExcludedTypes = new HashSet<QName>();
    if (excludedTypes != null) {
      for (QName excludedType : excludedTypes) {
        allExcludedTypes.addAll(dictionaryService.getSubTypes(excludedType, true));
      }
    }

    boolean inExpected = allExpectedTypes.contains(type);
    boolean excluded = allExcludedTypes.contains(type);
    return (inExpected && !excluded);
  }
 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.º 12
0
 /**
  * Returns human readable path for node. To improve performance may return simple toString()
  * method of the path.
  *
  * @param nodeRef
  * @return Human readable path for node
  */
 private String getNodePath(NodeRef nodeRef) {
   String result = null;
   if (nodeService.exists(nodeRef)) {
     Path path = nodeService.getPath(nodeRef);
     return path.toPrefixString(namespacePrefixResolver);
   }
   return result;
 }
  /**
   * Tests that read only methods don't create the shared credentials container, but that write ones
   * will do.
   */
  @Test
  public void testSharedCredentialsContainer() throws Exception {
    // Run as a test user
    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER_ONE);

    // To start with, the container shouldn't be there
    NodeRef container =
        ((RemoteCredentialsServiceImpl) PRIVATE_REMOTE_CREDENTIALS_SERVICE)
            .getSharedContainerNodeRef(false);
    if (container != null) {
      // Tidy up
      AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();

      // Zap the container
      PUBLIC_NODE_SERVICE.deleteNode(container);
    }

    // Run as a test user
    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER_ONE);

    // Ask for the list of shared remote systems
    REMOTE_CREDENTIALS_SERVICE.listSharedRemoteSystems(new PagingRequest(10));

    // Won't have been created by a read
    container =
        ((RemoteCredentialsServiceImpl) PRIVATE_REMOTE_CREDENTIALS_SERVICE)
            .getSharedContainerNodeRef(false);
    assertEquals(null, container);

    // Try to store some credentials
    PasswordCredentialsInfo credentials = new PasswordCredentialsInfoImpl();
    REMOTE_CREDENTIALS_SERVICE.createSharedCredentials(TEST_REMOTE_SYSTEM_ONE, credentials);

    // It will now exist
    container =
        ((RemoteCredentialsServiceImpl) PRIVATE_REMOTE_CREDENTIALS_SERVICE)
            .getSharedContainerNodeRef(false);
    assertNotNull(container);

    // Should have a marker aspect, and the specified name
    Set<QName> cAspects = PUBLIC_NODE_SERVICE.getAspects(container);
    assertEquals(
        "Aspect missing, found " + cAspects,
        true,
        cAspects.contains(RemoteCredentialsModel.ASPECT_REMOTE_CREDENTIALS_SYSTEM_CONTAINER));
    assertEquals(
        SHARED_SYSTEM_CONTAINER_NAME,
        PUBLIC_NODE_SERVICE.getProperty(container, ContentModel.PROP_NAME));

    // Should have single node in it
    assertEquals(1, PUBLIC_NODE_SERVICE.getChildAssocs(container).size());

    // Tidy up
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();

    // Zap the container
    PUBLIC_NODE_SERVICE.deleteNode(container);
  }
 /**
  * Returns all the classes of a node, including its type and aspects.
  *
  * @param nodeRef node reference
  * @return List<QName> list of classes
  */
 private List<QName> getInvokeClasses(NodeRef nodeRef) {
   List<QName> result = new ArrayList<QName>(10);
   result.add(nodeService.getType(nodeRef));
   Set<QName> aspects = nodeService.getAspects(nodeRef);
   for (QName aspect : aspects) {
     result.add(aspect);
   }
   return result;
 }
Ejemplo n.º 15
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());
  }
  /** Check that omitting all downgrade fields is valid. */
  @Test
  public void testCheckConsistencyOfProperties_notSpecified() {
    when(mockNodeService.hasAspect(NODE_REF, ASPECT_CLASSIFIED)).thenReturn(true);
    when(mockNodeService.getProperty(NODE_REF, PROP_DOWNGRADE_DATE)).thenReturn(null);
    when(mockNodeService.getProperty(NODE_REF, PROP_DOWNGRADE_EVENT)).thenReturn(null);
    when(mockNodeService.getProperty(NODE_REF, PROP_DOWNGRADE_INSTRUCTIONS)).thenReturn(null);

    classifiedAspect.checkConsistencyOfProperties(NODE_REF);
  }
  /** Check that an event without instructions throws an exception. */
  @Test(expected = MissingDowngradeInstructions.class)
  public void testCheckConsistencyOfProperties_eventMissingInstructions() {
    when(mockNodeService.hasAspect(NODE_REF, ASPECT_CLASSIFIED)).thenReturn(true);
    when(mockNodeService.getProperty(NODE_REF, PROP_DOWNGRADE_DATE)).thenReturn(null);
    when(mockNodeService.getProperty(NODE_REF, PROP_DOWNGRADE_EVENT)).thenReturn("Event");
    when(mockNodeService.getProperty(NODE_REF, PROP_DOWNGRADE_INSTRUCTIONS)).thenReturn(null);

    classifiedAspect.checkConsistencyOfProperties(NODE_REF);
  }
 @Override
 public Set<NodeRef> findFrom(NodeRef thisNode) {
   Set<NodeRef> result = Collections.emptySet();
   if (nodeService.exists(thisNode)
       && (WebSiteModel.TYPE_INDEX_PAGE.equals(nodeService.getType(thisNode)))) {
     result = new HashSet<NodeRef>();
     result.add(nodeService.getPrimaryParent(thisNode).getParentRef());
   }
   return result;
 }
  /**
   * Most of the shared credentials container tests work on the test one, so that things are in a
   * known and empty state. We have this one test that uses the real shared container, just to check
   * that it's correctly setup and available
   */
  @Test
  public void testRealSharedCredentialsContainer() throws Exception {
    // Create a new instance, using the real container
    RemoteCredentialsServiceImpl realService = new RemoteCredentialsServiceImpl();
    realService.setDictionaryService(DICTIONARY_SERVICE);
    realService.setNamespaceService(NAMESPACE_SERVICE);
    realService.setNodeService(PUBLIC_NODE_SERVICE);
    realService.setRepositoryHelper(REPOSITORY_HELPER);

    for (Entry<QName, RemoteCredentialsInfoFactory> e :
        ((RemoteCredentialsServiceImpl) PRIVATE_REMOTE_CREDENTIALS_SERVICE)
            .getCredentialsFactories()
            .entrySet()) {
      realService.registerCredentialsFactory(e.getKey(), e.getValue());
    }

    // Run as a test user
    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER_ONE);

    // Do a create / fetch / delete step
    PasswordCredentialsInfoImpl pwCredI = new PasswordCredentialsInfoImpl();
    pwCredI.setRemoteUsername(TEST_REMOTE_USERNAME_ONE);
    pwCredI.setRemotePassword(TEST_USER_THREE);
    BaseCredentialsInfo credentials = null;

    try {
      // Create
      credentials = realService.createSharedCredentials(TEST_REMOTE_SYSTEM_ONE, pwCredI);
      assertEquals(TEST_REMOTE_USERNAME_ONE, credentials.getRemoteUsername());

      // Update
      ((PasswordCredentialsInfoImpl) credentials).setRemoteUsername(TEST_REMOTE_USERNAME_TWO);
      ((PasswordCredentialsInfoImpl) credentials).setRemotePassword(TEST_USER_ONE);
      credentials = realService.updateCredentials(credentials);
      assertEquals(TEST_REMOTE_USERNAME_TWO, credentials.getRemoteUsername());

      // Delete
      realService.deleteCredentials(credentials);

      // Tidy, and zap the test parent
      PUBLIC_NODE_SERVICE.deleteNode(credentials.getRemoteSystemContainerNodeRef());
      credentials = null;
    } finally {
      // Tidy up if needed
      if (credentials != null) {
        AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();

        // Zap the credentials themselves
        PUBLIC_NODE_SERVICE.deleteNode(credentials.getNodeRef());

        // And their test parent
        PUBLIC_NODE_SERVICE.deleteNode(credentials.getRemoteSystemContainerNodeRef());
      }
    }
  }
  /**
   * @see CheckOutCheckInService#getWorkingCopy(NodeRef)
   * @see CheckOutCheckInService#getCheckedOut(NodeRef)
   */
  public void testBidirectionalReferences() {
    final NodeRef origNodeRef =
        nodeService
            .createNode(
                this.rootNodeRef,
                ContentModel.ASSOC_CHILDREN,
                QName.createQName("test2"),
                ContentModel.TYPE_CONTENT)
            .getChildRef();

    NodeRef wk1 = cociService.getWorkingCopy(origNodeRef);
    assertNull(wk1);

    // Check the document out
    final NodeRef workingCopy = cociService.checkout(origNodeRef);
    assertTrue(
        "Expect cm:workingcopy aspect",
        nodeService.hasAspect(workingCopy, ContentModel.ASPECT_WORKING_COPY));
    assertTrue(
        "Expect cm:checkedOut aspect",
        nodeService.hasAspect(origNodeRef, ContentModel.ASPECT_CHECKED_OUT));
    List<AssociationRef> targetAssocs =
        nodeService.getTargetAssocs(origNodeRef, ContentModel.ASSOC_WORKING_COPY_LINK);
    assertEquals("Expect a 1:1 relationship", 1, targetAssocs.size());
    List<AssociationRef> sourceAssocs =
        nodeService.getSourceAssocs(workingCopy, ContentModel.ASSOC_WORKING_COPY_LINK);
    assertEquals("Expect a 1:1 relationship", 1, sourceAssocs.size());

    // Need to commit the transaction in order to get the indexer to run
    setComplete();
    endTransaction();

    final NodeRef finalNodeRef = origNodeRef;

    this.transactionService
        .getRetryingTransactionHelper()
        .doInTransaction(
            new RetryingTransactionCallback<Object>() {
              public Object execute() {
                NodeRef wk2 = cociService.getWorkingCopy(finalNodeRef);
                assertNotNull(wk2);
                assertEquals(workingCopy, wk2);
                NodeRef orig2 = cociService.getCheckedOut(wk2);
                assertNotNull(orig2);
                assertEquals(origNodeRef, orig2);

                cociService.cancelCheckout(workingCopy);
                return null;
              }
            });

    NodeRef wk3 = cociService.getWorkingCopy(this.nodeRef);
    assertNull(wk3);
  }
Ejemplo n.º 21
0
  public DownloadRequest getDownloadRequest(NodeRef downloadNodeRef) {
    validateNode(downloadNodeRef);
    Map<QName, Serializable> properties = nodeService.getProperties(downloadNodeRef);

    List<AssociationRef> requestedNodes =
        nodeService.getTargetAssocs(downloadNodeRef, DownloadModel.ASSOC_REQUESTED_NODES);

    return new DownloadRequest(
        (Boolean) properties.get(DownloadModel.PROP_RECURSIVE),
        requestedNodes,
        (String) properties.get(ContentModel.PROP_CREATOR));
  }
  /**
   * Removes unwanted aspects
   *
   * @param nodeService
   * @param nodeRef
   */
  protected void cleanDisposableItem(NodeService nodeService, NodeRef nodeRef) {
    // Remove unwanted aspects
    for (QName aspect : unwantedAspects) {
      if (nodeService.hasAspect(nodeRef, aspect)) {
        nodeService.removeAspect(nodeRef, aspect);
      }
    }

    // remove the current disposition action (if there is one)
    DispositionAction dispositionAction = dispositionService.getNextDispositionAction(nodeRef);
    if (dispositionAction != null) {
      nodeService.deleteNode(dispositionAction.getNodeRef());
    }
  }
Ejemplo n.º 23
0
  @Override
  protected void executeImpl(Action action, NodeRef nodeRef) {
    String usernameAuth = authenticate();
    NodeService nodeService = serviceRegistry.getNodeService();
    NodeRef parentNodeRef = nodeService.getPrimaryParent(nodeRef).getParentRef();

    if (nodeService.hasAspect(nodeRef, documentSimpleRM)) {
      if (nodeService.hasAspect(parentNodeRef, expedientRM)) {
        updateExpedient(nodeService, nodeRef, parentNodeRef);

      } else if (nodeService.hasAspect(parentNodeRef, agregacioRM)) {
        updateAgregacio(nodeService, nodeRef, parentNodeRef);
      }

    } else if (nodeService.hasAspect(nodeRef, expedientRM)) {
      updateSerie(nodeService, nodeRef, parentNodeRef);

    } else if (nodeService.hasAspect(nodeRef, agregacioRM)) {
      updateSerie(nodeService, nodeRef, parentNodeRef);

    } else if (nodeService.hasAspect(nodeRef, serieRM)) {
      updateFons(nodeService, nodeRef, parentNodeRef);
    }

    AuthenticationUtil.setRunAsUser(usernameAuth);
    AuthenticationUtil.setFullyAuthenticatedUser(usernameAuth);
  }
  /** @return */
  private NodeRef checkout() {
    // Check out the node
    NodeRef workingCopy =
        cociService.checkout(
            this.nodeRef,
            this.rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName("workingCopy"));
    assertNotNull(workingCopy);

    // System.out.println(NodeStoreInspector.dumpNodeStore(this.nodeService, this.storeRef));

    // Ensure that the working copy and copy aspect has been applied
    assertTrue(nodeService.hasAspect(workingCopy, ContentModel.ASPECT_WORKING_COPY));
    assertTrue(nodeService.hasAspect(workingCopy, ContentModel.ASPECT_COPIEDFROM));

    // Check that the working copy owner has been set correctly
    assertEquals(
        this.userNodeRef,
        nodeService.getProperty(workingCopy, ContentModel.PROP_WORKING_COPY_OWNER));

    // Check that the working copy name has been set correctly
    String name = (String) this.nodeService.getProperty(this.nodeRef, PROP_NAME_QNAME);
    String expectedWorkingCopyLabel = I18NUtil.getMessage("coci_service.working_copy_label");
    String expectedWorkingCopyName =
        ((CheckOutCheckInServiceImpl) this.cociService)
            .createWorkingCopyName(name, expectedWorkingCopyLabel);
    String workingCopyName = (String) this.nodeService.getProperty(workingCopy, PROP_NAME_QNAME);
    assertEquals(expectedWorkingCopyName, workingCopyName);
    // Check a record has been kept of the working copy label used to create the working copy name
    assertEquals(
        "No record of working copy label kept",
        expectedWorkingCopyLabel,
        nodeService.getProperty(workingCopy, ContentModel.PROP_WORKING_COPY_LABEL));

    // Ensure that the content has been copied correctly
    ContentReader contentReader =
        this.contentService.getReader(this.nodeRef, ContentModel.PROP_CONTENT);
    assertNotNull(contentReader);
    ContentReader contentReader2 =
        this.contentService.getReader(workingCopy, ContentModel.PROP_CONTENT);
    assertNotNull(contentReader2);
    assertEquals(
        "The content string of the working copy should match the original immediatly after checkout.",
        contentReader.getContentString(),
        contentReader2.getContentString());

    return workingCopy;
  }
  @Test
  public void cloud928() {
    final NodeRef node =
        testNodes.createNodeWithTextContent(
            userHome,
            "CLOUD-928 Test Node",
            ContentModel.TYPE_CONTENT,
            user1.getUsername(),
            "Quick Share Test Node Content");

    QuickShareDTO dto = share(node, user1.getUsername());

    attributeService.removeAttribute(QuickShareServiceImpl.ATTR_KEY_SHAREDIDS_ROOT, dto.getId());

    AuthenticationUtil.runAs(
        new RunAsWork<Object>() {

          @Override
          public Object doWork() throws Exception {
            nodeService.deleteNode(node);
            return null;
          }
        },
        user1.getUsername());

    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
    Assert.assertFalse(nodeService.exists(node));
  }
Ejemplo n.º 26
0
  public NodeRef validateNode(NodeRef nodeRef) {
    if (!nodeService.exists(nodeRef)) {
      throw new EntityNotFoundException(nodeRef.getId());
    }

    return nodeRef;
  }
  /**
   * @see
   *     org.alfresco.repo.version.VersionServicePolicies.CalculateVersionLabelPolicy#calculateVersionLabel(org.alfresco.service.namespace.QName,
   *     org.alfresco.service.cmr.version.Version, int, java.util.Map)
   */
  public String calculateVersionLabel(
      final QName classRef,
      final Version preceedingVersion,
      final int versionNumber,
      final Map<String, Serializable> versionProperties) {
    String result = null;

    // Only set the base version if there's no prior version number (ie. when versioning is first
    // enabled)
    if (preceedingVersion == null) {
      NodeRef nodeRef = savedNodeRef.get();

      if (nodeRef != null) {
        String baseVersion =
            (String) nodeService.getProperty(nodeRef, PROPERTY_BASE_VERSION_NUMBER);

        if (baseVersion != null && baseVersion.trim().length() > 0) {
          result = baseVersion;
          savedNodeRef.remove();
        }
      }
    }

    if (result == null) {
      result =
          defaultPolicy.calculateVersionLabel(
              classRef, preceedingVersion, versionNumber, versionProperties);
    }

    return (result);
  }
  private NodeRef createFolderWithPermission(NodeRef parent, String username, String permission) {
    // Authenticate as system user because the current user should not be node owner
    AuthenticationComponent authenticationComponent =
        (AuthenticationComponent) this.applicationContext.getBean("authenticationComponent");
    authenticationComponent.setSystemUserAsCurrentUser();

    // Create the folder
    NodeRef folder =
        nodeService
            .createNode(
                parent,
                ContentModel.ASSOC_CHILDREN,
                QName.createQName("TestFolder" + GUID.generate()),
                ContentModel.TYPE_CONTENT)
            .getChildRef();

    // Apply permissions to folder
    permissionService.deletePermissions(folder);
    permissionService.setInheritParentPermissions(folder, false);
    permissionService.setPermission(folder, userName, permission, true);

    // Authenticate test user
    TestWithUserUtils.authenticateUser(
        this.userName, PWD, this.rootNodeRef, this.authenticationService);

    return folder;
  }
Ejemplo n.º 29
0
  @Override
  public void setUp() throws Exception {
    super.setUp();

    this.fileFolderService = (FileFolderService) ctx.getBean("FileFolderService");
    this.repositoryHelper = (Repository) ctx.getBean("repositoryHelper");
    this.nodeService = (NodeService) ctx.getBean("NodeService");
    this.transactionService = (TransactionService) ctx.getBean("transactionService");

    server.setServletAuthenticatorFactory(new LocalTestRunAsAuthenticatorFactory());

    NodeRef companyHomeNodeRef = repositoryHelper.getCompanyHome();
    String guid = GUID.generate();

    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());

    folderWithoutAspect =
        fileFolderService
            .create(companyHomeNodeRef, "folder_" + guid, ContentModel.TYPE_FOLDER)
            .getNodeRef();
    assertNotNull("Doesn't create folder", folderWithoutAspect);

    folderWithAspect =
        fileFolderService
            .create(companyHomeNodeRef, "folder_aspect_" + guid, ContentModel.TYPE_FOLDER)
            .getNodeRef();
    assertNotNull("Doesn't create folder", folderWithoutAspect);
    // add 'dublincore' aspect
    Map<QName, Serializable> aspectProps = new HashMap<QName, Serializable>(1);
    aspectProps.put(ContentModel.PROP_SUBJECT, "Test subject");
    nodeService.addAspect(folderWithAspect, ContentModel.ASPECT_DUBLINCORE, aspectProps);
  }
  private PersonFavourite addFavouriteSite(String userName, NodeRef nodeRef) {
    PersonFavourite favourite = null;

    SiteInfo siteInfo = siteService.getSite(nodeRef);
    if (siteInfo != null) {
      favourite = getFavouriteSite(userName, siteInfo);
      if (favourite == null) {
        Map<String, Serializable> preferences = new HashMap<String, Serializable>(1);

        String siteFavouritedKey = siteFavouritedKey(siteInfo);
        preferences.put(siteFavouritedKey, Boolean.TRUE);

        // ISO8601 string format: PreferenceService works with strings only for dates it seems
        String siteCreatedAtKey = siteCreatedAtKey(siteInfo);
        Date createdAt = new Date();
        String createdAtStr = ISO8601DateFormat.format(createdAt);
        preferences.put(siteCreatedAtKey, createdAtStr);

        preferenceService.setPreferences(userName, preferences);

        favourite =
            new PersonFavourite(
                userName, siteInfo.getNodeRef(), Type.SITE, siteInfo.getTitle(), createdAt);

        QName nodeClass = nodeService.getType(nodeRef);
        OnAddFavouritePolicy policy = onAddFavouriteDelegate.get(nodeRef, nodeClass);
        policy.onAddFavourite(userName, nodeRef);
      }
    } else {
      // shouldn't happen, getType recognizes it as a site or subtype
      logger.warn("Unable to get site for " + nodeRef);
    }

    return favourite;
  }