5. Collections and Arrays


We will slowly move towards real-time data processing now by installing sensors to our car and collecting their output.


package com.db4o.f1.chapter3;

import java.util.*;

public class SensorReadout {
    private double[] values;
    private Date time;
    private Car car;

    public SensorReadout(double[] values,Date time,Car car) {
        this.values=values;
        this.time=time;
        this.car=car;
    }

    public Car getCar() {
        return car;
    }

    public Date getTime() {
        return time;
    }

    public int getNumValues() {
        return values.length;
    }
    
    public double getValue(int idx) {
        return values[idx];
    }

    public String toString() {
        StringBuffer str=new StringBuffer();
        str.append(car.toString())
         .append(" : ")
         .append(time.getTime())
         .append(" : ");
        for(int idx=0;idx<values.length;idx++) {
            if(idx>0) {
                str.append(',');
            }
            str.append(values[idx]);
        }
        return str.toString();
    }
}


A car may produce its current sensor readout when requested and keep a list of readouts collected during a race.


package com.db4o.f1.chapter3;

import java.util.*;

public class Car {
    private String model;
    private Pilot pilot;
    private List history;

    public Car(String model) {
        this(model,new ArrayList());
    }

    public Car(String model,List history) {
        this.model=model;
        this.pilot=null;
        this.history=history;
    }

    public Pilot getPilot() {
        return pilot;
    }

    public void setPilot(Pilot pilot) {
        this.pilot=pilot;
    }

    public String getModel() {
        return model;
    }

    public SensorReadout[] getHistory() {
        return (SensorReadout[])history.toArray(
                new SensorReadout[history.size()]);
    }
    
    public void snapshot() {
        history.add(new SensorReadout(poll(),new Date(),this));
    }
    
    protected double[] poll() {
        int factor=history.size()+1;
        return new double[]{0.1d*factor,0.2d*factor,0.3d*factor};
    }
    
    public String toString() {
        return model+"["+pilot+"]/"+history.size();
    }
}


We will constrain ourselves to rather static data at the moment and add flexibility during the next chapters.


    5.1. Storing


    This should be familiar by now.


    Car car1=new Car("Ferrari");
    Pilot pilot1=new Pilot("Michael Schumacher",100);
    car1.setPilot(pilot1);
    db.set(car1);
        


    The second car will take two snapshots immediately at startup.


    Pilot pilot2=new Pilot("Rubens Barrichello",99);
    Car car2=new Car("BMW");
    car2.setPilot(pilot2);
    car2.snapshot();
    car2.snapshot();
    db.set(car2);
        



    5.2. Retrieving



      5.2.1. QBE


      First let us verify that we indeed have taken snapshots.


      SensorReadout proto=new SensorReadout(null,null,null);
      ObjectSet result=db.get(proto);
      Util.listResult(result);
          


      As a prototype for an array, we provide an array of the same type, containing only the values we expect the result to contain.


      SensorReadout proto=new SensorReadout(
              new double[]{0.3,0.1},null,null);
      ObjectSet result=db.get(proto);
      Util.listResult(result);
          


      Note that the actual position of the given elements in the prototype array is irrelevant.

      To retrieve a car by its stored sensor readouts, we install a history containing the sought-after values.


      SensorReadout protoreadout=new SensorReadout(
              new double[]{0.6,0.2},null,null);
      List protohistory=new ArrayList();
      protohistory.add(protoreadout);
      Car protocar=new Car(null,protohistory);
      ObjectSet result=db.get(protocar);
      Util.listResult(result);
          


      We can also query for the collections themselves, since they are first class objects.


      ObjectSet result=db.get(new ArrayList());
      Util.listResult(result);
          


      This doesn't work with arrays, though.


      ObjectSet result=db.get(new double[]{0.6,0.4});
      Util.listResult(result);
          



      5.2.2. Query API


      Handling of arrays and collections is analogous to the previous example.


      Query query=db.query();
      query.constrain(SensorReadout.class);
      Query valuequery=query.descend("values");
      valuequery.constrain(new Double(0.3));
      valuequery.constrain(new Double(0.1));
      ObjectSet result=query.execute();
      Util.listResult(result);
          



      Query query=db.query();
      query.constrain(Car.class);
      Query historyquery=query.descend("history");
      historyquery.constrain(SensorReadout.class);
      Query valuequery=historyquery.descend("values");
      valuequery.constrain(new Double(0.3));
      valuequery.constrain(new Double(0.1));
      ObjectSet result=query.execute();
      Util.listResult(result);
          



    5.3. Updating and deleting


    This should be familiar, we just have to remember to take care of the update depth .


    Db4o.configure().objectClass(Car.class)
            .cascadeOnUpdate(true);
        



    ObjectSet result=db.get(new Car("BMW",null));
    Car car=(Car)result.next();
    car.snapshot();
    db.set(car);
    retrieveAllSensorReadouts(db);
        


    There's nothing special about deleting arrays and collections, too.

    Deleting an object from a collection is an update, too, of course.


    Query query=db.query();
    query.constrain(Car.class);
    ObjectSet result=query.descend("history").execute();
    List coll=(List)result.next();
    coll.remove(0);
    db.set(coll);
    Car proto=new Car(null,null);
    result=db.get(proto);
    while(result.hasNext()) {
        Car car=(Car)result.next();
        for (int idx=0;idx<car.getHistory().length;idx++) {
            System.out.println(car.getHistory()[idx]);
        }
    }
        


    (This example also shows that with db4o it is quite easy to access object internals we were never meant to see. Please keep this always in mind and be careful.)

    We will delete all cars from the database again to prepare for the next chapter.


    Db4o.configure().objectClass(Car.class)
            .cascadeOnDelete(true);
        



    ObjectSet result=db.get(new Car(null,null));
    while(result.hasNext()) {
        db.delete(result.next());
    }
    ObjectSet readouts=db.get(
            new SensorReadout(null,null,null));
    while(readouts.hasNext()) {
        db.delete(readouts.next());
    }
        



    5.4. db4o custom collections


    db4o also provides customized collection implementations, tweaked for use with db4o. We will get to that in a later chapter when we have finished our first walkthrough.


    5.5. Conclusion


    Ok, collections are just objects. But why did we have to specify the concrete ArrayList type all the way? Was that necessary? How does db4o handle inheritance?


    5.6. Full source



    package com.db4o.f1.chapter3;

    import java.io.*;
    import java.util.*;
    import com.db4o.*;
    import com.db4o.f1.*;
    import com.db4o.query.*;


    public class CollectionsExample {
        private final static String FILENAME="f1.yap";
        
        public static void main(String[] args) {
            new File(FILENAME).delete();
            ObjectContainer db=Db4o.openFile(FILENAME);
            try {
                storeFirstCar(db);
                storeSecondCar(db);
                retrieveAllSensorReadouts(db);
                retrieveSensorReadoutQBE(db);
                retrieveCarQBE(db);
                retrieveCollections(db);
                retrieveArrays(db);
                retrieveSensorReadoutQuery(db);
                retrieveCarQuery(db);
                db.close();
                updateCarPart1();
                db=Db4o.openFile(FILENAME);
                updateCarPart2(db);
                updateCollection(db);
                db.close();
                deleteAllPart1();
                db=Db4o.openFile(FILENAME);
                deleteAllPart2(db);
                retrieveAllSensorReadouts(db);
            }
            finally {
                db.close();
            }
        }

        public static void storeFirstCar(ObjectContainer db) {
            Car car1=new Car("Ferrari");
            Pilot pilot1=new Pilot("Michael Schumacher",100);
            car1.setPilot(pilot1);
            db.set(car1);
        }
        
        public static void storeSecondCar(ObjectContainer db) {
            Pilot pilot2=new Pilot("Rubens Barrichello",99);
            Car car2=new Car("BMW");
            car2.setPilot(pilot2);
            car2.snapshot();
            car2.snapshot();
            db.set(car2);
        }
        
        public static void retrieveAllSensorReadouts(
                    ObjectContainer db) {
            SensorReadout proto=new SensorReadout(null,null,null);
            ObjectSet result=db.get(proto);
            Util.listResult(result);
        }

        public static void retrieveSensorReadoutQBE(
                    ObjectContainer db) {
            SensorReadout proto=new SensorReadout(
                    new double[]{0.3,0.1},null,null);
            ObjectSet result=db.get(proto);
            Util.listResult(result);
        }

        public static void retrieveCarQBE(ObjectContainer db) {
            SensorReadout protoreadout=new SensorReadout(
                    new double[]{0.6,0.2},null,null);
            List protohistory=new ArrayList();
            protohistory.add(protoreadout);
            Car protocar=new Car(null,protohistory);
            ObjectSet result=db.get(protocar);
            Util.listResult(result);
        }

        public static void retrieveCollections(ObjectContainer db) {
            ObjectSet result=db.get(new ArrayList());
            Util.listResult(result);
        }

        public static void retrieveArrays(ObjectContainer db) {
            ObjectSet result=db.get(new double[]{0.6,0.4});
            Util.listResult(result);
        }

        public static void retrieveSensorReadoutQuery(
                    ObjectContainer db) {
            Query query=db.query();
            query.constrain(SensorReadout.class);
            Query valuequery=query.descend("values");
            valuequery.constrain(new Double(0.3));
            valuequery.constrain(new Double(0.1));
            ObjectSet result=query.execute();
            Util.listResult(result);
        }

        public static void retrieveCarQuery(ObjectContainer db) {
            Query query=db.query();
            query.constrain(Car.class);
            Query historyquery=query.descend("history");
            historyquery.constrain(SensorReadout.class);
            Query valuequery=historyquery.descend("values");
            valuequery.constrain(new Double(0.3));
            valuequery.constrain(new Double(0.1));
            ObjectSet result=query.execute();
            Util.listResult(result);
        }

        public static void updateCarPart1() {
            Db4o.configure().objectClass(Car.class)
             .cascadeOnUpdate(true);
        }

        public static void updateCarPart2(ObjectContainer db) {
            ObjectSet result=db.get(new Car("BMW",null));
            Car car=(Car)result.next();
            car.snapshot();
            db.set(car);
            retrieveAllSensorReadouts(db);
        }
        
        public static void updateCollection(ObjectContainer db) {
            Query query=db.query();
            query.constrain(Car.class);
            ObjectSet result=query.descend("history").execute();
            List coll=(List)result.next();
            coll.remove(0);
            db.set(coll);
            Car proto=new Car(null,null);
            result=db.get(proto);
            while(result.hasNext()) {
                Car car=(Car)result.next();
                for (int idx=0;idx<car.getHistory().length;idx++) {
                    System.out.println(car.getHistory()[idx]);
                }
            }
        }
        
        public static void deleteAllPart1() {
            Db4o.configure().objectClass(Car.class)
             .cascadeOnDelete(true);
        }
        
        public static void deleteAllPart2(ObjectContainer db) {
            ObjectSet result=db.get(new Car(null,null));
            while(result.hasNext()) {
                db.delete(result.next());
            }
            ObjectSet readouts=db.get(
                    new SensorReadout(null,null,null));
            while(readouts.hasNext()) {
                db.delete(readouts.next());
            }
        }
    }





    --
    generated by
    Doctor courtesy of db4objecs Inc.