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

The following examples show how to use org.apache.sling.api.resource.LoginException. 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: 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 #2
Source File: MessageStoreImpl.java    From sling-samples with Apache License 2.0 6 votes vote down vote up
public void saveAll(Iterator<Message> iterator) throws IOException {
    ResourceResolver resolver = null;
    try {
        resolver = getResourceResolver();
        int mcount = 0;
        while (iterator.hasNext()) {
            Message msg = iterator.next();
            save(resolver, msg);

            mcount++;
            if (mcount % 100 == 0) {
                logger.debug(mcount+" messages processed.");
            }
        }
        logger.info(mcount+" messages processed.");
    } catch(LoginException e) {
        throw new RuntimeException("LoginException", e);
    } finally {
        if(resolver != null) {
            resolver.close();
        }
    }
}
 
Example #3
Source File: Activator.java    From aem-password-reset with Apache License 2.0 6 votes vote down vote up
@Activate
public void start(ActivatorConfiguration config) {
    String[] authorizableIds = config.pwdreset_authorizables();

    Session session = null;
    try {
        ResourceResolver resolver = resolverFactory.getAdministrativeResourceResolver(null);

        UserManager userManager = resolver.adaptTo(UserManager.class);
        session = resolver.adaptTo(Session.class);

        for (String authorizable : authorizableIds) {
            try {
                Authorizable user = userManager.getAuthorizable(authorizable);
                if (user != null) {
                    ((User) user).changePassword(authorizable);
                    if (!userManager.isAutoSave()) {
                        session.save();
                    }
                    log.info("Changed the password for {}", authorizable);
                } else {
                    log.error("Could not find authorizable {}", authorizable);
                }
            } catch (RepositoryException repEx) {
                log.error("Could not change password for {}", authorizable, repEx);
            }
        }
    } catch (LoginException loginEx) {
        log.error("Could not login to the repository", loginEx);
    } finally {
        if(session != null) {
            session.logout();
        }
    }
}
 
Example #4
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 #5
Source File: SampleServlet.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
    throws ServletException, IOException {
    ResourceResolver resourceResolver = null; // Noncompliant {{ResourceResolver should be closed in finally block.}}
    try {
        resourceResolver = resourceResolverFactory.getServiceResourceResolver(null);
    } catch (LoginException e) {
        LOGGER.error("Error during getting instance of ResourceResolver class", e);
    } finally {
        if (resourceResolver != null) {
            //resourceResolver.close();
        }
    }
}
 
Example #6
Source File: RatingPostServlet.java    From sling-samples with Apache License 2.0 5 votes vote down vote up
@Override
protected void doPost(final SlingHttpServletRequest request,
        final SlingHttpServletResponse response)
throws ServletException, IOException {
    final String rating = request.getParameter(RatingsUtil.PROPERTY_RATING);
    final String userId = request.getRemoteUser();

    logger.debug("New rating from {} : {}", userId, rating);

    // save rating
    ResourceResolver resolver = null;
    try {
        resolver = factory.getServiceResourceResolver(null);

        final Resource reqResource = resolver.getResource(request.getResource().getPath());

        ratingsService.setRating(reqResource, userId, Double.valueOf(rating));

    } catch ( final LoginException le ) {
        throw new ServletException("Unable to login", le);
    } finally {
        if ( resolver != null ) {
            resolver.close();
        }
    }

    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");
    response.setStatus(200);

    final PrintWriter pw = response.getWriter();
    pw.print("{ ");
    pw.print(" \"rating\" : ");
    pw.print(String.valueOf(ratingsService.getRating(request.getResource())));
    pw.print("}");
}
 
Example #7
Source File: CommentPostServlet.java    From sling-samples with Apache License 2.0 5 votes vote down vote up
@Override
protected void doPost(final SlingHttpServletRequest request,
        final SlingHttpServletResponse response)
throws ServletException, IOException {
    final String title = request.getParameter(CommentsUtil.PROPERTY_TITLE);
    final String text = request.getParameter(CommentsUtil.PROPERTY_TEXT);

    final String userId = request.getRemoteUser();

    logger.debug("New comment from {} : {} - {}", new Object[] {userId, title, text});
    // TODO - check values

    // save comment
    ResourceResolver resolver = null;
    try {
        resolver = factory.getServiceResourceResolver(null);

        final Resource reqResource = resolver.getResource(request.getResource().getPath());

        final Comment c = new Comment();
        c.setTitle(title);
        c.setText(text);
        c.setCreatedBy(userId);

        this.commentsService.addComment(reqResource, c);


        // send redirect at the end
        final String path = request.getResource().getPath();

        response.sendRedirect(resolver.map(request.getContextPath() + path + ".html"));
    } catch ( final LoginException le ) {
        throw new ServletException("Unable to login", le);
    } finally {
        if ( resolver != null ) {
            resolver.close();
        }
    }
}
 
Example #8
Source File: SetupService.java    From sling-samples with Apache License 2.0 5 votes vote down vote up
@Activate
protected void activate(final BundleContext bc) throws IOException, LoginException, PersistenceException, RepositoryException {
    logger.info("Setting up SlingShot...");
    ResourceResolver resolver = null;
    try {
        resolver = this.factory.getServiceResourceResolver(null);
        setupContent(resolver);
    } finally {
        if ( resolver != null ) {
            resolver.close();
        }
    }
    logger.info("Finished setting up SlingShot");
}
 
Example #9
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 #10
Source File: CheckPermissions.java    From APM with Apache License 2.0 5 votes vote down vote up
private void checkPermissionsForGlob(Session session, final boolean execute, final ActionResult actionResult,
    final Authorizable authorizable, final Set<Principal> authorizablesToCheck,
    final CqActions actions, final List<String> privilegesToCheck)
    throws RepositoryException, LoginException {
  final List<String> subpaths = getAllSubpaths(session, path);
  Pattern pattern = Pattern.compile(path + StringUtils.replace(glob, "*", ".*"));
  boolean foundMatch = false;
  boolean failed = false;
  for (String subpath : subpaths) {
    if (pattern.matcher(subpath).matches()) {
      foundMatch = true;
      failed = checkPermissionsForPath(authorizablesToCheck, actions, privilegesToCheck, subpath);
      if (failed) {
        logFailure(execute, actionResult, authorizable, subpath);
        break;
      }
    }
  }
  if (!foundMatch) {
    actionResult
        .logError("No match was found for " + authorizable.getID() + " for given glob " + glob);
    if (execute) {
      actionResult.logError(ActionUtils.ASSERTION_FAILED_MSG);
    }
  } else if (!failed) {
    actionResult.logMessage(
        "All required privileges are set for " + authorizable.getID() + " on " + path);
  }
}
 
Example #11
Source File: CheckPermissions.java    From APM with Apache License 2.0 5 votes vote down vote up
private List<String> getAllSubpaths(Session session, final String path) throws RepositoryException, LoginException {
  List<String> subPaths = new ArrayList<>();
  Node node = session.getNode(path);
  subPaths.addAll(crawl(node));

  return subPaths;
}
 
Example #12
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 #13
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 #14
Source File: SampleServlet.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
public void checkCorrectJumpMethod() {
    ResourceResolver resourceResolver = null;
    try {
        resourceResolver = getResourceResolverForUserNested(resourceResolverFactory, null);
    } catch (LoginException e) {
        e.printStackTrace();
    } finally {
        if (resourceResolver != null) {
            resourceResolver.close();
        }
    }
}
 
Example #15
Source File: SampleServlet.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
public void checkWrongJumpMethod() {
    ResourceResolver resourceResolver = null; // Noncompliant
    try {
        resourceResolver = getResourceResolverForUserNestedInit(resourceResolverFactory);
    } catch (LoginException e) {
        e.printStackTrace();
    } finally {
        if (resourceResolver != null) {
            //resourceResolver.close();
        }
    }
}
 
Example #16
Source File: AdministrativeAccessUsageCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
public ResourceResolver getResourceResolver(Map<String, Object> credentials) {
    ResourceResolver resolver = null;
    try {
        resolver = resolverFactory.getAdministrativeResourceResolver(credentials); // Noncompliant {{Method 'getAdministrativeResourceResolver' is deprecated. Use 'getServiceResourceResolver' instead.}}
    } catch (LoginException e) {
        //
    }
    return resolver;
}
 
Example #17
Source File: LongSessionService.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
@Activate
protected void activate(final BundleContext bundleContext, final Map<String, Object> properties) {
    try {
        resolver = resourceResolverFactory.getAdministrativeResourceResolver(null);
        registerObservation();
    } catch (LoginException x) {
    }
}
 
Example #18
Source File: AutoclosableResourceResolver.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
protected void resourceResolverInitialisedInTryBlockAndNotClosed() {
  ResourceResolver resourceResolver = null;
  try {
    resourceResolver = resourceResolverFactory.getServiceResourceResolver(null); // Noncompliant
  } catch (LoginException e) {
    System.out.println("something went wrong");
  } finally {
    if (resourceResolver != null) {
    }
  }
}
 
Example #19
Source File: AutoclosableResourceResolver.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
private void resourceResolverInitialisedInTryWithResourcesBlock() {
  try (ResourceResolver resourceResolver = resourceResolverFactory
      .getServiceResourceResolver(null)) {
    resourceResolver.getResource("path/to/resource");
  } catch (LoginException e) {
    System.out.println("something went wrong");
  }
}
 
Example #20
Source File: JCRBuilder.java    From jackalope with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the requested resource.
 *
 * @return the Resource
 */
public Resource build() {
    try {
        ResourceResolverImpl resolver = (ResourceResolverImpl)new SimpleResourceResolverFactory(new SlingRepositoryImpl()).getAdministrativeResourceResolver(null);
        return new NodeResourceImpl(resolver, ((NodeBuilderImpl)builder).build(resolver.adaptTo(Session.class)));
    }
    catch (LoginException le) {
        throw new SlingRepositoryException(le);
    }
}
 
Example #21
Source File: MessageStoreImpl.java    From sling-samples with Apache License 2.0 5 votes vote down vote up
public void save(Message msg) throws IOException {
    ResourceResolver resolver = null;
    try {
        resolver = getResourceResolver();
        save(resolver, msg);
    } catch (LoginException e) {
        throw new RuntimeException("LoginException", e);
    } finally {
        if(resolver != null) {
            resolver.close();
        }
    }
}
 
Example #22
Source File: ProductsSuggestionOmniSearchHandler.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
@Override
public void onEvent(EventIterator eventIterator) {
    if (resolver == null) {
        try {
            resolver = getResourceResolver();
            init(resolver);
            jsonMapper = new ObjectMapper();
        } catch (LoginException e) {
            LOGGER.error("Error initializing!", e);
        }
    }
}
 
Example #23
Source File: ComponentsConfigurationAdapterFactory.java    From aem-core-cif-components with Apache License 2.0 5 votes vote down vote up
protected void activate(ComponentContext context) {
    try {
        if (serviceResolver == null) {
            serviceResolver = resolverFactory.getServiceResourceResolver(authInfo);
        }
    } catch (LoginException e) {
        throw new RuntimeException(e);
    }
}
 
Example #24
Source File: SubjectLettersEntropy.java    From sling-samples with Apache License 2.0 5 votes vote down vote up
public void calculateEntropyAndPrint(PrintStream out) {
	try {
		if (resourceResolverFactory == null) {
			System.out.println("resourceResolverFactory is NULL");
		}
		resolver = resourceResolverFactory.getAdministrativeResourceResolver(null);

		String root = "/content/mailarchiveserver/archive"; // /domain/project/list/t/th/thread/message
		Resource main = resolver.getResource(root);
		iterate(main, 6);
		int[] sum = new int[SAMPLE_LENGTH];

		for (int i = 0; i < sum.length; i++) {
			for (int j = 0; j < ALPHABET_LENGTH; j++) {
				sum[i] += count[i][j];
			}
		}

		for (int i = 0; i < sum.length; i++) {
			for (int j = 0; j < ALPHABET_LENGTH; j++) {
				if (count[i][j] > 0) {
					double num = count[i][j]/1./sum[i];
					entropy[i] += - num * Math.log10(num); 
				}
			}
		}

		System.out.println(String.format("%s\t%s\t%s", "charAt","entropy", "sum"));
		for (int i = 0; i < sum.length; i++) {
			if (entropy[i] >= MAX_THEOR_ENTROPY*THRESHOLD || sum[i] >= messages*THRESHOLD) 
				System.out.println(String.format("%d\t%.3f\t%d", i, entropy[i], sum[i]));
		}
		out.println("Messages #: "+messages);
		
	} catch (LoginException e) {
		e.printStackTrace();
	}
}
 
Example #25
Source File: ProductsSuggestionOmniSearchHandler.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
@Deactivate
protected void deactivate(ComponentContext componentContext) throws LoginException {
    try {
        destroy(resolver);
    } finally {
        resolver.close();
    }
}
 
Example #26
Source File: ActivatorTest.java    From aem-password-reset with Apache License 2.0 5 votes vote down vote up
@Test
public void testAdminLoginError() throws Exception {
    when(mockResolverFactory.getAdministrativeResourceResolver(null)).thenThrow(new LoginException());

    Activator activator = spy(createActivator());
    activator.start(mockConfiguration);

    verify(mockAuthorizable, times(0)).changePassword(anyString());
    verify(mockSession, times(0)).save();
    verify(mockSession, times(0)).logout();
    verifyZeroInteractions(mockResolver);
    verifyZeroInteractions(mockAuthorizable);
    verifyZeroInteractions(mockUserManager);
    verifyZeroInteractions(mockSession);
}
 
Example #27
Source File: ProductsSuggestionOmniSearchHandler.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
@Activate
protected void activate(ComponentContext componentContext) throws LoginException, PathNotFoundException, RepositoryException {
    if (resolver == null) {
        resolver = getResourceResolver();
        init(resolver);
        jsonMapper = new ObjectMapper();
    }
}
 
Example #28
Source File: CatalogDataProviderManagerConfTest.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
@Test
public void testDataRoots() throws LoginException, RepositoryException, InterruptedException {
    String expectedDataRootPath = COMMERCE_ROOT + "/products/" + NN_DATA_ROOT;

    List<Resource> dataRoots = manager.getDataRoots();
    Assert.assertEquals("The manager found two data roots", 3, dataRoots.size());

    Resource dataRoot = dataRoots.get(0);
    Assert.assertEquals("The data root points to " + expectedDataRootPath, expectedDataRootPath, dataRoot.getPath());

}
 
Example #29
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 #30
Source File: MessageStoreImpl.java    From sling-samples with Apache License 2.0 5 votes vote down vote up
private boolean assertResource(ResourceResolver resolver, Resource parent, String name, Map<String, Object> newProps) 
        throws LoginException, PersistenceException {
    String checkPath = parent.getPath()+"/"+name;
    final Resource checkResource = resolver.getResource(checkPath);
    if (checkResource == null) {
        final Resource newResource = resolver.create(parent, name, newProps);
        resolver.commit();
        logger.debug(String.format("Resource created at %s .", newResource.getPath()));
        return true;
    } else {
        logger.debug(String.format("Resource at %s already exists.", checkResource.getPath()));
        return false;
    }
}