Package javax.jcr

Examples of javax.jcr.Session


            propertiesToRemove.add(property.getName());
        }

        propertiesToRemove.removeAll(resource.getProperties().keySet());

        Session session = node.getSession();

        // update the mixin types ahead of type as contraints are enforced before
        // the session is committed
        Object mixinTypes = resource.getProperties().get(JcrConstants.JCR_MIXINTYPES);
        if (mixinTypes != null) {
            updateMixins(node, mixinTypes);
        }

        // remove old properties first
        // this supports the scenario where the node type is changed to a less permissive one
        for (String propertyToRemove : propertiesToRemove) {
            node.getProperty(propertyToRemove).remove();
            getLogger().trace("Removed property {0} from node at {1}", propertyToRemove, node.getPath());
        }
       
        String primaryType = (String) resource.getProperties().get(JcrConstants.JCR_PRIMARYTYPE);
        if (!node.getPrimaryNodeType().getName().equals(primaryType) && node.getDepth() != 0) {
            node.setPrimaryType(primaryType);
            session.save();
            getLogger().trace("Set new primary type {0} for node at {1}", primaryType, node.getPath());
        }

        // TODO - review for completeness and filevault compatibility
        for (Map.Entry<String, Object> entry : resource.getProperties().entrySet()) {

            String propertyName = entry.getKey();
            Object propertyValue = entry.getValue();
            Property property = null;

            if (node.hasProperty(propertyName)) {
                property = node.getProperty(propertyName);
            }

            if (property != null && property.getDefinition().isProtected()) {
                continue;
            }

            ValueFactory valueFactory = session.getValueFactory();
            Value value = null;
            Value[] values = null;

            if (propertyValue instanceof String) {
                value = valueFactory.createValue((String) propertyValue);
                ensurePropertyDefinitionMatchers(property, PropertyType.STRING, false);
            } else if (propertyValue instanceof String[]) {
                values = toValueArray((String[]) propertyValue, session);
                ensurePropertyDefinitionMatchers(property, PropertyType.STRING, true);
            } else if (propertyValue instanceof Boolean) {
                value = valueFactory.createValue((Boolean) propertyValue);
                ensurePropertyDefinitionMatchers(property, PropertyType.BOOLEAN, false);
            } else if (propertyValue instanceof Boolean[]) {
                values = toValueArray((Boolean[]) propertyValue, session);
                ensurePropertyDefinitionMatchers(property, PropertyType.BOOLEAN, true);
            } else if (propertyValue instanceof Calendar) {
                value = valueFactory.createValue((Calendar) propertyValue);
                ensurePropertyDefinitionMatchers(property, PropertyType.DATE, false);
            } else if (propertyValue instanceof Calendar[]) {
                values = toValueArray((Calendar[]) propertyValue, session);
                ensurePropertyDefinitionMatchers(property, PropertyType.DATE, true);
            } else if (propertyValue instanceof Double) {
                value = valueFactory.createValue((Double) propertyValue);
                ensurePropertyDefinitionMatchers(property, PropertyType.DOUBLE, false);
            } else if (propertyValue instanceof Double[]) {
                values = toValueArray((Double[]) propertyValue, session);
                ensurePropertyDefinitionMatchers(property, PropertyType.DOUBLE, true);
            } else if (propertyValue instanceof BigDecimal) {
                value = valueFactory.createValue((BigDecimal) propertyValue);
                ensurePropertyDefinitionMatchers(property, PropertyType.DECIMAL, false);
            } else if (propertyValue instanceof BigDecimal[]) {
                values = toValueArray((BigDecimal[]) propertyValue, session);
                ensurePropertyDefinitionMatchers(property, PropertyType.DECIMAL, true);
            } else if (propertyValue instanceof Long) {
                value = valueFactory.createValue((Long) propertyValue);
                ensurePropertyDefinitionMatchers(property, PropertyType.LONG, false);
            } else if (propertyValue instanceof Long[]) {
                values = toValueArray((Long[]) propertyValue, session);
                ensurePropertyDefinitionMatchers(property, PropertyType.LONG, true);
                // TODO - distinguish between weak vs strong references
            } else if (propertyValue instanceof UUID) {
                Node reference = session.getNodeByIdentifier(((UUID) propertyValue).toString());
                value = valueFactory.createValue(reference);
                ensurePropertyDefinitionMatchers(property, PropertyType.REFERENCE, false);
            } else if (propertyValue instanceof UUID[]) {
                values = toValueArray((UUID[]) propertyValue, session);
                ensurePropertyDefinitionMatchers(property, PropertyType.REFERENCE, true);
View Full Code Here


    }

    @Override
    public Result<T> execute() {

        Session session = null;
        try {
            session = repository.login(credentials);

            T result = execute0(session);

            session.save();

            return JcrResult.success(result);
        } catch (LoginException e) {
            return JcrResult.failure(e);
        } catch (RepositoryException e) {
            return JcrResult.failure(e);
        } catch (IOException e) {
            return JcrResult.failure(e);
        } finally {
            if (session != null)
                session.logout();
        }
    }
View Full Code Here

    }

    private static void initializeJcrMock(ResourceResolverFactory factory) throws RepositoryException, LoginException {
        // register default namespaces
        ResourceResolver resolver = factory.getResourceResolver(null);
        Session session = resolver.adaptTo(Session.class);
        NamespaceRegistry namespaceRegistry = session.getWorkspace().getNamespaceRegistry();
        namespaceRegistry.registerNamespace("sling", "http://sling.apache.org/jcr/sling/1.0");
    }
View Full Code Here

        assertEquals(MockJcr.DEFAULT_USER_ID, this.session.getUserID());
    }

    @Test
    public void testWithCustomUserWorkspace() {
        Session mySession = MockJcr.newSession("myUser", "myWorkspace");
        assertEquals("myUser", mySession.getUserID());
        assertEquals("myWorkspace", mySession.getWorkspace().getName());
    }
View Full Code Here

            } catch (Exception e) {
                throw new RuntimeException("Exception occurred: " + e, e);
            }
        } else if (type.equals(ValueMap.class)) {
            try {
                Session session = getSession();
                Node node = session.getNode(getPath());
                HashMap<String, Object> map = new HashMap<String, Object>();

                PropertyIterator properties = node.getProperties();
                while (properties.hasNext()) {
                    Property p = properties.nextProperty();
                    if (p.getType() == PropertyType.BOOLEAN) {
                        map.put(p.getName(), p.getBoolean());
                    } else if (p.getType() == PropertyType.STRING) {
                        map.put(p.getName(), p.getString());
                    } else if (p.getType() == PropertyType.DATE) {
                        map.put(p.getName(), p.getDate().getTime());
                    } else if (p.getType() == PropertyType.NAME) {
                        map.put(p.getName(), p.getName());
                    } else {
                        throw new RuntimeException(
                                "Unsupported property type: " + p.getType());
                    }
                }
                ValueMap valueMap = new ValueMapDecorator(map);
                return (AdapterType) valueMap;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        } else if (type.equals(ModifiableValueMap.class)) {
            return (AdapterType) new ModifiableValueMap() {
               
                public Collection<Object> values() {
                    throw new UnsupportedOperationException();
                }
               
                public int size() {
                    throw new UnsupportedOperationException();
                }
               
                public Object remove(Object arg0) {
                    Session session = getSession();
                    try{
                        final Node node = session.getNode(getPath());
                        final Property p = node.getProperty(String.valueOf(arg0));
                        if (p!=null) {
                          p.remove();
                        }
                        // this is not according to the spec - but OK for tests since
                        // the return value is never used
                        return null;
                    } catch(PathNotFoundException pnfe) {
                      // perfectly fine
                      return null;
                    } catch(RepositoryException e) {
                        throw new RuntimeException(e);
                    }
                }
               
                public void putAll(Map<? extends String, ? extends Object> arg0) {
                    throw new UnsupportedOperationException();
                }
               
                public Object put(String arg0, Object arg1) {
                    Session session = getSession();
                    try{
                        final Node node = session.getNode(getPath());
                        Object result = null;
                        if (node.hasProperty(arg0)) {
                            final Property previous = node.getProperty(arg0);
                            if (previous==null) {
                                // null
                            } else if (previous.getType() == PropertyType.STRING) {
                                result = previous.getString();
                            } else if (previous.getType() == PropertyType.DATE) {
                                result = previous.getDate();
                            } else if (previous.getType() == PropertyType.BOOLEAN) {
                                result = previous.getBoolean();
                            } else {
                                throw new UnsupportedOperationException();
                            }
                        }
                        if (arg1 instanceof String) {
                            node.setProperty(arg0, (String)arg1);
                        } else if (arg1 instanceof Calendar) {
                            node.setProperty(arg0, (Calendar)arg1);
                        } else if (arg1 instanceof Boolean) {
                            node.setProperty(arg0, (Boolean)arg1);
                        } else {
                            throw new UnsupportedOperationException();
                        }
                        return result;
                    } catch(RepositoryException e) {
                        throw new RuntimeException(e);
                    }
                }
               
                public Set<String> keySet() {
                    Session session = getSession();
                    try {
                        final Node node = session.getNode(getPath());
                        final PropertyIterator pi = node.getProperties();
                        final Set<String> result = new HashSet<String>();
                        while(pi.hasNext()) {
                            final Property p = pi.nextProperty();
                            result.add(p.getName());
                        }
                        return result;
                    } catch (RepositoryException e) {
                        throw new RuntimeException(e);
                    }
                }
               
                public boolean isEmpty() {
                    throw new UnsupportedOperationException();
                }
               
                public Object get(Object arg0) {
                    Session session = getSession();
                    try{
                        final Node node = session.getNode(getPath());
                        final String key = String.valueOf(arg0);
                        if (node.hasProperty(key)) {
                            return node.getProperty(key);
                        } else {
                            return null;
                        }
                    } catch(RepositoryException re) {
                        throw new RuntimeException(re);
                    }
                }
               
                public Set<Entry<String, Object>> entrySet() {
                    throw new UnsupportedOperationException();
                }
               
                public boolean containsValue(Object arg0) {
                    throw new UnsupportedOperationException();
                }
               
                public boolean containsKey(Object arg0) {
                    Session session = getSession();
                    try{
                        final Node node = session.getNode(getPath());
                        return node.hasProperty(String.valueOf(arg0));
                    } catch(RepositoryException re) {
                        throw new RuntimeException(re);
                    }
                }
               
                public void clear() {
                    throw new UnsupportedOperationException();
                }
               
                public <T> T get(String name, T defaultValue) {
                    throw new UnsupportedOperationException();
                }
               
                public <T> T get(String name, Class<T> type) {
                    Session session = getSession();
                    try{
                        final Node node = session.getNode(getPath());
                        if (node==null) {
                          return null;
                        }
                        Property p = node.getProperty(name);
                        if (p==null) {
View Full Code Here

    protected void tearDown() {

        if (this.resourceResolver != null) {
            // revert potential unsaved changes in resource resolver/JCR session
            this.resourceResolver.revert();
            Session session = this.resourceResolver.adaptTo(Session.class);
            if (session != null) {
                try {
                    session.refresh(false);
                } catch (RepositoryException ex) {
                    // ignore
                }
            }
        }
View Full Code Here

        long start = System.currentTimeMillis();

        int numCleaned = 0;
        int numLive = 0;

        Session admin = null;
        try {
            // assume chunks are stored in the default workspace
            admin = repository.loginAdministrative(null);
            QueryManager qm = admin.getWorkspace().getQueryManager();

            QueryResult queryres = qm.createQuery(
                "SELECT * FROM [sling:chunks] ", Query.JCR_SQL2).execute();
            NodeIterator nodeItr = queryres.getNodes();
            while (nodeItr.hasNext()) {
                Node node = nodeItr.nextNode();
                if (isEligibleForCleanUp(node)) {
                    numCleaned++;
                    uploadhandler.deleteChunks(node);
                } else {
                    numLive++;
                }
            }
            if (admin.hasPendingChanges()) {
                try {
                    admin.refresh(true);
                    admin.save();
                } catch (InvalidItemStateException iise) {
                    log.info("ChunkCleanUpTask: Concurrent modification to one or more of the chunk to be removed. Retrying later");
                } catch (RepositoryException re) {
                    log.info("ChunkCleanUpTask: Failed persisting chunk removal. Retrying later");
                }
            }

        } catch (Throwable t) {
            log.error(
                "ChunkCleanUpTask: General failure while trying to cleanup chunks",
                t);
        } finally {
            if (admin != null) {
                admin.logout();
            }
        }
        long end = System.currentTimeMillis();
        log.info(
            "ChunkCleanUpTask finished: Removed {} chunk upload(s) in {}ms ({} chunk upload(s) still active)",
View Full Code Here

        }
    }
   
    @Test
    public void testLogin() throws RepositoryException {
        final Session s = repository.loginAdministrative(null);
        assertNotNull(s);
        s.logout();
    }
View Full Code Here

            final String userId = xingUser.getId(); // TODO make configurable

            User user = getUser(userId);
            if (user == null) {
                logger.debug("creating a new user with id '{}'", userId);
                final Session session = getSession();
                final UserManager userManager = getUserManager(session);
                user = userManager.createUser(userId, null);
            } else {
                logger.debug("updating an existing user with id '{}'", userId);
            }

            // TODO disable user on create?
            final ValueFactory valueFactory = getSession().getValueFactory();
            final Value dataValue = valueFactory.createValue(json);
            final Value hashValue = valueFactory.createValue(givenHash);
            user.setProperty(userDataProperty, dataValue);
            user.setProperty(userHashProperty, hashValue);
            session.save();
            return user;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
View Full Code Here

    private VltSerializationDataBuilder builder;

    public static void main(String[] args) throws RepositoryException, URISyntaxException, IOException {
        RepositoryAddress address = new RepositoryAddress("http://localhost:8080/server/root");
        Repository repo = new RepositoryProvider().getRepository(address);
        Session session = repo.login(new SimpleCredentials("admin", "admin".toCharArray()));

        VaultFileSystem fs = Mounter.mount(null, null, address, "/", session);

        String[] attempts = new String[] { "/rep:policy", "/var" };
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.