I want to test saving and retrieving of files using Apache Jackrabbit. I am not sure if it's saving when I am not able to retrieve it later. The following is my code. My question is how do I retrieve the file that I have saved.
@Test
public void storeFile() throws Exception {
File file = getFile();
FileInputStream fileInputStream = new FileInputStream(file);
Repository repository = new TransientRepository();
Session session = repository.login(
new SimpleCredentials("username", "password".toCharArray()));
try {
logger.info("logged in as user '{}'", session.getUserID());
Node root = session.getRootNode();
// Store content
Node hello = root.addNode("userid_12");
Node world = hello.addNode("files");
logger.debug("setting fileInputStream");
world.getSession().getValueFactory().createBinary(fileInputStream);
session.save();
// Retrieve content
Node node = root.getNode("userid_12/files");
logger.info(node.getPath());
//how do I retrieve the file now?
}
Just recently done something similar, and used the examples page (http://wiki.apache.org/jackrabbit/ExamplesPage) to do it.
You need to tell jackrabbit the node type and also pass it the binary data and the mime type when saving, something like this:
Node DocNode = currentDocNode.addNode(doc.getFilename(),"nt:file");
Node contentNode = DocNode.addNode("jcr:content","nt:resource");
Binary binary = session.getValueFactory().createBinary(file.getInputStream());
contentNode.setProperty("jcr:data",binary);
contentNode.setProperty("jcr:mimeType",file.getContentType());
Calendar created = Calendar.getInstance ();
contentNode.setProperty("jcr:lastModified", created);
This will save the document correctly in the node. Then retrieving the file is just getting the node and reading the data, there is a JcrUtils class that does this for you:
Node fileNode = root.getNode("path/to/node");
InputStream stream = null;
if(null != fileNode){
stream = JcrUtils.readFile(fileNode);
}
Then you can do what you what with the inputStream (stream it to response etc)