コード例 #1
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;
  }
コード例 #2
0
 private List<TemplateNode> buildMixedNodeList(Collection<ChildAssociationRef> cars) {
   List<TemplateNode> nodes = new ArrayList<TemplateNode>(cars.size());
   int i = 0;
   for (ChildAssociationRef car : cars) {
     QName type = services.getNodeService().getType(car.getChildRef());
     if (services.getDictionaryService().isSubClass(type, ContentModel.TYPE_CATEGORY)) {
       nodes.add(new CategoryTemplateNode(car.getChildRef(), this.services, this.imageResolver));
     } else {
       nodes.add(new TemplateNode(car.getChildRef(), this.services, this.imageResolver));
     }
   }
   return nodes;
 }
コード例 #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.");
  }
コード例 #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;
  }
コード例 #5
0
  private static NodeRef followAssociations(
      ServiceRegistry services,
      ChildAssociationRef association,
      QName qnameType,
      String[] navigation,
      int indexNavigation)
      throws InvalidAssociationException, InvalidContentException {
    NodeRef finalTarget = null;
    String uri = qnameType.getNamespaceURI();
    if (association.getQName().toString().contains(uri)
        && association.getQName().toString().contains(navigation[indexNavigation])) {
      NodeRef target = association.getChildRef();
      if (target != null) {
        if (indexNavigation < navigation.length - 2) {
          QName targetType = services.getNodeService().getType(target);
          List<ChildAssociationRef> nextAssociations =
              services.getNodeService().getChildAssocs(target);
          for (ChildAssociationRef nextAssociation : nextAssociations) {
            followAssociations(
                services, nextAssociation, targetType, navigation, indexNavigation++);
          }
        } else {
          finalTarget = target;
        }
      } else {
        throw new InvalidContentException(InvalidContentException.DOES_NOT_EXISTS);
      }
    } else {
      throw new InvalidAssociationException(InvalidAssociationException.DOES_NOT_EXISTS);
    }

    return finalTarget;
  }
コード例 #6
0
ファイル: AbstractSysObject.java プロジェクト: yanglogan/zgh
  @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;
  }
コード例 #7
0
 /**
  * Support to build node lists from category service API calls.
  *
  * @param childRefs Collection<ChildAssociationRef>
  * @return List of TemplateNode
  */
 private List<TemplateNode> buildTemplateNodeList(Collection<ChildAssociationRef> childRefs) {
   List<TemplateNode> answer = new ArrayList<TemplateNode>(childRefs.size());
   for (ChildAssociationRef ref : childRefs) {
     // create our Node representation from the NodeRef
     TemplateNode child = new TemplateNode(ref.getChildRef(), this.services, this.imageResolver);
     answer.add(child);
   }
   return answer;
 }
コード例 #8
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;
  }
コード例 #9
0
  /* (non-Javadoc)
   * @see org.alfresco.repo.tenant.TenantService#getBaseName(org.alfresco.service.cmr.repository.ChildAssociationRef)
   */
  public ChildAssociationRef getBaseName(ChildAssociationRef childAssocRef) {
    if (childAssocRef == null) {
      return null;
    }

    return new ChildAssociationRef(
        childAssocRef.getTypeQName(),
        getBaseName(childAssocRef.getParentRef()),
        childAssocRef.getQName(),
        getBaseName(childAssocRef.getChildRef()),
        childAssocRef.isPrimary(),
        childAssocRef.getNthSibling());
  }
コード例 #10
0
 /**
  * Retrieves the forum node the the given discussable
  *
  * @return Returns the <b>fm:forum</b> node or <tt>null</tt>
  */
 private NodeRef getForum(NodeRef discussableNodeRef) {
   List<ChildAssociationRef> destChildren =
       nodeService.getChildAssocs(
           discussableNodeRef, ForumModel.ASSOC_DISCUSSION, RegexQNamePattern.MATCH_ALL);
   // Take the first one
   if (destChildren.size() == 0) {
     return null;
   } else {
     // We just take the first one
     ChildAssociationRef discussionAssoc = destChildren.get(0);
     return discussionAssoc.getChildRef();
   }
 }
 @Override
 public void onCreateNode(ChildAssociationRef childAssociationRef) {
   NodeRef nodeRef = childAssociationRef.getChildRef();
   // Bind the listener to the transaction
   AlfrescoTransactionSupport.bindListener(transactionListener);
   // Get the set of nodes written
   @SuppressWarnings("unchecked")
   Set<NodeRef> updatedNodes =
       (Set<NodeRef>) AlfrescoTransactionSupport.getResource(KEY_UPDATED_NODES);
   if (updatedNodes == null) {
     updatedNodes = new HashSet<NodeRef>(5);
     AlfrescoTransactionSupport.bindResource(KEY_UPDATED_NODES, updatedNodes);
   }
   updatedNodes.add(nodeRef);
 }
コード例 #12
0
  /**
   * Actualitza el tamany del fons.
   *
   * @param nodeRef
   * @param parentNodeRef
   */
  private void updateFons(NodeService nodeService, NodeRef serieNodeRef, NodeRef fonsNodeRef) {
    System.out.println(
        DateFormat.getInstance().format(new Date()) + " START: Recalcular tamany fons.");
    int tamany = 0;
    List<ChildAssociationRef> children = nodeService.getChildAssocs(fonsNodeRef);

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

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

    nodeService.setProperty(fonsNodeRef, tamanyFonsRM, String.valueOf(tamany));
    Date now = new Date();
    System.out.println(
        DateFormat.getInstance().format(now) + " Update tamany fons: " + fonsNodeRef);
    System.out.println(DateFormat.getInstance().format(now) + " END: Recalcular tamany fons.");
  }
コード例 #13
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.");
  }
コード例 #14
0
  @After
  public void deleteTestNodes() throws Exception {
    AuthenticationUtil.setFullyAuthenticatedUser(ADMIN_USER);

    // Find the shared system container, and zap contents
    NodeRef container =
        ((RemoteCredentialsServiceImpl) PRIVATE_REMOTE_CREDENTIALS_SERVICE)
            .getSharedContainerNodeRef(false);
    if (container != null) {
      List<NodeRef> children = new ArrayList<NodeRef>();
      for (ChildAssociationRef child : PUBLIC_NODE_SERVICE.getChildAssocs(container)) {
        children.add(child.getChildRef());
      }
      performDeletionOfNodes(children);
    }

    // Zap the users, including any credentials stored for them
    deleteUser(TEST_USER_ONE);
    deleteUser(TEST_USER_TWO);
    deleteUser(TEST_USER_THREE);
  }
コード例 #15
0
  /** Ensure that the node has a <b>fm:forum</b> child node otherwise create one */
  public void onAddAspect(NodeRef discussableNodeRef, QName aspectTypeQName) {
    String name = (String) this.nodeService.getProperty(discussableNodeRef, ContentModel.PROP_NAME);
    String forumName = I18NUtil.getMessage("discussion.discussion_for", new Object[] {name});

    NodeRef forumNodeRef = getForum(discussableNodeRef);

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

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

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

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

    // Done
    if (logger.isDebugEnabled()) {
      logger.debug(
          "Created forum node for discussion: \n"
              + "   Discussable Node: "
              + discussableNodeRef
              + "\n"
              + "   Forum Node:       "
              + forumNodeRef);
    }
  }
コード例 #16
0
ファイル: ChildAssocImpl.java プロジェクト: negabaro/alfresco
 /**
  * {@inheritDoc}
  *
  * <p>This method is thread-safe and lazily creates the required references, if required.
  */
 public ChildAssociationRef getChildAssocRef(QNameDAO qnameDAO) {
   boolean trashReference = false;
   // first check if it is available
   refReadLock.lock();
   try {
     if (childAssocRef != null) {
       // double check that the parent and child node references match those of our reference
       if (childAssocRef.getParentRef() != parent.getNodeRef()
           || childAssocRef.getChildRef() != child.getNodeRef()) {
         trashReference = true;
       } else {
         // we are sure that the reference is correct
         return childAssocRef;
       }
     }
   } finally {
     refReadLock.unlock();
   }
   // get write lock
   refWriteLock.lock();
   try {
     // double check
     if (childAssocRef == null || trashReference) {
       if (typeQName == null) {
         typeQName = qnameDAO.getQName(this.typeQNameId).getSecond();
       }
       if (qname == null) {
         String qnameNamespace = qnameDAO.getNamespace(qnameNamespaceId).getSecond();
         qname = QName.createQName(qnameNamespace, qnameLocalName);
       }
       childAssocRef =
           new ChildAssociationRef(
               typeQName, parent.getNodeRef(), qname, child.getNodeRef(), this.isPrimary, index);
     }
     return childAssocRef;
   } finally {
     refWriteLock.unlock();
   }
 }
コード例 #17
0
  /**
   * This method sets the node(s) to publish or unpublish on the supplied publishing details. If the
   * actionedUponNode is a folder then it will include all content nodes within that folder.
   *
   * @param actionedUponNodeRef
   * @param unpublish
   * @param details
   */
  private List<NodeRef> setNodes(
      NodeRef actionedUponNodeRef, boolean unpublish, PublishingDetails details) {
    List<NodeRef> nodes = new ArrayList<NodeRef>();
    QName nodeType = nodeService.getType(actionedUponNodeRef);
    if (dictionaryService.isSubClass(nodeType, ContentModel.TYPE_FOLDER)) {
      List<ChildAssociationRef> children = nodeService.getChildAssocs(actionedUponNodeRef);
      for (ChildAssociationRef childRef : children) {
        NodeRef child = childRef.getChildRef();
        if (dictionaryService.isSubClass(nodeService.getType(child), ContentModel.TYPE_CONTENT)) {
          nodes.add(child);
        }
      }
    } else {
      nodes.add(actionedUponNodeRef);
    }

    if (unpublish) {
      details.addNodesToUnpublish(nodes);
    } else {
      details.addNodesToPublish(nodes);
    }
    return nodes;
  }
コード例 #18
0
  public NodeRef createDownloadNode(boolean recursive) {
    NodeRef downloadsContainer = getOrCreateDowloadContainer();

    Map<QName, Serializable> downloadProperties = new HashMap<QName, Serializable>();
    downloadProperties.put(DownloadModel.PROP_RECURSIVE, recursive);

    ChildAssociationRef newChildAssoc =
        nodeService.createNode(
            downloadsContainer,
            ContentModel.ASSOC_CHILDREN,
            ContentModel.ASSOC_CHILDREN,
            DownloadModel.TYPE_DOWNLOAD,
            downloadProperties);

    final NodeRef downloadNodeRef = newChildAssoc.getChildRef();

    if (log.isDebugEnabled()) {
      StringBuilder msg = new StringBuilder();
      msg.append("Created Download. ").append("', Download-NodeRef=");
      log.debug(msg.toString());
    }
    return downloadNodeRef;
  }
コード例 #19
0
  protected List<NodeRef> getNodes(
      StoreRef storeRef, RepositoryLocation repositoryLocation, QName nodeType) {
    List<NodeRef> nodeRefs = new ArrayList<NodeRef>();

    NodeRef rootNodeRef = nodeService.getRootNode(storeRef);
    if (nodeService.exists(rootNodeRef) == false) {
      // Tenant is deleted. But cache refresh was called to inform another cluster nodes
      // Should be reworked when MNT-11638 will be implemented
      return nodeRefs;
    }

    if (repositoryLocation instanceof DynamicCreateRepositoryLocation) {
      ((DynamicCreateRepositoryLocation) repositoryLocation).checkAndCreate(rootNodeRef);
    }

    String[] pathElements = repositoryLocation.getPathElements();

    NodeRef folderNodeRef = rootNodeRef;
    if (pathElements.length > 0) {
      folderNodeRef = resolveQNamePath(rootNodeRef, pathElements);
    }

    if (folderNodeRef != null) {
      Set<QName> types = new HashSet<QName>(1);
      types.add(nodeType);
      List<ChildAssociationRef> childAssocRefs = nodeService.getChildAssocs(folderNodeRef, types);

      if (childAssocRefs.size() > 0) {
        nodeRefs = new ArrayList<NodeRef>(childAssocRefs.size());
        for (ChildAssociationRef childAssocRef : childAssocRefs) {
          nodeRefs.add(childAssocRef.getChildRef());
        }
      }
    }

    return nodeRefs;
  }
コード例 #20
0
  /** Test when the aspect is not set when check-in is performed */
  public void testVersionAspectNotSetOnCheckIn() {
    // Create a bag of props
    Map<QName, Serializable> bagOfProps = createTypePropertyBag();
    bagOfProps.put(
        ContentModel.PROP_CONTENT,
        new ContentData(null, MimetypeMap.MIMETYPE_TEXT_PLAIN, 0L, "UTF-8"));

    // Create a new node
    ChildAssociationRef childAssocRef =
        nodeService.createNode(
            rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName("test"),
            ContentModel.TYPE_CONTENT,
            bagOfProps);
    NodeRef noVersionNodeRef = childAssocRef.getChildRef();

    // Check out and check in
    NodeRef workingCopy = cociService.checkout(noVersionNodeRef);
    cociService.checkin(workingCopy, new HashMap<String, Serializable>());

    // Check that the origional node has no version history dispite sending verion props
    assertNull(this.versionService.getVersionHistory(noVersionNodeRef));
  }
コード例 #21
0
 /** {@inheritDoc} */
 @Override
 public void onCreateNode(ChildAssociationRef childAssocRef) {
   this.auditComponent.recordAuditValues(
       CREATE_RATING_ROOT_PATH,
       Collections.<String, Serializable>singletonMap(KEY_NODE_REF, childAssocRef.getChildRef()));
 }
コード例 #22
0
  /**
   * Write exception transfer report
   *
   * @return NodeRef the node ref of the new transfer report
   */
  public NodeRef createTransferReport(
      Exception e,
      TransferTarget target,
      TransferDefinition definition,
      List<TransferEvent> events,
      File snapshotFile) {
    Map<QName, Serializable> properties = new HashMap<QName, Serializable>();

    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmssSSSZ");
    String timeNow = format.format(new Date());

    String title = "Transfer report, error,  " + timeNow;
    String description = "Transfer error report";
    String name = "Transfer error report, " + timeNow;

    properties.put(ContentModel.PROP_NAME, name);
    properties.put(ContentModel.PROP_TITLE, title);
    properties.put(ContentModel.PROP_DESCRIPTION, description);
    ChildAssociationRef ref =
        nodeService.createNode(
            target.getNodeRef(),
            ContentModel.ASSOC_CONTAINS,
            QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name),
            TransferModel.TYPE_TRANSFER_REPORT,
            properties);
    ContentWriter writer =
        contentService.getWriter(ref.getChildRef(), ContentModel.PROP_CONTENT, true);
    writer.setLocale(Locale.getDefault());
    writer.setMimetype(MimetypeMap.MIMETYPE_XML);
    writer.setEncoding(DEFAULT_ENCODING);

    //
    XMLTransferReportWriter reportWriter = new XMLTransferReportWriter();

    BufferedWriter bufferedWriter =
        new BufferedWriter(new OutputStreamWriter(writer.getContentOutputStream()));

    try {
      reportWriter.startTransferReport(DEFAULT_ENCODING, bufferedWriter);

      // Header
      reportWriter.writeTarget(target);

      reportWriter.writeDefinition(definition);

      reportWriter.writeException(e);

      // Detail
      reportWriter.writeTransferEvents(events);

      reportWriter.endTransferReport();

      return ref.getChildRef();
    } catch (SAXException se) {
      return null;
    } finally {
      try {
        bufferedWriter.close();
      } catch (IOException error) {
        error.printStackTrace();
      }
    }
  }
コード例 #23
0
  /**
   * Create a new transfer report of success
   *
   * @return NodeRef the node ref of the new transfer report
   */
  public NodeRef createTransferReport(
      Transfer transfer,
      TransferTarget target,
      TransferDefinition definition,
      List<TransferEvent> events,
      File snapshotFile) {
    Map<QName, Serializable> properties = new HashMap<QName, Serializable>();

    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmssSSSZ");
    String timeNow = format.format(new Date());

    String title = "Transfer report, " + timeNow + "success";
    String description = "Transfer report success targetName : " + target.getName();
    String name = "Transfer report, " + timeNow;

    properties.put(ContentModel.PROP_NAME, name);
    properties.put(ContentModel.PROP_TITLE, title);
    properties.put(ContentModel.PROP_DESCRIPTION, description);
    ChildAssociationRef ref =
        nodeService.createNode(
            target.getNodeRef(),
            ContentModel.ASSOC_CONTAINS,
            QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name),
            TransferModel.TYPE_TRANSFER_REPORT,
            properties);
    ContentWriter writer =
        contentService.getWriter(ref.getChildRef(), ContentModel.PROP_CONTENT, true);
    writer.setLocale(Locale.getDefault());
    writer.setMimetype(MimetypeMap.MIMETYPE_XML);
    writer.setEncoding(DEFAULT_ENCODING);

    //
    final XMLTransferReportWriter reportWriter = new XMLTransferReportWriter();

    BufferedWriter bufferedWriter =
        new BufferedWriter(new OutputStreamWriter(writer.getContentOutputStream()));

    try {
      reportWriter.startTransferReport(DEFAULT_ENCODING, bufferedWriter);

      // Header
      reportWriter.writeTarget(target);

      reportWriter.writeDefinition(definition);

      /** Write the node summary details to the transfer report */
      TransferManifestProcessor processor =
          new TransferManifestProcessor() {
            public void processTransferManifestNode(TransferManifestNormalNode node) {

              try {
                reportWriter.writeNodeSummary(node);
              } catch (SAXException error) {
                error.printStackTrace();
              }
            }

            public void processTransferManifestNode(TransferManifestDeletedNode node) {
              try {
                reportWriter.writeNodeSummary(node);
              } catch (SAXException error) {
                error.printStackTrace();
              }
            }

            public void processTransferManifiestHeader(TransferManifestHeader header) {
              /* NO-OP */
            }

            public void startTransferManifest() {
              /* NO-OP */
            }

            public void endTransferManifest() {
              /* NO-OP */
            }
          };

      /** Step 3: wire up the manifest reader to a manifest processor */
      SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
      SAXParser parser;
      parser = saxParserFactory.newSAXParser();
      XMLTransferManifestReader reader = new XMLTransferManifestReader(processor);

      /** Step 4: start the magic Give the manifest file to the manifest reader */
      try {
        parser.parse(snapshotFile, reader);
      } catch (IOException error) {
        // TODO temp code
        error.printStackTrace();
        return null;
      }

      // Detail Events
      reportWriter.writeTransferEvents(events);

      reportWriter.endTransferReport();

      return ref.getChildRef();
    } catch (SAXException se) {
      // TODO Temp code
      return null;
    } catch (ParserConfigurationException error) {
      // TODO temp code
      error.printStackTrace();
      return null;
    } finally {
      try {
        bufferedWriter.close();
      } catch (IOException error) {
        error.printStackTrace();
      }
    }
  }
コード例 #24
0
  public void onCopyComplete(
      QName classRef,
      NodeRef sourceNodeRef,
      NodeRef targetNodeRef,
      boolean copyToNewNode,
      Map<NodeRef, NodeRef> copyMap) {
    Set<NodeRef> workingCopyNodeRefs = TransactionalResourceHelper.getSet(KEY_WORKING_COPIES);
    if (!workingCopyNodeRefs.contains(sourceNodeRef)) {
      // This is not one of the nodes that needs to have discussions copied over
      return;
    }

    // First check that the source node has forums
    NodeRef sourceForumNodeRef = getForum(sourceNodeRef);
    if (sourceForumNodeRef == null) {
      // Missing!  Clean the source node up!
      nodeService.removeAspect(sourceNodeRef, ForumModel.ASPECT_DISCUSSABLE);
      return;
    }

    // The aspect may or may not exist on the target node
    if (!nodeService.hasAspect(targetNodeRef, ForumModel.ASPECT_DISCUSSABLE)) {
      // Add the aspect
      nodeService.addAspect(targetNodeRef, ForumModel.ASPECT_DISCUSSABLE, null);
    }
    // Get the forum node
    NodeRef targetForumNodeRef = getForum(targetNodeRef);
    // Merge the forum topics
    List<ChildAssociationRef> topicAssocRefs =
        nodeService.getChildAssocs(
            sourceForumNodeRef, Collections.singleton(ForumModel.TYPE_TOPIC));
    int copied = 0;
    for (ChildAssociationRef topicAssocRef : topicAssocRefs) {
      NodeRef topicNodeRef = topicAssocRef.getChildRef();
      try {
        // work out the name for the copied topic
        String topicName;
        String topicNodeName =
            nodeService.getProperty(topicNodeRef, ContentModel.PROP_NAME).toString();
        Serializable labelProp =
            nodeService.getProperty(targetNodeRef, ContentModel.PROP_VERSION_LABEL);
        if (labelProp == null) {
          SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss");
          topicName = topicNodeName + " - " + dateFormat.format(new Date());
        } else {
          topicName = topicNodeName + " (" + labelProp.toString() + ")";
        }

        if (fileFolderService.searchSimple(targetForumNodeRef, topicName) != null) {
          // A topic with that name already exists
          continue;
        }
        fileFolderService.copy(topicNodeRef, targetForumNodeRef, topicName);
        copied++;
      } catch (FileExistsException e) {
        // We checked for this, so this is a concurrency condition
        throw new ConcurrencyFailureException("Target topic exists: " + e.getMessage(), e);
      } catch (FileNotFoundException e) {
        // The node was there, but now it's gone
        throw new ConcurrencyFailureException("Forum was deleted: " + e.getMessage(), e);
      }
    }
  }
  private CategoryPaths getCategoryPaths(
      NodeRef nodeRef, Set<QName> aspects, Map<QName, Serializable> properties) {
    ArrayList<Pair<Path, QName>> categoryPaths = new ArrayList<Pair<Path, QName>>();
    ArrayList<ChildAssociationRef> categoryParents = new ArrayList<ChildAssociationRef>();

    nodeDAO.setCheckNodeConsistency();
    for (QName classRef : aspects) {
      AspectDefinition aspDef = dictionaryService.getAspect(classRef);
      if (!isCategorised(aspDef)) {
        continue;
      }
      LinkedList<Pair<Path, QName>> aspectPaths = new LinkedList<Pair<Path, QName>>();
      for (PropertyDefinition propDef : aspDef.getProperties().values()) {
        if (!propDef.getDataType().getName().equals(DataTypeDefinition.CATEGORY)) {
          // The property is not a category
          continue;
        }
        // Don't try to iterate if the property is null
        Serializable propVal = properties.get(propDef.getName());
        if (propVal == null) {
          continue;
        }
        for (NodeRef catRef : DefaultTypeConverter.INSTANCE.getCollection(NodeRef.class, propVal)) {
          if (catRef == null) {
            continue;
          }
          // can be running in context of System user, hence use input nodeRef
          catRef = tenantService.getName(nodeRef, catRef);

          try {
            Pair<Long, NodeRef> pair = nodeDAO.getNodePair(catRef);
            if (pair != null) {
              for (Path path : nodeDAO.getPaths(pair, false)) {
                aspectPaths.add(new Pair<Path, QName>(path, aspDef.getName()));
              }
            }
          } catch (InvalidNodeRefException e) {
            // If the category does not exists we move on the next
          }
        }
      }
      categoryPaths.addAll(aspectPaths);
    }
    // Add member final element
    for (Pair<Path, QName> pair : categoryPaths) {
      if (pair.getFirst().last() instanceof Path.ChildAssocElement) {
        Path.ChildAssocElement cae = (Path.ChildAssocElement) pair.getFirst().last();
        ChildAssociationRef assocRef = cae.getRef();
        ChildAssociationRef categoryParentRef =
            new ChildAssociationRef(
                assocRef.getTypeQName(),
                assocRef.getChildRef(),
                QName.createQName("member"),
                nodeRef);
        pair.getFirst().append(new Path.ChildAssocElement(categoryParentRef));
        categoryParents.add(categoryParentRef);
      }
    }

    return new CategoryPaths(categoryPaths, categoryParents);
  }
  @Override
  protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {

    long startTime = System.currentTimeMillis();

    logger.info("DEBUT Web Script SynchroniseDroitsSHDWebScript");

    Map<String, Object> model = new HashMap<String, Object>();
    model.put("nomWebScript", "SynchroniseDroitsSHDWebScript");

    if (!isSiteSirhExist()) {
      logger.debug("Site SIRH not exist");

      long endTime = System.currentTimeMillis();

      model.put("nbrAgentCree", "Site SIRH not exist");
      model.put("tempsExecution", endTime - startTime);

      return model;
    }

    NodeRef nodeAgents =
        alfrescoUtilsService.getNodeRef(
            "/app:company_home/site:sites/cm:SIRH/cm:documentLibrary/cm:Agents");

    List<ChildAssociationRef> listChildren = nodeService.getChildAssocs(nodeAgents);

    int nbrAgentCree = 0;
    if (null != listChildren && 0 < listChildren.size()) {
      for (ChildAssociationRef child : listChildren) {
        // nous gerons nous meme les transactions
        // car nous avons eu "TransactionalCache' is full"
        // cela ralentit fortement Alfresco
        UserTransaction trx =
            serviceRegistry.getTransactionService().getNonPropagatingUserTransaction(false);
        try {
          trx.begin();

          String nameFolderAgent =
              (String) nodeService.getProperty(child.getChildRef(), ContentModel.PROP_NAME);
          Integer idAgent = null;
          try {
            idAgent =
                new Integer(
                    nameFolderAgent.substring(
                        nameFolderAgent.length() - 7, nameFolderAgent.length()));
          } catch (NumberFormatException e) {
            logger.error("Error ParseException Node : " + nameFolderAgent);
            idAgent = null;
          }

          if (null != idAgent) {
            logger.debug("Add SHD Rights to " + idAgent);
            traiteDroitsOfNodeAgent(child, idAgent, nameFolderAgent);
            nbrAgentCree++;
          }

          trx.commit();
        } catch (Throwable e) {
          try {
            trx.rollback();
          } catch (IllegalStateException | SecurityException | SystemException e1) {
            logger.error(e1.getMessage());
          }
        }
      }
    }

    long endTime = System.currentTimeMillis();

    logger.info("FIN Web Script SynchroniseDroitsSHDWebScript");

    model.put("tempsExecution", endTime - startTime);
    model.put("nombreAgentsAjoutesSHD", nbrAgentCree);

    return model;
  }
コード例 #27
0
 /* (non-Javadoc)
  * @see org.alfresco.repo.node.NodeServicePolicies.OnMoveNodePolicy#onMoveNode(org.alfresco.service.cmr.repository.ChildAssociationRef, org.alfresco.service.cmr.repository.ChildAssociationRef)
  */
 @Override
 public void onMoveNode(
     ChildAssociationRef oldChildAssocRef, ChildAssociationRef newChildAssocRef) {
   markCascadeUpdate(oldChildAssocRef.getChildRef());
   markCascadeUpdate(newChildAssocRef.getChildRef());
 }
コード例 #28
0
  /** On setup in transaction implementation */
  @Override
  protected void onSetUpInTransaction() throws Exception {
    // Set the services
    this.nodeService = (NodeService) this.applicationContext.getBean("nodeService");
    this.cociService =
        (CheckOutCheckInService) this.applicationContext.getBean("checkOutCheckInService");
    this.contentService = (ContentService) this.applicationContext.getBean("contentService");
    this.versionService = (VersionService) this.applicationContext.getBean("versionService");
    this.authenticationService =
        (MutableAuthenticationService) this.applicationContext.getBean("authenticationService");
    this.lockService = (LockService) this.applicationContext.getBean("lockService");
    this.transactionService =
        (TransactionService) this.applicationContext.getBean("transactionComponent");
    this.permissionService =
        (PermissionService) this.applicationContext.getBean("permissionService");
    this.copyService = (CopyService) this.applicationContext.getBean("copyService");

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

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

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

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

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

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

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

    folderNodeRef =
        nodeService
            .createNode(
                rootNodeRef,
                ContentModel.ASSOC_CHILDREN,
                QName.createQName("test"),
                ContentModel.TYPE_FOLDER,
                Collections.<QName, Serializable>singletonMap(ContentModel.PROP_NAME, "folder"))
            .getChildRef();
    fileNodeRef =
        nodeService
            .createNode(
                folderNodeRef,
                ContentModel.ASSOC_CONTAINS,
                QName.createQName("test"),
                ContentModel.TYPE_CONTENT,
                Collections.<QName, Serializable>singletonMap(ContentModel.PROP_NAME, "file"))
            .getChildRef();
    contentWriter = this.contentService.getWriter(fileNodeRef, ContentModel.PROP_CONTENT, true);
    contentWriter.setMimetype("text/plain");
    contentWriter.setEncoding("UTF-8");
    contentWriter.putContent(CONTENT_1);
  }
コード例 #29
0
  public void testMultipleCheckoutsCheckInsWithPropChange() {
    // Note: this test assumes cm:autoVersionProps=true by default (refer to cm:versionableAspect in
    // contentModel.xml)

    // Create a new node
    ChildAssociationRef childAssocRef =
        nodeService.createNode(
            rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName("test"),
            ContentModel.TYPE_CONTENT,
            null);
    final NodeRef testNodeRef = childAssocRef.getChildRef();

    // Add the version aspect to the created node
    nodeService.addAspect(testNodeRef, ContentModel.ASPECT_VERSIONABLE, null);

    setComplete();
    endTransaction();

    // Checkout
    final NodeRef workingCopy1 =
        transactionService
            .getRetryingTransactionHelper()
            .doInTransaction(
                new RetryingTransactionCallback<NodeRef>() {
                  public NodeRef execute() throws Exception {
                    return cociService.checkout(testNodeRef);
                  }
                });

    // Change property and checkin
    transactionService
        .getRetryingTransactionHelper()
        .doInTransaction(
            new RetryingTransactionCallback<Object>() {
              public Object execute() throws Exception {
                nodeService.setProperty(workingCopy1, ContentModel.PROP_AUTHOR, "author1");

                Map<String, Serializable> versionProperties = new HashMap<String, Serializable>();
                versionProperties.put(Version.PROP_DESCRIPTION, "This is a test version 1");
                cociService.checkin(workingCopy1, versionProperties);

                return null;
              }
            });

    // Checkout
    final NodeRef workingCopy2 =
        transactionService
            .getRetryingTransactionHelper()
            .doInTransaction(
                new RetryingTransactionCallback<NodeRef>() {
                  public NodeRef execute() throws Exception {
                    return cociService.checkout(testNodeRef);
                  }
                });

    // Change property and checkin
    transactionService
        .getRetryingTransactionHelper()
        .doInTransaction(
            new RetryingTransactionCallback<Object>() {
              public Object execute() throws Exception {
                nodeService.setProperty(workingCopy2, ContentModel.PROP_AUTHOR, "author2");

                Map<String, Serializable> versionProperties = new HashMap<String, Serializable>();
                versionProperties.put(Version.PROP_DESCRIPTION, "This is a test version 2");
                cociService.checkin(workingCopy2, versionProperties);

                return null;
              }
            });

    // Checkout
    final NodeRef workingCopy3 =
        transactionService
            .getRetryingTransactionHelper()
            .doInTransaction(
                new RetryingTransactionCallback<NodeRef>() {
                  public NodeRef execute() throws Exception {
                    return cociService.checkout(testNodeRef);
                  }
                });

    // Change property and checkin
    transactionService
        .getRetryingTransactionHelper()
        .doInTransaction(
            new RetryingTransactionCallback<Object>() {
              public Object execute() throws Exception {
                nodeService.setProperty(workingCopy3, ContentModel.PROP_AUTHOR, "author3");

                Map<String, Serializable> versionProperties = new HashMap<String, Serializable>();
                versionProperties.put(Version.PROP_DESCRIPTION, "This is a test version 3");
                cociService.checkin(workingCopy3, versionProperties);

                return null;
              }
            });
  }
コード例 #30
0
 /* (non-Javadoc)
  * @see org.alfresco.repo.node.NodeServicePolicies.OnCreateChildAssociationPolicy#onCreateChildAssociation(org.alfresco.service.cmr.repository.ChildAssociationRef, boolean)
  */
 @Override
 public void onCreateChildAssociation(ChildAssociationRef childAssocRef, boolean isNewNode) {
   if (!isNewNode) {
     markCascadeUpdate(childAssocRef.getChildRef());
   }
 }