KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ozoneDB > core > Server


1 // You can redistribute this software and/or modify it under the terms of
2
// the Ozone Core License version 1 published by ozone-db.org.
3
//
4
// The original code and portions created by SMB are
5
// Copyright (C) 1997-@year@ by SMB GmbH. All rights reserved.
6
//
7
// $Id: Server.java,v 1.6 2002/09/21 16:06:35 per_nyfelt Exp $
8

9 package org.ozoneDB.core;
10
11 import java.lang.reflect.*;
12 import java.io.*;
13 import org.ozoneDB.DxLib.*;
14 import org.ozoneDB.*;
15 import org.ozoneDB.util.*;
16 import org.ozoneDB.tools.*;
17
18
19 /**
20  * Main class to start the stand-alone server.
21  *
22  * @author <a HREF="http://www.softwarebuero.de/">SMB</a>
23  * @version $Revision: 1.6 $Date: 2002/09/21 16:06:35 $
24  */

25 public class Server {
26
27     public static Env env;
28
29     public static boolean stop;
30
31     public static boolean stopped;
32
33
34     public static void main( String JavaDoc[] args ) throws Exception JavaDoc {
35         String JavaDoc dir = File.separator + "tmp" + File.separator + "db";
36         String JavaDoc debugLevel = null;
37         boolean help = false;
38         boolean verbose = false;
39         boolean createDB = false;
40         DxArrayBag users = new DxArrayBag();
41
42         for (int i = 0; i < args.length; i++) {
43             if (args[i].startsWith( "-debug" )) {
44                 debugLevel = args[i].substring("-debug".length());
45             } else if (args[i].startsWith( "-d" )) {
46                 dir = args[i].substring( 2 );
47             } else if (args[i].startsWith( "-c" )) {
48                 createDB = true;
49             } else if (args[i].startsWith( "-u" )) {
50                 String JavaDoc name = args[i].substring( 2 );
51                 users.add( name );
52             } else if (args[i].startsWith( "-h" )) {
53                 help = true;
54             } else {
55                 System.out.println( "illegal option: " + args[i] );
56                 help = true;
57             }
58         }
59
60         if (args.length == 0 || help) {
61             System.out.println( "usage: ozone -d<dir> [-h] [-debug] [-v]" );
62             System.out.println( " -d<directory> database directory" );
63             System.out.println( " -debug<level> debug level, levels are one of the string constants in the OzoneDebugLevel class" );
64             System.out.println( " -v starts the ozonometer (broken)" );
65             System.out.println( " -c create a database if neccessary" );
66             System.out.println( " -u<name> add user <name>" );
67             System.out.println( " -h shows this help" );
68             System.exit( 0 );
69         }
70
71         try {
72             if (createDB) {
73
74                 // Check if a DB exists and make a new database if not.
75
if (!Install.dbExists(dir)) {
76                     System.out.println( "Installing new database in " + dir + "..." );
77
78                     Setup defaults = new Setup( null );
79                     defaults.addProperties( System.getProperties(), "ozoneDB." );
80                     Install.createDB( dir, defaults, new PrintWriter( System.out, true ) );
81
82                     System.out.println( "Edit " + dir + Env.CONFIG_FILE + " to change settings." );
83                     System.out.println( "install complete\n" );
84                 }
85             }
86
87             System.out.println( "initializing environment..." );
88             env = new Env( dir, debugLevel);
89
90             // This is a good place to set up our shutdown hook. Doing it
91
// earlier would case a NullPointerException in race conditions.
92
// Doing it now is fine in terms of preventing database corruption
93
// because request processing has no yet begun.
94
setupShutdownHook();
95
96             int freeSlot = 101;
97             for (int i = 0; i < users.count(); i++) {
98                 String JavaDoc name = (String JavaDoc)users.elementAtIndex( i );
99                 // don't insert a name twice
100
if (env.userManager.userForName( name ) != null) {
101                     env.logWriter.newEntry( env, "User " + name + " already exists.", LogWriter.INFO );
102                     continue;
103                 }
104                 // find a free id
105
while (env.userManager.userForID( freeSlot ) != null) {
106                     freeSlot++;
107                 }
108                 // add the user
109
env.userManager.newUser( name, freeSlot );
110                 env.logWriter.newEntry( env, "user added: " + name + " ID: " + freeSlot, LogWriter.INFO );
111             }
112             env.storeSetup();
113
114             env.startExternalEventProcessing();
115             env.startDeadlockRecognition();
116
117             System.out.println( "(Ctrl-C or 'q' to shutdown without admin tool)" );
118
119             InputStreamReader is = new InputStreamReader( System.in );
120             Thread.currentThread().setPriority( Env.SERVER_THREAD_PRIORITY );
121
122             stop = false;
123             stopped = false;
124             // the main loop
125
while (!stop) {
126                 int gcCount = 0;
127                 int stateCount = 0;
128                 while (!is.ready() && !env.shuttingdown && !stop) {
129                     final int sleepMillis = 250;
130
131                     // this forces also task switches
132
Thread.currentThread().sleep( sleepMillis );
133
134                     // check component states every 5sec; this is not really a
135
// good solution but it works for now
136
// if (stateCount++ >= (5000/sleepMillis)) {
137
// stateCount = 0;
138
// if (env.isComponentStateChanged()) {
139
// env.logWriter.newEntry( env, "storing server state...", LogWriter.DEBUG );
140
// env.storeSetup();
141
// }
142
// }
143

144                     // force GC
145
if (env.transactionManager.taTableCount() == 0) {
146                         gcCount++;
147                     }
148                     else {
149                         gcCount = 0;
150                     }
151                     if (gcCount >= (10000/sleepMillis)) {
152 // env.logWriter.newEntry( env, "forcing GC...", LogWriter.DEBUG3 );
153
System.gc();
154                         gcCount = 0;
155                     }
156                 }
157
158                 if (is.ready()) {
159                     int c = is.read();
160                     if (c == 'q') {
161                         stop = true;
162                     }
163                 }
164             }
165             // wait for the admin thread to deconnect
166
Thread.sleep( 1000 );
167
168             // shutdown the system
169
env.shutdown();
170             stopped = true;
171         }
172         catch (Exception JavaDoc e) {
173             if (env != null) {
174                 env.shutdown();
175             }
176             // env.logWriter.newEntry (null, "", e, LogWriter.ERROR);
177
System.out.println( "Unable to initialize server." );
178             e.printStackTrace();
179         }
180         System.exit( 1 );
181     }
182
183
184     /**
185      * Attempt to add the shutdown hook using reflection.
186      */

187     private static void setupShutdownHook() {
188         try {
189            // We will now attempt to add the shutdown hook
190
// using reflection. If we're running in a VM that does
191
// not support shutdown hooks (i.e., pre-1.3), it will yield
192
// a NoSuchMethodException, which we quietly ignore.
193
Class JavaDoc runtimeClass = Runtime JavaDoc.class;
194            Method hookMethod = runtimeClass.getMethod("addShutdownHook", new Class JavaDoc[]{Thread JavaDoc.class});
195            Runtime JavaDoc rt = Runtime.getRuntime();
196            hookMethod.invoke(rt, new Object JavaDoc[]{createShutdownHook()});
197
198            env.logWriter.newEntry(Server.class, "Shutdown hook successfully added.",
199                    LogWriter.INFO);
200         }
201         catch (NoSuchMethodException JavaDoc nsme) {
202            /* Pre-1.3 VM. */
203            env.logWriter.newEntry(Server.class, "Running on pre-1.3 VM; no shutdown hook added.", LogWriter.INFO);
204         }
205         catch (SecurityException JavaDoc se) {
206            /* Either a screwy setup, or permission deliberately denied. */
207            env.logWriter.newEntry(Server.class, "Shutdown hook not added; permission denied.", LogWriter.WARN);
208         }
209         catch (InvocationTargetException ite) {
210            /* Runtime.addShutdownHook() failed */
211            Throwable JavaDoc te = ite.getTargetException();
212            env.logWriter.newEntry(Server.class, "WARNING: Shutdown hook addition failed: "
213                    + te.getClass().getName() + ": " + te.getMessage(),
214                    LogWriter.ERROR);
215         }
216         catch (IllegalAccessException JavaDoc iae) {
217            /* The VM is FUBAR. */
218            env.logWriter.newEntry(Server.class,"Runtime.addShutdownHook() not public? VM bug?", LogWriter.ERROR);
219         }
220     }
221
222     /**
223      * Constructs and returns a Thread to be used as a shutdown hook.
224      */

225     private static Runnable JavaDoc createShutdownHook() {
226         return new Thread JavaDoc() {
227             public void run() {
228                 if (env.shuttingdown == false) {
229                     env.logWriter.newEntry(Server.class, "Shutdown hook...", LogWriter.INFO);
230                     try {
231                         // signal the main loop to stop
232
stop = true;
233
234                        // wait for the mail thread to finish shutdown
235
while (!stopped) {
236                            sleep(500);
237                        }
238                     }
239                     catch (Exception JavaDoc e) {
240                     }
241                     env.logWriter.newEntry(Server.class, "Shutdown hook... shutdown finished.", LogWriter.INFO);
242                 }
243             }
244         };
245     }
246 }
247
248
Popular Tags