persistenceexample4/datafactory/ReadWriteEntities.java


package persistenceexample4.datafactory;

import java.util.Vector;

import com.sap.ip.me.api.conf.VisibilityType;
import com.sap.ip.me.api.persist.app.PersistableEntity;
import com.sap.ip.me.api.persist.core.PersistenceException;
import com.sap.ip.me.api.persist.core.PersistenceManager;
import com.sap.ip.me.api.persist.core.PersistenceRuntime;
import com.sap.ip.me.api.persist.core.TreeOptionType;
import com.sap.ip.me.api.persist.query.Condition;
import com.sap.ip.me.api.persist.query.LogicalOperatorType;
import com.sap.ip.me.api.persist.query.Query;
import com.sap.ip.me.api.persist.query.QueryRuntime;
import com.sap.ip.me.api.persist.query.RelationalOperatorType;
import com.sap.ip.me.api.persist.query.SortOrder;
import com.sap.ip.me.api.services.MeIterator;

/*
 *  Methods to read, write and delete entities
 *  using the persistence API
 */

public class ReadWriteEntities implements persistenceexample4.Constants {

    private static PersistenceRuntime persistence;
    private static PersistenceManager perManager;
    private static ExamplePackagePersistenceMaster master;
    private static int idCount;
    private static int currentIndex;
    private static int persistedEntityCount;

    /*
     *  Setup persistence runtime - create a transaction manager object. A transaction manager object
     *  is necessary for every action (write, read, delete) you perform. The transaction manager can
     *  be SHARED (= having access to all data on the device) or SEPARATED, like in this example 
     *  (= having access only to the user data).
     */

    public static void setupPersistenceRuntime() {
        try {
            persistence = PersistenceRuntime.getInstance();
            master = new ExamplePackagePersistenceMaster();
            persistence.registerPersistenceMaster(master);
            perManager = persistence.getPersistenceManager(VisibilityType.SEPARATED);
            perManager.registerEntityFactory(master);
            perManager.beginTransaction(true);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Error during startup");
            System.exit(-1);
        }
    }

    /*
     * Create Car entity with given ID
     */

    public static PersistableEntity createCarEntity(String name) {
        PersistableEntity car = new Car(perManager.getPersistedObjectFactory().createPersistedObject(ExamplePackagePersistenceMaster.P_CLASS_CAR, name));
        return car;
    }

    /*
     * Create License entity with given ID
     */

    public static PersistableEntity createLicenseEntity(String number) {
        PersistableEntity license = new License(perManager.getPersistedObjectFactory().createPersistedObject(ExamplePackagePersistenceMaster.P_CLASS_LICENSE, number));
        return license;
    }

    /*
     * Combine Car and Licence object
     */
    public static void combineCarLicense(PersistableEntity car, PersistableEntity license) {
        License l = (License) license;
        Car c = (Car) car;
        c.setLicense(l);
    }

    public static void setCarAttributes(PersistableEntity car, String make, String model, String engine, int cyl, int valves) {
        Car c = (Car) car;
        c.setValues(make, model, engine, cyl, valves);
    }

    /*
     * Write entity object. If the object already exists it will be replaced. The .commit method
     * submits the request and stores the entry persistent.
     * The TreeOptionType.COMPLETE defines that the entity itself and all associated entities 
     * (in this example it is one associated entity = License) are written.
     */

    public static void writeEntity(PersistableEntity obj) {
        if (obj != null) {
            PersistenceException e = null;
            try {
                // UPDATE performs an INSERT when entity does not exist or a MODIFY when entity exists (see comment below)
                perManager.update(obj, TreeOptionType.COMPLETE);

                /* The UPDATE method is equivalent to following coding
                            if (!trxManager.contains(obj.getEntityKey())) {
                                trxManager.insert(obj, TreeOptionType.COMPLETE);
                            } else { 
                                 trxManager.modify(obj, TreeOptionType.COMPLETE);
                            }  */
                /////                perManager.commit();
            } catch (PersistenceException e1) {
                e = e1;
                e1.printStackTrace();
            }
        }
    }
    /**
     * Method addEntity.- adds a new entry
     */

    public static void addEntity(String make, String model, String engine, String cylinders, String valves, String lic) {
        PersistableEntity ecar = null;
        PersistableEntity elic = null;
        if (make.length() > 0) {
            ecar = createCarEntity(Integer.toString(idCount));
            idCount++;
        }
        if (lic.length() > 0) {
            elic = createLicenseEntity(lic);
        }

        // if car and licence have been entered combine the two
        if ((elic != null) && (ecar != null)) {
            combineCarLicense(ecar, elic);
        }
        // Set attributes of car
        int cyl = Integer.parseInt(cylinders);
        int val = Integer.parseInt(valves);
        setCarAttributes(ecar, make, model, engine, cyl, val);

        // store data
        writeEntity(ecar);
        writeEntity(elic);
    }
    /**
     * Method readEntity  - reads all persisted entities from a special character
     * @param all - retVector = ?, index = ?, sortIndex = ?, sort_ascending = ?,
     * obj = array with wanted characters
     * @return Vector - special entities
     */
    public static MeIterator readEntity(int index, int sortIndex, boolean sort_ascending, String[] filter) {
        // Declaration variables
        //        Vector found_entities = null;
        int count = 0;
        MeIterator entities = null;
        try {
            // Persistence Manager not initialized
            if (perManager == null) {
                System.out.println(" trxmanager is null");
            } else {
                QueryRuntime queryRuntime = QueryRuntime.getInstance();
                SortOrder sortOrder = null;
                SortOrder[] sortOrderMake = new SortOrder[2];
                Condition cond = null;
                Query query = null;

                // Set up a sort order. We use the Make and Model column to be sorted and combine the two columns
                sortOrderMake[0] = queryRuntime.createSortOrder(ExamplePackagePersistenceMaster.CAR_ATTRIBS[sortIndex], sort_ascending);
                sortOrderMake[1] = queryRuntime.createSortOrder(ExamplePackagePersistenceMaster.CAR_ATTRIBS[sortIndex + 1], true);
                sortOrder = queryRuntime.createSortOrder(sortOrderMake);

                // Execute query with sort order.
                // Set up a condition. Index is the index to the attributes (like make, model etc.) you want to query
                // and the String obj is the string we are looking for.
                // In this example we use the operation EQUALS on the condition. You can use any other or change this method
                // to pass the condition as parameter.
                if (index < 0) {
                    // if index is less then 0 we read all Car objects. We want the output sorted (either by make or license #)
                    // To do that we set up a query that will always match all entries stored (number of cylinders greater 0) and
                    // use parameter sort_ascending to represent the data ascending (sort_ascending = true) or descending
                    // (sort_ascending = false)
                    cond = queryRuntime.createCondition(ExamplePackagePersistenceMaster.CAR_ATTRIBS[0], RelationalOperatorType.GREATER_THAN, "");

                } else {
                    Condition[] filterCond = new Condition[filter.length];
                    for (int i = 0; i < filter.length; i++) {
                        // Set up a condition. Index is the index to the attributes (like make, model etc.) you want to query
                        // and the String obj is the string we are looking for.
                        // In this example we use the operation EQUALS on the condition. You can use any other or change this method
                        // to pass the condition as parameter.
                        filterCond[i] = queryRuntime.createCondition(ExamplePackagePersistenceMaster.CAR_ATTRIBS[index - 1], RelationalOperatorType.STARTS_WITH, filter[i]);
                    }
                    cond = queryRuntime.createCondition(filterCond, LogicalOperatorType.OR);
                }
                // four current characters
                query = queryRuntime.createQuery(ExamplePackagePersistenceMaster.CLASSTYPES[0], cond, sortOrder);

                // database comando
                entities = perManager.get(query);

                // Read Car objects
                while (entities.hasNext()) {
                    // Cast to Car object and get entities
                    Car entity = (Car) entities.next();
                    /*                        found_entities = new Vector();
                                            found_entities.addElement(entity.toString());
                                            found_entities.addElement(entity.makeToString());
                                            found_entities.addElement(entity.modelToString());
                                            found_entities.addElement(entity.licToString());
                                            found_entities.addElement(entity.engineToString());
                                            found_entities.addElement(entity.cylToString());
                                            found_entities.addElement(entity.valveToString());
                                            // We leave some test writes in to see it on the console
                                            System.err.println("got car: " + entity.toString() + " : " + entity.makeToString());
                                            retVector.add(found_entities); */
                    count++;
                }

                setPersistedEntityCount(count);
            }
        } catch (PersistenceException e) {
            e.printStackTrace();
        }
        return entities;
    }
    /*
     *  Delete a entity with give ID. To delete an entry we have to create a transaction manager
     *  instance with TransactionType.WRITE to have write access.
     *
     *  If you delete a License entity the related Car entity is deleted as well.
     * 
     *  The ,commit method deletes the entry physically.
     */
    public static void deleteEntity(String obj) {
        if (obj != null) {
            PersistenceException e = null;
            try {
                // deprecated            trxManager.delete(obj, TreeOptionType.COMPLETE);
                PersistableEntity toDel = perManager.get(master.getClassDescriptor(Car.CLASSTYPE), obj);
                perManager.delete(toDel, TreeOptionType.COMPLETE);
                //                perManager.commit();
            } catch (PersistenceException e1) {
                e = e1;
                e1.printStackTrace();
            }
        }
    }

    /**
         * Method commit 
         * Store entries
         */
    public static void commit() {
        try {
            perManager.commit();
        } catch (PersistenceException e) {
            System.out.println("Data can not be stored");
            e.printStackTrace();
        }
    }
    /**
     * Method writeExampleEntries. 
     * This method is to fill the persistence layer with some demo entries, so that we do not display
     * an empty table on first start. If the entries already exist, they are updated - this will be
     * on subsequent calls of the example
     */
    public static void writeExampleEntries() {
        /* First we check if there are already entries (in case the example have been already started once. 
         * If there are we do not add the example entries        */
        int count = numberOfEntries();

        if (count == 0) {
            idCount = 0;
            addEntity("BMW", "540", "Gasoline", "8", "2", "HD-JD1234");
            addEntity("BMW", "320", "Gasoline", "6", "2", "HD-JM2345");
            addEntity("VW", "Passat", "Diesel", "4", "2", "");
            addEntity("Opel", "Vectra", "Diesel", "4", "4", "HD-JL3456");
            addEntity("Toyota", "Camry", "Diesel", "4", "2", "BRA-XX456");
            addEntity("Mazda", "6", "Gasoline", "4", "2", "SFA-BA456");
            addEntity("Renault", "Megane", "Diesel", "4", "2", "F-ME1256");
            addEntity("Renault", "Scenic", "Gasoline", "4", "2", "F-SC 5478");
            addEntity("Ford", "Mondeo", "Gasoline", "6", "2", "K-MO 1239");
            addEntity("Peugeot", "307", "Gasoline", "4", "2", "AA-X 139");
        }
    }

    /**
     * Method numberOfEntries.
     * @return int - number of records in data base
     */
    private static int numberOfEntries() {
        idCount = -1;
        int count = 0;
        try {
            MeIterator entities = perManager.getAll(master.getClassDescriptor(Car.CLASSTYPE));
            while (entities.hasNext()) {
                count++;
                Car entity = (Car) entities.next();
                int id = Integer.parseInt(entity.toString());
                // find highest id number
                if (id > idCount)
                    idCount = id;
            }
            // Set counter one up for new entity
            idCount++;
        } catch (PersistenceException e) {
        }
        return count;
    }
    /**
     * @return the elements in the entities
     */
    public static int getPersistedEntityCount() {
        return persistedEntityCount;
    }

    /**
     * @param i sets the number of elements in the persisted entities
     */
    public static void setPersistedEntityCount(int i) {
        persistedEntityCount = i;
    }

    //creates  a subarray of the full dataset defined by a start index and the number of rows
    //The result is returned and also kept locally as retSubVec to be retrieved by the bean
    public static Vector getEntities(MeIterator persistenceEntities, int fromIndex, int count) {
        int recCount = count;
        int start_index = fromIndex;

        Vector retSubVec = new Vector();
        Vector found_entities = null;
        int i = 0;
        persistenceEntities.reset();
        // Read Car objects
        while (persistenceEntities.hasNext()) {
            // Cast to Car object and get entities
            Car entity = (Car) persistenceEntities.next();
            if (i >= fromIndex) {
                found_entities = new Vector();
                found_entities.addElement(entity.toString());
                found_entities.addElement(entity.makeToString());
                found_entities.addElement(entity.modelToString());
                found_entities.addElement(entity.licToString());
                found_entities.addElement(entity.engineToString());
                found_entities.addElement(entity.cylToString());
                found_entities.addElement(entity.valveToString());
                // We leave some test writes in to see it on the console
                System.err.println("got car: " + entity.toString() + " : " + entity.makeToString());
                retSubVec.addElement(found_entities);
            }
            i++;
            //return when count has been reached            
            if (i >= (fromIndex + count))
                return retSubVec;
        }

        //return - there are less than required data in the Vector
        return retSubVec;
    }

    public static int getEntity(MeIterator persistenceEntities, String id, int prev) {
        Car entity = null;
        String prevId = null;
        currentIndex = -1;
        persistenceEntities.reset();
        // Read Car objects
        while (persistenceEntities.hasNext()) {
            currentIndex++;
            // Cast to Car object and get entities
            entity = (Car) persistenceEntities.next();
            if (entity != null) {
                if (entity.toString().compareTo(id) == 0) {
                    if (prev == 0) {
                        return currentIndex;
                    }
                    // take prev entry
                    if (prev == -1) {
                        if (prevId != null) {
                            currentIndex--;
                            return currentIndex;
                        } else {
                            return currentIndex;
                        }
                    }
                    // take next entry
                    if (prev == 1) {

                        if (persistenceEntities.hasNext()) {
                            currentIndex++;
                            return currentIndex;
                        } else {
                            return currentIndex;
                        }
                    }
                }
                prevId = entity.toString();
            }
        }
        return currentIndex;

    }

    public static int getCurrentIndex() {
        return currentIndex;
    }
}