[Q&A Friday] How to add extra files to a document using Content Automation


Fri 25 January 2013 By Laurent Doguin


 Title Caption How to add extra files to a document using Content Automation How to add extra files to a document using Content Automation

Today we have someone asking how to attach extra files to a document using Content Automation. So I'm going to do this using nuxeo-automation-client. This is a jar that you can add as a dependency to your Java application and that gives you a nice API to make content automation call to a Nuxeo server.

I've written a small example that opens a Content Automation HTTP session to a local Nuxeo server as Administrator and execute an operation that adds a file to an existing document. Those operations are wrapped in the DocumentService. This class hides part of the complexity to make an operation request. You can take a look at our documentation for the complete details. Now here's the code sample, most of it is explained in the comments:

public class SampleAttachFiles {

public static void main(String[] args) throws Exception {
try {
// Create an instance of the client using the address of your
// server.
HttpAutomationClient client = new HttpAutomationClient(
"http://localhost:8080/nuxeo/site/automation");
// Open a session as Administrator with password Administrator
Session session = client.getSession("Administrator",
"Administrator");
// let's assume you now the id of the document
String docId = "0e8d31c3-eef1-43fe-a575-7d63705ecbbf";
// and the path to the file to attach
File file = new File("/path/to/your/file");
// The DocumentService will give you some nice shortcut to the most
// common operations
DocumentService rs = session.getAdapter(DocumentService.class);
// Create a document Ref object with the id of the document
DocRef docRef = new DocRef(docId);
// Create a blob object from the file to upload
Blob blob = new FileBlob(file);
// Use DocumentService to attach the blob. Giving files:files as
// argument will add the blob to the existing attachment
rs.setBlob(docRef, blob, "files:files");
// This will replace the content of the firt attachement
rs.setBlob(docRef, blob, "files:files/0/file");
// If you do that, do not forget to change the filename too
rs.setProperty(docRef, "files:files/0/filename", "NewName");
client.shutdown();
} catch (RemoteException e) {
e.printStackTrace();
System.out.println(e.getRemoteStackTrace());
}
}
}

Category: Product & Development
Tagged: Java, Nuxeo Automation, Q&A