KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > derby > RegisterDerby


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.derby;
21
22 import java.io.File JavaDoc;
23 import java.io.FileOutputStream JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.io.OutputStream JavaDoc;
26 import java.util.Properties JavaDoc;
27 import org.netbeans.api.db.explorer.JDBCDriver;
28 import org.netbeans.api.db.explorer.JDBCDriverManager;
29 import org.netbeans.api.java.platform.JavaPlatform;
30 import org.netbeans.api.java.platform.JavaPlatformManager;
31 import org.netbeans.api.progress.ProgressHandle;
32 import org.netbeans.api.progress.ProgressHandleFactory;
33 import org.netbeans.modules.derby.api.DerbyDatabases;
34 import org.netbeans.spi.db.explorer.DatabaseRuntime;
35 import org.openide.ErrorManager;
36 import org.openide.execution.NbProcessDescriptor;
37 import org.openide.filesystems.FileObject;
38 import org.openide.filesystems.FileUtil;
39 import org.openide.util.NbBundle;
40 import org.openide.util.RequestProcessor;
41 import org.openide.util.Utilities;
42
43
44 /**
45  *
46  * @author Ludo, Petr Jiricka
47  */

48 public class RegisterDerby implements DatabaseRuntime {
49     
50     // XXX this class does too much. Should maybe be split into
51
// DatabaseRuntimeImpl and the rest.
52

53     private static final ErrorManager LOGGER = ErrorManager.getDefault().getInstance(RegisterDerby.class.getName());
54     private static final boolean LOG = LOGGER.isLoggable(ErrorManager.INFORMATIONAL);
55     
56     private static RegisterDerby reg=null;
57     
58     /** Derby server process */
59     static Process JavaDoc process = null;
60     
61     /** Creates a new instance of RegisterDerby */
62     private RegisterDerby() {
63     }
64     
65     public static synchronized RegisterDerby getDefault(){
66         if (reg==null)
67             reg= new RegisterDerby();
68         return reg;
69     }
70     
71     /**
72      * Whether this runtime accepts this connection string.
73      */

74     public boolean acceptsDatabaseURL(String JavaDoc url){
75         return url.trim().startsWith("jdbc:derby://localhost"); // NOI18N
76
}
77     
78     /**
79      * Is database server up and running.
80      */

81     public boolean isRunning(){
82         if (process!=null){
83             try{
84                 int e = process.exitValue();
85                 process=null;
86             } catch (IllegalThreadStateException JavaDoc e){
87                 //not exited yet...it's ok
88

89             }
90         }
91         return (process!=null);
92         
93     }
94     
95     public String JavaDoc getJDBCDriverClass() {
96         return DerbyOptions.DRIVER_CLASS_NET;
97     }
98     
99     /**
100      * Can the database be started from inside the IDE?
101      */

102     public boolean canStart(){
103         // issue 81619: should only try to start if the location is set
104
return DerbyOptions.getDefault().getLocation().length() > 0;
105     }
106     
107     /**
108      * Start the database server.
109      */

110     public void start(){
111         start(5000);//wait 5 seconds
112
}
113
114     private String JavaDoc getNetworkServerClasspath() {
115         return
116             Util.getDerbyFile("lib/derby.jar").getAbsolutePath() + File.pathSeparator +
117             Util.getDerbyFile("lib/derbytools.jar").getAbsolutePath() + File.pathSeparator +
118             Util.getDerbyFile("lib/derbynet.jar").getAbsolutePath(); // NOI18N
119
}
120     
121     /**
122      * Returns the registered Derby driver.
123      */

124     private JDBCDriver getRegisteredDerbyDriver() {
125         JDBCDriver[] drvs = JDBCDriverManager.getDefault().getDrivers(DerbyOptions.DRIVER_CLASS_NET);
126         if (drvs.length > 0) {
127             return drvs[0];
128         }
129         return null;
130     }
131     
132     public int getPort() {
133         return 1527;
134     }
135     
136     /** Posts the creation of the new database to request processor.
137      */

138     void postCreateNewDatabase(final String JavaDoc databaseName, final String JavaDoc user, final String JavaDoc password) throws Exception JavaDoc {
139         // DerbyDatabases.createDatabase would start the database too, but
140
// doing it beforehand to avoid having two progress bars running
141
ensureStarted();
142         
143         RequestProcessor.getDefault().post(new Runnable JavaDoc() {
144             public void run () {
145                 try {
146                 ProgressHandle ph = ProgressHandleFactory.createHandle(NbBundle.getMessage(
147                         RegisterDerby.class, "MSG_CreatingDBProgressLabel", databaseName));
148                 ph.start();
149                     try {
150                         DerbyDatabases.createDatabase(databaseName, user, password);
151                     } finally {
152                         ph.finish();
153                     }
154                 }
155                 catch (Exception JavaDoc e) {
156                     ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
157                     String JavaDoc message = NbBundle.getMessage(RegisterDerby.class, "ERR_CreateDatabase", e.getMessage());
158                     Util.showInformation(message);
159                 }
160             }
161         });
162     }
163     
164     private String JavaDoc getDerbySystemHome() {
165         // return System.getProperty("netbeans.user") + File.separator + "derby";
166
return DerbyOptions.getDefault().getSystemHome();
167     }
168     
169     private void createDerbyPropertiesFile() {
170         File JavaDoc derbyProperties = new File JavaDoc(getDerbySystemHome(), "derby.properties");
171         if (derbyProperties.exists())
172             return;
173         Properties JavaDoc derbyProps = new Properties JavaDoc();
174         // fill it
175
if (Utilities.isMac()) {
176             derbyProps.setProperty("derby.storage.fileSyncTransactionLog", "true");
177         }
178
179         // write it out
180
OutputStream JavaDoc fileos = null;
181         try {
182             File JavaDoc derbyPropertiesParent = derbyProperties.getParentFile();
183             derbyPropertiesParent.mkdirs();
184             fileos = new FileOutputStream JavaDoc(derbyProperties);
185             derbyProps.store(fileos, NbBundle.getMessage(RegisterDerby.class, "MSG_DerbyPropsFile"));
186         } catch (IOException JavaDoc ex) {
187             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
188         } finally {
189             if (fileos != null) {
190                 try {
191                     fileos.close();
192                 } catch (IOException JavaDoc ex) {
193                     ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
194                 }
195             }
196         }
197         
198     }
199     
200     private File JavaDoc getInstallLocation() {
201         String JavaDoc location = DerbyOptions.getDefault().getLocation();
202         if (location.equals("")) { // NOI18N
203
return null;
204         }
205         return new File JavaDoc(location);
206     }
207             
208     private String JavaDoc[] getEnvironment() {
209         String JavaDoc location = DerbyOptions.getDefault().getLocation();
210         if (location.equals("")) { // NOI18N
211
return null;
212         }
213         return new String JavaDoc[] { "DERBY_INSTALL=" + location }; // NOI18N
214
}
215     
216     private JavaPlatform getJavaPlatform() {
217         JavaPlatformManager jpm = JavaPlatformManager.getDefault();
218         return jpm.getDefaultPlatform();
219     }
220     
221     /**
222      * Start the database server, and wait some time (in milliseconds) to make sure the server is active.
223      */

224     private void start(int waitTime){
225         if (process!=null){// seems to be already running?
226
stop();
227         }
228         if (!Util.hasInstallLocation()) {
229             Util.showInformation(NbBundle.getMessage(RegisterDerby.class, "MSG_DerbyLocationIncorrect"));
230             return;
231         }
232         try {
233             ExecSupport ee= new ExecSupport();
234             ee.setStringToLookFor("" + getPort());
235             FileObject javaFO = getJavaPlatform().findTool("java");
236             if (javaFO == null)
237                 throw new Exception JavaDoc (NbBundle.getMessage(RegisterDerby.class, "EXC_JavaExecutableNotFound"));
238             String JavaDoc java = FileUtil.toFile(javaFO).getAbsolutePath();
239             
240             // create the derby.properties file
241
createDerbyPropertiesFile();
242             
243             // java -Dderby.system.home="<userdir/derby>" -classpath
244
// "<DERBY_INSTALL>/lib/derby.jar:<DERBY_INSTALL>/lib/derbytools.jar:<DERBY_INSTALL>/lib/derbynet.jar"
245
// org.apache.derby.drda.NetworkServerControl start
246
NbProcessDescriptor desc = new NbProcessDescriptor(
247               java,
248               "-Dderby.system.home=\"" + getDerbySystemHome() + "\" " +
249               "-classpath \"" + getNetworkServerClasspath() + "\"" +
250               " org.apache.derby.drda.NetworkServerControl start"
251             );
252             if (LOG) {
253                 LOGGER.log(ErrorManager.INFORMATIONAL, "Running " + desc.getProcessName() + " " + desc.getArguments());
254             }
255             process = desc.exec (
256                 null,
257                 getEnvironment(),
258                 true,
259                 getInstallLocation()
260             );
261
262             ee.displayProcessOutputs(process,NbBundle.getMessage(StartAction.class, "LBL_outputtab"));
263             if (waitTime > 0){
264                 ee.waitForMessage(NbBundle.getMessage(RegisterDerby.class, "MSG_StartingDerby"),
265                     waitTime); // to make sure the server is up and running
266
//Thread.currentThread().sleep(waitTime); // to make sure the server is up and running
267
}
268             
269         } catch (Exception JavaDoc e) {
270             Util.showInformation(e.getLocalizedMessage());
271         }
272     }
273     
274     /**
275      * Stop the database server.
276      */

277     public void stop(){
278         try {
279             if (process==null){//nothing to stop...
280
return;
281             }
282             //BufferedWriter processIn = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
283
//processIn.write("q\ny\n");
284
//processIn.flush();
285
String JavaDoc java = FileUtil.toFile(getJavaPlatform().findTool("java")).getAbsolutePath();
286             if (java == null)
287                 throw new Exception JavaDoc (NbBundle.getMessage(RegisterDerby.class, "EXC_JavaExecutableNotFound"));
288             // java -Dderby.system.home="<userdir/derby>" -classpath
289
// "<DERBY_INSTALL>/lib/derby.jar:<DERBY_INSTALL>/lib/derbytools.jar:<DERBY_INSTALL>/lib/derbynet.jar"
290
// org.apache.derby.drda.NetworkServerControl shutdown
291
NbProcessDescriptor desc = new NbProcessDescriptor(
292               java,
293               "-Dderby.system.home=\"" + getDerbySystemHome() + "\" " +
294               "-classpath \"" + getNetworkServerClasspath() + "\"" +
295               " org.apache.derby.drda.NetworkServerControl shutdown"
296             );
297             if (LOG) {
298                 LOGGER.log(ErrorManager.INFORMATIONAL, "Running " + desc.getProcessName() + " " + desc.getArguments());
299             }
300             Process JavaDoc shutwownProcess = desc.exec (
301                 null,
302                 getEnvironment(),
303                 true,
304                 getInstallLocation()
305             );
306             shutwownProcess.waitFor();
307
308             process.destroy();
309         }
310         catch (Exception JavaDoc e) {
311             Util.showInformation(e.getMessage());
312         }
313         finally {
314             process=null;
315         }
316     }
317     
318     public void ensureStarted() {
319         if (!isRunning() && canStart()) {
320             start();
321         }
322     }
323     
324     
325 }
326
Popular Tags