Search in sources :

Example 11 with ModifiableValueMap

use of org.apache.sling.api.resource.ModifiableValueMap in project sling by apache.

the class CustomConfigurationPersistenceStrategy2 method replaceProperties.

private void replaceProperties(Resource resource, Map<String, Object> properties) {
    ModifiableValueMap modValueMap = resource.adaptTo(ModifiableValueMap.class);
    // remove all existing properties that do not have jcr: namespace
    for (String propertyName : new HashSet<>(modValueMap.keySet())) {
        if (StringUtils.startsWith(propertyName, "jcr:")) {
            continue;
        }
        modValueMap.remove(propertyName);
    }
    modValueMap.putAll(properties);
}
Also used : ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) HashSet(java.util.HashSet)

Example 12 with ModifiableValueMap

use of org.apache.sling.api.resource.ModifiableValueMap in project sling by apache.

the class MockedResource method adaptTo.

@SuppressWarnings("unchecked")
@Override
public <AdapterType> AdapterType adaptTo(Class<AdapterType> type) {
    if (type.equals(Node.class)) {
        try {
            return (AdapterType) getSession().getNode(getPath());
        } catch (Exception e) {
            logger.error("Exception occurred: " + e, 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 if (p.getType() == PropertyType.LONG) {
                    map.put(p.getName(), p.getLong());
                } else {
                    throw new RuntimeException("Unsupported property type: " + p.getType());
                }
            }
            ValueMap valueMap = new ValueMapDecorator(map);
            return (AdapterType) valueMap;
        } catch (Exception e) {
            logger.error("adaptTo failed with : " + e);
            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();
                    }
                    // 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 if (previous.getType() == PropertyType.LONG) {
                            result = previous.getLong();
                        } 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 if (arg1 instanceof Date) {
                        final Calendar c = Calendar.getInstance();
                        c.setTime((Date) arg1);
                        node.setProperty(arg0, c);
                    } else if (arg1 instanceof Long) {
                        node.setProperty(arg0, (Long) arg1);
                    } else if (arg1 == null) {
                        node.setProperty(arg0, (Value) null);
                    } 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;
                    }
                    if (!node.hasProperty(name)) {
                        return null;
                    }
                    Property p = node.getProperty(name);
                    if (p == null) {
                        return null;
                    }
                    if (type.equals(Calendar.class)) {
                        return (T) p.getDate();
                    } else if (type.equals(String.class)) {
                        return (T) p.getString();
                    } else {
                        throw new UnsupportedOperationException();
                    }
                } catch (RepositoryException e) {
                    throw new RuntimeException(e);
                }
            }
        };
    } else {
        return super.adaptTo(type);
    }
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) ValueMap(org.apache.sling.api.resource.ValueMap) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) Node(javax.jcr.Node) Property(javax.jcr.Property) Calendar(java.util.Calendar) PropertyIterator(javax.jcr.PropertyIterator) ValueMapDecorator(org.apache.sling.api.wrappers.ValueMapDecorator) RepositoryException(javax.jcr.RepositoryException) PathNotFoundException(javax.jcr.PathNotFoundException) RepositoryException(javax.jcr.RepositoryException) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) Date(java.util.Date) Collection(java.util.Collection) PathNotFoundException(javax.jcr.PathNotFoundException) Session(javax.jcr.Session)

Example 13 with ModifiableValueMap

use of org.apache.sling.api.resource.ModifiableValueMap in project sling by apache.

the class SyncTokenService method storeMySyncToken.

private boolean storeMySyncToken(String syncTokenId) {
    logger.trace("storeMySyncToken: start");
    if (slingId == null) {
        logger.info("storeMySyncToken: not yet activated (slingId is null)");
        return false;
    }
    ResourceResolver resourceResolver = null;
    try {
        resourceResolver = getResourceResolver();
        final Resource resource = ResourceHelper.getOrCreateResource(resourceResolver, getSyncTokenPath());
        ModifiableValueMap syncTokens = resource.adaptTo(ModifiableValueMap.class);
        boolean updateToken = false;
        if (!syncTokens.containsKey(slingId)) {
            updateToken = true;
        } else {
            Object existingToken = syncTokens.get(slingId);
            if (existingToken == null || !existingToken.equals(syncTokenId)) {
                updateToken = true;
            }
        }
        if (updateToken) {
            syncTokens.put(slingId, syncTokenId);
            resourceResolver.commit();
            logger.info("storeMySyncToken: stored syncToken of slingId=" + slingId + " as=" + syncTokenId);
        } else {
            logger.info("storeMySyncToken: syncToken was left unchanged for slingId=" + slingId + " at=" + syncTokenId);
        }
        return true;
    } catch (LoginException e) {
        logger.error("storeMySyncToken: could not login for storing my syncToken: " + e, e);
        return false;
    } catch (PersistenceException e) {
        logger.error("storeMySyncToken: got PersistenceException while storing my syncToken: " + e, e);
        return false;
    } finally {
        logger.trace("storeMySyncToken: end");
        if (resourceResolver != null) {
            resourceResolver.close();
        }
    }
}
Also used : ResourceResolver(org.apache.sling.api.resource.ResourceResolver) Resource(org.apache.sling.api.resource.Resource) PersistenceException(org.apache.sling.api.resource.PersistenceException) LoginException(org.apache.sling.api.resource.LoginException) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap)

Example 14 with ModifiableValueMap

use of org.apache.sling.api.resource.ModifiableValueMap in project sling by apache.

the class VotingView method newVoting.

/**
     * Create a new voting with the given list of instances, the given
     * voting/view id and the given slingid of the initiator.
     * @param newViewId the new voting/view id
     * @param initiatorId the slingid of the initiator
     * @param liveInstances the list of live instances to add to the voting
     * @return a DAO object representing the voting
     */
public static VotingView newVoting(final ResourceResolver resourceResolver, final Config config, final String newViewId, String initiatorId, final Set<String> liveInstances) throws PersistenceException {
    if (!liveInstances.contains(initiatorId)) {
        // SLING-4617 : a voting, on a single instance, was created without the local instance
        // this should in no case happen - the local instance should always be part of the live
        // instances. if that's not the case, then something's fishy and we should not create
        // the new voting - and instead rely on a retry later.
        logger.warn("newVoting: liveInstances does not include initiatorId (local instance) - not creating new, invalid, voting");
        return null;
    }
    final Resource votingResource = ResourceHelper.getOrCreateResource(resourceResolver, config.getOngoingVotingsPath() + "/" + newViewId);
    final ModifiableValueMap votingMap = votingResource.adaptTo(ModifiableValueMap.class);
    votingMap.put("votingStart", Calendar.getInstance());
    String clusterId = null;
    Calendar clusterIdDefinedAt = null;
    String clusterIdDefinedBy = null;
    final View currentlyEstablishedView = ViewHelper.getEstablishedView(resourceResolver, config);
    if (currentlyEstablishedView != null) {
        final ValueMap establishedViewValueMap = currentlyEstablishedView.getResource().adaptTo(ValueMap.class);
        clusterId = establishedViewValueMap.get(VIEW_PROPERTY_CLUSTER_ID, String.class);
        if (clusterId == null || clusterId.length() == 0) {
            clusterId = currentlyEstablishedView.getResource().getName();
        }
        Date date = establishedViewValueMap.get(VIEW_PROPERTY_CLUSTER_ID_DEFINED_AT, Date.class);
        if (date != null) {
            clusterIdDefinedAt = Calendar.getInstance();
            clusterIdDefinedAt.setTime(date);
        }
        clusterIdDefinedBy = establishedViewValueMap.get(VIEW_PROPERTY_CLUSTER_ID_DEFINED_BY, String.class);
    }
    if (clusterId == null || clusterId.length() == 0) {
        clusterId = newViewId;
        clusterIdDefinedAt = Calendar.getInstance();
    }
    votingMap.put(VIEW_PROPERTY_CLUSTER_ID, clusterId);
    if (clusterIdDefinedAt != null) {
        votingMap.put(VIEW_PROPERTY_CLUSTER_ID_DEFINED_AT, clusterIdDefinedAt);
    }
    if (clusterIdDefinedBy == null || clusterIdDefinedBy.length() == 0) {
        clusterIdDefinedBy = initiatorId;
    }
    votingMap.put(VIEW_PROPERTY_CLUSTER_ID_DEFINED_BY, clusterIdDefinedBy);
    final Resource membersResource = resourceResolver.create(votingResource, "members", null);
    final Iterator<String> it = liveInstances.iterator();
    while (it.hasNext()) {
        String memberId = it.next();
        Map<String, Object> properties = new HashMap<String, Object>();
        if (memberId.equals(initiatorId)) {
            properties.put("initiator", true);
            properties.put("vote", true);
            properties.put("votedAt", Calendar.getInstance());
        }
        Resource instanceResource = ResourceHelper.getOrCreateResource(resourceResolver, config.getClusterInstancesPath() + "/" + memberId);
        String leaderElectionId = instanceResource.adaptTo(ValueMap.class).get("leaderElectionId", String.class);
        properties.put("leaderElectionId", leaderElectionId);
        resourceResolver.create(membersResource, memberId, properties);
    }
    logger.debug("newVoting: committing new voting: newViewId=" + newViewId + ", initiatorId=" + initiatorId + ", resource=" + votingResource + ", #members: " + liveInstances.size() + ", members: " + liveInstances);
    resourceResolver.commit();
    logger.info("newVoting: new voting started: newViewId=" + newViewId + ", initiatorId=" + initiatorId + ", resource=" + votingResource + ", #members: " + liveInstances.size() + ", members: " + liveInstances);
    return new VotingView(votingResource);
}
Also used : HashMap(java.util.HashMap) Calendar(java.util.Calendar) ValueMap(org.apache.sling.api.resource.ValueMap) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) Resource(org.apache.sling.api.resource.Resource) View(org.apache.sling.discovery.impl.common.View) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) Date(java.util.Date)

Example 15 with ModifiableValueMap

use of org.apache.sling.api.resource.ModifiableValueMap in project sling by apache.

the class DiscoveryServiceImpl method doUpdateProperties.

/**
     * Update the properties by inquiring the PropertyProvider's current values.
     * <p>
     * This method is invoked regularly by the heartbeatHandler.
     * The properties are stored in the repository under Config.getClusterInstancesPath()
     * and announced in the topology.
     * <p>
     * @see Config#getClusterInstancesPath()
     */
private void doUpdateProperties() {
    if (resourceResolverFactory == null) {
        // cannot update the properties then..
        logger.debug("doUpdateProperties: too early to update the properties. resourceResolverFactory not yet set.");
        return;
    } else {
        logger.debug("doUpdateProperties: updating properties now..");
    }
    final Map<String, String> newProps = new HashMap<String, String>();
    for (final ProviderInfo info : this.providerInfos) {
        info.refreshProperties();
        newProps.putAll(info.properties);
    }
    ResourceResolver resourceResolver = null;
    try {
        resourceResolver = resourceResolverFactory.getServiceResourceResolver(null);
        Resource myInstance = ResourceHelper.getOrCreateResource(resourceResolver, config.getClusterInstancesPath() + "/" + slingId + "/properties");
        // SLING-2879 - revert/refresh resourceResolver here to work
        // around a potential issue with jackrabbit in a clustered environment
        resourceResolver.revert();
        resourceResolver.refresh();
        final ModifiableValueMap myInstanceMap = myInstance.adaptTo(ModifiableValueMap.class);
        final Set<String> keys = new HashSet<String>(myInstanceMap.keySet());
        for (final String key : keys) {
            if (newProps.containsKey(key)) {
                // perfect
                continue;
            } else if (key.indexOf(":") != -1) {
                // ignore
                continue;
            } else {
                // remove
                myInstanceMap.remove(key);
            }
        }
        boolean anyChanges = false;
        for (final Entry<String, String> entry : newProps.entrySet()) {
            Object existingValue = myInstanceMap.get(entry.getKey());
            if (entry.getValue().equals(existingValue)) {
                // SLING-3389: dont rewrite the properties if nothing changed!
                if (logger.isDebugEnabled()) {
                    logger.debug("doUpdateProperties: unchanged: {}={}", entry.getKey(), entry.getValue());
                }
                continue;
            }
            if (logger.isDebugEnabled()) {
                logger.debug("doUpdateProperties: changed: {}={}", entry.getKey(), entry.getValue());
            }
            anyChanges = true;
            myInstanceMap.put(entry.getKey(), entry.getValue());
        }
        if (anyChanges) {
            resourceResolver.commit();
        }
    } catch (LoginException e) {
        logger.error("handleEvent: could not log in administratively: " + e, e);
        throw new RuntimeException("Could not log in to repository (" + e + ")", e);
    } catch (PersistenceException e) {
        logger.error("handleEvent: got a PersistenceException: " + e, e);
        throw new RuntimeException("Exception while talking to repository (" + e + ")", e);
    } finally {
        if (resourceResolver != null) {
            resourceResolver.close();
        }
    }
    logger.debug("doUpdateProperties: updating properties done.");
}
Also used : HashMap(java.util.HashMap) Resource(org.apache.sling.api.resource.Resource) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) PersistenceException(org.apache.sling.api.resource.PersistenceException) LoginException(org.apache.sling.api.resource.LoginException) HashSet(java.util.HashSet)

Aggregations

ModifiableValueMap (org.apache.sling.api.resource.ModifiableValueMap)111 Resource (org.apache.sling.api.resource.Resource)74 PersistenceException (org.apache.sling.api.resource.PersistenceException)32 Test (org.junit.Test)28 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)26 HashMap (java.util.HashMap)22 ValueMap (org.apache.sling.api.resource.ValueMap)22 Calendar (java.util.Calendar)13 LoginException (org.apache.sling.api.resource.LoginException)9 ChildResource (org.apache.sling.validation.model.ChildResource)9 Date (java.util.Date)8 HashSet (java.util.HashSet)8 Map (java.util.Map)8 NonExistingResource (org.apache.sling.api.resource.NonExistingResource)8 ByteArrayInputStream (java.io.ByteArrayInputStream)7 IOException (java.io.IOException)7 ValidationModel (org.apache.sling.validation.model.ValidationModel)7 InputStream (java.io.InputStream)6 Node (javax.jcr.Node)6 RepositoryException (javax.jcr.RepositoryException)6