org.apache.sling.api.resource.ResourceResolverFactory Java Examples

The following examples show how to use org.apache.sling.api.resource.ResourceResolverFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MockRemoteStorageProvider.java    From sling-whiteboard with Apache License 2.0 6 votes vote down vote up
@Override
public @Nullable RemoteResourceReference findResource(@NotNull String slingPath, @NotNull Map<String, Object> authenticationInfo) {
    String path = slingPath.startsWith("/") ? slingPath.substring(1) : slingPath;
    java.io.File file = new java.io.File(root, path);
    while (file.getAbsolutePath().startsWith(root.getAbsolutePath())) {
        if (file.exists()) {
            if (!whitelist.isEmpty()) {
                String user = (String) authenticationInfo.get(ResourceResolverFactory.USER);
                if (user == null || user.isEmpty()) {
                    return null;
                }
                Set<String> whitelistedUsers = whitelist.get(file.getPath());
                if (whitelistedUsers != null) {
                    if (whitelistedUsers.contains(user)) {
                        return new MockRemoteResourceReference(this, file);
                    }
                }
            } else {
                return new MockRemoteResourceReference(this, file);
            }
        }
        file = file.getParentFile();
    }
    return null;
}
 
Example #2
Source File: SlingHelper.java    From APM with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new session for specified user (impersonating).
 */
public static ResourceResolver getResourceResolverForUser(ResourceResolverFactory factory, String userId)
    throws LoginException {
  ResourceResolver resolver;
  if (userId != null) {
    Map<String, Object> authenticationInfo = Maps.newHashMap();
    authenticationInfo.put(ResourceResolverFactory.USER_IMPERSONATION, userId);
    resolver = factory.getAdministrativeResourceResolver(authenticationInfo);
  } else {
    Map<String, Object> parameters = new HashMap<>();
    parameters.put(ResourceResolverFactory.SUBSERVICE, SUBSERVICE_NAME);
    resolver = factory.getServiceResourceResolver(parameters);
  }

  return resolver;
}
 
Example #3
Source File: SlingHelper.java    From APM with Apache License 2.0 6 votes vote down vote up
/**
 * Do some operation on repository (delete or update resource etc) with wrapped impersonated session
 * (automatically opened and closed).
 */
public static void operate(ResourceResolverFactory factory, String userId, OperateCallback callback)
    throws OperateException {
  ResourceResolver resolver = null;
  try {
    resolver = getResourceResolverForUser(factory, userId);
    callback.operate(resolver);
    resolver.commit();
  } catch (Exception e) {
    throw new OperateException(OPERATE_ERROR_MESSAGE, e);
  } finally {
    if (resolver != null && resolver.isLive()) {
      resolver.close();
    }
  }
}
 
Example #4
Source File: SlingHelper.java    From APM with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve values from repository with wrapped impersonated session (automatically opened and closed).
 */
@SuppressWarnings("unchecked")
public static <T> T resolve(ResourceResolverFactory factory, String userId, ResolveCallback callback)
    throws ResolveException {
  ResourceResolver resolver = null;
  try {
    resolver = getResourceResolverForUser(factory, userId);
    return (T) callback.resolve(resolver);
  } catch (Exception e) {
    throw new ResolveException(RESOLVE_ERROR_MESSAGE, e);
  } finally {
    if (resolver != null && resolver.isLive()) {
      resolver.close();
    }
  }
}
 
Example #5
Source File: SlingResource.java    From sling-whiteboard with Apache License 2.0 6 votes vote down vote up
@GET
public Response sling(@PathParam("resourcePath") String resourcePath) throws IOException, LoginException {
    final SlingRequestProcessor p = SlingContext.get().getService(SlingRequestProcessor.class);
    assert (p != null);

    final ResourceResolverFactory fac = SlingContext.get().getService(ResourceResolverFactory.class);
    assertNotNull("Expecting a ResourceResolverFactory", fac);
    final ResourceResolver resolver = fac.getResourceResolver(new HashMap<String, Object>());
    assertNotNull("Expecting a ResourceResolver", resolver);

    request.setAttribute(RequestProgressTracker.class.getName(), new SlingRequestProgressTracker(request));

    try {
        p.processRequest(request, new HttpResponse(), resolver);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    final Resource r = (Resource)request.getAttribute(MockServletResolver.RESOURCE_ATTR);
    return Response.ok(r).build();
}
 
Example #6
Source File: SlingContextTest.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
@BeforeAll
public static void setup() throws LoginException {
    final ResourceResolverFactory fac = SlingContext.get().getService(ResourceResolverFactory.class);
    assertNotNull("Expecting a ResourceResolverFactory", fac);
    resolver = fac.getResourceResolver(new HashMap<String, Object>());
    assertNotNull("Expecting a ResourceResolver", resolver);
}
 
Example #7
Source File: MockRemoteStorageProvider.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
@Override
public @Nullable Directory getDirectory(@NotNull RemoteResourceReference reference, @Nullable Map<String, Object> authenticationInfo) {
    java.io.File file = ((MockRemoteResourceReference) reference).file;
    if (!file.exists() || !file.isDirectory()) {
        return null;
    }
    List<RemoteResourceReference> children = new ArrayList<>();
    for (java.io.File f : file.listFiles()) {
        MockRemoteResourceReference child = null;
        if (!whitelist.isEmpty()) {
            String user = (String) authenticationInfo.get(ResourceResolverFactory.USER);
            if (user == null || user.isEmpty()) {
                return null;
            }
            Set<String> whitelistedUsers = whitelist.get(f.getPath());
            if (whitelistedUsers != null) {
                if (whitelistedUsers.contains(user)) {
                    child = new MockRemoteResourceReference(this, f);
                }
            }
        } else {
            child = new MockRemoteResourceReference(this, f);
        }
        if (child != null) {
            children.add(child);
        }
    }
    return new MockDirectory(this, file, children);
}
 
Example #8
Source File: ComponentsConfigurationAdapterFactoryTest.java    From aem-core-cif-components with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    context.load().json("/context/jcr-conf.json", "/conf/testing");
    context.load().json("/context/jcr-content.json", "/content/my-site");
    ResourceResolverFactory resourceResolverFactory = Mockito.mock(ResourceResolverFactory.class);
    ServiceUserMapped serviceUserMapped = Mockito.mock(ServiceUserMapped.class);

    context.registerService(ServiceUserMapped.class, serviceUserMapped, ImmutableMap.of(ServiceUserMapped.SUBSERVICENAME,
        "cif-components-configuration"));

    ComponentsConfigurationAdapterFactory factory = new ComponentsConfigurationAdapterFactory();

    context.registerInjectActivateService(factory);
}
 
Example #9
Source File: SampleServlet.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new session for specified user (impersonating).
 */
public static ResourceResolver getResourceResolverForUser(ResourceResolverFactory factory, String userId)
    throws LoginException {
    ResourceResolver resolver;
    if (userId != null) {
        Map<String, Object> authenticationInfo = new HashMap<>();
        authenticationInfo.put(ResourceResolverFactory.USER_IMPERSONATION, userId);
        resolver = factory.getServiceResourceResolver(authenticationInfo);
    } else {
        resolver = factory.getServiceResourceResolver(null);
    }
    return resolver;
}
 
Example #10
Source File: SlingHelper.java    From APM with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve values from repository with wrapped session (automatically opened and closed).
 */
public static <T> T resolveDefault(ResourceResolverFactory factory, String userId, ResolveCallback callback,
    T defaultValue) {
  try {
    return resolve(factory, userId, callback);
  } catch (ResolveException e) {
    LOG.error(RESOLVE_ERROR_MESSAGE, e);
  }

  return defaultValue;
}
 
Example #11
Source File: CatalogDataResourceProviderManagerImpl.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
@Activate
protected synchronized void activate(final ComponentContext ctx) throws LoginException, RepositoryException {
    // check enabled state
    if (resolver == null) {
        bundleContext = ctx.getBundleContext();
        final Map<String, Object> map = new HashMap<>();
        map.put(ResourceResolverFactory.SUBSERVICE, VIRTUAL_PRODUCTS_SERVICE);
        resolver = resolverFactory.getServiceResourceResolver(map);

        // Watch for events on the root to register/deregister virtual catalogs data roots at runtime
        // For each observed path create an event listener object which redirects the event to the main class
        final Session session = resolver.adaptTo(Session.class);
        if (session != null) {
            this.observationEventListeners = new EventListener[this.observationPaths.length];
            for (int i = 0; i < this.observationPaths.length; i++) {
                this.observationEventListeners[i] = new EventListener() {
                    public void onEvent(EventIterator events) {
                        CatalogDataResourceProviderManagerImpl.this.onEvent(events);
                    }
                };
                session.getWorkspace()
                    .getObservationManager()
                    .addEventListener(this.observationEventListeners[i],
                        Event.NODE_ADDED | Event.NODE_REMOVED | Event.PROPERTY_ADDED | Event.PROPERTY_CHANGED | Event.PROPERTY_REMOVED,
                        this.observationPaths[i],
                        // absolute path
                        true,
                        // isDeep
                        null,
                        // uuids
                        null,
                        // node types
                        true); // noLocal
            }
        }

        // register all virtual catalog data definitions that already exist
        registerDataRoots();
    }
}
 
Example #12
Source File: SlingHelper.java    From APM with Apache License 2.0 5 votes vote down vote up
/**
 * Do some operation on repository (delete or update resource etc) with wrapped session (automatically
 * opened and closed).
 */
public static void operateTraced(ResourceResolverFactory factory, String userId, OperateCallback callback) {
  try {
    operate(factory, userId, callback);
  } catch (OperateException e) {
    LOG.error(OPERATE_ERROR_MESSAGE, e);
  }
}
 
Example #13
Source File: ProductBindingCreator.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
protected void activate(final ComponentContext context) throws LoginException {
    LOG.debug("Activating the component");
    final Map<String, Object> map = new HashMap<>();
    map.put(ResourceResolverFactory.SUBSERVICE, PRODUCT_BINDING_SERVICE);
    resolver = resolverFactory.getServiceResourceResolver(map);
    LOG.debug("Do we have a resolver? {}", resolver != null);
}
 
Example #14
Source File: SampleServlet.java    From AEM-Rules-for-SonarQube with Apache License 2.0 4 votes vote down vote up
public static ResourceResolver getResourceResolverForUserInit(ResourceResolverFactory factory)
    throws LoginException {
    ResourceResolver resolver = factory.getServiceResourceResolver(null);
    return resolver;
}
 
Example #15
Source File: SampleServlet.java    From AEM-Rules-for-SonarQube with Apache License 2.0 4 votes vote down vote up
public static ResourceResolver getResourceResolverForUserNested(ResourceResolverFactory factory, String userId)
    throws LoginException {
    ResourceResolver resolver;
    resolver = getResourceResolverForUser(resourceResolverFactory, userId);
    return resolver;
}
 
Example #16
Source File: SampleServlet.java    From AEM-Rules-for-SonarQube with Apache License 2.0 4 votes vote down vote up
public static ResourceResolver getResourceResolverForUserNestedInit(ResourceResolverFactory factory)
    throws LoginException {
    ResourceResolver resolver = getResourceResolverForUserInit(resourceResolverFactory);
    return resolver;
}
 
Example #17
Source File: SlingHelper.java    From APM with Apache License 2.0 4 votes vote down vote up
public static ResourceResolver getResourceResolverForService(ResourceResolverFactory factory)
    throws LoginException {
  return getResourceResolverForUser(factory, null);
}
 
Example #18
Source File: SlingHelper.java    From APM with Apache License 2.0 4 votes vote down vote up
/**
 * Retrieve values from repository with wrapped session (automatically opened and closed).
 */
public static <T> T resolveDefault(ResourceResolverFactory factory, ResolveCallback callback,
    T defaultValue) {
  return resolveDefault(factory, null, callback, defaultValue);
}
 
Example #19
Source File: RemoteResourceProvider.java    From sling-whiteboard with Apache License 2.0 4 votes vote down vote up
private String extractUser(@NotNull Map<String, Object> authenticationInfo) {
    if (requiresAuthentication) {
        return (String) authenticationInfo.get(ResourceResolverFactory.USER);
    }
    return ANY;
}
 
Example #20
Source File: Activator.java    From aem-password-reset with Apache License 2.0 4 votes vote down vote up
@Reference
protected void setResourceResolverFactory(ResourceResolverFactory resolverFactory) {
    this.resolverFactory = resolverFactory;
}
 
Example #21
Source File: ProductsSuggestionOmniSearchHandler.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
ResourceResolver getResourceResolver() throws LoginException {
    Map<String, Object> param = new HashMap<>();
    param.put(ResourceResolverFactory.SUBSERVICE, OMNI_SEARCH_SERVICE_USER);
    return resolverFactory.getServiceResourceResolver(param);
}
 
Example #22
Source File: SlingHelper.java    From APM with Apache License 2.0 2 votes vote down vote up
/**
 * Do some operation on repository (delete or update resource etc) with wrapped session (automatically
 * opened and closed).
 */
public static void operateTraced(ResourceResolverFactory factory, OperateCallback callback) {
  operateTraced(factory, null, callback);
}