Snippets

Karolis Jocevičius IBM FileNet P8 Java API examples

You are viewing an old version of this snippet. View the current version.
Revised by Karolis Jocevičius 5b565d7
package lt.mesgalis.filenet.training;

import java.io.FileInputStream;
import java.util.Arrays;
import java.util.Iterator;
import java.util.function.Function;

import com.filenet.api.collection.AccessPermissionList;
import com.filenet.api.collection.ClassDescriptionSet;
import com.filenet.api.collection.ContentElementList;
import com.filenet.api.collection.IndependentObjectSet;
import com.filenet.api.collection.PageIterator;
import com.filenet.api.collection.PropertyDescriptionList;
import com.filenet.api.constants.AccessLevel;
import com.filenet.api.constants.AccessType;
import com.filenet.api.constants.AutoClassify;
import com.filenet.api.constants.CheckinType;
import com.filenet.api.constants.FilteredPropertyType;
import com.filenet.api.constants.RefreshMode;
import com.filenet.api.constants.ReservationType;
import com.filenet.api.core.ContentElement;
import com.filenet.api.core.ContentTransfer;
import com.filenet.api.core.Document;
import com.filenet.api.core.Domain;
import com.filenet.api.core.EngineObject;
import com.filenet.api.core.Factory;
import com.filenet.api.core.Folder;
import com.filenet.api.core.ObjectStore;
import com.filenet.api.core.RetrievingBatch;
import com.filenet.api.core.Versionable;
import com.filenet.api.meta.ClassDescription;
import com.filenet.api.meta.PropertyDescription;
import com.filenet.api.property.Properties;
import com.filenet.api.property.Property;
import com.filenet.api.property.PropertyFilter;
import com.filenet.api.query.SearchSQL;
import com.filenet.api.query.SearchScope;
import com.filenet.api.security.AccessPermission;

import lt.mesgalis.filenet.training.controller.Connector;
import lt.mesgalis.filenet.training.controller.impl.ConnectorImpl;

public class App {

	private static final String CE_URL = "https://devdesk.elinar.fi/wsi/FNCEWS40MTOM/";
	private static final String CE_OS_NAME = "DEVOS";
	private static final String USERNAME = "Seb1";
	private static final String PASSWORD = "Training12345";
	
	private static final String PATH_DOCUMENT = "/Private/User1/sg248055.pdf";
	private static final String PATH_USER_FOLDER = "/Private/User1";
	private static final String PATH_CUSTOM_OBJECT_1 = "/Common/MAR.pdf";
	private static final String PATH_CUSTOM_OBJECT_2 = PATH_USER_FOLDER + "/ExampleXXX";
	
	private static final String SQL_ALL_DOCUMENTS = "Select * from Document";
	private static final String SQL_ALL_DOCUMENTS_IN_FOLDER = "Select D.DocumentTitle from Document D "
			+ "INNER JOIN ReferentialContainmentRelationship r ON D.This = r.Head "
			+ "WHERE r.Tail = OBJECT('/Common')";
	private static final String SQL_ALL_FOLDERS_WITH_PARENT = "Select * from Folder WHERE Parent = ('/Private')";

	public static void main(String[] args) {
		
		try {
			Connector connector = new ConnectorImpl(CE_URL,USERNAME,PASSWORD,"FileNetP8");
			connector.establish();
			System.out.println("Connection established");
			
			ObjectStore objectStore = connector.fetchObjectStore(CE_OS_NAME);
			System.out.println("ObjectStore fetched");
			
			Folder userFolder = connector.fetchFolder(PATH_USER_FOLDER, objectStore);
			Folder karFolder = null;
			Document document = null;
			Properties properties = null;
			
			Iterator it = null;
			
			// CREATE FOLDER
//			karFolder = connector.createFolder("kar", userFolder);

			// DELETE FOLDER
			karFolder = connector.fetchFolder("/Private/User1/kar", objectStore);
//			connector.deleteFolder(userFolder);
			
			// RETRIEVE OBJECTS FROM FOLDER
			connector.printSubfolders(userFolder);
			connector.printObjects(userFolder);
			connector.printDocuments(userFolder);
			
			// FETCH DOCUMENT
			document = connector.fetchDocument(PATH_DOCUMENT, objectStore);
			ContentElementList contentElements = document.get_ContentElements();
			it = contentElements.iterator();
			printElements(it, p -> ((ContentElement) p).get_ContentType() 
					+ ":" + ((ContentTransfer) p).get_RetrievalName() 
					+ ":" + ((ContentTransfer) p).get_ContentSize());
			
			// RETRIEVE CLASS DESCRIPTIONS
			ClassDescriptionSet classDescriptions = objectStore.get_ClassDescriptions();
			printElements(classDescriptions.iterator(), p -> ((ClassDescription) p).get_DisplayName());

			// RETRIEVE PROPERTIES DESCRIPTIONS II
			PropertyFilter propertyFilter = new PropertyFilter();
			propertyFilter.addIncludeType(0, null, null, FilteredPropertyType.ANY, 1);
			Document customDocument = Factory.Document.fetchInstance(objectStore, PATH_CUSTOM_OBJECT_1, propertyFilter);
			ClassDescription classDescription = customDocument.get_ClassDescription();
			System.out.println(customDocument.get_Name() + ":" + classDescription.get_DisplayName());
			PropertyDescriptionList propertyDescriptions = classDescription.get_PropertyDescriptions();
			System.out.println("PROPERTIES:");
			printElements(propertyDescriptions.iterator(), p -> ((PropertyDescription) p).get_DisplayName() + ":" + ((PropertyDescription) p).get_DataType());
			
			// RETRIEVE DOCUMENT PROPERTIES
			properties = customDocument.getProperties();
			printElements(properties.iterator(), p -> ((Property) p).getPropertyName() + ":" + ((Property) p).toString()); // annoying else/if to retrieve all values by type
			

			//------------------------------------------------------------------
			// SEARCH FOR DOCUMENT
			SearchScope searchScope = new SearchScope(objectStore);
			SearchSQL searchSQL = new SearchSQL(SQL_ALL_DOCUMENTS);
//			SearchSQL searchSQL = new SearchSQL(SQL_ALL_DOCUMENTS_IN_FOLDER);
//			SearchSQL searchSQL = new SearchSQL(SQL_ALL_FOLDERS_WITH_PARENT);
			IndependentObjectSet results = searchScope.fetchObjects(searchSQL, Integer.valueOf(10), null, Boolean.valueOf(true));
			
			// No paging
			printElements(results.iterator(), p -> ((Document) p).get_Name());
			printElements(results.iterator(), p -> ((Document) p).getProperties().getStringValue("DocumentTitle"));
			
			// Paging
			PageIterator pageIterator = results.pageIterator();
			pageIterator.setPageSize(5);
			EngineObject[] currentPage = null;
			boolean nextPage = pageIterator.nextPage();
			int page = 0;
			while (nextPage) {
				System.out.println("Search page: " + page);
				currentPage = (EngineObject[]) pageIterator.getCurrentPage();
				Arrays.stream(currentPage).forEach(d -> {
					if (d instanceof Document) {
						System.out.println(((Document) d).get_Name());
					} else if (d instanceof Folder) {
						System.out.println(((Folder) d).get_Name());
					} else {
						System.out.println(d.toString());
					}
				});
				nextPage = pageIterator.nextPage();	
				page++;
			}

			//------------------------------------------------------------------
			AccessPermissionList permissions = null;
			// RETRIEVE OBJECT PERMISSIONS
			permissions = userFolder.get_Permissions();
			it = permissions.iterator();
			printElements(it, p -> ((AccessPermission) p).get_GranteeName() + ":" + ((AccessPermission) p).get_AccessType().toString());
			
			// SET OBJECT PERMISSIONS
			// AccessMask is deprecated - use combination of access rights
			AccessPermission permission = Factory.AccessPermission.createInstance();
			permission.set_GranteeName("Seb5");
			permission.set_AccessType(AccessType.ALLOW);
			permission.set_InheritableDepth(-1);
			permission.set_AccessMask(AccessLevel.FULL_CONTROL_FOLDER_AS_INT);
			permissions = karFolder.get_Permissions();
			permissions.add(permission);
			karFolder.set_Permissions(permissions);
			karFolder.save(RefreshMode.REFRESH);
			
			//------------------------------------------------------------------
			
			document = Factory.Document.fetchInstance(objectStore, PATH_CUSTOM_OBJECT_2, null);
			
			// CHECKOUT
			printElements(document.get_Versions().iterator(), p -> ((Versionable) p).get_MajorVersionNumber() + "." + ((Versionable) p).get_MinorVersionNumber() );
			document.checkout(ReservationType.EXCLUSIVE, null, null, null);
			document.save(RefreshMode.NO_REFRESH);
			
			// GET RESERVATION
			if (!document.get_IsReserved()) {
				document = (Document) document.get_Reservation();
				if (document == null) {
					throw new IllegalStateException();
				}
			}
			
			// ADD DOCUMENTS
			ContentElementList content = Factory.ContentElement.createList();
			ContentTransfer ctObject = Factory.ContentTransfer.createInstance();
			FileInputStream fis = new FileInputStream("C:\\1.jpg");
			ctObject.setCaptureSource(fis);
			ctObject.set_ContentType("image/jpg");
			content.add(ctObject);
			document.set_ContentElements(content);
			
			// SET PROPS
			properties = document.getProperties();
			Property intVal = properties.find("intValue");
			intVal.setObjectValue(Integer.valueOf(5));
			
			// CHECKIN
			document.checkin(AutoClassify.AUTO_CLASSIFY, CheckinType.MAJOR_VERSION);
			document.save(RefreshMode.NO_REFRESH);
			
			// CANCEL CHECKOUT
			document.cancelCheckout();
			document.save(RefreshMode.NO_REFRESH);

			//------------------------------------------------------------------
			
			// BATCH RETRIEVE
			Domain domain = objectStore.get_Domain();
			RetrievingBatch retrievingBatchInstance = RetrievingBatch.createRetrievingBatchInstance(domain);
			Document doc1 = Factory.Document.getInstance(objectStore, null, PATH_USER_FOLDER + "\\248022.pdf");
			Document doc2 = Factory.Document.getInstance(objectStore, null, PATH_USER_FOLDER + "\\248055.pdf");
			retrievingBatchInstance.add(doc1, null);
			retrievingBatchInstance.add(doc2, null);
			retrievingBatchInstance.retrieveBatch();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void printElements(Iterator it, Function<Object, String> converter) {
		while (it.hasNext()) {
			System.out.println(converter.apply(it.next()));
		}
	}

}
package lt.mesgalis.filenet.training.controller;

import com.filenet.api.collection.IndependentObjectSet;
import com.filenet.api.core.Document;
import com.filenet.api.core.Folder;
import com.filenet.api.core.ObjectStore;
import com.filenet.api.util.Id;

import lt.mesgalis.filenet.training.exception.ConnNotEstablished;
import lt.mesgalis.filenet.training.exception.InvalidArgument;

public interface Connector {
	
	/**
     * Establish connection to FileNet
     * @throws ConnNotEstablished  Throws a ConnNotEstablished exception if connection cannot be established
     */
    public void establish() throws ConnNotEstablished;
    
    /**
     * Fetch Object Store By Name
     * @param name Name of object store
     * @return Object Store
     * @throws InvalidArgument If Object Store name is empty or null
     * @throws Exception if object store is not found or cannot be fetched
     */
    public ObjectStore fetchObjectStore(String name) throws InvalidArgument, Exception;
    
    public Folder createFolder(String name, Folder parent);

	void deleteFolder(Folder folder);
    
	void printSubfolders(Folder folder);

	void printDocuments(Folder folder);

	void printObjects(Folder folder);

    /**
     * Fetch Folder from Object Store by Object Store Name
     * @param path Path to fetched folder
     * @param os Object Store Name
     * @return Folder
     * @throws InvalidArgument
     * @throws Exception 
     */
    public Folder fetchFolder(String path, String os) throws InvalidArgument, Exception;
    
    /**
     * Fetch Folder from Object Store
     * @param path Path to Folder
     * @param os Object Store
     * @return Folder
     * @throws InvalidArgument
     * @throws Exception 
     */
     public Folder fetchFolder(String path,  ObjectStore os) throws InvalidArgument, Exception;
    
    /**
     * Run search the object store
     * @param symbolicName Symbolic name of searched object
     * @param includeSubClasses Include inherited classes 
     * @param MaxRecords Maximum number of records
     * @param Where Where condition
     * @param os ObjectStore name
     * @return IndependentObjectSet of matching objects
     * @throws Exception 
     */
    public IndependentObjectSet search(String symbolicName, boolean includeSubClasses, int MaxRecords, String Where, String os) throws Exception;

    /**
     * Run search the object store
     * @param symbolicName Symbolic name of searched object
     * @param includeSubClasses Include inherited classes 
     * @param MaxRecords Maximum number of records
     * @param Where Where condition
     * @param os ObjectStore
     * @return IndependentObjectSet of matching objects
     * @throws Exception 
     */
    public IndependentObjectSet search(String symbolicName, boolean includeSubClasses, int MaxRecords, String Where, ObjectStore os) throws Exception;
     
    public Document fetchDocument(String id, String os) throws InvalidArgument, Exception;
    
    /**
     * Fetching Document using Id and Object Store
     * @param id Id 
     * @param os Object Store Name
     * @return Document
     * @throws InvalidArgument
     * @throws Exception 
     */
    public Document fetchDocument(Id id,  ObjectStore os) throws InvalidArgument, Exception;
    
    public Document fetchDocument(String path,  ObjectStore os) throws InvalidArgument, Exception;

}
package lt.mesgalis.filenet.training.controller.impl;

import java.util.Iterator;

import javax.security.auth.Subject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.filenet.api.collection.DocumentSet;
import com.filenet.api.collection.FolderSet;
import com.filenet.api.collection.IndependentObjectSet;
import com.filenet.api.collection.ReferentialContainmentRelationshipSet;
import com.filenet.api.constants.RefreshMode;
import com.filenet.api.core.Connection;
import com.filenet.api.core.Document;
import com.filenet.api.core.Domain;
import com.filenet.api.core.Factory;
import com.filenet.api.core.Folder;
import com.filenet.api.core.IndependentObject;
import com.filenet.api.core.ObjectStore;
import com.filenet.api.core.ReferentialContainmentRelationship;
import com.filenet.api.query.SearchSQL;
import com.filenet.api.query.SearchScope;
import com.filenet.api.util.Id;
import com.filenet.api.util.UserContext;

import lt.mesgalis.filenet.training.controller.Connector;
import lt.mesgalis.filenet.training.exception.ConnNotEstablished;
import lt.mesgalis.filenet.training.exception.InvalidArgument;

public class ConnectorImpl implements Connector {

	private final Log log = LogFactory.getLog(ConnectorImpl.class.getName());

	private final String ceURL;

	private Connection conn;
	private Domain domain;

	private Subject subject;

	/**
	 * ConnectorImpl Contructor for Web-Based Logins
	 *
	 * Ie. Sample with WebSphere
	 * com.ibm.websphere.security.auth.WSSubject.getCallerSubject();
	 * http://www-01.ibm.com/support/knowledgecenter/SS7K4U_8.5.5/com.ibm.
	 * websphere.zseries.doc/ae/rsec_logmod.html
	 *
	 * @param ceURL
	 *            Content Engine Url
	 * @param subject
	 *            Authentication Subject
	 */
	public ConnectorImpl(String ceURL, Subject subject) {
		this.ceURL = ceURL;
		this.subject = subject;
		// cleanExistContexts();
		UserContext uc = UserContext.get();
		uc.pushSubject(subject);
	}

	/**
	 * For Non Based Applications (Username login)
	 *
	 * @param ceURL
	 *            Content Engine URL
	 * @param username
	 *            UserName
	 * @param password
	 *            Password
	 * @param stanza
	 *            Stanza
	 */
	public ConnectorImpl(String ceURL, String username, String password, String stanza) {
		this.ceURL = ceURL;
		this.conn = Factory.Connection.getConnection(this.ceURL); // Initialize
																	// connection
																	// object

		cleanExistContexts(); // Clean up existing authentication subjects if
								// any
		createSubject(username, password, stanza); // Create an authentication
													// subject

	}

	@Override
	public Folder createFolder(String name, Folder parent) {
		Folder subFolder = parent.createSubFolder(name); // or create as
															// separate Folder
															// by Factory and
															// set parent
		subFolder.save(RefreshMode.REFRESH);
		System.out.println("Folder created");
		return subFolder;
	}

	@Override
	public void deleteFolder(Folder folder) {
		folder.delete();
		folder.save(RefreshMode.REFRESH);
		System.out.println("Folder deleted");
	}

	@Override
	public void printSubfolders(Folder folder) {
		FolderSet subfolders = folder.get_SubFolders();
		Iterator iterator = subfolders.iterator();

		System.out.println("SUBFOLDERS: ");
		while (iterator.hasNext()) {
			Folder next = (Folder) iterator.next();
			System.out.println(next.get_Name());
		}
	}

	@Override
	public void printDocuments(Folder folder) {
		DocumentSet docs = folder.get_ContainedDocuments();
		Iterator iterator = docs.iterator();

		System.out.println("DOCUMENTS: ");
		while (iterator.hasNext()) {
			Document next = (Document) iterator.next();
			System.out.println(next.get_Name());
		}
	}

	@Override
	public void printObjects(Folder folder) {
		ReferentialContainmentRelationshipSet objects = folder.get_Containees();
		Iterator iterator = objects.iterator();

		System.out.println("OBJECTS: ");
		while (iterator.hasNext()) {
			ReferentialContainmentRelationship next = (ReferentialContainmentRelationship) iterator.next();
			IndependentObject head = next.get_Head();
			System.out.println(head.getClassName() + ":" + next.get_Name());
		}
	}

	private void cleanExistContexts() {
		com.filenet.api.util.UserContext ucCurrThread = com.filenet.api.util.UserContext.get();
		// clear the context of all credentials
		int popCnt = 0;
		while (ucCurrThread.popSubject() != null) {
			popCnt++;
		}
	}

	@Override
	public void establish() throws ConnNotEstablished {
		log.debug("Establishing connection to " + this.ceURL + "");
		try {

			this.domain = Factory.Domain.getInstance(this.conn, null);

			if (this.domain == null) {
				throw new ConnNotEstablished("Error while fetching domain object");
			}

		} catch (ConnNotEstablished ex) {
			log.error("Establising connection to FileNet Failed", ex);
		}
	}

	@Override
	public ObjectStore fetchObjectStore(String name) throws InvalidArgument, Exception {

		if (name == null || name.length() == 0) {
			throw new InvalidArgument("Invalid objectstore name");
		}
		System.out.println("Requesting ObjectStore :: " + name);

		if (domain == null || this.conn == null) {
			throw new Exception("Establish connection first");
		}

		ObjectStore os = Factory.ObjectStore.fetchInstance(domain, name, null);

		if (os == null) {
			throw new Exception("Objectstore not found");
		}
		System.out.println("Returning ObjectStore " + os.get_SymbolicName() + " " + os.get_Id());
		return os;
	}

	@Override
	public Folder fetchFolder(String path, String os) throws InvalidArgument, Exception {
		if (os == null || os.isEmpty()) {
			throw new InvalidArgument("Object store name must be defined");
		}
		ObjectStore store = fetchObjectStore(os);

		return fetchFolder(path, store);
	}

	@Override
	public Folder fetchFolder(String path, ObjectStore os) throws InvalidArgument, Exception {
		log.debug("Running search");
		return Factory.Folder.fetchInstance(os, path, null);
	}

	@Override
	public IndependentObjectSet search(String symbolicName, boolean includeSubClasses, int MaxRecords, String Where, String os) throws Exception {
		if (os == null || os.isEmpty()) {
            throw new InvalidArgument("Object store name must be defined");
        }
        
        ObjectStore store= this.fetchObjectStore(os);

        return search(symbolicName, includeSubClasses, MaxRecords, Where, store);
	}

	@Override
	public IndependentObjectSet search(String symbolicName, boolean includeSubClasses, int MaxRecords, String Where, ObjectStore os) throws Exception {
		log.debug("Running search");
        if (os == null) {
            throw new InvalidArgument("Object store name must be defined");
        }
        
         
        SearchScope search = new SearchScope(os);
        SearchSQL statement = new SearchSQL();
        statement.setFromClauseInitialValue(symbolicName, symbolicName, includeSubClasses);
        if (MaxRecords > 0) {
            statement.setMaxRecords(MaxRecords);
        }
        if (Where != null && Where.length() > 0) {
            statement.setWhereClause(Where);
        }
        IndependentObjectSet ObjectSet = (IndependentObjectSet) search.fetchObjects(statement, null, null, Boolean.valueOf(true));
        return ObjectSet;
	}

	@Override
	public Document fetchDocument(String id, String os) throws InvalidArgument, Exception {
		if (os == null || os.isEmpty()) {
			throw new InvalidArgument("Object store name must be defined");
		}
		ObjectStore store = this.fetchObjectStore(os);
		return this.fetchDocument(new Id(id), store);
	}

	@Override
	public Document fetchDocument(Id id, ObjectStore os) throws InvalidArgument, Exception {
		log.debug("Fetching document Id");
        
        return Factory.Document.fetchInstance(os, id, null);
	}
	
	@Override
	public Document fetchDocument(String path, ObjectStore os) throws InvalidArgument, Exception {
		log.debug("Fetching document");
		
		return Factory.Document.fetchInstance(os, path, null);
	}

	/**
	 * Creates a new authentication subject
	 */
	private void createSubject(String username, String password, String stanza) {
		UserContext uc = UserContext.get();

		Subject ss = UserContext.createSubject(this.conn, username, password, stanza);
		uc.pushSubject(ss);
		this.subject = ss;

	}

}

IBM FileNet P8 Java API examples

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.