• Home
  • History
  • Annotate
  • Line#
  • Navigate
  • Raw
  • Download
  • only in /asuswrt-rt-n18u-9.0.0.4.380.2695/release/src-rt/router/db-4.8.30/examples_java/src/db/repquote_gsg/
1/*-
2 * See the file LICENSE for redistribution information.
3 *
4 * Copyright (c) 2001-2009 Oracle.  All rights reserved.
5 *
6 * $Id$
7 */
8
9package db.repquote_gsg;
10
11import java.io.FileNotFoundException;
12// BufferedReader and InputStreamReader needed for our command line
13// prompt.
14import java.io.BufferedReader;
15import java.io.InputStreamReader;
16import java.io.IOException;
17import java.io.UnsupportedEncodingException;
18
19import com.sleepycat.db.Cursor;
20import com.sleepycat.db.Database;
21import com.sleepycat.db.DatabaseConfig;
22import com.sleepycat.db.DatabaseEntry;
23import com.sleepycat.db.DatabaseException;
24import com.sleepycat.db.DatabaseType;
25import com.sleepycat.db.Environment;
26import com.sleepycat.db.EnvironmentConfig;
27import com.sleepycat.db.LockMode;
28import com.sleepycat.db.OperationStatus;
29import db.repquote_gsg.SimpleConfig;
30
31public class SimpleTxn
32{
33    private SimpleConfig simpleConfig;
34    private Environment dbenv;
35
36    public SimpleTxn()
37        throws DatabaseException
38    {
39        simpleConfig = null;
40        dbenv = null;
41    }
42
43    public static void usage()
44    {
45        System.err.println("usage: " + SimpleConfig.progname + " -h home");
46        System.exit(1);
47    }
48
49    public static void main(String[] argv)
50        throws Exception
51    {
52        SimpleConfig config = new SimpleConfig();
53        // Extract the command line parameters.
54        for (int i = 0; i < argv.length; i++)
55        {
56            if (argv[i].compareTo("-h") == 0) {
57                // home - a string arg.
58                i++;
59                config.home = argv[i];
60            } else {
61                System.err.println("Unrecognized option: " + argv[i]);
62                usage();
63            }
64        }
65
66        // Error check command line.
67        if (config.home.length() == 0)
68            usage();
69
70        SimpleTxn runner = null;
71        try {
72            runner = new SimpleTxn();
73            runner.init(config);
74
75            runner.doloop();
76            runner.terminate();
77        } catch (DatabaseException dbe) {
78            System.err.println("Caught an exception during " +
79                "initialization or processing: " + dbe.toString());
80            if (runner != null)
81                runner.terminate();
82        }
83            System.exit(0);
84    } // end main
85
86    public int init(SimpleConfig config)
87        throws DatabaseException
88    {
89        int ret = 0;
90        simpleConfig = config;
91        EnvironmentConfig envConfig = new EnvironmentConfig();
92        envConfig.setErrorStream(System.err);
93        envConfig.setErrorPrefix(SimpleConfig.progname);
94
95        envConfig.setCacheSize(SimpleConfig.CACHESIZE);
96        envConfig.setTxnNoSync(true);
97
98        envConfig.setAllowCreate(true);
99        envConfig.setRunRecovery(true);
100        envConfig.setInitializeLocking(true);
101        envConfig.setInitializeLogging(true);
102        envConfig.setInitializeCache(true);
103        envConfig.setTransactional(true);
104        try {
105            dbenv = new Environment(simpleConfig.getHome(), envConfig);
106        } catch(FileNotFoundException e) {
107            System.err.println("FileNotFound exception: " + e.toString());
108            System.err.println(
109                "Ensure that the environment directory is pre-created.");
110            ret = 1;
111        }
112
113        return ret;
114    }
115
116    // Provides the main data processing function for our application.
117    // This function provides a command line prompt to which the user
118    // can provide a ticker string and a stock price.  Once a value is
119    // entered to the application, the application writes the value to
120    // the database and then displays the entire database.
121    public int doloop()
122        throws DatabaseException, UnsupportedEncodingException
123    {
124        Database db = null;
125
126        for (;;)
127        {
128            if (db == null) {
129                DatabaseConfig dbconf = new DatabaseConfig();
130                dbconf.setType(DatabaseType.BTREE);
131                dbconf.setAllowCreate(true);
132                dbconf.setTransactional(true);
133
134                try {
135                    db = dbenv.openDatabase(null,              // txn handle
136                                        SimpleConfig.progname, // db filename
137                                        null,                  // db name
138                                        dbconf);
139                } catch (FileNotFoundException fnfe) {
140                    System.err.println("File not found exception" +
141                        fnfe.toString());
142                    // Get here only if the environment home directory
143                    // somehow does not exist.
144               }
145            }
146
147            BufferedReader stdin =
148                new BufferedReader(new InputStreamReader(System.in));
149
150            // Listen for input, and add it to the database.
151            System.out.print("QUOTESERVER> ");
152            System.out.flush();
153            String nextline = null;
154            try {
155                nextline = stdin.readLine();
156            } catch (IOException ioe) {
157                System.err.println("Unable to get data from stdin");
158                break;
159            }
160            String[] words = nextline.split("\\s");
161
162            // A blank line causes the DB to be dumped to stdout.
163            if (words.length == 0 ||
164                (words.length == 1 && words[0].length() == 0)) {
165                try {
166                    printStocks(db);
167                } catch (DatabaseException e) {
168                    System.err.println("Got db exception reading " +
169                        "DB: " + e.toString());
170                    break;
171                }
172                continue;
173            }
174
175            if (words.length == 1 &&
176                (words[0].compareToIgnoreCase("quit") == 0 ||
177                words[0].compareToIgnoreCase("exit") == 0)) {
178                break;
179            } else if (words.length != 2) {
180                System.err.println("Format: TICKER VALUE");
181                continue;
182            }
183
184            DatabaseEntry key =
185                    new DatabaseEntry(words[0].getBytes("UTF-8"));
186            DatabaseEntry data =
187                    new DatabaseEntry(words[1].getBytes("UTF-8"));
188
189            db.put(null, key, data);
190        }
191        if (db != null)
192            db.close(true);
193        return 0;
194    }
195
196    public void terminate()
197        throws DatabaseException
198    {
199            dbenv.close();
200    }
201
202    // Display all the stock quote information in the database.
203    // Return type is void because error conditions are propagated
204    // via exceptions.
205    private void printStocks(Database db)
206        throws DatabaseException
207    {
208        Cursor dbc = db.openCursor(null, null);
209
210        System.out.println("\tSymbol\tPrice");
211        System.out.println("\t======\t=====");
212
213        DatabaseEntry key = new DatabaseEntry();
214        DatabaseEntry data = new DatabaseEntry();
215        OperationStatus ret;
216        for (ret = dbc.getFirst(key, data, LockMode.DEFAULT);
217            ret == OperationStatus.SUCCESS;
218            ret = dbc.getNext(key, data, LockMode.DEFAULT)) {
219            String keystr = new String
220                (key.getData(), key.getOffset(), key.getSize());
221            String datastr = new String
222                (data.getData(), data.getOffset(), data.getSize());
223            System.out.println("\t"+keystr+"\t"+datastr);
224
225        }
226        dbc.close();
227    }
228} // end class
229
230