Search in sources :

Example 21 with ResourceResolver

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

the class HeartbeatHandler method doCheckView.

/** Check whether the established view matches the reality, ie matches the
     * heartbeats
     */
@Override
protected void doCheckView() {
    super.doCheckView();
    ResourceResolver resourceResolver = null;
    try {
        resourceResolver = getResourceResolver();
        doCheckViewWith(resourceResolver);
    } catch (LoginException e) {
        logger.error("checkView: could not log in administratively: " + e, e);
    } catch (PersistenceException e) {
        logger.error("checkView: encountered a persistence exception during view check: " + e, e);
    } catch (RuntimeException e) {
        logger.error("checkView: encountered a runtime exception during view check: " + e, e);
    } finally {
        if (resourceResolver != null) {
            resourceResolver.close();
        }
    }
}
Also used : ResourceResolver(org.apache.sling.api.resource.ResourceResolver) PersistenceException(org.apache.sling.api.resource.PersistenceException) LoginException(org.apache.sling.api.resource.LoginException)

Example 22 with ResourceResolver

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

the class HeartbeatHandler method resetLeaderElectionId.

/**
     * Hook that will cause a reset of the leaderElectionId
     * on next invocation of issueClusterLocalHeartbeat.
     * @return true if the leaderElectionId was reset - false if that was not
     * necessary as that happened earlier already and it has not propagated
     * yet to the ./clusterInstances in the meantime
     */
public boolean resetLeaderElectionId() {
    if (resetLeaderElectionId) {
        // resetting twice doesn't work
        return false;
    }
    resetLeaderElectionId = true;
    ResourceResolver resourceResolver = null;
    try {
        resourceResolver = getResourceResolver();
        if (resourceResolver != null) {
            newLeaderElectionId = newLeaderElectionId(resourceResolver);
            if (votingHandler != null) {
                logger.info("resetLeaderElectionId: set new leaderElectionId with votingHandler to: " + newLeaderElectionId);
                votingHandler.setLeaderElectionId(newLeaderElectionId);
            } else {
                logger.info("resetLeaderElectionId: no votingHandler, new leaderElectionId would be: " + newLeaderElectionId);
            }
        } else {
            logger.warn("resetLeaderElectionId: could not login, new leaderElectionId will be calculated upon next heartbeat only!");
        }
    } catch (LoginException e) {
        logger.error("resetLeaderElectionid: could not login: " + e, e);
    } finally {
        if (resourceResolver != null) {
            resourceResolver.close();
        }
    }
    return true;
}
Also used : ResourceResolver(org.apache.sling.api.resource.ResourceResolver) LoginException(org.apache.sling.api.resource.LoginException)

Example 23 with ResourceResolver

use of org.apache.sling.api.resource.ResourceResolver 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)

Example 24 with ResourceResolver

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

the class DescriptorHelper method setDescriptor.

public static void setDescriptor(ResourceResolverFactory factory, String key, String value) throws Exception {
    ResourceResolver resourceResolver = factory.getServiceResourceResolver(null);
    try {
        Session session = resourceResolver.adaptTo(Session.class);
        if (session == null) {
            return;
        }
        Repository repo = session.getRepository();
        //<hack>
        //            Method setDescriptorMethod = repo.getClass().
        //                    getDeclaredMethod("setDescriptor", String.class, String.class);
        //            if (setDescriptorMethod!=null) {
        //                setDescriptorMethod.setAccessible(true);
        //                setDescriptorMethod.invoke(repo, key, value);
        //            } else {
        //                fail("could not get 'setDescriptor' method");
        //            }
        Method getDescriptorsMethod = repo.getClass().getDeclaredMethod("getDescriptors");
        if (getDescriptorsMethod == null) {
            fail("could not get 'getDescriptors' method");
        } else {
            getDescriptorsMethod.setAccessible(true);
            GenericDescriptors descriptors = (GenericDescriptors) getDescriptorsMethod.invoke(repo);
            SimpleValueFactory valueFactory = new SimpleValueFactory();
            descriptors.put(key, valueFactory.createValue(value), true, true);
        }
        //</hack>
        //<verify-hack>
        assertEquals(value, repo.getDescriptor(key));
    //</verify-hack>
    } finally {
        if (resourceResolver != null) {
            resourceResolver.close();
        }
    }
}
Also used : GenericDescriptors(org.apache.jackrabbit.oak.util.GenericDescriptors) Repository(javax.jcr.Repository) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) Method(java.lang.reflect.Method) SimpleValueFactory(org.apache.jackrabbit.commons.SimpleValueFactory) Session(javax.jcr.Session)

Example 25 with ResourceResolver

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

the class VotingHandlerTest method asyncVote.

private void asyncVote(final String debugInfo, final VotingHandler votingHandler, final List<VotingDetail> votingDetails, final Semaphore ready, final Semaphore go, final Semaphore done, final Set<Throwable> exceptions) throws Exception {
    Runnable r = new Runnable() {

        @Override
        public void run() {
            boolean released = false;
            try {
                logger.info("asyncVote[" + debugInfo + "] logging in...");
                Map<VotingView, VotingDetail> result = null;
                ResourceResolver rr = null;
                int retries = 0;
                while (true) {
                    try {
                        rr = factory.getServiceResourceResolver(null);
                        if (retries == 0) {
                            logger.info("asyncVote[" + debugInfo + "] marking ready...");
                            ready.release();
                            logger.info("asyncVote[" + debugInfo + "] waiting for go...");
                            go.acquire();
                        } else {
                            logger.info("asyncVote[" + debugInfo + "] not doing ready/go on retry.");
                        }
                        logger.info("asyncVote[" + debugInfo + "] analyzeVotings...");
                        result = votingHandler.analyzeVotings(rr);
                        break;
                    } catch (Exception e) {
                        logger.warn("asyncVote[" + debugInfo + "] Exception: " + e, e);
                        if (retries++ < 5) {
                            Thread.sleep(500);
                            logger.info("asyncVote[" + debugInfo + "] retrying after Exception...");
                            continue;
                        }
                        throw e;
                    } finally {
                        if (rr != null) {
                            rr.close();
                        }
                    }
                }
                logger.info("asyncVote[" + debugInfo + "] done, asserting results...");
                assertNotNull(result);
                votingDetails.addAll(result.values());
                logger.info("asyncVote[" + debugInfo + "] marking done.");
                done.release();
                released = true;
            } catch (RuntimeException re) {
                // SLING-5244: make sure we're not silently running into an unchecked exception
                logger.info("asyncVote[" + debugInfo + "] RuntimeException: " + re, re);
                exceptions.add(re);
                throw re;
            } catch (Error er) {
                // SLING-5244: make sure we're not silently running into an unchecked exception
                logger.info("asyncVote[" + debugInfo + "] Error: " + er, er);
                exceptions.add(er);
                throw er;
            } catch (Exception e) {
                // SLING-5244: make sure we're not silently running into an unchecked exception
                logger.info("asyncVote[" + debugInfo + "] Exception: " + e, e);
                exceptions.add(e);
            } finally {
                // SLING-5244: make sure we're getting informed when this thread is done - be it normal or not
                logger.info("asyncVote[" + debugInfo + "] finally [released=" + released + "]");
            }
        }
    };
    threadPool.execute(r);
}
Also used : ResourceResolver(org.apache.sling.api.resource.ResourceResolver) VotingDetail(org.apache.sling.discovery.impl.cluster.voting.VotingHandler.VotingDetail) PathNotFoundException(javax.jcr.PathNotFoundException)

Aggregations

ResourceResolver (org.apache.sling.api.resource.ResourceResolver)339 Resource (org.apache.sling.api.resource.Resource)168 Test (org.junit.Test)131 HashMap (java.util.HashMap)65 LoginException (org.apache.sling.api.resource.LoginException)53 PersistenceException (org.apache.sling.api.resource.PersistenceException)52 Session (javax.jcr.Session)31 ModifiableValueMap (org.apache.sling.api.resource.ModifiableValueMap)29 ValueMap (org.apache.sling.api.resource.ValueMap)27 SyntheticResource (org.apache.sling.api.resource.SyntheticResource)26 ArrayList (java.util.ArrayList)23 DistributionRequest (org.apache.sling.distribution.DistributionRequest)23 DistributionPackage (org.apache.sling.distribution.packaging.DistributionPackage)21 Map (java.util.Map)19 Before (org.junit.Before)19 IOException (java.io.IOException)17 NonExistingResource (org.apache.sling.api.resource.NonExistingResource)17 ChildResource (org.apache.sling.validation.model.ChildResource)17 HashSet (java.util.HashSet)16 ResourceResolverFactory (org.apache.sling.api.resource.ResourceResolverFactory)15