Showing posts with label CE Document API. Show all posts
Showing posts with label CE Document API. Show all posts

Friday, 26 May 2017

Java code for Downloading Document Content (Attachments) (FileNet Content Engine API)

//Java code for Downloading Document Content (Attachments) (FileNet Content Engine API)

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import javax.security.auth.Subject;
import com.filenet.api.collection.ContentElementList;
import com.filenet.api.collection.IndependentObjectSet;
import com.filenet.api.constants.RefreshMode;
import com.filenet.api.core.Connection;
import com.filenet.api.core.ContentTransfer;
import com.filenet.api.core.Document;
import com.filenet.api.core.Domain;
import com.filenet.api.core.Factory;
import com.filenet.api.core.ObjectStore;
import com.filenet.api.property.Properties;
import com.filenet.api.query.SearchSQL;
import com.filenet.api.query.SearchScope;
import com.filenet.api.util.UserContext;

public class DownloadContent {

private static Connection conn = null;
public static Connection getCEConn()
{

try {

String ceURI = "http://localhost:9080/wsi/FNCEWS40MTOM/";
String userName ="username";
String password ="password";
if(conn==null){
conn = Factory.Connection.getConnection(ceURI);
Subject subject = UserContext.createSubject(conn, userName, password, null);
UserContext uc = UserContext.get();
uc.pushSubject(subject);
}

} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("CE Conn :: "+conn);
return conn;
}
public static void downloadDoc(String osName) throws IOException{

try{
//get the CE document

Connection conn = getCEConn();
Domain domain = Factory.Domain.fetchInstance(conn,null, null);
ObjectStore objStore = Factory.ObjectStore.fetchInstance(domain, osName,null);
SearchScope searchScope = new SearchScope(objStore);

int count=1;
String sqlStr = "Select * FROM DocClass where Title='abcd'";
SearchSQL searchSQL = new SearchSQL(sqlStr);
System.out.println("Query ::"+sqlStr);
IndependentObjectSet independentObjectSet = searchScope.fetchObjects(searchSQL, new Integer(10), null, new Boolean(true)); 
String docTitle=null;
if(!(independentObjectSet.isEmpty())){
Iterator it=independentObjectSet.iterator();
while(it.hasNext()) {
Document doc=(Document)it.next();
Properties documentProperties = doc.getProperties();
docTitle=documentProperties.getStringValue("DocumentTitle");
System.out.println("Doc Title :: "+ docTitle);
ContentElementList docContentList = doc.get_ContentElements();
Iterator iter = docContentList.iterator();
String filepath = "D:\\";
FileOutputStream fos = new FileOutputStream(filepath+docTitle);
count++; 
while (iter.hasNext() )
{
   ContentTransfer ct = (ContentTransfer) iter.next();
   // Print element sequence number and content type of the element.
   System.out.println("\nElement Sequence number: " + ct.get_ElementSequenceNumber().intValue() + "\n" +"Content type: " + ct.get_ContentType() + "\n");
   InputStream stream = ct.accessContentStream();
   byte[] buffer = new byte[4096000];
   int bytesRead = 0;
   while ((bytesRead = stream.read(buffer)) != -1) {
    System.out.print(".");
    fos.write(buffer,0,bytesRead);
   }
   System.out.println("done!");
       fos.close();
   stream.close();
    }
}
System.out.println("Count:::;"+count);
System.out.println("Done");
}
}
catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
downloadDoc("ObjectStore");
}


}

Thursday, 12 May 2016

Retrieving Documents and properties based on Content Based Retrieval(CBR)

//Retrieving Documents and properties based on Content Based Retrieval(CBR)

//content-based document searching

import java.util.Iterator;
import javax.security.auth.Subject;

import com.filenet.api.collection.DocumentSet;
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.ObjectStore;
import com.filenet.api.query.SearchSQL;
import com.filenet.api.query.SearchScope;
import com.filenet.api.util.UserContext;

public class ceUtil {

public static void main(String[] args) {
ceUtil obj = new ceUtil();
obj.FetchCEObjects(obj.getCEConnection());


}

public Connection getCEConnection() {

Connection conn = null;
try {

String ceURI = "http://localhost:9080/wsi/FNCEWS40MTOM/";

String userName = "userName";
String password = "password";
conn = Factory.Connection.getConnection(ceURI);
Subject subject = UserContext.createSubject(conn, userName,
password, null);
UserContext uc = UserContext.get();
uc.pushSubject(subject);
} catch (Exception e1) {
e1.printStackTrace();
}
System.out.println("CE Connection" + conn);
return conn;
}

public void FetchCEObjects(Connection conn) {
try {
Domain domain = Factory.Domain.fetchInstance(conn, null, null);
ObjectStore objStore = Factory.ObjectStore.fetchInstance(domain,"OSNAME", null);

SearchScope search = new SearchScope(objStore);
String keyWord = "keyword in attachment";

String mySQLString= "SELECT d.this, DocumentTitle,Name FROM docClass d INNER JOIN ContentSearch v ON v.QueriedObject= d.This WHERE d.IsCurrentVersion= TRUE AND CONTAINS(d.*,'" + keyWord+ "')";
SearchSQL sql= new SearchSQL(mySQLString); 
DocumentSet documents = (DocumentSet) search.fetchObjects(sql,Integer.valueOf("50"),null, Boolean.valueOf(true));
com.filenet.api.core.Document doc; 

Iterator it = documents.iterator();
while (it.hasNext())
{
doc = (Document)it.next();
System.out.println("document="+doc.get_Name());
}

} catch (Exception e) {
e.printStackTrace();
}
}

}


/*
Additinal Queries for Content Based search

SELECT d.This, DocumentTitle, Name FROM docClass d INNER JOIN VerityContentSearch v ON v.QueriedObject= d.This WHERE d.IsCurrentVersion= TRUE AND CONTAINS(d.*,'model <SENTENCE> Deluxe')
//Search for documents that contain the two key words in a sentence (use with <SENTENCE>).

SELECT d.This, DocumentTitle, Name FROM docClass d INNER JOIN VerityContentSearch v ON v.QueriedObject= d.This WHERE d.IsCurrentVersion= TRUE AND CONTAINS(d.*, 'tested <NEAR/25> passed')
//Search for documents that contain the two key words located close to each other (use with <NEAR>)
*/

*******************************************************************************

//Sample code for retrieving the properties based on CBR

RepositoryRowSet rowSet= search.fetchRows(sql, Integer.valueOf("50"),null,Boolean.valueOf(true));
Iterator itRow= rowSet.iterator();
RepositoryRow row; 
com.filenet.api.property.Properties props; 
com.filenet.api.property.Property prop; 
while (itRow.hasNext()) 
{
row = (RepositoryRow)itRow.next();
props = row.getProperties(); 
Iterator itProp= props.iterator(); 
while (itProp.hasNext())
{
prop =(com.filenet.api.property.Property) itProp.next();
if(prop.getPropertyName().equalsIgnoreCase("Rank"))
{
System.out.println(prop.getPropertyName() +" = " + prop.getFloat64Value().toString());
else
System.out.println(prop.getPropertyName()+" = " + prop.getStringValue());
}
}
}

Searching or Retriving Documents from Multiple Object stores in FileNet Content Engine

//Searching or Retriving Documents from Multiple Object stores in FileNet Content Engine

import java.util.Iterator;
import javax.security.auth.Subject;

import com.filenet.api.collection.DocumentSet;
import com.filenet.api.constants.MergeMode;
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.ObjectStore;
import com.filenet.api.property.FilterElement;
import com.filenet.api.property.PropertyFilter;
import com.filenet.api.query.SearchSQL;
import com.filenet.api.query.SearchScope;
import com.filenet.api.util.UserContext;


public class ceUtil {


public static void main(String[] args) {
ceUtil obj = new ceUtil();
obj.FetchCEObjects(obj.getCEConnection());


}

public Connection getCEConnection() {

Connection conn = null;
try {

String ceURI = "http://localhost:9080/wsi/FNCEWS40MTOM/";

String userName = "username";
String password = "password";
conn = Factory.Connection.getConnection(ceURI);
Subject subject = UserContext.createSubject(conn, userName,
password, null);
UserContext uc = UserContext.get();
uc.pushSubject(subject);
} catch (Exception e1) {
e1.printStackTrace();
}
System.out.println("CE Connection" + conn);
return conn;
}

public void FetchCEObjects(Connection conn) {

try {
Domain domain = Factory.Domain.fetchInstance(conn, null, null);

ObjectStore objectStores[] = new ObjectStore[2];
objectStores[0] = Factory.ObjectStore.fetchInstance(domain,"DESIGNOS", null);
objectStores[1] = Factory.ObjectStore.fetchInstance(domain,"TARGETOS", null);
System.out.println("Object Store 1 : "+objectStores[0].get_DisplayName());
System.out.println("Object Store 2 : "+objectStores[1].get_DisplayName());

PropertyFilter pf= new PropertyFilter();
pf.addIncludeProperty(new FilterElement(Integer.getInteger("2"),null, Boolean.valueOf(true),"Name"));
SearchScope search = new SearchScope(objectStores, MergeMode.UNION);
SearchSQL sql= new SearchSQL("Select * from docClass where Creator='p8admin'");
DocumentSet documents = (DocumentSet)search.fetchObjects(sql,Integer.getInteger("50"),pf, Boolean.valueOf(true));

Document doc;
Iterator it = documents.iterator();
while (it.hasNext()){doc = (Document)it.next();
System.out.println("document="+doc.get_Name());
}

} catch (Exception e) {
e.printStackTrace();
}
}
}

Searching Documents with Paging concept in FileNet Content Engine

PageIterator (Paging)  (FileNet Content Engine API)

Provides paging functionality for sets of independent objects and repository rows.


Sets of independent objects and repository rows are divided into pages;each page is a number of collection elements (objects or rows) that represent a subset of the collection elements. You can iterate a page at a time instead of one object or row at a time. 

As an example, if a page is defined as 10 elements, and the collection has a total of 22 elements, the first paging operation returns a page containing 10 elements, the second page returns the next 10 elements, and the third page returns the last 2 elements. This page iteration is especially useful for interactive applications that display a page of information at a time.


//Searching Documents with Paging concept in FileNet Content Engine

import java.util.Iterator;
import javax.security.auth.Subject;
import com.filenet.api.collection.ClassDescriptionSet;
import com.filenet.api.collection.DocumentSet;
import com.filenet.api.collection.PageIterator;
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.ObjectStore;
import com.filenet.api.meta.ClassDescription;
import com.filenet.api.query.SearchSQL;
import com.filenet.api.query.SearchScope;
import com.filenet.api.util.UserContext;

public class ceUtil {

public static void main(String[] args) {
ceUtil obj = new ceUtil();
obj.FetchCEObjects(obj.getCEConnection());
}

public Connection getCEConnection() {

Connection conn = null;
try {
String ceURI = "http://localhost:9080/wsi/FNCEWS40MTOM/";
String userName = "username";
String password = "password!";
conn = Factory.Connection.getConnection(ceURI);
Subject subject = UserContext.createSubject(conn, userName,
password, null);
UserContext uc = UserContext.get();
uc.pushSubject(subject);
} catch (Exception e1) {
e1.printStackTrace();
}
System.out.println("CE Connection" + conn);
return conn;
}

public void FetchCEDocs(Connection conn) {


try {
Domain domain = Factory.Domain.fetchInstance(conn, null, null);
ObjectStore objStore = Factory.ObjectStore.fetchInstance(domain,"OS NAME", null);
String folder= "/TestEform";

SearchScope search = new SearchScope(objStore);
String sql1 = "Select * from docClass where Creator='p8admin'";
SearchSQL searchSQL= new SearchSQL(sql1); 
DocumentSet documents = (DocumentSet) search.fetchObjects(searchSQL,Integer.valueOf("50"),null, Boolean.valueOf(true)); 

//Without Paging Concept
Document doc;
Iterator DocIt= documents.iterator();
while (DocIt.hasNext())
{
doc = (Document)DocIt.next();
System.out.println("document="+doc.get_Name());
}

// With Paging Concept
PageIterator pageIter= documents.pageIterator();
pageIter.getPageSize();pageIter.setPageSize(5);
int pageCount= 0; 
while (pageIter.nextPage() == true) 
{
pageCount++;
int elementCount= pageIter.getElementCount();
System.out.println("Element Count = "+elementCount);
Object[] pageObjects= pageIter.getCurrentPage();
for (int index=0; index<pageObjects.length;index++)
{
Document document = (Document)pageObjects[index];
System.out.println("document= "+ document.get_Name());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Wednesday, 11 May 2016

Java Sample for Retrieving collections of individual classes meta data and individual properties meta data (FileNet Content Engine API)

// Java Sample for Retrieving collections of individual classes meta data and individual properties meta data (FileNet Content Engine API)

public void FetchPropClassDesc(Connection conn) {

try {
Domain domain = Factory.Domain.fetchInstance(conn, null, null);
ObjectStore objStore = Factory.ObjectStore.fetchInstance(domain,"OSNAME", null);


/*
ClassDescription Are collections of metadata that describe individual classes
Provide access to PropertyDescriptionobjects associated with class 
Return default permission for an object of a particular class
Determine if versioning is enabled for a particular Document class
Assign a document lifecycle policy to a document class or subclassRetrieve
*/

ClassDescriptionSet classDescriptions= objStore.get_ClassDescriptions();
ClassDescription classDesc;
Iterator it = classDescriptions.iterator();
while (it.hasNext()) 
{
classDesc= (ClassDescription)it.next();
System.out.println("Class name = " + classDesc.get_DisplayName());

}

PropertyFilter pf= new PropertyFilter();
pf.addIncludeType(0, null, null, FilteredPropertyType.ANY,1);
Document document=Factory.Document.fetchInstance(objStore, new Id("{08CA2852-111B-4E5D-B032-DBG2A653B4FD}"), pf);
String documentName= document.get_Name();
System.out.println(documentName+ " Document has been retrieved");


com.filenet.api.meta.ClassDescription classDescription= document.get_ClassDescription();
/*
Are collections of metadata that describe individual properties
Are contained in the ClassDescriptionPropertyDescriptionsproperty
Provide information on how the property needs to be represented to the user
Contain information such as choice lists 
Each instance of a PropertyDescription object describes a specific property for a single class
*/

PropertyDescriptionList propDescs= classDescription.get_PropertyDescriptions();
PropertyDescription propDesc; 
Iterator propIt= propDescs.iterator();
while (propIt.hasNext()) 
{
propDesc=(PropertyDescription)propIt.next();

System.out.println("Property name = " +propDesc.get_SymbolicName()); 
//get_SymbolicName(): A String thatrepresents the programmatic identifier for this PropertyDescription

System.out.println("Read only? " + propDesc.get_IsReadOnly().toString()); 
//get_IsReadOnly(): A Boolean value that indicates whether or not you can modify the value of the property. If true, the property value can be changed only by the server

System.out.println("Value of Property" + propDesc.get_Settability()); 
//get_Settability(): A constant that indicates when the value of a property can be setRetrieve (READ_ONLY-3, READ_WRITE-0, SETTABLE_ONLY_BEFORE_CHECKIN-1, SETTABLE_ONLY_ON_CREATE)

System.out.println("Is Value Required ? "+propDesc.get_IsValueRequired()); 
//get_IsValueRequired(): A Boolean value that indicates whether the property is required to have a value (true) or not (false)

System.out.println("Cardinality = " + propDesc.get_Cardinality()); 
//get_Cardinality() :A constant that indicates the cardinality of the PropertyDescription (ENUM-1, LIST-2, SINGLE-0)

System.out.println(""+propDesc.get_IsSystemGenerated());
/*get_IsSystemGenerated(): A Boolean value that indicates whether the property has its value set automatically by the Content Engine server (true) or not (false). 
If the value is true, the described property does one of the following:
Provides system information
Has its value determined by the server
*/

}

} catch (Exception e) {
e.printStackTrace();
}
}

Tuesday, 10 May 2016

Retrieving all documents and objects in Folder (FileNet CE API)

//Retrieving all documents and objects in Folder (FileNet CE API)

public void FetchCEObjectsInFolder(Connection conn) {  //FileNet CE Connection 

try {
Domain domain = Factory.Domain.fetchInstance(conn, null, null);
ObjectStore objStore = Factory.ObjectStore.fetchInstance(domain,"OSNAME", null);
System.out.println("Object Store ="+ objStore.get_DisplayName() );

String folder= "/Test"; // Folder name

com.filenet.api.core.Folder folderOj= Factory.Folder.fetchInstance(objStore,folder, null);
System.out.println("del"+folderOj.get_Name());

DocumentSet documents = folderOj.get_ContainedDocuments(); //For documents

ReferentialContainmentRelationshipSet refConRelSet= folderOj.get_Containees(); // for objects
Iterator it = documents.iterator(); 
while(it.hasNext())
{

//Retrieving documents
Document retrieveDoc= (Document)it.next();
String name = retrieveDoc.get_Name();
System.out.println("Document Name :: "+ name);

//Retrieving Objects
ReferentialContainmentRelationship retrieveObj=(ReferentialContainmentRelationship)it.next();
IndependentObject containee=retrieveObj.get_Head();
String className= containee.getClassName();
String displayName= retrieveObj.get_Name(); 
System.out.println("Class Name = "+ className);
System.out.println("Display Name = "+ displayName);
}
} catch (Exception e) {
e.printStackTrace();
}
}

Friday, 11 March 2016

Fetch(or Filter) Meta Data(of Document) from Content Engine and write into CSV file

//Fetch(or Filter) Meta Data(of Document) from Content Engine  and write into CSV file

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import javax.security.auth.Subject;
import com.csvreader.CsvWriter;
import com.filenet.api.collection.IndependentObjectSet;
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.ObjectStore;
import com.filenet.api.property.Properties;
import com.filenet.api.query.SearchSQL;
import com.filenet.api.query.SearchScope;
import com.filenet.api.util.UserContext;

public class CSVReportFromCEDoc{
private static Connection conn = null;
    public static Connection getCEConnection()
    {
        try {
            String ceURI = "http://localhst:9080/wsi/FNCEWS40MTOM/"; //FileNet URL
            String userName ="p8admin"; //User Name
            String password ="filenet"; //Password
            if(conn==null){
            conn = Factory.Connection.getConnection(ceURI); //CE connection
            Subject subject = UserContext.createSubject(conn, userName, password, null); //creating subject
            UserContext uc = UserContext.get(); 
            uc.pushSubject(subject); //push subject
            }

        } catch (Exception e1) {
            e1.printStackTrace();
        }
        System.out.println("CE Connection"+conn);
        return conn;
    }
    public static void getInternalQADocuments() throws IOException{
        String osName="RAKESHOS"; //Object Store name
        try{
            Connection conn = getCEConnection();
            Domain domain = Factory.Domain.fetchInstance(conn,null, null); //fetching domain
            ObjectStore objStore = Factory.ObjectStore.fetchInstance(domain, osName,null); //fetching object store
            SearchScope searchScope = new SearchScope(objStore); // Creating search scope object
            int count=1;
            String sqlStr = "Select * FROM DocClass"; //CE Query
            SearchSQL searchSQL = new SearchSQL(sqlStr);
            System.out.println("Query ::"+sqlStr);
            //fetching Data from Content Engine
            IndependentObjectSet independentObjectSet = searchScope.fetchObjects(searchSQL, new Integer(10), null, new Boolean(true)); 
           
            File file = new File("E:\\Report.csv"); 

            if ( !file.exists() ){
                file.createNewFile();
            }
            // Use FileWriter constructor that specifies open for appending
            CsvWriter csvOutput = new CsvWriter(new FileWriter(file, true), ',');
            //Create Header for CSV
            csvOutput.write("Title");
            csvOutput.write("Doc Type");
            csvOutput.write("Country");
            csvOutput.write("State");
            csvOutput.write("Street");
            csvOutput.write("House No");
            csvOutput.write("Added On");
            csvOutput.write("Modified On");
             csvOutput.endRecord();
            
            String Title=null;
            String DocType=null;
            Date DateCreated=null;
            Date DateLastModified=null;
            String State=null;
            String Country=null;
            String Street=null;
            String HouseNo=null;
            if(!(independentObjectSet.isEmpty())){
                Iterator it=independentObjectSet.iterator();
                while(it.hasNext())    {
                    Document doc=(Document)it.next();
                   
                    //fetching properties from each document
                    Properties documentProperties = doc.getProperties();
                     Title=doc.getProperties().getStringValue("DocumentTitle");
                     System.out.println("Title:::"+Title);
                     DocType=documentProperties.getStringValue("DocType");
                     DateCreated=documentProperties.getDateTimeValue("DateCreated");
                     DateLastModified=documentProperties.getDateTimeValue("DateLastModified");
                     State=documentProperties.getStringValue("State");
                     Country=documentProperties.getStringValue("Country");
                     Street=documentProperties.getStringValue("Street");
                     HouseNo=documentProperties.getStringValue("HouseNo");
                   
                     //inserting into CSV file
                     csvOutput.write(Title);
                     csvOutput.write(DocType);
                     csvOutput.write(Country);
                     csvOutput.write(State);
                     csvOutput.write(Street);
                     csvOutput.write(HouseNo);
                     csvOutput.write(DateCreated.toString());
                     csvOutput.write(DateLastModified.toString());
                     csvOutput.endRecord();
                     count++; 
                     System.out.println("Count:::;"+count);
                    }
                }
            }
        catch(Exception e){
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws IOException {
        getInternalQADocuments();
    }
}

Thursday, 12 February 2015

Create a Document with Content (CE API)

Create a Document with Content (CE API)
-----------------------------------------------------------

//Get CE Connetcion
//Create Subject
//Push Subject

//Get Domain (domain)
ObjectStore os = null;
objectStoreName = "COS"
os = Factory.ObjectStore.fetchInstance(domain, objectStoreName, null); 


 //Get Folder
 Folder folder=null;
 folderName = ''/Sample";
folder=Factory.Folder.fetchInstance(os, folderName, null); 


 //Get the File details
InputStream file = "";
String fileName = "";
int fileSize = "";
 
// Create Document

String docClass = "dcumnet class name";
Document doc = Factory.Document.createInstance(os, docClass); 
if (file != null && fileSize > 0) {
                        ContentTransfer contentTransfer = Factory.ContentTransfer.createInstance();
                        contentTransfer.setCaptureSource(file);
                        contentElementList.add(contentTransfer);
                        doc.set_ContentElements(contentElementList);
                        contentTransfer.set_RetrievalName(fileName);                       
                        doc.set_MimeType(getMimetype(fileName));
                    }
                   


//Check-in the doc
doc.checkin(AutoClassify.DO_NOT_AUTO_CLASSIFY,CheckinType.MAJOR_VERSION);                   
//Get and put the doc properties
String documentName =""
Properties p = doc.getProperties();
p.putValue("DocumentTitle","abcd");
p.putValue("Name","Rakesh");
p.putValue("Number","01234"); 

              

doc.save(RefreshMode.REFRESH);

//Stores above content to the folder

 ReferentialContainmentRelationship rc = folder.file(doc,
                                    AutoUniqueName.AUTO_UNIQUE,
                                    documentName,
                                    DefineSecurityParentage.DO_NOT_DEFINE_SECURITY_PARENTAGE);

 rc.save(RefreshMode.REFRESH);