Ejemplo n.º 1
0
 /**
  * get all book in workspace
  *
  * @return List<Book>
  */
 public List<Book> getAllBook() {
   /* create query string */
   StringBuffer sb = new StringBuffer("Select * from " + BookNodeTypes.EXO_BOOK);
   SessionProvider sProvider = SessionProvider.createSystemProvider();
   try {
     /* create QueryManager from session */
     QueryManager queryManager = getSession(sProvider).getWorkspace().getQueryManager();
     /* create Query object */
     Query query = queryManager.createQuery(sb.toString(), Query.SQL);
     /* execute query and return result to QueryResult */
     QueryResult result = query.execute();
     /* transfer data to NodeIterator */
     NodeIterator nodes = result.getNodes();
     List<Book> books = new ArrayList<Book>();
     while (nodes.hasNext()) {
       Node node = nodes.nextNode();
       books.add(createBookByNode(node));
     }
     return books;
   } catch (RepositoryException re) {
     log.error("Can not find book", re);
     return null;
   } finally {
     sProvider.close();
   }
 }
Ejemplo n.º 2
0
 /**
  * search book by name with like condition(using SQL)
  *
  * @param name The name of book
  * @return List<Book>
  */
 public List<Book> searchBookByNameLikeSQL(String name) {
   /* replace "" sign and - sign */
   name.replaceAll("\"", "\\\"").replaceAll("-", StringUtils.EMPTY);
   /* create query string */
   StringBuffer sb = new StringBuffer("Select * from " + BookNodeTypes.EXO_BOOK);
   sb.append(" where " + BookNodeTypes.EXO_BOOK_NAME + " like '%" + name + "%'");
   SessionProvider sProvider = SessionProvider.createSystemProvider();
   try {
     /* create QueryManager from session */
     QueryManager queryManager = getSession(sProvider).getWorkspace().getQueryManager();
     /* create Query object */
     Query query = queryManager.createQuery(sb.toString(), Query.SQL);
     /* execute query and return result to QueryResult */
     QueryResult result = query.execute();
     /* transfer data to NodeIterator */
     NodeIterator nodes = result.getNodes();
     List<Book> books = new ArrayList<Book>();
     while (nodes.hasNext()) {
       Node node = nodes.nextNode();
       books.add(createBookByNode(node));
     }
     return books;
   } catch (RepositoryException re) {
     log.error("Can not find book", re);
     return null;
   } finally {
     sProvider.close();
   }
 }
Ejemplo n.º 3
0
  protected void performCheck(String statement, String expected) throws RepositoryException {
    QueryManager qm = superuser.getWorkspace().getQueryManager();
    Query query =
        qm.createQuery(
            "/jcr:root[rep:spellcheck('" + statement + "')]/(rep:spellcheck())", Query.XPATH);
    RowIterator rows = query.execute().getRows();
    assertEquals("no results returned", 1, rows.getSize());
    Row r = rows.nextRow();
    Value v = r.getValue("rep:spellcheck()");
    if (statement.equals(expected)) {
      assertNull("must not return a suggestion", v);
    } else {
      assertNotNull("no suggestion returned", v);
      assertEquals("wrong suggestion returned", expected, v.getString());
    }

    query =
        qm.createQuery(
            "select rep:spellcheck() from nt:base where "
                + "jcr:path = '/' and spellcheck('"
                + statement
                + "')",
            Query.SQL);
    rows = query.execute().getRows();
    assertEquals("no results returned", 1, rows.getSize());
    r = rows.nextRow();
    v = r.getValue("rep:spellcheck()");
    if (statement.equals(expected)) {
      assertNull("must not return a suggestion", v);
    } else {
      assertNotNull("no suggestion returned", v);
      assertEquals("wrong suggestion returned", expected, v.getString());
    }
  }
Ejemplo n.º 4
0
  @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);
    }
  }
Ejemplo n.º 5
0
  @Test
  public void testCopiedFacetSelectIsIndexed() throws RepositoryException {
    String[] content = {
      "/test", "nt:unstructured",
      "jcr:mixinTypes", "mix:referenceable",
      "/test/target", "nt:unstructured",
      "jcr:mixinTypes", "mix:referenceable",
      "/test/target/dummy", "nt:unstructured",
      "/test/nav", "hippo:facetselect",
      "hippo:docbase", "/test/target",
      "hippo:facets", null,
      "hippo:modes", null,
      "hippo:values", null,
      "/test/nav2", "hippo:facetselect",
      "hippo:docbase", "/test/target",
      "hippo:facets", null,
      "hippo:modes", null,
      "hippo:values", null
    };
    build(content, session);
    session.save();
    session.refresh(false);

    recurse(session.getNode("/test"));
    JcrUtils.copy(session.getNode("/test/nav"), "mirror", session.getNode("/test"));
    session.save();
    session.refresh(false);

    QueryManager queryManager = session.getWorkspace().getQueryManager();
    Query query = queryManager.createQuery("//element(mirror,hippo:facetselect)", Query.XPATH);
    QueryResult result = query.execute();
    assertTrue(result.getNodes().hasNext());
    assertTrue(result.getNodes().hasNext());
    assertTrue(result.getNodes().hasNext());
  }
Ejemplo n.º 6
0
  /**
   * Executes a the given query string (based on the language information) against a JCR repository,
   * returning a rest model based result.
   *
   * @param request a non-null {@link HttpServletRequest}
   * @param repositoryName a non-null, URL encoded {@link String} representing the name of a
   *     repository
   * @param workspaceName a non-null, URL encoded {@link String} representing the name of a
   *     workspace
   * @param language a non-null String which should be a valid query language, as recognized by the
   *     {@link javax.jcr.query.QueryManager}
   * @param statement a non-null String which should be a valid query string in the above language.
   * @param offset a numeric value which indicates the index in the result set from where results
   *     should be returned.
   * @param limit a numeric value indicating the maximum number of rows to return.
   * @param uriInfo a non-null {@link UriInfo} object which is provided by RestEASY, allowing extra
   *     request parameters to be retrieved.
   * @return a {@link RestQueryHandler} instance
   * @throws RepositoryException if any operation fails at the JCR level
   */
  public RestQueryResult executeQuery(
      HttpServletRequest request,
      String repositoryName,
      String workspaceName,
      String language,
      String statement,
      long offset,
      long limit,
      UriInfo uriInfo)
      throws RepositoryException {
    assert repositoryName != null;
    assert workspaceName != null;
    assert language != null;
    assert statement != null;

    Session session = getSession(request, repositoryName, workspaceName);
    Query query = createQuery(language, statement, session);
    bindExtraVariables(uriInfo, session.getValueFactory(), query);

    QueryResult result = query.execute();
    RestQueryResult restQueryResult = new RestQueryResult();

    String[] columnNames = result.getColumnNames();
    setColumns(result, restQueryResult, columnNames);

    String baseUrl = RestHelper.repositoryUrl(request);

    setRows(offset, limit, session, result, restQueryResult, columnNames, baseUrl);

    return restQueryResult;
  }
Ejemplo n.º 7
0
 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);
   }
 }
Ejemplo n.º 8
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);
   }
 }
Ejemplo n.º 9
0
  @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);
    }
  }
Ejemplo n.º 10
0
  /** 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");
  }
Ejemplo n.º 11
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;
  }
Ejemplo n.º 12
0
 /**
  * get user by name with xpath
  *
  * @param username
  * @return
  */
 public User getUserByNameXPath(String username) {
   username.replaceAll("\"", "\\\"").replaceAll("-", StringUtils.EMPTY);
   username = username.trim();
   SessionProvider sProvider = SessionProvider.createSystemProvider();
   StringBuffer queryString =
       new StringBuffer(
           "//element(*, "
               + BookNodeTypes.EXO_USER
               + ")[(jcr:like(@"
               + BookNodeTypes.EXO_USER_NAME
               + ",'%"
               + username
               + "%'"
               + ") and @"
               + BookNodeTypes.EXO_USER_ADDRESS
               + "='Hanoi'"
               + ")]");
   try {
     QueryManager queryManager = getSession(sProvider).getWorkspace().getQueryManager();
     Query query = queryManager.createQuery(queryString.toString(), Query.XPATH);
     QueryResult result = query.execute();
     NodeIterator nodes = result.getNodes();
     if (nodes.getSize() > 0) {
       Node node = nodes.nextNode();
       PropertyReader reader = new PropertyReader(node);
       return createUserByNode(node);
     }
     return null;
   } catch (RepositoryException re) {
     log.error("Can not get user by name(XPath)", re);
     return null;
   } finally {
     sProvider.close();
   }
 }
Ejemplo n.º 13
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;
 }
Ejemplo n.º 14
0
 /**
  * get user by book name
  *
  * @param bookName
  * @return
  */
 public User getUserByBookQuery(String bookName) {
   bookName.replaceAll("\"", "\\\"").replaceAll("-", StringUtils.EMPTY);
   bookName = bookName.trim();
   SessionProvider sProvider = SessionProvider.createSystemProvider();
   StringBuffer queryString = new StringBuffer("Select * from " + BookNodeTypes.EXO_USER);
   queryString.append(
       " where /"
           + BookNodeTypes.EXO_BOOK
           + "/"
           + BookNodeTypes.EXO_BOOK_NAME
           + "="
           + bookName
           + "'");
   try {
     QueryManager queryManager = getSession(sProvider).getWorkspace().getQueryManager();
     Query query = queryManager.createQuery(queryString.toString(), Query.SQL);
     QueryResult result = query.execute();
     NodeIterator nodes = result.getNodes();
     if (nodes.getSize() > 0) {
       Node node = nodes.nextNode();
       return createUserByNode(node);
     }
     return null;
   } catch (RepositoryException re) {
     log.error("Can not get user by name", re);
     return null;
   } finally {
     sProvider.close();
   }
 }
Ejemplo n.º 15
0
  @Test
  public void shouldNotIndexNotQueryableConnector() throws Exception {
    federationManager.createProjection(
        "/testRoot", "mock-source-non-queryable", MockConnector.DOC2_LOCATION, "federated2");

    Workspace workspace = session.getWorkspace();
    workspace.reindex();

    QueryManager queryManager = workspace.getQueryManager();
    Query query =
        queryManager.createQuery(
            "select * FROM [nt:base] WHERE [jcr:path] LIKE '/testRoot/federated2'", Query.JCR_SQL2);
    assertEquals(0, query.execute().getNodes().getSize());

    query =
        queryManager.createQuery(
            "select * FROM [nt:base] WHERE [jcr:path] LIKE '/testRoot/federated2/federated3'",
            Query.JCR_SQL2);
    assertEquals(0, query.execute().getNodes().getSize());

    Node externalNode = session.getNode("/testRoot/federated2/federated3");
    externalNode.setProperty("test", "a value");
    session.save();

    query =
        queryManager.createQuery(
            "select * FROM [nt:base] as a WHERE a.test='a value'", Query.JCR_SQL2);
    assertEquals(0, query.execute().getNodes().getSize());
  }
Ejemplo n.º 16
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;
  }
  /**
   * {@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.");
    }
  }
Ejemplo n.º 18
0
 /**
  * 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());
 }
Ejemplo n.º 19
0
  /**
   * @see
   *     org.apache.jackrabbit.core.security.authorization.AccessControlProvider#getEffectivePolicies(java.util.Set,
   *     CompiledPermissions)
   */
  public AccessControlPolicy[] getEffectivePolicies(
      Set<Principal> principals, CompiledPermissions permissions) throws RepositoryException {
    String propName = ISO9075.encode(session.getJCRName(P_PRINCIPAL_NAME));

    StringBuilder stmt = new StringBuilder("/jcr:root");
    stmt.append("//element(*,");
    stmt.append(session.getJCRName(NT_REP_ACE));
    stmt.append(")[");
    int i = 0;
    for (Principal principal : principals) {
      if (i > 0) {
        stmt.append(" or ");
      }
      stmt.append("@");
      stmt.append(propName);
      stmt.append("='");
      stmt.append(principal.getName().replaceAll("'", "''"));
      stmt.append("'");
      i++;
    }
    stmt.append("]");

    QueryResult result;
    try {
      QueryManager qm = session.getWorkspace().getQueryManager();
      Query q = qm.createQuery(stmt.toString(), Query.XPATH);
      result = q.execute();
    } catch (RepositoryException e) {
      log.error("Unexpected error while searching effective policies.", e.getMessage());
      throw new UnsupportedOperationException(
          "Retrieve effective policies for set of principals not supported.", e);
    }

    Set<AccessControlPolicy> acls = new LinkedHashSet<AccessControlPolicy>();
    for (NodeIterator it = result.getNodes(); it.hasNext(); ) {
      NodeImpl aclNode = (NodeImpl) it.nextNode().getParent();
      Name aclName = aclNode.getQName();
      NodeImpl accessControlledNode = (NodeImpl) aclNode.getParent();

      if (N_POLICY.equals(aclName) && isAccessControlled(accessControlledNode)) {
        if (permissions.canRead(aclNode.getPrimaryPath(), aclNode.getNodeId())) {
          acls.add(getACL(accessControlledNode, N_POLICY, accessControlledNode.getPath()));
        } else {
          throw new AccessDeniedException(
              "Access denied at " + Text.getRelativeParent(aclNode.getPath(), 1));
        }
      } else if (N_REPO_POLICY.equals(aclName) && isRepoAccessControlled(accessControlledNode)) {
        if (permissions.canRead(aclNode.getPrimaryPath(), aclNode.getNodeId())) {
          acls.add(getACL(accessControlledNode, N_REPO_POLICY, null));
        } else {
          throw new AccessDeniedException(
              "Access denied at " + Text.getRelativeParent(aclNode.getPath(), 1));
        }
      } // else: not a regular policy node -> ignore.
    }

    return acls.toArray(new AccessControlPolicy[acls.size()]);
  }
 private void assertExtractedTextHasNotBeenIndexed(String validationQuery)
     throws RepositoryException {
   Query query =
       jcrSession()
           .getWorkspace()
           .getQueryManager()
           .createQuery(validationQuery, JcrQuery.JCR_SQL2);
   QueryResult result = query.execute();
   assertEquals("Node with text content was found", 0, result.getNodes().getSize());
 }
 /**
  * Tests if {@link Query#getStoredQueryPath()} returns the correct path where the query had been
  * saved.
  */
 public void testGetPersistentQueryPath() throws RepositoryException {
   String statement = "/" + jcrRoot;
   Query q = superuser.getWorkspace().getQueryManager().createQuery(statement, Query.XPATH);
   String path = testRoot + "/" + nodeName1;
   q.storeAsNode(path);
   assertEquals(
       "Query.getPersistentQueryPath() does not return the correct path.",
       path,
       q.getStoredQueryPath());
 }
Ejemplo n.º 22
0
  public void postSave(Membership m, boolean isNew) throws Exception {

    String username = m.getUserName();
    String groupId = m.getGroupId();
    cservice_.addUserContactInAddressBook(username, groupId);
    DataStorage storage_ = new JCRDataStorage(nodeHierarchyCreator_, reposervice_);
    SessionProvider systemSession = SessionProvider.createSystemProvider();
    try {
      String usersPath = nodeHierarchyCreator_.getJcrPath(DataStorage.USERS_PATH);
      Contact contact = cservice_.getPublicContact(username);
      QueryManager qm = getSession(systemSession).getWorkspace().getQueryManager();
      Map<String, String> groups = new LinkedHashMap<String, String>();
      for (String group : contact.getAddressBookIds()) groups.put(group, group);
      groups.put(groupId, groupId);
      contact.setAddressBookIds(groups.keySet().toArray(new String[] {}));
      cservice_.saveContact(username, contact, false);
      StringBuffer queryString =
          new StringBuffer(
                  "/jcr:root"
                      + usersPath
                      + "//element(*,exo:contactGroup)[@exo:viewPermissionGroups='")
              .append(groupId + "']");
      Query query = qm.createQuery(queryString.toString(), Query.XPATH);
      QueryResult result = query.execute();
      NodeIterator nodes = result.getNodes();
      List<String> to = Arrays.asList(new String[] {username});
      while (nodes.hasNext()) {
        Node address = nodes.nextNode();
        String from = address.getProperty("exo:sharedUserId").getString();
        String addressBookId = address.getProperty("exo:id").getString();
        storage_.shareAddressBook(from, addressBookId, to);
      }
      queryString =
          new StringBuffer(
                  "/jcr:root" + usersPath + "//element(*,exo:contact)[@exo:viewPermissionGroups='")
              .append(groupId + "']");
      query = qm.createQuery(queryString.toString(), Query.XPATH);
      result = query.execute();
      nodes = result.getNodes();
      while (nodes.hasNext()) {
        Node contactNode = nodes.nextNode();
        String split = "/";
        String temp = contactNode.getPath().split(usersPath)[1];
        String userId = temp.split(split)[1];
        String[] addressBookIds = new String[] {contactNode.getProperty("exo:id").getString()};
        storage_.shareContact(userId, addressBookIds, to);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      systemSession.close();
    }
  }
 private void queryContentInWorkspace(JcrRepository newRepository, String workspaceName)
     throws RepositoryException {
   JcrSession session = newRepository.login();
   try {
     String statement = "SELECT [car:model], [car:year], [car:msrp] FROM [car:Car] AS car";
     Query query = session.getWorkspace().getQueryManager().createQuery(statement, Query.JCR_SQL2);
     QueryResult results = query.execute();
     assertThat(results.getRows().getSize(), is(13L));
   } finally {
     session.logout();
   }
 }
Ejemplo n.º 24
0
 /**
  * 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);
       }
     }
   }
 }
Ejemplo n.º 25
0
  /** Get keyword map */
  private Map<String, Integer> getKeywordMapLive(String token, List<String> filter)
      throws RepositoryException, DatabaseException {
    log.debug("getKeywordMapLive({}, {})", token, filter);
    String statement =
        "/jcr:root//*[@jcr:primaryType eq 'okm:document' or @jcr:primaryType eq 'okm:mail' or @jcr:primaryType eq 'okm:folder']";
    HashMap<String, Integer> cloud = new HashMap<String, Integer>();
    Session session = null;

    try {
      if (token == null) {
        session = JCRUtils.getSession();
      } else {
        session = JcrSessionManager.getInstance().get(token);
      }

      Workspace workspace = session.getWorkspace();
      QueryManager queryManager = workspace.getQueryManager();
      Query query = queryManager.createQuery(statement, Query.XPATH);
      javax.jcr.query.QueryResult qResult = query.execute();

      for (NodeIterator nit = qResult.getNodes(); nit.hasNext(); ) {
        Node doc = nit.nextNode();
        Value[] keywordsValue = doc.getProperty(com.openkm.bean.Property.KEYWORDS).getValues();
        ArrayList<String> keywordCollection = new ArrayList<String>();

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

        if (filter != null && keywordCollection.containsAll(filter)) {
          for (Iterator<String> it = keywordCollection.iterator(); it.hasNext(); ) {
            String keyword = it.next();

            if (!filter.contains(keyword)) {
              Integer occurs = cloud.get(keyword) != null ? cloud.get(keyword) : 0;
              cloud.put(keyword, occurs + 1);
            }
          }
        }
      }
    } catch (javax.jcr.RepositoryException e) {
      log.error(e.getMessage(), e);
      throw new RepositoryException(e.getMessage(), e);
    } finally {
      if (token == null) JCRUtils.logout(session);
    }

    log.debug("getKeywordMapLive: {}", cloud);
    return cloud;
  }
Ejemplo n.º 26
0
 /**
  * @purpose Check if a query is valid
  * @param workspace
  * @param strQuery
  * @param SQLLanguage
  * @return true as valid query, false as Invalid
  * @author vinh_nguyen from ECMS
  */
 public static boolean checkQuery(String workspace, String strQuery, String SQLLanguage) {
   try {
     Session session =
         WCMCoreUtils.getUserSessionProvider()
             .getSession(
                 workspace,
                 WCMCoreUtils.getService(RepositoryService.class).getCurrentRepository());
     QueryManager qm = session.getWorkspace().getQueryManager();
     Query query = qm.createQuery(strQuery, SQLLanguage);
     query.execute();
   } catch (Exception e) {
     return false;
   }
   return true;
 }
Ejemplo n.º 27
0
 /**
  * check user exist by name
  *
  * @param username
  * @param sProvider
  * @return
  */
 private boolean isExistUserName(String username, SessionProvider sProvider) {
   username.replaceAll("\"", "\\\"").replaceAll("-", StringUtils.EMPTY);
   StringBuffer queryString = new StringBuffer("Select * from " + BookNodeTypes.EXO_USER);
   queryString.append(" where " + BookNodeTypes.EXO_USER_NAME + " = '" + username + "'");
   try {
     QueryManager queryManager = getSession(sProvider).getWorkspace().getQueryManager();
     Query query = queryManager.createQuery(queryString.toString(), Query.SQL);
     QueryResult result = query.execute();
     NodeIterator nodes = result.getNodes();
     return nodes.hasNext();
   } catch (RepositoryException re) {
     log.error("Failed to check exist user name", re);
     return false;
   }
 }
Ejemplo n.º 28
0
  /** Execute query */
  private ResultSet executeQuery(Session session, Query query, int offset, int limit)
      throws RepositoryException {
    log.debug("executeQuery({}, {}, {}, {})", new Object[] {session, query, offset, limit});
    ResultSet rs = new ResultSet();

    try {
      ArrayList<QueryResult> al = new ArrayList<QueryResult>();

      // http://n4.nabble.com/Query-performance-for-large-query-results-td531360.html
      ((QueryImpl) query).setLimit(limit);
      ((QueryImpl) query).setOffset(offset);
      QueryResultImpl result = (QueryResultImpl) query.execute();
      RowIterator rit = result.getRows();
      rs.setTotal(result.getTotalSize());

      while (rit.hasNext()) {
        Row row = rit.nextRow();
        QueryResult qr = queryRowResultDigester(session, row);
        al.add(qr);
      }

      rs.setResults(al);
    } catch (javax.jcr.RepositoryException e) {
      log.error(e.getMessage(), e);
      throw new RepositoryException(e.getMessage(), e);
    }

    log.debug("executeQuery: {}", rs);
    return rs;
  }
Ejemplo n.º 29
0
  private static boolean hasCheckOuts(Node node) throws RepositoryException {
    // Build xpath query of the form
    // '//path/to/node//*[jcr:isCheckedOut='true']'
    String xPath = "/*[jcr:isCheckedOut='true']";
    String path = node.getPath();
    if ("/".equals(path)) {
      path = "";
    }
    xPath = '/' + Util.escape(path) + xPath;

    // Execute query
    QueryManager queryManager = node.getSession().getWorkspace().getQueryManager();
    Query query = queryManager.createQuery(xPath, Query.XPATH);
    QueryResult queryResult = query.execute();
    return queryResult.getNodes().hasNext();
  }
  private NodeIterator getDailyNodes(Node pluginDayNode, String userId) throws Exception {
    final boolean stats =
        NotificationContextFactory.getInstance().getStatistics().isStatisticsEnabled();
    long startTime = 0;
    if (stats) startTime = System.currentTimeMillis();
    //
    userId = userId.replace("'", "''");

    StringBuilder strQuery =
        new StringBuilder("SELECT * FROM ").append(NTF_MESSAGE).append(" WHERE ");
    strQuery
        .append(" (jcr:path LIKE '")
        .append(pluginDayNode.getPath())
        .append("/%'")
        .append(" AND NOT jcr:path LIKE '")
        .append(pluginDayNode.getPath())
        .append("/%/%')");
    strQuery.append(" AND (").append(NTF_SEND_TO_DAILY).append("='").append(userId).append("'");
    strQuery
        .append(" OR ")
        .append(NTF_SEND_TO_DAILY)
        .append("='")
        .append(NotificationInfo.FOR_ALL_USER)
        .append("') AND ")
        .append(NTF_FROM)
        .append("<>'")
        .append(userId)
        .append("'");
    strQuery
        .append(" order by ")
        .append(NTF_ORDER)
        .append(ASCENDING)
        .append(", exo:dateCreated")
        .append(DESCENDING);

    QueryManager qm = pluginDayNode.getSession().getWorkspace().getQueryManager();
    Query query = qm.createQuery(strQuery.toString(), Query.SQL);
    NodeIterator it = query.execute().getNodes();

    if (stats) {
      NotificationContextFactory.getInstance()
          .getStatisticsCollector()
          .queryExecuted(strQuery.toString(), it.getSize(), System.currentTimeMillis() - startTime);
    }
    return it;
  }