Java Code Examples for javax.jcr.Session#logout()

The following examples show how to use javax.jcr.Session#logout() . These examples are extracted from open source projects. 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
@Test
public void testGetPackageRootNoRootAccess() throws Exception {
    Node packageRoot = packMgr.getPackageRoot();

    // TODO: maybe rather change the setup of the test-base to not assume that everyone has full read-access
    AccessControlManager acMgr = admin.getAccessControlManager();
    JackrabbitAccessControlList acl = AccessControlUtils.getAccessControlList(acMgr, "/");
    acMgr.removePolicy(acl.getPath(), acl);

    AccessControlUtils.getAccessControlList(acMgr, "/etc/packages");
    AccessControlUtils.allow(packageRoot, org.apache.jackrabbit.oak.spi.security.principal.EveryonePrincipal.NAME, javax.jcr.security.Privilege.JCR_READ);

    admin.save();

    Session anonymous = repository.login(new GuestCredentials());
    try {
        assertFalse(anonymous.nodeExists("/"));
        assertFalse(anonymous.nodeExists("/etc"));
        assertTrue(anonymous.nodeExists("/etc/packages"));

        JcrPackageManagerImpl jcrPackageManager = new JcrPackageManagerImpl(anonymous, new String[0]);
        jcrPackageManager.getPackageRoot(false);
    } finally {
        anonymous.logout();
    }
}
 
Example 2
@Override
protected void registerNodeTypes() throws Exception {
    LOG.info("Register node types");
    Session session = getSession();
    final String[] jcrNamespaces = session.getWorkspace().getNamespaceRegistry().getPrefixes();
    boolean createNamespace = true;
    for (String jcrNamespace : jcrNamespaces) {
        if (jcrNamespace.equals("mycollab")) {
            createNamespace = false;
            LOG.debug("Jackrabbit OCM namespace exists.");
        }
    }
    if (createNamespace) {
        session.getWorkspace().getNamespaceRegistry()
                .registerNamespace("mycollab", "http://www.esofthead.com/mycollab");
        LOG.debug("Successfully created Mycollab content namespace.");
    }
    if (session.getRootNode() == null) {
        throw new ContentException("Jcr session setup not successful.");
    }

    NodeTypeManager manager = session.getWorkspace().getNodeTypeManager();
    manager.registerNodeType(createMyCollabContentType(manager), true);
    manager.registerNodeType(createMyCollabFolderType(manager), true);
    session.logout();
}
 
Example 3
@Test
public void testNotAdminUser() throws Exception {
    JackrabbitSession jackrabbitSession = (JackrabbitSession) admin;
    Authorizable vip = jackrabbitSession.getUserManager().getAuthorizable(TEST_USER);
    assertNull("test user must not exist", vip);

    jackrabbitSession.getUserManager().createUser(TEST_USER, TEST_USER);
    admin.save();

    Session session = repository.login(new SimpleCredentials(TEST_USER, TEST_USER.toCharArray()));
    try {
        assertFalse(
                "\"" + TEST_USER + "\" is not admin/system and doesn't belong to administrators thus shouldn't have admin permissions",
                AdminPermissionChecker.hasAdministrativePermissions(session));
    } finally {
        session.logout();
    }
}
 
Example 4
@Test
public void testAdminGroup() throws Exception {
    JackrabbitSession jackrabbitSession = (JackrabbitSession) admin;
    Authorizable admins = jackrabbitSession.getUserManager().getAuthorizable("administrators");
    if (admins == null) {
        admins = jackrabbitSession.getUserManager().createGroup("administrators");
    }
    Group adminsGroup = (Group) admins;
    User testUser = (User) jackrabbitSession.getUserManager().getAuthorizable(TEST_USER);
    if (testUser == null) {
        testUser = jackrabbitSession.getUserManager().createUser(TEST_USER, TEST_USER);
    }
    adminsGroup.addMember(testUser);
    admin.save();
    Session session = repository.login(new SimpleCredentials(TEST_USER, TEST_USER.toCharArray()));
    try {
        assertTrue(
                "user \"" + TEST_USER + "\" has been added to administrators group thus should have admin permissions",
                AdminPermissionChecker.hasAdministrativePermissions(session));
    } finally {
        session.logout();
    }
}
 
Example 5
@Test
public void testAdditionalAdminUser() throws AccessDeniedException, UnsupportedRepositoryOperationException, RepositoryException {
    JackrabbitSession jackrabbitSession = (JackrabbitSession) admin;
    Authorizable vip = jackrabbitSession.getUserManager().getAuthorizable(TEST_USER);
    assertNull("test user must not exist", vip);

    jackrabbitSession.getUserManager().createUser(TEST_USER, TEST_USER);
    admin.save();

    Session session = repository.login(new SimpleCredentials(TEST_USER, TEST_USER.toCharArray()));
    try {
        assertTrue(
                "\"" + TEST_USER + "\" is additional admin/system thus should have admin permissions",
                AdminPermissionChecker.hasAdministrativePermissions(session, TEST_USER));
    } finally {
        session.logout();
    }
}
 
Example 6
@Test
public void testAdditionalAdminGroup() throws Exception {
    JackrabbitSession jackrabbitSession = (JackrabbitSession) admin;
    Authorizable admins = jackrabbitSession.getUserManager().getAuthorizable("myadmins");
    if (admins == null) {
        admins = jackrabbitSession.getUserManager().createGroup("myadmins");
    }
    Group adminsGroup = (Group) admins;
    User testUser = (User) jackrabbitSession.getUserManager().getAuthorizable(TEST_USER);
    if (testUser == null) {
        testUser = jackrabbitSession.getUserManager().createUser(TEST_USER, TEST_USER);
    }
    adminsGroup.addMember(testUser);
    admin.save();
    Session session = repository.login(new SimpleCredentials(TEST_USER, TEST_USER.toCharArray()));
    try {
        assertTrue(
                "user \"" + TEST_USER + "\" has been added to additional administrators group thus should have admin permissions",
                AdminPermissionChecker.hasAdministrativePermissions(session, "myadmins"));
    } finally {
        session.logout();
    }
}
 
Example 7
public void two() {
    Session session = null;
    try {
        session = repository.loginAdministrative(null);
    } catch (RepositoryException e) {
        e.printStackTrace();
    } finally {
        if (session != null && session.isLive()) {
            session.logout();
        }
    }
}
 
Example 8
public void three() {
    Session session = null;
    try {
        session = repository.loginService(null, null);
    } catch (RepositoryException e) {
        e.printStackTrace();
    } finally {
        if (session != null && session.isLive()) {
            session.logout();
        }
    }
}
 
Example 9
public void one() {
    Session session = null;
    try {
        session = createAdminSession();
    } finally {
        if (session != null && session.isLive()) {
            session.logout();
        }
    }
}
 
Example 10
Source Project: publick-sling-blog   File: Activator.java    License: 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 11
private static void dump(final File repoDirectory) throws Exception {
    final TransientRepository repository = getTransientRepository(repoDirectory);
    try {
        final Session session = getSession(repository);
        message("Root node dump:");
        dump(session.getRootNode());
        session.logout();
    } finally {
        repository.shutdown();
    }
}
 
Example 12
@Test
public void testImportWithoutRootAndTmpAccess() throws IOException, RepositoryException, ConfigurationException {
    Assume.assumeTrue(!isOak());

    // Create test user
    UserManager userManager = ((JackrabbitSession)admin).getUserManager();
    String userId = "user1";
    String userPwd = "pwd1";
    User user1 = userManager.createUser(userId, userPwd);
    Principal principal1 = user1.getPrincipal();

    // Create /tmp folder
    admin.getRootNode().addNode("tmp").addNode("foo");
    admin.save();

    // Setup test user ACLs such that the
    // root node is not accessible
    AccessControlUtils.addAccessControlEntry(admin, null, principal1, new String[]{"jcr:namespaceManagement","jcr:nodeTypeDefinitionManagement"}, true);
    AccessControlUtils.addAccessControlEntry(admin, "/", principal1, new String[]{"jcr:all"}, false);
    AccessControlUtils.addAccessControlEntry(admin, "/tmp/foo", principal1, new String[]{"jcr:all"}, true);
    admin.save();

    // Import with a session associated to the test user
    Session session = repository.login(new SimpleCredentials(userId, userPwd.toCharArray()));
    ZipArchive archive = new ZipArchive(getTempFile("/test-packages/tmp_foo.zip"));
    archive.open(true);
    ImportOptions opts = getDefaultOptions();
    Importer importer = new Importer(opts);
    importer.run(archive, session, "/");
    session.logout();

    assertNodeExists("/tmp/foo/bar/tobi");
}
 
Example 13
/**
 * Installs a package with an install hook and a not allowed user
 */
@Test
public void testHookWithNotAllowedNonAdminUser() throws RepositoryException, IOException, PackageException {
    if (admin.nodeExists("/testroot")) {
        admin.getNode("/testroot").remove();
    }
    admin.getRootNode().addNode("testroot", "nt:unstructured").addNode("testnode", "nt:unstructured");
    admin.save();
    
    // Create test user
    UserManager userManager = ((JackrabbitSession)admin).getUserManager();
    String userId = "user1";
    String userPwd = "pwd1";
    User user1 = userManager.createUser(userId, userPwd);
    Principal principal1 = user1.getPrincipal();
    
    // Setup test user ACLs that there are no restrictions
    AccessControlUtils.addAccessControlEntry(admin, null, principal1, new String[]{"jcr:namespaceManagement","jcr:nodeTypeDefinitionManagement"}, true);
    AccessControlUtils.addAccessControlEntry(admin, "/", principal1, new String[]{"jcr:all"}, true);
    admin.save();
    
    Session userSession = repository.login(new SimpleCredentials(userId, userPwd.toCharArray()));
    try {
        packMgr = new JcrPackageManagerImpl(userSession, new String[0], null, null);

        PackageEventDispatcherImpl dispatcher = new PackageEventDispatcherImpl();
        dispatcher.bindPackageEventListener(new ActivityLog(), Collections.singletonMap("component.id", (Object) "1234"));
        packMgr.setDispatcher(dispatcher);
        
        JcrPackage pack = packMgr.upload(getStream("/test-packages/test_hook.zip"), false);
        assertNotNull(pack);
        thrown.expect(PackageException.class);
        thrown.expectMessage("Package extraction requires admin session as it has a hook");
        packMgr.getInternalRegistry().installPackage(userSession, new JcrRegisteredPackage(pack), getDefaultOptions(), true);
        
    
    } finally {
        userSession.logout();
    }
}
 
Example 14
/**
 * Installs a package with an install hook and an explicitly allowed user
 */
@Test
public void testHookWithAllowedNonAdminUser() throws RepositoryException, IOException, PackageException {
    if (admin.nodeExists("/testroot")) {
        admin.getNode("/testroot").remove();
    }
    admin.getRootNode().addNode("testroot", "nt:unstructured").addNode("testnode", "nt:unstructured");
    admin.save();
    
    // Create test user
    UserManager userManager = ((JackrabbitSession)admin).getUserManager();
    String userId = "user1";
    String userPwd = "pwd1";
    User user1 = userManager.createUser(userId, userPwd);
    Principal principal1 = user1.getPrincipal();
    
    // Setup test user ACLs that there are no restrictions
    AccessControlUtils.addAccessControlEntry(admin, null, principal1, new String[]{"jcr:namespaceManagement","jcr:nodeTypeDefinitionManagement"}, true);
    AccessControlUtils.addAccessControlEntry(admin, "/", principal1, new String[]{"jcr:all"}, true);
    admin.save();
    
    Session userSession = repository.login(new SimpleCredentials(userId, userPwd.toCharArray()));
    try {
        packMgr = new JcrPackageManagerImpl(userSession, new String[0], new String[] {"user1"}, null);

        PackageEventDispatcherImpl dispatcher = new PackageEventDispatcherImpl();
        dispatcher.bindPackageEventListener(new ActivityLog(), Collections.singletonMap("component.id", (Object) "1234"));
        packMgr.setDispatcher(dispatcher);
        
        JcrPackage pack = packMgr.upload(getStream("/test-packages/test_hook.zip"), false);
        assertNotNull(pack);
        packMgr.getInternalRegistry().installPackage(userSession, new JcrRegisteredPackage(pack), getDefaultOptions(), true);
        assertTrue(admin.propertyExists("/testroot/hook-example"));
        
    } finally {
        userSession.logout();
    }
}
 
Example 15
/**
 * Tests if package installation works w/o RW access to / and /tmp.
 * this currently fails, due to the creation of the snapshot.
 * also see {@link TestNoRootAccessExport#exportNoRootAccess()}
 */
@Test
@Ignore("JCRVLT-100")
public void testInstallWithoutRootAndTmpAccess() throws IOException, RepositoryException, ConfigurationException, PackageException {
    JcrPackage pack = packMgr.upload(getStream("/test-packages/tmp_foo.zip"), true, true);
    assertNotNull(pack);
    assertTrue(pack.isValid());
    PackageId id = pack.getPackage().getId();
    pack.close();

    // Create test user
    UserManager userManager = ((JackrabbitSession)admin).getUserManager();
    String userId = "user1";
    String userPwd = "pwd1";
    User user1 = userManager.createUser(userId, userPwd);
    Principal principal1 = user1.getPrincipal();

    // Create /tmp folder
    admin.getRootNode().addNode("tmp").addNode("foo");
    admin.save();

    // Setup test user ACLs such that the
    // root node is not accessible
    AccessControlUtils.addAccessControlEntry(admin, null, principal1, new String[]{"jcr:namespaceManagement","jcr:nodeTypeDefinitionManagement"}, true);
    AccessControlUtils.addAccessControlEntry(admin, "/", principal1, new String[]{"jcr:all"}, false);
    AccessControlUtils.addAccessControlEntry(admin, ((JcrPackageRegistry)packMgr.getRegistry()).getPackRootPaths()[0], principal1, new String[]{"jcr:all"}, true);
    AccessControlUtils.addAccessControlEntry(admin, "/tmp/foo", principal1, new String[]{"jcr:all"}, true);
    admin.save();

    Session session = repository.login(new SimpleCredentials(userId, userPwd.toCharArray()));
    JcrPackageManagerImpl userPackMgr = new JcrPackageManagerImpl(session, new String[0], null, null);
    pack = userPackMgr.open(id);
    ImportOptions opts = getDefaultOptions();
    pack.install(opts);
    pack.close();
    session.logout();

    assertNodeExists("/tmp/foo/bar/tobi");
}
 
Example 16
/**
 * Test if package extraction works w/o RW access to / and /tmp.
 */
@Test
public void testExtractWithoutRootAndTmpAccess() throws IOException, RepositoryException, ConfigurationException, PackageException {
    Assume.assumeTrue(!isOak());

    JcrPackage pack = packMgr.upload(getStream("/test-packages/tmp_foo.zip"), true, true);
    assertNotNull(pack);
    assertTrue(pack.isValid());
    PackageId id = pack.getPackage().getId();
    pack.close();

    // Create test user
    UserManager userManager = ((JackrabbitSession)admin).getUserManager();
    String userId = "user1";
    String userPwd = "pwd1";
    User user1 = userManager.createUser(userId, userPwd);
    Principal principal1 = user1.getPrincipal();

    // Create /tmp folder
    admin.getRootNode().addNode("tmp").addNode("foo");
    admin.save();

    // Setup test user ACLs such that the
    // root node is not accessible
    AccessControlUtils.addAccessControlEntry(admin, null, principal1, new String[]{"jcr:namespaceManagement","jcr:nodeTypeDefinitionManagement"}, true);
    AccessControlUtils.addAccessControlEntry(admin, "/", principal1, new String[]{"jcr:all"}, false);
    AccessControlUtils.addAccessControlEntry(admin, ((JcrPackageRegistry)packMgr.getRegistry()).getPackRootPaths()[0], principal1, new String[]{"jcr:all"}, true);
    AccessControlUtils.addAccessControlEntry(admin, "/tmp/foo", principal1, new String[]{"jcr:all"}, true);
    admin.save();

    Session session = repository.login(new SimpleCredentials(userId, userPwd.toCharArray()));
    JcrPackageManagerImpl userPackMgr = new JcrPackageManagerImpl(session, new String[0], null, null);
    pack = userPackMgr.open(id);
    ImportOptions opts = getDefaultOptions();
    pack.extract(opts);
    pack.close();
    session.logout();

    assertNodeExists("/tmp/foo/bar/tobi");
}
 
Example 17
Source Project: jackrabbit-filevault   File: Sync.java    License: Apache License 2.0 5 votes vote down vote up
public void run(VltContext ctx) throws VltException {
    if (mountPoint == null) {
        mountPoint = ctx.getMountpoint();
    }
    if (mountPoint == null) {
        throw ctx.error(ctx.getCwd().getAbsolutePath(), "No remote specified and not in vlt checkout.");
    }

    // currently we just read the config node, assuming it's at the correct location
    Session s = null;
    try {
        s = ctx.login(mountPoint);
        switch (cmd) {
            case STATUS:
            case ST:
                status(ctx, s);
                break;
            case REGISTER:
                register(ctx, s, null);
                break;
            case UNREGISTER:
                unregister(ctx, s);
                break;
            case INSTALL:
                install(ctx, s);
                break;
            case INIT:
                init(ctx, s);
        }
    } catch (RepositoryException e) {
        throw new VltException("Error while performing command", e);
    } finally {
        if (s != null) {
            s.logout();
        }
    }
}
 
Example 18
@Test
public void testJcrProducer() throws Exception {

    WildFlyCamelContext camelctx = new WildFlyCamelContext();
    camelctx.getNamingContext().bind("repository", repository);

    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            getContext().setUseBreadcrumb(false);
            from("direct:a").to("jcr://user:[email protected]/home/test");
        }
    });

    camelctx.start();
    try {
        String content = "<hello>world!</hello>";
        HashMap<String, Object> headers = new HashMap<>();
        headers.put(JcrConstants.JCR_NODE_NAME, "node");
        headers.put("my.contents.property", content);
        ProducerTemplate template = camelctx.createProducerTemplate();
        String result = template.requestBodyAndHeaders("direct:a", null, headers, String.class);
        Assert.assertNotNull(result);
        Session session = openSession();
        try {
            Node node = session.getNodeByIdentifier(result);
            Assert.assertEquals("/home/test/node", node.getPath());
            Assert.assertEquals(content, node.getProperty("my.contents.property").getString());
        } finally {
            session.logout();
        }
    } finally {
        camelctx.close();
    }
}
 
Example 19
/**
 * Close the given Session, created via the given repository, if it is not managed externally (i.e. not
 * bound to the thread).
 * @param session the Jcr Session to close
 * @param sessionFactory JcrSessionFactory that the Session was created with (can be null)
 */
public static void releaseSession(Session session, SessionFactory sessionFactory) {
    if (session == null) {
        return;
    }
    // Only close non thread bound Sessions.
    if (!isSessionThreadBound(session, sessionFactory)) {
        LOG.debug("Closing JCR Session");
        session.logout();
    }
}
 
Example 20
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");

    JSONArray solrDocs = new JSONArray();

    final String slingResourceType = getSlingResourceType(request);

    if (StringUtils.isEmpty(slingResourceType)) {
        response.getWriter().write(solrDocs.toJSONString());
        return;
    }

    Map<String, String> params = new HashMap<String, String>();
    params.put("path", "/content/geometrixx-media");
    params.put("type", "cq:PageContent");
    params.put("property", "sling:resourceType");
    params.put("property.value", slingResourceType);
    params.put("p.offset", "0");
    params.put("p.limit", "50");

    Session session = null;

    try {
        session = repository.loginAdministrative(null);
        Query query = queryBuilder.createQuery(PredicateGroup.create(params), session);
        SearchResult results = query.getResult();

        LOG.info("Found '{}' matches for query", results.getTotalMatches());

        for (Hit hit: results.getHits()) {

            // The query returns the jcr:content node, so we need its parent.
            Resource page = hit.getResource().getParent();
            GeometrixxMediaContentType contentType = page.adaptTo(GeometrixxMediaPage.class);

            if (contentType != null) {
                solrDocs.add(contentType.getJson());
            }
        }

    } catch (RepositoryException e) {
        LOG.error("Error getting repository", e);
    } finally {
        if (session != null && session.isLive())  {
            session.logout();
        }
    }

    response.getWriter().write(solrDocs.toJSONString());
}