Examples of ResourceResolver


Examples of org.apache.sling.api.resource.ResourceResolver

        for (final ProviderInfo info : this.providerInfos) {
            info.refreshProperties();
            newProps.putAll(info.properties);
        }

        ResourceResolver resourceResolver = null;
        try {
            resourceResolver = resourceResolverFactory
                    .getAdministrativeResourceResolver(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.");
    }
View Full Code Here

Examples of org.apache.sling.api.resource.ResourceResolver

    public boolean authenticate(final HttpServletRequest request,
            final HttpServletResponse response) {
        if ( this.authentiationSupport.handleSecurity(request, response) ) {
            // get ResourceResolver (set by AuthenticationSupport)
            Object resolverObject = request.getAttribute(AuthenticationSupport.REQUEST_ATTRIBUTE_RESOLVER);
            final ResourceResolver resolver = (resolverObject instanceof ResourceResolver)
                    ? (ResourceResolver) resolverObject
                    : null;
            if ( resolver != null ) {
                final Session session = resolver.adaptTo(Session.class);
                if ( session != null ) {
                    try {
                        final User u = this.authenticate(session);
                        if ( u != null ) {
                            request.setAttribute(USER_ATTRIBUTE, u);
View Full Code Here

Examples of org.apache.sling.api.resource.ResourceResolver

        // announcement-heartbeat-dates anymore at all, this resetting here
        // became unnecessary.
       
        final String announcementJson = asJSON();
    if (announcementChildResource==null) {
            final ResourceResolver resourceResolver = announcementsResource.getResourceResolver();
            Map<String, Object> properties = new HashMap<String, Object>();
            properties.put("topologyAnnouncement", announcementJson);
            resourceResolver.create(announcementsResource, getPrimaryKey(), properties);
        } else {
            final ModifiableValueMap announcementChildMap = announcementChildResource.adaptTo(ModifiableValueMap.class);
            announcementChildMap.put("topologyAnnouncement", announcementJson);
        }
    }
View Full Code Here

Examples of org.apache.sling.api.resource.ResourceResolver

        Map<String,Object> attributes = new HashMap<String, Object>();
        if (authenticationInfo!=null) {
            attributes.put(ResourceResolverFactory.USER, authenticationInfo.get(ResourceResolverFactory.USER));
        }
       
        final ResourceResolver result = new MockResourceResolver(options, this, resources, attributes);
        Stack<ResourceResolver> resolverStack = resolverStackHolder.get();
        if ( resolverStack == null ) {
            resolverStack = new Stack<ResourceResolver>();
            resolverStackHolder.set(resolverStack);
        }
View Full Code Here

Examples of org.apache.sling.api.resource.ResourceResolver

    /**
     * @see org.apache.sling.api.resource.ResourceResolverFactory#getThreadResourceResolver()
     */
    // part of Resource API 2.8.0
    public ResourceResolver getThreadResourceResolver() {
        ResourceResolver result = null;
        final Stack<ResourceResolver> resolverStack = resolverStackHolder.get();
        if ( resolverStack != null && !resolverStack.isEmpty() ) {
            result = resolverStack.peek();
        }
        return result;
View Full Code Here

Examples of org.apache.sling.api.resource.ResourceResolver

        forcePing = false;
    }

    /** Issue a cluster local heartbeat (into the repository) **/
    private void issueClusterLocalHeartbeat() {
        ResourceResolver resourceResolver = null;
        final String myClusterNodePath = getLocalClusterNodePath();
        final Calendar currentTime = Calendar.getInstance();
        try {
            resourceResolver = getResourceResolver();
            if (resourceResolver == null) {
                logger.error("issueClusterLocalHeartbeat: no resourceresolver available!");
                return;
            }

            final Resource resource = ResourceHelper.getOrCreateResource(
                    resourceResolver, myClusterNodePath);
            final ModifiableValueMap resourceMap = resource.adaptTo(ModifiableValueMap.class);

            if (firstHeartbeatWritten!=-1 && lastHeartbeatWritten!=null) {
              // SLING-2892: additional paranoia check
              // after the first heartbeat, check if there's someone else using
              // the same sling.id in this cluster
              final long timeSinceFirstHeartbeat =
                  System.currentTimeMillis() - firstHeartbeatWritten;
              if (timeSinceFirstHeartbeat > 2*config.getHeartbeatInterval()) {
                // but wait at least 2 heartbeat intervals to handle the situation
                // where a bundle is refreshed, and startup cases.
                final Calendar lastHeartbeat = resourceMap.get("lastHeartbeat", Calendar.class);
                if (lastHeartbeat!=null) {
                  // if there is a heartbeat value, check if it is what I've written
                  // the last time
                  if (!lastHeartbeatWritten.getTime().equals(lastHeartbeat.getTime())) {
                    // then we've likely hit the situation where there is another
                    // sling instance accessing the same repository (ie in the same cluster)
                    // using the same sling.id - hence writing to the same
                    // resource
                    logger.error("issueClusterLocalHeartbeat: SLING-2892: Detected unexpected, concurrent update of: "+
                        myClusterNodePath+" 'lastHeartbeat'. If not done manually, " +
                        "this likely indicates that there is more than 1 instance running in this cluster" +
                        " with the same sling.id. My sling.id is "+slingId+"." +
                        " Check for sling.id.file in your installation of all instances in this cluster " +
                        "to verify this! Duplicate sling.ids are not allowed within a cluster!");
                  }
                }
              }

              // SLING-2901 : robust paranoia check: on first heartbeat write, the
              //              'runtimeId' is set as a property (ignoring any former value).
              //              If in subsequent calls the value of 'runtimeId' changes, then
              //              there is someone else around with the same slingId.
              final String readRuntimeId = resourceMap.get("runtimeId", String.class);
              if ( readRuntimeId == null ) { // SLING-3977
                  // someone deleted the resource property
                  firstHeartbeatWritten = -1;
              } else if (!runtimeId.equals(readRuntimeId)) {
                logger.error("issueClusterLocalHeartbeat: SLING-2091: Detected more than 1 instance running in this cluster " +
                    " with the same sling.id. My sling.id is "+slingId+", " +
                " Check for sling.id.file in your installation of all instances in this cluster " +
                "to verify this! Duplicate sling.ids are not allowed within a cluster!");
                logger.error("issueClusterLocalHeartbeat: sending TOPOLOGY_CHANGING before self-disabling.");
                discoveryService.forcedShutdown();
                logger.error("issueClusterLocalHeartbeat: disabling discovery.impl");
                activated = false;
                if (context!=null) {
                  // disable all components
                  try {
              context.getBundleContext().getBundle().stop();
            } catch (BundleException e) {
              logger.warn("issueClusterLocalHeartbeat: could not stop bundle: "+e, e);
              // then disable all compnoents instead
              context.disableComponent(null);
            }
                }
                return;
              }
            }
            resourceMap.put("lastHeartbeat", currentTime);
            if (firstHeartbeatWritten==-1) {
              resourceMap.put("runtimeId", runtimeId);
            }
            if (resetLeaderElectionId || !resourceMap.containsKey("leaderElectionId")) {
                int maxLongLength = String.valueOf(Long.MAX_VALUE).length();
                String currentTimeMillisStr = String.format("%0"
                        + maxLongLength + "d", System.currentTimeMillis());

                String prefix = "0";

                String leaderElectionRepositoryDescriptor = config.getLeaderElectionRepositoryDescriptor();
                if (leaderElectionRepositoryDescriptor!=null && leaderElectionRepositoryDescriptor.length()!=0) {
                    // when this property is configured, check the value of the repository descriptor
                    // and if that value is set, include it in the leader election id

                    final Session session = resourceResolver.adaptTo(Session.class);
                    if ( session != null ) {
                        String value = session.getRepository()
                                .getDescriptor(leaderElectionRepositoryDescriptor);
                        if (value != null && value.equalsIgnoreCase("true")) {
                            prefix = "1";
                        }
                    }
                }
                resourceMap.put("leaderElectionId", prefix + "_"
                        + currentTimeMillisStr + "_" + slingId);
                resetLeaderElectionId = false;
            }
            resourceResolver.commit();

            // SLING-2892: only in success case: remember the last heartbeat value written
            lastHeartbeatWritten = currentTime;
            // and set the first heartbeat written value - if it is not already set
            if (firstHeartbeatWritten==-1) {
              firstHeartbeatWritten = System.currentTimeMillis();
            }

        } catch (LoginException e) {
            logger.error("issueHeartbeat: could not log in administratively: "
                    + e, e);
        } catch (PersistenceException e) {
            logger.error("issueHeartbeat: Got a PersistenceException: "
                    + myClusterNodePath + " " + e, e);
        } finally {
            if (resourceResolver != null) {
                resourceResolver.close();
            }
        }
    }
View Full Code Here

Examples of org.apache.sling.api.resource.ResourceResolver

            logger.error("announcementRegistry is null");
            return;
        }
        announcementRegistry.checkExpiredAnnouncements();

        ResourceResolver resourceResolver = null;
        try {
            resourceResolver = getResourceResolver();
            doCheckView(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);
        } finally {
            if (resourceResolver != null) {
                resourceResolver.close();
            }
        }
    }
View Full Code Here

Examples of org.apache.sling.api.resource.ResourceResolver

        }
    }

    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

Examples of org.apache.sling.api.resource.ResourceResolver

       
        if (resourceResolverFactory == null) {
            logger.error("unregisterAnnouncement: resourceResolverFactory is null");
            return;
        }
        ResourceResolver resourceResolver = null;
        try {
            resourceResolver = resourceResolverFactory
                    .getAdministrativeResourceResolver(null);

            final String path = config.getClusterInstancesPath()
                    + "/"
                    + settingsService.getSlingId()
                    + "/announcements/" + ownerId;
            final Resource announcementsResource = resourceResolver.getResource(path);
            if (announcementsResource!=null) {
                resourceResolver.delete(announcementsResource);
                resourceResolver.commit();
            }

        } catch (LoginException e) {
            logger.error(
                    "unregisterAnnouncement: could not log in administratively: "
                            + e, e);
            throw new RuntimeException("Could not log in to repository (" + e
                    + ")", e);
        } catch (PersistenceException e) {
            logger.error("unregisterAnnouncement: got a PersistenceException: "
                    + e, e);
            throw new RuntimeException(
                    "Exception while talking to repository (" + e + ")", e);
        } finally {
            if (resourceResolver != null) {
                resourceResolver.close();
            }
        }
    }
View Full Code Here

Examples of org.apache.sling.api.resource.ResourceResolver

    public synchronized Collection<Announcement> listAnnouncementsInSameCluster(final ClusterView localClusterView) {
        if (localClusterView==null) {
            throw new IllegalArgumentException("clusterView must not be null");
        }
        ResourceResolver resourceResolver = null;
        final Collection<Announcement> incomingAnnouncements = new LinkedList<Announcement>();
        final InstanceDescription localInstance = getLocalInstanceDescription(localClusterView);
        try {
            resourceResolver = resourceResolverFactory
                    .getAdministrativeResourceResolver(null);

            Resource clusterInstancesResource = ResourceHelper
                    .getOrCreateResource(
                            resourceResolver,
                            config.getClusterInstancesPath());

            Iterator<Resource> it0 = clusterInstancesResource.getChildren()
                    .iterator();
            while (it0.hasNext()) {
                Resource aClusterInstanceResource = it0.next();
                final String instanceId = aClusterInstanceResource.getName();
                if (localInstance!=null && localInstance.getSlingId().equals(instanceId)) {
                    // this is the local instance then - which we serve from the cache only
                    fillWithCachedAnnouncements(incomingAnnouncements);
                    continue;
                }
               
                //TODO: add ClusterView.contains(instanceSlingId) for convenience to next api change
                if (!contains(localClusterView, instanceId)) {
                    // then the instance is not in my view, hence ignore its announcements
                    // (corresponds to earlier expiry-handling)
                    continue;
                }
                final Resource announcementsResource = aClusterInstanceResource
                        .getChild("announcements");
                if (announcementsResource == null) {
                    continue;
                }
                Iterator<Resource> it = announcementsResource.getChildren()
                        .iterator();
                Announcement topologyAnnouncement;
                while (it.hasNext()) {
                    Resource anAnnouncement = it.next();
                    topologyAnnouncement = Announcement
                            .fromJSON(anAnnouncement
                                    .adaptTo(ValueMap.class).get(
                                            "topologyAnnouncement",
                                            String.class));
                    incomingAnnouncements.add(topologyAnnouncement);
                    // SLING-3389: no longer check for expired announcements -
                    // instead make use of the fact that this instance
                    // has a clusterView and that every live instance
                    // is responsible of cleaning up expired announcements
                    // with the repository
                }
            }
            // since SLING-3389 this method does only read operations, hence
            // no commit necessary anymore - close happens in below finally block
        } catch (LoginException e) {
            logger.error(
                    "listAnnouncementsInSameCluster: could not log in administratively: " + e, e);
            throw new RuntimeException("Could not log in to repository (" + e
                    + ")", e);
        } catch (PersistenceException e) {
            logger.error("listAnnouncementsInSameCluster: got a PersistenceException: " + e, e);
            throw new RuntimeException(
                    "Exception while talking to repository (" + e + ")", e);
        } catch (JSONException e) {
            logger.error("listAnnouncementsInSameCluster: got a JSONException: " + e, e);
            throw new RuntimeException("Exception while converting json (" + e
                    + ")", e);
        } finally {
            if (resourceResolver != null) {
                resourceResolver.close();
            }
        }
      if (logger.isDebugEnabled()) {
        logger.debug("listAnnouncementsInSameCluster: result: "+incomingAnnouncements.size());
      }
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. 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.