javax.jcr.query.Row Java Examples

The following examples show how to use javax.jcr.query.Row. 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: JcrMetadataRepository.java    From archiva with Apache License 2.0 6 votes vote down vote up
private <T extends MetadataFacet> Function<Row, Optional<T>> getFacetFromRowFunc(MetadataFacetFactory<T> factory, String repositoryId) {
    return (Row row) -> {
        try {
            Node node = row.getNode("facet");
            if (node.hasProperty("archiva:name")) {
                String facetName = node.getProperty("archiva:name").getString();
                return Optional.ofNullable(createFacetFromNode(factory, node, repositoryId, facetName));
            } else {
                return Optional.empty();
            }
        } catch (RepositoryException e) {
            log.error("Exception encountered {}", e.getMessage());
            return Optional.empty();
        }
    };
}
 
Example #2
Source File: JcrMetadataRepository.java    From archiva with Apache License 2.0 6 votes vote down vote up
@Override
public <T extends MetadataFacet> Stream<T> getMetadataFacetStream(RepositorySession session, String repositoryId, Class<T> facetClazz, QueryParameter queryParameter) throws MetadataRepositoryException {
    final Session jcrSession = getSession(session);
    final MetadataFacetFactory<T> factory = metadataService.getFactory(facetClazz);
    final String facetId = factory.getFacetId();
    final String facetPath = '/' + getFacetPath(repositoryId, facetId);
    StringBuilder query = new StringBuilder("SELECT * FROM [");
    query.append(FACET_NODE_TYPE).append("] AS facet WHERE ISDESCENDANTNODE(facet, [")
            .append(facetPath).append("]) AND [facet].[archiva:name] IS NOT NULL");
    appendQueryParams(query, "facet", "archiva:name", queryParameter);
    String q = query.toString();
    Map<String, String> params = new HashMap<>();
    QueryResult result = runNativeJcrQuery(jcrSession, q, params, queryParameter.getOffset(), queryParameter.getLimit());
    final Function<Row, Optional<T>> rowFunc = getFacetFromRowFunc(factory, repositoryId);
    return StreamSupport.stream(createResultSpliterator(result, rowFunc), false).filter(Optional::isPresent).map(Optional::get);

}
 
Example #3
Source File: ProductsSuggestionOmniSearchHandler.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
@Override
public QueryResult execute() throws InvalidQueryException, RepositoryException {
    // Get JCR results
    QueryResult queryResult = query.execute();

    // Get CIF products
    Iterator<Resource> it = getVirtualResults(resolver, Collections.singletonMap("fulltext", searchTerm), 10, 0);
    if (it == null || !it.hasNext()) {
        return queryResult; // No CIF results
    }

    ValueFactory valueFactory = resolver.adaptTo(Session.class).getValueFactory();
    List<Row> rows = new ArrayList<>();
    while (it.hasNext()) {
        String title = it.next().getValueMap().get(JcrConstants.JCR_TITLE, String.class);
        Value value = valueFactory.createValue(title);
        rows.add(new SuggestionRow(value));
    }

    RowIterator suggestionIterator = queryResult.getRows();
    while (suggestionIterator.hasNext()) {
        rows.add(suggestionIterator.nextRow());
    }

    SuggestionQueryResult result = new SuggestionQueryResult(rows);
    return result;
}
 
Example #4
Source File: JcrMetadataRepository.java    From archiva with Apache License 2.0 5 votes vote down vote up
private <T> Spliterator<T> createResultSpliterator(QueryResult result, Function<Row, T> converter) throws MetadataRepositoryException {
    final RowIterator rowIterator;
    try {
        rowIterator = result.getRows();
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException(e.getMessage(), e);
    }
    return new Spliterator<T>() {
        @Override
        public boolean tryAdvance(Consumer<? super T> action) {
            while (rowIterator.hasNext()) {
                T item = converter.apply(rowIterator.nextRow());
                if (item != null) {
                    action.accept(item);
                    return true;
                }
            }
            return false;
        }

        @Override
        public Spliterator<T> trySplit() {
            return null;
        }

        @Override
        public long estimateSize() {
            return 0;
        }

        @Override
        public int characteristics() {
            return ORDERED + NONNULL;
        }
    };
}
 
Example #5
Source File: JcrMetadataRepository.java    From archiva with Apache License 2.0 5 votes vote down vote up
private Function<Row, Optional<ArtifactMetadata>> getArtifactFromRowFunc(final String repositoryId) {
    return (Row row) -> {
        try {
            return Optional.of(getArtifactFromNode(repositoryId, row.getNode("artifact")));
        } catch (RepositoryException e) {
            return Optional.empty();
        }
    };
}
 
Example #6
Source File: JcrMetadataRepository.java    From archiva with Apache License 2.0 5 votes vote down vote up
@Override
public Stream<ArtifactMetadata> getArtifactByDateRangeStream(RepositorySession session, String repositoryId, ZonedDateTime startTime, ZonedDateTime endTime, QueryParameter queryParameter) throws MetadataRepositoryException {
    final Session jcrSession = getSession(session);
    final QueryResult result = queryArtifactByDateRange(jcrSession, repositoryId, startTime, endTime, queryParameter);
    final Function<Row, Optional<ArtifactMetadata>> rowFunc = getArtifactFromRowFunc(repositoryId);
    return StreamSupport.stream(createResultSpliterator(result, rowFunc), false).filter(Optional::isPresent).map(Optional::get);
}
 
Example #7
Source File: JcrMetadataRepository.java    From archiva with Apache License 2.0 5 votes vote down vote up
public List<ArtifactMetadata> runJcrQuery(final Session jcrSession, final String repositoryId, final String qParam,
                                          final Map<String, String> bindingParam, final boolean checkPath)
        throws MetadataRepositoryException {

    String q = qParam;
    List<ArtifactMetadata> artifacts;
    if (repositoryId != null && checkPath) {
        q += " AND ISDESCENDANTNODE(artifact,'/" + getRepositoryContentPath(repositoryId) + "')";
    }

    log.info("Running JCR Query: {}", q);

    try {
        QueryResult result = runNativeJcrQuery(jcrSession, q, bindingParam);
        artifacts = new ArrayList<>();
        RowIterator rows = result.getRows();
        while (rows.hasNext()) {
            Row row = rows.nextRow();
            Node node = row.getNode("artifact");
            artifacts.add(getArtifactFromNode(repositoryId, node));
        }
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException(e.getMessage(), e);
    }
    log.info("Artifacts found {}", artifacts.size());
    for (ArtifactMetadata meta : artifacts) {
        log.info("Artifact: " + meta.getVersion() + " " + meta.getFacetList());
    }
    return artifacts;
}
 
Example #8
Source File: JcrMetadataRepository.java    From archiva with Apache License 2.0 5 votes vote down vote up
private Optional<ArtifactMetadata> getArtifactOptional(final String repositoryId, final Row row) {
    try {
        return Optional.of(getArtifactFromNode(repositoryId, row.getNode("artifact")));
    } catch (RepositoryException e) {
        return Optional.empty();
    }
}
 
Example #9
Source File: ProductsSuggestionOmniSearchHandler.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
private SuggestionQueryResult(List<Row> rows) {
    this.rows = rows;
}
 
Example #10
Source File: ProductsSuggestionOmniSearchHandlerTest.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
@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 #11
Source File: JcrMetadataRepository.java    From archiva with Apache License 2.0 4 votes vote down vote up
@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);
        }
    }