Showing posts with label FileNet API. Show all posts
Showing posts with label FileNet API. Show all posts

Tuesday 10 May 2016

Retrieve all Object stores in CE


// Retrieve all Object stores in CE

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

try {

Domain domain = Factory.Domain.fetchInstance(conn, null, null);
ObjectStoreSet osSet= domain.get_ObjectStores();
ObjectStore store;
Iterator iterator = osSet.iterator();
Iterator<ObjectStore> osIter = iterator;
while (osIter.hasNext()) {
store = (ObjectStore)osIter.next();
 
if((store.getAccessAllowed().intValue() & AccessLevel.USE_OBJECT_STORE.getValue())>0)
System.out.println(store.get_Name());
 
}

} 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);




 

Tuesday 10 February 2015

Search CE Object using SearchSQL (Content Engine API)

Search CE Object

  Note* : first fetch the Object Store 
 

 public ArrayList getCEObjects(String filterParams, String[] resultParams, String ObjectClassName, boolean includeSubClass)
  {
    log.debug("ENTRY ");
    String searchClassScope = includeSubClass ? "INCLUDESUBCLASSES" : "EXCLUDESUBCLASSES";
    String searchQuery = "";

    for (int i = 0; i < resultParams.length; i++) {
      if (i == 0)
        searchQuery = resultParams[i];
      else {
        searchQuery = searchQuery + "," + resultParams[i];
      }
    }
    String searchQ = "SELECT " + searchQuery + " FROM " + ObjectClassName + " WITH " +
      searchClassScope + " WHERE " + filterParams;

    log.debug("CE Search Query " + searchQ);
    SearchSQL sqlObject = new SearchSQL(searchQ);
    SearchScope searchScope = new SearchScope(this.objectStore);

    IndependentObjectSet objectSet = searchScope.fetchObjects(sqlObject, null, null, new Boolean(true));
    Iterator iter = objectSet.iterator();

    ArrayList coList = new ArrayList();
    while (iter.hasNext())
    {
      Hashtable htResult = new Hashtable();
      CustomObject customObject = (CustomObject)iter.next();
      coList.add(customObject);
    }
    if ((coList.size() != 0) && (coList != null))
    {
      log.info(coList.size() + " Custom Objects fetched ");
    }
    log.debug("EXIT");
    return coList;
  }




Thursday 20 November 2014

Add Case Comments in Case Client (IBM Case Manager API)

//Add Case Comments in Case Client (IBM Case Manager API)

public void addCaseCommentInHistory() throws Exception {
            String caseFolderGUID = //GUID of Case Folder
            String comment = "Hi"
            CaseMgmtContext oldCmc = null;
            log.info("Inside [WorkFlowHoldUnholdServices]addCaseComment():.............");
            ICMManager icmManager=new ICMManager();
            Connection conn=null;
            DomainReference domainRef=null;
            ObjectStoreReference osRef=null;
            Folder folder=null;
            try{
                conn=// Establish Connection

                if(conn!=null){
                    domainRef=ICMManager.getDomainReference(conn);
                    if(domainRef!=null){
                        osRef=ICMManager.getTargetOSReference(domainRef, fnObjectStoreName);
                        if(osRef!=null){
                            // retrieve case folder
                            folder = Factory.Folder.fetchInstance(osRef.getFetchlessCEObject(), caseFolderGUID, null);
                            // retrieve case using GUID
                            Id folderGUID = folder.get_Id();
                            Case cs = Case.getFetchlessInstance(osRef, folderGUID);
                            cs.addCaseComment(CommentContext.CASE, comment);
                            cs.save(RefreshMode.REFRESH, null, ModificationIntent.MODIFY);
                            log.info("History updated in Case");
                           
                        }else{
                            log.info("History Not updated As Target OS Ref is NULL");
                        }
                    }   
                }       
            }catch (Exception e) {
                log.error("addCaseCommentInHistory(String, String) - exception:"+ e,e); //$NON-NLS-1$
                e.printStackTrace();               

            }                    
        }               
             




//for connection please click on below link

IBM Case Manager API (fetch P8Connection, Domain, Target Obbject Store)


  

Dispatch Work Item in FileNet Process Engine (Process Engine API)

   
    //Fetch the Work Item
    VWWorkObject vwWorkObj=null;
      try{
          VWRoster roster=peSession.getRoster(rosterName);
          int queryFlags=VWRoster.QUERY_NO_OPTIONS;
          String Name = "abcd";
          String filter="Doc_Name="+Name;//Change Accrordigly (Based on Process Administaration tool fields)
             
          VWRosterQuery query=roster.createQuery(null, null, null, queryFlags, filter, null, VWFetchType.FETCH_TYPE_WORKOBJECT);
          log.info("Total records for Work ITem: "+query.fetchCount());
         
          while(query.hasNext()){
              vwWorkObj=(VWWorkObject) query.next(); 
          }
         
      }catch(VWException vwe){
          log.error("Exception found at PEManager.getVWWorkObject():"+vwe,vwe);
          vwe.printStackTrace();
      }catch(Exception vwe){
          log.error("Exception found at PEManager.getVWWorkObject():"+vwe,vwe);
          vwe.printStackTrace();
      }
     
//Terminate(Dispatch) work Item
try{

if(vwWorkObj!=null){

String Response = "Cancel";
VWStepElement vwStepObj=vwWorkObj.fetchStepElement();
vwStepObj.doLock(true);
vwStepObj.setSelectedResponse(Response);

vwStepObj.doDispatch();
}else{
                           
log.info("VWWorkObject is NULL");
                       
}
                       
}catch(Exception ex){
                           
ex.printStackTrace();
                       
}   

Tuesday 18 November 2014

Build URL of Document in FileNet (Content Engine API)

//Build URL of Document in FileNet (Content Engine API)



//The below code generates the URL of Document. The URL works on same Browser where you run the code else it asks Credentials

public void opendoc() throws IOException
    {
        String baseP8URL = "http://localhost:9080/WorkplaceXT/";
        String user = //User Name
        String password = //Password
        //String objectStore = //Object Store Name
        String docID = //GUID of Document
        //Get Connection
        //Get Domain
        objectStore = //Get Object Store
        com.filenet.api.core.Document doc=com.filenet.api.core.Factory.Document.fetchInstance(objectStore, docID, null);
        String vsId = doc.get_VersionSeries().get_Id().toString();
       
        // Call WorkplaceXT’s setCredentials servlet to obtain user token
        try {
       
        URL url = new URL(baseP8URL +
        "setCredentials?op=getUserToken&userId="
        + user + "&password=" + password + "&verify=true");
        HttpURLConnection p8con =
        (HttpURLConnection) url.openConnection();
        p8con.setRequestMethod("POST");
        p8con.connect();
        InputStream in = p8con.getInputStream();
        int c = -1;
        String tempUserToken = "";
        while ( (c=in.read()) >= 0) tempUserToken +=
        new Character((char)c).toString();
                String userToken = URLEncoder.encode(tempUserToken, "UTF-8");
                System.out.println("the user token "+userToken);
                String strURL = baseP8URL + "getContent?objectStoreName="
                + "Target" + "&vsId=" + vsId + "&objectType=document&ut=" //
                + userToken + "&impersonate=true";
        System.out.println("ssss"+ strURL);
        }
        catch (Exception e )
        {
            e.printStackTrace();
        }
               
    }

View Content (Attachment) in FileNet Document (Content Engine API)

//View Content (Attachment) in FileNet Document (Content Engine API)


        ceConnection = //Get Connection
        domain = //Get Domain
        objectStore = //Get Object Store
       
        InputStream inputStream=null;
        try
        {
        FileInputStream is=null;
       
        System.out.println("inside fetchdoc Filenet----------------------------");
        ArrayList[] ars=new ArrayList[2];
        SearchScope search=new SearchScope(objectStore);
       
        String sql1= "Select * from [DocClass_Test] where ([DocumentTitle]= '"+DocTitle+"')";
        SearchSQL searchSQL=new SearchSQL(sql1);
        DocumentSet documents=(DocumentSet)search.fetchObjects(searchSQL, Integer.getInteger("50"), null, Boolean.valueOf(true));
        Document doc;
        Iterator it=documents.iterator();
       
        System.out.println("calling FileInputStream");
        while(it.hasNext())
        {
            doc=(Document)it.next();
            ContentElementList contents = doc.get_ContentElements();
              ContentTransfer ct;
              Iterator itContent = contents.iterator();
              while(itContent.hasNext()) {
                  ct = (ContentTransfer)itContent.next();
              inputStream = ct.accessContentStream();
              int bufferLength = 64*1024; // buffer size (64KB)
                byte[] buffer = new byte[bufferLength];
                int read=0;
              
                DataOutputStream out = new DataOutputStream(response.getOutputStream());
                System.out.println("calling while-- check");
                while((read=inputStream.read(buffer))!=-1)
                {
                    out.write(buffer,0,read);                 
                }
               
                out.close();
   
        }     
        }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

Friday 14 November 2014

Get and Put properties on Document(CE API)

//Put Multiple Properties on multiple Documents

                ObjectStore objectstore =//Get Object Store
                logger.info("Object Store Name :: "+objectstore.get_DisplayName());
                SearchScope search=new SearchScope(objectstore);
                String value = "abcd"
                String sql1= "Select * from DocumentClass where DocumentTitle = "+value;
                SearchSQL searchSQL=new SearchSQL(sql1);
                DocumentSet documents=(DocumentSet)search.fetchObjects(searchSQL, Integer.getInteger("50"), null, Boolean.valueOf(true));
                Document doc;
                Iterator it=documents.iterator();
                while(it.hasNext())
                {
                    doc=(Document)it.next();
                    doc.getProperties().putValue("Name", abc);
                    doc.getProperties().putValue("number", 123);
                    doc.getProperties().putValue("Salary", 200);
                    doc.save(RefreshMode.REFRESH);

                }


//

Searching and Deleting documents(CE API)

//Searching and Deleting documents(CE API)

             SearchScope search=new SearchScope(objectstore);
                String value = abc;
                String sql1= "Select * from DocClass where DocumentTitle = "+ Value;
                SearchSQL searchSQL=new SearchSQL(sql1);
                DocumentSet documents=(DocumentSet)search.fetchObjects(searchSQL, Integer.getInteger("50"), null, Boolean.valueOf(true));
                Document doc;
                Iterator it=documents.iterator();
                while(it.hasNext())
                {
                    doc=(Document)it.next();
                    logger.info("document name::"+doc.get_Name());
                    logger.info("deleting the document now:::");
                    doc.delete();
                    doc.save(RefreshMode.REFRESH);
                   
                }

Thursday 13 November 2014

IBM Case Manager API (fetch P8Connection, Domain, Target Obbject Store)

//Establish ICM Connection

public static Connection getICMConnection(String uri,String userID,String password){
      
        try{
            //uri = "http://localhost:9080/wsi/FNCEWS40MTOM/";
            P8ConnectionCache connCache = new SimpleP8ConnectionCache();
            conn = connCache.getP8Connection(uri);
            log.info("ICM Connection: "+conn);
          
            Subject subject =   UserContext.createSubject(conn, userID, password, "FileNetP8WSI");
            uc = UserContext.get();
            uc.pushSubject(subject);
          
            origLocale = uc.getLocale();
            uc.setLocale(origLocale);
            origCmctx = CaseMgmtContext.set(new CaseMgmtContext(new SimpleVWSessionCache(), connCache));
        }catch(Exception ex){
            ex.printStackTrace();
            log.error("[ICMManager]getICMConnection():Exception found is :"+ex.getMessage());
        }
      
      
        return conn;
    }



//Domain References

public static DomainReference getDomainReference(Connection conn){
       
       
        try{
            Domain domain=Factory.Domain.fetchInstance(conn, null, null);
            log.info("[ICMManager]getDomainreference():Domain Name: "+domain.get_Name());
           
            domainReference=new DomainReference(domain);
        }catch(Exception ex){
            ex.printStackTrace();
            log.error("[ICMManager]getDomainreference():Exception found: "+ex,ex);
        }
        return domainReference;
       
    }


//Get Target Object Store

public static ObjectStoreReference getTargetOSReference(DomainReference domRef,String osName){
       
        try{
            targetObjectStoreReference=new ObjectStoreReference(domRef, osName);
            log.info("[ICMManager]getTargetOSReference():Target Object Store Reference: "+targetObjectStoreReference.toString());
        }catch(Exception ex){
            ex.printStackTrace();
            log.error("[ICMManager]getTargetOSReference():Exception found: "+ex,ex);
        }
        return targetObjectStoreReference;
       
    }


//Close ICM Connection

public static void closeICMObjects(){
        CaseMgmtContext.set(origCmctx);
        uc.setLocale(origLocale);
        uc.popSubject();
        targetObjectStoreReference=null;
        domainReference=null;
        conn=null;
       
    }















Search Work Item in Roaster (PE API)

//Search Work Item in Roaster


public static VWWorkObject getVWWorkObject(VWSession peSession,String rosterName){
      VWWorkObject vwwObj=null;
      try{
     
     
          VWRoster roster=peSession.getRoster(rosterName);
          int queryFlags=VWRoster.QUERY_NO_OPTIONS;
          String abc = "abc";
          String filter="Property_Name ="+abc;

          //Change filter based on requirement

       
          VWRosterQuery query=roster.createQuery(null, null, null, queryFlags, filter, null, VWFetchType.FETCH_TYPE_WORKOBJECT);
          log.info("Total records for Work ITem: "+query.fetchCount());
         
          while(query.hasNext()){
              vwwObj=(VWWorkObject) query.next(); 
          }
         
      }catch(VWException vwe){
          log.error("Exception found at PEManager.getVWWorkObject():"+vwe,vwe);
          vwe.printStackTrace();
      }catch(Exception vwe){
          log.error("Exception found at PEManager.getVWWorkObject():"+vwe,vwe);
          vwe.printStackTrace();
      }
     
      return vwwObj;
  }

Get PE Session (Process Engine JAVA API)

Process Engine API

//Get Session

  public static VWSession getPESession()
    {
      String strAppURI1="http://localhost:9080/wsi/FNCEWS40MTOM/";
      System.out.println("[ENTER  PEManager getPESession()]");
      VWSession peSession = null;

      System.setProperty("java.security.auth.login.config","C:\\opt\\jaas.conf.WSI");
    

      try
      {
        peSession = new VWSession();
        peSession.setBootstrapCEURI(strAppURI1);
    
        peSession.logon(username, password, connectionPoint);
        String sn = peSession.getPEServerName();
        System.out.println("++++++++++++++++"+ sn);

        System.out.println("PE session established:"+peSession);
      }
      catch (VWException e) {
          System.out.println("Exception occured while establishing PE session." );
          e.printStackTrace();

      }
      System.out.println("[Exit PEManager getPESession()]");
    return peSession;
  }

//Close VWSession

public static void closePESession(VWSession peSession)
  {
    log.debug("[Enter closePESession]");
    try {
      if (peSession != null)
        peSession.logoff();
    }
    catch (VWException e) {
      log.error(e.getMessage(), e);
    }

    log.debug("[Exit : closePESession]");
  } 


Content Engine JAVA API

Content Engine API's

// Get Connection

    public Connection getCEConnectionHTTP() {
        try{
        String UserName = "p8admin";
        String Password = "p8admin";
        String Url = "http://localhost:9080/wsi/FNCEWS40MTOM/";
        String Stanza = "FileNetP8WSI";
        connection = Factory.Connection.getConnection(Url);
        System.out.println("Connection is established");
        subject = UserContext.createSubject(connection, UserName, Password, Stanza);
        UserContext uc = UserContext.get();
        uc.pushSubject(subject);
        return connection;
        }
        catch (EngineRuntimeException engineRuntimeException) {
            System.out.println("RuntimeException occured while getting the connection = "+ engineRuntimeException.getMessage());
                           
            engineRuntimeException.printStackTrace();
        }
        return connection;
    }


//Get Domain


public Domain getFileNetDomain()
    {
        String domainName = "P8DEVAirtelAfrica";
        Domain domain = null;
        try
        {
        domain = Factory.Domain.fetchInstance(getCEConnectionHTTP(), domainName, null);
        }
        catch (EngineRuntimeException engineRuntimeException) {
            System.out.println("RuntimeException occured while getting the Domain = "+ engineRuntimeException.getMessage());
                           
            engineRuntimeException.printStackTrace();
        }
        return domain;
    }


// Get Object Store

public ObjectStore getObjectStore(Domain domain, String objectStoreName) {
        ObjectStore os = null;
        try {
//            domain = null;
            os = Factory.ObjectStore.fetchInstance(domain, objectStoreName, null);
            System.out.println("ObjectStor Details " + os.get_DisplayName());
        } catch (EngineRuntimeException ere) {
            System.out.println("getObjectStore :" + ere.getExceptionCode().getKey());
            ere.printStackTrace();
        }
        return os;
    }