javax.jcr.query.QueryResult Java Examples

The following examples show how to use javax.jcr.query.QueryResult. 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 vote down vote up
/**
 * 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: StorageUpdate12.java    From nextreports-server with Apache License 2.0 6 votes vote down vote up
private void addRuntimeNameProperty() throws RepositoryException {
	
	String statement = 
			"/jcr:root" + ISO9075.encodePath(StorageConstants.REPORTS_ROOT) + 
			"//*[@className='ro.nextreports.server.domain.Report']" + 
			"//*[fn:name()='parametersValues']";
	  
	QueryResult queryResult = getTemplate().query(statement);

	NodeIterator nodes = queryResult.getNodes();
	
	LOG.info("RuntimeHistory : Found " + nodes.getSize() + " parameterValues nodes");
	while (nodes.hasNext()) {			
		Node node = nodes.nextNode();
		NodeIterator childrenIt = node.getNodes();
		while (childrenIt.hasNext()) {
			Node child = childrenIt.nextNode();				
			child.setProperty("runtimeName", child.getName());
		}
	}	
	getTemplate().save();		
}
 
Example #3
Source File: JcrMetadataRepository.java    From archiva with Apache License 2.0 6 votes vote down vote up
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 #4
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 #5
Source File: JcrMetadataRepository.java    From archiva with Apache License 2.0 6 votes vote down vote up
@Override
public List<ArtifactMetadata> getArtifactsByDateRange(RepositorySession session, String repoId, ZonedDateTime startTime, ZonedDateTime endTime, QueryParameter queryParameter)
        throws MetadataRepositoryException {
    final Session jcrSession = getSession(session);

    List<ArtifactMetadata> artifacts;
    try {
        QueryResult result = queryArtifactByDateRange(jcrSession, repoId, startTime, endTime, queryParameter);

        artifacts = new ArrayList<>();
        for (Node n : JcrUtils.getNodes(result)) {
            artifacts.add(getArtifactFromNode(repoId, 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 vote down vote up
@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 #7
Source File: JcrMetadataRepository.java    From archiva with Apache License 2.0 6 votes vote down vote up
@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 #8
Source File: JcrStorageDao.java    From nextreports-server with Apache License 2.0 6 votes vote down vote up
private Entity[] getEntities(QueryResult queryResult) {
	try {
		NodeIterator nodes = queryResult.getNodes();
		List<Entity> entities = new ArrayList<Entity>();
		while (nodes.hasNext()) {
			Entity entity = getEntity(nodes.nextNode());
			if (entity != null) {
				entities.add(entity);
			}
		}

		return entities.toArray(new Entity[entities.size()]);
	} catch (RepositoryException e) {
		throw convertJcrAccessException(e);
	}
}
 
Example #9
Source File: StorageUpdate10.java    From nextreports-server with Apache License 2.0 6 votes vote down vote up
private void modifyDashboardState() throws RepositoryException {
	LOG.info("Modify dashboard state - add columnCount property");
	
	String path = StorageConstants.DASHBOARDS_ROOT;
	String className = "ro.nextreports.server.domain.DashboardState";		
       String statement = "/jcr:root" + ISO9075.encodePath(path) + "//*[@className='" + className + "']";
       QueryResult queryResult = getTemplate().query(statement);

       NodeIterator nodes = queryResult.getNodes();
       LOG.info("Found " + nodes.getSize() + " dashboard state nodes");
       while (nodes.hasNext()) {
       	Node node = nodes.nextNode();
       	node.setProperty("columnCount", 2);
       }
       
       getTemplate().save();
}
 
Example #10
Source File: StorageUpdate15.java    From nextreports-server with Apache License 2.0 6 votes vote down vote up
private void updateTemplateNodes() throws RepositoryException {
	
	// add shortcutType node to all report templates nodes
   	String statement = 
			"/jcr:root" + ISO9075.encodePath(StorageConstants.REPORTS_ROOT) + 
			"//*[@className='ro.nextreports.server.domain.Report']/templates";
	  
	QueryResult queryResult = getTemplate().query(statement);
	NodeIterator nodes = queryResult.getNodes();
	
	LOG.info("Add shortcutType node to all report templates nodes : Found " + nodes.getSize() + " report nodes");
	while (nodes.hasNext()) {			
		Node node = nodes.nextNode();
		NodeIterator templatesForReport = node.getNodes();
		while (templatesForReport.hasNext()) {
			Node template = templatesForReport.nextNode();
			Node shortcutTypeNode = template.addNode("shortcutType");
			shortcutTypeNode.setProperty("type", 0);
			shortcutTypeNode.setProperty("timeType", 0);
			shortcutTypeNode.setProperty("timeUnits", 0);
		}
	}					

   	getTemplate().save();
	
}
 
Example #11
Source File: QueryTest.java    From sling-whiteboard with Apache License 2.0 6 votes vote down vote up
@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 #12
Source File: StorageUpdate6.java    From nextreports-server with Apache License 2.0 6 votes vote down vote up
private void addAnalystUserProfile() throws RepositoryException {
	LOG.info("User profile analyst");

	String path = StorageConstants.USERS_ROOT ;
	String className = "ro.nextreports.server.domain.User";
       String statement = "/jcr:root" + ISO9075.encodePath(path) + "//*[@className='" + className + "']";
       QueryResult queryResult = getTemplate().query(statement);

       NodeIterator nodes = queryResult.getNodes();
       LOG.info("Found " + nodes.getSize() + " nodes");
       while (nodes.hasNext()) {
       	Node node = nodes.nextNode();
       	node.setProperty("profile", "analyst");
       }

       getTemplate().save();
}
 
Example #13
Source File: ProductsSuggestionOmniSearchHandlerTest.java    From commerce-cif-connector with Apache License 2.0 6 votes vote down vote up
@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 #14
Source File: StorageUpdate8.java    From nextreports-server with Apache License 2.0 6 votes vote down vote up
private void updateInternalSettings() throws RepositoryException {
	// find all internalSettings nodes from DASHBOARDS and change chartId property in entityId
	String statement = "/jcr:root" + ISO9075.encodePath(StorageConstants.DASHBOARDS_ROOT) + "//*[fn:name()='internalSettings']";
    QueryResult queryResult = getTemplate().query(statement);
    NodeIterator nodes = queryResult.getNodes();
    LOG.info("Found " + nodes.getSize() +  " internalSettings nodes");
    while (nodes.hasNext()) {
    	Node node = nodes.nextNode();
    	try {
    		Property prop = node.getProperty("chartId");
    		node.setProperty("entityId", prop.getValue());
    		prop.remove();
    	} catch (PathNotFoundException ex) {
    		// if property not found we have nothing to do
    	}
    } 	
}
 
Example #15
Source File: StorageUpdate3.java    From nextreports-server with Apache License 2.0 6 votes vote down vote up
private void renameChartWidgetClassName() throws RepositoryException {
	LOG.info("Rename chart widget class name");
	
	String path = StorageConstants.DASHBOARDS_ROOT;
	String className = "ro.nextreports.server.web.chart.ChartWidget";
	String newClassName = "ro.nextreports.server.web.dashboard.chart.ChartWidget";
       String statement = "/jcr:root" + ISO9075.encodePath(path) + "//*[@widgetClassName='" + className + "']";
       QueryResult queryResult = getTemplate().query(statement);

       NodeIterator nodes = queryResult.getNodes();
       LOG.info("Found " + nodes.getSize() + " nodes");
       while (nodes.hasNext()) {
       	Node node = nodes.nextNode();
       	node.setProperty("widgetClassName", newClassName);
       }
       
       getTemplate().save();
}
 
Example #16
Source File: StorageUpdate11.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
private void convertReports() throws RepositoryException {
	
	String statement = 
			"/jcr:root" + ISO9075.encodePath(StorageConstants.REPORTS_ROOT) + 
			"//*[@className='ro.nextreports.server.domain.Report' and @type='Next']" + 
			"//*[fn:name()='jcr:content' and @jcr:mimeType='text/xml']";
	  
	QueryResult queryResult = getTemplate().query(statement);

	NodeIterator nodes = queryResult.getNodes();
	LOG.info("Converter 5.1 : Found " + nodes.getSize() + " report nodes");
	while (nodes.hasNext()) {
		
		Node node = nodes.nextNode();
		
		Node reportNode = node.getParent().getParent().getParent().getParent();
		String reportName = reportNode.getName();
		String reportPath = reportNode.getPath();	
		LOG.info(" * Start convert '" + reportPath + "'");						
											
		Property prop = node.getProperty("jcr:data");			
       	String xml = null;
           try {                  	
           	xml = new Converter_5_2().convertFromInputStream(prop.getBinary().getStream(), true);            	            	
           	if (xml != null) {
               	ValueFactory valueFactory = node.getSession().getValueFactory(); 
               	Binary binaryValue = valueFactory.createBinary(new ByteArrayInputStream(xml.getBytes("UTF-8")));
               	node.setProperty ("jcr:data", binaryValue);                	
               	LOG.info("\t -> OK");
               } else {
               	LOG.error("\t -> FAILED : null xml");
               }
           	            	            	
           } catch (Throwable t) {                    	            	            
           	LOG.error("\t-> FAILED : " + t.getMessage(), t);            	
           } 					
           
	}
}
 
Example #17
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 #18
Source File: StorageUpdate20.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
private void renamePackage(String path, String propertyName) throws RepositoryException {
       String statement = "/jcr:root" + ISO9075.encodePath(path) + "//*[@" + propertyName + "]";
       QueryResult queryResult = getTemplate().query(statement);

       NodeIterator nodes = queryResult.getNodes();
       LOG.info("Found " + nodes.getSize() + " entity nodes with property '" + propertyName + "'");
       while (nodes.hasNext()) {
       	renamePackage(nodes.nextNode(), propertyName);
       }
}
 
Example #19
Source File: StorageUpdater.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
private void resetFirstUsageDates() throws Exception {
  	LOG.info("Reset firstUsage.date for all users");
String statement = "/jcr:root"
		+ ISO9075.encodePath(StorageConstants.USERS_ROOT)
		+ "//*[@className='ro.nextreports.server.domain.UserPreferences']";
QueryResult queryResult = jcrTemplate.query(statement);

NodeIterator nodes = queryResult.getNodes();
LOG.info("Found " + nodes.getSize() + " user preferences nodes");		
while (nodes.hasNext()) {
	Node node = nodes.nextNode();
	
	Node pNode = node.getNode("preferences");
	try {
		Property property = pNode.getProperty("firstUsage.date");
		if (property.getValue() != null) {
			LOG.info("    removed firstUsage.date = " + property.getString() + "  for user " + node.getParent().getName());
			String s = null;
			pNode.setProperty("firstUsage.date", s);
		}
	} catch (PathNotFoundException ex) {
		// nothing to do
	}
}

jcrTemplate.save();
  }
 
Example #20
Source File: StorageUpdate7.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
private void addDestinations() throws RepositoryException {
	LOG.info("Add destinations to scheduler jobs");

	String path = StorageConstants.SCHEDULER_ROOT ;
	String className = "ro.nextreports.server.domain.SchedulerJob";
       String statement = "/jcr:root" + ISO9075.encodePath(path) + "//*[@className='" + className + "']";
       QueryResult queryResult = getTemplate().query(statement);

       NodeIterator nodes = queryResult.getNodes();
       LOG.info("Found " + nodes.getSize() + " scheduler job nodes");
       while (nodes.hasNext()) {
       	Node node = nodes.nextNode();
       	if (node.hasNode("mail")) {
       		LOG.info("Found 'mail' node for '" + node.getName() + "'");
       		Node mailNode = node.getNode("mail");
       		LOG.info("Create '" + StorageConstants.DESTINATIONS + "' node for '" + node.getName() + "'");
       		Node destinationsNode = node.addNode(StorageConstants.DESTINATIONS);
       		className = SmtpDestination.class.getName();
       		LOG.info("Change 'className' property for 'mail' node to '" + className + "'");
       		mailNode.setProperty("className", className);
       		LOG.info("Move '" + mailNode.getName() + "' to '" + destinationsNode.getName() + "/mail");
       		getTemplate().move(mailNode.getPath(), destinationsNode.getPath() + "/mail");
       	}
       }

       getTemplate().save();
}
 
Example #21
Source File: JcrMetadataRepository.java    From archiva with Apache License 2.0 5 votes vote down vote up
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 #22
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 #23
Source File: StorageUpdate18.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
private void onUpdate() throws RepositoryException {
	
	String statement = "/jcr:root" + ISO9075.encodePath(StorageConstants.DATASOURCES_ROOT) + "//*[@className='ro.nextreports.server.domain.DataSource']";
       QueryResult queryResult = getTemplate().query(statement);

       NodeIterator nodes = queryResult.getNodes();
       LOG.info("Found " + nodes.getSize() +  " data sources nodes");
       while (nodes.hasNext()) {
       	Node node = nodes.nextNode();
       	Node propertiesNode = node.addNode(StorageConstants.PROPERTIES);
       }
	
	getTemplate().save();	
}
 
Example #24
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 #25
Source File: CatalogDataResourceProviderManagerImpl.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #26
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 #27
Source File: QueryImpl.java    From jackalope with Apache License 2.0 4 votes vote down vote up
public QueryImpl(String statement, String language, QueryResult result) {
    this.statement = statement;
    this.language = language;
    this.result = result;
}
 
Example #28
Source File: StorageUpdate13.java    From nextreports-server with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
	private void createNodeTemplates() throws RepositoryException {
		Session session = SessionFactoryUtils.getSession(getTemplate().getSessionFactory(), false);
    	Workspace workspace = session.getWorkspace();
    	    	
    	NodeTypeManagerImpl nodeTypeManager = (NodeTypeManagerImpl) workspace.getNodeTypeManager();
//    	nodeTypeManager.unregisterNodeType(StorageConstants.NEXT_REPORT_MIXIN);
    	    	
    	NodeTypeTemplate nodeTypeTemplate = nodeTypeManager.createNodeTypeTemplate();
    	nodeTypeTemplate.setName(StorageConstants.NEXT_REPORT_MIXIN);
    	nodeTypeTemplate.setMixin(true);
    	nodeTypeTemplate.setOrderableChildNodes(false);
    	nodeTypeTemplate.setPrimaryItemName("nt:unstructured");
    	nodeTypeTemplate.setDeclaredSuperTypeNames(new String[] { "mix:referenceable", "mix:versionable" });   
    	
    	NodeDefinitionTemplate nodeDefinitionTemplate = nodeTypeManager.createNodeDefinitionTemplate();
    	nodeDefinitionTemplate.setName("runHistory");
    	nodeDefinitionTemplate.setDefaultPrimaryTypeName("nt:unstructured");
    	nodeDefinitionTemplate.setRequiredPrimaryTypeNames(new String[] { "nt:unstructured" });
    	nodeDefinitionTemplate.setAutoCreated(true);
    	nodeDefinitionTemplate.setMandatory(false);
    	nodeDefinitionTemplate.setOnParentVersion(OnParentVersionAction.IGNORE);
    	nodeDefinitionTemplate.setProtected(false);
    	nodeDefinitionTemplate.setSameNameSiblings(false);

    	nodeTypeTemplate.getNodeDefinitionTemplates().add(nodeDefinitionTemplate);
    	    	
    	NodeDefinitionTemplate nodeDefinitionTemplate2 = nodeTypeManager.createNodeDefinitionTemplate();
    	nodeDefinitionTemplate2.setName("templates");
    	nodeDefinitionTemplate2.setDefaultPrimaryTypeName("nt:unstructured");
    	nodeDefinitionTemplate2.setRequiredPrimaryTypeNames(new String[] { "nt:unstructured" });
    	nodeDefinitionTemplate2.setAutoCreated(true);
    	nodeDefinitionTemplate2.setMandatory(false);
    	nodeDefinitionTemplate2.setOnParentVersion(OnParentVersionAction.IGNORE);
    	nodeDefinitionTemplate2.setProtected(false);
    	nodeDefinitionTemplate2.setSameNameSiblings(false);
    	
    	nodeTypeTemplate.getNodeDefinitionTemplates().add(nodeDefinitionTemplate2);

    	LOG.info("Registering node type mixin '" + StorageConstants.NEXT_REPORT_MIXIN + "'");
    	nodeTypeManager.registerNodeType(nodeTypeTemplate, true);
    	
    	// add templates node to all existing reports
    	String statement = 
				"/jcr:root" + ISO9075.encodePath(StorageConstants.REPORTS_ROOT) + 
				"//*[@className='ro.nextreports.server.domain.Report']";
		  
		QueryResult queryResult = getTemplate().query(statement);
		NodeIterator nodes = queryResult.getNodes();
		
		LOG.info("Create templates nodes : Found " + nodes.getSize() + " report nodes");
		while (nodes.hasNext()) {			
			Node node = nodes.nextNode();
			node.addNode("templates");
		}					

    	getTemplate().save();
	}
 
Example #29
Source File: StorageUpdate.java    From nextreports-server with Apache License 2.0 4 votes vote down vote up
protected NodeIterator getNodesByClassName(String className) throws Exception {
       String statement = "/jcr:root" + StorageConstants.NEXT_SERVER_ROOT + "//*[@className='" + className + "']";
       QueryResult queryResult = getTemplate().query(statement);
       return queryResult.getNodes();
}
 
Example #30
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);
}