@Test
  public void testReOrderingOfChildNodesWithRemovedChild() throws Exception {
    // GIVEN
    ((MockNode) baseNode).setPrimaryNodeType(new MockNodeType(NodeTypes.Content.NAME, null, true));
    baseNode.addNode("child-a");
    baseNode.addNode("child-b");
    baseNode.addNode("child-c");
    JcrNodeAdapter item = new JcrNodeAdapter(baseNode);
    item.removeChild(new JcrNodeAdapter(baseNode.getNode("child-c")));
    item.addChild(new JcrNodeAdapter(baseNode.getNode("child-b")));
    item.addChild(new JcrNodeAdapter(baseNode.getNode("child-a")));

    // WHEN
    item.applyChanges();

    // THEN
    List<String> nodes =
        Lists.newArrayList(
            Iterators.transform(
                item.getJcrItem().getNodes(),
                new Function<Node, String>() {
                  @Nullable
                  @Override
                  public String apply(@Nullable Node node) {
                    return NodeUtil.getName(node);
                  }
                }));

    assertThat(nodes, contains("child-b", "child-a"));
  }
  public String getHomePageLogoURI() {
    SessionProvider sProvider = SessionProvider.createSystemProvider();
    Node rootNode = null;
    Node publicApplicationNode = null;
    String pathImageNode = null;
    Node ImageNode = null;
    Session session = null;
    try {
      publicApplicationNode = nodeCreator.getPublicApplicationNode(sProvider);
      session = publicApplicationNode.getSession();
      rootNode = session.getRootNode();
      Node logosNode = rootNode.getNode(path);
      if (logosNode.hasNode(logo_name)) {
        ImageNode = logosNode.getNode(logo_name);
        pathImageNode = ImageNode.getPath() + "?" + System.currentTimeMillis();
      }
    } catch (Exception e) {
      LOG.error("Can not get path of Logo : default LOGO will be used" + e.getMessage(), e);
      return null;
    } finally {
      if (session != null) session.logout();

      if (sProvider != null) sProvider.close();
    }

    return pathImageNode;
  }
  @Test
  public void testAddExistingChildAndStore() throws Exception {
    // GIVEN
    JcrNodeAdapter item = new JcrNodeAdapter(baseNode);
    // Add property to the Item
    DefaultProperty<String> property = new DefaultProperty<String>(String.class, "propertyValue");
    item.addItemProperty("propertyName", property);
    // Create a child node
    Node child = baseNode.addNode("childNode");
    JcrNodeAdapter childItem = new JcrNodeAdapter(child);
    item.addChild(childItem);
    // Add property to the child Item
    DefaultProperty<String> childProperty =
        new DefaultProperty<String>(String.class, "childPropertyValue");
    childItem.addItemProperty("childPropertyName", childProperty);

    // WHEN
    Node res = item.applyChanges();

    // THEN
    assertNotNull(res);
    assertEquals(baseNode, res);
    assertEquals(true, res.hasProperty("propertyName"));
    assertEquals("propertyValue", res.getProperty("propertyName").getValue().getString());
    assertEquals(true, res.hasNode("childNode"));
    assertEquals(true, res.getNode("childNode").hasProperty("childPropertyName"));
    assertEquals(
        "childPropertyValue",
        res.getNode("childNode").getProperty("childPropertyName").getValue().getString());
  }
  @Ignore
  // @Test(timeout=5000)
  public void benchmark() throws RepositoryException {
    /* once to warm up, second one for real */
    String uuid = documents.get(random.nextInt(documents.size()));
    Node document = session.getNodeByUUID(uuid);
    document = document.getNode(document.getName());
    long t1 = System.currentTimeMillis();
    Set<Node> referrers = getReferrers(document);
    if (log.isDebugEnabled()) {
      System.err.println("result " + referrers.size() + " out of " + documents.size());
    }
    long t2 = System.currentTimeMillis();
    if (log.isDebugEnabled()) {
      System.err.println("timing references " + (t2 - t1) / 1000.0);
    }

    uuid = documents.get(random.nextInt(documents.size()));
    document = session.getNodeByUUID(uuid);
    document = document.getNode(document.getName());
    t1 = System.currentTimeMillis();
    referrers = getReferrers(document);
    t2 = System.currentTimeMillis();
    if (log.isDebugEnabled()) {
      System.err.println("timing references " + (t2 - t1) / 1000.0);
    }
  }
Example #5
0
  @Override
  public void updateFile(
      long companyId, long repositoryId, String fileName, String versionLabel, InputStream is)
      throws PortalException, SystemException {

    Session session = null;

    try {
      session = JCRFactoryUtil.createSession();

      Workspace workspace = session.getWorkspace();

      VersionManager versionManager = workspace.getVersionManager();

      Node rootNode = getRootNode(session, companyId);

      Node repositoryNode = getFolderNode(rootNode, repositoryId);

      if (fileName.contains(StringPool.SLASH)) {
        String path = fileName.substring(0, fileName.lastIndexOf(StringPool.SLASH));

        fileName = fileName.substring(path.length() + 1);

        repositoryNode = getFolderNode(repositoryNode, path);
      }

      Node fileNode = repositoryNode.getNode(fileName);

      Node contentNode = fileNode.getNode(JCRConstants.JCR_CONTENT);

      versionManager.checkout(contentNode.getPath());

      contentNode.setProperty(JCRConstants.JCR_MIME_TYPE, "text/plain");

      ValueFactory valueFactory = session.getValueFactory();

      Binary binary = valueFactory.createBinary(is);

      contentNode.setProperty(JCRConstants.JCR_DATA, binary);

      contentNode.setProperty(JCRConstants.JCR_LAST_MODIFIED, Calendar.getInstance());

      session.save();

      Version version = versionManager.checkin(contentNode.getPath());

      VersionHistory versionHistory = versionManager.getVersionHistory(contentNode.getPath());

      versionHistory.addVersionLabel(
          version.getName(), versionLabel, PropsValues.DL_STORE_JCR_MOVE_VERSION_LABELS);
    } catch (PathNotFoundException pnfe) {
      throw new NoSuchFileException(
          "{fileName=" + fileName + ", versionLabel=" + versionLabel + "}");
    } catch (RepositoryException re) {
      throw new SystemException(re);
    } finally {
      JCRFactoryUtil.closeSession(session);
    }
  }
 /** {@inheritDoc} */
 public List<Node> getTemplatesByCategory(
     String portletName, String category, SessionProvider sessionProvider) throws Exception {
   Node basedApplicationTemplateHome = getBasedApplicationTemplatesHome(sessionProvider);
   Node applicationHome = basedApplicationTemplateHome.getNode(portletName);
   Node categoryNode = applicationHome.getNode(category);
   List<Node> templateNodes = new ArrayList<Node>();
   for (NodeIterator iterator = categoryNode.getNodes(); iterator.hasNext(); ) {
     templateNodes.add(iterator.nextNode());
   }
   return templateNodes;
 }
Example #7
0
 @Test
 public void shouldFindMasterBranchAsPrimaryItemUnderTreeNode() throws Exception {
   Node git = gitNode();
   Node tree = git.getNode("tree");
   Item primaryItem = tree.getPrimaryItem();
   assertThat(primaryItem, is(notNullValue()));
   assertThat(primaryItem, is(instanceOf(Node.class)));
   Node primaryNode = (Node) primaryItem;
   assertThat(primaryNode.getName(), is("master"));
   assertThat(primaryNode.getParent(), is(sameInstance(tree)));
   assertThat(primaryNode, is(sameInstance(tree.getNode("master"))));
 }
  // start setting of list in right rail
  public void rightRailList(
      Node listNode, Element rightListEle, Map<String, String> urlMap, String locale) {
    try {
      Element title;
      Element description;
      Elements headElements = rightListEle.getElementsByTag("h2");
      if (headElements.size() > 1) {
        title = rightListEle.getElementsByTag("h2").last();
        description = rightListEle.getElementsByTag("p").last();
        sb.append("<li>Mismatch in count of list panel component in right rail.</li>");
      } else {
        title = rightListEle.getElementsByTag("h2").first();
        description = rightListEle.getElementsByTag("p").first();
      }
      listNode.setProperty("title", title.text());
      javax.jcr.Node introNode = listNode.getNode("intro");
      introNode.setProperty("paragraph_rte", description.text());
      javax.jcr.Node eleListNode = listNode.getNode("element_list_0");

      Elements ulList = rightListEle.getElementsByTag("ul");
      for (Element element : ulList) {
        java.util.List<String> list = new ArrayList<String>();
        Elements menuLiList = element.getElementsByTag("li");

        for (Element li : menuLiList) {
          JSONObject jsonObjrr = new JSONObject();
          Element listItemAnchor = li.getElementsByTag("a").first();
          String anchorText = listItemAnchor != null ? listItemAnchor.text() : "";
          String anchorHref = listItemAnchor.absUrl("href");
          if (StringUtil.isBlank(anchorHref)) {
            anchorHref = listItemAnchor.attr("href");
          }
          // Start extracting valid href
          log.debug("Before right list LinkUrl" + anchorHref + "\n");
          anchorHref = FrameworkUtils.getLocaleReference(anchorHref, urlMap, locale, sb);
          log.debug("after right list LinkUrl" + anchorHref + "\n");
          // End extracting valid href

          jsonObjrr.put("linktext", anchorText);
          jsonObjrr.put("linkurl", anchorHref);
          jsonObjrr.put("icon", "none");
          jsonObjrr.put("size", "");
          jsonObjrr.put("description", "");
          jsonObjrr.put("openInNewWindow", "false");
          list.add(jsonObjrr.toString());
        }
        eleListNode.setProperty("listitems", list.toArray(new String[list.size()]));
      }
      log.debug("Updated title, descriptoin and linktext at " + listNode.getPath());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #9
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());
  }
Example #10
0
  /**
   * Test get active java script_11.
   *
   * <p>Child node have properties normal and value of jcr:data is: - "jcr:data": This is the
   * default.js file.
   */
  public void testGetActiveJavaScript_11() {
    try {
      Node webContent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, null, null);
      Node jsNode = webContent.getNode("js").getNode("default.js");
      Node jsContent = jsNode.getNode("jcr:content");
      jsContent.setProperty("jcr:data", "This is the default.js file.");
      session.save();

      String jsData = javascriptService.getActiveJavaScript(webContent);
      assertEquals("This is the default.js file.", jsData);
    } catch (Exception e) {
      fail();
    }
  }
  @Test
  public void testCreateObjectWithExistingHierarchy() throws Exception {
    when(mockNode.getParent()).thenReturn(mockParent);
    when(mockParent.getParent()).thenReturn(mockRoot);
    when(mockParent.isNew()).thenReturn(false);
    when(mockRoot.hasNode("foo")).thenReturn(true);
    when(mockRoot.getNode("foo")).thenReturn(mockParent);
    when(mockRoot.getNode("foo/bar")).thenReturn(mockNode);
    when(mockNode.isNew()).thenReturn(true);
    when(mockNode.getDepth()).thenReturn(1);

    final Node actual = getJcrNode(testObj.findOrCreate(mockSession, "/foo/bar"));
    assertEquals(mockNode, actual);
    verify(mockParent, never()).addMixin(FedoraTypes.FEDORA_PAIRTREE);
  }
Example #12
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 #13
0
  @Override
  public void deleteDirectory(long companyId, long repositoryId, String dirName)
      throws PortalException {

    Session session = null;

    try {
      session = JCRFactoryUtil.createSession();

      Node rootNode = getRootNode(session, companyId);

      Node repositoryNode = getFolderNode(rootNode, repositoryId);

      Node dirNode = repositoryNode.getNode(dirName);

      dirNode.remove();

      session.save();
    } catch (PathNotFoundException pnfe) {
      throw new NoSuchDirectoryException(dirName);
    } catch (RepositoryException re) {
      String message = GetterUtil.getString(re.getMessage());

      if (message.contains("failed to resolve path")) {
        throw new NoSuchDirectoryException(dirName);
      } else {
        throw new PortalException(re);
      }
    } finally {
      JCRFactoryUtil.closeSession(session);
    }
  }
Example #14
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));
  }
  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);
      }
    }
  }
  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;
  }
 protected SimpleAttachment getAttachment(Node node, String language) throws RepositoryException {
   String attachmentNodeName = SimpleDocument.FILE_PREFIX + language;
   if (node.hasNode(attachmentNodeName)) {
     return attachmentConverter.convertNode(node.getNode(attachmentNodeName));
   }
   return null;
 }
  /**
   * 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);
  }
Example #19
0
  @Override
  public boolean bind(Object content, javax.jcr.Node node) throws ContentNodeBindingException {
    if (content instanceof Review) {
      try {
        Review review = (Review) content;
        node.setProperty(PROP_NAME, review.getName());
        node.setProperty(PROP_EMAIL, review.getEmail());
        node.setProperty(PROP_COMMENT, review.getComment());
        node.setProperty(PROP_RATING, review.getRating());
        node.setProperty(PROP_DATE, Calendar.getInstance());

        javax.jcr.Node prdLinkNode;

        if (node.hasNode(NT_PRODUCTLINK)) {
          prdLinkNode = node.getNode(NT_PRODUCTLINK);
        } else {
          prdLinkNode = node.addNode(NT_PRODUCTLINK, "hippo:mirror");
        }
        prdLinkNode.setProperty("hippo:docbase", review.getProductUuid());

      } catch (Exception e) {
        log.error("Unable to bind the content to the JCR Node" + e.getMessage(), e);
        throw new ContentNodeBindingException(e);
      }
    }
    return true;
  }
 protected String readFileFromNode(Node fileNode)
     throws IOException, ValueFormatException, PathNotFoundException, RepositoryException {
   CharArrayWriter writer = null;
   InputStream in = null;
   Reader reader = null;
   try {
     in =
         fileNode.getNode(JcrConstants.JCR_CONTENT).getProperty(JcrConstants.JCR_DATA).getStream();
     writer = new CharArrayWriter();
     reader = new InputStreamReader(in);
     char[] buffer = new char[8];
     int c = 0;
     while ((c = reader.read(buffer)) != -1) {
       writer.write(buffer, 0, c);
     }
     return new String(writer.toCharArray());
   } catch (IOException ioex) {
     return null;
   } finally {
     if (reader != null) {
       reader.close();
     }
     if (in != null) {
       in.close();
     }
     if (writer != null) {
       writer.close();
     }
   }
 }
Example #21
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 #22
0
 /**
  * Generate the Thumbnail Image URI.
  *
  * @param file the node
  * @return the Thumbnail uri with medium size
  * @throws Exception the exception
  */
 public static String generateThumbnailImageURI(Node file) throws Exception {
   StringBuilder builder = new StringBuilder();
   NodeLocation fielLocation = NodeLocation.getNodeLocationByNode(file);
   String repository = fielLocation.getRepository();
   String workspaceName = fielLocation.getWorkspace();
   String nodeIdentifiler = file.getPath().replaceFirst("/", "");
   String portalName = PortalContainer.getCurrentPortalContainerName();
   String restContextName = PortalContainer.getCurrentRestContextName();
   InputStream stream =
       file.getNode(NodetypeConstant.JCR_CONTENT)
           .getProperty(NodetypeConstant.JCR_DATA)
           .getStream();
   if (stream.available() == 0) return null;
   stream.close();
   builder
       .append("/")
       .append(portalName)
       .append("/")
       .append(restContextName)
       .append("/")
       .append("thumbnailImage/medium/")
       .append(repository)
       .append("/")
       .append(workspaceName)
       .append("/")
       .append(nodeIdentifiler);
   return builder.toString();
 }
Example #23
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();
    }
  }
Example #24
0
  @Before
  public void setUp() throws RepositoryException {
    initMocks(this);
    final String relPath = "/" + testPid;
    final NodeType[] types = new NodeType[0];
    try {
      when(mockObjNode.getName()).thenReturn(testPid);
      when(mockObjNode.getSession()).thenReturn(mockSession);
      when(mockObjNode.getMixinNodeTypes()).thenReturn(types);
      NodeType mockNodeType = mock(NodeType.class);
      when(mockNodeType.getName()).thenReturn("nt:folder");
      when(mockObjNode.getPrimaryNodeType()).thenReturn(mockNodeType);
      when(mockSession.getRootNode()).thenReturn(mockRootNode);
      when(mockRootNode.getNode(relPath)).thenReturn(mockObjNode);
      when(mockSession.getUserID()).thenReturn(mockUser);
      testFedoraObject = new FedoraObject(mockObjNode);

      mockNodetypes = new NodeType[2];
      mockNodetypes[0] = mock(NodeType.class);
      mockNodetypes[1] = mock(NodeType.class);

      when(mockObjNode.getMixinNodeTypes()).thenReturn(mockNodetypes);

      when(mockPredicate.apply(mockObjNode)).thenReturn(true);

    } catch (final RepositoryException e) {
      e.printStackTrace();
      fail(e.getMessage());
    }
  }
Example #25
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;
 }
  @Test(timeout = 5000000)
  public void testBasicDDLStatement() throws Exception {
    String ddl = "CREATE VIEW Tweet AS select * FROM twitterview.getTweets;";
    Node fileNode = prepareSequence(ddl, SequencerType.DDL);

    //
    // Sequencing completed, now verify
    //

    // DDL Sequencer creates the 'Tweet' node
    Node tweetNode = fileNode.getNode("Tweet");
    assertNotNull(tweetNode);

    // TSQL Sequencer is triggered from the Tweet node's queryExpression property
    // and sequences its string value into TSQL nodes starting with a query node
    Node queryNode = verify(tweetNode, Query.ID, Query.ID);

    // Query should have a SELECT
    Node selectNode = verify(queryNode, Query.SELECT_REF_NAME, Select.ID);

    // Select should have a symbols collection
    // Select has a * so symbolsNode should be a MultipleElementSymbol
    verify(selectNode, Select.SYMBOLS_REF_NAME, MultipleElementSymbol.ID);

    // Should have a FROM
    Node fromNode = verify(queryNode, Query.FROM_REF_NAME, From.ID);

    // UnaryFromClause should have a group
    verifyUnaryFromClauseGroup(fromNode, From.CLAUSES_REF_NAME, 1, "twitterview.getTweets");
  }
 public Node getRuntimeRolesFolderNode(final Session session, ITenant tenant)
     throws RepositoryException {
   Node tenantRootFolderNode = null;
   try {
     tenantRootFolderNode =
         (Node) session.getItem(ServerRepositoryPaths.getTenantRootFolderPath(tenant));
   } catch (PathNotFoundException e) {
     throw new RepositoryException(
         "Error retrieving RuntimeRoles for folder, folder not found", e);
     // Assert.state(false, Messages.getInstance().getString(
     // "JcrRoleAuthorizationPolicyRoleBindingDao.ERROR_0002_REPO_NOT_INITIALIZED")); //$NON-NLS-1$
   }
   Node authzFolderNode = tenantRootFolderNode.getNode(FOLDER_NAME_AUTHZ);
   Node roleBasedFolderNode = authzFolderNode.getNode(FOLDER_NAME_ROLEBASED);
   return roleBasedFolderNode.getNode(FOLDER_NAME_RUNTIMEROLES);
 }
  @Override
  public long setContent(
      Node parentNode,
      String resourceName,
      InputStream newContent,
      String contentType,
      String characterEncoding)
      throws RepositoryException, IOException {
    Node contentNode;
    if (parentNode.hasNode(CONTENT_NODE_NAME)) {
      contentNode = parentNode.getNode(CONTENT_NODE_NAME);
    } else {
      contentNode = parentNode.addNode(CONTENT_NODE_NAME, newContentPrimaryType);
    }

    // contentNode.setProperty(MIME_TYPE_PROP_NAME, contentType != null ? contentType :
    // "application/octet-stream");
    contentNode.setProperty(
        ENCODING_PROP_NAME, characterEncoding != null ? characterEncoding : "UTF-8");
    Binary binary = parentNode.getSession().getValueFactory().createBinary(newContent);
    contentNode.setProperty(DATA_PROP_NAME, binary);
    contentNode.setProperty(MODIFIED_PROP_NAME, Calendar.getInstance());

    // Copy the content to the property, THEN re-read the content from the Binary value to avoid
    // discaring the first
    // bytes of the stream
    if (contentType == null) {
      contentType = mimeTypeDetector.mimeTypeOf(resourceName, binary.getStream());
    }

    return contentNode.getProperty(DATA_PROP_NAME).getLength();
  }
 public Node getLibraryNode(SlingHttpServletRequest request, HtmlLibrary library) {
   Node node = null;
   try {
     // we want the non-minified version as the root path
     String cacheRoot =
         Text.getRelativeParent(
             (new StringBuilder(CACHE_PATH).append(library.getPath(false))).toString(), 1);
     String optPath =
         (new StringBuilder(cacheRoot).append("/").append(getLibraryName(library))).toString();
     node = JcrUtils.getNodeIfExists(optPath, getAdminSession());
     if (null == node) {
       // generate empty jcr:data to cache
       node = createEmptyCache(library, cacheRoot, getAdminSession());
     }
     // lib was modified after last cache write
     if (!node.hasNode(JcrConstants.JCR_CONTENT)
         || library.getLastModified(false)
             > JcrUtils.getLongProperty(
                 node.getNode(JcrConstants.JCR_CONTENT), JcrConstants.JCR_LASTMODIFIED, 0L)) {
       // generate new binary, if possible
       node = populateCache(library, node.getPath(), getAdminSession());
     }
     // reassign with user session
     node = request.getResourceResolver().resolve(node.getPath()).adaptTo(Node.class);
   } catch (RepositoryException re) {
     log.debug(re.getMessage());
   } finally {
     getResolver().close();
   }
   return node;
 }
Example #30
0
 /**
  * Gets the title.
  *
  * @param node the node
  * @return the title
  * @throws Exception the exception
  */
 public static String getTitle(Node node) throws Exception {
   String title = null;
   try {
     title = node.getProperty("exo:title").getValue().getString();
   } catch (PathNotFoundException pnf1) {
     try {
       Value[] values = node.getNode("jcr:content").getProperty("dc:title").getValues();
       if (values.length != 0) {
         title = values[0].getString();
       }
     } catch (PathNotFoundException pnf2) {
       title = null;
     }
   } catch (ValueFormatException e) {
     title = null;
   } catch (IllegalStateException e) {
     title = null;
   } catch (RepositoryException e) {
     title = null;
   }
   if (StringUtils.isBlank(title)) {
     title = node.getName();
   }
   return ContentReader.getXSSCompatibilityContent(title);
 }