KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > persist > EventExampleDPL


1 /*-
2  * See the file LICENSE for redistribution information.
3  *
4  * Copyright (c) 2004,2006 Oracle. All rights reserved.
5  *
6  * $Id: EventExampleDPL.java,v 1.1 2006/11/02 16:34:58 linda Exp $
7  */

8
9 package persist;
10
11 import static com.sleepycat.persist.model.Relationship.MANY_TO_ONE;
12
13 import java.io.File JavaDoc;
14 import java.util.Calendar JavaDoc;
15 import java.util.Date JavaDoc;
16 import java.util.HashSet JavaDoc;
17 import java.util.Random JavaDoc;
18 import java.util.Set JavaDoc;
19
20 import com.sleepycat.je.DatabaseException;
21 import com.sleepycat.je.Environment;
22 import com.sleepycat.je.EnvironmentConfig;
23 import com.sleepycat.je.Transaction;
24 import com.sleepycat.persist.EntityCursor;
25 import com.sleepycat.persist.EntityStore;
26 import com.sleepycat.persist.PrimaryIndex;
27 import com.sleepycat.persist.SecondaryIndex;
28 import com.sleepycat.persist.StoreConfig;
29 import com.sleepycat.persist.model.Entity;
30 import com.sleepycat.persist.model.PrimaryKey;
31 import com.sleepycat.persist.model.SecondaryKey;
32
33 /**
34  * EventExampleDPL is a trivial example which stores Java objects that
35  * represent an event. Events are primarily indexed by a timestamp, but have
36  * other attributes, such as price, account reps, customer name and
37  * quantity. Some of those other attributes are indexed.
38  * <p>
39  * The example simply shows the creation of a JE environment and database,
40  * inserting some events, and retrieving the events using the Direct
41  * Persistence layer.
42  * <p>
43  * This example is meant to be paired with its twin, EventExample.java.
44  * EventExample.java and EventExampleDPL.java perform the same functionality,
45  * but use the Base API and the Direct Persistence Layer api, respectively.
46  * This may be a useful way to compare the two apis.
47  * <p>
48  * To run the example:
49  * <pre>
50  * javac EventExampleDPL.java
51  * java -cp je.jar EventExampleDPL -h <environmentDirectory>
52  * </pre>
53  */

54 public class EventExampleDPL {
55
56     /*
57      * The Event class embodies our example event and is the application
58      * data. The @Entity annotation indicates that this class defines the
59      * objects stored in a JE database.
60      */

61     @Entity
62     static class Event {
63
64         @PrimaryKey
65         private Date JavaDoc time;
66
67         @SecondaryKey(relate=MANY_TO_ONE)
68         private int price;
69
70         private Set JavaDoc<String JavaDoc> accountReps;
71
72         private String JavaDoc customerName;
73         private int quantity;
74
75         Event(Date JavaDoc time,
76               int price,
77               String JavaDoc customerName) {
78
79             this.time = time;
80             this.price = price;
81             this.customerName = customerName;
82             this.accountReps = new HashSet JavaDoc<String JavaDoc>();
83         }
84
85         private Event() {} // For deserialization
86

87         void addRep(String JavaDoc rep) {
88             accountReps.add(rep);
89         }
90
91         @Override JavaDoc
92         public String JavaDoc toString() {
93             StringBuilder JavaDoc sb = new StringBuilder JavaDoc();
94             sb.append("time=").append(time);
95             sb.append(" price=").append(price);
96             sb.append(" customerName=").append(customerName);
97             sb.append(" reps=");
98             if (accountReps.size() == 0) {
99                 sb.append("none");
100             } else {
101                 for (String JavaDoc rep: accountReps) {
102                     sb.append(rep).append(" ");
103                 }
104             }
105             return sb.toString();
106         }
107     }
108
109     /* A JE environment is roughly equivalent to a relational database. */
110     private Environment env;
111     private EntityStore store;
112
113     /*
114      * Event accessors let us access events by the primary index (time)
115      * as well as by the rep and price fields
116      */

117     PrimaryIndex<Date JavaDoc,Event> eventByTime;
118     SecondaryIndex<Integer JavaDoc,Date JavaDoc,Event> eventByPrice;
119
120     /* Used for generating example data. */
121     private Calendar JavaDoc cal;
122     
123     /*
124      * First manually make a directory to house the JE environment.
125      * Usage: java -cp je.jar EventExampleDPL -h <envHome>
126      * All JE on-disk storage is held within envHome.
127      */

128     public static void main(String JavaDoc[] args)
129         throws DatabaseException {
130
131         if (args.length != 2 || !"-h".equals(args[0])) {
132             System.err.println
133                 ("Usage: java " + EventExampleDPL.class.getName() +
134                  " -h <envHome>");
135             System.exit(2);
136         }
137         EventExampleDPL example = new EventExampleDPL(new File JavaDoc(args[1]));
138         example.run();
139         example.close();
140     }
141
142     private EventExampleDPL(File JavaDoc envHome)
143         throws DatabaseException {
144
145         /* Open a transactional Berkeley DB engine environment. */
146         System.out.println("-> Creating a JE environment");
147         EnvironmentConfig envConfig = new EnvironmentConfig();
148         envConfig.setAllowCreate(true);
149         envConfig.setTransactional(true);
150         env = new Environment(envHome, envConfig);
151
152         /* Initialize the data access object. */
153         init();
154         cal = Calendar.getInstance();
155     }
156
157     /**
158      * Create all primary and secondary indices.
159      */

160     private void init()
161         throws DatabaseException {
162
163         /* Open a transactional entity store. */
164         System.out.println("-> Creating a JE database");
165         StoreConfig storeConfig = new StoreConfig();
166         storeConfig.setAllowCreate(true);
167         storeConfig.setTransactional(true);
168         store = new EntityStore(env, "ExampleStore", storeConfig);
169
170         eventByTime = store.getPrimaryIndex(Date JavaDoc.class, Event.class);
171         eventByPrice = store.getSecondaryIndex(eventByTime,
172                                                Integer JavaDoc.class,
173                                                "price");
174     }
175
176     private void run()
177         throws DatabaseException {
178
179         Random JavaDoc rand = new Random JavaDoc();
180
181         /*
182          * Create a set of events. Each insertion is a separate, auto-commit
183          * transaction.
184          */

185         System.out.println("-> Inserting 4 events");
186         eventByTime.put(new Event(makeDate(1), 100, "Company_A"));
187         eventByTime.put(new Event(makeDate(2), 2, "Company_B"));
188         eventByTime.put(new Event(makeDate(3), 20, "Company_C"));
189         eventByTime.put(new Event(makeDate(4), 40, "CompanyD"));
190
191         /* Load a whole set of events transactionally. */
192         Transaction txn = env.beginTransaction(null, null);
193         int maxPrice = 50;
194         System.out.println("-> Inserting some randomly generated events");
195         for (int i = 0; i < 25; i++) {
196             Event e = new Event(makeDate(rand.nextInt(365)),
197                                 rand.nextInt(maxPrice),
198                                 "Company_X");
199             if ((i%2) ==0) {
200                 e.addRep("Bob");
201                 e.addRep("Nikunj");
202             } else {
203                 e.addRep("Yongmin");
204             }
205             eventByTime.put(e);
206         }
207         txn.commitWriteNoSync();
208
209         /*
210          * Windows of events - display the events between June 1 and Aug 31
211          */

212         System.out.println("\n-> Display the events between June 1 and Aug 31");
213         Date JavaDoc startDate = makeDate(Calendar.JUNE, 1);
214         Date JavaDoc endDate = makeDate(Calendar.AUGUST, 31);
215
216         EntityCursor<Event> eventWindow =
217             eventByTime.entities(startDate, true, endDate, true);
218         printEvents(eventWindow);
219         
220         /*
221          * Display all events, ordered by a secondary index on price.
222          */

223         System.out.println("\n-> Display all events, ordered by price");
224         EntityCursor<Event> byPriceEvents = eventByPrice.entities();
225         printEvents(byPriceEvents);
226     }
227
228     private void close()
229         throws DatabaseException {
230
231         store.close();
232         env.close();
233     }
234     
235     /**
236      * Print all events covered by this cursor.
237      */

238     private void printEvents(EntityCursor<Event> eCursor)
239         throws DatabaseException {
240         try {
241             for (Event e: eCursor) {
242                 System.out.println(e);
243             }
244         } finally {
245             /* Be sure to close the cursor. */
246             eCursor.close();
247         }
248     }
249
250     /**
251      * Little utility for making up java.util.Dates for different days, just
252      * to generate test data.
253      */

254     private Date JavaDoc makeDate(int day) {
255
256         cal.set((Calendar.DAY_OF_YEAR), day);
257         return cal.getTime();
258     }
259
260     /**
261      * Little utility for making up java.util.Dates for different days, just
262      * to make the test data easier to read.
263      */

264     private Date JavaDoc makeDate(int month, int day) {
265
266         cal.set((Calendar.MONTH), month);
267         cal.set((Calendar.DAY_OF_MONTH), day);
268         return cal.getTime();
269     }
270 }
271
Popular Tags