Search in sources :

Example 1 with Path

use of org.apache.sling.api.resource.path.Path in project sling by apache.

the class MapEntries method getVanityPaths.

/**
     * get the vanity paths  Search for all nodes having a specific vanityPath
     */
private Map<String, List<MapEntry>> getVanityPaths(String vanityPath) {
    Map<String, List<MapEntry>> entryMap = new HashMap<>();
    // sling:vanityPath (lowercase) is the property name
    final String queryString = "SELECT sling:vanityPath, sling:redirect, sling:redirectStatus FROM nt:base WHERE sling:vanityPath =" + "'" + escapeIllegalXpathSearchChars(vanityPath).replaceAll("'", "''") + "' OR sling:vanityPath =" + "'" + escapeIllegalXpathSearchChars(vanityPath.substring(1)).replaceAll("'", "''") + "' ORDER BY sling:vanityOrder DESC";
    ResourceResolver queryResolver = null;
    try {
        queryResolver = factory.getServiceResourceResolver(factory.getServiceUserAuthenticationInfo("mapping"));
        final Iterator<Resource> i = queryResolver.findResources(queryString, "sql");
        while (i.hasNext()) {
            final Resource resource = i.next();
            boolean isValid = false;
            for (final Path sPath : this.factory.getObservationPaths()) {
                if (sPath.matches(resource.getPath())) {
                    isValid = true;
                    break;
                }
            }
            if (isValid) {
                if (this.factory.isMaxCachedVanityPathEntriesStartup() || vanityCounter.longValue() < this.factory.getMaxCachedVanityPathEntries()) {
                    loadVanityPath(resource, resolveMapsMap, vanityTargets, true, false);
                    entryMap = resolveMapsMap;
                } else {
                    final Map<String, List<String>> targetPaths = new HashMap<>();
                    loadVanityPath(resource, entryMap, targetPaths, true, false);
                }
            }
        }
    } catch (LoginException e) {
        log.error("Exception while obtaining queryResolver", e);
    } finally {
        if (queryResolver != null) {
            queryResolver.close();
        }
    }
    return entryMap;
}
Also used : Path(org.apache.sling.api.resource.path.Path) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) Resource(org.apache.sling.api.resource.Resource) LoginException(org.apache.sling.api.resource.LoginException) List(java.util.List) ArrayList(java.util.ArrayList)

Example 2 with Path

use of org.apache.sling.api.resource.path.Path in project sling by apache.

the class MapEntries method loadVanityPaths.

/**
     * Load vanity paths Search for all nodes inheriting the sling:VanityPath
     * mixin
     */
private Map<String, List<String>> loadVanityPaths(boolean createVanityBloomFilter) {
    // sling:vanityPath (lowercase) is the property name
    final Map<String, List<String>> targetPaths = new ConcurrentHashMap<>();
    final String queryString = "SELECT sling:vanityPath, sling:redirect, sling:redirectStatus FROM nt:base WHERE sling:vanityPath IS NOT NULL";
    final Iterator<Resource> i = resolver.findResources(queryString, "sql");
    while (i.hasNext() && (createVanityBloomFilter || isAllVanityPathEntriesCached() || vanityCounter.longValue() < this.factory.getMaxCachedVanityPathEntries())) {
        final Resource resource = i.next();
        boolean isValid = false;
        for (final Path sPath : this.factory.getObservationPaths()) {
            if (sPath.matches(resource.getPath())) {
                isValid = true;
                break;
            }
        }
        if (isValid) {
            if (isAllVanityPathEntriesCached() || vanityCounter.longValue() < this.factory.getMaxCachedVanityPathEntries()) {
                // fill up the cache and the bloom filter
                loadVanityPath(resource, resolveMapsMap, targetPaths, true, createVanityBloomFilter);
            } else {
                // fill up the bloom filter
                loadVanityPath(resource, resolveMapsMap, targetPaths, false, createVanityBloomFilter);
            }
        }
    }
    return targetPaths;
}
Also used : Path(org.apache.sling.api.resource.path.Path) Resource(org.apache.sling.api.resource.Resource) List(java.util.List) ArrayList(java.util.ArrayList) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 3 with Path

use of org.apache.sling.api.resource.path.Path in project sling by apache.

the class ResourceResolverFactoryActivator method activate.

// ---------- SCR Integration ---------------------------------------------
/**
     * Activates this component (called by SCR before)
     */
@Activate
protected void activate(final BundleContext bundleContext, final ResourceResolverFactoryConfig config) {
    this.bundleContext = bundleContext;
    this.config = config;
    final BidiMap virtuals = new TreeBidiMap();
    for (int i = 0; config.resource_resolver_virtual() != null && i < config.resource_resolver_virtual().length; i++) {
        final String[] parts = Mapping.split(config.resource_resolver_virtual()[i]);
        virtuals.put(parts[0], parts[2]);
    }
    virtualURLMap = virtuals;
    final List<Mapping> maps = new ArrayList<>();
    for (int i = 0; config.resource_resolver_mapping() != null && i < config.resource_resolver_mapping().length; i++) {
        maps.add(new Mapping(config.resource_resolver_mapping()[i]));
    }
    final Mapping[] tmp = maps.toArray(new Mapping[maps.size()]);
    // check whether direct mappings are allowed
    if (config.resource_resolver_allowDirect()) {
        final Mapping[] tmp2 = new Mapping[tmp.length + 1];
        tmp2[0] = Mapping.DIRECT;
        System.arraycopy(tmp, 0, tmp2, 1, tmp.length);
        mappings = tmp2;
    } else {
        mappings = tmp;
    }
    // from configuration if available
    searchPath = config.resource_resolver_searchpath();
    if (searchPath != null && searchPath.length > 0) {
        for (int i = 0; i < searchPath.length; i++) {
            // ensure leading slash
            if (!searchPath[i].startsWith("/")) {
                searchPath[i] = "/" + searchPath[i];
            }
            // ensure trailing slash
            if (!searchPath[i].endsWith("/")) {
                searchPath[i] += "/";
            }
        }
    }
    if (searchPath == null) {
        searchPath = new String[] { "/" };
    }
    // the root of the resolver mappings
    mapRoot = config.resource_resolver_map_location();
    mapRootPrefix = mapRoot + '/';
    final String[] paths = config.resource_resolver_map_observation();
    this.observationPaths = new Path[paths.length];
    for (int i = 0; i < paths.length; i++) {
        this.observationPaths[i] = new Path(paths[i]);
    }
    // vanity path white list
    this.vanityPathWhiteList = null;
    String[] vanityPathPrefixes = config.resource_resolver_vanitypath_whitelist();
    if (vanityPathPrefixes != null) {
        final List<String> prefixList = new ArrayList<>();
        for (final String value : vanityPathPrefixes) {
            if (value.trim().length() > 0) {
                if (value.trim().endsWith("/")) {
                    prefixList.add(value.trim());
                } else {
                    prefixList.add(value.trim() + "/");
                }
            }
        }
        if (prefixList.size() > 0) {
            this.vanityPathWhiteList = prefixList.toArray(new String[prefixList.size()]);
        }
    }
    // vanity path black list
    this.vanityPathBlackList = null;
    vanityPathPrefixes = config.resource_resolver_vanitypath_blacklist();
    if (vanityPathPrefixes != null) {
        final List<String> prefixList = new ArrayList<>();
        for (final String value : vanityPathPrefixes) {
            if (value.trim().length() > 0) {
                if (value.trim().endsWith("/")) {
                    prefixList.add(value.trim());
                } else {
                    prefixList.add(value.trim() + "/");
                }
            }
        }
        if (prefixList.size() > 0) {
            this.vanityPathBlackList = prefixList.toArray(new String[prefixList.size()]);
        }
    }
    // check for required property
    Set<String> requiredResourceProvidersLegacy = getStringSet(config.resource_resolver_required_providers());
    Set<String> requiredResourceProviderNames = getStringSet(config.resource_resolver_required_providernames());
    boolean hasLegacyRequiredProvider = false;
    if (requiredResourceProvidersLegacy != null) {
        hasLegacyRequiredProvider = requiredResourceProvidersLegacy.remove(ResourceResolverFactoryConfig.LEGACY_REQUIRED_PROVIDER_PID);
        if (!requiredResourceProvidersLegacy.isEmpty()) {
            logger.error("ResourceResolverFactory is using deprecated required providers configuration (resource.resolver.required.providers" + "). Please change to use the property resource.resolver.required.providernames for values: " + requiredResourceProvidersLegacy);
        } else {
            requiredResourceProvidersLegacy = null;
        }
    }
    if (hasLegacyRequiredProvider) {
        final boolean hasRequiredProvider;
        if (requiredResourceProviderNames != null) {
            hasRequiredProvider = !requiredResourceProviderNames.add(ResourceResolverFactoryConfig.REQUIRED_PROVIDER_NAME);
        } else {
            hasRequiredProvider = false;
            requiredResourceProviderNames = Collections.singleton(ResourceResolverFactoryConfig.REQUIRED_PROVIDER_NAME);
        }
        if (hasRequiredProvider) {
            logger.warn("ResourceResolverFactory is using deprecated required providers configuration (resource.resolver.required.providers" + ") with value '" + ResourceResolverFactoryConfig.LEGACY_REQUIRED_PROVIDER_PID + ". Please remove this configuration property. " + ResourceResolverFactoryConfig.REQUIRED_PROVIDER_NAME + " is already contained in the property resource.resolver.required.providernames.");
        } else {
            logger.warn("ResourceResolverFactory is using deprecated required providers configuration (resource.resolver.required.providers" + ") with value '" + ResourceResolverFactoryConfig.LEGACY_REQUIRED_PROVIDER_PID + ". Please remove this configuration property and add " + ResourceResolverFactoryConfig.REQUIRED_PROVIDER_NAME + " to the property resource.resolver.required.providernames.");
        }
    }
    // for testing: if we run unit test, both trackers are set from the outside
    if (this.resourceProviderTracker == null) {
        this.resourceProviderTracker = new ResourceProviderTracker();
        this.changeListenerWhiteboard = new ResourceChangeListenerWhiteboard();
        this.preconds.activate(this.bundleContext, requiredResourceProvidersLegacy, requiredResourceProviderNames, resourceProviderTracker);
        this.changeListenerWhiteboard.activate(this.bundleContext, this.resourceProviderTracker, searchPath);
        this.resourceProviderTracker.activate(this.bundleContext, this.eventAdmin, new ChangeListener() {

            @Override
            public void providerAdded() {
                if (factoryRegistration == null) {
                    checkFactoryPreconditions(null, null);
                }
            }

            @Override
            public void providerRemoved(final String name, final String pid, final boolean stateful, final boolean isUsed) {
                if (factoryRegistration != null) {
                    if (isUsed && (stateful || config.resource_resolver_providerhandling_paranoid())) {
                        unregisterFactory();
                    }
                    checkFactoryPreconditions(name, pid);
                }
            }
        });
    } else {
        this.preconds.activate(this.bundleContext, requiredResourceProvidersLegacy, requiredResourceProviderNames, resourceProviderTracker);
        this.checkFactoryPreconditions(null, null);
    }
}
Also used : Path(org.apache.sling.api.resource.path.Path) ResourceProviderTracker(org.apache.sling.resourceresolver.impl.providers.ResourceProviderTracker) ArrayList(java.util.ArrayList) BidiMap(org.apache.commons.collections4.BidiMap) TreeBidiMap(org.apache.commons.collections4.bidimap.TreeBidiMap) Mapping(org.apache.sling.resourceresolver.impl.mapping.Mapping) ChangeListener(org.apache.sling.resourceresolver.impl.providers.ResourceProviderTracker.ChangeListener) TreeBidiMap(org.apache.commons.collections4.bidimap.TreeBidiMap) ResourceChangeListenerWhiteboard(org.apache.sling.resourceresolver.impl.observation.ResourceChangeListenerWhiteboard) Activate(org.osgi.service.component.annotations.Activate)

Example 4 with Path

use of org.apache.sling.api.resource.path.Path in project sling by apache.

the class ResourceProviderTracker method updateProviderContext.

private void updateProviderContext(final ResourceProviderHandler handler) {
    final Set<String> excludedPaths = new HashSet<String>();
    final Path handlerPath = new Path(handler.getPath());
    for (final String otherPath : handlers.keySet()) {
        if (!handler.getPath().equals(otherPath) && handlerPath.matches(otherPath)) {
            excludedPaths.add(otherPath);
        }
    }
    final PathSet excludedPathSet = PathSet.fromStringCollection(excludedPaths);
    handler.getProviderContext().update(reporterGenerator.create(handlerPath, excludedPathSet), excludedPathSet);
}
Also used : Path(org.apache.sling.api.resource.path.Path) PathSet(org.apache.sling.api.resource.path.PathSet) HashSet(java.util.HashSet)

Example 5 with Path

use of org.apache.sling.api.resource.path.Path in project sling by apache.

the class MapEntriesTest method setup.

@SuppressWarnings({ "unchecked" })
@Before
public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);
    final List<VanityPathConfig> configs = new ArrayList<>();
    configs.add(new VanityPathConfig("/libs/", false));
    configs.add(new VanityPathConfig("/libs/denied", true));
    configs.add(new VanityPathConfig("/foo/", false));
    configs.add(new VanityPathConfig("/baa/", false));
    configs.add(new VanityPathConfig("/justVanityPath", false));
    configs.add(new VanityPathConfig("/justVanityPath2", false));
    configs.add(new VanityPathConfig("/badVanityPath", false));
    configs.add(new VanityPathConfig("/redirectingVanityPath", false));
    configs.add(new VanityPathConfig("/redirectingVanityPath301", false));
    configs.add(new VanityPathConfig("/vanityPathOnJcrContent", false));
    Collections.sort(configs);
    vanityBloomFilterFile = new File("src/main/resourcesvanityBloomFilter.txt");
    when(bundle.getSymbolicName()).thenReturn("TESTBUNDLE");
    when(bundleContext.getBundle()).thenReturn(bundle);
    when(bundleContext.getDataFile("vanityBloomFilter.txt")).thenReturn(vanityBloomFilterFile);
    when(resourceResolverFactory.getServiceResourceResolver(any(Map.class))).thenReturn(resourceResolver);
    when(resourceResolverFactory.isVanityPathEnabled()).thenReturn(true);
    when(resourceResolverFactory.getVanityPathConfig()).thenReturn(configs);
    when(resourceResolverFactory.isOptimizeAliasResolutionEnabled()).thenReturn(true);
    when(resourceResolverFactory.getObservationPaths()).thenReturn(new Path[] { new Path("/") });
    when(resourceResolverFactory.getMapRoot()).thenReturn(MapEntries.DEFAULT_MAP_ROOT);
    when(resourceResolverFactory.getMaxCachedVanityPathEntries()).thenReturn(-1L);
    when(resourceResolverFactory.isMaxCachedVanityPathEntriesStartup()).thenReturn(true);
    when(resourceResolver.findResources(anyString(), eq("sql"))).thenReturn(Collections.<Resource>emptySet().iterator());
    mapEntries = new MapEntries(resourceResolverFactory, bundleContext, eventAdmin);
    final Field aliasMapField = MapEntries.class.getDeclaredField("aliasMap");
    aliasMapField.setAccessible(true);
    this.aliasMap = (Map<String, Map<String, String>>) aliasMapField.get(mapEntries);
}
Also used : Path(org.apache.sling.api.resource.path.Path) Field(java.lang.reflect.Field) ArrayList(java.util.ArrayList) Resource(org.apache.sling.api.resource.Resource) VanityPathConfig(org.apache.sling.resourceresolver.impl.mapping.MapConfigurationProvider.VanityPathConfig) Matchers.anyString(org.mockito.Matchers.anyString) File(java.io.File) ValueMap(org.apache.sling.api.resource.ValueMap) Map(java.util.Map) HashMap(java.util.HashMap) Before(org.junit.Before)

Aggregations

Path (org.apache.sling.api.resource.path.Path)8 ArrayList (java.util.ArrayList)4 HashMap (java.util.HashMap)3 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)3 Resource (org.apache.sling.api.resource.Resource)3 List (java.util.List)2 Map (java.util.Map)2 Test (org.junit.Test)2 File (java.io.File)1 Field (java.lang.reflect.Field)1 HashSet (java.util.HashSet)1 LinkedHashMap (java.util.LinkedHashMap)1 BidiMap (org.apache.commons.collections4.BidiMap)1 TreeBidiMap (org.apache.commons.collections4.bidimap.TreeBidiMap)1 LoginException (org.apache.sling.api.resource.LoginException)1 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)1 ValueMap (org.apache.sling.api.resource.ValueMap)1 PathSet (org.apache.sling.api.resource.path.PathSet)1 VanityPathConfig (org.apache.sling.resourceresolver.impl.mapping.MapConfigurationProvider.VanityPathConfig)1 Mapping (org.apache.sling.resourceresolver.impl.mapping.Mapping)1