private Node prepareAnActivityNode(String id, Calendar timestamp) throws RepositoryException {
   Node activityNode = mock(Node.class, RETURNS_DEEP_STUBS);
   when(activityNode.hasProperty("timestamp")).thenReturn(true);
   when(activityNode.getProperty("timestamp").getDate()).thenReturn(timestamp);
   when(activityNode.getProperty("resourceId").getString()).thenReturn(id);
   return activityNode;
 }
Example #2
0
  @Test
  @FixFor("MODE-1912")
  public void shouldRemoveMixVersionablePropertiesWhenRemovingMixin() throws Exception {
    Node node = session.getRootNode().addNode("testNode");
    node.addMixin(JcrMixLexicon.VERSIONABLE.getString());
    session.save();

    // mix:referenceable
    assertNotNull(node.getProperty(JcrLexicon.UUID.getString()));
    // mix:simpleVersionable
    assertTrue(node.getProperty(JcrLexicon.IS_CHECKED_OUT.getString()).getBoolean());
    // mix:versionable
    assertNotNull(node.getProperty(JcrLexicon.BASE_VERSION.getString()));
    assertNotNull(node.getProperty(JcrLexicon.VERSION_HISTORY.getString()));
    assertNotNull(node.getProperty(JcrLexicon.PREDECESSORS.getString()));

    node.removeMixin(JcrMixLexicon.VERSIONABLE.getString());
    session.save();

    // mix:referenceable
    assertPropertyIsAbsent(node, JcrLexicon.UUID.getString());
    // mix:simpleVersionable
    assertPropertyIsAbsent(node, JcrLexicon.IS_CHECKED_OUT.getString());
    // mix:versionable
    assertPropertyIsAbsent(node, JcrLexicon.VERSION_HISTORY.getString());
    assertPropertyIsAbsent(node, JcrLexicon.BASE_VERSION.getString());
    assertPropertyIsAbsent(node, JcrLexicon.PREDECESSORS.getString());
  }
Example #3
0
  /**
   * Get download link of a node which stored binary data
   *
   * @param node Node
   * @return download link
   * @throws Exception
   */
  public static String getDownloadLink(Node node) throws Exception {

    if (!Utils.getRealNode(node).getPrimaryNodeType().getName().equals(NT_FILE)) return null;

    // Get binary data from node
    DownloadService dservice = WCMCoreUtils.getService(DownloadService.class);
    Node jcrContentNode = node.getNode(JCR_CONTENT);
    InputStream input = jcrContentNode.getProperty(JCR_DATA).getStream();

    // Get mimeType of binary data
    String mimeType = jcrContentNode.getProperty(JCR_MIMETYPE).getString();

    // Make download stream
    InputStreamDownloadResource dresource = new InputStreamDownloadResource(input, mimeType);

    // Make extension part for file if it have not yet
    DMSMimeTypeResolver mimeTypeSolver = DMSMimeTypeResolver.getInstance();
    String ext = "." + mimeTypeSolver.getExtension(mimeType);
    String fileName = Utils.getRealNode(node).getName();
    if (fileName.lastIndexOf(ext) < 0 && !mimeTypeSolver.getMimeType(fileName).equals(mimeType)) {
      dresource.setDownloadName(fileName + ext);
    } else {
      dresource.setDownloadName(fileName);
    }

    return dservice.getDownloadLink(dservice.addDownloadResource(dresource));
  }
  @Test
  public void ferrari_has_modification_information() throws RepositoryException {
    Node ferrari = session.getNode("/cars/ferrari");

    assertThat(ferrari.getProperty("jcr:lastModifiedBy"), notNullValue());
    assertThat(ferrari.getProperty("jcr:lastModified"), notNullValue());
  }
  /**
   * Get content of document node. Content is got by exo:content or exo:text or exo:summary
   *
   * @param node
   * @return
   * @throws Exception
   */
  private DocumentContent getArticleContent(Node node, List<Node> taxonomyTrees) throws Exception {
    DocumentContent documentContent =
        new DocumentContent(node.getName(), getIcon(node), "", getType(node));
    // If node is added mix rss-enabled then get exo:content property
    if (node.hasProperty("exo:content")) {
      documentContent.setContent(node.getProperty("exo:content").getString());
    }
    // Some node have exo:text so we override value of exo:content
    if (node.hasProperty("exo:text")) {
      documentContent.setContent(node.getProperty("exo:text").getString());
    }
    // Some node have exo:summary so we override value of exo:content
    if (node.hasProperty("exo:summary")) {
      documentContent.setContent(node.getProperty("exo:summary").getString());
    }

    List<Node> categories = taxonomyService_.getAllCategories(node);

    CategoryNode categoryNode;
    for (Node category : categories) {
      categoryNode = getCategoryNode(category, "");
      for (Node taxonomyTree : taxonomyTrees) {
        if (category.getPath().contains(taxonomyTree.getPath())) {
          categoryNode.setParentPath(
              (category.getParent().getPath().replace(taxonomyTree.getParent().getPath(), "")));
          break;
        }
      }
      if (categoryNode != null) documentContent.getCategories().add(categoryNode);
    }
    return documentContent;
  }
Example #6
0
  /**
   * Writes all the properties of a sakai/file node. Also checks what the permissions are for a
   * session and where the links are.
   *
   * @param node
   * @param write
   * @param objectInProgress Whether object creation is in progress. If false, object is started and
   *     ended in this method call.
   * @throws JSONException
   * @throws RepositoryException
   */
  public static void writeFileNode(Node node, Session session, JSONWriter write, int maxDepth)
      throws JSONException, RepositoryException {

    write.object();

    // dump all the properties.
    ExtendedJSONWriter.writeNodeTreeToWriter(write, node, true, maxDepth);
    // The permissions for this session.
    writePermissions(node, session, write);

    if (node.hasNode(JcrConstants.JCR_CONTENT)) {
      Node contentNode = node.getNode(JcrConstants.JCR_CONTENT);
      write.key(JcrConstants.JCR_LASTMODIFIED);
      Calendar cal = contentNode.getProperty(JcrConstants.JCR_LASTMODIFIED).getDate();
      write.value(DateUtils.iso8601(cal));
      write.key(JcrConstants.JCR_MIMETYPE);
      write.value(contentNode.getProperty(JcrConstants.JCR_MIMETYPE).getString());

      if (contentNode.hasProperty(JcrConstants.JCR_DATA)) {
        write.key(JcrConstants.JCR_DATA);
        write.value(contentNode.getProperty(JcrConstants.JCR_DATA).getLength());
      }
    }

    write.endObject();
  }
Example #7
0
 private JcrNodeModel getPhysicalNode(JcrNodeModel model) {
   Node node = model.getNode();
   if (node != null) {
     try {
       if (node.isNodeType("nt:version")) {
         Node frozen = node.getNode("jcr:frozenNode");
         String uuid = frozen.getProperty("jcr:frozenUuid").getString();
         try {
           Node docNode = node.getSession().getNodeByUUID(uuid);
           if (docNode.getDepth() > 0) {
             Node parent = docNode.getParent();
             if (parent.isNodeType(HippoNodeType.NT_HANDLE)) {
               return new JcrNodeModel(parent);
             }
           }
           return new JcrNodeModel(docNode);
         } catch (ItemNotFoundException infe) {
           // node doesn't exist anymore.  If it's a document, the handle
           // should still be available though.
           if (frozen.hasProperty(HippoNodeType.HIPPO_PATHS)) {
             Value[] ancestors = frozen.getProperty(HippoNodeType.HIPPO_PATHS).getValues();
             if (ancestors.length > 1) {
               uuid = ancestors[1].getString();
               return new JcrNodeModel(node.getSession().getNodeByUUID(uuid));
             }
           }
           throw infe;
         }
       }
     } catch (RepositoryException ex) {
       log.error(ex.getMessage());
     }
   }
   return model;
 }
Example #8
0
  @Test
  public void shouldUpdateExternalNodeProperties() throws Exception {
    federationManager.createProjection(
        "/testRoot", SOURCE_NAME, MockConnector.DOC1_LOCATION, "federated1");
    Node doc1Federated = session.getNode("/testRoot/federated1");
    Node externalNode1 = doc1Federated.addNode("federated1_1", null);
    externalNode1.setProperty("prop1", "a value");
    externalNode1.setProperty("prop2", "a value 2");
    session.save();

    externalNode1.setProperty("prop1", "edited value");
    assertEquals("a value 2", externalNode1.getProperty("prop2").getString());
    externalNode1.getProperty("prop2").remove();
    externalNode1.setProperty("prop3", "a value 3");
    session.save();

    Node federated1_1 = doc1Federated.getNode("federated1_1");
    assertEquals("edited value", federated1_1.getProperty("prop1").getString());
    assertEquals("a value 3", federated1_1.getProperty("prop3").getString());
    try {
      federated1_1.getProperty("prop2");
      fail("Property was not removed from external node");
    } catch (PathNotFoundException e) {
      // expected
    }
  }
Example #9
0
  public void testSave() throws Exception {
    UserStateModel userModel =
        new UserStateModel(
            session.getUserID(), new Date().getTime(), UserStateService.DEFAULT_STATUS);
    userStateService.save(userModel);

    SessionProvider sessionProvider = SessionProvider.createSystemProvider();
    try {
      Node userNodeApp =
          nodeHierarchyCreator.getUserApplicationNode(sessionProvider, session.getUserID());
      assertTrue(userNodeApp.hasNode(VIDEOCALLS_BASE_PATH));

      Node videoCallNode = userNodeApp.getNode(VIDEOCALLS_BASE_PATH);
      assertTrue(videoCallNode.isNodeType(USER_STATATUS_NODETYPE));

      assertTrue(videoCallNode.hasProperty(USER_ID_PROP));
      assertEquals(userModel.getUserId(), videoCallNode.getProperty(USER_ID_PROP).getString());

      assertTrue(videoCallNode.hasProperty(LAST_ACTIVITY_PROP));
      assertEquals(
          userModel.getLastActivity(), videoCallNode.getProperty(LAST_ACTIVITY_PROP).getLong());

      assertTrue(videoCallNode.hasProperty(STATUS_PROP));
      assertEquals(userModel.getStatus(), videoCallNode.getProperty(STATUS_PROP).getString());
    } finally {
      sessionProvider.close();
    }
  }
  private void checkCustomProperties(Session session) throws javax.jcr.RepositoryException {

    NodeTypeManager nodetypeManager = new NodeTypeManager();
    // Check and create required custom properties
    javax.jcr.Node systemNode = JCRUtils.getSystemNode(session);
    if (systemNode.hasNode(JLibraryConstants.JLIBRARY_CUSTOM_PROPERTIES)) {
      javax.jcr.Node propertiesNode =
          systemNode.getNode(JLibraryConstants.JLIBRARY_CUSTOM_PROPERTIES);
      NodeIterator it = propertiesNode.getNodes();
      while (it.hasNext()) {
        javax.jcr.Node propsNode = (javax.jcr.Node) it.next();
        CustomPropertyDefinition propdef = new CustomPropertyDefinition();
        propdef.setName(
            propsNode.getProperty(JLibraryConstants.JLIBRARY_PROPERTY_NAME).getString());
        propdef.setType(
            (int) propsNode.getProperty(JLibraryConstants.JLIBRARY_PROPERTY_TYPE).getLong());
        propdef.setMultivalued(
            propsNode.getProperty(JLibraryConstants.JLIBRARY_PROPERTY_MULTIVALUED).getBoolean());
        propdef.setAutocreated(
            propsNode.getProperty(JLibraryConstants.JLIBRARY_PROPERTY_AUTOCREATED).getBoolean());
        if (propsNode.hasProperty(JLibraryConstants.JLIBRARY_PROPERTY_DEFAULT)) {
          propdef.setDefaultValues(
              propsNode.getProperty(JLibraryConstants.JLIBRARY_PROPERTY_DEFAULT).getValues());
        }

        logger.info("Registering property : " + propdef);
        nodetypeManager.registerCustomProperty(session, propdef);
      }
    }
  }
Example #11
0
  @Test
  public void shouldCreateProjectionWithAlias() throws Exception {
    // add an internal node
    testRoot.addNode("node1");
    session.save();

    // link the first external document
    federationManager.createProjection(
        "/testRoot", SOURCE_NAME, MockConnector.DOC1_LOCATION, "federated1");
    assertEquals(2, testRoot.getNodes().getSize());

    Node doc1Federated = assertNodeFound("/testRoot/federated1");
    assertEquals(testRoot.getIdentifier(), doc1Federated.getParent().getIdentifier());
    assertEquals("a string", doc1Federated.getProperty("federated1_prop1").getString());
    assertEquals(12, doc1Federated.getProperty("federated1_prop2").getLong());

    // link a second external document with a sub-child
    federationManager.createProjection(
        "/testRoot", SOURCE_NAME, MockConnector.DOC2_LOCATION, "federated2");
    assertEquals(3, testRoot.getNodes().getSize());

    Node doc2Federated = assertNodeFound("/testRoot/federated2");
    assertEquals(testRoot.getIdentifier(), doc2Federated.getParent().getIdentifier());
    assertEquals("another string", doc2Federated.getProperty("federated2_prop1").getString());
    assertEquals(false, doc2Federated.getProperty("federated2_prop2").getBoolean());

    Node doc2FederatedChild = assertNodeFound("/testRoot/federated2/federated3");
    assertEquals(
        "yet another string", doc2FederatedChild.getProperty("federated3_prop1").getString());
  }
  private Node createFileNode() throws ValueFormatException, RepositoryException {
    Calendar cal = Calendar.getInstance();

    Node contentNode = mock(Node.class);
    Property dateProp = mock(Property.class);
    when(dateProp.getDate()).thenReturn(cal);
    Property lengthProp = mock(Property.class);
    when(lengthProp.getLength()).thenReturn(12345L);

    Property mimetypeProp = mock(Property.class);
    when(mimetypeProp.getString()).thenReturn("text/plain");

    when(contentNode.getProperty(JcrConstants.JCR_LASTMODIFIED)).thenReturn(dateProp);
    when(contentNode.getProperty(JcrConstants.JCR_MIMETYPE)).thenReturn(mimetypeProp);
    when(contentNode.getProperty(JcrConstants.JCR_DATA)).thenReturn(lengthProp);
    when(contentNode.hasProperty(JcrConstants.JCR_DATA)).thenReturn(true);

    Node node = mock(Node.class);

    Property fooProp = new MockProperty("foo");
    fooProp.setValue("bar");
    List<Property> propertyList = new ArrayList<Property>();
    propertyList.add(fooProp);
    MockPropertyIterator propertyIterator = new MockPropertyIterator(propertyList.iterator());

    when(node.getProperties()).thenReturn(propertyIterator);
    when(node.hasNode("jcr:content")).thenReturn(true);
    when(node.getNode("jcr:content")).thenReturn(contentNode);
    when(node.getPath()).thenReturn("/path/to/file.doc");
    when(node.getName()).thenReturn("file.doc");

    return node;
  }
 /**
  * Reads the update timestamp from the <code>jcr:content/jcr:lastModified</code> property.
  *
  * @param node mail node
  * @return update timestamp
  * @throws RepositoryException if a repository error occurs
  */
 private Date getLastUpdated(Node node) throws RepositoryException {
   try {
     node = node.getNode("jcr:content");
   } catch (PathNotFoundException e) {
     node = node.getProperty("jcr:content").getNode();
   }
   return node.getProperty("jcr:lastModified").getDate().getTime();
 }
  private EcmDocument readDocumentByNode(Node node, int readType) throws EcmException {
    EcmDocument doc = null;
    try {
      if (node == null) {
        return doc;
      }
      doc = new EcmDocument();

      Node resNode = node.getNode(Property.JCR_CONTENT);
      if (resNode == null) {
        return doc;
      }
      /** Load the document meta data */
      DocumentMetadata meta = this.loadDocumentMetadata(resNode);

      meta.setFileName(node.getName());
      meta.setIdentifier(node.getIdentifier());

      String createdBy = node.getProperty(Property.JCR_CREATED_BY).getString();
      Calendar createdDate = node.getProperty(Property.JCR_CREATED).getDate();

      meta.setCreated(createdDate.getTime());
      meta.setCreatedBy(createdBy);
      meta.setCheckedOut(node.isCheckedOut());
      meta.setFullPath(node.getPath());

      doc.setMetadata(meta);
      doc.setFileName(meta.getFileName());
      doc.setParentFolder(node.getParent().getName());

      /** Load the file content */
      Property dataProperty = resNode.getProperty(Property.JCR_DATA);
      if (dataProperty != null && readType == 0) {
        doc.setInputStream(dataProperty.getBinary().getStream());
        doc.getMetadata().setSize(dataProperty.getBinary().getSize());
      } else if (dataProperty != null && readType == 1) {
        byte[] contents = convertToByteArray(dataProperty.getBinary());
        doc.setContent(contents);
        doc.getMetadata().setSize(dataProperty.getBinary().getSize());
      }

    } catch (PathNotFoundException e) {
      throw new EcmException(
          "Fail to read document from repository.", e, ErrorCodes.REPOSITROY_ERR_INVALID_PATH);

    } catch (RepositoryException e) {
      throw new EcmException(
          "Fail to read document from repository.", e, ErrorCodes.REPOSITROY_ERR_GENERIC);

    } catch (IOException e) {
      throw new EcmException(
          "Fail to read document from repository.",
          e,
          ErrorCodes.REPOSITROY_ERR_FAIL_TO_READ_CONTENT);
    }

    return doc;
  }
  public void route(Node n, MessageRoutes routing) {
    List<MessageRoute> toRemove = new ArrayList<MessageRoute>();
    List<MessageRoute> toAdd = new ArrayList<MessageRoute>();

    // Check if this message is a discussion message.
    try {
      if (n.hasProperty(MessageConstants.PROP_SAKAI_TYPE)
          && n.hasProperty(DiscussionConstants.PROP_MARKER)
          && DiscussionTypes.hasValue(
              n.getProperty(MessageConstants.PROP_SAKAI_TYPE).getString())) {

        // This is a discussion message, find the settings file for it.
        String marker = n.getProperty(DiscussionConstants.PROP_MARKER).getString();
        String type = n.getProperty(MessageConstants.PROP_SAKAI_TYPE).getString();

        // TODO: I have a feeling that this is really part of something more generic
        //   and not specific to discussion. If we make it specific to discussion we
        //   will loose unified messaging and control of that messaging.

        Node settings = discussionManager.findSettings(marker, n.getSession(), type);
        if (settings != null && settings.hasProperty(DiscussionConstants.PROP_NOTIFICATION)) {
          boolean sendMail =
              settings.getProperty(DiscussionConstants.PROP_NOTIFICATION).getBoolean();
          if (sendMail && settings.hasProperty(DiscussionConstants.PROP_NOTIFY_ADDRESS)) {
            String address =
                settings.getProperty(DiscussionConstants.PROP_NOTIFY_ADDRESS).getString();
            toAdd.add(new DiscussionRoute("internal:" + address));
          }
        }
      }
    } catch (ValueFormatException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (PathNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (RepositoryException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    for (MessageRoute route : routing) {
      if (DiscussionTypes.hasValue(route.getTransport())) {
        toAdd.add(new DiscussionRoute("internal:" + route.getRcpt()));
        toRemove.add(route);
      }
    }
    // Add the new routes
    for (MessageRoute route : toAdd) {
      routing.add(route);
    }
    // Remove the discussion route (if there is any).
    for (MessageRoute route : toRemove) {
      routing.remove(route);
    }
  }
Example #16
0
  public static Map<String, String> populateActivityData(
      Node node,
      String activityOwnerId,
      String activityMsgBundleKey,
      boolean isSystemComment,
      String systemComment)
      throws Exception {
    /** The date formatter. */
    DateFormat dateFormatter = null;
    dateFormatter = new SimpleDateFormat(ISO8601.SIMPLE_DATETIME_FORMAT);

    // get activity data
    String repository =
        ((ManageableRepository) node.getSession().getRepository()).getConfiguration().getName();
    String workspace = node.getSession().getWorkspace().getName();

    String illustrationImg = Utils.getIllustrativeImage(node);
    String strDateCreated = "";
    if (node.hasProperty(NodetypeConstant.EXO_DATE_CREATED)) {
      Calendar dateCreated = node.getProperty(NodetypeConstant.EXO_DATE_CREATED).getDate();
      strDateCreated = dateFormatter.format(dateCreated.getTime());
    }
    String strLastModified = "";
    if (node.hasNode(NodetypeConstant.JCR_CONTENT)) {
      Node contentNode = node.getNode(NodetypeConstant.JCR_CONTENT);
      if (contentNode.hasProperty(NodetypeConstant.JCR_LAST_MODIFIED)) {
        Calendar lastModified =
            contentNode.getProperty(NodetypeConstant.JCR_LAST_MODIFIED).getDate();
        strLastModified = dateFormatter.format(lastModified.getTime());
      }
    }

    activityOwnerId = activityOwnerId != null ? activityOwnerId : "";

    // populate data to map object
    Map<String, String> activityParams = new HashMap<String, String>();
    activityParams.put(ContentUIActivity.CONTENT_NAME, node.getName());
    activityParams.put(ContentUIActivity.AUTHOR, activityOwnerId);
    activityParams.put(ContentUIActivity.DATE_CREATED, strDateCreated);
    activityParams.put(ContentUIActivity.LAST_MODIFIED, strLastModified);
    activityParams.put(ContentUIActivity.CONTENT_LINK, getContentLink(node));
    activityParams.put(
        ContentUIActivity.ID,
        node.isNodeType(NodetypeConstant.MIX_REFERENCEABLE) ? node.getUUID() : "");
    activityParams.put(ContentUIActivity.REPOSITORY, repository);
    activityParams.put(ContentUIActivity.WORKSPACE, workspace);
    activityParams.put(ContentUIActivity.MESSAGE, activityMsgBundleKey);
    activityParams.put(ContentUIActivity.MIME_TYPE, getMimeType(node));
    activityParams.put(ContentUIActivity.IMAGE_PATH, illustrationImg);
    activityParams.put(ContentUIActivity.IMAGE_PATH, illustrationImg);
    if (isSystemComment) {
      activityParams.put(ContentUIActivity.IS_SYSTEM_COMMENT, String.valueOf(isSystemComment));
      activityParams.put(ContentUIActivity.SYSTEM_COMMENT, systemComment);
    }
    return activityParams;
  }
Example #17
0
 @Test
 public void shouldFollowReferenceFromOldTagToCommit() throws Exception {
   Node git = gitNode();
   Node tag = git.getNode("tags/dna-0.2");
   assertThat(tag.getProperty("git:objectId").getString(), is(notNullValue()));
   assertThat(tag.getProperty("git:tree").getString(), is(notNullValue()));
   assertThat(tag.getProperty("git:history").getString(), is(notNullValue()));
   Node tagTree = tag.getProperty("git:tree").getNode();
   assertThat(tagTree.getPath(), is(treePathFor(tag)));
   assertChildrenInclude(tagTree, "pom.xml", "dna-jcr", "dna-common", ".project");
 }
Example #18
0
  @Test
  public void shouldCreateProjectionWithoutAlias() throws Exception {
    // link the first external document
    federationManager.createProjection("/testRoot", SOURCE_NAME, MockConnector.DOC1_LOCATION, null);
    assertEquals(1, testRoot.getNodes().getSize());

    Node doc1Federated = assertNodeFound("/testRoot" + MockConnector.DOC1_LOCATION);
    assertEquals(testRoot.getIdentifier(), doc1Federated.getParent().getIdentifier());
    assertEquals("a string", doc1Federated.getProperty("federated1_prop1").getString());
    assertEquals(12, doc1Federated.getProperty("federated1_prop2").getLong());
  }
Example #19
0
  public void postSave(Membership m, boolean isNew) throws Exception {

    String username = m.getUserName();
    String groupId = m.getGroupId();
    cservice_.addUserContactInAddressBook(username, groupId);
    DataStorage storage_ = new JCRDataStorage(nodeHierarchyCreator_, reposervice_);
    SessionProvider systemSession = SessionProvider.createSystemProvider();
    try {
      String usersPath = nodeHierarchyCreator_.getJcrPath(DataStorage.USERS_PATH);
      Contact contact = cservice_.getPublicContact(username);
      QueryManager qm = getSession(systemSession).getWorkspace().getQueryManager();
      Map<String, String> groups = new LinkedHashMap<String, String>();
      for (String group : contact.getAddressBookIds()) groups.put(group, group);
      groups.put(groupId, groupId);
      contact.setAddressBookIds(groups.keySet().toArray(new String[] {}));
      cservice_.saveContact(username, contact, false);
      StringBuffer queryString =
          new StringBuffer(
                  "/jcr:root"
                      + usersPath
                      + "//element(*,exo:contactGroup)[@exo:viewPermissionGroups='")
              .append(groupId + "']");
      Query query = qm.createQuery(queryString.toString(), Query.XPATH);
      QueryResult result = query.execute();
      NodeIterator nodes = result.getNodes();
      List<String> to = Arrays.asList(new String[] {username});
      while (nodes.hasNext()) {
        Node address = nodes.nextNode();
        String from = address.getProperty("exo:sharedUserId").getString();
        String addressBookId = address.getProperty("exo:id").getString();
        storage_.shareAddressBook(from, addressBookId, to);
      }
      queryString =
          new StringBuffer(
                  "/jcr:root" + usersPath + "//element(*,exo:contact)[@exo:viewPermissionGroups='")
              .append(groupId + "']");
      query = qm.createQuery(queryString.toString(), Query.XPATH);
      result = query.execute();
      nodes = result.getNodes();
      while (nodes.hasNext()) {
        Node contactNode = nodes.nextNode();
        String split = "/";
        String temp = contactNode.getPath().split(usersPath)[1];
        String userId = temp.split(split)[1];
        String[] addressBookIds = new String[] {contactNode.getProperty("exo:id").getString()};
        storage_.shareContact(userId, addressBookIds, to);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      systemSession.close();
    }
  }
Example #20
0
 /**
  * Gets the values as string.
  *
  * @param node the node
  * @param propName the prop name
  * @return the values as string
  * @throws Exception the exception
  */
 public static List<String> getValuesAsString(Node node, String propName) throws Exception {
   if (!node.hasProperty(propName)) return new ArrayList<String>();
   List<String> results = new ArrayList<String>();
   try {
     for (Value value : node.getProperty(propName).getValues()) {
       results.add(value.getString());
     }
   } catch (ValueFormatException ex) {
     results.add(node.getProperty(propName).getValue().getString());
   }
   return results;
 }
Example #21
0
  /**
   * initializes fields
   *
   * @throws Exception
   */
  public void initParams() throws Exception {

    // get current node

    // name field
    if (currentNode.hasProperty("exo:title")) {
      nameValue_ = currentNode.getProperty("exo:title").getValue().getString();
    }
    if (currentNode.hasNode("jcr:content")) {
      Node content = currentNode.getNode("jcr:content");
      if (content.hasProperty("dc:title")) {
        try {
          nameValue_ = content.getProperty("dc:title").getValues()[0].getString();
        } catch (Exception e) {
          nameValue_ = null;
        }
      }
    }

    if (nameValue_ == null) nameValue_ = currentNode.getName();

    boolean hasNavigableMixinType = currentNode.isNodeType("exo:navigable");
    if (hasNavigableMixinType) {
      isVisible = true;
      if (currentNode.getParent().isNodeType("exo:navigable")) {
        if (currentNode.hasProperty("exo:index")) {
          index_ = currentNode.getProperty("exo:index").getLong();
        }
        renderIndexField = true;
      }

      if (currentNode.hasProperty("exo:navigationNode")) {
        navigationNode_ = currentNode.getProperty("exo:navigationNode").getString();
      }

      if (currentNode.hasProperty("exo:clickable")) {
        if (currentNode.getProperty("exo:clickable").getBoolean()) {
          isClickable = true;
        } else isClickable = false;
      }

      if (currentNode.hasProperty("exo:page")) {
        listTargetPage_ = currentNode.getProperty("exo:page").getString();
      }

      if (currentNode.hasProperty("exo:pageParamId")) {
        listShowClvBy_ = currentNode.getProperty("exo:pageParamId").getString();
      }

      if (currentNode.hasProperty("exo:childrenPage")) {
        detailTargetPage_ = currentNode.getProperty("exo:childrenPage").getString();
      }

      if (currentNode.hasProperty("exo:childrenPageParamId")) {
        detailShowClvBy_ = currentNode.getProperty("exo:childrenPageParamId").getString();
      }
    }
  }
 /**
  * Load script form supplied node.
  *
  * @param node JCR node
  * @throws Exception if any error occurs
  */
 private void loadScript(Node node) throws Exception {
   ResourceId key =
       new NodeScriptKey(repository.getConfiguration().getName(), workspaceName, node);
   ObjectFactory<AbstractResourceDescriptor> resource =
       groovyScript2RestLoader.groovyPublisher.unpublishResource(key);
   if (resource != null) {
     groovyScript2RestLoader.groovyPublisher.publishPerRequest(
         node.getProperty("jcr:data").getStream(), key, resource.getObjectModel().getProperties());
   } else {
     groovyScript2RestLoader.groovyPublisher.publishPerRequest(
         node.getProperty("jcr:data").getStream(), key, null);
   }
 }
Example #23
0
  public void testJCR1438_Simple() throws Exception {
    Node testRoot = root.addNode("testRoot");
    root.save();

    Node l1Node = testRoot.addNode("l1");
    l1Node.addMixin("mix:versionable");
    Node folder = l1Node.addNode("folder", "nt:folder");
    root.save();

    l1Node.checkin();
    l1Node.checkout();
    root.save();

    Node testImage = folder.addNode("test_image", "nt:file");
    testImage.addMixin("mix:versionable");

    Node contentTestImage = testImage.addNode("jcr:content", "nt:resource");
    contentTestImage.setProperty("jcr:data", "content_test_image_data");
    contentTestImage.setProperty("jcr:encoding", "UTF-8");
    contentTestImage.setProperty("jcr:lastModified", Calendar.getInstance());
    contentTestImage.setProperty("jcr:mimeType", "text/jpeg");
    root.save();

    Version tImageV1 = testImage.checkin();
    testImage.checkout();
    testImage.save();

    Version v2 = l1Node.checkin();
    l1Node.checkout();
    root.save();

    Node rTestImage = testRoot.getNode("l1").getNode("folder").getNode("test_image");
    assertNotNull(rTestImage);
    Node rTestImageContent = rTestImage.getNode("jcr:content");
    assertNotNull(rTestImageContent);
    assertNotNull(rTestImageContent.getProperty("jcr:data"));
    assertEquals("content_test_image_data", rTestImageContent.getProperty("jcr:data").getString());

    /*testImage.remove();
    root.save();*/

    l1Node.restore("2", true);

    rTestImage = testRoot.getNode("l1").getNode("folder").getNode("test_image");
    assertNotNull(rTestImage);
    rTestImageContent = rTestImage.getNode("jcr:content");
    assertNotNull(rTestImageContent);
    assertNotNull(rTestImageContent.getProperty("jcr:data"));
    assertEquals("content_test_image_data", rTestImageContent.getProperty("jcr:data").getString());
  }
  protected static Map<String, Map<Long, ResponseValue>> getTallyResponses(Resource tallyResource)
      throws JSONException {
    Map<String, Map<Long, ResponseValue>> returnValue =
        new HashMap<String, Map<Long, ResponseValue>>();
    final ResourceResolver resolver = tallyResource.getResourceResolver();
    final String tallyPath = tallyResource.getPath();
    if (!tallyPath.startsWith("/content/usergenerated")) {
      tallyResource = resolver.resolve("/content/usergenerated" + tallyPath);
    }
    final Resource responsesNode = tallyResource.getChild(TallyConstants.RESPONSES_PATH);
    if (responsesNode == null) {
      return null;
    }
    NestedBucketStorageSystem bucketSystem = getBucketSystem(responsesNode);
    if (null == bucketSystem) {
      return null;
    }

    final Iterator<Resource> buckets = bucketSystem.listBuckets();
    while (buckets.hasNext()) {
      final Resource bucketResource = buckets.next();
      final Node bucketNode = bucketResource.adaptTo(Node.class);
      try {
        final NodeIterator userNodesInBucket = bucketNode.getNodes();
        while (userNodesInBucket.hasNext()) {
          final Node userNode = userNodesInBucket.nextNode();
          final NestedBucketStorageSystem userBucketSystem =
              getBucketSystem(resolver.getResource(userNode.getPath()));
          final Iterator<Resource> userBuckets = userBucketSystem.listBuckets();
          final Map<Long, ResponseValue> userReturnValue = new HashMap<Long, ResponseValue>();
          while (userBuckets.hasNext()) {
            final NodeIterator userResponses = userBuckets.next().adaptTo(Node.class).getNodes();
            while (userResponses.hasNext()) {
              final Node responseNode = userResponses.nextNode();
              final Long responseTimestamp = responseNode.getProperty(TIMESTAMP_PROPERTY).getLong();
              userReturnValue.put(
                  responseTimestamp,
                  new PollResponse(responseNode.getProperty(RESPONSE_PROPERTY).getString()));
            }
          }
          returnValue.put(userNode.getName(), userReturnValue);
        }
      } catch (final RepositoryException e) {
        throw new JSONException(
            "Error trying to read user responses from bucket in " + bucketResource.getPath(), e);
      }
    }
    return returnValue;
  }
Example #25
0
  /**
   * @param node
   * @return
   * @throws Exception
   */
  public static String getTitleWithSymlink(Node node) throws Exception {
    String title = null;
    Node nProcessNode = node;
    if (title == null) {
      nProcessNode = node;
      if (nProcessNode.hasProperty("exo:title")) {
        title = nProcessNode.getProperty("exo:title").getValue().getString();
      }
      if (nProcessNode.hasNode("jcr:content")) {
        Node content = nProcessNode.getNode("jcr:content");
        if (content.hasProperty("dc:title")) {
          try {
            title = content.getProperty("dc:title").getValues()[0].getString();
          } catch (Exception e) {
            title = null;
          }
        }
      }
      if (title != null) title = title.trim();
    }
    if (title != null && title.length() > 0) return ContentReader.getXSSCompatibilityContent(title);
    if (isSymLink(node)) {
      nProcessNode = getNodeSymLink(nProcessNode);
      if (nProcessNode == null) {
        nProcessNode = node;
      }
      if (nProcessNode.hasProperty("exo:title")) {
        title = nProcessNode.getProperty("exo:title").getValue().getString();
      }
      if (nProcessNode.hasNode("jcr:content")) {
        Node content = nProcessNode.getNode("jcr:content");
        if (content.hasProperty("dc:title")) {
          try {
            title = content.getProperty("dc:title").getValues()[0].getString();
          } catch (Exception e) {
            title = null;
          }
        }
      }
      if (title != null) {
        title = title.trim();
        if (title.length() == 0) title = null;
      }
    }

    if (title == null) title = nProcessNode.getName();
    return ContentReader.getXSSCompatibilityContent(title);
  }
Example #26
0
 /**
  * @param node
  * @param node
  * @throws RepositoryException
  * @throws PathNotFoundException
  * @throws ValueFormatException
  */
 public ProviderSettingsImpl(Content profileContent, Node settingsNode)
     throws RepositoryException {
   this.profileNode = profileContent;
   this.settingsNode = settingsNode;
   if (settingsNode.hasProperty(ProviderSettings.PROFILE_PROVIDER)) {
     provider = settingsNode.getProperty(ProviderSettings.PROFILE_PROVIDER).getString();
   }
   if (settingsNode.hasProperty(ProviderSettings.PROFILE_PROVIDER_SETTINGS)) {
     String providerSettingsPath =
         settingsNode.getProperty(ProviderSettings.PROFILE_PROVIDER_SETTINGS).getString();
     Session session = settingsNode.getSession();
     if (session.nodeExists(providerSettingsPath)) {
       this.providerNode = session.getNode(providerSettingsPath);
     }
   }
 }
  /** {@inheritDoc} */
  public void onEvent(EventIterator eventIterator) {
    // waiting for Event.PROPERTY_ADDED, Event.PROPERTY_REMOVED,
    // Event.PROPERTY_CHANGED
    Session session = null;
    try {
      while (eventIterator.hasNext()) {
        Event event = eventIterator.nextEvent();
        String path = event.getPath();

        if (path.endsWith("/jcr:data")) {
          // jcr:data removed 'exo:groovyResourceContainer' then unbind resource
          if (event.getType() == Event.PROPERTY_REMOVED) {
            unloadScript(path.substring(0, path.lastIndexOf('/')));
          } else if (event.getType() == Event.PROPERTY_ADDED
              || event.getType() == Event.PROPERTY_CHANGED) {
            if (session == null) {
              session = repository.getSystemSession(workspaceName);
            }

            Node node = session.getItem(path).getParent();
            if (node.getProperty("exo:autoload").getBoolean()) loadScript(node);
          }
        }
      }
    } catch (Exception e) {
      LOG.error("Process event failed. ", e);
    } finally {
      if (session != null) {
        session.logout();
      }
    }
  }
  /**
   * Writes the message content to the <code>jcr:content/jcr:data</code> binary property.
   *
   * @param node mail node
   * @param message mail message
   * @throws MessagingException if a messaging error occurs
   * @throws RepositoryException if a repository error occurs
   * @throws IOException if an IO error occurs
   */
  @SuppressWarnings("deprecation")
  private void setMessage(Node node, final MimeMessage message)
      throws RepositoryException, IOException {
    try {
      node = node.getNode("jcr:content");
    } catch (PathNotFoundException e) {
      node = node.getProperty("jcr:content").getNode();
    }

    PipedInputStream input = new PipedInputStream();
    final PipedOutputStream output = new PipedOutputStream(input);
    new Thread() {
      public void run() {
        try {
          message.writeTo(output);
        } catch (Exception e) {
        } finally {
          try {
            output.close();
          } catch (IOException e) {
          }
        }
      }
    }.start();
    node.setProperty("jcr:data", input);
  }
 /**
  * Reads the remote address from the <code>james:remoteaddr</code> property.
  *
  * @param node mail node
  * @return remote address, or <code>null</code> if not set
  * @throws RepositoryException if a repository error occurs
  */
 private String getRemoteAddr(Node node) throws RepositoryException {
   try {
     return node.getProperty("james:remoteaddr").getString();
   } catch (PathNotFoundException e) {
     return null;
   }
 }
Example #30
0
 public String getContentType() {
   String ct = "application/octet-stream";
   try {
     if (node.getPrimaryNodeType().getName().equals(JcrConstants.NT_FILE)) {
       Node contentNode = node.getNode(JcrConstants.JCR_CONTENT);
       ct = contentNode.getProperty(JcrConstants.JCR_MIMETYPE).getString();
     } else {
       if (node.hasProperty(MessageConstants.PROP_SAKAI_CONTENT_TYPE)) {
         ct = node.getProperty(MessageConstants.PROP_SAKAI_CONTENT_TYPE).getString();
       }
     }
   } catch (RepositoryException re) {
     LOGGER.error(re.getMessage(), re);
   }
   return ct;
 }