Search in sources :

Example 11 with ResourceResolver

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

the class ConfigurationWebConsolePlugin method printResolutionTestTool.

private void printResolutionTestTool(HttpServletRequest request, PrintWriter pw) {
    final String path = this.getParameter(request, "path", null);
    String configNameOther = this.getParameter(request, "configNameOther", null);
    String configName = this.getParameter(request, "configName", null);
    if (configName == null) {
        configName = configNameOther;
    } else {
        configNameOther = null;
    }
    final boolean resourceCollection = BooleanUtils.toBoolean(this.getParameter(request, "resourceCollection", "false"));
    ResourceResolver resolver = null;
    try {
        Resource contentResource = null;
        if (path != null) {
            resolver = getResolver();
            if (resolver != null) {
                contentResource = resolver.getResource(path);
            }
        }
        pw.println("<form method='get'>");
        tableStart(pw, "Test Configuration Resolution", 2);
        String alertMessage = null;
        if (path != null) {
            if (resolver == null) {
                alertMessage = "Unable to access repository - please check system configuration.";
            } else if (contentResource == null) {
                alertMessage = "Path does not exist.";
            }
        }
        textField(pw, "Content Path", "path", path, alertMessage);
        tableRows(pw);
        selectField(pw, "Config Name", "configName", configName, configurationManager.getConfigurationNames());
        tableRows(pw);
        textField(pw, "Other Config Name", "configNameOther", configNameOther);
        tableRows(pw);
        checkboxField(pw, "Resource collection", "resourceCollection", resourceCollection);
        tableRows(pw);
        pw.println("<td></td>");
        pw.println("<td><input type='submit' value='Resolve'/></td>");
        tableEnd(pw);
        pw.println("</form>");
        pw.println("<br/>");
        if (contentResource != null) {
            // context paths
            Iterator<ContextResource> contextResources = contextPathStrategyMultiplexer.findContextResources(contentResource);
            tableStart(pw, "Context paths", 3);
            pw.println("<th>Context path</th>");
            pw.println("<th>Config reference</th>");
            pw.println("<th>Ranking</th>");
            while (contextResources.hasNext()) {
                ContextResource contextResource = contextResources.next();
                tableRows(pw);
                pw.println("<td>" + xss.encodeForHTML(contextResource.getResource().getPath()) + "</td>");
                pw.println("<td>" + xss.encodeForHTML(contextResource.getConfigRef()) + "</td>");
                pw.println("<td>" + contextResource.getServiceRanking() + "</td>");
            }
            tableEnd(pw);
            pw.println("<br/>");
            // resolve configuration
            Collection<ConfigurationData> configDatas;
            if (resourceCollection) {
                configDatas = configurationManager.getConfigurationCollection(contentResource, configName).getItems();
            } else {
                ConfigurationData configData = configurationManager.getConfiguration(contentResource, configName);
                if (configData != null) {
                    configDatas = Collections.singletonList(configData);
                } else {
                    configDatas = Collections.emptyList();
                }
            }
            tableStart(pw, "Result", 6);
            if (configDatas.size() == 0) {
                pw.println("<td colspan='6'>");
                alertDiv(pw, "No matching item found.");
                pw.println("<br/>&nbsp;</td>");
            } else {
                pw.println("<th>Property</th>");
                pw.println("<th>Effective Value</th>");
                pw.println("<th>Value</th>");
                pw.println("<th>Default</th>");
                pw.println("<th>Inherited</th>");
                pw.println("<th>Overwritten</th>");
                for (ConfigurationData data : configDatas) {
                    tableRows(pw);
                    pw.println("<td colspan='6' style='background-color:#f3f3f3'>");
                    pw.print("Path: " + xss.encodeForHTML(data.getResourcePath()));
                    pw.println("</td>");
                    for (String propertyName : data.getPropertyNames()) {
                        ValueInfo<?> valueInfo = data.getValueInfo(propertyName);
                        tableRows(pw);
                        td(pw, propertyName);
                        td(pw, valueInfo.getEffectiveValue());
                        td(pw, valueInfo.getValue());
                        td(pw, valueInfo.isDefault());
                        String title = null;
                        if (valueInfo.isInherited()) {
                            title = "Source path: " + valueInfo.getConfigSourcePath();
                        }
                        td(pw, valueInfo.isInherited(), title);
                        td(pw, valueInfo.isOverridden());
                    }
                }
            }
            tableEnd(pw);
        }
    } finally {
        if (resolver != null) {
            resolver.close();
        }
    }
}
Also used : ResourceResolver(org.apache.sling.api.resource.ResourceResolver) Resource(org.apache.sling.api.resource.Resource) ContextResource(org.apache.sling.caconfig.resource.spi.ContextResource) ConfigurationData(org.apache.sling.caconfig.management.ConfigurationData) ContextResource(org.apache.sling.caconfig.resource.spi.ContextResource)

Example 12 with ResourceResolver

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

the class ConfigurationPersistenceStrategyMultiplexerImplTest method testMultipleStrategies.

@SuppressWarnings("deprecation")
@Test
public void testMultipleStrategies() {
    // strategy 1 (using old ConfigurationPersistenceStrategy with bridge to  ConfigurationPersistenceStrategy2)
    context.registerService(org.apache.sling.caconfig.spi.ConfigurationPersistenceStrategy.class, new org.apache.sling.caconfig.spi.ConfigurationPersistenceStrategy() {

        @Override
        public Resource getResource(Resource resource) {
            return resource2;
        }

        @Override
        public String getResourcePath(String resourcePath) {
            return resource2.getPath();
        }

        @Override
        public boolean persistConfiguration(ResourceResolver resourceResolver, String configResourcePath, ConfigurationPersistData data) {
            return true;
        }

        @Override
        public boolean persistConfigurationCollection(ResourceResolver resourceResolver, String configResourceCollectionParentPath, ConfigurationCollectionPersistData data) {
            return false;
        }

        @Override
        public boolean deleteConfiguration(ResourceResolver resourceResolver, String configResourcePath) {
            return false;
        }
    }, Constants.SERVICE_RANKING, 2000);
    // strategy 2
    context.registerService(ConfigurationPersistenceStrategy2.class, new ConfigurationPersistenceStrategy2() {

        @Override
        public Resource getResource(Resource resource) {
            return resource1;
        }

        @Override
        public Resource getCollectionParentResource(Resource resource) {
            return resource1;
        }

        @Override
        public Resource getCollectionItemResource(Resource resource) {
            return resource1;
        }

        @Override
        public String getResourcePath(String resourcePath) {
            return resource1.getPath();
        }

        @Override
        public String getCollectionParentResourcePath(String resourcePath) {
            return resource1.getPath();
        }

        @Override
        public String getCollectionItemResourcePath(String resourcePath) {
            return resource1.getPath();
        }

        @Override
        public String getConfigName(String configName, String relatedConfigPath) {
            return resource1.getPath();
        }

        @Override
        public String getCollectionParentConfigName(String configName, String relatedConfigPath) {
            return resource1.getPath();
        }

        @Override
        public String getCollectionItemConfigName(String configName, String relatedConfigPath) {
            return resource1.getPath();
        }

        @Override
        public boolean persistConfiguration(ResourceResolver resourceResolver, String configResourcePath, ConfigurationPersistData data) {
            return false;
        }

        @Override
        public boolean persistConfigurationCollection(ResourceResolver resourceResolver, String configResourceCollectionParentPath, ConfigurationCollectionPersistData data) {
            return true;
        }

        @Override
        public boolean deleteConfiguration(ResourceResolver resourceResolver, String configResourcePath) {
            return true;
        }
    }, Constants.SERVICE_RANKING, 1000);
    assertSame(resource2, underTest.getResource(resource1));
    assertSame(resource1, underTest.getCollectionParentResource(resource1));
    assertSame(resource2, underTest.getCollectionItemResource(resource1));
    assertEquals(resource2.getPath(), underTest.getResourcePath(resource1.getPath()));
    assertEquals(resource1.getPath(), underTest.getCollectionParentResourcePath(resource1.getPath()));
    assertEquals(resource2.getPath(), underTest.getCollectionItemResourcePath(resource1.getPath()));
    assertEquals(resource2.getPath(), underTest.getConfigName(resource1.getPath(), null));
    assertEquals(resource1.getPath(), underTest.getCollectionParentConfigName(resource1.getPath(), null));
    assertEquals(resource2.getPath(), underTest.getCollectionItemConfigName(resource1.getPath(), null));
    assertEquals(ImmutableList.of(resource2.getPath(), resource1.getPath()), ImmutableList.copyOf(underTest.getAllConfigNames(resource1.getPath())));
    assertEquals(ImmutableList.of(resource1.getPath()), ImmutableList.copyOf(underTest.getAllCollectionParentConfigNames(resource1.getPath())));
    assertEquals(ImmutableList.of(resource2.getPath(), resource1.getPath()), ImmutableList.copyOf(underTest.getAllCollectionItemConfigNames(resource1.getPath())));
    assertTrue(underTest.persistConfiguration(context.resourceResolver(), "/conf/test1", new ConfigurationPersistData(resource1.getValueMap())));
    assertTrue(underTest.persistConfigurationCollection(context.resourceResolver(), "/conf/testCol", new ConfigurationCollectionPersistData(ImmutableList.of(new ConfigurationPersistData(resource1.getValueMap()).collectionItemName(resource1.getName()), new ConfigurationPersistData(resource2.getValueMap()).collectionItemName(resource2.getName())))));
    assertTrue(underTest.deleteConfiguration(context.resourceResolver(), "/conf/test1"));
}
Also used : ConfigurationPersistenceStrategy2(org.apache.sling.caconfig.spi.ConfigurationPersistenceStrategy2) ConfigurationPersistData(org.apache.sling.caconfig.spi.ConfigurationPersistData) ConfigurationCollectionPersistData(org.apache.sling.caconfig.spi.ConfigurationCollectionPersistData) Resource(org.apache.sling.api.resource.Resource) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) Test(org.junit.Test)

Example 13 with ResourceResolver

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

the class AnnouncementRegistryImpl method listAnnouncementsInSameCluster.

@Override
public synchronized Collection<Announcement> listAnnouncementsInSameCluster(final ClusterView localClusterView) {
    logger.debug("listAnnouncementsInSameCluster: start. localClusterView: {}", 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.getServiceResourceResolver(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();
            logger.debug("listAnnouncementsInSameCluster: handling clusterInstance: {}", instanceId);
            if (localInstance != null && localInstance.getSlingId().equals(instanceId)) {
                // this is the local instance then - which we serve from the cache only
                logger.debug("listAnnouncementsInSameCluster: matched localInstance, filling with cache: {}", instanceId);
                fillWithCachedAnnouncements(incomingAnnouncements);
                continue;
            }
            //TODO: add ClusterView.contains(instanceSlingId) for convenience to next api change
            if (!contains(localClusterView, instanceId)) {
                logger.debug("listAnnouncementsInSameCluster: instance is not in my view, ignoring: {}", instanceId);
                // (corresponds to earlier expiry-handling)
                continue;
            }
            final Resource announcementsResource = aClusterInstanceResource.getChild("announcements");
            if (announcementsResource == null) {
                logger.debug("listAnnouncementsInSameCluster: instance has no announcements: {}", instanceId);
                continue;
            }
            logger.debug("listAnnouncementsInSameCluster: instance has announcements: {}", instanceId);
            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));
                logger.debug("listAnnouncementsInSameCluster: found announcement: {}", topologyAnnouncement);
                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());
    }
    return incomingAnnouncements;
}
Also used : JsonException(javax.json.JsonException) ValueMap(org.apache.sling.api.resource.ValueMap) Resource(org.apache.sling.api.resource.Resource) LinkedList(java.util.LinkedList) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) PersistenceException(org.apache.sling.api.resource.PersistenceException) LoginException(org.apache.sling.api.resource.LoginException) InstanceDescription(org.apache.sling.discovery.InstanceDescription)

Example 14 with ResourceResolver

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

the class AnnouncementRegistryImpl method unregisterAnnouncement.

@Override
public synchronized void unregisterAnnouncement(final String ownerId) {
    if (ownerId == null || ownerId.length() == 0) {
        throw new IllegalArgumentException("ownerId must not be null or empty");
    }
    // remove from the cache - even if there's an error afterwards
    ownAnnouncementsCache.remove(ownerId);
    if (resourceResolverFactory == null) {
        logger.error("unregisterAnnouncement: resourceResolverFactory is null");
        return;
    }
    ResourceResolver resourceResolver = null;
    try {
        resourceResolver = resourceResolverFactory.getServiceResourceResolver(null);
        final String path = config.getClusterInstancesPath() + "/" + slingId + "/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();
        }
    }
}
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)

Example 15 with ResourceResolver

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

the class DistributedEventReceiver method cleanUpObsoleteInstances.

private void cleanUpObsoleteInstances() {
    final Set<String> slingIds = this.instances;
    if (slingIds != null) {
        this.instances = null;
        this.logger.debug("Checking for old instance trees for distributed events.");
        ResourceResolver resolver = null;
        try {
            resolver = this.resourceResolverFactory.getServiceResourceResolver(null);
            final Resource baseResource = resolver.getResource(this.rootPath);
            // sanity check - should never be null
            if (baseResource != null) {
                final ResourceHelper.BatchResourceRemover brr = ResourceHelper.getBatchResourceRemover(50);
                final Iterator<Resource> iter = baseResource.listChildren();
                while (iter.hasNext()) {
                    final Resource rootResource = iter.next();
                    if (!slingIds.contains(rootResource.getName())) {
                        brr.delete(rootResource);
                    }
                }
                // final commit for outstanding deletes
                resolver.commit();
            }
        } catch (final PersistenceException pe) {
            // in the case of an error, we just log this as a warning
            this.logger.warn("Exception during job resource tree cleanup.", pe);
        } catch (final LoginException ignore) {
            this.ignoreException(ignore);
        } finally {
            if (resolver != null) {
                resolver.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)

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