/**
   * Registors the custome node types for the jackrabbit-jcr-demo application from a given CND file.
   * Location of the CND file is given as an initial parameter
   *
   * @throws ServletException is thrown when registration not possible.
   */
  private void registerCustomNodeTypes() throws ServletException {

    // location of the CND file is kept as a servelt init parameter in the web.xml
    String cndPath = getInitParameter("cnd.path");
    String ocmPath = getInitParameter("ocm.path");

    try {

      Workspace ws = session.getWorkspace();

      NodeTypeManagerImpl ntTypeMgr = (NodeTypeManagerImpl) ws.getNodeTypeManager();

      // Registors the custom node types and namespaces
      InputStream inputStream = getServletContext().getResourceAsStream(cndPath);
      ntTypeMgr.registerNodeTypes(inputStream, JackrabbitNodeTypeManager.TEXT_X_JCR_CND, true);

      InputStream nodeTypeStream = getServletContext().getResourceAsStream(ocmPath);
      ntTypeMgr.registerNodeTypes(nodeTypeStream, JackrabbitNodeTypeManager.TEXT_XML, true);

      // Register a namespace to be used with in the program
      // ex. for a username "nandana" we can use demo:nandana
      NamespaceRegistryImpl nsReg =
          (NamespaceRegistryImpl) session.getWorkspace().getNamespaceRegistry();
      nsReg.safeRegisterNamespace("demo", "http://code.google.com/p/jackrabbit-jcr-demo");
      nsReg.safeRegisterNamespace("ocm", "http://jackrabbit.apache.org/ocm");

      log("JACKRABBIT-JCR-DEMO: Custom Node types registered  ...");

    } catch (RepositoryException e) {
      throw new ServletException("Failed to registor node types", e);
    } catch (IOException e) {
      throw new ServletException("Error occured while accessing the file" + cndPath, e);
    }
  }
  @Override
  protected void internalStore(Mail mail) throws MessagingException, IOException {
    try {
      Session session = login();
      try {
        String name = Text.escapeIllegalJcrChars(mail.getName());
        final String xpath = "/jcr:root/" + MAIL_PATH + "//element(" + name + ",james:mail)";

        QueryManager manager = session.getWorkspace().getQueryManager();
        @SuppressWarnings("deprecation")
        Query query = manager.createQuery(xpath, Query.XPATH);
        NodeIterator iterator = query.execute().getNodes();

        if (iterator.hasNext()) {
          while (iterator.hasNext()) {
            setMail(iterator.nextNode(), mail);
          }
        } else {
          Node parent = session.getRootNode().getNode(MAIL_PATH);
          Node node = parent.addNode(name, "james:mail");
          Node resource = node.addNode("jcr:content", "nt:resource");
          resource.setProperty("jcr:mimeType", "message/rfc822");
          setMail(node, mail);
        }
        session.save();
        logger.info("Mail " + mail.getName() + " stored in repository");
      } finally {
        session.logout();
      }
    } catch (IOException e) {
      throw new MessagingException("Unable to store message: " + mail.getName(), e);
    } catch (RepositoryException e) {
      throw new MessagingException("Unable to store message: " + mail.getName(), e);
    }
  }
 private Node populateCache(HtmlLibrary library, String root, Session session) {
   Node cacheNode = null;
   try {
     String libPath = (new StringBuilder(CACHE_PATH).append(library.getPath(false))).toString();
     Node src = JcrUtils.getNodeIfExists(libPath, session);
     cacheNode = session.getNode(root);
     if (null != src) {
       // this.lock.readLock().lock();
       // produced closure compiled src
       String compiled = compile(library, this.optimization, JcrUtils.readFile(src));
       // this.lock.readLock().unlock();
       // this.lock.writeLock().lock();
       //
       JcrUtils.putFile(
           cacheNode.getParent(),
           getLibraryName(library),
           library.getType().contentType,
           IOUtils.toInputStream(compiled, "UTF-8"));
       session.save();
       // this.lock.writeLock().unlock();
     }
   } catch (RepositoryException re) {
     log.debug(re.getMessage());
   } catch (IOException ioe) {
     log.debug(ioe.getMessage());
   }
   return cacheNode;
 }
 public void updateFolderAllowed(String path) {
   UIFormSelectBox sltWorkspace = getChildById(UIDriveInputSet.FIELD_WORKSPACE);
   String strWorkspace = sltWorkspace.getSelectedValues()[0];
   SessionProvider sessionProvider = WCMCoreUtils.getSystemSessionProvider();
   try {
     Session session =
         sessionProvider.getSession(
             strWorkspace,
             getApplicationComponent(RepositoryService.class).getCurrentRepository());
     Node rootNode = (Node) session.getItem(path);
     List<SelectItemOption<String>> foldertypeOptions = new ArrayList<SelectItemOption<String>>();
     RequestContext context = RequestContext.getCurrentInstance();
     ResourceBundle res = context.getApplicationResourceBundle();
     for (String foldertype : setFoldertypes) {
       if (isChildNodePrimaryTypeAllowed(rootNode, foldertype)) {
         try {
           foldertypeOptions.add(
               new SelectItemOption<String>(
                   res.getString(getId() + ".label." + foldertype.replace(":", "_")), foldertype));
         } catch (MissingResourceException mre) {
           foldertypeOptions.add(new SelectItemOption<String>(foldertype, foldertype));
         }
       }
     }
     Collections.sort(foldertypeOptions, new ItemOptionNameComparator());
     getUIFormSelectBox(FIELD_ALLOW_CREATE_FOLDERS).setOptions(foldertypeOptions);
   } catch (Exception e) {
     if (LOG.isErrorEnabled()) {
       LOG.error("Unexpected problem occurs while updating", e);
     }
   }
 }
 public Mail retrieve(String key) throws MessagingException {
   try {
     Session session = login();
     try {
       String name = toSafeName(key);
       QueryManager manager = session.getWorkspace().getQueryManager();
       @SuppressWarnings("deprecation")
       Query query =
           manager.createQuery(
               "/jcr:root/" + MAIL_PATH + "//element(" + name + ",james:mail)", Query.XPATH);
       NodeIterator iterator = query.execute().getNodes();
       if (iterator.hasNext()) {
         return getMail(iterator.nextNode());
       } else {
         return null;
       }
     } finally {
       session.logout();
     }
   } catch (IOException e) {
     throw new MessagingException("Unable to retrieve message: " + key, e);
   } catch (RepositoryException e) {
     throw new MessagingException("Unable to retrieve message: " + key, e);
   }
 }
  /** {@inheritDoc} */
  public void undeleteFile(
      final Session session,
      final PentahoJcrConstants pentahoJcrConstants,
      final Serializable fileId)
      throws RepositoryException {
    Node fileToUndeleteNode = session.getNodeByIdentifier(fileId.toString());
    String trashFileIdNodePath = fileToUndeleteNode.getParent().getPath();
    String origParentFolderPath =
        getOriginalParentFolderPath(session, pentahoJcrConstants, fileToUndeleteNode, false);

    String absDestPath =
        origParentFolderPath + RepositoryFile.SEPARATOR + fileToUndeleteNode.getName();

    if (session.itemExists(absDestPath)) {
      RepositoryFile file =
          JcrRepositoryFileUtils.nodeToFile(
              session,
              pentahoJcrConstants,
              pathConversionHelper,
              lockHelper,
              (Node) session.getItem(absDestPath));
      throw new RepositoryFileDaoFileExistsException(file);
    }

    session.move(fileToUndeleteNode.getPath(), absDestPath);
    session.getItem(trashFileIdNodePath).remove();
  }
  /**
   * Tests if restoring the <code>Version</code> of an existing node throws an <code>
   * ItemExistsException</code> if removeExisting is set to FALSE.
   */
  public void testWorkspaceRestoreWithUUIDConflictJcr2()
      throws RepositoryException, NotExecutableException {
    try {
      // Verify that nodes used for the test are indeed versionable
      NodeDefinition nd = wVersionableNode.getDefinition();
      if (nd.getOnParentVersion() != OnParentVersionAction.COPY
          && nd.getOnParentVersion() != OnParentVersionAction.VERSION) {
        throw new NotExecutableException("Nodes must be versionable in order to run this test.");
      }

      VersionManager versionManager =
          wVersionableNode.getSession().getWorkspace().getVersionManager();
      String path = wVersionableNode.getPath();
      Version v = versionManager.checkin(path);
      versionManager.checkout(path);
      wSuperuser.move(
          wVersionableChildNode.getPath(),
          wVersionableNode2.getPath() + "/" + wVersionableChildNode.getName());
      wSuperuser.save();
      wSuperuser.getWorkspace().getVersionManager().restore(new Version[] {v}, false);

      fail(
          "Node.restore( Version, boolean ): An ItemExistsException must be thrown if the node to be restored already exsits and removeExisting was set to false.");
    } catch (ItemExistsException e) {
      // success
    }
  }
示例#8
0
  public AbstractPageList<ResultNode> searchPageContents(
      SessionProvider sessionProvider,
      QueryCriteria queryCriteria,
      int pageSize,
      boolean isSearchContent)
      throws Exception {
    ManageableRepository currentRepository = repositoryService.getCurrentRepository();
    Session session = sessionProvider.getSession("portal-system", currentRepository);
    QueryManager queryManager = session.getWorkspace().getQueryManager();
    long startTime = System.currentTimeMillis();
    Query query = createSearchPageQuery(queryCriteria, queryManager);
    String suggestion = getSpellSuggestion(queryCriteria.getKeyword(), currentRepository);
    if (LOG.isDebugEnabled()) {
      LOG.debug("execute query: " + query.getStatement().toLowerCase());
    }
    AbstractPageList<ResultNode> pageList =
        PageListFactory.createPageList(
            query.getStatement(),
            session.getWorkspace().getName(),
            query.getLanguage(),
            true,
            new PageNodeFilter(),
            new PageDataCreator(),
            pageSize,
            0);

    long queryTime = System.currentTimeMillis() - startTime;
    pageList.setQueryTime(queryTime);
    pageList.setSpellSuggestion(suggestion);
    return pageList;
  }
示例#9
0
 /**
  * Gets the spell suggestion.
  *
  * @param checkingWord the checking word
  * @param manageableRepository the manageable repository
  * @return the spell suggestion
  * @throws Exception the exception
  */
 private String getSpellSuggestion(String checkingWord, ManageableRepository manageableRepository)
     throws Exception {
   // Retrieve spell suggestion in special way to avoid access denied exception
   String suggestion = null;
   Session session = null;
   try {
     session =
         manageableRepository.getSystemSession(
             manageableRepository.getConfiguration().getDefaultWorkspaceName());
     QueryManager queryManager = session.getWorkspace().getQueryManager();
     Query query =
         queryManager.createQuery(
             "SELECT rep:spellcheck() FROM nt:base WHERE jcr:path like '/' AND SPELLCHECK('"
                 + checkingWord
                 + "')",
             Query.SQL);
     RowIterator rows = query.execute().getRows();
     Value value = rows.nextRow().getValue("rep:spellcheck()");
     if (value != null) {
       suggestion = value.getString();
     }
   } catch (Exception e) {
     if (LOG.isWarnEnabled()) {
       LOG.warn(e.getMessage());
     }
   } finally {
     if (session != null) session.logout();
   }
   return suggestion;
 }
  /**
   * {@inheritDoc}
   *
   * @see
   *     org.sakaiproject.nakamura.api.search.SearchResultProcessor#getSearchResultSet(org.apache.sling.api.SlingHttpServletRequest,
   *     javax.jcr.query.Query)
   */
  public SearchResultSet getSearchResultSet(SlingHttpServletRequest request, Query query)
      throws SearchException {
    try {
      // Perform the query
      QueryResult qr = query.execute();
      RowIterator iterator = qr.getRows();

      // Do another query to get the files.
      Session session = request.getResourceResolver().adaptTo(Session.class);
      QueryManager qm = session.getWorkspace().getQueryManager();
      String statement =
          "//element(*, sakai:site)//*[@sling:resourceType='sakai/link']/jcr:deref(@jcr:reference, '*')[jcr:contains(.,'*u*')]";
      Query q = qm.createQuery(statement, Query.XPATH);
      QueryResult filesQueryResult = q.execute();
      RowIterator filesIterator = filesQueryResult.getRows();

      MergedRowIterator mergedIterator = new MergedRowIterator(iterator, filesIterator);

      long siteHits = SearchUtil.getHits(qr);
      long filesHits = SearchUtil.getHits(filesQueryResult);
      long totalHits = siteHits + filesHits;

      return new AbstractSearchResultSet(mergedIterator, totalHits);

    } catch (RepositoryException e) {
      throw new SearchException(500, "Unable to do files query.");
    }
  }
示例#11
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;
  }
  private boolean removeNode(String path) {

    Resource templateResource = resourceResolver.getResource(path);
    if (templateResource != null) {
      Node nodeToDelete = templateResource.adaptTo(Node.class);

      if (nodeToDelete != null) {
        try {
          nodeToDelete.remove();
          TemplateUtils.saveNode(nodeToDelete);
          session.save();
          return true;
        } catch (VersionException ex) {
          java.util.logging.Logger.getLogger(TemplateManagerDeleteServlet.class.getName())
              .log(Level.SEVERE, null, ex);
        } catch (LockException ex) {
          java.util.logging.Logger.getLogger(TemplateManagerDeleteServlet.class.getName())
              .log(Level.SEVERE, null, ex);
        } catch (ConstraintViolationException ex) {
          java.util.logging.Logger.getLogger(TemplateManagerDeleteServlet.class.getName())
              .log(Level.SEVERE, null, ex);
        } catch (AccessDeniedException ex) {
          java.util.logging.Logger.getLogger(TemplateManagerDeleteServlet.class.getName())
              .log(Level.SEVERE, null, ex);
        } catch (RepositoryException ex) {
          java.util.logging.Logger.getLogger(TemplateManagerDeleteServlet.class.getName())
              .log(Level.SEVERE, null, ex);
        } finally {
          session.logout();
        }
      }
    }
    return false;
  }
  public void writeNodes(
      SlingHttpServletRequest request,
      JSONWriter write,
      Aggregator aggregator,
      RowIterator iterator)
      throws JSONException, RepositoryException {

    Session session = request.getResourceResolver().adaptTo(Session.class);

    // TODO Get size from somewhere else.
    long total = iterator.getSize();
    long start = SearchUtil.getPaging(request, total);

    iterator.skip(start);

    for (long i = 0; i < start && iterator.hasNext(); i++) {
      Row row = iterator.nextRow();
      String path = row.getValue("jcr:path").getString();
      Node node = (Node) session.getItem(path);
      if (aggregator != null) {
        aggregator.add(node);
      }
      ExtendedJSONWriter.writeNodeToWriter(write, node);
    }
  }
示例#14
0
  @Test
  public void testWrapper() throws Exception {
    Connection conn = getConnection();

    assertTrue(conn.isWrapperFor(JcrConnection.class));

    try {
      conn.isWrapperFor(null);
      fail();
    } catch (IllegalArgumentException ignore) {
    }

    assertFalse(conn.isWrapperFor(Session.class));

    JcrConnection jcrConn = conn.unwrap(JcrConnection.class);
    Session jcrSession = jcrConn.getSession();
    assertNotNull(jcrSession);
    assertTrue(jcrSession.isLive());

    try {
      conn.unwrap(null);
      fail();
    } catch (IllegalArgumentException ignore) {
    }

    try {
      conn.unwrap(Session.class);
      fail();
    } catch (SQLException ignore) {
    }

    conn.close();
  }
示例#15
0
  @Override
  public ImportantFile[] listFiles(String path) {
    ArrayList<ImportantFile> importantFiles = new ArrayList<ImportantFile>();
    try {
      NodeIterator itr = session.getRootNode().getNodes();
      if (path != null && !path.equals("")) {
        itr = session.getNode(path).getNodes();
      }

      while (itr.hasNext()) {
        Node currentNode = itr.nextNode();
        if (!isNodeVisible(currentNode)) {
          continue;
        }
        ImportantFile iF = new ImportantFile(currentNode.getPath(), isNodeFolder(currentNode));
        importantFiles.add(iF);

        //				PropertyIterator pi = currentNode.getProperties("jcr:primaryType");
        //				while (pi.hasNext()) {
        //					Property p = pi.nextProperty();
        //					LOG.debug("name - " + p.getName());
        //					LOG.debug("value - " + p.getValue());
        //				}

      }

    } catch (RepositoryException e) {
      LOG.error(e);
    }
    return importantFiles.toArray(new ImportantFile[importantFiles.size()]);
  }
示例#16
0
  @Override
  public List<String> getEnabledExtensions() throws OKMException {
    List<String> extensions = new ArrayList<String>();
    Session session = null;

    try {
      Profile up = new Profile();
      session = JCRUtils.getSession();
      UserConfig uc = UserConfigDAO.findByPk(session, session.getUserID());
      up = uc.getProfile();
      extensions = new ArrayList<String>(up.getMisc().getExtensions());
    } catch (LoginException e) {
      log.error(e.getMessage(), e);
      throw new OKMException(
          ErrorCode.get(ErrorCode.ORIGIN_OKMGeneralService, ErrorCode.CAUSE_Repository),
          e.getMessage());
    } catch (javax.jcr.RepositoryException e) {
      log.error(e.getMessage(), e);
      throw new OKMException(
          ErrorCode.get(ErrorCode.ORIGIN_OKMGeneralService, ErrorCode.CAUSE_Repository),
          e.getMessage());
    } catch (DatabaseException e) {
      log.warn(e.getMessage(), e);
      throw new OKMException(
          ErrorCode.get(ErrorCode.ORIGIN_OKMGeneralService, ErrorCode.CAUSE_Database),
          e.getMessage());
    } finally {
      JCRUtils.logout(session);
    }

    return extensions;
  }
  /**
   * Returns an internal folder to store all files deleted from a given folder. Provides fast access
   * when searching for files deleted from a given folder.
   */
  private Node legacyGetTrashFolderIdNode(
      final Session session,
      final PentahoJcrConstants pentahoJcrConstants,
      final String origParentFolderPath)
      throws RepositoryException {

    // get folder id
    String folderId = null;
    if (session.itemExists(origParentFolderPath)) {
      folderId = ((Node) session.getItem(origParentFolderPath)).getIdentifier();
    } else {
      throw new RuntimeException(
          Messages.getInstance()
              .getString("DefaultDeleteHelper.ERROR_0001_PATH_NOT_FOUND")); // $NON-NLS-1$
    }

    final String prefix = session.getNamespacePrefix(PentahoJcrConstants.PHO_NS) + ":";
    Node trashInternalFolderNode = getOrCreateTrashInternalFolderNode(session, pentahoJcrConstants);
    if (NodeHelper.hasNode(trashInternalFolderNode, prefix, folderId)) {
      return NodeHelper.getNode(trashInternalFolderNode, prefix, folderId);
    } else {
      // if Trash Structure 1 (legacy) doesn't exist, no need to create it now
      return null;
    }
  }
  public void initDefaultUsers() {
    Session session = null;
    try {
      session = repository.loginAdministrative(null);
      UserManager userManager = AccessControlUtil.getUserManager(session);

      // Apply default user properties from JSON files.
      Pattern fileNamePattern = Pattern.compile("/users/|\\.json");
      @SuppressWarnings("rawtypes")
      Enumeration entriesEnum = bundle.findEntries("users", "*.json", true);
      while (entriesEnum.hasMoreElements()) {
        Object entry = entriesEnum.nextElement();
        URL jsonUrl = new URL(entry.toString());
        String jsonFileName = jsonUrl.getFile();
        String authorizableId = fileNamePattern.matcher(jsonFileName).replaceAll("");
        Authorizable authorizable = userManager.getAuthorizable(authorizableId);
        if (authorizable != null) {
          applyJsonToAuthorizable(jsonUrl, authorizable, session);
          LOGGER.info("Initialized default authorizable {}", authorizableId);
        } else {
          LOGGER.warn("Configured default authorizable {} not found", authorizableId);
        }
      }
    } catch (RepositoryException e) {
      LOGGER.error("Could not configure default authorizables", e);
    } catch (IOException e) {
      LOGGER.error("Could not configure default authorizables", e);
    } finally {
      if (session != null) {
        session.logout();
      }
    }
  }
示例#19
0
  /** Test if the removeExisting-flag removes an existing node in case of uuid conflict. */
  public void testWorkspaceRestoreWithRemoveExistingJcr2()
      throws NotExecutableException, RepositoryException {
    // create version for parentNode of childNode
    superuser
        .getWorkspace()
        .clone(
            workspaceName, wVersionableChildNode.getPath(), wVersionableChildNode.getPath(), false);
    Version parentV =
        versionableNode
            .getSession()
            .getWorkspace()
            .getVersionManager()
            .checkin(versionableNode.getPath());

    // move child node in order to produce the uuid conflict
    String newChildPath = wVersionableNode2.getPath() + "/" + wVersionableChildNode.getName();
    wSuperuser.move(wVersionableChildNode.getPath(), newChildPath);
    wSuperuser.save();

    // restore the parent with removeExisting == true >> moved child node
    // must be removed.
    wSuperuser.getWorkspace().getVersionManager().restore(new Version[] {parentV}, true);
    if (wSuperuser.itemExists(newChildPath)) {
      fail(
          "Workspace.restore(Version[], boolean) with the boolean flag set to true, must remove the existing node in case of Uuid conflict.");
    }
  }
示例#20
0
 @Override
 protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
     throws ServletException, IOException {
   String paramUser = request.getParameter(SiteService.SiteEvent.USER);
   logger.info("Request to add user " + paramUser);
   String paramGroup = "";
   try {
     Node requestedNode = request.getResource().adaptTo(Node.class);
     Value[] authorizables = requestedNode.getProperty("sakai:authorizables").getValues();
     paramGroup = authorizables[1].getString();
     request.setAttribute(JoinRequestConstants.PARAM_SITENODE, requestedNode);
     Session session = slingRepository.loginAdministrative(null);
     UserManager userManager = AccessControlUtil.getUserManager(session);
     Authorizable userAuth = userManager.getAuthorizable(paramUser);
     Group groupAuth = (Group) userManager.getAuthorizable(paramGroup);
     if (siteJoinIsAuthorized(request)) {
       groupAuth.addMember(userAuth);
       logger.info(paramUser + " added as member of group " + paramGroup);
     } else {
       response.sendError(403, "Not authorized to add member to site.");
     }
     if (session.hasPendingChanges()) {
       session.save();
     }
   } catch (Exception e) {
     response.sendError(500, e.getMessage());
   }
 }
  /**
   * 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);
    }
  }
示例#22
0
 /**
  * Test method TaxonomyService.init() Expect: Create system taxonomy tree in dms-system
  *
  * @see {@link # testInit()}
  */
 public void testInit() throws Exception {
   Node systemTreeDef = (Node) dmsSesssion.getItem(definitionPath + "/System");
   Node systemTreeStorage = (Node) dmsSesssion.getItem(storagePath + "/System");
   assertNotNull(systemTreeDef);
   assertNotNull(systemTreeStorage);
   assertEquals(systemTreeStorage, linkManage.getTarget(systemTreeDef, true));
 }
示例#23
0
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");

    String[] prefixes;
    try {
      Session session = (Session) request.getResourceResolver().adaptTo(Session.class);
      prefixes = session.getNamespacePrefixes();
    } catch (RepositoryException re) {
      prefixes = new String[] {""};
    }

    try {
      TidyJSONWriter out = new TidyJSONWriter(response.getWriter());
      out.setTidy("true".equals(request.getParameter(TIDY)));
      out.object();
      out.key("namespaces");
      out.array();
      for (String p : prefixes) {
        out.value(p);
      }
      out.endArray();
      out.endObject();
    } catch (JSONException e) {
      // todo...
    }
  }
示例#24
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);
    }
  }
示例#25
0
 @Override
 protected void internalRemove(String key) throws MessagingException {
   try {
     Session session = login();
     try {
       String name = ISO9075.encode(Text.escapeIllegalJcrChars(key));
       QueryManager manager = session.getWorkspace().getQueryManager();
       @SuppressWarnings("deprecation")
       Query query =
           manager.createQuery(
               "/jcr:root/" + MAIL_PATH + "//element(" + name + ",james:mail)", Query.XPATH);
       NodeIterator nodes = query.execute().getNodes();
       if (nodes.hasNext()) {
         while (nodes.hasNext()) {
           nodes.nextNode().remove();
         }
         session.save();
         logger.info("Mail " + key + " removed from repository");
       } else {
         logger.warn("Mail " + key + " not found");
       }
     } finally {
       session.logout();
     }
   } catch (RepositoryException e) {
     throw new MessagingException("Unable to remove message: " + key, e);
   }
 }
示例#26
0
  @Override
  public ResultSet query(String text, String lang) {
    Session session = (Session) this.getThreadLocalRequest().getSession().getAttribute("session");
    ResultSet rs = new ResultSet();
    try {
      QueryManager qm = session.getWorkspace().getQueryManager();
      Query q = qm.createQuery(text, lang);

      QueryResult qr = q.execute();

      rs.setColumnNames(qr.getColumnNames());
      ArrayList<String[]> rows = new ArrayList();
      RowIterator it = qr.getRows();
      while (it.hasNext()) {
        Row row = it.nextRow();
        String[] list = new String[qr.getColumnNames().length];

        for (int i = 0; i < qr.getColumnNames().length; i++) {
          Value v = row.getValue(qr.getColumnNames()[i]);
          list[i] = v != null ? v.getString() : "null";
        }

        rows.add(list);
      }

      rs.setRows(rows);
    } catch (RepositoryException e) {
      log.log(Level.SEVERE, "Error executing query: " + text, e);
    }
    return rs;
  }
  /** {@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();
      }
    }
  }
  public void testRestoreSNS() throws RepositoryException {
    Session session = getHelper().getSuperuserSession();

    // - Create a node 'a' with nodetype nt:unstructured
    // (defining it's childnodes to show OPV Version behaviour)
    Node node = session.getRootNode().addNode("RestoreSameNameSiblingTest");
    try {
      // - Create a child node 'b'
      node.addNode("test");
      // - Make 'a' versionable (add mixin mix:versionable)
      node.addMixin(mixVersionable);
      session.save();

      // - Checkin/Checkout 'a'
      Version version = node.checkin();
      node.checkout();
      assertEquals(1, node.getNodes("test").getSize());

      // - Restore any version of 'a'
      node.restore(version, true);
      assertEquals(1, node.getNodes("test").getSize());
    } finally {
      node.remove();
      session.save();
      session.logout();
    }
  }
 private Node createEmptyCache(HtmlLibrary library, String root, Session session) {
   Node node = null;
   // this.lock.writeLock().lock();
   try {
     Node swap =
         JcrUtils.getOrCreateByPath(
             root,
             JcrResourceConstants.NT_SLING_FOLDER,
             JcrResourceConstants.NT_SLING_FOLDER,
             session,
             true);
     node = swap.addNode(getLibraryName(library), JcrConstants.NT_FILE);
     swap = node.addNode(JcrConstants.JCR_CONTENT, JcrConstants.NT_RESOURCE);
     swap.setProperty(JcrConstants.JCR_LASTMODIFIED, 0L);
     swap.setProperty(JcrConstants.JCR_MIMETYPE, library.getType().contentType);
     swap.setProperty(
         JcrConstants.JCR_DATA,
         session.getValueFactory().createBinary(new ByteArrayInputStream(new byte[0])));
     session.save();
     // this.lock.writeLock().unlock();
   } catch (RepositoryException re) {
     log.debug(re.getMessage());
   }
   return node;
 }
  private void persistBinaryContent(JcrRepository repository)
      throws RepositoryException, IOException {
    assertNotNull(repository);

    long minimumBinarySize =
        repository.getConfiguration().getBinaryStorage().getMinimumBinarySizeInBytes();
    long binarySize = minimumBinarySize + 1;

    Session session = repository.login();
    InputStream binaryValueStream = null;
    try {
      byte[] content = new byte[(int) binarySize];
      new Random().nextBytes(content);
      JCR_TOOLS.uploadFile(session, "folder/file", new ByteArrayInputStream(content));
      session.save();

      Node nodeWithBinaryContent = session.getNode("/folder/file/jcr:content");
      Binary binaryValue = nodeWithBinaryContent.getProperty("jcr:data").getBinary();
      binaryValueStream = binaryValue.getStream();
      byte[] retrievedContent = IoUtil.readBytes(binaryValueStream);
      assertArrayEquals(content, retrievedContent);
    } finally {
      if (binaryValueStream != null) {
        binaryValueStream.close();
      }
      session.logout();
    }
  }