javax.jcr.query.Query Java Examples
The following examples show how to use
javax.jcr.query.Query.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BlogServiceImpl.java From publick-sling-blog with Apache License 2.0 | 7 votes |
/** * Get blog posts with pagination * * @param offset The starting point of blog posts to return. * @param limit The number of blog posts to return. * @return The blog posts. */ public NodeIterator getPosts(Long offset, Long limit) { NodeIterator nodes = null; if (session != null) { try { QueryManager queryManager = session.getWorkspace().getQueryManager(); Query query = queryManager.createQuery(BLOG_QUERY, Query.JCR_SQL2); if (offset != null) { query.setOffset(offset); } if (limit != null) { query.setLimit(limit); } QueryResult result = query.execute(); nodes = result.getNodes(); } catch (RepositoryException e) { LOGGER.error("Could not search repository", e); } } return nodes; }
Example #2
Source File: ProductsSuggestionOmniSearchHandlerTest.java From commerce-cif-connector with Apache License 2.0 | 6 votes |
@Test public void testSuggestionQueryNoCifResults() throws Exception { // The mocked JCR result MockNode jcrNode = new MockNode("/var/commerce/products/jcrnode"); jcrNode.setProperty("rep:suggest()", BROOKLYN_COAT); MockQueryResult jcrResults = new MockQueryResult(Collections.singletonList(jcrNode)); Query jcrQuery = Mockito.mock(Query.class); Mockito.when(jcrQuery.execute()).thenReturn(jcrResults); Mockito.doReturn(jcrQuery).when(suggestionHandler).getSuperSuggestionQuery(resolver, "coats"); Mockito.doReturn(resolver).when(suggestionHandler).getResourceResolver(); Mockito.when(resolver.findResources(Mockito.any(), Mockito.any())).thenThrow(new RuntimeException()); suggestionHandler.onEvent(null); suggestionHandler.activate(null); Query suggestionQuery = suggestionHandler.getSuggestionQuery(resolver, "coats"); QueryResult queryResult = suggestionQuery.execute(); RowIterator rows = queryResult.getRows(); // No CIF result, only JCR result Assert.assertEquals(BROOKLYN_COAT, rows.nextRow().getValue("rep:suggest()").getString()); Assert.assertFalse(rows.hasNext()); }
Example #3
Source File: JcrMetadataRepository.java From archiva with Apache License 2.0 | 6 votes |
@Override public List<ArtifactMetadata> getArtifacts(RepositorySession session, String repositoryId) throws MetadataRepositoryException { final Session jcrSession = getSession(session); List<ArtifactMetadata> artifacts; String q = getArtifactQuery(repositoryId).toString(); try { Query query = jcrSession.getWorkspace().getQueryManager().createQuery(q, Query.JCR_SQL2); QueryResult result = query.execute(); artifacts = new ArrayList<>(); for (Node n : JcrUtils.getNodes(result)) { if (n.isNodeType(ARTIFACT_NODE_TYPE)) { artifacts.add(getArtifactFromNode(repositoryId, n)); } } } catch (RepositoryException e) { throw new MetadataRepositoryException(e.getMessage(), e); } return artifacts; }
Example #4
Source File: JcrMetadataRepository.java From archiva with Apache License 2.0 | 6 votes |
@Override public List<ArtifactMetadata> getArtifactsByChecksum(RepositorySession session, String repositoryId, String checksum) throws MetadataRepositoryException { final Session jcrSession = getSession(session); List<ArtifactMetadata> artifacts; String q = getArtifactQuery(repositoryId).append(" AND ([artifact].[checksums/*/value] = $checksum)").toString(); try { Query query = jcrSession.getWorkspace().getQueryManager().createQuery(q, Query.JCR_SQL2); ValueFactory valueFactory = jcrSession.getValueFactory(); query.bindValue("checksum", valueFactory.createValue(checksum)); QueryResult result = query.execute(); artifacts = new ArrayList<>(); for (Node n : JcrUtils.getNodes(result)) { artifacts.add(getArtifactFromNode(repositoryId, n)); } } catch (RepositoryException e) { throw new MetadataRepositoryException(e.getMessage(), e); } return artifacts; }
Example #5
Source File: JcrMetadataRepository.java From archiva with Apache License 2.0 | 6 votes |
private QueryResult queryArtifactByDateRange(Session jcrSession, String repositoryId, ZonedDateTime startTime, ZonedDateTime endTime, QueryParameter queryParameter) throws MetadataRepositoryException { String q = buildArtifactByDateRangeQuery(repositoryId, startTime, endTime, queryParameter).toString(); try { Query query = jcrSession.getWorkspace().getQueryManager().createQuery(q, Query.JCR_SQL2); query.setOffset(queryParameter.getOffset()); query.setLimit(queryParameter.getLimit()); ValueFactory valueFactory = jcrSession.getValueFactory(); if (startTime != null) { query.bindValue("start", valueFactory.createValue(createCalendar(startTime.withZoneSameInstant(ModelInfo.STORAGE_TZ)))); } if (endTime != null) { query.bindValue("end", valueFactory.createValue(createCalendar(endTime.withZoneSameInstant(ModelInfo.STORAGE_TZ)))); } return query.execute(); } catch (RepositoryException e) { throw new MetadataRepositoryException(e.getMessage(), e); } }
Example #6
Source File: QueryTest.java From sling-whiteboard with Apache License 2.0 | 6 votes |
@ParameterizedTest @MethodSource("countAndStatementProvider") public void testQuery(String countAndStatement) throws RepositoryException { assertNoContent(); final String [] params = countAndStatement.split("#"); final String statement = params[1]; final int expected = Integer.valueOf(params[0]); final Query q = session.getWorkspace().getQueryManager().createQuery(statement, Query.XPATH); if(expected < 0) { try { q.execute(); fail("Expected an Exception for " + statement); } catch(RepositoryException asExpected) { } } else { final QueryResult qr = q.execute(); final AtomicInteger count = new AtomicInteger(); qr.getRows().forEachRemaining(row -> count.incrementAndGet()); assertEquals(expected, count.get(), "Expecting " + expected + " rows for query " + statement); } }
Example #7
Source File: QueryManagerImpl.java From jackalope with Apache License 2.0 | 5 votes |
@Override public Query createQuery(String statement, String language) throws InvalidQueryException, RepositoryException { for (Query query : queries) if (query.getLanguage().equals(language) && query.getStatement().equals(statement)) return query; return new QueryImpl(statement, language, new QueryResultImpl()); }
Example #8
Source File: CommentServiceImpl.java From publick-sling-blog with Apache License 2.0 | 5 votes |
/** * Get all Comments in the order of newest to oldest. * * @param request The current request * @return List of all comments */ public List<Resource> getComments(final SlingHttpServletRequest request) { final List<Resource> comments = new ArrayList<>(); final Iterator<Resource> queryResults = request.getResourceResolver().findResources(BLOG_QUERY, Query.JCR_SQL2); while (queryResults.hasNext()) { comments.add(queryResults.next()); } return comments; }
Example #9
Source File: ScriptFinderImpl.java From APM with Apache License 2.0 | 5 votes |
private Stream<Resource> findScripts(ResourceResolver resolver) { final String query = String.format(QUERY, SCRIPT_PATH); return Stream.of(resolver.findResources(query, Query.JCR_SQL2)) .map(resourceIterator -> Spliterators.spliteratorUnknownSize(resourceIterator, Spliterator.ORDERED)) .flatMap(resourceSpliterator -> StreamSupport.stream(resourceSpliterator, false)) .filter(Objects::nonNull); }
Example #10
Source File: JCRQueryBuilder.java From jackalope with Apache License 2.0 | 5 votes |
public QueryManager build() { List<Query> queries = new ArrayList<>(); for (QueryBuilder queryBuilder : queryBuilders) queries.add(queryBuilder.build()); QueryManager queryManager = new QueryManagerImpl(queries.toArray(new Query[queries.size()])); ((WorkspaceImpl)session.getWorkspace()).setQueryManager(queryManager); return queryManager; }
Example #11
Source File: TestContentLoader.java From sling-whiteboard with Apache License 2.0 | 5 votes |
@Override public void prepareForQuery(SessionWrapper s, Query q) throws RepositoryException { // Simplistic way of finding out if the query affects content // that we have to load. For a real implementation we'll probably // need to analyze the Query Object Model in a more precise way. if(q.getStatement().contains("/content/")) { // Simplistiy way of loading content, we might // need a more subtle strategy if that's possible. Maybe query a // different back-end index to find out what's actually required TestBase.visitRecursively(s.getRootNode(), path -> true, null); } }
Example #12
Source File: JcrMetadataRepository.java From archiva with Apache License 2.0 | 5 votes |
public QueryResult runNativeJcrQuery(final Session jcrSession, final String q, final Map<String, String> bindingParam, long offset, long maxEntries) throws MetadataRepositoryException { Map<String, String> bindings; if (bindingParam == null) { bindings = new HashMap<>(); } else { bindings = bindingParam; } try { log.debug("Query: offset={}, limit={}, query={}", offset, maxEntries, q); Query query = jcrSession.getWorkspace().getQueryManager().createQuery(q, Query.JCR_SQL2); query.setLimit(maxEntries); query.setOffset(offset); ValueFactory valueFactory = jcrSession.getValueFactory(); for (Entry<String, String> entry : bindings.entrySet()) { log.debug("Binding: {}={}", entry.getKey(), entry.getValue()); Value value = valueFactory.createValue(entry.getValue()); log.debug("Binding value {}={}", entry.getKey(), value); query.bindValue(entry.getKey(), value); } long start = System.currentTimeMillis(); log.debug("Execute query {}", query); QueryResult result = query.execute(); long end = System.currentTimeMillis(); log.info("JCR Query ran in {} milliseconds: {}", end - start, q); return result; } catch (RepositoryException e) { throw new MetadataRepositoryException(e.getMessage(), e); } }
Example #13
Source File: CatalogDataResourceProviderManagerImpl.java From commerce-cif-connector with Apache License 2.0 | 5 votes |
/** * Find all existing virtual catalog data roots using all query defined in service configuration. * * @param resolver Resource resolver * @return all virtual catalog roots */ @SuppressWarnings("unchecked") private List<Resource> findDataRoots(ResourceResolver resolver) { List<Resource> allResources = new ArrayList<>(); for (String queryString : this.findAllQueries) { if (!StringUtils.contains(queryString, "|")) { throw new IllegalArgumentException("Query string does not contain query syntax seperated by '|': " + queryString); } String queryLanguage = StringUtils.substringBefore(queryString, "|"); String query = StringUtils.substringAfter(queryString, "|"); // data roots are JCR nodes, so we prefer JCR query because the resource resolver appears to be unreliable // when we are in the middle of registering/unregistering resource providers try { Session session = resolver.adaptTo(Session.class); Workspace workspace = session.getWorkspace(); QueryManager qm = workspace.getQueryManager(); Query jcrQuery = qm.createQuery(query, queryLanguage); QueryResult result = jcrQuery.execute(); NodeIterator nodes = result.getNodes(); while (nodes.hasNext()) { Node node = nodes.nextNode(); Resource resource = resolver.getResource(node.getPath()); if (resource != null) { allResources.add(resource); } } } catch (RepositoryException x) { log.error("Error finding data roots", x); } } dataRoots = allResources; return allResources; }
Example #14
Source File: QueryManagerImpl.java From jackalope with Apache License 2.0 | 4 votes |
public QueryManagerImpl(Query... queries) { this.queries = queries; }
Example #15
Source File: JCRQueryBuilder.java From jackalope with Apache License 2.0 | 4 votes |
public Query build() { return new QueryImpl(statement, language, queryResultBuilder.build()); }
Example #16
Source File: JcrMetadataRepository.java From archiva with Apache License 2.0 | 4 votes |
@Override public void populateStatistics(RepositorySession repositorySession, MetadataRepository repository, String repositoryId, RepositoryStatistics repositoryStatistics) throws MetadataRepositoryException { if (!(repository instanceof JcrMetadataRepository)) { throw new MetadataRepositoryException( "The statistics population is only possible for JcrMetdataRepository implementations"); } Session session = getSession(repositorySession); // TODO: these may be best as running totals, maintained by observations on the properties in JCR try { QueryManager queryManager = session.getWorkspace().getQueryManager(); // TODO: Check, if this is still the case - Switched to Jackrabbit OAK with archiva 3.0 // Former statement: JCR-SQL2 query will not complete on a large repo in Jackrabbit 2.2.0 - see JCR-2835 // Using the JCR-SQL2 variants gives // "org.apache.lucene.search.BooleanQuery$TooManyClauses: maxClauseCount is set to 1024" // String whereClause = "WHERE ISDESCENDANTNODE([/repositories/" + repositoryId + "/content])"; // Query query = queryManager.createQuery( "SELECT size FROM [archiva:artifact] " + whereClause, // Query.JCR_SQL2 ); String whereClause = "WHERE ISDESCENDANTNODE([/repositories/" + repositoryId + "/content])"; Query query = queryManager.createQuery("SELECT type,size FROM [" + ARTIFACT_NODE_TYPE + "] " + whereClause, Query.JCR_SQL2); QueryResult queryResult = query.execute(); Map<String, Integer> totalByType = new HashMap<>(); long totalSize = 0, totalArtifacts = 0; for (Row row : JcrUtils.getRows(queryResult)) { Node n = row.getNode(); log.debug("Result node {}", n); totalSize += row.getValue("size").getLong(); String type; if (n.hasNode(MavenArtifactFacet.FACET_ID)) { Node facetNode = n.getNode(MavenArtifactFacet.FACET_ID); type = facetNode.getProperty("type").getString(); } else { type = "Other"; } Integer prev = totalByType.get(type); totalByType.put(type, prev != null ? prev + 1 : 1); totalArtifacts++; } repositoryStatistics.setTotalArtifactCount(totalArtifacts); repositoryStatistics.setTotalArtifactFileSize(totalSize); for (Map.Entry<String, Integer> entry : totalByType.entrySet()) { log.info("Setting count for type: {} = {}", entry.getKey(), entry.getValue()); repositoryStatistics.setTotalCountForType(entry.getKey(), entry.getValue()); } // The query ordering is a trick to ensure that the size is correct, otherwise due to lazy init it will be -1 // query = queryManager.createQuery( "SELECT * FROM [archiva:project] " + whereClause, Query.JCR_SQL2 ); query = queryManager.createQuery("SELECT * FROM [archiva:project] " + whereClause + " ORDER BY [jcr:score]", Query.JCR_SQL2); repositoryStatistics.setTotalProjectCount(query.execute().getRows().getSize()); // query = queryManager.createQuery( // "SELECT * FROM [archiva:namespace] " + whereClause + " AND namespace IS NOT NULL", Query.JCR_SQL2 ); query = queryManager.createQuery( "SELECT * FROM [archiva:namespace] " + whereClause + " AND namespace IS NOT NULL ORDER BY [jcr:score]", Query.JCR_SQL2); repositoryStatistics.setTotalGroupCount(query.execute().getRows().getSize()); } catch (RepositoryException e) { throw new MetadataRepositoryException(e.getMessage(), e); } }
Example #17
Source File: QueryManagerImpl.java From jackalope with Apache License 2.0 | 4 votes |
@Override public Query getQuery(Node node) throws InvalidQueryException, RepositoryException { return null; }
Example #18
Source File: HistoryAutocleanService.java From APM with Apache License 2.0 | 4 votes |
private void deleteHistoryByQuery(ResourceResolver resolver, String query, int offset) { Iterable<Resource> iterable = () -> resolver.findResources(query, Query.JCR_SQL2); StreamSupport.stream(iterable.spliterator(), false) .skip(offset) .forEach(resource -> deleteItem(resolver, resource)); }
Example #19
Source File: HistoryImpl.java From APM with Apache License 2.0 | 4 votes |
@Override public List<Resource> findAllResources(ResourceResolver resourceResolver) { Iterator<Resource> resources = resourceResolver.findResources(HISTORY_ENTRIES_QUERY, Query.JCR_SQL2); return Lists.newArrayList(resources); }
Example #20
Source File: LazyLoadingQuery.java From sling-whiteboard with Apache License 2.0 | 4 votes |
public LazyLoadingQuery(SessionWrapper<?> sessionWrapper, Query wrappedQuery) { super(sessionWrapper, wrappedQuery); lazyLoadingSession = (LazyLoadingSession)sessionWrapper; contentLoader = ((LazyLoadingSession)sessionWrapper).getContentLoader(); }
Example #21
Source File: LazyLoadingWrapper.java From sling-whiteboard with Apache License 2.0 | 4 votes |
@Override public Query wrap(SessionWrapper s, Query q) { return new LazyLoadingQuery(s, q); }
Example #22
Source File: QueryManagerWrapper.java From sling-whiteboard with Apache License 2.0 | 4 votes |
@Override public Query getQuery(Node node) throws InvalidQueryException, RepositoryException { return sessionWrapper.getObjectWrapper().wrap(sessionWrapper, delegate.getQuery(node)); }
Example #23
Source File: QueryManagerWrapper.java From sling-whiteboard with Apache License 2.0 | 4 votes |
@Override public Query createQuery(String statement, String language) throws InvalidQueryException, RepositoryException { return sessionWrapper.getObjectWrapper().wrap(this.sessionWrapper, delegate.createQuery(statement, language)); }
Example #24
Source File: DefaultObjectWrapper.java From sling-whiteboard with Apache License 2.0 | 4 votes |
public Query wrap(SessionWrapper s, Query q) { return new QueryWrapper(s, q); }
Example #25
Source File: QueryWrapper.java From sling-whiteboard with Apache License 2.0 | 4 votes |
public QueryWrapper(SessionWrapper<?> sessionWrapper, Query wrappedQuery) { super(sessionWrapper, wrappedQuery); }
Example #26
Source File: SearchSandbox.java From sling-samples with Apache License 2.0 | 4 votes |
@Activate public void test() throws PersistenceException, LoginException { System.out.println("*** Search service sandbox"); if (resolver == null) { resolver = resourceResolverFactory.getAdministrativeResourceResolver(null); } Resource testRoot; final Resource root = resolver.getResource("/"); final String path = getClass().getSimpleName(); testRoot = resolver.getResource(root, path); if (testRoot == null) { testRoot = resolver.create(root, path, null); resolver.commit(); } for (int i = 0; i < 3; i++) { final Props props = new Props("title", "HELLO", "jcr:text", "world"); resolver.create(testRoot, "child_" + System.currentTimeMillis(), props).getPath(); resolver.commit(); } Scanner sc = new Scanner(System.in); System.out.println("Type \"quit\" to continue loading MAS."); System.out.print("*** New query: >"); String query = sc.nextLine(); while (!query.equalsIgnoreCase("quit")) { try { System.out.println("*** sql"); Iterator<Resource> resSQL = resolver.findResources(query, Query.JCR_SQL2); while (resSQL.hasNext()) { Resource resource = (Resource) resSQL.next(); System.out.println(resource.toString()); } // System.out.println("*** xpath"); // Iterator<Resource> resXPath = resolver.findResources(query, Query.XPATH); // while (resXPath.hasNext()) { // Resource resource = (Resource) resXPath.next(); // System.out.println(resource.toString()); // } } catch (Exception e) { e.printStackTrace(); } System.out.print("*** New query: >"); query = sc.nextLine(); } }
Example #27
Source File: SearchServiceImpl.java From sling-samples with Apache License 2.0 | 4 votes |
@Override public Iterator<Resource> find(String phrase) { String query = queryBuilder.buildQuery(parser.parse(phrase), QueryBuilderImpl.SQL2); Iterator<Resource> res = resolver.findResources(query, Query.JCR_SQL2); return res; }
Example #28
Source File: ProductsSuggestionOmniSearchHandlerTest.java From commerce-cif-connector with Apache License 2.0 | 4 votes |
@Test public void testSuggestionQuery() throws Exception { // The mocked JCR result MockNode jcrNode = new MockNode("/var/commerce/products/jcrnode"); jcrNode.setProperty("rep:suggest()", BROOKLYN_COAT); MockQueryResult jcrResults = new MockQueryResult(Collections.singletonList(jcrNode)); Query jcrQuery = Mockito.mock(Query.class); Mockito.when(jcrQuery.execute()).thenReturn(jcrResults); Mockito.doReturn(jcrQuery).when(suggestionHandler).getSuperSuggestionQuery(resolver, "coats"); Mockito.doReturn(resolver).when(suggestionHandler).getResourceResolver(); ValueFactory valueFactory = Mockito.mock(ValueFactory.class); Mockito.when(valueFactory.createValue(EL_GORDO_DOWN_JACKET)).thenReturn(new MockValue(EL_GORDO_DOWN_JACKET)); Session session = Mockito.mock(Session.class); Mockito.when(resolver.adaptTo(Session.class)).thenReturn(session); Mockito.when(session.getValueFactory()).thenReturn(valueFactory); // The mocked CIF result MockResource cifProduct = new MockResource(resolver, "/var/commerce/products/graphql/cifresource", "commerce/components/product"); cifProduct.addProperty(JcrConstants.JCR_TITLE, EL_GORDO_DOWN_JACKET); // The title is used for the suggestion Mockito.when(resolver.findResources(Mockito.any(), Mockito.any())) .thenReturn(Collections.singletonList((Resource) cifProduct).iterator()); suggestionHandler.activate(null); suggestionHandler.onEvent(null); Query suggestionQuery = suggestionHandler.getSuggestionQuery(resolver, "coats"); QueryResult queryResult = suggestionQuery.execute(); RowIterator rows = queryResult.getRows(); // The CIF result is first, then the JCR result Row row = rows.nextRow(); Assert.assertEquals(EL_GORDO_DOWN_JACKET, row.getValue("rep:suggest()").getString()); Assert.assertEquals(BROOKLYN_COAT, rows.nextRow().getValue("rep:suggest()").getString()); // Not implemented Assert.assertNull(suggestionQuery.getLanguage()); Assert.assertNull(suggestionQuery.getStatement()); Assert.assertNull(suggestionQuery.getStoredQueryPath()); Assert.assertNull(suggestionQuery.getBindVariableNames()); Assert.assertNull(suggestionQuery.storeAsNode("whatever")); Assert.assertNull(queryResult.getColumnNames()); Assert.assertNull(queryResult.getNodes()); Assert.assertNull(queryResult.getSelectorNames()); Assert.assertNull(row.getValues()); Assert.assertNull(row.getPath()); Assert.assertNull(row.getPath("whatever")); Assert.assertNull(row.getNode()); Assert.assertNull(row.getNode("whatever")); Assert.assertEquals(0d, row.getScore(), 0); Assert.assertEquals(0d, row.getScore("whatever"), 0); suggestionHandler.deactivate(null); }
Example #29
Source File: CollapsibleBlogList.java From publick-sling-blog with Apache License 2.0 | 2 votes |
/** * Get the immediate resources under the blog path that relate to blog posts * e.g. [/content/blog/2014, /content/blog/2015, /content/blog/2016]. * * @return resources related to blog posts directly under the blog path */ public Iterator<Resource> getPosts() { return getResourceResolver().findResources("SELECT * FROM [nt:unstructured] WHERE ISCHILDNODE('" + PublickConstants.BLOG_PATH + "') AND NAME() <> 'jcr:content'", Query.JCR_SQL2); }
Example #30
Source File: ContentLoader.java From sling-whiteboard with Apache License 2.0 | 2 votes |
/** Load the required content for the supplied Query, if its scope extends * to pre-loadable content. * * This will require analyzing Queries to find out if pre-loadable content * influences their results. * * The set of Queries that cause pre-loading will need to be strictly * defined to avoid pre-loading everything as soon as a somewhat * broad Query is prepared. * * This will have an impact at the application level, where too * broad queries will be ignored by this method, causing useful content * to be missing. */ void prepareForQuery(SessionWrapper s, Query q) throws RepositoryException;