javax.jcr.Repository Java Examples

The following examples show how to use javax.jcr.Repository. 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: AbstractSessionHolderProviderManager.java    From mycollab with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * @see org.springframework.extensions.jcr.SessionHolderProviderManager#getSessionProvider(Repository)
 */
public SessionHolderProvider getSessionProvider(Repository repository) {
    // graceful fallback
    if (repository == null)
        return defaultProvider;

    String key = repository.getDescriptor(Repository.REP_NAME_DESC);
    List<SessionHolderProvider> providers = getProviders();

    // search the provider
    for (int i = 0; i < providers.size(); i++) {
        SessionHolderProvider provider = providers.get(i);
        if (provider.acceptsRepository(key)) {
            if (LOG.isDebugEnabled())
                LOG.debug("specific SessionHolderProvider found for repository " + key);
            return provider;
        }
    }

    // no provider found - return the default one
    if (LOG.isDebugEnabled())
        LOG.debug("no specific SessionHolderProvider found for repository " + key + "; using the default one");
    return defaultProvider;
}
 
Example #2
Source File: VaultFsApp.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
protected void connect() {
    if (rep != null) {
        throw new ExecutionException("Already connected to " + getProperty(KEY_URI));
    } else {
        String uri = getProperty(KEY_DEFAULT_URI);
        try {
            rep = repProvider.getRepository(new RepositoryAddress(uri));
            setProperty(KEY_URI, uri);
            StringBuffer info = new StringBuffer();
            info.append(rep.getDescriptor(Repository.REP_NAME_DESC)).append(' ');
            info.append(rep.getDescriptor(Repository.REP_VERSION_DESC));
            log.info("Connected to {} ({})", uri, info.toString());
        } catch (Exception e) {
            rep = null;
            throw new ExecutionException("Error while connecting to " + uri, e);
        }
    }
}
 
Example #3
Source File: ImportTests.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
@Test
public void testSNSImport() throws IOException, RepositoryException, ConfigurationException {
    ZipArchive archive = new ZipArchive(getTempFile("/test-packages/test_sns.zip"));
    archive.open(true);
    Node rootNode = admin.getRootNode();
    ImportOptions opts = getDefaultOptions();
    Importer importer = new Importer(opts);
    importer.run(archive, rootNode);

    assertNodeExists("/tmp/testroot");
    assertNodeExists("/tmp/testroot/foo");
    assertProperty("/tmp/testroot/foo/name", "foo1");

    // only check for SNS nodes if SNS supported
    if (admin.getRepository().getDescriptorValue(Repository.NODE_TYPE_MANAGEMENT_SAME_NAME_SIBLINGS_SUPPORTED).getBoolean()) {
        assertNodeExists("/tmp/testroot/foo[2]");
        assertNodeExists("/tmp/testroot/foo[3]");
        assertProperty("/tmp/testroot/foo[2]/name", "foo2");
        assertProperty("/tmp/testroot/foo[3]/name", "foo3");
    } else {
        // otherwise nodes must not exist
        assertNodeMissing("/tmp/testroot/foo[2]");
        assertNodeMissing("/tmp/testroot/foo[3]");
    }

}
 
Example #4
Source File: RepositoryProvider.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
private Repository wrapLogger(Repository base,RepositoryAddress address) {
    try {
        Class clazz = getClass().getClassLoader().loadClass("org.apache.jackrabbit.jcrlog.RepositoryLogger");
        // just map all properties
        Properties props = new Properties();
        for (Object o: System.getProperties().keySet()) {
            String name = o.toString();
            if (name.startsWith("jcrlog.")) {
                props.put(name.substring("jcrlog.".length()), System.getProperty(name));
            }
        }
        Constructor c = clazz.getConstructor(Repository.class, Properties.class, String.class);
        return (Repository) c.newInstance(base, props, address.toString());
    } catch (Exception e) {
        log.error("Unable to initialize JCR logger: {}", e.toString());
        return null;
    }
}
 
Example #5
Source File: JcrSessionFactory.java    From mycollab with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * A toString representation of the Repository.
 * 
 * @return
 */
private String getRepositoryInfo() {
	// in case toString() is called before afterPropertiesSet()
	if (getRepository() == null)
		return "<N/A>";

	StringBuffer buffer = new StringBuffer();
	buffer.append(getRepository().getDescriptor(Repository.REP_NAME_DESC));
	buffer.append(" ");
	buffer.append(getRepository()
			.getDescriptor(Repository.REP_VERSION_DESC));
	return buffer.toString();
}
 
Example #6
Source File: JcrSessionFactory.java    From mycollab with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Constructor containing all the fields available.
 * 
 * @param repository
 * @param workspaceName
 * @param credentials
 * @param sessionHolderProviderManager
 */
public JcrSessionFactory(Repository repository, String workspaceName,
		Credentials credentials,
		SessionHolderProviderManager sessionHolderProviderManager) {
	this.repository = repository;
	this.workspaceName = workspaceName;
	this.credentials = credentials;
	this.sessionHolderProviderManager = sessionHolderProviderManager;
}
 
Example #7
Source File: MockedResourceResolver.java    From sling-samples with Apache License 2.0 5 votes vote down vote up
public MockedResourceResolver(Repository repositoryOrNull) throws RepositoryException {
	if (repositoryOrNull==null) {
		this.repository = RepositoryProvider.instance().getRepository();
	} else {
		this.repository = repositoryOrNull;
	}
}
 
Example #8
Source File: VltContext.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
public Session login(RepositoryAddress mountpoint) throws RepositoryException {
    Repository rep = repProvider.getRepository(mountpoint);
    Credentials creds = credsProvider.getCredentials(mountpoint);
    Session s = rep.login(creds);
    // hack to store credentials
    credsProvider.storeCredentials(mountpoint, creds);
    return s;
}
 
Example #9
Source File: TestCugHandling.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
private static Repository createRepository() {
    SecurityProvider securityProvider = createSecirityProvider();
    QueryEngineSettings queryEngineSettings = new QueryEngineSettings();
    queryEngineSettings.setFailTraversal(true);
    Jcr jcr = new Jcr();
    jcr.with(securityProvider);
    jcr.with(queryEngineSettings);
    return jcr.createRepository();
}
 
Example #10
Source File: RepositoryProvider.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
private Repository createRepository(RepositoryAddress address)
        throws RepositoryException {
    ServiceLoader<RepositoryFactory> loader = ServiceLoader.load(RepositoryFactory.class);
    Iterator<RepositoryFactory> iter = loader.iterator();
    Set<String> supported = new HashSet<String>();
    while (iter.hasNext()) {
        RepositoryFactory fac = iter.next();
        supported.addAll(fac.getSupportedSchemes());
        Repository rep = fac.createRepository(address);
        if (rep != null) {
            // wrap JCR logger
            if (Boolean.getBoolean("jcrlog.sysout") || System.getProperty("jcrlog.file") != null) {
                Repository wrapped = wrapLogger(rep, address);
                if (wrapped != null) {
                    log.info("Enabling JCR Logger.");
                    rep = wrapped;
                }
            }
            return rep;
        }
    }
    StringBuffer msg = new StringBuffer("URL scheme ");
    msg.append(address.getURI().getScheme());
    msg.append(" not supported. only");
    for (String s: supported) {
        msg.append(" ").append(s);
    }
    throw new RepositoryException(msg.toString());
}
 
Example #11
Source File: RepositoryProvider.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
public Repository getRepository(RepositoryAddress address)
        throws RepositoryException {
    Repository rep = repos.get(address);
    if (rep == null) {
        rep = createRepository(address);
        repos.put(address, rep);
    }
    return rep;
}
 
Example #12
Source File: AggregateManagerImpl.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new artifact manager that is rooted at the given path using
 * the provided repository, credentials and workspace to create the
 * session.
 *
 * @param config fs config
 * @param wspFilter the workspace filter
 * @param rep the jcr repository
 * @param credentials the credentials
 * @param mountpoint the address of the mountpoint
 * @return an artifact manager
 * @throws RepositoryException if an error occurs.
 */
public static AggregateManager mount(VaultFsConfig config,
                                     WorkspaceFilter wspFilter,
                                     Repository rep,
                                     Credentials credentials,
                                     RepositoryAddress mountpoint)
throws RepositoryException {
    if (config == null) {
        config = getDefaultConfig();
    }
    if (wspFilter == null) {
        wspFilter = getDefaultWorkspaceFilter();
    }
    Node rootNode;
    String wspName = mountpoint.getWorkspace();
    try {
        rootNode = rep.login(credentials, wspName).getNode(mountpoint.getPath());
    } catch (LoginException e) {
        if (wspName == null) {
            // try again with default workspace
            // todo: make configurable
            rootNode = rep.login(credentials, "crx.default").getNode(mountpoint.getPath());
        } else {
            throw e;
        }
    }
    return new AggregateManagerImpl(config, wspFilter, mountpoint, rootNode, true);
}
 
Example #13
Source File: CheckPassword.java    From APM with Apache License 2.0 5 votes vote down vote up
private boolean checkLogin(Repository repository) throws RepositoryException {
  boolean loginSuccessful = true;
  Credentials credentials = new SimpleCredentials(userId, userPassword.toCharArray());
  try {
    repository.login(credentials).logout();
  } catch (LoginException e) {
    loginSuccessful = false;
  }
  return loginSuccessful;
}
 
Example #14
Source File: UIEERepositoryDirectoryIT.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
@Override
public void setApplicationContext( final ApplicationContext applicationContext ) throws BeansException {
  SessionFactory jcrSessionFactory = (SessionFactory) applicationContext.getBean( "jcrSessionFactory" );
  testJcrTemplate = new JcrTemplate( jcrSessionFactory );
  testJcrTemplate.setAllowCreate( true );
  testJcrTemplate.setExposeNativeSession( true );
  repositoryAdminUsername = (String) applicationContext.getBean( "repositoryAdminUsername" );
  superAdminRoleName = (String) applicationContext.getBean( "superAdminAuthorityName" );
  sysAdminUserName = (String) applicationContext.getBean( "superAdminUserName" );
  tenantAuthenticatedRoleName = (String) applicationContext.getBean( "singleTenantAuthenticatedAuthorityName" );
  singleTenantAdminRoleName = (String) applicationContext.getBean( "singleTenantAdminAuthorityName" );
  tenantManager = (ITenantManager) applicationContext.getBean( "tenantMgrProxy" );
  roleBindingDaoTarget =
      (IRoleAuthorizationPolicyRoleBindingDao) applicationContext
          .getBean( "roleAuthorizationPolicyRoleBindingDaoTarget" );
  authorizationPolicy = (IAuthorizationPolicy) applicationContext.getBean( "authorizationPolicy" );
  repo = (IUnifiedRepository) applicationContext.getBean( "unifiedRepository" );
  userRoleDao = (IUserRoleDao) applicationContext.getBean( "userRoleDao" );
  repositoryFileDao = (IRepositoryFileDao) applicationContext.getBean( "repositoryFileDao" );
  testUserRoleDao = userRoleDao;
  repositoryLifecyleManager =
      (IBackingRepositoryLifecycleManager) applicationContext.getBean( "defaultBackingRepositoryLifecycleManager" );
  txnTemplate = (TransactionTemplate) applicationContext.getBean( "jcrTransactionTemplate" );
  TestPrincipalProvider.userRoleDao = testUserRoleDao;
  TestPrincipalProvider.adminCredentialsStrategy =
      (CredentialsStrategy) applicationContext.getBean( "jcrAdminCredentialsStrategy" );
  TestPrincipalProvider.repository = (Repository) applicationContext.getBean( "jcrRepository" );
}
 
Example #15
Source File: PurRepositoryTestBase.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
@Override
public void setApplicationContext( ApplicationContext applicationContext ) throws BeansException {
  unifiedRepository = applicationContext.getBean( "unifiedRepository", IUnifiedRepository.class );
  tenantManager = applicationContext.getBean( "tenantMgrProxy", ITenantManager.class );
  userRoleDao = applicationContext.getBean( "userRoleDao", IUserRoleDao.class );
  authorizationPolicy = applicationContext.getBean( "authorizationPolicy", IAuthorizationPolicy.class );
  roleBindingDaoTarget =
      (IRoleAuthorizationPolicyRoleBindingDao) applicationContext
          .getBean( "roleAuthorizationPolicyRoleBindingDaoTarget" );

  SessionFactory jcrSessionFactory = (SessionFactory) applicationContext.getBean( "jcrSessionFactory" );
  testJcrTemplate = new JcrTemplate( jcrSessionFactory );
  testJcrTemplate.setAllowCreate( true );
  testJcrTemplate.setExposeNativeSession( true );
  txnTemplate = applicationContext.getBean( "jcrTransactionTemplate", TransactionTemplate.class );
  repositoryFileDao = (IRepositoryFileDao) applicationContext.getBean( "repositoryFileDao" );

  superAdminRole = applicationContext.getBean( "superAdminAuthorityName", String.class );
  repositoryAdmin = applicationContext.getBean( "repositoryAdminUsername", String.class );
  systemAdmin = (String) applicationContext.getBean( "superAdminUserName" );
  tenantAdminRole = applicationContext.getBean( "singleTenantAdminAuthorityName", String.class );
  tenantAuthenticatedRole = applicationContext.getBean( "singleTenantAuthenticatedAuthorityName", String.class );

  TestPrincipalProvider.userRoleDao = userRoleDao;
  TestPrincipalProvider.adminCredentialsStrategy =
      (CredentialsStrategy) applicationContext.getBean( "jcrAdminCredentialsStrategy" );
  TestPrincipalProvider.repository = (Repository) applicationContext.getBean( "jcrRepository" );

  doSetApplicationContext( applicationContext );
}
 
Example #16
Source File: PurRepositoryIT.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
@Override
public void setApplicationContext( final ApplicationContext applicationContext ) throws BeansException {
  SessionFactory jcrSessionFactory = (SessionFactory) applicationContext.getBean( "jcrSessionFactory" );
  testJcrTemplate = new JcrTemplate( jcrSessionFactory );
  testJcrTemplate.setAllowCreate( true );
  testJcrTemplate.setExposeNativeSession( true );
  repositoryAdminUsername = (String) applicationContext.getBean( "repositoryAdminUsername" );
  superAdminRoleName = (String) applicationContext.getBean( "superAdminAuthorityName" );
  sysAdminUserName = (String) applicationContext.getBean( "superAdminUserName" );
  tenantAuthenticatedRoleName = (String) applicationContext.getBean( "singleTenantAuthenticatedAuthorityName" );
  singleTenantAdminRoleName = (String) applicationContext.getBean( "singleTenantAdminAuthorityName" );
  tenantManager = (ITenantManager) applicationContext.getBean( "tenantMgrProxy" );
  roleBindingDaoTarget =
      (IRoleAuthorizationPolicyRoleBindingDao) applicationContext
          .getBean( "roleAuthorizationPolicyRoleBindingDaoTarget" );
  authorizationPolicy = (IAuthorizationPolicy) applicationContext.getBean( "authorizationPolicy" );
  repo = (IUnifiedRepository) applicationContext.getBean( "unifiedRepository" );
  userRoleDao = (IUserRoleDao) applicationContext.getBean( "userRoleDao" );
  repositoryFileDao = (IRepositoryFileDao) applicationContext.getBean( "repositoryFileDao" );
  testUserRoleDao = userRoleDao;
  repositoryLifecyleManager =
      (IBackingRepositoryLifecycleManager) applicationContext.getBean( "defaultBackingRepositoryLifecycleManager" );
  txnTemplate = (TransactionTemplate) applicationContext.getBean( "jcrTransactionTemplate" );
  TestPrincipalProvider.userRoleDao = testUserRoleDao;
  TestPrincipalProvider.adminCredentialsStrategy =
      (CredentialsStrategy) applicationContext.getBean( "jcrAdminCredentialsStrategy" );
  TestPrincipalProvider.repository = (Repository) applicationContext.getBean( "jcrRepository" );
}
 
Example #17
Source File: OakDescriptorSourceTest.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultJcrDescriptors_filtered() throws Exception {
    registerOakDescriptorSource(Repository.REP_NAME_DESC);
    assertNotNull(source.getCapabilities());
    assertEquals("Apache Jackrabbit Oak", source.getCapabilities().get(Repository.REP_NAME_DESC));
    // Repository.REP_VENDOR_DESC is not exposed, so should return null
    assertNull(source.getCapabilities().get(Repository.REP_VENDOR_DESC));
}
 
Example #18
Source File: OakDescriptorSourceTest.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultJcrDescriptors_listed() throws Exception {
    registerOakDescriptorSource(Repository.REP_NAME_DESC, Repository.REP_VENDOR_DESC);
    assertNotNull(source.getCapabilities());
    assertEquals("Apache Jackrabbit Oak", source.getCapabilities().get(Repository.REP_NAME_DESC));
    assertEquals("The Apache Software Foundation", source.getCapabilities().get(Repository.REP_VENDOR_DESC));
}
 
Example #19
Source File: ConfirmedOrdersObserver.java    From sling-samples with Apache License 2.0 5 votes vote down vote up
protected void activate(ComponentContext context)  throws Exception {
    session = repository.loginAdministrative(null);
    
    // Listen for changes to our orders
    if (repository.getDescriptor(Repository.OPTION_OBSERVATION_SUPPORTED).equals("true")) {
        observationManager = session.getWorkspace().getObservationManager();
        final String[] types = { "nt:unstructured" };
        final boolean isDeep = true;
        final boolean noLocal = true;
        final String path = SlingbucksConstants.ORDERS_PATH;
        observationManager.addEventListener(this, Event.PROPERTY_CHANGED | Event.PROPERTY_ADDED, path, isDeep, null, types, noLocal);
        log.info("Observing property changes to {} nodes under {}", Arrays.asList(types), path);
    }
    
}
 
Example #20
Source File: MockedResourceResolver.java    From sling-samples with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <AdapterType> AdapterType adaptTo(Class<AdapterType> type) {
    if (type.equals(Session.class)) {
        try {
            return (AdapterType) getSession();
        } catch (RepositoryException e) {
            throw new RuntimeException("RepositoryException: " + e, e);
        }
    } else if (type.equals(Repository.class)) {
    	return (AdapterType) getRepository();
    }
    throw new UnsupportedOperationException("Not implemented");
}
 
Example #21
Source File: SessionImpl.java    From jackalope with Apache License 2.0 5 votes vote down vote up
public SessionImpl(Repository repository) {
    this.repository = repository;
    try {
        addItem(new NodeImpl(this, "/"));
    }
    catch (RepositoryException re) { /* can't happen */ }
    save();
}
 
Example #22
Source File: ThumbnailGenerator.java    From sling-samples with Apache License 2.0 5 votes vote down vote up
protected void activate(ComponentContext context)  throws Exception {
    supportedMimeTypes.put("image/jpeg", ".jpg");
       supportedMimeTypes.put("image/png", ".png");

       String contentPath = (String)context.getProperties().get(CONTENT_PATH_PROPERTY);

	session = repository.loginAdministrative(null);
	if (repository.getDescriptor(Repository.OPTION_OBSERVATION_SUPPORTED).equals("true")) {
		observationManager = session.getWorkspace().getObservationManager();
		String[] types = { "nt:file" };
		observationManager.addEventListener(this, Event.NODE_ADDED, contentPath, true, null, types, false);
	}
}
 
Example #23
Source File: JcrUtils.java    From mycollab with GNU Affero General Public License v3.0 4 votes vote down vote up
public static boolean supportsSQLQuery(Repository repository) {
    return "true".equals(repository.getDescriptor(Repository.OPTION_QUERY_SQL_SUPPORTED));
}
 
Example #24
Source File: TransactionAwareRepository.java    From mycollab with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * @see org.springframework.beans.factory.FactoryBean#getObjectType()
 */
public Class<Repository> getObjectType() {
    return Repository.class;
}
 
Example #25
Source File: CacheableSessionHolderProviderManager.java    From mycollab with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * @see org.springframework.extensions.jcr.util.CachingMapDecorator#create(java.lang.Object)
 */
@Override
protected SessionHolderProvider create(Repository key) {
    return parentLookup(key);
}
 
Example #26
Source File: CacheableSessionHolderProviderManager.java    From mycollab with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Overwrite the method to provide caching.
 * @see org.springframework.extensions.jcr.support.AbstractSessionHolderProviderManager#getSessionProvider(Repository)
 */
@Override
public SessionHolderProvider getSessionProvider(Repository repository) {
    return providersCache.get(repository);
}
 
Example #27
Source File: JcrUtils.java    From mycollab with GNU Affero General Public License v3.0 4 votes vote down vote up
public static boolean supportsLevel2(Repository repository) {
    return "true".equals(repository.getDescriptor(Repository.LEVEL_2_SUPPORTED));
}
 
Example #28
Source File: JcrUtils.java    From mycollab with GNU Affero General Public License v3.0 4 votes vote down vote up
public static boolean supportsTransactions(Repository repository) {
    return "true".equals(repository.getDescriptor(Repository.OPTION_TRANSACTIONS_SUPPORTED));
}
 
Example #29
Source File: JcrUtils.java    From mycollab with GNU Affero General Public License v3.0 4 votes vote down vote up
public static boolean supportsVersioning(Repository repository) {
    return "true".equals(repository.getDescriptor(Repository.OPTION_VERSIONING_SUPPORTED));
}
 
Example #30
Source File: JcrUtils.java    From mycollab with GNU Affero General Public License v3.0 4 votes vote down vote up
public static boolean supportsObservation(Repository repository) {
    return "true".equals(repository.getDescriptor(Repository.OPTION_OBSERVATION_SUPPORTED));
}