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

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

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

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

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

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

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

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

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

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

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

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

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

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

    preferences.put(prefKeys.getSharePrefKey(), values.toString());
    preferenceService.setPreferences(userName, preferences);
  }
Example #4
0
  /**
   * Helper to convert a path into an indexed path which uniquely identifies a node
   *
   * @param nodeRef
   * @param path
   * @return
   */
  private Path createIndexedPath(NodeRef nodeRef, Path path) {
    // Add indexes for same name siblings
    // TODO: Look at more efficient approach
    for (int i = path.size() - 1; i >= 0; i--) {
      Path.Element pathElement = path.get(i);
      if (i > 0 && pathElement instanceof Path.ChildAssocElement) {
        int index = 1; // for xpath index compatibility
        String searchPath = path.subPath(i).toPrefixString(namespaceService);
        List<NodeRef> siblings =
            searchService.selectNodes(nodeRef, searchPath, null, namespaceService, false);
        if (siblings.size() > 1) {
          ChildAssociationRef childAssoc = ((Path.ChildAssocElement) pathElement).getRef();
          NodeRef childRef = childAssoc.getChildRef();
          for (NodeRef sibling : siblings) {
            if (sibling.equals(childRef)) {
              childAssoc.setNthSibling(index);
              break;
            }
            index++;
          }
        }
      }
    }

    return path;
  }
 @Override
 public void deleteContent(CopyToEnvironmentItem item) {
   PersistenceManagerService persistenceManagerService =
       _servicesManager.getService(PersistenceManagerService.class);
   String fullPath =
       SITE_ENVIRONMENT_ROOT_PATTERN.replaceAll(SITE_REPLACEMENT_PATTERN, item.getSite());
   fullPath = fullPath.replaceAll(ENVIRONMENT_REPLACEMENT_PATTERN, WORK_AREA_REPOSITORY);
   fullPath = fullPath + item.getPath();
   NodeRef nodeRef = persistenceManagerService.getNodeRef(fullPath);
   if (nodeRef != null) {
     // _dmContentService.deleteContent(site, path, true, true, null);
     // return;
     List<String> paths = new ArrayList<String>();
     paths.add(item.getPath());
     _dmContentService.generateDeleteActivity(item.getSite(), paths, item.getUser());
     NodeRef parentNode = persistenceManagerService.getPrimaryParent(nodeRef).getParentRef();
     persistenceManagerService.deleteNode(nodeRef);
     persistenceManagerService.deleteObjectState(nodeRef.getId());
     List<FileInfo> children = persistenceManagerService.list(parentNode);
     while (children == null || children.size() < 1) {
       NodeRef helpNode = parentNode;
       parentNode = persistenceManagerService.getPrimaryParent(helpNode).getParentRef();
       persistenceManagerService.deleteNode(helpNode);
       children = persistenceManagerService.list(parentNode);
     }
   }
 }
Example #6
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;
  }
  private AuditMode onApplicationAudit(
      AuditMode auditMode,
      AuditState auditInfo,
      String source,
      String description,
      NodeRef key,
      Object... args) {
    AuditMode effectiveAuditMode =
        auditModel.beforeExecution(auditMode, source, description, key, args);
    auditModel.getAuditRecordOptions(source);
    if (auditMode != AuditMode.NONE) {
      if (source.equals(SYSTEM_APPLICATION)) {
        throw new AuditException(
            "Application audit can not use the reserved identifier " + SYSTEM_APPLICATION);
      }

      auditInfo.setAuditApplication(source);
      auditInfo.setAuditConfiguration(auditConfiguration);
      auditInfo.setAuditMethod(null);
      auditInfo.setAuditService(null);
      auditInfo.setClientAddress(null);
      auditInfo.setDate(new Date());
      auditInfo.setFail(false);
      auditInfo.setFiltered(false);
      auditInfo.setHostAddress(auditHost);
      auditInfo.setPath(null);
      if (key != null) {
        auditInfo.setKeyStore(key.getStoreRef());
        auditInfo.setKeyGUID(key.getId());
        RecordOptions recordOptions = auditModel.getAuditRecordOptions(source);
        if (recordOptions != null && recordOptions.getRecordPath() == TrueFalseUnset.TRUE) {
          auditInfo.setPath(getNodePath(key));
        }
      }
      auditInfo.setKeyPropertiesAfter(null);
      auditInfo.setKeyPropertiesBefore(null);
      auditInfo.setMessage(description);
      if (args != null) {
        Serializable[] serArgs = new Serializable[args.length];
        for (int i = 0; i < args.length; i++) {
          if (args[i] == null) {
            serArgs[i] = null;
          } else if (args[i] instanceof Serializable) {
            serArgs[i] = (Serializable) args[i];
          } else {
            serArgs[i] = args[i].toString();
          }
        }
        auditInfo.setMethodArguments(serArgs);
      }
      auditInfo.setReturnObject(null);
      auditInfo.setSessionId(null);
      auditInfo.setThrowable(null);
      auditInfo.setTxId(AlfrescoTransactionSupport.getTransactionId());
      auditInfo.setUserIdentifier(AuthenticationUtil.getFullyAuthenticatedUser());
    }

    return effectiveAuditMode;
  }
 /**
  * @param task
  * @return
  */
 private Object getPackageItemValues(WorkflowTask task) {
   List<NodeRef> items = workflowService.getPackageContents(task.getId());
   ArrayList<String> results = new ArrayList<String>(items.size());
   for (NodeRef item : items) {
     results.add(item.toString());
   }
   return results;
 }
Example #9
0
  /* (non-Javadoc)
   * @see org.alfresco.repo.tenant.TenantService#getName(org.alfresco.service.cmr.repository.NodeRef)
   */
  public NodeRef getName(NodeRef nodeRef) {
    if (nodeRef == null) {
      return null;
    }

    return new NodeRef(
        nodeRef.getStoreRef().getProtocol(),
        getName(nodeRef.getStoreRef().getIdentifier()),
        nodeRef.getId());
  }
Example #10
0
  @Override
  public void unLink(String specific) throws AfException {

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

    NodeService nodeService = ServiceHelper.getNodeService(afSession);

    NodeRef parent = getSpecifiedNode(specific);
    if (parent == null || !(nodeService.exists(parent))) {
      return;
    }

    List<ChildAssociationRef> parents = nodeService.getParentAssocs(nodeRef);

    for (ChildAssociationRef ref : parents) {

      if (ref.getParentRef().getId().equals(parent.getId())) {

        if (!ref.isPrimary()) {
          // not primary,delete
          nodeService.removeChildAssociation(ref);
          return;
        } else {
          // primary, it's not a good coding.f**k it!
          String rootId = AFCHelper.getNodeRefByPath(afSession, "/").getId();
          if (parents.size() <= 1) {
            if (rootId.equals(ref.getParentRef().getId())) {
              return;
            } else {
              moveTo("/", null);
              nodeService.removeChildAssociation(ref);
              return;
            }

          } else {
            // set the 2nd as the primary.moveTo
            for (ChildAssociationRef anotherP : parents) {
              if (!anotherP.equals(ref)) {
                String scndPId = anotherP.getParentRef().getId();

                nodeService.removeChildAssociation(anotherP);

                moveTo(scndPId, null);
                nodeService.removeChildAssociation(ref);
                return;
              }
            }
          }
        }
      }
    }
  }
Example #11
0
  /**
   * Create the specified home space if it does not exist, and return the ID
   *
   * @param locationId Parent location
   * @param spaceName Home space to create, can be null to simply return the parent
   * @param oldHomeFolderRef the previous home space, for the case where the the user is being
   *     updated. It may not have changed.
   * @param error True to throw an error if the space already exists, else ignore and return
   * @return ID of the home space
   */
  protected NodeRef createHomeSpace(
      String locationId, String spaceName, NodeRef oldHomeFolderRef, boolean error) {
    NodeRef homeSpaceNodeRef = null;
    if (spaceName != null && spaceName.length() != 0) {
      NodeRef parentRef = new NodeRef(Repository.getStoreRef(), locationId);

      // check for existence of home space with same name - return immediately
      // if it exists or throw an exception an give user chance to enter another name
      NodeRef childRef =
          this.getNodeService().getChildByName(parentRef, ContentModel.ASSOC_CONTAINS, spaceName);
      if (childRef != null) {
        if (childRef.equals(oldHomeFolderRef)) {
          return oldHomeFolderRef;
        }
        if (error) {
          throw new AlfrescoRuntimeException("A Home Space with the same name already exists.");
        } else {
          return childRef;
        }
      }

      // space does not exist already, create a new Space under it with
      // the specified name
      String qname = QName.createValidLocalName(spaceName);
      ChildAssociationRef assocRef =
          this.getNodeService()
              .createNode(
                  parentRef,
                  ContentModel.ASSOC_CONTAINS,
                  QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, qname),
                  ContentModel.TYPE_FOLDER);

      NodeRef nodeRef = assocRef.getChildRef();

      // set the name property on the node
      this.getNodeService().setProperty(nodeRef, ContentModel.PROP_NAME, spaceName);

      if (logger.isDebugEnabled()) logger.debug("Created Home Space for with name: " + spaceName);

      // apply the uifacets aspect - icon, title and description props
      Map<QName, Serializable> uiFacetsProps = new HashMap<QName, Serializable>(3);
      uiFacetsProps.put(ApplicationModel.PROP_ICON, CreateSpaceWizard.DEFAULT_SPACE_ICON_NAME);
      uiFacetsProps.put(ContentModel.PROP_TITLE, spaceName);
      this.getNodeService().addAspect(nodeRef, ApplicationModel.ASPECT_UIFACETS, uiFacetsProps);

      setupHomeSpacePermissions(nodeRef);

      // return the ID of the created space
      homeSpaceNodeRef = nodeRef;
    }

    return homeSpaceNodeRef;
  }
Example #12
0
  public List<Folder> getFolders() {
    List<Folder> folders = new ArrayList<>();

    NodeRef rootFolder = repository.getRootHome();

    // for (rootFolder.children)

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

    return folders;
  }
 @Override
 public void unLockItem(final String site, final String path) {
   GeneralLockService generalLockService =
       getServicesManager().getService(GeneralLockService.class);
   PersistenceManagerService persistenceManagerService =
       _servicesManager.getService(PersistenceManagerService.class);
   String rootPath = SITE_REPO_ROOT_PATTERN.replaceAll(SITE_REPLACEMENT_PATTERN, site);
   NodeRef nodeRef = persistenceManagerService.getNodeRef(rootPath, path);
   if (nodeRef != null) {
     generalLockService.unlock(nodeRef.getId());
   }
 }
Example #14
0
  /**
   * Helper method to set audited information after method invocation and to determine if auditing
   * should take place based on the method return value.
   *
   * @param auditMode
   * @param auditInfo
   * @param mi
   * @param returnObject
   * @return - the audit mode.
   */
  private AuditMode postInvocation(
      AuditMode auditMode, AuditState auditInfo, MethodInvocation mi, Object returnObject) {
    if (returnObject == null) {
      auditInfo.setReturnObject(null);
    } else if (returnObject instanceof Serializable) {
      auditInfo.setReturnObject((Serializable) returnObject);
    } else {
      auditInfo.setReturnObject(returnObject.toString());
    }

    Auditable auditable = mi.getMethod().getAnnotation(Auditable.class);
    if (auditable.key() == Auditable.Key.RETURN) {
      if (returnObject != null) {
        if (returnObject instanceof NodeRef) {
          NodeRef key = (NodeRef) returnObject;
          auditInfo.setKeyStore(key.getStoreRef());
          auditInfo.setKeyGUID(key.getId());
          RecordOptions recordOptions = auditModel.getAuditRecordOptions(mi);
          if (recordOptions != null && recordOptions.getRecordPath() == TrueFalseUnset.TRUE) {
            auditInfo.setPath(getNodePath(key));
          }
        } else if (returnObject instanceof StoreRef) {
          auditInfo.setKeyStore((StoreRef) returnObject);
        } else if (returnObject instanceof ChildAssociationRef) {
          ChildAssociationRef car = (ChildAssociationRef) returnObject;
          auditInfo.setKeyStore(car.getChildRef().getStoreRef());
          auditInfo.setKeyGUID(car.getChildRef().getId());
          RecordOptions recordOptions = auditModel.getAuditRecordOptions(mi);
          if (recordOptions != null && recordOptions.getRecordPath() == TrueFalseUnset.TRUE) {
            auditInfo.setPath(nodeService.getPath(car.getChildRef()).toString());
          }
        } else {
          logger.warn(
              "Key argument is not a node, store or child assoc ref for return object on "
                  + publicServiceIdentifier.getPublicServiceName(mi)
                  + "."
                  + mi.getMethod().getName()
                  + " it is "
                  + returnObject.getClass().getName());
        }
      }
    }

    // If the user name is not set, try and set it after the method call.
    // This covers authentication when the user is only known after the call.

    if (auditInfo.getUserIdentifier() == null) {
      auditInfo.setUserIdentifier(AuthenticationUtil.getFullyAuthenticatedUser());
    }

    return auditMode;
  }
Example #15
0
  /* (non-Javadoc)
   * @see org.alfresco.repo.tenant.TenantService#getName(org.alfresco.service.cmr.repository.NodeRef, org.alfresco.service.namespace.QName)
   */
  public QName getName(NodeRef inNodeRef, QName name) {
    // Check that all the passed values are not null
    ParameterCheck.mandatory("InNodeRef", inNodeRef);
    ParameterCheck.mandatory("Name", name);

    int idx = inNodeRef.getStoreRef().getIdentifier().lastIndexOf(SEPARATOR);
    if (idx != -1) {
      String tenantDomain = inNodeRef.getStoreRef().getIdentifier().substring(1, idx);
      checkTenantEnabled(tenantDomain);
      return getName(name, tenantDomain);
    }

    return name;
  }
  private Map<QName, Serializable> getAndAssertProperties(NodeRef nodeRef, String versionLabel) {
    assertNotNull("NodeRef of document is NULL!", nodeRef);

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

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

    return properties;
  }
 @Override
 public void setSystemProcessing(String site, List<String> paths, boolean isSystemProcessing) {
   PersistenceManagerService persistenceManagerService =
       _servicesManager.getService(PersistenceManagerService.class);
   List<String> objectIds = new ArrayList<String>();
   String rootPath = SITE_REPO_ROOT_PATTERN.replaceAll(SITE_REPLACEMENT_PATTERN, site);
   for (String relativePath : paths) {
     NodeRef nodeRef = persistenceManagerService.getNodeRef(rootPath, relativePath);
     if (nodeRef != null) {
       objectIds.add(nodeRef.getId());
     }
   }
   persistenceManagerService.setSystemProcessingBulk(objectIds, isSystemProcessing);
 }
  /** @return Returns true if the pattern is present, otherwise false. */
  public boolean contains(
      NodeRef nodeRef,
      QName propertyQName,
      String googleLikePattern,
      SearchParameters.Operator defaultOperator) {
    ResultSet resultSet = null;
    try {
      // build Lucene search string specific to the node
      StringBuilder sb = new StringBuilder();
      sb.append("+ID:\"")
          .append(nodeRef.toString())
          .append("\" +(TEXT:(")
          .append(googleLikePattern.toLowerCase())
          .append(") ");
      if (propertyQName != null) {
        sb.append(" OR @")
            .append(
                SearchLanguageConversion.escapeLuceneQuery(
                    QName.createQName(
                            propertyQName.getNamespaceURI(),
                            ISO9075.encode(propertyQName.getLocalName()))
                        .toString()));
        sb.append(":(").append(googleLikePattern.toLowerCase()).append(")");
      } else {
        for (QName key : nodeService.getProperties(nodeRef).keySet()) {
          sb.append(" OR @")
              .append(
                  SearchLanguageConversion.escapeLuceneQuery(
                      QName.createQName(key.getNamespaceURI(), ISO9075.encode(key.getLocalName()))
                          .toString()));
          sb.append(":(").append(googleLikePattern.toLowerCase()).append(")");
        }
      }
      sb.append(")");

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

      resultSet = this.query(sp);
      boolean answer = resultSet.length() > 0;
      return answer;
    } finally {
      if (resultSet != null) {
        resultSet.close();
      }
    }
  }
Example #19
0
  public NodeRef validateNode(NodeRef nodeRef) {
    if (!nodeService.exists(nodeRef)) {
      throw new EntityNotFoundException(nodeRef.getId());
    }

    return nodeRef;
  }
Example #20
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);
  }
Example #21
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);
    }
  }
 @Override
 public void stateTransition(String site, List<String> paths, TransitionEvent event) {
   PersistenceManagerService persistenceManagerService =
       _servicesManager.getService(PersistenceManagerService.class);
   List<String> objectIds = new ArrayList<String>();
   String rootPath = SITE_REPO_ROOT_PATTERN.replaceAll(SITE_REPLACEMENT_PATTERN, site);
   for (String relativePath : paths) {
     NodeRef nodeRef = persistenceManagerService.getNodeRef(rootPath, relativePath);
     if (nodeRef != null) {
       objectIds.add(nodeRef.getId());
     }
   }
   ObjectStateService.TransitionEvent convertedEvent = eventConversionMap.get(event);
   ObjectStateService.State defaultState = defaultStateForEvent.get(event);
   persistenceManagerService.transitionBulk(objectIds, convertedEvent, defaultState);
 }
Example #23
0
  /* (non-Javadoc)
   * @see org.alfresco.repo.tenant.TenantService#getName(org.alfresco.service.cmr.repository.NodeRef, org.alfresco.service.cmr.repository.NodeRef)
   */
  public NodeRef getName(NodeRef inNodeRef, NodeRef nodeRef) {
    if (inNodeRef == null || nodeRef == null) {
      return null;
    }

    int idx = inNodeRef.getStoreRef().getIdentifier().lastIndexOf(SEPARATOR);
    if (idx != -1) {
      String tenantDomain = inNodeRef.getStoreRef().getIdentifier().substring(1, idx);
      return new NodeRef(
          nodeRef.getStoreRef().getProtocol(),
          getName(nodeRef.getStoreRef().getIdentifier(), tenantDomain),
          nodeRef.getId());
    }

    return nodeRef;
  }
  @Override
  protected void executeImpl(Action action, NodeRef actionedUponNodeRef) {
    if (tracer.isDebugEnabled()) tracer.debug("DocumentAEMarkDocumentAdd action, execution init");

    String markArea = (String) action.getParameterValue(PARAM_MARK_AREA);
    if (markArea == null) {
      tracer.error("no markFileName specified for RCS mark prepare.");
      throw new MarkFailedException("no markFileName specified for RCS mark prepare.");
    }

    MarkDocumentArea markDocumentArea = MarkDocumentArea.fromBase64String(markArea);

    List<MarkDocument> docs = markDocumentArea.getDocuments();
    if (docs == null) {
      docs = new ArrayList<MarkDocument>();
      markDocumentArea.setDocuments(docs);
    }

    MarkDocument doc = new MarkDocument();
    doc.setNodeRefId(actionedUponNodeRef.getId());
    if (!docs.contains(doc)) docs.add(doc);

    action.setParameterValue(PARAM_RESULT, markDocumentArea.toBase64String());

    if (tracer.isDebugEnabled()) tracer.debug("DocumentAEMarkDocumentAdd action, execution end");
  }
  public void testBasicCommitContent() throws Exception {
    startNewTransaction();
    TransferManifestNormalNode node = null;

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

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

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

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

    bs.write(byteArray, 0, byteArray.length);
    String content = bs.toString();
    assertEquals(content, dummyContent);
  }
 /**
  * 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);
   }
 }
Example #27
0
  private Map<String, String> buildArgs(
      Map<String, String> properties, NodeRef inviter, NodeRef invitee) {
    String params = buildUrlParamString(properties);
    String serverPath = properties.get(wfVarServerPath);
    String acceptLink = serverPath + properties.get(wfVarAcceptUrl) + params;
    String rejectLink = serverPath + properties.get(wfVarRejectUrl) + params;

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