javax.jcr.ValueFactory Java Examples

The following examples show how to use javax.jcr.ValueFactory. 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
@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 #2
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 #3
Source File: TestAceOrder.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
@Override
public void setUp() throws Exception {
    super.setUp();
    uMgr = ((JackrabbitSession) admin).getUserManager();
    User testuser = uMgr.createUser(NAME_TEST_USER, null);
    admin.save();

    acMgr = admin.getAccessControlManager();

    Node tmp = admin.getRootNode().addNode("testroot").addNode("secured");
    JackrabbitAccessControlList list = AccessControlUtils.getAccessControlList(acMgr, tmp.getPath());
    Privilege[] writePrivilege = AccessControlUtils.privilegesFromNames(acMgr, Privilege.JCR_WRITE);
    ValueFactory vf = admin.getValueFactory();
    Principal everyone = ((JackrabbitSession) admin).getPrincipalManager().getEveryone();
    list.addEntry(everyone, writePrivilege, true, ImmutableMap.of("rep:glob", vf.createValue("/foo")));
    list.addEntry(testuser.getPrincipal(), writePrivilege, false, ImmutableMap.of("rep:glob", vf.createValue("/foo")));
    list.addEntry(everyone, writePrivilege, true, ImmutableMap.of("rep:glob", vf.createValue("/bar")));
    acMgr.setPolicy(tmp.getPath(), list);

    expectedEntries = ImmutableList.copyOf(list.getAccessControlEntries());

    admin.refresh(false);
}
 
Example #4
Source File: JcrPackageDefinitionImpl.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void setDependencies(@NotNull Dependency[] dependencies, boolean autoSave) {
    try {
        final List<Value> values = new ArrayList<>(dependencies.length);
        final ValueFactory fac = defNode.getSession().getValueFactory();
        for (Dependency d: dependencies) {
            if (d != null) {
                values.add(fac.createValue(d.toString()));
            }
        }
        defNode.setProperty(PN_DEPENDENCIES, values.toArray(new Value[values.size()]));
        if (autoSave) {
            defNode.getSession().save();
        }
    } catch (RepositoryException e) {
        log.error("Error during setDependencies()", e);
    }
}
 
Example #5
Source File: JackrabbitACLImporter.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
void convertRestrictions(JackrabbitAccessControlList acl, ValueFactory vf, Map<String, Value> svRestrictions, Map<String, Value[]> mvRestrictions) throws RepositoryException {
    for (String restName : acl.getRestrictionNames()) {
        DocViewProperty restriction = restrictions.get(restName);
        if (restriction != null) {
            Value[] values = new Value[restriction.values.length];
            int type = acl.getRestrictionType(restName);
            for (int i=0; i<values.length; i++) {
                values[i] = vf.createValue(restriction.values[i], type);
            }
            if (restriction.isMulti) {
                mvRestrictions.put(restName, values);
            } else {
                svRestrictions.put(restName, values[0]);
            }
        }
    }
}
 
Example #6
Source File: Activator.java    From publick-sling-blog with Apache License 2.0 5 votes vote down vote up
/**
 * Create user groups for authors and testers.
 *
 * @param bundleContext The bundle context provided by the component.
 */
private void createGroups(BundleContext bundleContext){
    ServiceReference SlingRepositoryFactoryReference = bundleContext.getServiceReference(SlingRepository.class.getName());
    SlingRepository repository = (SlingRepository)bundleContext.getService(SlingRepositoryFactoryReference);

    Session session = null;

    if (repository != null) {
        try {
            session = repository.loginAdministrative(null);

            if (session != null && session instanceof JackrabbitSession) {
                UserManager userManager = ((JackrabbitSession)session).getUserManager();
                ValueFactory valueFactory = session.getValueFactory();

                Authorizable authors = userManager.getAuthorizable(PublickConstants.GROUP_ID_AUTHORS);

                if (authors == null) {
                    authors = userManager.createGroup(PublickConstants.GROUP_ID_AUTHORS);
                    authors.setProperty(GROUP_DISPLAY_NAME, valueFactory.createValue(PublickConstants.GROUP_DISPLAY_AUTHORS));
                }

                Authorizable testers = userManager.getAuthorizable(PublickConstants.GROUP_ID_TESTERS);

                if (testers == null) {
                    testers = userManager.createGroup(PublickConstants.GROUP_ID_TESTERS);
                    testers.setProperty(GROUP_DISPLAY_NAME, valueFactory.createValue(PublickConstants.GROUP_DISPLAY_TESTERS));
                }
            }
        } catch (RepositoryException e) {
            LOGGER.error("Could not get session", e);
        } finally {
            if (session != null && session.isLive()) {
                session.logout();
                session = null;
            }
        }
    }
}
 
Example #7
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 #8
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 #9
Source File: JcrTemplate.java    From mycollab with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @see org.springframework.extensions.jcr.JcrOperations#getValueFactory()
 */
@Override
public ValueFactory getValueFactory() {
    return execute(new JcrCallback<ValueFactory>() {
        /**
         * @see JcrCallback#doInJcr(javax.jcr.Session)
         */
        @Override
        public ValueFactory doInJcr(Session session) throws RepositoryException {
            return session.getValueFactory();
        }
    }, true);
}
 
Example #10
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 #11
Source File: ScriptStorageImpl.java    From APM with Apache License 2.0 5 votes vote down vote up
private Script saveScript(FileDescriptor descriptor, LaunchMetadata launchMetadata, boolean overwrite,
    ResourceResolver resolver) {
  Script result = null;
  try {
    final Session session = resolver.adaptTo(Session.class);
    final ValueFactory valueFactory = session.getValueFactory();
    final Binary binary = valueFactory.createBinary(descriptor.getInputStream());
    final Node saveNode = session.getNode(descriptor.getPath());

    final Node fileNode, contentNode;
    if (overwrite && saveNode.hasNode(descriptor.getName())) {
      fileNode = saveNode.getNode(descriptor.getName());
      contentNode = fileNode.getNode(JcrConstants.JCR_CONTENT);
    } else {
      fileNode = saveNode.addNode(generateFileName(descriptor.getName(), saveNode), JcrConstants.NT_FILE);
      contentNode = fileNode.addNode(JcrConstants.JCR_CONTENT, JcrConstants.NT_RESOURCE);
    }

    contentNode.setProperty(JcrConstants.JCR_DATA, binary);
    contentNode.setProperty(JcrConstants.JCR_ENCODING, SCRIPT_ENCODING.name());
    fileNode.addMixin(ScriptNode.APM_SCRIPT);
    fileNode.setProperty(ScriptNode.APM_LAUNCH_ENABLED, launchMetadata.isExecutionEnabled());
    setOrRemoveProperty(fileNode, ScriptNode.APM_LAUNCH_MODE, launchMetadata.getLaunchMode());
    setOrRemoveProperty(fileNode, ScriptNode.APM_LAUNCH_ENVIRONMENT, launchMetadata.getLaunchEnvironment());
    setOrRemoveProperty(fileNode, ScriptNode.APM_LAUNCH_HOOK, launchMetadata.getExecutionHook());
    setOrRemoveProperty(fileNode, ScriptNode.APM_LAUNCH_SCHEDULE, launchMetadata.getExecutionSchedule());
    removeProperty(fileNode, ScriptNode.APM_LAST_EXECUTED);
    JcrUtils.setLastModified(fileNode, Calendar.getInstance());
    session.save();
    result = scriptFinder.find(fileNode.getPath(), resolver);
  } catch (RepositoryException e) {
    LOG.error(e.getMessage(), e);
  }
  return result;
}
 
Example #12
Source File: PermissionActionHelper.java    From APM with Apache License 2.0 5 votes vote down vote up
public PermissionActionHelper(ValueFactory valueFactory, String path, List<String> permissions,
    Restrictions restrictions) {
  this.valueFactory = valueFactory;
  this.path = path;
  this.permissions = permissions;
  this.restrictions = restrictions;
}
 
Example #13
Source File: Restrictions.java    From APM with Apache License 2.0 5 votes vote down vote up
private Value[] createRestrictions(ValueFactory valueFactory, List<String> names)
    throws ValueFormatException {

  Value[] values = new Value[names.size()];
  for (int index = 0; index < names.size(); index++) {
    values[index] = valueFactory.createValue(names.get(index), PropertyType.NAME);
  }
  return values;
}
 
Example #14
Source File: Restrictions.java    From APM with Apache License 2.0 5 votes vote down vote up
private void addRestrictions(ValueFactory valueFactory, Map<String, Value[]> result, String key, List<String> names)
    throws ValueFormatException {

  if (names != null && !names.isEmpty()) {
    result.put(key, createRestrictions(valueFactory, names));
  }
}
 
Example #15
Source File: Restrictions.java    From APM with Apache License 2.0 5 votes vote down vote up
public Map<String, Value[]> getMultiValueRestrictions(ValueFactory valueFactory)
    throws ValueFormatException {

  Map<String, Value[]> result = new HashMap<>();
  addRestrictions(valueFactory, result, "rep:ntNames", ntNames);
  addRestrictions(valueFactory, result, "rep:itemNames", itemNames);
  return result;
}
 
Example #16
Source File: Restrictions.java    From APM with Apache License 2.0 5 votes vote down vote up
public Map<String, Value> getSingleValueRestrictions(ValueFactory valueFactory) {
  Map<String, Value> result = new HashMap<>();
  if (StringUtils.isNotBlank(glob)) {
    result.put("rep:glob", normalizeGlob(valueFactory));
  }
  return result;
}
 
Example #17
Source File: ContextImpl.java    From APM with Apache License 2.0 4 votes vote down vote up
@Override
public ValueFactory getValueFactory() throws RepositoryException {
  return session.getValueFactory();
}
 
Example #18
Source File: SessionImpl.java    From jackalope with Apache License 2.0 4 votes vote down vote up
@Override
public ValueFactory getValueFactory() throws UnsupportedRepositoryOperationException, RepositoryException {
    return new ValueFactoryImpl();
}
 
Example #19
Source File: FileArtifactHandler.java    From jackrabbit-filevault with Apache License 2.0 4 votes vote down vote up
private boolean importNtResource(ImportInfo info, Node content, Artifact artifact)
        throws RepositoryException, IOException {

    String path = content.getPath();
    boolean modified = false;
    if (explodeXml && !content.isNodeType(JcrConstants.NT_RESOURCE)) {
        // explode xml
        InputStream in = artifact.getInputStream();
        try {
            content.getSession().importXML(path, in, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);
            // can't really augment info here
        } finally {
            in.close();
        }
        modified = true;
    } else {
        ValueFactory factory = content.getSession().getValueFactory();
        Value value = factory.createValue(artifact.getInputStream());
        if (!content.hasProperty(JcrConstants.JCR_DATA)
                || !value.equals(content.getProperty(JcrConstants.JCR_DATA).getValue())) {
            content.setProperty(JcrConstants.JCR_DATA, value);
            modified = true;
        }

        // always update last modified if binary was modified (bug #22969)
        if (!content.hasProperty(JcrConstants.JCR_LASTMODIFIED) || modified) {
            Calendar lastMod = Calendar.getInstance();
            content.setProperty(JcrConstants.JCR_LASTMODIFIED, lastMod);
            modified = true;
        }

        if (!content.hasProperty(JcrConstants.JCR_MIMETYPE)) {
            String mimeType = artifact.getContentType();
            if (mimeType == null) {
                mimeType = Text.getName(artifact.getRelativePath(), '.');
                mimeType = MimeTypes.getMimeType(mimeType, MimeTypes.APPLICATION_OCTET_STREAM);
            }
            content.setProperty(JcrConstants.JCR_MIMETYPE, mimeType);
            modified = true;
        }
        if (content.isNew()) {
            // mark binary data as modified
            info.onCreated(path + "/" + JcrConstants.JCR_DATA);
            info.onNop(path);
        } else if (modified) {
            // mark binary data as modified
            info.onModified(path + "/" + JcrConstants.JCR_DATA);
            info.onModified(path);
        }
    }
    return modified;
}
 
Example #20
Source File: Restrictions.java    From APM with Apache License 2.0 4 votes vote down vote up
private Value normalizeGlob(ValueFactory valueFactory) {
  if (STRICT.equalsIgnoreCase(glob)) {
    return valueFactory.createValue(StringUtils.EMPTY);
  }
  return valueFactory.createValue(glob);
}
 
Example #21
Source File: SessionWrapper.java    From sling-whiteboard with Apache License 2.0 4 votes vote down vote up
@Override
public ValueFactory getValueFactory() throws UnsupportedRepositoryOperationException, RepositoryException {
    return this.wrappedSession.getValueFactory();
}
 
Example #22
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 #23
Source File: JcrModel1Operations.java    From mycollab with GNU Affero General Public License v3.0 2 votes vote down vote up
/**
 * @see javax.jcr.Session#getValueFactory()
 */
ValueFactory getValueFactory();
 
Example #24
Source File: Context.java    From APM with Apache License 2.0 votes vote down vote up
ValueFactory getValueFactory() throws RepositoryException;