ExamplesPage

Apache Jackrabbit Examples

This page will be used to show solutions to common problems related to Apache Jackrabbit and the JCR API. These examples shouldn't be considered Best Practices - general error checking and exception handling have been omitted to keep the example code simple.

Please feel free to add your own examples.

Importing a File

Also see: [WWW] FSImport.java for more complete filesystem examples.

    public Node importFile (Node folderNode, File file, String mimeType,
            String encoding) throws RepositoryException, IOException
    {
        //create the file node - see section 6.7.22.6 of the spec
        Node fileNode = folderNode.addNode (file.getName (), "nt:file");
        
        //create the mandatory child node - jcr:content
        Node resNode = fileNode.addNode ("jcr:content", "nt:resource");
        resNode.setProperty ("jcr:mimeType", mimeType);
        resNode.setProperty ("jcr:encoding", encoding);
        resNode.setProperty ("jcr:data", new FileInputStream (file));
        Calendar lastModified = Calendar.getInstance ();
        lastModified.setTimeInMillis (file.lastModified ());
        resNode.setProperty ("jcr:lastModified", lastModified);

        return fileNode;
    }

Renaming a Node

    void rename(Node node, String newName) throws RepositoryException 
    {
        node.getSession().move(node.getPath(), node.getParent().getPath() + "/" + newName);
    }

Register a Node Type

There are a few solutions in the works. For example, see [WWW] OSAF offline tool, [WWW] Graffito Jira Issue.

    public void registerNodeType(NodeTypeDef nodeTypeDef, Session session) throws RepositoryException
    {
        //NodeTypeRegistry object
        Workspace wsp = session.getWorkspace();
        NodeTypeManager ntMgr = wsp.getNodeTypeManager();
        
        //non-JSR 170 - jackrabbit specific
        NodeTypeRegistry ntReg = 
                ((NodeTypeManagerImpl) ntMgr).getNodeTypeRegistry();
        ntReg.registerNodeType(nodeTypeDef);
    }

Register a Node Type [CND]

Register one or more node types using CND. CND is described in [WWW] http://jackrabbit.apache.org/node-type-notation.html.

    public void createCustomNodeTypes(Session session)
        throws RepositoryException, IOException {

        // Get the JackrabbitNodeTypeManager from the Workspace.
        // Note that it must be cast from the generic JCR NodeTypeManager to
        // the  Jackrabbit-specific implementation.
        // (see: http://jackrabbit.apache.org/node-types.html)
        JackrabbitNodeTypeManager manager =
           (JackrabbitNodeTypeManager) session.getWorkspace().getNodeTypeManager();

        // Register the custom node types defined in the CND file
        InputStream is = Thread.currentThread().getContextClassLoader()
                             .getResourceAsStream("com/example/jcr/custom.cnd");
        manager.registerNodeTypes(is, JackrabbitNodeTypeManager.TEXT_X_JCR_CND);
    }

You can automatically install your node types/namespace during initialization. (This is why the method above pulls the file as classloader resource).

    public Session setup(Credentials cred)
        throws RepositoryException, IOException {
        Session session;

        session = repository.login(cred);
 
        // create 'custom' namespace if necessary
        Workspace workspace = session.getWorkspace();
        NamespaceRegistry reg = workspace.getNamespaceRegistry();

        if (!Arrays.asList(reg.getPrefixes()).contains("custom")) {
            createCustomNodeTypes(session);
        }

        return session;
    }

Versioning Basics

    public void versioningBasics (Node parentNode, Session session) throws RepositoryException
    {
          //create versionable node
          Node n = parentNode.addNode("childNode", "nt:unstructured");
          n.addMixin("mix:versionable");
          n.setProperty("anyProperty", "Blah");
          session.save();
          Version firstVersion = n.checkin();

          //add new version
          Node child = parentNode.getNode("childNode");
          child.checkout();
          child.setProperty("anyProperty", "Blah2");
          session.save();
          child.checkin();

          //print version history
          VersionHistory history = child.getVersionHistory();
          for (VersionIterator it = history.getAllVersions(); it.hasNext();) {
            Version version = (Version) it.next();
            System.out.println(version.getCreated().getTime());
          }
          
          //restoring old version
          child.checkout();
          child.restore(firstVersion, true);          
    }

Creating a Workspace

((org.apache.jackrabbit.core.WorkspaceImpl)workspace).createWorkspace(name);

Deleting a Workspace

You have to manually remove the workspace.xml - there's no programmatic way yet.

Shutting Down the Repository

javax.jcr.Session session = ...;
((org.apache.jackrabbit.core.RepositoryImpl) session.getRepository()).shutdown();

Simple Standalone RMI Server / Client

Server:

Repository repository = new TransientRepository();
ServerAdapterFactory factory = new ServerAdapterFactory();
RemoteRepository remote = factory.getRemoteRepository(repository);
Registry reg = LocateRegistry.createRegistry(1100);
reg.rebind("jackrabbit", remote);

Client:

ClientRepositoryFactory factory = new ClientRepositoryFactory();
Repository repository = factory.getRepository("rmi://localhost:1100/jackrabbit");

Jackrabbit Cache Configuration

This info has moved to the CacheManager page.

last edited 2009-06-09 08:57:49 by ThomasMueller