Package javax.jcr

Examples of javax.jcr.Session


        assertFalse(repository.isSingleValueDescriptor("test"));
    }
   
    @Test
    public void testMultipleSessions() throws RepositoryException {
        Session session1 = repository.login();
        Session session2 = repository.login();

        // add a node in session 1
        Node root = session1.getRootNode();
        root.addNode("test");
        session1.save();
       
        // try to get node in session 2
        Node testNode2 = session2.getNode("/test");
        assertNotNull(testNode2);
       
        // delete node and make sure it is removed in session 1 as well
        testNode2.remove();
        session2.save();
       
        try {
            session1.getNode("/test");
            fail("Node was not removed");
        }
View Full Code Here


    public static RepositoryAddress getRepositoryAddress(RepositoryInfo repositoryInfo) {
        StringBuilder errors = new StringBuilder();
        for (String webDavUrlLocation : WEBDAV_URL_LOCATIONS) {

            Session session = null;
            String url = repositoryInfo.getUrl() + webDavUrlLocation;
            try {
                RepositoryAddress address = new RepositoryAddress(url);
                Repository repository;
                synchronized (SYNC) {
                    repository = REGISTERED_REPOSITORIES.get(address);

                    if (repository == null) {
                        Set<String> supportedSchemes = FACTORY.getSupportedSchemes();
                        if (!supportedSchemes.contains(address.getURI().getScheme())) {
                            throw new IllegalArgumentException("Unable to create a a repository for "
                                    + address.getURI()
                                    + ", since the scheme is unsupported. Only schemes '" + supportedSchemes
                                    + "' are supported");
                        }

                        // SLING-3739: ensure that a well-known ClassLoader is used
                        ClassLoader old = Thread.currentThread().getContextClassLoader();
                        Thread.currentThread().setContextClassLoader(Repository.class.getClassLoader());
                        try {
                            repository = FACTORY.createRepository(address);
                        } finally {
                            Thread.currentThread().setContextClassLoader(old);
                        }
                        REGISTERED_REPOSITORIES.put(address, repository);
                    }
                }

                session = repository.login(new SimpleCredentials(repositoryInfo.getUsername(), repositoryInfo
                        .getPassword().toCharArray()));
                return address;
            } catch (URISyntaxException e) {
                throw new RuntimeException(e);
            } catch (RepositoryException e) {
                Activator.getDefault().getPluginLogger().trace("Failed connecting to repository at " + url, e);
                errors.append(url).append(" : ").append(e.getMessage()).append('\n');
                continue;
            } finally {
                if (session != null) {
                    session.logout();
                }
            }
        }

        errors.deleteCharAt(errors.length() - 1);
View Full Code Here

        services.add(service);
    }

    public void activateAll(boolean resetRepo) throws Exception {
        if (resetRepo) {
            Session l = RepositoryProvider.instance().getRepository()
                    .loginAdministrative(null);
            try {
                l.removeItem("/var");
                l.save();
                l.logout();
            } catch (Exception e) {
                l.refresh(false);
                l.logout();
            }
        }

        for (@SuppressWarnings("rawtypes")
        Iterator it = services.iterator(); it.hasNext();) {
View Full Code Here

    /**
     * Return a new session.
     */
    public Session createSession() throws RepositoryException {
        // get an administrative session for potential impersonation
        final Session admin = this.repository.loginAdministrative(null);

        // do use the admin session, if the admin's user id is the same as owner
        if (admin.getUserID().equals(this.classLoaderOwner)) {
            return admin;
        }

        // else impersonate as the owner and logout the admin session again
        try {
            return admin.impersonate(new SimpleCredentials(this.classLoaderOwner, new char[0]));
        } finally {
            admin.logout();
        }
    }
View Full Code Here

     * @see org.apache.sling.commons.classloader.ClassLoaderWriter#delete(java.lang.String)
     */
    public boolean delete(final String name) {
        final String path = cleanPath(name);
        this.handleChangeEvent(path);
        Session session = null;
        try {
            session = createSession();
            if (session.itemExists(path)) {
                Item fileItem = session.getItem(path);
                fileItem.remove();
                session.save();
                return true;
            }
        } catch (final RepositoryException re) {
            logger.error("Cannot remove " + path, re);
        } finally {
            if ( session != null ) {
                session.logout();
            }
        }

        // fall back to false if item does not exist or in case of error
        return false;
View Full Code Here

     */
    public boolean rename(final String oldName, final String newName) {
        final String oldPath = cleanPath(oldName);
        final String newPath = cleanPath(newName);

        Session session = null;
        try {
            session = this.createSession();
            session.move(oldPath, newPath);
            session.save();

            this.handleChangeEvent(oldName);
            this.handleChangeEvent(newName);

            return true;
        } catch (final RepositoryException re) {
            logger.error("Cannot rename " + oldName + " to " + newName, re);
        } finally {
            if ( session != null ) {
                session.logout();
            }
        }

        // fall back to false in case of error or non-existence of oldFileName
        return false;
View Full Code Here

     * @see org.apache.sling.commons.classloader.ClassLoaderWriter#getInputStream(java.lang.String)
     */
    public InputStream getInputStream(final String name)
    throws IOException {
        final String path = cleanPath(name) + "/jcr:content/jcr:data";
        Session session = null;
        try {
            session = this.createSession();
            if ( session.itemExists(path) ) {
                final Property prop = (Property)session.getItem(path);
                final InputStream is = prop.getStream();
                final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int l = 0;
                final byte[] buf = new byte[2048];
                while ( (l = is.read(buf)) > -1 ) {
                    if ( l > 0 ) {
                        baos.write(buf, 0, l);
                    }
                }
                return new ByteArrayInputStream(baos.toByteArray());
            }
            throw new FileNotFoundException("Unable to find " + name);
        } catch (final RepositoryException re) {
            throw (IOException) new IOException(
                        "Failed to get InputStream for " + name).initCause(re);
        } finally {
            if ( session != null ) {
                session.logout();
            }
        }
    }
View Full Code Here

    /**
     * @see org.apache.sling.commons.classloader.ClassLoaderWriter#getLastModified(java.lang.String)
     */
    public long getLastModified(final String name) {
        final String path = cleanPath(name) + "/jcr:content/jcr:lastModified";
        Session session = null;
        try {
            session = this.createSession();
            if ( session.itemExists(path) ) {
                final Property prop = (Property)session.getItem(path);
                return prop.getLong();
            }
        } catch (final RepositoryException se) {
            logger.error("Cannot get last modification time for " + name, se);
        } finally {
            if ( session != null ) {
                session.logout();
            }
        }

        // fall back to "non-existent" in case of problems
        return -1;
View Full Code Here

         */
        @Override
        public void close() throws IOException {
            super.close();

            Session session = null;
            try {
                // get an own session for writing
                session = repositoryOutputProvider.createSession();
                final int lastPos = fileName.lastIndexOf('/');
                final String path = (lastPos == -1 ? null : fileName.substring(0, lastPos));
                final String name = (lastPos == -1 ? fileName : fileName.substring(lastPos + 1));
                if ( lastPos != -1 ) {
                    if ( !repositoryOutputProvider.mkdirs(session, path) ) {
                        throw new IOException("Unable to create path for " + path);
                    }
                }
                Node fileNode = null;
                Node contentNode = null;
                Node parentNode = null;
                if (session.itemExists(fileName)) {
                    final Item item = session.getItem(fileName);
                    if (item.isNode()) {
                        final Node node = item.isNode() ? (Node) item : item.getParent();
                        if ("jcr:content".equals(node.getName())) {
                            // replace the content properties of the jcr:content
                            // node
                            parentNode = node;
                            contentNode = node;
                        } else if (node.isNodeType("nt:file")) {
                            // try to set the content properties of jcr:content
                            // node
                            parentNode = node;
                            contentNode = node.getNode("jcr:content");
                        } else { // fileName is a node
                            // try to set the content properties of the node
                            parentNode = node;
                            contentNode = node;
                        }
                    } else {
                        // replace property with an nt:file node (if possible)
                        parentNode = item.getParent();
                        item.remove();
                        session.save();
                        fileNode = parentNode.addNode(name, "nt:file");
                    }
                } else {
                    if (lastPos <= 0) {
                        parentNode = session.getRootNode();
                    } else {
                        Item parent = session.getItem(path);
                        if (!parent.isNode()) {
                            throw new IOException("Parent at " + path + " is not a node.");
                        }
                        parentNode = (Node) parent;
                    }
                    fileNode = parentNode.addNode(name, "nt:file");
                }

                // if we have a file node, create the contentNode
                if (fileNode != null) {
                    contentNode = fileNode.addNode("jcr:content", "nt:resource");
                }

                final MimeTypeService mtService = this.repositoryOutputProvider.mimeTypeService;

                String mimeType = (mtService == null ? null : mtService.getMimeType(fileName));
                if (mimeType == null) {
                    mimeType = "application/octet-stream";
                }

                contentNode.setProperty("jcr:lastModified", System.currentTimeMillis());
                contentNode.setProperty("jcr:data", new ByteArrayInputStream(buf, 0, size()));
                contentNode.setProperty("jcr:mimeType", mimeType);

                session.save();
                this.repositoryOutputProvider.handleChangeEvent(fileName);
            } catch (final RepositoryException re) {
                throw (IOException)new IOException("Cannot write file " + fileName + ", reason: " + re.toString()).initCause(re);
            } finally {
                if ( session != null ) {
                    session.logout();
                }
            }
        }
View Full Code Here

     *
     * @throws NullPointerException If this class loader has already been
     *      destroyed.
     */
    private boolean findClassLoaderResource(final String path) throws IOException {
        Session session = null;
        boolean res = false;
        try {
            session = this.writer.createSession();
            if ( session.itemExists(path) ) {
                logger.debug("Found resource at {}", path);
                res = true;
            } else {
                logger.debug("No classpath entry contains {}", path);
            }
        } catch (final RepositoryException re) {
            logger.debug("Error while trying to get node at " + path, re);
        } finally {
            if ( session != null ) {
                session.logout();
            }
        }

        return res;
    }
View Full Code Here

TOP

Related Classes of javax.jcr.Session

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.