Wednesday, October 30, 2019

SpringBoot Server Monitor

SpringBoot based demo Server Monitor Application



Check out the source-code at Github:
Github

Friday, May 11, 2018

Spring Boot 2 Security Data JPA Hibernate Bootstrap

What we will accomplish:
  1. User login
  2. User registration and user-role selection at registration screen itself
  3. Spring Security
  4. Remember-me feature
  5. CRUD Operations using Data JPA Hibernate
  6. Form Validations
  7. UI using Bootstrap, Popper, Jquery, Font Awesome, Datatable


Technologies (Majorly) Used:

Spring Boot - 2.0.2
Spring Data JPA 2.0.6
Spring web/security 5.0.x (as on May 23, 2018)
Hibernate 5.2.17


Overall look and feel:

Login (Remember - me)



Invalid Login



CRUD Operations (Role Based)


http://localhost:8080/list
http://localhost:8080/registration
http://localhost:8080/edit-user-xxxxxx
http://localhost:8080/delete-user-xxxxxx

















Add / Register User





Validations while adding/editing user(s)



Home page 

http://localhost:8080/home





The source code:

Github

Stay Tuned.

Happy learning..!!




Tuesday, March 13, 2018

Spring MVC Spring Security 4 Hibernate 5 CRUD Application

Tools Used:

  • JDK 8. Which can be downloaded from here: http://www.oracle.com/technetwork/java/javase/downloads/index.html
  • MySQL Database Server (or any other DB of your choice). MySQL can be downloaded from here: http://dev.mysql.com/downloads/
  • IDE of your choice. Eclipse - https://eclipse.org/downloads/  AND/OR Netbeans - https://netbeans.org/downloads

The POM:
<springframework.version>4.3.14.RELEASE</springframework.version>
        <springsecurity.version>4.2.4.RELEASE</springsecurity.version>
        <hibernate.version>5.1.12.Final</hibernate.version>
        <hibernate.validator.version>5.4.2.Final</hibernate.validator.version>
         <ch.qos.logback.version>1.1.7</ch.qos.logback.version>
         <javax.validation.api.version>1.1.0.Final</javax.validation.api.version>
         <javax.servlet.api.version>3.1.0</javax.servlet.api.version>
         <javax.servlet.jsp.api.version>2.3.1</javax.servlet.jsp.api.version>
         <javax.servlet.jstl.version>1.2</javax.servlet.jstl.version>
        <mysql.connector.version>5.1.45</mysql.connector.version>


              <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.2</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>2.4</version>
                    <configuration>
                        <warSourceDirectory>src/main/webapp</warSourceDirectory>
                        <warName>Spring4Hibernate5</warName>
                        <failOnMissingWebXml>false</failOnMissingWebXml>
                    </configuration>
                </plugin>




Login screen



Admin login


User registration (only for Admin User)


Validations



Editor login (having only edit permissions)

Viewer login (read only permissions)


Access denied page.
Try to access:
http://localhost:8088/Spring4Hibernate5/delete-user-admin




Create a basic Sping MVC CRUD application which has: 
  • User login.
  • Login-Logout feature.
  • Authentication Filter.
  • Remember-me feature
  • Spring Model, View and Controller.
  • Access denied for unauthorized users.
  • Hibernate Transaction Management
  • Bootstrap 4 CSS usage.

Source Code:

Thursday, September 21, 2017

FileNet APIs - Quick Reference

package akfilenetceoperations;

import com.filenet.api.admin.ClassDefinition;
import com.filenet.api.admin.PropertyDefinition;
import com.filenet.api.collection.AccessPermissionDescriptionList;
import com.filenet.api.collection.AccessPermissionList;
import com.filenet.api.collection.ContentElementList;
import java.io.*;
import javax.security.auth.Subject;
import javax.security.auth.callback.*;
import javax.security.auth.login.*;
import com.filenet.api.collection.DocumentSet;
import com.filenet.api.collection.EngineCollection;
import com.filenet.api.collection.FolderSet;
import com.filenet.api.collection.IndependentObjectSet;
import com.filenet.api.collection.ObjectStoreSet;
import com.filenet.api.collection.PropertyDefinitionList;
import com.filenet.api.collection.PropertyDescriptionList;
import com.filenet.api.collection.ReferentialContainmentRelationshipSet;
import com.filenet.api.collection.RepositoryRowSet;
import com.filenet.api.constants.*;
import com.filenet.api.core.*;
import com.filenet.api.exception.EngineRuntimeException;
import com.filenet.api.exception.ExceptionCode;
import com.filenet.api.meta.ClassDescription;
import com.filenet.api.meta.PropertyDescription;
import com.filenet.api.property.FilterElement;
import com.filenet.api.property.Properties;
import com.filenet.api.property.PropertyFilter;
import com.filenet.api.query.RepositoryRow;
import com.filenet.api.query.SearchSQL;
import com.filenet.api.query.SearchScope;
import com.filenet.api.security.AccessPermission;
import com.filenet.api.security.AccessPermissionDescription;
import com.filenet.api.security.Permission;
import com.filenet.api.util.Id;
import com.filenet.api.util.UserContext;
import com.filenet.wcm.api.Permissions;
import com.filenet.wcm.api.Property;
import java.text.SimpleDateFormat;
import java.util.Iterator;

public class FileNetCEOperations {

    private static final class ConfigInfo {

        static boolean USE_EXPLICIT_JAAS_LOGIN = false;
        static String USERID = "fnp8adminuname";
        static String PASSWORD = "fnp8adminpwd";
        static String JAAS_STANZA_NAME = "FileNetP8WSI";
        static String CE_URI = "http://ceserver1:9080/wsi/FNCEWS40MTOM";
        static String OBJECT_STORE_NAME = "SomeOSName";
        static String FOLDER_NAME = "APITest";
        static String LOCAL_FILE_NAME = "c:/apitest/test.pdf";
        static String DOCUMENT_TITLE = "Some Document Title";
        static String CONTAINMENT_NAME = "Any Contained Document";
        static boolean USE_SKIP = true;
    }

    private final Connection conn = Factory.Connection.getConnection(ConfigInfo.CE_URI);

    public static void main(String[] args) throws LoginException, Exception {
        System.out.println("CE is at " + ConfigInfo.CE_URI);
        System.out.println("ObjectStore is " + ConfigInfo.OBJECT_STORE_NAME);
        FileNetCEOperations fncop = new FileNetCEOperations();

        if (ConfigInfo.USE_EXPLICIT_JAAS_LOGIN) {
            loginAndRun(fncop, ConfigInfo.USERID, ConfigInfo.PASSWORD);
        } else {
            Subject subject = UserContext.createSubject(fncop.conn, ConfigInfo.USERID,
                    ConfigInfo.PASSWORD, ConfigInfo.JAAS_STANZA_NAME);
            UserContext.get().pushSubject(subject);
            try {
                String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date());
                System.out.println("Current and START time :: " + timeStamp);
                System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>  FileNet CE/CPE Operations Begin <<<<<<<<<<<<<<<<<<<<<<<<<");
                System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");

                fncop.DeleteDocsInAFolder("osName", "/foldername");

            } finally {
                UserContext.get().popSubject();
            }
        }
        System.out.println("\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
        String fintimeStamp2 = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date());
        System.out.println("Current and FINISH time :: " + fintimeStamp2);
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>  FileNet CE/CPE Operations End <<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
    }

    public void countobjectsinAllOS() {
        Connection conn = Factory.Connection.getConnection(ConfigInfo.CE_URI);
        Domain domain = Factory.Domain.fetchInstance(conn, null, null);

        Iterator<ObjectStoreSet> it = domain.get_ObjectStores().iterator();

        int countofos = 0;
        while (it.hasNext()) {

            ObjectStore os = (ObjectStore) it.next();
            String osname = os.get_DisplayName();

            System.out.println("Working on Object Store " + osname);
            countofos++;
            countObjectsInAnOS(osname);
        }
        System.out.println("\n\n");
        //System.out.println("Number of Object Stores found in doamin >>\t" + domain.get_Name() + "\t<< is " + countofos);
    }

    public void countObjectsInAnOS(String OSName) {
        Connection conn = Factory.Connection.getConnection(ConfigInfo.CE_URI);
        Domain domain = Factory.Domain.fetchInstance(conn, null, null);
        ObjectStore os = Factory.ObjectStore.fetchInstance(domain, OSName, null);
        // Create a SearchSQL instance and specify the SQL statement (using the
        // helper methods).
        SearchSQL sqlObject = new SearchSQL();
        sqlObject.setSelectList("*");
        //sqlObject.setMaxRecords(10);
        sqlObject.setWhereClause("f.This INSUBFOLDER '/'");
        sqlObject.setFromClauseInitialValue("Folder", "f", false);
        domain.get_ObjectStores();
// Uncomment below lines for Documents   
//    sqlObject.setSelectList("d.DocumentTitle, d.Id");
//    sqlObject.setMaxRecords(20);
//    sqlObject.setFromClauseInitialValue("Document", "d", false); 
        // Check the SQL statement.         

        //Uncomment to see the SQL
        //System.out.println("SQL: " + sqlObject.toString());
        // Create a SearchScope instance. (Assumes you have the object store
        // object.)
        Boolean continuable = new Boolean(true);

        // Set the page size (Long) to use for a page of query result data. This value is passed
        // in the pageSize parameter. If null, this defaults to the value of
        // ServerCacheConfiguration.QueryPageDefaultSize.
        Integer myPageSize = new Integer(10);

        // Specify a property filter to use for the filter parameter, if needed.
        // This can be null if you are not filtering properties.
//        PropertyFilter myFilter = new PropertyFilter();
//        int myFilterLevel = 1;
//        myFilter.setMaxRecursion(myFilterLevel);
//        myFilter.addIncludeType(new FilterElement(null, null, null, FilteredPropertyType.ANY, null));
        // Set the (Boolean) value for the continuable parameter. This indicates
        // whether to iterate requests for subsequent pages of result data when the end of the
        // first page of results is reached. If null or false, only a single page of results is
        // returned.
        // Execute the fetchObjects method using the specified parameters.
        //IndependentObjectSet myObjects = search.fetchObjects(sqlObject, myPageSize, myFilter, continuable);
        SearchScope searchScope = new SearchScope(os);
        RepositoryRowSet rowSet = searchScope.fetchRows(sqlObject, myPageSize, null, continuable);
        long count = 0;
        Iterator<RepositoryRow> it = rowSet.iterator();
        while (it.hasNext()) {
            it.next();
            count++;
        }
//System.out.println("Total number of Documents >>\t\t" + count + "\n\n");
        System.out.println("Total number of Folders >>\t\t" + count + "\n\n");

    }

    public void GetAccessPermissionDesc() {
        Connection conn = Factory.Connection.getConnection(ConfigInfo.CE_URI);
        Domain domain = Factory.Domain.fetchInstance(conn, null, null);
        ObjectStore os = Factory.ObjectStore.fetchInstance(domain, "SomeOS", null);
        String apdClass = ClassNames.FOLDER;
        ClassDescription cd = Factory.ClassDescription.getInstance(os, apdClass);
        cd.fetchProperty(PropertyNames.PERMISSION_DESCRIPTIONS, null);
        AccessPermissionDescriptionList apdl = cd.get_PermissionDescriptions();
        System.out.println(apdClass + " has this many APDs: " + apdl.size());
        for (Iterator it = apdl.iterator(); it.hasNext();) {
            AccessPermissionDescription apd = (AccessPermissionDescription) it.next();
            String dn = apd.get_DisplayName();
            String dt = apd.get_DescriptiveText();
            dt = (dn.equals(dt) ? "" : ": " + dt);
            String pt = apd.get_PermissionType().toString();
            pt += "                     ".substring(pt.length());
            System.out.println(pt + "  " + dn + dt);
        }
    }

    public void setgetPermissionsOnFolders(String osName, String folder) throws IOException {

        try {
            Connection conn = Factory.Connection.getConnection(ConfigInfo.CE_URI);
            Domain domain = Factory.Domain.fetchInstance(conn, null, null);
            ObjectStore os = Factory.ObjectStore.fetchInstance(domain, osName, null);
            //String folder= "/Test";

            com.filenet.api.core.Folder folderOj = Factory.Folder.fetchInstance(os, folder, null);
            System.out.println("Folder :: " + folderOj.get_Name());
            folderOj.refresh();
            // Gets permissions from Loans subclass.
            Properties props = folderOj.getProperties();

            AccessPermissionList apl = folderOj.get_Permissions();
            Iterator ite = apl.iterator();
            while (ite.hasNext()) {
                Properties propss = folderOj.getProperties();
                //String DateCreated = documentProperties.getDateTimeValue("DateCreated").toString();
                //String DateLastModified = documentProperties.getDateTimeValue("DateLastModified").toString();
                Permission permission = (Permission) ite.next();

                System.out.println("Grantee Name :: " + permission.get_GranteeName());
            }

//System.out.println(f.get_Permissions().toString());
            //AccessPermission permission = Factory.AccessPermission.createInstance();
            //System.out.println(apl);
            //System.out.println(permission.get_GranteeName().toString());
//}
            //permission.set_GranteeName("User");
            //permission.set_AccessType(AccessType.ALLOW);
            //permission.set_InheritableDepth(new Integer(-1));
            //permission.set_AccessMask(new Integer(AccessLevel.FULL_CONTROL_FOLDER_AS_INT));
//            The maximum depth to which a permission (ACE) can be inherited. As the ACE gets inherited from a security parent, the value is decremented. Example values are as follows:
//0 - No inheritance (this object only).
//1 - This object and immediate children only.
//-1 - This object and all children (infinite levels deep).
//-2 - All children (infinite levels deep) but not this object.
//-3 - Immediate children only; not this object.
            //AccessPermissionList permissions = folderOj.get_Permissions();
            //permissions.add(permission);
            //folderOj.set_Permissions(permissions);
            //.save(RefreshMode.REFRESH);   
            System.out.println("\nDone");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void createMultipleFolderStructure() {
        Connection conn = Factory.Connection.getConnection(ConfigInfo.CE_URI);
        String parent = "/APITest/folder/test/";
        String level1 = "LevelA";
        String level2 = "LevelB";
        try {
            Domain dom = Factory.Domain.getInstance(conn, null);
            ObjectStore os = Factory.ObjectStore.fetchInstance(dom, "SomeOS", null);
            System.out.println("Object Store =" + os.get_DisplayName());
            //Creating Root folder

            for (int x = 1; x < 10; x++) {
                Folder f = Factory.Folder.createInstance(os, null);
                Folder rootFolder = Factory.Folder.getInstance(os, null, parent);

                //System.out.println("Parent Folder :: " + parent);
                f.set_Parent(rootFolder);
                //System.out.println("Creating folder  " + rootFolder + x);
                f.set_FolderName(level1 + x); //Folder Name
                f.save(RefreshMode.REFRESH);

            }

            Folder fobj = Factory.Folder.fetchInstance(os, parent, null);
            FolderSet fs = fobj.get_SubFolders();
            Iterator sfit = fs.iterator();

            while (sfit.hasNext()) {
                Folder sf = (Folder) sfit.next();
                String name = ((Folder) sf).get_FolderName();
                System.out.println("FolderName  " + name);
                for (int x = 1; x < 5; x++) {
                    Folder f = Factory.Folder.createInstance(os, null);
                    Folder rootFolder2 = Factory.Folder.getInstance(os, null, parent + name);

                    System.out.println("Parent Folder :: " + parent);
                    f.set_Parent(rootFolder2);
                    System.out.println("Creating folder  " + rootFolder2 + x);
                    f.set_FolderName(level2 + x); //Folder Name
                    f.save(RefreshMode.REFRESH);

                }
            }

//     FolderSet fs = f.get_SubFolders();
//     Iterator its = fs.iterator();
//     while (its.hasNext()){
//         for (int y = 1; y < 5; y++) {
//         
//                System.out.println("Printing y  " + y);
//             //Creating Sub folder 
//            Folder sf = f.createSubFolder(level2 + y);
//            sf.save(RefreshMode.REFRESH);
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    public void deleteCEFolder(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 = "/NewFolder";

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

            FolderSet subFolders = folderOj.get_SubFolders();
            Iterator it = subFolders.iterator();
            while (it.hasNext()) {

                com.filenet.api.core.Folder subFolder = (com.filenet.api.core.Folder) it.next();

                String name = ((com.filenet.api.core.Folder) subFolder).get_FolderName();
                System.out.println("Subfolder = " + name);

                //1. First Delete sub folders
                subFolder.delete();
                subFolder.save(RefreshMode.NO_REFRESH);
                System.out.println("Subfolder = " + name + " is Deleted");
            }

            //2. Delete Root folder
            folderOj.delete();
            folderOj.save(RefreshMode.REFRESH);
            System.out.println("Root Folder " + folderOj + "is Deleted");

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

    public void getFolderStructure() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date());
        System.out.println("Start time :: " + timeStamp + "\n");
        String folder = "/AKTest/level1/Test/Tesst";
        Domain dom = Factory.Domain.getInstance(conn, null);
        ObjectStore os = Factory.ObjectStore.getInstance(dom,
                ConfigInfo.OBJECT_STORE_NAME);
        Folder fobj = Factory.Folder.fetchInstance(os, folder, null);
        System.out.println("Parent Folder :: = " + fobj.get_Name());
        FolderSet subFolders = fobj.get_SubFolders();
        Iterator sfit = subFolders.iterator();
        System.out.println("\nDocuments in parent folder...START...\n");
        iterateThruAllDocs(os, folder);
        System.out.println("\nDocuments in parent folder...END...\n");
        System.out.println("\n>>>>>>>>>>>>>>>>          Iterating through Subfolders now          <<<<<<<<<<<<<<<<<<\n");
        while (sfit.hasNext()) {
            Folder subFolder = (Folder) sfit.next();
            String name = ((Folder) subFolder).get_FolderName();
            System.out.println("Folder Name " + name);
            String name2 = folder + "/" + name;
            getChildFolderStructure(os, name2, name2);
            //setgetPermissionsOnFolders("SomeOS", name2);
        }
        String timeStamp2 = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date());
        System.out.println("\nFinish time :: " + timeStamp2);
    }

    public void getChildFolderStructure(ObjectStore os, String currentparent, String childfolder) throws IOException {
        //String folder = "/AKTest";
        Folder fobj = Factory.Folder.fetchInstance(os, childfolder, null);
        //System.out.println("'" + fobj.get_Name() + "'"+ " has a subfolder ");
        FolderSet subFolders = fobj.get_SubFolders();
        Iterator sfit = subFolders.iterator();
        iterateThruAllDocs(os, currentparent);
        while (sfit.hasNext()) {
            Folder subFolder = (Folder) sfit.next();
            String name = ((Folder) subFolder).get_FolderName();
            System.out.println("FolderName  " + name);
            String name2 = currentparent + "/" + name;
            if (subFolder != null) {
                getChildFolderStructure(os, name2, name2);
                setgetPermissionsOnFolders("SomeOS", name2);
            }
        }
    }

    public void iterateThruAllDocs(ObjectStore os, String foldername) {
        Folder folder = Factory.Folder.fetchInstance(os, foldername, null);
        Document doc = Factory.Document.getInstance(os, null, foldername);

        DocumentSet docset = folder.get_ContainedDocuments();
        Iterator<DocumentSet> docitr = docset.iterator();

        while (docitr.hasNext()) {

            doc = (Document) docitr.next();
            String mydocid = doc.get_Id().toString();
            Document mydoc = Factory.Document.fetchInstance(os, mydocid, null);
            AccessPermissionList apl = mydoc.get_Permissions();
            Iterator ite = apl.iterator();
            while (ite.hasNext()) {
                Properties documentProperties = doc.getProperties();
                String DateCreated = documentProperties.getDateTimeValue("DateCreated").toString();
                String DateLastModified = documentProperties.getDateTimeValue("DateLastModified").toString();
                Permission permission = (Permission) ite.next();
                String docTitle = doc.getProperties().getStringValue("DocumentTitle");
                System.out.println("Document Title for document with DocumentID \"" + mydoc.get_Id() + "\" is \"" + docTitle + "\"");
                //String someprop = documentProperties.getStringValue("someprop");
                System.out.println("Document was Created on  :: " + DateCreated);
                System.out.println("Document was Last Modified on :: " + DateLastModified);
                System.out.println("Grantee Name :: " + permission.get_GranteeName());
                //if (permission.get_GranteeName().equals(groupname/username)) {
                //permission.set_GranteeName("groupname/username");
                //  System.out.println("Security REMOVED for document....");
                //mydoc.save(RefreshMode.REFRESH);
                // Go Nuts on Documents Here......
                break;
            }
        }
    }

    public static Folder createFolderStructure() {
        Connection conn = Factory.Connection.getConnection(ConfigInfo.CE_URI);
        Domain dom = Factory.Domain.getInstance(conn, null);
        ObjectStore os = Factory.ObjectStore.getInstance(dom,
                ConfigInfo.OBJECT_STORE_NAME);
        Folder folder = null;
        String folderpath = "APITest/folder/test/Test1/5000/4/2";
        System.out.println("\nGiven input folder path is :: " + folderpath + "\n");
        String[] myarray = folderpath.split("/");
        for (int x = 0; x < myarray.length; x++) {

            try {
                if (x == 0) {
                    folder = Factory.Folder.createInstance(os, null);
                    Folder rootFolder = Factory.Folder.getInstance(os, null, "/");
                    folder.set_Parent(rootFolder);
                    folder.set_FolderName(myarray[x]);
                    System.out.println("Creating main (first) folder.. \t" + myarray[x]);
                    folder.save(RefreshMode.NO_REFRESH);

                } else {
                    String currentfolder = myarray[x];
                    String parentfolder = "";
                    for (int i = 0; i < x; i++) {
                        folder = Factory.Folder.createInstance(os, null);
                        parentfolder = parentfolder + "/" + myarray[i];
                        Folder nxtrootFolder = Factory.Folder.getInstance(os, null, parentfolder);
                        folder.set_Parent(nxtrootFolder);
                        folder.set_FolderName(currentfolder);
                    }
                    System.out
                            .println("Trying to create " + currentfolder + " in " + parentfolder);

                    folder.save(RefreshMode.NO_REFRESH);
                }

            } catch (EngineRuntimeException ere) {
                ExceptionCode code = ere.getExceptionCode();
                if (code != ExceptionCode.E_NOT_UNIQUE) {
                    throw ere;
                }
                System.out.println("Above folder already exists...skipping...");
            }

        }
        return folder;
    }

    public static Folder DeleteFolderStructure() {
        Connection conn = Factory.Connection.getConnection(ConfigInfo.CE_URI);
        Domain dom = Factory.Domain.getInstance(conn, null);
        ObjectStore os = Factory.ObjectStore.getInstance(dom,
                ConfigInfo.OBJECT_STORE_NAME);
        Folder folder = null;
        String filepath = "APITest/folder/test/Test1/5000/4/2";
        String filepath1 = filepath.replace('\\', '/');
        System.out.println(filepath1);
        String[] myarray = filepath1.split("/");
        for (int x = 0; x < myarray.length; x++) {
            System.out.println(myarray[x]);
        }
        for (int x = 0; x < myarray.length; x++) {

            try {
                if (x == 0) {
                    folder = Factory.Folder.createInstance(os, null);
                    Folder rootFolder = Factory.Folder.getInstance(os, null, "/");
                    folder.set_Parent(rootFolder);
                    folder.set_FolderName(myarray[x]);
                    System.out.println("Creating main (first) folder.. \t" + myarray[x]);
                    folder.save(RefreshMode.NO_REFRESH);

                } else {
                    String currentfolder = myarray[x];
                    String parentfolder = "";
                    for (int i = 0; i < x; i++) {
                        folder = Factory.Folder.createInstance(os, null);
                        parentfolder = parentfolder + "/" + myarray[i];
                        Folder nxtrootFolder = Factory.Folder.getInstance(os, null, parentfolder);
                        folder.set_Parent(nxtrootFolder);
                        folder.set_FolderName(currentfolder);
                        // System.out.println(parentfolder + " 2");
                    }
                    System.out
                            .println("Trying to create >> " + currentfolder + " << in \t\t>> " + parentfolder + " <<");

                    folder.save(RefreshMode.NO_REFRESH);
                }

            } catch (EngineRuntimeException ere) {
                ExceptionCode code = ere.getExceptionCode();
                if (code != ExceptionCode.E_NOT_UNIQUE) {
                    throw ere;
                }
                System.out.println("Above folder already exist...skipping...");
            }

        }
        return folder;
    }

    public void createAndFileDocument() throws FileNotFoundException {
        Domain dom = Factory.Domain.getInstance(conn, null);
        ObjectStore os = Factory.ObjectStore.getInstance(dom,
                ConfigInfo.OBJECT_STORE_NAME);
        String folderName = "/" + ConfigInfo.FOLDER_NAME;
        Folder folder = Factory.Folder.fetchInstance(os, folderName, null);
        String fileName = ConfigInfo.LOCAL_FILE_NAME;
        System.out.println("Reading input file..");
        File myfile = new File(fileName);
        InputStream file = new FileInputStream(myfile);
        ContentElementList cel = Factory.ContentElement.createList();
        String docClass = null;
        Document doc = Factory.Document.createInstance(os, docClass);
        if (myfile.exists()) {
            ContentTransfer contentTransfer = Factory.ContentTransfer.createInstance();
            contentTransfer.setCaptureSource(file);
            cel.add(contentTransfer);
            System.out.println("Setting CEL to document ..");
            doc.set_ContentElements(cel);
            contentTransfer.set_RetrievalName(fileName);
        }
        doc.checkin(AutoClassify.DO_NOT_AUTO_CLASSIFY, CheckinType.MAJOR_VERSION);
        Properties p = doc.getProperties();
        System.out.println("Setting document properties..like document title etc...");
        p.putValue("DocumentTitle", "abcd");
        doc.save(RefreshMode.REFRESH);
        DynamicReferentialContainmentRelationship rcr
                = Factory.DynamicReferentialContainmentRelationship.createInstance(os, null,
                        AutoUniqueName.AUTO_UNIQUE,
                        DefineSecurityParentage.DO_NOT_DEFINE_SECURITY_PARENTAGE);
        rcr.set_Tail(folder);
        rcr.set_Head(doc);
        rcr.set_ContainmentName(ConfigInfo.CONTAINMENT_NAME);
        rcr.save(RefreshMode.REFRESH);
        System.out.println("Document saved in the folder ..  " + ConfigInfo.FOLDER_NAME);
        //Below is a transactional operation: all calls in the batch succeed or fail as a unit.
        //In the event of a failure, the transaction is rolled back and an exception is thrown.
        UpdatingBatch ub = UpdatingBatch.createUpdatingBatchInstance(dom,
                RefreshMode.NO_REFRESH);
        ub.add(doc, null);
        ub.add(rcr, null);
        ub.updateBatch();
        System.out.println("Done updates via UpdatingBatch for document \t\t" + doc.get_Id());
    }

    public void downloadDOCStoLocal() {
        Domain dom = Factory.Domain.getInstance(conn, null);
        ObjectStore os = Factory.ObjectStore.getInstance(dom, ConfigInfo.OBJECT_STORE_NAME);
        System.out.println("Selected Object Store ::\t\t" + ConfigInfo.OBJECT_STORE_NAME);
        Folder folder = Factory.Folder.fetchInstance(os, "/APITest", null);
        System.out.println("Selected Folder from Object Store ::\t\t" + folder.get_FolderName());
        DocumentSet document_set = folder.get_ContainedDocuments();
        long i = 1;
        Iterator<DocumentSet> doc_iterator = document_set.iterator();
        while (doc_iterator.hasNext()) {
            Document doc = (Document) doc_iterator.next();
            try {
                System.out.println("Currently Downloading Document #  " + i + " with DOC ID ::\t\t" + doc.get_Id());
                FileOutputStream fos = new FileOutputStream("C:\\apitest\\dwld\\" + doc.get_Id());
                Document mydoc = Factory.Document.fetchInstance(os, doc.get_Id(), null);
                ContentElementList cel = mydoc.get_ContentElements();
                Iterator ite = cel.iterator();
                while (ite.hasNext()) {
                    ContentTransfer ct = (ContentTransfer) ite.next();
                    InputStream is = ct.accessContentStream();
                    int data_length = ct.get_ContentSize().intValue();
                    byte buff[] = new byte[data_length];
                    try {
                        is.read(buff);
                        fos.write(buff);
                    } catch (Exception e) {
                        System.out.println("" + e.getLocalizedMessage());
                    }
                }
                i++;
            } catch (Exception e) {
                System.out.println("Error...!!!" + e.getLocalizedMessage());
            }
        }
        System.out.println("Operation completed");
    }

    public void classesList() {
        Domain dom = Factory.Domain.getInstance(conn, null);
        ObjectStore os = Factory.ObjectStore.getInstance(dom,
                ConfigInfo.OBJECT_STORE_NAME);
        SearchScope scope = new SearchScope(os);
        SearchSQL sql = new SearchSQL("SELECT * FROM ClassDefinition");
        EngineCollection coll = scope.fetchObjects(sql, null, null, false);
        Iterator<?> it = coll.iterator();
        while (it.hasNext()) {
            ClassDefinition def = (ClassDefinition) it.next();
            String cdName = def.get_SymbolicName();
            System.out.println(cdName);
            ClassDefinition cls = Factory.ClassDefinition.fetchInstance(os, cdName, null);
            PropertyDefinitionList pdefLst = cls.get_PropertyDefinitions();
            Iterator<?> pdefitr = pdefLst.iterator();
            while (pdefitr.hasNext()) {
                PropertyDefinition prop = (PropertyDefinition) pdefitr.next();
                String myprop = prop.get_DisplayName();
                System.out.println("\t" + myprop + "  >>  " + prop.get_DataType());
                ClassDescription cdesc = prop.get_ClassDescription();
                PropertyDescriptionList pdl = cdesc.get_PropertyDescriptions();
                PropertyDescription pd;
                Iterator pdescitr = pdl.iterator();
                while (pdescitr.hasNext()) {
                    pd = (PropertyDescription) pdescitr.next();
                    System.out.println("\t\tProperty name >> " + pd.get_SymbolicName());
                    System.out.println("\t\tHidden? >> " + pd.get_IsHidden());
                    System.out.println("\t\tOrderable? >> " + pd.get_IsOrderable());
                    System.out.println("\t\tRead only? >> " + pd.get_IsReadOnly().toString());
                    System.out.println("\t\tSettable? >> " + pd.get_Settability());
                    System.out.println("\t\tCardinality >> " + pd.get_Cardinality());
                    System.out.println("\t\tSearchable? >> " + pd.get_IsSearchable());
                    System.out.println("\t\tSystem owned? >> " + pd.get_IsSystemOwned());
                    System.out.println("\t\tProperty name >> " + pd.get_SymbolicName());
                    System.out.println("\t\tValue of Property >> " + pd.get_Settability());
                    System.out.println("\t\tSystem Generated? >> " + pd.get_IsSystemGenerated());
                    System.out.println("\t\tIs Value Required? >> " + pd.get_IsValueRequired());
                    System.out.println("\t\tID >> " + pd.get_Id());
                }
            }
            System.out.println("\n");
        }
    }

    public void getDocumentClassProperties() throws Exception {
        Domain dom = Factory.Domain.getInstance(conn, null);
        ObjectStore os = Factory.ObjectStore.getInstance(dom,
                ConfigInfo.OBJECT_STORE_NAME);
        String strClassDescSymbolicName = "Test";
        String strPropDescSymbolicName;
        PropertyFilter pf = new PropertyFilter();
        pf.addIncludeType(0, null, Boolean.TRUE, FilteredPropertyType.ANY, null);
        ClassDescription objClassDesc = Factory.ClassDescription.fetchInstance(os, strClassDescSymbolicName, pf);
        PropertyDescriptionList pdl = objClassDesc.get_PropertyDescriptions();
        Iterator pdescitr = pdl.iterator();
        PropertyDescription pd = null;
        while (pdescitr.hasNext()) {
            pd = (PropertyDescription) pdescitr.next();
            //System.out.println("Parent >>>>>>>>>>   " + objClassDesc.get_SymbolicName());
            System.out.println("Property description selected: " + pd.get_SymbolicName());
            System.out.println("\t\tProperty name >> " + pd.get_SymbolicName());
            System.out.println("\t\tHidden? >> " + pd.get_IsHidden());
            System.out.println("\t\tOrderable? >> " + pd.get_IsOrderable());
            System.out.println("\t\tRead only? >> " + pd.get_IsReadOnly().toString());
            System.out.println("\t\tSettable? >> " + pd.get_Settability());
            System.out.println("\t\tCardinality >> " + pd.get_Cardinality());
            System.out.println("\t\tSearchable? >> " + pd.get_IsSearchable());
            System.out.println("\t\tSystem owned? >> " + pd.get_IsSystemOwned());
            System.out.println("\t\tProperty name >> " + pd.get_SymbolicName());
            System.out.println("\t\tValue of Property >> " + pd.get_Settability());
            System.out.println("\t\tSystem Generated? >> " + pd.get_IsSystemGenerated());
            System.out.println("\t\tIs Value Required? >> " + pd.get_IsValueRequired());
            System.out.println("\t\tID >> " + pd.get_Id());
            //break;
            System.out.println("\n");
        }

    }

    public void writetoCSV(String myid, String mytitle, String mycrtdate, String mylmydocfncopdate) throws FileNotFoundException {
        try (PrintWriter pw = new PrintWriter(new File("c:/myoutput.csv"))) {
            StringBuilder sb = new StringBuilder();
            sb.append(myid);
            sb.append(',');
            sb.append(mytitle);
            sb.append(',');
            sb.append(mycrtdate);
            sb.append(',');
            sb.append(mylmydocfncopdate);
            sb.append('\n');

            pw.write(sb.toString());
        }
        System.out.println("CSV write successful...!");
    }

    public void DeleteDocsInAFolder(String osName, String foldername) {
        Domain domain = Factory.Domain.fetchInstance(conn, null, null);
        ObjectStore objStore = Factory.ObjectStore.fetchInstance(domain, osName, null);
        Folder folder = Factory.Folder.fetchInstance(objStore, foldername, null);
        Document doc = Factory.Document.getInstance(objStore, null, foldername);
        DocumentSet docset = folder.get_ContainedDocuments();
        Iterator<DocumentSet> docitr = docset.iterator();
        long i = 1;
        while (docitr.hasNext()) {
            doc = (Document) docitr.next();
            Properties documentProperties = doc.getProperties();
            String docTitle = documentProperties.getStringValue("DocumentTitle");
            System.out.println("Deleting Document number # " + i + "\t" + docTitle);

            doc.delete();
            doc.save(RefreshMode.REFRESH);
            i++;
        }
    }

    public void FetchNDeleteCEDocs(String osName) {

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

            SearchScope search = new SearchScope(objStore);
            String sql1 = "Select * from DocClassName where someIndex=123456";
            SearchSQL searchSQL = new SearchSQL(sql1);
            DocumentSet documents = (DocumentSet) search.fetchObjects(searchSQL, Integer.valueOf("20"), null, Boolean.valueOf(true));

            //Without Paging Concept
            Document doc;
            Iterator DocIt = documents.iterator();
            while (DocIt.hasNext()) {
                doc = (Document) DocIt.next();
                System.out.println("888       888                           d8b                   \n"
                        + "888   o   888                           Y8P                   \n"
                        + "888  d8b  888                                                 \n"
                        + "888 d888b 888  8888b.  888d888 88888b.  888 88888b.   .d88b.  \n"
                        + "888d88888b888     \"88b 888P\"   888 \"88b 888 888 \"88b d88P\"88b \n"
                        + "88888P Y88888 .d888888 888     888  888 888 888  888 888  888 \n"
                        + "8888P   Y8888 888  888 888     888  888 888 888  888 Y88b 888 \n"
                        + "888P     Y888 \"Y888888 888     888  888 888 888  888  \"Y88888 \n"
                        + "                                                          888 \n"
                        + "                                                     Y8b d88P \n"
                        + "                                                      \"Y88P\"  ");
                System.out.println("\nGoing to Delete the Document with Title >>>>>>>>>>>>>>>\t" + doc.get_Name() + "\t<<<<<<<<<<<<<<<<<<\n");
                System.out.println("======================================================================================================\n");
                System.out.println("Add the below lines to Proceed...!!\ndoc.delete(); \ndoc.save(RefreshMode.REFRESH);");

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

    }

    public void FetchCEObjectsInFolder() {  //FileNet CE Connection

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

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

            com.filenet.api.core.Folder folderOj = Factory.Folder.fetchInstance(objStore, folder, null);
            System.out.println("Folder Name   " + 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 all the Objects under the folder
                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) {
        }
    }

    public void setAccessRights(
            Domain domain,
            String granteeName, // Example: "CEMPAdmin"
            String objStoreName) // Example: "ObjectStore1"
    {

        final int ACCESS_REQUIRED = AccessRight.WRITE_ANY_OWNER.getValue()
                | AccessRight.REMOVE_OBJECTS.getValue() | AccessRight.STORE_OBJECTS.getValue()
                | AccessRight.CONNECT.getValue() | AccessRight.WRITE_ACL.getValue()
                | AccessRight.READ_ACL.getValue() | AccessRight.MODIFY_OBJECTS.getValue();

        // Create a new access permission object.
        AccessPermission ap = Factory.AccessPermission.createInstance();

        // Set access permissions. 
        ap.set_GranteeName(granteeName);
        ap.set_AccessType(AccessType.ALLOW);
        ap.set_AccessMask(ACCESS_REQUIRED);

        // Set and save the new permissions.
        ObjectStore objStore = Factory.ObjectStore.fetchInstance(domain, objStoreName, null);
        AccessPermissionList apl = objStore.get_Permissions();
        apl.add(ap);
        objStore.set_Permissions(apl);
        objStore.save(RefreshMode.REFRESH);
        //System.out.println(objStore.get_ClassDescriptions());
        //System.out.println(objStore.getProperties());
    }

    private static void loginAndRun(FileNetCEOperations fncop, String userid,
            String password) throws LoginException {
        LoginContext lc = new LoginContext(ConfigInfo.JAAS_STANZA_NAME,
                new FileNetCEOperations.CallbackHandler(userid, password));
        lc.login();
    }

    private static final class CallbackHandler
            implements javax.security.auth.callback.CallbackHandler {

        private final String userid;
        private final String password;

        public CallbackHandler(String userid, String password) {
            this.userid = userid;
            this.password = password;
        }

        @Override
        public void handle(Callback[] callbacks) throws UnsupportedCallbackException {
            for (Callback callback : callbacks) {
                if (callback instanceof TextOutputCallback) {
                    //TextOutputCallback toc = (TextOutputCallback)callbacks[i];
                    //System.err.println("JAAS callback: " + toc.getMessage());
                } else if (callback instanceof NameCallback) {
                    NameCallback nc = (NameCallback) callback;
                    nc.setName(userid);
                } else if (callback instanceof PasswordCallback) {
                    PasswordCallback pc = (PasswordCallback) callback;
                    pc.setPassword(password.toCharArray());
                } else {
                    throw new UnsupportedCallbackException(callback, "Unrecognized Callback");
                }
            }
        }
    }
}