Java Code Examples for javax.jcr.query.Query#execute()
The following examples show how to use
javax.jcr.query.Query#execute() .
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: 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 4
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 5
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 6
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 7
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 8
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 9
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 10
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); } }