Search code examples
javaaemjcrsling

Programmatically Accessing CQ5 Content using the JCR


I would like to access the content programmatically, I tried the following:

private Session getSession(String user, String passwort) {
        Session session = null;
        try {
            Repository repository = JcrUtils.getRepository("http://localhost:4503/crx/server");
            JcrUtils.getRepository("http://localhost:4503/crx/server");
            session = repository.login(new SimpleCredentials(user, passwort.toCharArray()));
        } catch (RepositoryException e) {
            LOG.error(e.getMessage());
        }
        return session;
    }

I get the following exception when I call the getRepository method:

 javax.jcr.RepositoryException: Unable to access a repository with the following settings:
        org.apache.jackrabbit.repository.uri: http://localhost:4503/crx/server
    The following RepositoryFactory classes were consulted:
    Perhaps the repository you are trying to access is not available at the moment.

I have the version cq5.4. Any idea?

P.S: I tried to Access publish and author instance and got the same exception.


Solution

  • You don't need and don't want to call JcrUtils.getRepository in a Sling/CQ app, you should rather access the SlingRepository OSGi service that CQ provides.

    The simplest is to use an @Reference annotation in an OSGi declarative services @Component - there are multiple examples of this in the Apache Sling codebase, the http://svn.apache.org/repos/asf/sling/trunk/samples/slingbucks sample is a good starting point for that.

    If your code executes as part of request processing, you don't need to create a Session yourself, you can get it by calling request.getResourceResolver().adaptTo(Session.class) where request is the SlingHttpServletRequest that you get in a Sling servlet.