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);
  }
  /** @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);
      }
    }
  }
Beispiel #3
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.");
  }
 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>());
     }
   }
 }
  /** 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);
  }
  /** 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);
  }
  /** @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;
  }
  public int getSequenceNumber(NodeRef nodeRef) {
    validateNode(nodeRef);
    Serializable sequenceNumber =
        nodeService.getProperty(nodeRef, DownloadModel.PROP_SEQUENCE_NUMBER);

    return ((Integer) sequenceNumber).intValue();
  }
  /**
   * @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);
  }
 //    @Test
 public void testGetCompanyHome() {
   AuthenticationUtil.setFullyAuthenticatedUser(ADMIN_USER_NAME);
   NodeRef companyHome = demoComponent.getCompanyHome();
   assertNotNull(companyHome);
   String companyHomeName = (String) nodeService.getProperty(companyHome, ContentModel.PROP_NAME);
   assertNotNull(companyHomeName);
   assertEquals("Company Home", companyHomeName);
 }
  /**
   * 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);
  }
  public Serializable extractData(Serializable value) throws Throwable {
    NodeRef nodeRef = (NodeRef) value;

    String identifier =
        (String) nodeService.getProperty(nodeRef, RecordsManagementModel.PROP_IDENTIFIER);

    // Done
    return identifier;
  }
  /**
   * Return the file name for a node
   *
   * @param node NodeRef
   * @return String
   */
  public String getFileNameImpl(NodeRef node) {
    String fname = null;

    try {
      fname = (String) nodeService.getProperty(node, ContentModel.PROP_NAME);
    } catch (InvalidNodeRefException ex) {
    }

    return fname;
  }
  public void testAlfrescoCheckoutDoesNotModifyNode() {
    String adminUser = AuthenticationUtil.getAdminUserName();
    AuthenticationUtil.setFullyAuthenticatedUser(adminUser);

    Serializable initModifier = nodeService.getProperty(nodeRef, ContentModel.PROP_MODIFIER);
    Serializable initModified = nodeService.getProperty(nodeRef, ContentModel.PROP_MODIFIED);
    assertFalse("The initial modifier should not be Admin!", adminUser.equals(initModifier));

    NodeRef copy =
        cociService.checkout(
            nodeRef, rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("workingCopy"));

    Serializable modifier = nodeService.getProperty(nodeRef, ContentModel.PROP_MODIFIER);
    assertEquals("Checkout should not cause the modifier to change!", initModifier, modifier);
    Serializable modified = nodeService.getProperty(nodeRef, ContentModel.PROP_MODIFIED);
    assertEquals("Checkout should not cause the modified date to change!", initModified, modified);

    cociService.cancelCheckout(copy);
    modifier = nodeService.getProperty(nodeRef, ContentModel.PROP_MODIFIER);
    assertEquals(
        "Cancel checkout should not cause the modifier to change!", initModifier, modifier);
    modified = nodeService.getProperty(nodeRef, ContentModel.PROP_MODIFIED);
    assertEquals(
        "Cancel checkout should not cause the modified date to change!", initModified, modified);

    copy =
        cociService.checkout(
            nodeRef, rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("workingCopy"));
    Map<String, Serializable> versionProperties = new HashMap<String, Serializable>();
    versionProperties.put(Version.PROP_DESCRIPTION, "This is a test version");
    cociService.checkin(copy, versionProperties);

    modifier = nodeService.getProperty(nodeRef, ContentModel.PROP_MODIFIER);
    assertEquals("The modifier should change to Admin after checkin!", adminUser, modifier);
  }
  public Serializable extractData(Serializable value) throws Throwable {
    NodeRef nodeRef = (NodeRef) value;

    // Get path from the RM root
    List<NodeRef> nodeRefPath = rmService.getNodeRefPath(nodeRef);

    StringBuilder sb = new StringBuilder(128);
    for (NodeRef pathNodeRef : nodeRefPath) {
      String name = (String) nodeService.getProperty(pathNodeRef, ContentModel.PROP_NAME);
      sb.append("/").append(name);
    }

    // Done
    return sb.toString();
  }
Beispiel #16
0
  public void beforeDeleteNodeSite(NodeRef siteNodeRef) {
    String siteId = (String) nodeService.getProperty(siteNodeRef, ContentModel.PROP_NAME);

    Set<String> deletedSiteIds =
        (Set<String>) AlfrescoTransactionSupport.getResource(KEY_DELETED_SITE_IDS);
    if (deletedSiteIds == null) {
      deletedSiteIds =
          Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>()); // Java 6
      AlfrescoTransactionSupport.bindResource(KEY_DELETED_SITE_IDS, deletedSiteIds);
    }

    deletedSiteIds.add(siteId);

    AlfrescoTransactionSupport.bindListener(deleteSiteTransactionListener);
  }
  private PersonFavourite getFavouriteDocumentOrFolder(
      String userName, Type type, NodeRef nodeRef) {
    PersonFavourite favourite = null;

    PrefKeys prefKeys = getPrefKeys(type);
    Map<String, Serializable> preferences =
        preferenceService.getPreferences(userName, prefKeys.getSharePrefKey());
    String nodes = (String) preferences.get(prefKeys.getSharePrefKey());
    if (nodes != null) {
      Map<PersonFavouriteKey, PersonFavourite> favouriteNodes =
          extractFavouriteNodes(userName, type, nodes);
      String title = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_TITLE);
      PersonFavouriteKey key = new PersonFavouriteKey(userName, title, type, nodeRef);
      favourite = favouriteNodes.get(key);
    }
    return favourite;
  }
  /*
   * Extract favourite nodes of the given type from the comma-separated list in "nodes".
   */
  private Map<PersonFavouriteKey, PersonFavourite> extractFavouriteNodes(
      String userName, Type type, String nodes) {
    PrefKeys prefKeys = getPrefKeys(type);
    Map<PersonFavouriteKey, PersonFavourite> favouriteNodes =
        new HashMap<PersonFavouriteKey, PersonFavourite>();

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

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

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

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

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

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

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

    return favouriteNodes;
  }
Beispiel #19
0
  public void beforeDeleteNodePerson(NodeRef personNodeRef) {
    String userId = (String) nodeService.getProperty(personNodeRef, ContentModel.PROP_USERNAME);
    // MNT-9104 If username contains uppercase letters the action of joining a site will not be
    // displayed in "My activities"
    if (!userNamesAreCaseSensitive) {
      userId = userId.toLowerCase();
    }
    Set<String> deletedUserIds =
        (Set<String>) AlfrescoTransactionSupport.getResource(KEY_DELETED_USER_IDS);
    if (deletedUserIds == null) {
      deletedUserIds =
          Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>()); // Java 6
      AlfrescoTransactionSupport.bindResource(KEY_DELETED_USER_IDS, deletedUserIds);
    }

    deletedUserIds.add(userId);

    AlfrescoTransactionSupport.bindListener(deletePersonTransactionListener);
  }
  private PersonFavourite addFavouriteDocumentOrFolder(
      String userName, Type type, NodeRef nodeRef) {
    Map<PersonFavouriteKey, PersonFavourite> personFavourites = getFavouriteNodes(userName, type);
    PersonFavourite personFavourite = getPersonFavourite(userName, type, nodeRef);
    if (personFavourite == null) {
      Date createdAt = new Date();
      final String name = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_NAME);
      personFavourite = new PersonFavourite(userName, nodeRef, type, name, createdAt);
      personFavourites.put(personFavourite.getKey(), personFavourite);
      updateFavouriteNodes(userName, type, personFavourites);

      QName nodeClass = nodeService.getType(nodeRef);
      final String finalRef = nodeRef.getId();
      final QName nodeType = nodeClass;

      eventPublisher.publishEvent(
          new EventPreparator() {
            @Override
            public Event prepareEvent(String user, String networkId, String transactionId) {
              return new ActivityEvent(
                  "favorite.added",
                  transactionId,
                  networkId,
                  user,
                  finalRef,
                  null,
                  nodeType == null ? null : nodeType.toString(),
                  Client.asType(ClientType.script),
                  null,
                  name,
                  null,
                  0l,
                  null);
            }
          });

      OnAddFavouritePolicy policy = onAddFavouriteDelegate.get(nodeRef, nodeClass);
      policy.onAddFavourite(userName, nodeRef);
    }

    return personFavourite;
  }
Beispiel #21
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");
  }
Beispiel #22
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.");
  }
Beispiel #23
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.");
  }
Beispiel #24
0
  // TODO filter CMIS properties
  private Properties getCMISProperties(NodeRef nodeRef) {
    CMISNodeInfoImpl nodeInfo = cmisConnector.createNodeInfo(nodeRef);
    final Properties properties = cmisConnector.getNodeProperties(nodeInfo, null);

    // fake the title property, which CMIS doesn't give us
    String title = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_TITLE);
    final PropertyStringImpl titleProp =
        new PropertyStringImpl(ContentModel.PROP_TITLE.toString(), title);
    Properties wrapProperties =
        new Properties() {
          @Override
          public List<CmisExtensionElement> getExtensions() {
            return properties.getExtensions();
          }

          @Override
          public void setExtensions(List<CmisExtensionElement> extensions) {
            properties.setExtensions(extensions);
          }

          @Override
          public Map<String, PropertyData<?>> getProperties() {
            Map<String, PropertyData<?>> updatedProperties =
                new HashMap<String, PropertyData<?>>(properties.getProperties());
            updatedProperties.put(titleProp.getId(), titleProp);
            return updatedProperties;
          }

          @Override
          public List<PropertyData<?>> getPropertyList() {
            List<PropertyData<?>> propertyList =
                new ArrayList<PropertyData<?>>(properties.getPropertyList());
            propertyList.add(titleProp);
            return propertyList;
          }
        };

    return wrapProperties;
  }
  public void initMessages() {
    if (this.repositoryMessagesLocations != null) {
      // Register the messages found in the repository
      for (RepositoryLocation repositoryLocation : this.repositoryMessagesLocations) {
        StoreRef storeRef = repositoryLocation.getStoreRef();

        if (!nodeService.exists(storeRef)) {
          logger.info("StoreRef '" + storeRef + "' does not exist");
          continue; // skip this location
        }

        if (repositoryLocation.getQueryLanguage().equals(RepositoryLocation.LANGUAGE_PATH)) {
          List<NodeRef> nodeRefs =
              getNodes(storeRef, repositoryLocation, ContentModel.TYPE_CONTENT);

          if (nodeRefs.size() > 0) {
            List<String> resourceBundleBaseNames = new ArrayList<String>();

            for (NodeRef messageResource : nodeRefs) {
              String resourceName =
                  (String) nodeService.getProperty(messageResource, ContentModel.PROP_NAME);

              String bundleBaseName = messageService.getBaseBundleName(resourceName);

              if (!resourceBundleBaseNames.contains(bundleBaseName)) {
                resourceBundleBaseNames.add(bundleBaseName);
              }
            }
          }
        } else {
          logger.error(
              "Unsupported query language for messages location: "
                  + repositoryLocation.getQueryLanguage());
        }
      }
    }
  }
  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);
    }
  }
  /**
   * Helper method to extract file info from a specific node.
   *
   * <p>This method goes direct to the repo for all information and no data is cached here.
   *
   * @param nodeRef the node
   * @param readOnly, should the file be shown as "read only", regardless of its permissions?
   * @param lockedFilesAsOffline should a locked file be marked as offline
   * @return Returns the file information pertinent to the node
   * @throws FileNotFoundException if the path refers to a non-existent file
   */
  private ContentFileInfo getFileInformationImpl(
      NodeRef nodeRef, boolean readOnly, boolean lockedFilesAsOffline)
      throws FileNotFoundException {
    // get the file info
    org.alfresco.service.cmr.model.FileInfo fileFolderInfo = fileFolderService.getFileInfo(nodeRef);

    // retrieve required properties and create new JLAN file info
    ContentFileInfo fileInfo = new ContentFileInfo(nodeRef);

    // Set the file id from the node's DBID
    long id =
        DefaultTypeConverter.INSTANCE.convert(
            Long.class, nodeService.getProperty(nodeRef, ContentModel.PROP_NODE_DBID));
    fileInfo.setFileId((int) (id & 0xFFFFFFFFL));

    // unset all attribute flags
    int fileAttributes = 0;
    fileInfo.setFileAttributes(fileAttributes);

    if (fileFolderInfo.isFolder()) {
      // add directory attribute
      fileAttributes |= FileAttribute.Directory;
      fileInfo.setFileAttributes(fileAttributes);
      fileInfo.setFileType(FileType.Directory);
    } else {
      Map<QName, Serializable> nodeProperties = fileFolderInfo.getProperties();

      // Get the file size from the content

      ContentData contentData = (ContentData) nodeProperties.get(ContentModel.PROP_CONTENT);
      long size = 0L;
      if (contentData != null) {
        size = contentData.getSize();
      }
      fileInfo.setSize(size);

      // Set the allocation size by rounding up the size to a 512 byte block boundary

      if (size > 0) {
        fileInfo.setAllocationSize((size + 512L) & 0xFFFFFFFFFFFFFE00L);
      }

      // Check whether the file is locked

      if (nodeService.hasAspect(nodeRef, ContentModel.ASPECT_LOCKABLE)) {
        LockType lockType = lockService.getLockType(nodeRef);

        int attr = fileInfo.getFileAttributes();

        if (lockType != null) {
          switch (lockType) {
            case NODE_LOCK:
              if ((attr & FileAttribute.ReadOnly) == 0) attr += FileAttribute.ReadOnly;
              break;
            case WRITE_LOCK:
              LockStatus lockStatus = lockService.getLockStatus(nodeRef);
              if (lockStatus == LockStatus.LOCK_OWNER) {
              } else {
                if ((attr & FileAttribute.ReadOnly) == 0) {
                  attr += FileAttribute.ReadOnly;
                }

                if (lockedFilesAsOffline) {
                  attr += FileAttribute.NTOffline;
                }
              }
              break;
            case READ_ONLY_LOCK:
              if ((attr & FileAttribute.ReadOnly) == 0) {
                attr += FileAttribute.ReadOnly;
              }

              if (lockedFilesAsOffline) {
                attr += FileAttribute.NTOffline;
              }
              break;
          }

          fileInfo.setFileAttributes(attr);
        }
      }

      // Check if it is a link node

      if (fileFolderInfo.isLink()) {
        fileInfo.setLinkNodeRef(fileFolderInfo.getLinkNodeRef());
      }
    }

    // created
    Date createdDate = fileFolderInfo.getCreatedDate();
    if (createdDate != null) {
      long created = DefaultTypeConverter.INSTANCE.longValue(createdDate);
      fileInfo.setCreationDateTime(created);
    }
    // modified
    Date modifiedDate = fileFolderInfo.getModifiedDate();
    if (modifiedDate != null) {
      long modified = DefaultTypeConverter.INSTANCE.longValue(modifiedDate);
      fileInfo.setModifyDateTime(modified);
      fileInfo.setAccessDateTime(modified);
      fileInfo.setChangeDateTime(modified);
    }
    // name
    String name = fileFolderInfo.getName();
    if (name != null) {
      fileInfo.setFileName(name);

      // Check for file names that should be hidden
      if (hiddenAspect.getVisibility(Client.cifs, fileInfo.getNodeRef())
          == Visibility.HiddenAttribute) {
        // Add the hidden file attribute
        int attr = fileInfo.getFileAttributes();
        if ((attr & FileAttribute.Hidden) == 0) {
          attr += FileAttribute.Hidden;
          fileInfo.setFileAttributes(attr);
        }
      }
    }

    // Read/write access

    if (!fileFolderInfo.isFolder() || isReadOnlyFlagOnFolders) {
      boolean deniedPermission =
          permissionService.hasPermission(nodeRef, PermissionService.WRITE) == AccessStatus.DENIED;
      if (readOnly || deniedPermission) {
        int attr = fileInfo.getFileAttributes();
        if ((attr & FileAttribute.ReadOnly) == 0) {
          attr += FileAttribute.ReadOnly;
          fileInfo.setFileAttributes(attr);
        }
      }
    }

    // Set the normal file attribute if no other attributes are set

    if (fileInfo.getFileAttributes() == 0) fileInfo.setFileAttributes(FileAttribute.NTNormal);

    // Debug

    if (logger.isDebugEnabled()) {
      logger.debug("Fetched file info: \n" + "   info: " + fileInfo);
    }

    // Return the file information

    return fileInfo;
  }
  /** Perform the actual repository access, checking for the existence of a valid transaction */
  private void onDictionaryInitInTxn() {
    if (AlfrescoTransactionSupport.getTransactionReadState() == TxnReadState.TXN_NONE) {
      throw new IllegalStateException(
          "The Repository-based dictionary initialization has to be done in the context of a transaction.");
    }

    long startTime = System.currentTimeMillis();

    if (logger.isTraceEnabled()) {
      String tenantDomain = tenantAdminService.getCurrentUserDomain();
      logger.trace(
          "onDictionaryInit: ["
              + Thread.currentThread()
              + "]"
              + (tenantDomain.equals(TenantService.DEFAULT_DOMAIN)
                  ? ""
                  : " (Tenant: " + tenantDomain + ")"));
    }

    Collection<QName> modelsBefore = dictionaryDAO.getModels(true); // note: re-entrant
    int modelsBeforeCnt = (modelsBefore != null ? modelsBefore.size() : 0);

    List<String> loadedModels = new ArrayList<String>();

    if (this.repositoryModelsLocations != null) {
      // URI to model map
      Map<String, DynamicModelInfo> modelMap = new HashMap<String, DynamicModelInfo>();

      if (logger.isTraceEnabled()) {
        logger.trace("onDictionaryInit: locations=" + this.repositoryModelsLocations);
      }

      // Register the models found in the repository

      for (RepositoryLocation repositoryLocation : this.repositoryModelsLocations) {
        StoreRef storeRef = repositoryLocation.getStoreRef();

        if (!nodeService.exists(storeRef)) {
          logger.info("StoreRef '" + storeRef + "' does not exist");
          continue; // skip this location
        }

        List<NodeRef> nodeRefs = null;

        if (repositoryLocation.getQueryLanguage().equals(RepositoryLocation.LANGUAGE_PATH)) {
          nodeRefs = getNodes(storeRef, repositoryLocation, ContentModel.TYPE_DICTIONARY_MODEL);

          if (nodeRefs.size() > 0) {
            for (NodeRef dictionaryModel : nodeRefs) {
              try {
                // Ignore if the node is a working copy or archived, or if its inactive
                if (!(nodeService.hasAspect(dictionaryModel, ContentModel.ASPECT_WORKING_COPY)
                    || nodeService.hasAspect(dictionaryModel, ContentModel.ASPECT_ARCHIVED))) {
                  Boolean isActive =
                      (Boolean)
                          nodeService.getProperty(dictionaryModel, ContentModel.PROP_MODEL_ACTIVE);

                  if ((isActive != null) && (isActive.booleanValue() == true)) {
                    M2Model model = createM2Model(dictionaryModel);
                    if (model != null) {
                      if (logger.isTraceEnabled()) {
                        logger.trace(
                            "onDictionaryInit: " + model.getName() + " (" + dictionaryModel + ")");
                      }

                      for (M2Namespace namespace : model.getNamespaces()) {
                        modelMap.put(
                            namespace.getUri(),
                            new DynamicModelInfo(repositoryLocation, model, dictionaryModel));
                      }
                    }
                  }
                }
              } catch (InvalidNodeRefException inre) {
                // ignore - model no longer exists
                if (logger.isDebugEnabled()) {
                  logger.debug("onDictionaryInit: " + inre + " (assume concurrently deleted)");
                }

                continue;
              }
            }
          }
        } else {
          logger.error(
              "Unsupported query language for models location: "
                  + repositoryLocation.getQueryLanguage());
        }
      }

      // Load the models ensuring that they are loaded in the correct order
      for (Map.Entry<String, DynamicModelInfo> entry : modelMap.entrySet()) {
        RepositoryLocation importedLocation = entry.getValue().location;
        M2Model importedModel = entry.getValue().model;
        loadModel(modelMap, loadedModels, importedModel, importedLocation);
        notifyDynamicModelLoaded(entry.getValue());
      }
    }

    Collection<QName> modelsAfter = dictionaryDAO.getModels(true);
    int modelsAfterCnt = (modelsAfter != null ? modelsAfter.size() : 0);

    if (logger.isDebugEnabled()) {
      String tenantDomain = tenantAdminService.getCurrentUserDomain();
      logger.debug(
          "Model count: before="
              + modelsBeforeCnt
              + ", load/update="
              + loadedModels.size()
              + ", after="
              + modelsAfterCnt
              + " in "
              + (System.currentTimeMillis() - startTime)
              + " msecs ["
              + Thread.currentThread()
              + "] "
              + (tenantDomain.equals(TenantService.DEFAULT_DOMAIN)
                  ? ""
                  : " (Tenant: " + tenantDomain + ")"));
    }
  }
Beispiel #29
0
 private String getEmail(NodeRef person) {
   return (String) nodeService.getProperty(person, ContentModel.PROP_EMAIL);
 }
  /**
   * 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);
    }
  }