/** * search book by name with limit of result(using SQL) * * @param name The name of book * @return List<Book> */ public List<Book> searchBookByNameLimitSQL(String name) { /* replace "" sign and - sign */ name = name.replaceAll("\"", "\\\"").replaceAll("-", StringUtils.EMPTY); /* 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 QueryImpl object */ QueryImpl query = (QueryImpl) queryManager.createQuery(sb.toString(), QueryImpl.SQL); /* set offset(which first record will be get) */ query.setOffset(2); /* set limit(how many record will be get after offset) */ query.setLimit(3); /* 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(); } }
/** * 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(); } }
/** * 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(); } }
/** * 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; }
/** 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"); }
/** * {@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."); } }
@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); } }
@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; }
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); } }
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()); } }
@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()); }
@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); } }
@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); } }
/** * 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(); } }
/** * get user by name in range with sql statement * * @param username */ public User getUserByNameLimtSQL(String username) { username.replaceAll("\"", "\\\"").replaceAll("-", StringUtils.EMPTY); username = username.trim(); SessionProvider sProvider = SessionProvider.createSystemProvider(); StringBuffer queryString = new StringBuffer("Select * from " + BookNodeTypes.EXO_USER); queryString.append(" where " + BookNodeTypes.EXO_USER_NAME + " = '" + username + "'"); try { QueryManager queryManager = getSession(sProvider).getWorkspace().getQueryManager(); QueryImpl query = (QueryImpl) queryManager.createQuery(queryString.toString(), Query.SQL); query.setOffset(0L); query.setLimit(3L); 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(); } }
/** * @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 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; }
@Override public String[] supportedQueryLanguages() { Session session = (Session) this.getThreadLocalRequest().getSession().getAttribute("session"); try { QueryManager qm = session.getWorkspace().getQueryManager(); return qm.getSupportedQueryLanguages(); } catch (RepositoryException e) { log.log(Level.SEVERE, "Error getting supported query languages", e); } return null; }
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(); } }
/** * 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); } } } }
/** 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; }
/** * @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; }
/** * 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; } }
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 Query createSearchPageQuery(QueryCriteria queryCriteria, QueryManager queryManager) throws Exception { SQLQueryBuilder queryBuilder = new SQLQueryBuilder(); List<String> mopPages = this.searchPageByTitle(queryCriteria.getSiteName(), queryCriteria.getKeyword()); List<QueryProperty> queryProps = new ArrayList<QueryCriteria.QueryProperty>(); for (String page : mopPages) { QueryProperty prop = queryCriteria.new QueryProperty(); prop.setName("mop:page"); prop.setValue(page); prop.setComparisonType(COMPARISON_TYPE.EQUAL); queryProps.add(prop); } QueryProperty prop = queryCriteria.new QueryProperty(); prop.setName("exo:name"); prop.setValue("mop:" + queryCriteria.getKeyword().toLowerCase()); queryProps.add(prop); queryCriteria.setQueryMetadatas(queryProps.toArray(new QueryProperty[queryProps.size()])); mapQueryTypes(queryCriteria, queryBuilder); if (queryCriteria.isFulltextSearch()) { mapQueryPath(queryCriteria, queryBuilder); mapFulltextQueryTearm(queryCriteria, queryBuilder, LOGICAL.OR); } else { searchByNodeName(queryCriteria, queryBuilder); } mapCategoriesCondition(queryCriteria, queryBuilder); mapDatetimeRangeSelected(queryCriteria, queryBuilder); mapMetadataProperties(queryCriteria, queryBuilder, LOGICAL.OR); orderBy(queryCriteria, queryBuilder); String queryStatement = queryBuilder.createQueryStatement(); Query query = queryManager.createQuery(queryStatement, Query.SQL); return query; }
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; }
/** * Configure. * * @param session the session * @param folderPath the folder path * @param portalName the portal name * @throws Exception the exception */ private void configure(Node targetNode, String portalName) throws Exception { String statement = "select * from nt:resource where jcr:path like '" + targetNode.getPath() + "/%' order by jcr:dateModified ASC"; QueryManager queryManager = targetNode.getSession().getWorkspace().getQueryManager(); Query query = queryManager.createQuery(statement, Query.SQL); NodeIterator iterator = query.execute().getNodes(); for (; iterator.hasNext(); ) { Node ntResource = iterator.nextNode(); String mimeType = ntResource.getProperty("jcr:mimeType").getString(); if (!mimeType.startsWith("text")) continue; String jcrData = ntResource.getProperty("jcr:data").getString(); if (!jcrData.contains("{portalName}")) continue; String realData = StringUtils.replace(jcrData, "{portalName}", portalName); ntResource.setProperty("jcr:data", realData); } }
private NodeIterator setQuery(boolean isQuery, String value) throws Exception { NodeIterator iter; Session session = sessionManager.getCurrentSession(); if (session == null || !session.isLive()) { sessionManager.openSession(); session = sessionManager.getCurrentSession(); } if (isQuery) { QueryManager qm = session.getWorkspace().getQueryManager(); Query query = qm.createQuery(value, Query.XPATH); QueryResult result = query.execute(); iter = result.getNodes(); } else { Node node = (Node) session.getItem(value); iter = node.getNodes(); } return iter; }
public Set<Node> getReferrers(Node document) throws RepositoryException { Set<Node> referrers = new TreeSet<Node>( new Comparator<Node>() { public int compare(Node node1, Node node2) { try { return node1.getIdentifier().compareTo(node2.getIdentifier()); } catch (UnsupportedRepositoryOperationException ex) { // cannot happen return 0; } catch (RepositoryException ex) { return 0; } } }); if (!document.isNodeType(HippoNodeType.NT_DOCUMENT)) { return null; } document = ((HippoNode) document).getCanonicalNode(); Node handle = document.getParent(); if (!handle.isNodeType(HippoNodeType.NT_HANDLE) || !handle.isNodeType(HippoNodeType.NT_HARDHANDLE)) { return null; } String uuid = handle.getIdentifier(); QueryManager queryManager = document.getSession().getWorkspace().getQueryManager(); String statement = "//*[@hippo:docbase='" + uuid + "']"; Query query = queryManager.createQuery(statement, Query.XPATH); QueryResult result = query.execute(); for (NodeIterator iter = result.getNodes(); iter.hasNext(); ) { Node node = iter.nextNode(); while (node != null && !node.isNodeType(HippoNodeType.NT_DOCUMENT)) { node = (node.getDepth() > 0 ? node.getParent() : null); } if (node != null) { if (node.isNodeType("hippostd:publishable") && node.hasProperty("hippostd:state") && node.getProperty("hippostd:state").getString().equals("published")) { referrers.add(node); } } } return referrers; }
/** * Set-up the configuration values used for the test. Per default retrieves a session, configures * testRoot, and nodetype and checks if the query language for the current language is available. * <br> */ protected void setUp() throws Exception { super.setUp(); jcrScore = superuser.getNamespacePrefix(NS_JCR_URI) + ":score"; jcrPath = superuser.getNamespacePrefix(NS_JCR_URI) + ":path"; jcrRoot = superuser.getNamespacePrefix(NS_JCR_URI) + ":root"; jcrContains = superuser.getNamespacePrefix(NS_JCR_URI) + ":contains"; jcrDeref = superuser.getNamespacePrefix(NS_JCR_URI) + ":deref"; xpathRoot = "/" + jcrRoot + ISO9075.encodePath(testRoot); qm = superuser.getWorkspace().getQueryManager(); qf = qm.getQOMFactory(); vf = superuser.getValueFactory(); }