Skip to content

Instantly share code, notes, and snippets.

@tewari2312
Last active January 13, 2021 17:49
Show Gist options
  • Save tewari2312/b31ecae262328312bb227e101abf27b6 to your computer and use it in GitHub Desktop.
Save tewari2312/b31ecae262328312bb227e101abf27b6 to your computer and use it in GitHub Desktop.
Java code to connect to documentum server and perform upload, download and delete operations. NOTE: provide the necessary jars. ASSUMPTION: dfc.properties and dfc.keystore are correct and present in classpath
package main.java.com.Documentum;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.log4j.Logger;
import com.documentum.com.DfClientX;
import com.documentum.com.IDfClientX;
import com.documentum.fc.client.DfQuery;
import com.documentum.fc.client.IDfClient;
import com.documentum.fc.client.IDfCollection;
import com.documentum.fc.client.IDfQuery;
import com.documentum.fc.client.IDfSession;
import com.documentum.fc.client.IDfSessionManager;
import com.documentum.fc.client.IDfSysObject;
import com.documentum.fc.common.DfException;
import com.documentum.fc.common.IDfLoginInfo;
import com.documentum.fc.tools.RegistryPasswordUtils;
/**
* This class provides methods to connect to Documentum server and perform actions.
* To enable logger set Documentum.logger (logger used is apache log4j); In case the logger is NOT set the messages will be sent to standard console
* <br><b>Caution:</b> The methods of this class are <u>NOT</u> thread safe, it is therefore highly recommended NOT to use this jar in a multithreading environment
* <br><b>Dependencies:</b> This jar requires the following jars in classpath:
* <br>aspectjrt.jar
* <br>certjFIPS.jar
* <br>commons-lang-2.5.jar
* <br>dfc.jar
* <br>jaxb-api.jar
* <br>jaxb-impl.jar
* <br>jsafeFIPS.jar
* <br>log4j-1.2.16.jar
* */
public class Documentum {
public static Logger logger;
/**
* This method creates documentum session. <b>Caution:</b> This jar internally uses dfc.jar which requires dfc.properties and dfc.keystore files to be present in classpath,
* therefore it is highly recommended to use the other overloaded method of the same name.
* @param documentumUsername <i>[mandatory]</i> The username required to connect to documentum repository
* @param repositoryName <i>[mandatory]</i> The repository that this session needs to establish a connection to
* @param documentumPassword <i>[mandatory]</i> The password required to connect to documentum repository
* @param isPasswordEncrypted <i>[mandatory]</i> This is a boolean parameter, a true value means that the password being provided is encrypted using dfc.jar
* @return IDfSession object
* @throws DfException if there is a problem Decrypting the password or while creating a new session
* */
public static IDfSession createSession(String documentumUsername, String documentumPassword, String repositoryName, Boolean isPasswordEncrypted) throws DfException{
log("Creating session...",null,null);
IDfClientX clientx = new DfClientX();
IDfClient client = clientx.getLocalClient();
IDfLoginInfo loginInfoObj = clientx.getLoginInfo();
loginInfoObj.setUser(documentumUsername);
if(isPasswordEncrypted){
log("Decrypting documentum password...",null,null);
loginInfoObj.setPassword(RegistryPasswordUtils.decrypt(documentumPassword));
log("Documentum password decrypted",null,null);
}else{
loginInfoObj.setPassword(documentumPassword);
}
IDfSessionManager sessionManager = client.newSessionManager();
sessionManager.setIdentity(repositoryName,loginInfoObj);
IDfSession session = sessionManager.getSession(repositoryName);
log("Session created",null,null);
return session;
}
/**
* This method creates Documentum session
* <br><b>Assumption:</b> dfc.properties and dfc.keystore are present in the CLASSPATH
* @param isPasswordEncrypted <i>[mandatory]</i> This is a boolean parameter, a true value means that the password being provided is encrypted using dfc.jar
* @throws DfException if there is a problem creating Documentum session or decrypting password
* @throws IOException if there is a problem reading dfc.properties
* */
public static IDfSession createSession(Boolean isPasswordEncrypted) throws DfException, IOException{
Properties properties = new Properties();
InputStream input = null;
log("Locating dfc.properties in CLASSPATH...",null,null);
input = Documentum.class.getResourceAsStream("/dfc.properties");
properties.load(input);
if (input != null) {
input.close();
}
log("dfc.properties file found",null,null);
return createSession(properties.getProperty("dfc.globalregistry.username"),properties.getProperty("dfc.globalregistry.password"),properties.getProperty("dfc.globalregistry.repository"),isPasswordEncrypted);
}
/**
* This method is used to upload a multiple blobs to documentum server
* @param session <i>[mandatory]</i> This is the Documentum session object (IDfSession object), make sure that the session object is not null and the session is still alive.
* @param documentType <i>[not mandatory]</i> This is the document type that will be assigned to the blob when uploading it to Documentum, if not sure send this parameter as null. (default value = dm_document)
* @param attachmentDetails <i>[mandatory]</i> The key of the map represents the attachment name and the value is the blob that needs to be uploaded
* @param cabinetName This is the name of the cabinet where the attachments are to be stored
* @return a HashMap which has the attachment name as the key and documentum id as the value, if the upload of a particular attachment failed the documentum id will be null
* */
public static Map<String,String> uploadBlobToDocumentum(IDfSession session,String documentType, Map<String,Blob> attachmentDetails, String cabinetName) throws IOException, DfException, SQLException{
if(documentType==null || documentType.trim().length()<1){
documentType="dm_document";
}
Map<String,String> result = new HashMap<String,String>();
Set<String> allKeys = attachmentDetails.keySet();
String value = "";
for (String key : allKeys){
value = uploadBlobToDocumentum(session, documentType, key, attachmentDetails.get(key), cabinetName);
result.put(key, value);
}
return result;
}
/**
* This method is used to upload a blob to Documentum server
* @param session <i>[mandatory]</i> This is the Documentum session object (IDfSession object), make sure that the session object is not null and the session is still alive.
* @param documentType <i>[not mandatory]</i> This is the document type that will be assigned to the blob when uploading it to Documentum, if not sure send this parameter as null. (default value = dm_document)
* @param attachmentName <i>[mandatory]</i> The attachment name
* @param mBlob <i>[mandatory]</i> The file that needs to be uploaded
* @param cabinetName <i>[mandatory]</i> This is the name of the cabinet where the attachments are to be stored
* @return Documentum ID of the blob that has been uploaded to server, if the upload failed, this ID is returned as null
* */
public static String uploadBlobToDocumentum(IDfSession session,String documentType, String attachmentName, Blob mBlob, String cabinetName) throws IOException, DfException, SQLException{
if(documentType==null || documentType.trim().length()<1){
documentType="dm_document";
}
session.beginTrans();
String documentumID="";
String result = null;
log("Start uploading file to documentum",null,null);
IDfSysObject doc = (IDfSysObject) session.newObject(documentType);
doc.setObjectName(attachmentName);
doc.setContentType(getFormat(session, attachmentName));
int blobLength = (int) mBlob.length();
byte[] blobAsBytes = mBlob.getBytes(1, blobLength);
ByteArrayOutputStream out = new ByteArrayOutputStream(blobAsBytes.length);
out.write(blobAsBytes, 0, blobAsBytes.length);
doc.setContent(out);
doc.link(cabinetName);
doc.save();
documentumID=""+doc.getObjectId();
if(documentumID==null || documentumID.trim()==""){
log("Failed to fetch documentum ID. The Documentum server might be down, unresponsive or unrechable. Please check configuration details before proceeding.",null,"ERROR");
if(session!=null){
session.abortTrans();
}
}else{
log("Attachment has been successfully added to documentum. Documentum ID: "+documentumID,null,null);
if(session!=null){
session.commitTrans();
result = documentumID;
}
}
out.close();
return result;
}
/**
* This method is used to upload a byte array to Documentum server
* @param session <i>[mandatory]</i> This is the Documentum session object (IDfSession object), make sure that the session object is not null and the session is still alive.
* @param documentType <i>[not mandatory]</i> This is the document type that will be assigned to the blob when uploading it to Documentum, if not sure send this parameter as null. (default value = dm_document)
* @param attachmentName <i>[mandatory]</i> The attachment name
* @param file <i>[mandatory]</i> The file (as a byte array) that needs to be uploaded
* @param cabinetName <i>[mandatory]</i> This is the name of the cabinet where the attachments are to be stored
* @return Documentum ID of the blob that has been uploaded to server, if the upload failed, this ID is returned as null
* */
public static String uploadByteArrayToDocumentum(IDfSession session,String documentType, String attachmentName, byte[] file, String cabinetName) throws IOException, DfException, SQLException{
if(documentType==null || documentType.trim().length()<1){
documentType="dm_document";
}
String result = null;
try{
session.beginTrans();
String documentumID="";
log("Start uploading file to documentum",null,null);
IDfSysObject doc = (IDfSysObject) session.newObject(documentType);
doc.setObjectName(attachmentName);
doc.setContentType(getFormat(session, attachmentName));
log("Writing byte array to ByteArrayOutputStream..",null,"INFO");
ByteArrayOutputStream out = new ByteArrayOutputStream(file.length);
out.write(file, 0, file.length);
log("Writing ByteArrayOutputStream to Documentum Object content..",null,"INFO");
doc.setContent(out);
log("Linking Documentum Object to cabinet: "+cabinetName,null,"INFO");
doc.link(cabinetName);
log("Saving Documentum object..",null,"INFO");
doc.save();
log("Documentum object saved",null,"INFO");
documentumID=""+doc.getObjectId();
log("Documentum ID is "+documentumID,null,"INFO");
if(documentumID==null || documentumID.trim()==""){
log("Failed to fetch documentum ID. The Documentum server might be down, unresponsive or unrechable. Please check configuration details before proceeding.",null,"ERROR");
if(session!=null){
session.abortTrans();
}
}else{
log("Attachment has been successfully added to documentum. Documentum ID: "+documentumID,null,null);
if(session!=null){
session.commitTrans();
result = documentumID;
}
}
out.close();
}catch(Exception ex){
log("An exception occurred while uploading byte array to Documentum server",ex,"ERROR");
}
return result;
}
/**
* This method returns the documentum file format for the attachment type passed as parameter
* @param <i>[mandatory]</i> This is the Documentum session object (IDfSession object), make sure that the session object is not null and the session is still alive.
* @param <i>[mandatory]</i> This is the complete file name. E.g. if the filename is test.pdf do not send it as test
* @return The documentum file format for the attachment type passed as parameter
* */
public static String getFormat(IDfSession session, String completeFileName) throws DfException {
HashMap<String,String> documentumFileFormat = (HashMap<String,String>)fetchCommonDocumentumFileFormats();
String format = "unknown";
log("Fetching attachment extension...",null,null);
int n = completeFileName.lastIndexOf(".");
if (n == -1){
log("The file doesn't seem to have an extension",null,"WARN");
return format;
}
String extension = completeFileName.substring(n + 1).toLowerCase();
log("Attachment extension is "+extension,null,null);
log("Retrieving Documentum file format for the above extension...",null,null);
if(documentumFileFormat.containsKey(extension)){
format=documentumFileFormat.get(extension);
}else{
IDfCollection col = null;
IDfQuery q = new DfQuery();
q.setDQL("select name from dm_format where dos_extension = '"+ extension + "'");
col = q.execute(session, DfQuery.DF_READ_QUERY);
if (col != null && col.next()) {
format = col.getString("name");
}
if (col != null) {
col.close();
}
}
log("Documentum file format is "+format,null,null);
return format;
}
/**
* This method returns the most common of documentum file formats
* @return a map of the most common of documentum file formats
* */
public static Map<String,String> fetchCommonDocumentumFileFormats(){
log("Loading documentum file formats...",null,null);
Map<String,String> documentumFileFormat = new HashMap<String, String>();
documentumFileFormat = new HashMap<String,String>();
documentumFileFormat.put("txt", "crtext");
documentumFileFormat.put("doc", "msw8");
documentumFileFormat.put("docx", "msw12");
documentumFileFormat.put("xls", "excel");
documentumFileFormat.put("xlsx", "excel12book");
documentumFileFormat.put("ppt", "powerpoint");
documentumFileFormat.put("pptx", "ppt12");
documentumFileFormat.put("pdf", "pdf");
documentumFileFormat.put("png", "png");
documentumFileFormat.put("jpg", "jpeg");
documentumFileFormat.put("tif", "tiff");
documentumFileFormat.put("bmp", "bmp");
documentumFileFormat.put("gif", "gif");
documentumFileFormat.put("zip", "zip");
documentumFileFormat.put("xlsm", "excel12mebook");
log("Documentum file formats have been successfully loaded",null,null);
return documentumFileFormat;
}
/**
* This method fetches the attachment from documentum server and returns it as input stream
* @param session <i>[mandatory]</i> This is the Documentum session object (IDfSession object), make sure that the session object is not null and the session is still alive.
* @param documentumId <i>[mandatory]</i> The Documentum id of the file that you want to fetch
* @return Map<String,InputStream> The file name is the key, the value is the file itself fetched as InputStream from documentum server
* @throws DfException
* @throws IOException
* */
public static Map<String,InputStream> fetchAttachmentContent(IDfSession session, String documentumId) throws DfException, IOException{
Map<String,InputStream> returnValue = new HashMap<String,InputStream>();
String filePath = "";
InputStream inputStream = null;
log("Fetching file path and file name...",null,null);
String[] fileNameAndPath = queryForFilePath(session, documentumId);
if (!(fileNameAndPath[0].equals("") && fileNameAndPath[1].equals(""))) {
log("File found in documentum server",null,null);
filePath = fileNameAndPath[0] + '/' + fileNameAndPath[1];
log("File path is: " + filePath,null,null);
IDfSysObject doc = (IDfSysObject) session.getObjectByPath(filePath);
inputStream = doc.getContent();
returnValue.put(fileNameAndPath[1], inputStream);
} else {
log("File not found",null,"ERROR");
}
if(inputStream!=null){
inputStream.close();
}
return returnValue;
}
/**
* This method fetches multiple attachments from documentum server and returns it as a HashMap
* <b>Caution:</b> use this method only if the documents you are fetching have unique names. else use the overloaded method recursively.
* @param session <i>[mandatory]</i> This is the Documentum session object (IDfSession object), make sure that the session object is not null and the session is still alive.
* @param documentumIds <i>[mandatory]</i> This is the set of documentum IDs for which you wish to fetch the attachments
* @return The outer map's key is the documentum id of the object, the outer Map's value is the Inner Map.
* The InnerMap's key is the document name and the value is the document itself as input stream
* */
public static Map<String,Map<String,InputStream>> fetchAttachmentContent(IDfSession session, Set<String> documentumIds){
Map<String,Map<String,InputStream>> returnValue = new HashMap<String,Map<String,InputStream>>();
for(String documentumId : documentumIds){
try{
returnValue.put(documentumId, fetchAttachmentContent(session,documentumId));
}catch(Exception exception){
returnValue.put(documentumId, null);
log("An exception occcurred while fetching file from Documentum server",exception,"ERROR");
}
}
return returnValue;
}
/**
* This method deletes a document from the Documentum server. <b>Caution:</b> This is a physical delete. documents once deleted cannot be recovered. This method has no affect on the index (if it exists) created on the documents in server.
* @param session <i>[mandatory]</i> This is the Documentum session object (IDfSession object), make sure that the session object is not null and the session is still alive.
* @param documentId <i>[mandatory]</i> The Documentum id of the file that you want to delete
* @return True if the file was deleted, False if the file was not found or if the deletion failed
* @throws DfException
*
* */
public static boolean deleteDocumentFromDocumentum(IDfSession session,String documentId) throws DfException{
boolean result=false;
if(documentId!=null && documentId.trim().length()>0){
log("Fetching file path and file name...",null,null);
String[] filePathAndName = queryForFilePath(session, documentId);
String delFilePath = "";
if (!(filePathAndName[0].equals("") && filePathAndName[1].equals(""))) {
log("File found in documentum server",null,null);
delFilePath = filePathAndName[0] + '/' + filePathAndName[1];
log("File path is: "+delFilePath,null,null);
IDfSysObject doc = (IDfSysObject) session.getObjectByPath(delFilePath);
doc.destroy();
result=true;
log("Documentum file destroyed",null,null);
} else {
log("File not found",null,"ERROR");
}
}
return result;
}
private static String[] queryForFilePath(IDfSession session, String docObjectId) throws DfException {
IDfCollection col = null;
int n = 0;
String[] fileNameAndPath = new String[] { "", "" };
try {
IDfQuery q = new DfQuery();
String qryStr = "select a.r_object_id, a.object_name, b.r_folder_path from dm_document a, dm_folder b where a.i_folder_id = b.r_object_id and b.r_folder_path IS NOT NULLSTRING and a.r_object_id = '"+ docObjectId + "' enable (row_based)";
q.setDQL(qryStr);
col = q.execute(session, DfQuery.DF_READ_QUERY);
if (col != null && col.next())
{
n++;
fileNameAndPath[0] = col.getString("r_folder_path");
fileNameAndPath[1] = col.getString("object_name");
}
} finally {
if (col != null) {
col.close();
}
if (n == 0) {
return fileNameAndPath;
}
}
return fileNameAndPath;
}
private static void log(String Message,Exception exception,String level){
if(logger!=null){
if(level=="ERROR"){
logger.info(" Documentum.jar: [ERROR] "+Message, exception);
}else if(level=="WARN"){
logger.warn(" Documentum.jar: [WARN] "+Message, exception);
}else{
logger.error(" Documentum.jar: [INFO] "+Message, exception);
}
}else{
System.out.println(" Documentum.jar: "+Message);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment