/**
   * 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);
    }
  }
  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;
  }
 /**
  * This method will re-observer all nodes that have been ever observed with all repositories.
  *
  * @throws Exception
  */
 private void reInitObserver() throws Exception {
   RepositoryEntry repo = repoService_.getCurrentRepository().getConfiguration();
   ManageableRepository repository = repoService_.getCurrentRepository();
   String[] workspaceNames = repository.getWorkspaceNames();
   for (String workspace : workspaceNames) {
     Session session = repository.getSystemSession(workspace);
     QueryManager queryManager = null;
     try {
       queryManager = session.getWorkspace().getQueryManager();
     } catch (Exception e) {
       if (LOG.isErrorEnabled()) {
         LOG.error("Unexpected error", e);
       }
     }
     if (queryManager == null) {
       session.logout();
       continue;
     }
     try {
       Query query = queryManager.createQuery(WATCHABLE_MIXIN_QUERY, Query.XPATH);
       QueryResult queryResult = query.execute();
       for (NodeIterator iter = queryResult.getNodes(); iter.hasNext(); ) {
         Node observedNode = iter.nextNode();
         EmailNotifyListener emailNotifyListener = new EmailNotifyListener(observedNode);
         ObservationManager manager = session.getWorkspace().getObservationManager();
         List<String> list = getDocumentNodeTypes(observedNode);
         String[] observedNodeTypeNames = list.toArray(new String[list.size()]);
         manager.addEventListener(
             emailNotifyListener,
             Event.PROPERTY_CHANGED,
             observedNode.getPath(),
             true,
             null,
             observedNodeTypeNames,
             false);
       }
       session.logout();
     } catch (Exception e) {
       if (LOG.isWarnEnabled()) {
         LOG.warn(
             "==>>> Cannot init observer for node: "
                 + e.getLocalizedMessage()
                 + " in '"
                 + repo.getName()
                 + "' repository");
       }
       if (LOG.isErrorEnabled()) {
         LOG.error("Unexpected error", e);
       }
     }
   }
 }
  /** Sets up the fixture for the test cases. */
  protected void setUp() throws Exception {
    isReadOnly = true;
    super.setUp();

    session = getHelper().getReadOnlySession();
    manager = session.getWorkspace().getNodeTypeManager();
  }
  @Override
  public Node getNodeVersion(final String label) {
    try {
      final Session session = getSession();

      final Node n = getFrozenNode(label);

      if (n != null) {
        return n;
      }

      if (isVersioned()) {
        final VersionHistory hist =
            session.getWorkspace().getVersionManager().getVersionHistory(getPath());

        if (hist.hasVersionLabel(label)) {
          LOGGER.debug("Found version for {} by label {}.", this, label);
          return hist.getVersionByLabel(label).getFrozenNode();
        }
      }

      LOGGER.warn("Unknown version {} with label or uuid {}!", this, label);
      return null;
    } catch (final RepositoryException e) {
      throw new RepositoryRuntimeException(e);
    }
  }
  public static void main(String[] argv) {

    // Create and start the engine ...
    ModeShapeEngine engine = new ModeShapeEngine();
    engine.start();

    // Load the configuration for a repository via the classloader (can also use path to a file)...
    Repository repository = null;
    String repositoryName = null;
    try {
      URL url = ModeShapeExample.class.getClassLoader().getResource("my-repository-config.json");
      RepositoryConfiguration config = RepositoryConfiguration.read(url);

      // We could change the name of the repository programmatically ...
      // config = config.withName("Some Other Repository");

      // Verify the configuration for the repository ...
      Problems problems = config.validate();
      if (problems.hasErrors()) {
        System.err.println("Problems starting the engine.");
        System.err.println(problems);
        System.exit(-1);
      }

      // Deploy the repository ...
      repository = engine.deploy(config);
      repositoryName = config.getName();
    } catch (Throwable e) {
      e.printStackTrace();
      System.exit(-1);
      return;
    }

    Session session = null;
    try {
      // Get the repository
      repository = engine.getRepository(repositoryName);

      // Create a session ...
      session = repository.login("default");

      // Get the root node ...
      Node root = session.getRootNode();
      assert root != null;

      System.out.println(
          "Found the root node in the \"" + session.getWorkspace().getName() + "\" workspace");
    } catch (RepositoryException e) {
      e.printStackTrace();
    } finally {
      if (session != null) session.logout();
      System.out.println("Shutting down engine ...");
      try {
        engine.shutdown().get();
        System.out.println("Success!");
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
 /**
  * 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;
 }
  /**
   * Tests if the remapping of jcr:primaryType to a different prefix works and returns the property
   * with the correct primaryType value.
   */
  public void testNamespaceRemapping() throws RepositoryException {
    Property primaryTypeProp = session.getRootNode().getProperty(jcrPrimaryType);
    NodeType ntBaseType = session.getWorkspace().getNodeTypeManager().getNodeType(ntBase);

    // find an unused prefix
    String jcrPrefix = getUnusedPrefix();
    // remap jcr prefix
    session.setNamespacePrefix(jcrPrefix, NS_JCR_URI);
    // find an unused prefix
    String ntPrefix = getUnusedPrefix();
    // remap nt prefix
    session.setNamespacePrefix(ntPrefix, NS_NT_URI);

    assertTrue(
        "Unable to retrieve property with new namespace prefix.",
        session.getRootNode().getProperty(jcrPrefix + ":primaryType").isSame(primaryTypeProp));

    assertEquals(
        "NodeType name does not use new namespace prefix.",
        ntBaseType.getName(),
        ntPrefix + ":base");

    String propval = session.getRootNode().getProperty(jcrPrefix + ":primaryType").getString();
    String primaryType = session.getRootNode().getPrimaryNodeType().getName();
    assertEquals("Remapping of jcr prefix failed", primaryType, propval);
  }
  /** TODO: Not fully implemented SEE: DirectSearchModule.getKeywordMapLive() */
  public static synchronized void refreshUserDocKeywords(Session session)
      throws RepositoryException {
    log.info("refreshUserDocKeywords({})", session);
    String statement = "/jcr:root/" + Repository.ROOT + "/element(*,okm:document)";

    try {
      Workspace workspace = session.getWorkspace();
      QueryManager queryManager = workspace.getQueryManager();
      Query query = queryManager.createQuery(statement, Query.XPATH);
      javax.jcr.query.QueryResult qResult = query.execute();
      Map<String, Set<String>> userDocKeywords = new HashMap<String, Set<String>>();

      for (NodeIterator nit = qResult.getNodes(); nit.hasNext(); ) {
        Node docNode = nit.nextNode();
        Value[] keywords = docNode.getProperty(Property.KEYWORDS).getValues();
        Set<String> keywordSet = new HashSet<String>();

        for (int i = 0; i < keywords.length; i++) {
          keywordSet.add(keywords[i].getString());
        }

        userDocKeywords.put(docNode.getUUID(), keywordSet);
      }

      // userDocumentKeywordsMgr.put(session.getUserID(), userDocKeywords);
    } catch (javax.jcr.RepositoryException e) {
      log.error(e.getMessage(), e);
      throw new RepositoryException(e.getMessage(), e);
    }

    log.info("refreshUserDocKeywords: void");
  }
  @Override
  public List<ModelResource> search(String queryExpression) {
    if (queryExpression == null || queryExpression.isEmpty()) {
      queryExpression = "*";
    }

    try {
      List<ModelResource> modelResources = new ArrayList<>();
      QueryManager queryManager = session.getWorkspace().getQueryManager();
      Query query =
          queryManager.createQuery(
              queryExpression, org.modeshape.jcr.api.query.Query.FULL_TEXT_SEARCH);
      logger.debug("Searching repository with expression " + query.getStatement());
      QueryResult result = query.execute();
      RowIterator rowIterator = result.getRows();

      while (rowIterator.hasNext()) {
        Row row = rowIterator.nextRow();
        Node currentNode = row.getNode();
        if (currentNode.hasProperty("vorto:type") && !isMappingNode(currentNode)) {
          modelResources.add(createModelResource(currentNode));
        }
      }

      return modelResources;
    } catch (RepositoryException e) {
      throw new RuntimeException("Could not create query manager", e);
    }
  }
  @Before
  public void setup() throws RepositoryException {
    initMocks(this);

    when(mockSession.getWorkspace()).thenReturn(mockWorkspace);
    when(mockWorkspace.getNamespaceRegistry()).thenReturn(mockNamespaceRegistry);
    when(mockNamespaceRegistry.getPrefixes()).thenReturn(new String[] {});

    testData.session(mockSession);
    testData.topic(createURI("test:subject"));
    testData.concat(
        new Triple(
            createURI("test:subject"), createURI("test:predicate"), createLiteral("test:object")));
    testData.concat(
        new Triple(
            createURI("test:subject"),
            createURI(getRDFNamespaceForJcrNamespace(JCR_NAMESPACE) + "primaryType"),
            createLiteral("nt:file")));

    testData2.session(mockSession);
    testData2.topic(createURI("test:subject2"));
    testData2.concat(
        new Triple(
            createURI("test:subject2"),
            createURI(getRDFNamespaceForJcrNamespace(JCR_NAMESPACE) + "mixinTypes"),
            createLiteral("childOf:ntFile")));
    final UriInfo info = Mockito.mock(UriInfo.class);
    setField(testProvider, "uriInfo", info);
  }
  @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);
    }
  }
 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);
   }
 }
 @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);
   }
 }
  /** 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.");
    }
  }
  /**
   * 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
    }
  }
  @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;
  }
  private void purgeHistory(Node fileNode, Session session, PentahoJcrConstants pentahoJcrConstants)
      throws RepositoryException {
    // Delete all previous versions of this node
    VersionManager versionManager = session.getWorkspace().getVersionManager();
    if (JcrRepositoryFileUtils.isPentahoFolder(pentahoJcrConstants, fileNode)) {
      // go down to children
      NodeIterator nodes = fileNode.getNodes();
      while (nodes.hasNext()) {
        Node next = (Node) nodes.next();
        purgeHistory(next, session, pentahoJcrConstants);
      }
    } else if (JcrRepositoryFileUtils.isPentahoFile(pentahoJcrConstants, fileNode)
        && fileNode.isNodeType(pentahoJcrConstants.getPHO_MIX_VERSIONABLE())) {
      VersionHistory versionHistory = versionManager.getVersionHistory(fileNode.getPath());

      VersionIterator allVersions = versionHistory.getAllVersions();
      while (allVersions.hasNext()) {
        Version next = (Version) allVersions.next();
        String name = next.getName();
        // Root version cannot be deleted, the remove below will take care of that.
        if (!JCR_ROOT_VERSION.equals(name)) {
          versionHistory.removeVersion(name);
        }
      }
    }
  }
Beispiel #19
0
  public String getFileURL(String path) throws Exception {
    WebuiRequestContext context = WebuiRequestContext.getCurrentInstance();
    if (!(context instanceof PortalRequestContext)) {
      context = (WebuiRequestContext) context.getParentAppRequestContext();
    }
    String portalName = getPortalName();
    String requestURL = ((PortalRequestContext) context).getRequest().getRequestURL().toString();
    String domainURL = requestURL.substring(0, requestURL.indexOf(portalName));
    Session session = getCurrentSession();
    String workspace = session.getWorkspace().getName();
    String repository =
        ((ManageableRepository) session.getRepository()).getConfiguration().getName();

    String url =
        domainURL
            + portalName
            + "/"
            + PortalContainer.getCurrentRestContextName()
            + "/jcr/"
            + repository
            + "/"
            + workspace
            + path;
    return url;
  }
  /**
   * {@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.");
    }
  }
Beispiel #21
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);
    }
  }
 @Before
 public void setUp() throws RepositoryException {
   initMocks(this);
   testProvider.registerMimeTypes();
   when(mockSession.getWorkspace()).thenReturn(mockWorkspace);
   when(mockWorkspace.getNamespaceRegistry()).thenReturn(mockNamespaceRegistry);
   when(mockNamespaceRegistry.getPrefixes()).thenReturn(new String[] {});
 }
 /**
  * Tests it the statement returned by {@link Query#getStatement()} is equal to the one passed in
  * createQuery().
  */
 public void testGetStatement() throws RepositoryException {
   String statement = "/" + jcrRoot + "/foo";
   Query q = session.getWorkspace().getQueryManager().createQuery(statement, Query.XPATH);
   assertEquals(
       "Statement returned by Query.getStatement() is not equal to the initial statement.",
       statement,
       q.getStatement());
 }
Beispiel #24
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);
    }
  }
  private List<Node> getLastEditedNode(String noOfItem, String showGadgetWs) throws Exception {
    if (showGadgetWs != null && showGadgetWs.length() > 0) {
      show_gadget = Boolean.parseBoolean(showGadgetWs);
    }
    ArrayList<Node> lstNode = new ArrayList<Node>();
    StringBuffer bf = new StringBuffer(1024);
    List<String> lstNodeType = templateService.getDocumentTemplates();
    if (lstNodeType != null) {
      for (String nodeType : lstNodeType) {
        bf.append("(")
            .append(JCR_PRIMARYTYPE)
            .append("=")
            .append("'")
            .append(nodeType)
            .append("'")
            .append(")")
            .append(" OR ");
      }
    }

    if (bf.length() == 1) return null;
    bf.delete(bf.lastIndexOf("OR") - 1, bf.length());
    if (noOfItem == null || noOfItem.trim().length() == 0) noOfItem = String.valueOf(NO_PER_PAGE);
    String queryStatement = StringUtils.replace(QUERY_STATEMENT, "$0", NT_BASE);
    queryStatement = StringUtils.replace(queryStatement, "$1", bf.toString());
    queryStatement = StringUtils.replace(queryStatement, "$2", DATE_MODIFIED);
    ManageableRepository manageableRepository = repositoryService.getCurrentRepository();
    try {
      String[] workspaces = manageableRepository.getWorkspaceNames();
      List<String> lstWorkspace = new ArrayList<String>();
      // Arrays.asList() return fixed size list;
      lstWorkspace.addAll(Arrays.asList(workspaces));
      if (!show_gadget && lstWorkspace.contains(GADGET)) {
        lstWorkspace.remove(GADGET);
      }
      SessionProvider provider = WCMCoreUtils.createAnonimProvider();
      QueryImpl query = null;
      Session session = null;
      QueryResult queryResult = null;
      QueryManager queryManager = null;
      for (String workspace : lstWorkspace) {
        session = provider.getSession(workspace, manageableRepository);
        queryManager = session.getWorkspace().getQueryManager();
        query = (QueryImpl) queryManager.createQuery(queryStatement, Query.SQL);
        query.setLimit(Integer.parseInt(noOfItem));
        query.setOffset(0);
        queryResult = query.execute();
        puttoList(lstNode, queryResult.getNodes());
        session.logout();
      }
    } catch (RepositoryException e) {
      if (LOG.isErrorEnabled()) {
        LOG.error("Exception when execute SQL " + queryStatement, e);
      }
    }
    return lstNode;
  }
 /**
  * This method will observes the specification node by giving the following param : listener, node
  * Its add an event listener to this node to observes anything that changes to this
  *
  * @param node Specify the node to observe
  * @param listener The object of EventListener
  * @see EventListener
  * @see Node
  * @throws Exception
  */
 private void observeNode(Node node, EventListener listener) throws Exception {
   String workspace = node.getSession().getWorkspace().getName();
   Session systemSession = repoService_.getCurrentRepository().getSystemSession(workspace);
   List<String> list = getDocumentNodeTypes(node);
   String[] observedNodeTypeNames = list.toArray(new String[list.size()]);
   ObservationManager observationManager = systemSession.getWorkspace().getObservationManager();
   observationManager.addEventListener(
       listener, Event.PROPERTY_CHANGED, node.getPath(), true, null, observedNodeTypeNames, false);
   systemSession.logout();
 }
  @Test
  public void ferrari_can_be_versioned() throws RepositoryException {
    Node ferrari = session.getNode("/cars/ferrari");
    VersionManager vm = session.getWorkspace().getVersionManager();

    Version base = vm.getBaseVersion(ferrari.getPath());
    assertThat(base, notNullValue());
    VersionHistory history = vm.getVersionHistory(ferrari.getPath());
    assertThat(history, notNullValue());
  }
Beispiel #28
0
  /**
   * Get the property name for an RDF predicate
   *
   * @param predicate
   * @param namespaceMapping
   * @return
   * @throws RepositoryException
   */
  public String getPropertyNameFromPredicate(
      final com.hp.hpl.jena.rdf.model.Property predicate,
      final Map<String, String> namespaceMapping)
      throws RepositoryException {

    final NamespaceRegistry namespaceRegistry =
        (org.modeshape.jcr.api.NamespaceRegistry) session.getWorkspace().getNamespaceRegistry();

    return getPropertyNameFromPredicate(namespaceRegistry, predicate, namespaceMapping);
  }
  /**
   * This method registers the listener <code> org.apache.jackrabbit.demo.blog.model.AlertManager
   * </code> with the default workspace. This listener listens to events of adding new comments to
   * blog entries.
   *
   * @throws RepositoryException if an error occur in the repository
   */
  private void registerListeners() throws RepositoryException {

    Workspace ws = session.getWorkspace();
    ObservationManager observationMgr = ws.getObservationManager();
    AlertManager alertMgr = new AlertManager(repository);
    observationMgr.addEventListener(
        alertMgr, Event.NODE_ADDED, "/blogRoot", true, null, null, false);

    log("JACKRABBIT-JCR-DEMO: Listeners registered ...");
  }
  /**
   * Creates a {@link Query} for the given statement in the requested language, treating optional
   * languages gracefully
   *
   * @throws RepositoryException
   */
  protected Query createQuery(Session session, String statement, String language)
      throws RepositoryException, NotExecutableException {
    log.println("Creating query: " + statement);

    // check for unsupported query languages early
    if (!isSupportedLanguage(language) && !Query.JCR_SQL2.equals(language)) {
      throw new NotExecutableException("Repository does not support " + language + " query syntax");
    } else {
      return session.getWorkspace().getQueryManager().createQuery(statement, language);
    }
  }