Get File Out of JCR File Node
Asked Answered
P

1

14

I have the following code to insert "rose.gif" into a roseNode. But how do I retrieve the file from the repository?

    Node roseNode = session.getRootNode().getNode("wiki:encyclopedia/wiki:entry[1]/");

    File file = new File("rose.gif");
    MimeTable mt = MimeTable.getDefaultTable();
    String mimeType = mt.getContentTypeFor(file.getName());
    if (mimeType == null) mimeType = "application/octet-stream";

    Node fileNode = roseNode.addNode(file.getName(), "nt:file");

    System.out.println( fileNode.getName() );

    Node resNode = fileNode.addNode("jcr:content", "nt:resource");
    resNode.setProperty("jcr:mimeType", mimeType);
    resNode.setProperty("jcr:encoding", "");
    resNode.setProperty("jcr:data", new FileInputStream(file));
    Calendar lastModified = Calendar.getInstance();
    lastModified.setTimeInMillis(file.lastModified());
    resNode.setProperty("jcr:lastModified", lastModified);

    //retrieve file and output as rose-out.gif
    File outputFile = new File("rose-out.gif");
    FileOutputStream out = new FileOutputStream(outputFile);
Proglottis answered 13/1, 2011 at 22:16 Comment(0)
T
18

The only thing you really need to do is get the name of the file from the name of the "nt:file" node, and the content for the file from the "jcr:data" property on the "jcr:content" child node.

JCR 1.0 and 2.0 differ a bit in how you get the stream for the binary "jcr:data" property value. If you're using JCR 1.0, then the code would be like this:

Node fileNode = // find this somehow
Node jcrContent = fileNode.getNode("jcr:content");
String fileName = fileNode.getName();
InputStream content = jcrContent.getProperty("jcr:data").getStream();

If you're using JCR 2.0, the last line is a bit different because you first have to get the Binary object from the property value:

InputStream content = jcrContent.getProperty("jcr:data").getBinary().getStream();

You can then use standard Java stream utility to write the bytes from the 'content' stream into the file.

When you're done with the Binary object, be sure to call the Binary's dispose() method to tell signal that you're done with the Binary and that the implementation can release all resources acquired by the Binary object. You should always do this, even though some JCR implementations try to catch programming errors by returning a stream that, when closed, will automatically call dispose() for you.

Twinkling answered 14/1, 2011 at 3:22 Comment(3)
Hi Randall, what I want is an OutputStream and not an input stream. Is this possible?Proglottis
I figured it out. Just converted the inputStream to an outputStream byte by byte.Proglottis
For 2.0, I think you have to call Binary.dispose() when you are done w/ the Binary object (day.com/specs/jcr/2.0/5_Reading.html).Shamanism

© 2022 - 2024 — McMap. All rights reserved.