Search code examples
javajackrabbitjcrsling

Create a new mixin in sling


I am having trouble create a new custom type to the jackrabbit in apache sling using the below code. This worked fine straight on Jackrabbit but not on Apache Sling. Am I doing this correctly for sling? Thanks

The following code gives me a "javax.jcr.InvalidItemStateException: Conflict". I am using a standalone sling and am the only user so there is definitely no conflict.

Repository repository = JcrUtils.getRepository("http://localhost:8080/server");

Session session = repository.login(new SimpleCredentials("admin", "admin".toCharArray()));

NamespaceRegistry registry = session.getWorkspace().getNamespaceRegistry();
registry.registerNamespace("my", "http://my.com/v1.0");

CndImporter.registerNodeTypes(new FileReader("C:\\test.cnd"), session);

Solution

  • If you're using Sling, you can avoid all this by putting your CND file in an OSGi bundle (where your java code should reside anyway), with a header that tells Sling where to find it.

    Your node types will then be registered automatically when your bundle is activated. For an example of this see the event.cnd file which is declared in a Sling-Nodetypes bundle header that's set in that module's pom.xml (or in any other way if you're not using Maven).

    Note also that you shouldn't need JcrUtils.getRepository in Sling anyway, the right way to get a repository is via the SlingRepository OSGi service, which takes care of repository login and configuration in a consistent way for all your Sling components. You can get the repository via a @Reference to a SlingRepository in java code, or get a JCR Session from the Resource that Sling provides to request handlers like servlets and scripts. The Slingbucks sample uses both mechanisms.