1/*-
2 * See the file LICENSE for redistribution information.
3 *
4 * Copyright (c) 2002,2008 Oracle.  All rights reserved.
5 *
6 * $Id: HelloDatabaseWorld.java,v 12.8 2008/02/07 17:12:20 mark Exp $
7 */
8
9package collections.hello;
10
11import java.io.File;
12import java.util.Iterator;
13import java.util.Map;
14import java.util.SortedMap;
15
16import com.sleepycat.bind.serial.ClassCatalog;
17import com.sleepycat.bind.serial.SerialBinding;
18import com.sleepycat.bind.serial.StoredClassCatalog;
19import com.sleepycat.bind.tuple.TupleBinding;
20import com.sleepycat.collections.StoredSortedMap;
21import com.sleepycat.collections.TransactionRunner;
22import com.sleepycat.collections.TransactionWorker;
23import com.sleepycat.db.Database;
24import com.sleepycat.db.DatabaseConfig;
25import com.sleepycat.db.DatabaseType;
26import com.sleepycat.db.Environment;
27import com.sleepycat.db.EnvironmentConfig;
28
29/**
30 * @author Mark Hayes
31 */
32public class HelloDatabaseWorld implements TransactionWorker {
33
34    private static final String[] INT_NAMES = {
35        "Hello", "Database", "World",
36    };
37    private static boolean create = true;
38
39    private Environment env;
40    private ClassCatalog catalog;
41    private Database db;
42    private SortedMap map;
43
44    /** Creates the environment and runs a transaction */
45    public static void main(String[] argv)
46        throws Exception {
47
48        String dir = "./tmp";
49
50        // environment is transactional
51        EnvironmentConfig envConfig = new EnvironmentConfig();
52        envConfig.setTransactional(true);
53        envConfig.setInitializeCache(true);
54        envConfig.setInitializeLocking(true);
55        if (create) {
56            envConfig.setAllowCreate(true);
57        }
58        Environment env = new Environment(new File(dir), envConfig);
59
60        // create the application and run a transaction
61        HelloDatabaseWorld worker = new HelloDatabaseWorld(env);
62        TransactionRunner runner = new TransactionRunner(env);
63        try {
64            // open and access the database within a transaction
65            runner.run(worker);
66        } finally {
67            // close the database outside the transaction
68            worker.close();
69        }
70    }
71
72    /** Creates the database for this application */
73    private HelloDatabaseWorld(Environment env)
74        throws Exception {
75
76        this.env = env;
77        open();
78    }
79
80    /** Performs work within a transaction. */
81    public void doWork()
82        throws Exception {
83
84        writeAndRead();
85    }
86
87    /** Opens the database and creates the Map. */
88    private void open()
89        throws Exception {
90
91        // use a generic database configuration
92        DatabaseConfig dbConfig = new DatabaseConfig();
93        dbConfig.setTransactional(true);
94        if (create) {
95            dbConfig.setAllowCreate(true);
96            dbConfig.setType(DatabaseType.BTREE);
97        }
98
99        // catalog is needed for serial bindings (java serialization)
100        Database catalogDb = env.openDatabase(null, "catalog", null, dbConfig);
101        catalog = new StoredClassCatalog(catalogDb);
102
103        // use Integer tuple binding for key entries
104        TupleBinding keyBinding =
105            TupleBinding.getPrimitiveBinding(Integer.class);
106
107        // use String serial binding for data entries
108        SerialBinding dataBinding = new SerialBinding(catalog, String.class);
109
110        this.db = env.openDatabase(null, "helloworld", null, dbConfig);
111
112        // create a map view of the database
113        this.map = new StoredSortedMap(db, keyBinding, dataBinding, true);
114    }
115
116    /** Closes the database. */
117    private void close()
118        throws Exception {
119
120        if (catalog != null) {
121            catalog.close();
122            catalog = null;
123        }
124        if (db != null) {
125            db.close();
126            db = null;
127        }
128        if (env != null) {
129            env.close();
130            env = null;
131        }
132    }
133
134    /** Writes and reads the database via the Map. */
135    private void writeAndRead() {
136
137        // check for existing data
138        Integer key = new Integer(0);
139        String val = (String) map.get(key);
140        if (val == null) {
141            System.out.println("Writing data");
142            // write in reverse order to show that keys are sorted
143            for (int i = INT_NAMES.length - 1; i >= 0; i -= 1) {
144                map.put(new Integer(i), INT_NAMES[i]);
145            }
146        }
147        // get iterator over map entries
148        Iterator iter = map.entrySet().iterator();
149        System.out.println("Reading data");
150        while (iter.hasNext()) {
151            Map.Entry entry = (Map.Entry) iter.next();
152            System.out.println(entry.getKey().toString() + ' ' +
153                               entry.getValue());
154        }
155    }
156}
157