@Test
  public void testAddRemoveExistingChildAndStore() 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 one new child Item
    // Create a child node
    Node child = baseNode.addNode("childNode");
    JcrNodeAdapter childItem = new JcrNodeAdapter(child);
    item.addChild(childItem);
    assertEquals(true, baseNode.hasNode("childNode"));
    // Add property to the child Item
    DefaultProperty<String> childProperty =
        new DefaultProperty<String>(String.class, "childPropertyValue");
    childItem.addItemProperty("childPropertyName", childProperty);

    // WHEN
    item.removeChild(childItem);

    // THEN
    // Get node
    Node res = item.applyChanges();
    assertNotNull(res);
    assertEquals(baseNode, res);
    assertEquals(true, res.hasProperty("propertyName"));
    assertEquals("propertyValue", res.getProperty("propertyName").getValue().getString());
    assertEquals(false, res.hasNode("childNode"));
  }
  /**
   * Creates the node strucure is it not already created
   *
   * @throws ServletException if error
   */
  private void createNodeStructure() throws ServletException {

    try {

      Node rootNode = session.getRootNode();
      Node admin = null;

      // creates the root node of the system if not already created
      if (!rootNode.hasNode("blogRoot")) {
        Node blogRoot = rootNode.addNode("blogRoot", "nt:folder");

        // Adding the admin user
        admin = blogRoot.addNode("admin", "blog:user");
        admin.setProperty("blog:nickname", "admin");
        admin.setProperty("blog:email", "*****@*****.**");
        admin.setProperty("blog:password", "admin");
        session.save();

        // Adding the guest user
        Node guest = blogRoot.addNode("guest", "blog:user");
        guest.setProperty("blog:nickname", "guest");

        // These properties will never be used by the system
        guest.setProperty("blog:email", "*****@*****.**");
        guest.setProperty("blog:password", "guest");
      }

      // Created the library node if not already created
      if (!rootNode.hasNode("library")) {
        rootNode.addNode("library", "nt:folder");
      }

      if (!rootNode.hasNode("wiki")) {
        Node wiki = rootNode.addNode("wiki", "nt:folder");
        Node frontPage = wiki.addNode("frontPage", "wiki:wikiPage");

        frontPage.setProperty("wiki:title", "Front Page");
        frontPage.setProperty("wiki:content", "Type the content here");
        frontPage.setProperty("wiki:savedBy", admin.getUUID());
      }

      session.save();

      log("JACKRABBIT-JCR-DEMO: Node Structure created ...");

    } catch (RepositoryException e) {
      throw new ServletException("Failed to create node structure ", e);
    }
  }
Esempio n. 3
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);
  }
Esempio n. 4
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();
    }
  }
Esempio n. 5
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;
  }
  /**
   * The main entry point of the example application.
   *
   * @param args command line arguments (ignored)
   * @throws Exception if an error occurs
   */
  public static void main(String[] args) throws Exception {
    Repository repository = new TransientRepository();
    Session session = repository.login(new SimpleCredentials("admin", "admin".toCharArray()));
    try {
      Node root = session.getRootNode();

      // Import the XML file unless already imported
      if (!root.hasNode("importxml")) {
        System.out.print("Importing xml... ");

        // Create an unstructured node under which to import the XML
        Node node = root.addNode("importxml", "nt:unstructured");

        // Import the file "test.xml" under the created node
        FileInputStream xml = new FileInputStream("test.xml");
        session.importXML(node.getPath(), xml, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);
        xml.close();
        session.save();
        System.out.println("done.");
      }

      // output the repository content
      dump(root);
    } finally {
      session.logout();
    }
  }
  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);
      }
    }
  }
 /**
  * Check existed software registration node
  *
  * @return
  */
 private boolean hasSoftwareRegistration() {
   SessionProvider sessionProvider = null;
   try {
     if (hasSoftwareRegisteredNode) {
       return hasSoftwareRegisteredNode;
     } else {
       try {
         sessionProvider = SessionProvider.createSystemProvider();
         Node publicApplicationNode =
             nodeHierarchyCreator.getPublicApplicationNode(sessionProvider);
         if (publicApplicationNode.hasNode(SW_NODE_NAME)) {
           hasSoftwareRegisteredNode = true;
         } else {
           hasSoftwareRegisteredNode = false;
         }
       } catch (Exception e) {
         LOG.error("Software Registration: cannot get node", e);
         hasSoftwareRegisteredNode = false;
       } finally {
         sessionProvider.close();
       }
       return hasSoftwareRegisteredNode;
     }
   } catch (Exception e) {
     LOG.error("Software Registration: cannot check node", e);
   }
   return hasSoftwareRegisteredNode;
 }
Esempio n. 9
0
 public boolean feedExists() {
   try {
     return itemNode.hasNode(RSS_NODE_NAME);
   } catch (Exception e) {
     return false;
   }
 }
 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;
 }
 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;
 }
Esempio n. 12
0
  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;
  }
  /**
   * This will prepare <code>jcrPath</code> to have a storage node for the unique id. Call this
   * method on initialization time when no concurrent access will hapen.
   */
  public void initializePath(String jcrPath) throws IDException {
    jcrPath = removeJCRPrefix(jcrPath);

    Session session;
    try {
      session = login();

      Item item = session.getItem(jcrPath);
      if (!item.isNode()) {
        throw new IDException("Path '" + jcrPath + "' is a property (should be a node)");
      } else {
        // check if it has a subnode containing a unique id
        Node parent = (Node) item;
        if (!parent.hasNode(ID_NODE)) {
          // create the id node if it does not exist yet
          parent.addNode(ID_NODE, ID_NODE_TYPE);
          session.save();
        }
      }
      session.logout();
    } catch (LoginException e) {
      throw new IDException("Login to repository failed.", e);
    } catch (PathNotFoundException e) {
      throw new IDException("Repository path does not exist: " + jcrPath, e);
    } catch (RepositoryException e) {
      throw new IDException("Cannot lookup repository path: " + jcrPath, e);
    }
  }
  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;
  }
  @Test
  public void testAddNewChildAndStore() 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 one new child Item
    JcrNewNodeAdapter newChild = new JcrNewNodeAdapter(baseNode, "mgnl:content", "childNode");
    item.addChild(newChild);
    // Add property to the child Item
    DefaultProperty<String> childProperty =
        new DefaultProperty<String>(String.class, "childPropertyValue");
    newChild.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());
  }
Esempio n. 16
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();
  }
Esempio n. 17
0
  @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();
  }
Esempio n. 18
0
 private void initSettingHome() throws Exception {
   Node rootNode = session.getRootNode();
   if (rootNode.hasNode("settings") == false) {
     Node settingNode = rootNode.addNode("settings", "stg:settings");
     settingNode.addNode("user", "stg:subcontext");
     session.save();
   }
 }
 private void migratePrimaryCta(
     Element upperRightElement,
     Node midSizeUpperRightNode,
     String locale,
     Map<String, String> urlMap)
     throws PathNotFoundException, ValueFormatException, VersionException, LockException,
         ConstraintViolationException, RepositoryException {
   if (upperRightElement != null) {
     if (midSizeUpperRightNode.hasNode("primary_cta_v2")) {
       Element title = upperRightElement.getElementsByTag("h3").first();
       Element description = upperRightElement.getElementsByTag("p").first();
       Element link = upperRightElement.getElementsByTag("a").first();
       Node ctaNode = midSizeUpperRightNode.getNode("primary_cta_v2");
       if (title != null) {
         ctaNode.setProperty("title", title.text());
       } else {
         sb.append(Constants.PRIMARY_CTA_TITLE_ELEMENT_NOT_FOUND);
       }
       if (description != null) {
         ctaNode.setProperty("description", description.text());
       } else {
         sb.append(Constants.PRIMARY_CTA_DESCRIPTION_ELEMENT_NOT_FOUND);
       }
       if (link != null) {
         ctaNode.setProperty("linktext", link.text());
         if (ctaNode.hasNode("linkurl")) {
           String aUrl = link.absUrl("href");
           if (aUrl.equals("")) {
             aUrl = link.attr("href");
           }
           aUrl = FrameworkUtils.getLocaleReference(aUrl, urlMap, locale, sb);
           Node linkUrlNode = ctaNode.getNode("linkurl");
           linkUrlNode.setProperty("url", aUrl);
         } else {
           sb.append(Constants.PRIMARY_CTA_LINK_URL_NODE_NOT_FOUND);
         }
       } else {
         sb.append(Constants.PRIMARY_CTA_ANCHOR_ELEMENT_NOT_FOUND);
       }
     } else {
       sb.append(Constants.PRIMARY_CTA_COMPONENT_NOT_FOUND);
     }
   } else {
     sb.append(Constants.PRIMARY_CTA_COMPONENT_INWEB_NOT_FOUND);
   }
 }
Esempio n. 20
0
 /** Clean all node for testing */
 public void tearDown() throws Exception {
   Node myRoot = session.getRootNode();
   if (myRoot.hasNode("Feeds")) {
     myRoot.getNode("Feeds").remove();
   }
   session.save();
   super.tearDown();
 }
Esempio n. 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();
      }
    }
  }
Esempio n. 22
0
  public void saveProfilePic(String username, InputStream inputStream) {
    Session session = null;
    try {
      session = repository.login(credentials);
      Node rootNode = session.getRootNode();
      Node userHomeFolder = null;
      if (rootNode.hasNode(username)) {
        userHomeFolder = rootNode.getNode(username);
      } else {
        userHomeFolder = rootNode.addNode(username, NodeType.NT_FOLDER);
      }

      Node userProfilePicFile = null;
      if (userHomeFolder.hasNode(username)) {
        userProfilePicFile = userHomeFolder.getNode(username);
      } else {
        userProfilePicFile = userHomeFolder.addNode(username, NodeType.NT_FILE);
      }

      Node userProfilePicData = null;

      if (userProfilePicFile.hasNode(username + ".jpg")) {
        userProfilePicData = userProfilePicFile.getNode(username + ".jpg");
      } else {
        userProfilePicData = userProfilePicFile.addNode(username + ".jpg", NodeType.NT_RESOURCE);
      }

      Binary value = session.getValueFactory().createBinary(inputStream);

      userProfilePicData.setProperty(Property.JCR_DATA, value);

      session.save();

    } catch (LoginException e) {

      new ApplicationException("Failed to authenticate with content repository", e);
    } catch (RepositoryException e) {

      new ApplicationException("failed to add file", e);
    } finally {
      if (session != null && session.isLive()) {
        session.logout();
      }
    }
  }
Esempio n. 23
0
  @Override
  public void addFile(long companyId, long repositoryId, String fileName, 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);
      }

      if (repositoryNode.hasNode(fileName)) {
        throw new DuplicateFileException(fileName);
      } else {
        Node fileNode = repositoryNode.addNode(fileName, JCRConstants.NT_FILE);

        Node contentNode = fileNode.addNode(JCRConstants.JCR_CONTENT, JCRConstants.NT_RESOURCE);

        contentNode.addMixin(JCRConstants.MIX_VERSIONABLE);
        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(), VERSION_DEFAULT, false);
      }
    } catch (RepositoryException re) {
      throw new SystemException(re);
    } finally {
      JCRFactoryUtil.closeSession(session);
    }
  }
Esempio n. 24
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;
  }
 private void addTab(Node view, String tabName, String buttons) throws Exception {
   Node tab;
   if (view.hasNode(tabName)) {
     tab = view.getNode(tabName);
   } else {
     tab = view.addNode(tabName, "exo:tab");
   }
   tab.setProperty("exo:buttons", buttons);
   view.save();
 }
 public void removeAttachment(Node documentNode, String language) throws RepositoryException {
   String lang = language;
   if (lang == null) {
     lang = I18NHelper.defaultLanguage;
   }
   if (documentNode.hasNode(SimpleDocument.FILE_PREFIX + lang)) {
     Node attachmentNode = documentNode.getNode(SimpleDocument.FILE_PREFIX + lang);
     attachmentNode.remove();
   }
 }
 private Node getAttachmentNode(String attachmentNodeName, Node documentNode)
     throws RepositoryException {
   Node attachmentNode;
   if (documentNode.hasNode(attachmentNodeName)) {
     attachmentNode = documentNode.getNode(attachmentNodeName);
   } else {
     attachmentNode = documentNode.addNode(attachmentNodeName, SLV_SIMPLE_ATTACHMENT);
   }
   return attachmentNode;
 }
Esempio n. 28
0
  /**
   * Creates an excerpt for the given <code>hit</code>.
   *
   * @param hit the current hit.
   * @param excerptPropNames the names of the properties to use for the excerpt.
   * @param maxLength the maximum length of the excerpt.
   * @return the excerpt.
   * @throws RepositoryException if an error occurs while reading from the repository.
   */
  public static Excerpt create(final HitImpl hit, final Set excerptPropNames, final int maxLength)
      throws RepositoryException {
    Node node = hit.getResource().adaptTo(Node.class);
    if (node == null) {
      // use repository built in mechanism
      return new Excerpt(hit.getExcerpts().get("."));
    }
    Node content =
        node.hasNode(JcrConstants.JCR_CONTENT) ? node.getNode(JcrConstants.JCR_CONTENT) : node;
    if (content.isNodeType(JcrConstants.NT_RESOURCE)) {
      // use repository built in mechanism
      return new Excerpt(hit.getExcerpts().get("."));
    }

    final List<Excerpt> excerpt = new ArrayList<Excerpt>();
    final int prefixLength = node.getPath().length() + 1;
    // build excerpt built on a given set of property names
    try {
      content.accept(
          new TraversingItemVisitor.Default(true) {
            protected void entering(Property property, int level) throws RepositoryException {

              if (!excerptPropNames.contains(property.getName())) {
                // ignore
                return;
              }
              String relPath = property.getPath().substring(prefixLength);
              Excerpt e = createExcerpt(property, relPath, hit.getRow(), maxLength);
              if (e == null) {
                return;
              }
              if (e.hasHighlights) {
                excerpt.clear();
                excerpt.add(e);
                throw new RepositoryException();
              } else if (excerpt.size() == 0) {
                excerpt.add(e);
              }
            }
          });
    } catch (RepositoryException e) {
      if (excerpt.size() == 0) {
        throw e;
      }
      // otherwise the exception was thrown to
      // terminate the traversal
    }
    if (excerpt.size() == 0) {
      // no suitable excerpt found
      return new Excerpt("");
    } else {
      return excerpt.get(0);
    }
  }
 @Override
 protected Node doExecute(Node node) throws Exception {
   String newName = "folder";
   do {
     newName += random.nextInt(10);
   } while (node.hasNode(newName));
   String absPath =
       context.getFolderWorkflow(node).add("new-file-folder", "asset gallery", newName);
   node.getSession().refresh(false);
   return node.getSession().getNode(absPath);
 }
Esempio n. 30
0
 /** get collection node in user home. creates if not found */
 private Node getCollectionHome(Session userSession) throws RepositoryException {
   User user = userResolver.resolveUser(userSession);
   Node userHome = userSession.getNode(user.getHomePath());
   Node collHome = null;
   if (!userHome.hasNode(COLLECTIONS)) {
     collHome = userHome.addNode(COLLECTIONS);
   } else {
     collHome = userHome.getNode(COLLECTIONS);
   }
   return collHome;
 }