OpenText | Content Web Services

Uploading Documents (Java)

This tutorial walks you through all the steps needed to start uploading documents to Content Server using the CWS API with Java and Eclipse.

Outline

Create a New Project

The first thing we need is a new project in Eclipse to work with.

  1. Open Eclipse.

  2. Open the File menu and select New → Java Project.

  3. Enter a name for the project and then select Finish.

    Create New Java Project

Create CWS Client Proxies

Next, we need create the client proxies for each CWS service we want to use.

  1. Open a new command prompt.

  2. Use the wsimport command to generate the client proxies for each service. Enter the following commands:

    wsimport -keep http://localhost:8080/cws/services/Authentication?wsdl

    wsimport -keep http://localhost:8080/cws/services/ContentService?wsdl

    wsimport -keep http://localhost:8080/cws/services/DocumentManagement?wsdl

    wsimport

  3. Use the jar command to bundle the generated class files into a .jar file. Enter the following command:

    jar cvfM cws.jar com/opentext*

    Create cws.jar File

  4. Copy the cws.jar file into your eclipse project and add it to your build path by right clicking the cws.jar file in the Package Explorer and select Build Path → Add to Build Path.

    Add to Build Path

Write Your Code

Now that the CWS services are ready to use we can go ahead and start writing some code. The first thing to do is to authenticate a user. We will use basic Content Server authentication using the CWS Authentication service. You will need to change the username and password to use valid credentials of a user on your system.

// The user's credentials
final String USERNAME = "username";
final String PASSWORD = "password";

// Create the Authentication service client
Authentication_Service authService = new Authentication_Service();
Authentication authClient = authService.getBasicHttpBindingAuthentication();

// Store the authentication token
String authToken = null;

// Call the AuthenticateUser() method to get an authentication token
try
{
	System.out.print("Authenticating User...");
	authToken = authClient.authenticateUser(USERNAME, PASSWORD);
	System.out.println("SUCCESS!\n");
}
catch (SOAPFaultException e)
{
	System.out.println("FAILED!\n");
	System.out.println(e.getFault().getFaultCode() + " : " + e.getMessage());
	return;
}

Next, store the metadata for the upload in a method context on the server. You will need to change the FILE_PATH to point to a file on your local system. You can also change the PARENT_ID to upload the file to a different location, if needed.

// The local file path of the file to upload
final String FILE_PATH = "C:/temp/test.pdf";

// The ID of the parent container to add the document to
final int PARENT_ID = 2000;

// Store the information for the local file
File file = new File(FILE_PATH);

if (!file.exists())
{
	System.out.println("ERROR!\n");
	System.out.println("File does not exist at : " + FILE_PATH);
	return;
}

// Create the DocumentManagement service client
DocumentManagement_Service docManService = new DocumentManagement_Service();
DocumentManagement docManClient = docManService.getBasicHttpBindingDocumentManagement();

// Create the OTAuthentication object and set the authentication token
OTAuthentication otAuth = new OTAuthentication();
otAuth.setAuthenticationToken(authToken);

// We need to manually set the SOAP header to include the authentication token
try
{
	// The namespace of the OTAuthentication object
	final String ECM_API_NAMESPACE = "urn:api.ecm.opentext.com";

	// Create a SOAP header
	SOAPHeader header = MessageFactory.newInstance().createMessage().getSOAPPart().getEnvelope().getHeader();

	// Add the OTAuthentication SOAP header element
	SOAPHeaderElement otAuthElement = header.addHeaderElement(new QName(ECM_API_NAMESPACE, "OTAuthentication"));

	// Add the AuthenticationToken SOAP element
	SOAPElement authTokenElement = otAuthElement.addChildElement(new QName(ECM_API_NAMESPACE, "AuthenticationToken"));
	authTokenElement.addTextNode(otAuth.getAuthenticationToken());

	// Set the SOAP header on the docManClient
	((WSBindingProvider) docManClient).setOutboundHeaders(Headers.create(otAuthElement));
}
catch (SOAPException e)
{
	System.out.println("Failed to set authentication SOAP header!\n");
	System.out.println(e.getMessage());
	return;
}

// Store the context ID for the upload
String contextID = null;

// Call the createDocumentContext() method to create the context ID
try
{
	System.out.print("Generating context ID...");
	contextID = docManClient.createDocumentContext(PARENT_ID, file.getName(), null, false, null);
	System.out.println("SUCCESS!\n");
}
catch (SOAPFaultException e)
{
	System.out.println("FAILED!\n");
	System.out.println(e.getFault().getFaultCode() + " : " + e.getMessage());
	return;
}

Finally, upload the file using the contextID from before using the ContentService.

// Create the ContentService client
// NOTE: ContentService is the only service that requires MTOM support
ContentService_Service contentService = new ContentService_Service();
ContentService contentServiceClient = contentService.getBasicHttpBindingContentService(new MTOMFeature());

// The number of bytes to write in each chunk
final int CHUNK_SIZE = 10240;

// Enable streaming and use chunked transfer encoding to send the request body to support large files
((BindingProvider) contentServiceClient).getRequestContext().put(JAXWSProperties.HTTP_CLIENT_STREAMING_CHUNK_SIZE, CHUNK_SIZE);

// Get the file attributes
BasicFileAttributes fileAttributes;
try
{
	fileAttributes = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
}
catch (IOException e)
{
	System.out.println("Failed to read file attributes!\n");
	System.out.println(e.getMessage());
	return;
}

// Create the FileAtts object to send in the upload call
FileAtts fileAtts = new FileAtts();

try
{
	fileAtts.setCreatedDate(DatatypeFactory.newInstance().newXMLGregorianCalendar(fileAttributes.creationTime().toString()));
	fileAtts.setFileName(file.getName());
	fileAtts.setFileSize(file.length());
	fileAtts.setModifiedDate(DatatypeFactory.newInstance().newXMLGregorianCalendar(fileAttributes.lastModifiedTime().toString()));
}
catch (DatatypeConfigurationException e)
{
	System.out.println("Failed to set file attributes!\n");
	System.out.println(e.getMessage());
	return;
}

// We need to manually set the SOAP headers to include the authentication token, context ID, and file attributes
try
{
	// Namespaces for the SOAP headers
	final String ECM_API_NAMESPACE = "urn:api.ecm.opentext.com";
	final String CORE_NAMESPACE = "urn:Core.service.livelink.opentext.com";

	// Create a SOAP header
	SOAPHeader header = MessageFactory.newInstance().createMessage().getSOAPPart().getEnvelope().getHeader();

	// Add the OTAuthentication SOAP header element
	SOAPHeaderElement otAuthElement = header.addHeaderElement(new QName(ECM_API_NAMESPACE, "OTAuthentication"));

	// Add the AuthenticationToken
	SOAPElement authTokenElement = otAuthElement.addChildElement(new QName(ECM_API_NAMESPACE, "AuthenticationToken"));
	authTokenElement.addTextNode(otAuth.getAuthenticationToken());

	// Add the ContextID SOAP header element
	SOAPHeaderElement contextIDElement = header.addHeaderElement(new QName(CORE_NAMESPACE, "contextID"));
	contextIDElement.addTextNode(contextID);

	// Add the FileAtts SOAP header element
	SOAPHeaderElement fileAttsElement = header.addHeaderElement(new QName(CORE_NAMESPACE, "fileAtts"));

	// Add the CreatedDate element
	SOAPElement createdDateElement = fileAttsElement.addChildElement(new QName(CORE_NAMESPACE, "CreatedDate"));
	createdDateElement.addTextNode(fileAtts.getCreatedDate().toString());

	// Add the ModifiedDate element
	SOAPElement modifiedDateElement = fileAttsElement.addChildElement(new QName(CORE_NAMESPACE, "ModifiedDate"));
	modifiedDateElement.addTextNode(fileAtts.getModifiedDate().toString());

	// Add the FileSize element
	SOAPElement fileSizeElement = fileAttsElement.addChildElement(new QName(CORE_NAMESPACE, "FileSize"));
	fileSizeElement.addTextNode(fileAtts.getFileSize().toString());

	// Add the FileName element
	SOAPElement fileNameElement = fileAttsElement.addChildElement(new QName(CORE_NAMESPACE, "FileName"));
	fileNameElement.addTextNode(fileAtts.getFileName());

	// Set the headers on the binding provider
	List<Header> headers = new ArrayList<Header>();
	headers.add(Headers.create(otAuthElement));
	headers.add(Headers.create(contextIDElement));
	headers.add(Headers.create(fileAttsElement));

	((WSBindingProvider) contentServiceClient).setOutboundHeaders(headers);
}
catch (SOAPException e)
{
	System.out.println("Failed to set SOAP headers!\n");
	System.out.println(e.getMessage());
	return;
}

// Call the UploadContent() method to upload the file
try
{
	System.out.print("Uploading document...");
	String objectID = contentServiceClient.uploadContent(new DataHandler(new FileDataSource(file)));
	System.out.println("SUCCESS!\n");
	System.out.println("New document uploaded with ID = " + objectID);

}
catch (SOAPFaultException e)
{
	System.out.println("FAILED!\n");
	System.out.println(e.getFault().getFaultCode() + " : " + e.getMessage());
	return;
}

Run the Program

If everything is setup correctly you should be able to successfully run the program.

  1. Open the Run menu and select Run (Ctrl + F11).

    Result

Source Code

References