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.meta.AttributeDescriptor;
import com.sap.ip.me.api.persist.meta.ClassDescriptor;
import com.sap.ip.me.api.persist.query.Condition;
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;

    /*
     *  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
     * @param all - boolean values that control if Car and License objects or only Car objects are read
     * @return String[] - entities as string
     */

    public static Vector readEntity(Vector retVector, int index, int sortIndex, boolean sort_ascending, String obj, boolean all) {

        Vector found_entities = null;
        int count = 0;
        PersistenceException e = null;
        try {
            if (perManager == null) {
                System.out.println(" perManager is null");
            } else {
                MeIterator entities = null;
                QueryRuntime queryRuntime = QueryRuntime.getInstance();
                SortOrder sortOrder = null;
                SortOrder[] sortOrderMake = new SortOrder[2];
                Condition cond = null;
                Query query = null;
                ClassDescriptor cdes = master.getClassDescriptor(Car.CLASSTYPE);
                AttributeDescriptor attDesc = cdes.getAttributeDescriptor(0);
                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(attDesc, RelationalOperatorType.GREATER_THAN, "");

                } else {
                    // 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.
                    cond = queryRuntime.createCondition(attDesc, RelationalOperatorType.STARTS_WITH, obj);
                }

                // 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.
                query = queryRuntime.createQuery(cdes.getClasstype(), cond, sortOrder);
                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());
                    count++;
                    retVector.addElement(found_entities);
                }

                if (all == true) {

                    // Read License objects, if Full List is wanted. This path displays only the license objects.
                    // For a better view in the JSP we set the row 0 (usually contains the Car entities) to a non breaking
                    // space, so the table in the browser is correctly displayed.
                    entities = perManager.getAll(ExamplePackagePersistenceMaster.P_CLASS_LICENSE);
                    while (entities.hasNext()) {
                        License entity = (License) entities.next();
                        System.err.println("got license: " + entity);
                        found_entities = new Vector();
                        found_entities.addElement(BLANK_VALUE);
                        found_entities.addElement(BLANK_VALUE);
                        found_entities.addElement(BLANK_VALUE);
                        found_entities.addElement(BLANK_VALUE);
                        found_entities.addElement(BLANK_VALUE);
                        found_entities.addElement(BLANK_VALUE);
                        found_entities.addElement(entity.toString());
                        count++;
                        retVector.addElement(found_entities);
                    }
                }
            }
        } catch (PersistenceException e1) {
            e = e1;
            e.printStackTrace();
        }
        return retVector;
    }

    /*
     *  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();
        }
        try {
            // after commit a new persistence manager has to be set up 
            perManager = persistence.getPersistenceManager(VisibilityType.SEPARATED);
            perManager.registerEntityFactory(master);
            perManager.beginTransaction(true);
        } catch (PersistenceException e1) {
            System.out.println("Persistence Manager cannot be started");
            e1.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;
    }
}