KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openejb > webadmin > main > CMPMappingBean


1 /**
2  * Redistribution and use of this software and associated documentation
3  * ("Software"), with or without modification, are permitted provided
4  * that the following conditions are met:
5  *
6  * 1. Redistributions of source code must retain copyright
7  * statements and notices. Redistributions must also contain a
8  * copy of this document.
9  *
10  * 2. Redistributions in binary form must reproduce the
11  * above copyright notice, this list of conditions and the
12  * following disclaimer in the documentation and/or other
13  * materials provided with the distribution.
14  *
15  * 3. The name "OpenEJB" must not be used to endorse or promote
16  * products derived from this Software without prior written
17  * permission of The OpenEJB Group. For written permission,
18  * please contact dev@openejb.org.
19  *
20  * 4. Products derived from this Software may not be called "OpenEJB"
21  * nor may "OpenEJB" appear in their names without prior written
22  * permission of The OpenEJB Group. OpenEJB is a registered
23  * trademark of The OpenEJB Group.
24  *
25  * 5. Due credit should be given to the OpenEJB Project
26  * (http://www.openejb.org/).
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE OPENEJB GROUP AND CONTRIBUTORS
29  * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
30  * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
31  * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
32  * THE OPENEJB GROUP OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
33  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
34  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
35  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
37  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
38  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
39  * OF THE POSSIBILITY OF SUCH DAMAGE.
40  *
41  * Copyright 2001 (C) The OpenEJB Group. All Rights Reserved.
42  *
43  * $Id: CMPMappingBean.java 2167 2005-09-19 22:15:13Z jcscoobyrs $
44  */

45 package org.openejb.webadmin.main;
46
47 import java.io.File JavaDoc;
48 import java.io.FileInputStream JavaDoc;
49 import java.io.FileOutputStream JavaDoc;
50 import java.io.IOException JavaDoc;
51 import java.io.ObjectInputStream JavaDoc;
52 import java.io.ObjectOutputStream JavaDoc;
53 import java.io.PrintWriter JavaDoc;
54 import java.util.Properties JavaDoc;
55
56 import javax.ejb.Handle JavaDoc;
57 import javax.naming.Context JavaDoc;
58 import javax.naming.InitialContext JavaDoc;
59 import javax.rmi.PortableRemoteObject JavaDoc;
60
61 import org.exolab.castor.jdo.conf.Database;
62 import org.exolab.castor.jdo.conf.DatabaseChoice;
63 import org.exolab.castor.jdo.conf.Driver;
64 import org.exolab.castor.jdo.conf.Jndi;
65 import org.exolab.castor.jdo.conf.Mapping;
66 import org.exolab.castor.jdo.conf.Param;
67 import org.exolab.castor.xml.ValidationException;
68 import org.openejb.core.EnvProps;
69 import org.openejb.loader.SystemInstance;
70 import org.openejb.util.FileUtils;
71 import org.openejb.webadmin.HttpRequest;
72 import org.openejb.webadmin.HttpResponse;
73 import org.openejb.webadmin.WebAdminBean;
74
75 /**
76  * @author <a HREF="mailto:tim_urberg@yahoo.com">Tim Urberg</a>
77  */

78 public class CMPMappingBean extends WebAdminBean {
79     /** the handle file name */
80     private static final String JavaDoc HANDLE_FILE = System.getProperty("file.separator") + "configurationHandle.obj";
81
82     /** Creates a new instance of HomeBean */
83     public void ejbCreate() {
84         this.section = "CMPMapping";
85     }
86
87     /** called before any content is written to the browser
88      * @param request the http request
89      * @param response the http response
90      * @throws IOException if an exception is thrown
91      */

92     public void preProcess(HttpRequest request, HttpResponse response) throws IOException JavaDoc {}
93
94     /** called after all content is written to the browser
95      * @param request the http request
96      * @param response the http response
97      * @throws IOException if an exception is thrown
98      */

99     public void postProcess(HttpRequest request, HttpResponse response) throws IOException JavaDoc {}
100
101     /** Write the TITLE of the HTML document. This is the part
102      * that goes into the <code>&lt;head&gt;&lt;title&gt;
103      * &lt;/title&gt;&lt;/head&gt;</code> tags
104      *
105      * @param body the output to write to
106      * @exception IOException of an exception is thrown
107      *
108      */

109     public void writeHtmlTitle(PrintWriter JavaDoc body) throws IOException JavaDoc {
110         body.println(HTML_TITLE);
111     }
112
113     /** Write the title of the page. This is displayed right
114      * above the main block of content.
115      *
116      * @param body the output to write to
117      * @exception IOException if an exception is thrown
118      */

119     public void writePageTitle(PrintWriter JavaDoc body) throws IOException JavaDoc {
120         body.println("Container Managed Persistance Mapping");
121     }
122
123     /** Write the sub items for this bean in the left navigation bar of
124      * the page. This should look somthing like the one below:
125      *
126      * <code>
127      * &lt;tr&gt;
128      * &lt;td valign="top" align="left"&gt;
129      * &lt;a HREF="system?show=deployments"&gt;&lt;span class="subMenuOff"&gt;
130      * &nbsp;&nbsp;&nbsp;Deployments
131      * &lt;/span&gt;
132      * &lt;/a&gt;&lt;/td&gt;
133      * &lt;/tr&gt;
134      * </code>
135      *
136      * Alternately, the bean can use the method formatSubMenuItem(..) which
137      * will create HTML like the one above
138      *
139      * @param body the output to write to
140      * @exception IOException if an exception is thrown
141      *
142      */

143     public void writeSubMenuItems(PrintWriter JavaDoc body) throws IOException JavaDoc {}
144
145     /**
146      * writes the main body content to the broswer. This content is inside
147      * a <code>&lt;p&gt;</code> block
148      *
149      * @param body the output to write to
150      * @exception IOException if an exception is thrown
151      */

152     public void writeBody(PrintWriter JavaDoc body) throws IOException JavaDoc {
153 // CMPMappingDataObject dataObject;
154
// String submitDBInfo = request.getFormParameter(CMPMappingWriter.FORM_FIELD_SUBMIT_DB_INFO);
155
// String handleFile = request.getFormParameter(CMPMappingWriter.FORM_FIELD_HANDLE_FILE);
156
//
157
// //get or create a new handle
158
// if (handleFile == null) {
159
// dataObject = getCMPMappingDataObject();
160
// handleFile = createHandle(dataObject);
161
// } else {
162
// dataObject = getHandle(handleFile);
163
// }
164
//
165
// //check for which type of action we're taking
166
// if (submitDBInfo != null && submitDatabaseInformation(body, dataObject, handleFile)) {
167
// CMPMappingWriter.printMappingInfo(body, handleFile, new MappingRoot());
168
// } else {
169
// CMPMappingWriter.printDBInfo(body, "", new DatabaseData(), handleFile);
170
// }
171

172         body.println("Coming soon...");
173     }
174
175     /**
176      * takes care of the submission of database information
177      */

178     private boolean submitDatabaseInformation(PrintWriter JavaDoc body, CMPMappingDataObject dataObject, String JavaDoc handleFile) throws IOException JavaDoc {
179         /* TODO:
180          * 1. Check to see if files exist
181          * 2. Validate required fields
182          */

183         DatabaseData databaseData = new DatabaseData();
184         databaseData.setDbEngine(request.getFormParameter(CMPMappingWriter.FORM_FIELD_DB_ENGINE));
185         databaseData.setDriverClass(request.getFormParameter(CMPMappingWriter.FORM_FIELD_DRIVER_CLASS));
186         databaseData.setDriverUrl(request.getFormParameter(CMPMappingWriter.FORM_FIELD_DRIVER_URL));
187         databaseData.setFileName(request.getFormParameter(CMPMappingWriter.FORM_FIELD_FILE_NAME));
188         databaseData.setJndiName(request.getFormParameter(CMPMappingWriter.FORM_FIELD_JNDI_NAME));
189         databaseData.setPassword(request.getFormParameter(CMPMappingWriter.FORM_FIELD_PASSWORD));
190         databaseData.setUsername(request.getFormParameter(CMPMappingWriter.FORM_FIELD_USERNAME));
191
192         //validate the required fields
193
try {
194             databaseData.validate();
195         } catch (ValidationException e) {
196             CMPMappingWriter.printDBInfo(body, e.getMessage(), databaseData, handleFile);
197             return false;
198         }
199
200         //assemble the file names
201
String JavaDoc path =
202             SystemInstance.get().getBase().getDirectory("conf").getAbsolutePath()
203                 + System.getProperty("file.separator")
204                 + databaseData.getFileName();
205
206         //create the file paths and names
207
String JavaDoc localDBFileName = path + ".cmp_local_database.xml";
208         String JavaDoc globalDBFileName = path + ".cmp_global_database.xml";
209         String JavaDoc mappingFileName = path + ".cmp_or_mapping.xml";
210
211         //set the standard variables for the global and local databases
212
Database globalDatabase = new Database();
213         DatabaseChoice globalDatabaseChoice = new DatabaseChoice();
214         Database localDatabase = new Database();
215         DatabaseChoice localDatabaseChoice = new DatabaseChoice();
216         globalDatabase.setName(EnvProps.GLOBAL_TX_DATABASE);
217         globalDatabase.setEngine(databaseData.getDbEngine());
218         localDatabase.setName(EnvProps.LOCAL_TX_DATABASE);
219         localDatabase.setEngine(databaseData.getDbEngine());
220
221         //create and set the mapping for the db's
222
Mapping mapping = new Mapping();
223         mapping.setHref(mappingFileName);
224         globalDatabase.addMapping(mapping);
225         localDatabase.addMapping(mapping);
226
227         //set up the global specific fields
228
Jndi jndi = new Jndi();
229         jndi.setName(databaseData.getJndiName());
230         globalDatabaseChoice.setJndi(jndi);
231
232         //set up the local specific fields
233
Driver driver = new Driver();
234         Param userNameParam = new Param();
235         Param passwordParam = new Param();
236
237         //set up the user and password
238
userNameParam.setName("user");
239         userNameParam.setValue(databaseData.getUsername());
240         passwordParam.setName("password");
241         passwordParam.setValue(databaseData.getPassword());
242
243         //set up the driver
244
driver.setClassName(databaseData.getDriverClass());
245         driver.setUrl(databaseData.getDriverUrl());
246         driver.addParam(userNameParam);
247         driver.addParam(passwordParam);
248
249         localDatabaseChoice.setDriver(driver);
250         
251         localDatabase.setDatabaseChoice(localDatabaseChoice);
252         globalDatabase.setDatabaseChoice(globalDatabaseChoice);
253
254         //validate the two database types again just in case
255
try {
256             localDatabase.validate();
257             globalDatabase.validate();
258         } catch (ValidationException e) {
259             CMPMappingWriter.printDBInfo(body, e.getMessage(), databaseData, handleFile);
260             return false;
261         }
262
263         //here we want to move the jdbc driver over to the bin dir
264
File JavaDoc jdbcDriverSource = new File JavaDoc(request.getFormParameter(CMPMappingWriter.FORM_FIELD_JDBC_DRIVER));
265         String JavaDoc libDir =
266             SystemInstance.get().getBase().getDirectory("lib").getAbsolutePath()
267                 + System.getProperty("file.separator")
268                 + jdbcDriverSource.getName();
269         File JavaDoc destFile = new File JavaDoc(libDir);
270
271         //copy the file if it exists
272
if (jdbcDriverSource.isFile()) {
273             if (!destFile.exists() && !destFile.createNewFile()) {
274                 throw new IOException JavaDoc("Could not create file: " + libDir);
275             }
276             
277             FileUtils.copyFile(destFile, jdbcDriverSource);
278         }
279
280         //put the data into the data object
281
dataObject.setGlobalDatabase(globalDatabase);
282         dataObject.setGlobalDatabaseFileName(globalDBFileName);
283         dataObject.setLocalDatabase(localDatabase);
284         dataObject.setLocalDatabaseFileName(localDBFileName);
285         dataObject.setMappingRootFileName(mappingFileName);
286
287         //this is part of the mapping in the next section
288
//MappingRoot root = new MappingRoot();
289
//ClassMapping map = new ClassMapping();
290

291         return true;
292     }
293
294     /**
295      * gets an object reference and handle
296      *
297      * @param mappingData the object to create a handle from
298      * @return an absolute path of the handle file
299      * @throws IOException if the file cannot be created
300      */

301     private String JavaDoc createHandle(CMPMappingDataObject mappingData) throws IOException JavaDoc {
302         //write the handle out to a file
303
File JavaDoc myHandleFile = new File JavaDoc(FileUtils.createTempDirectory().getAbsolutePath() + HANDLE_FILE);
304         if (!myHandleFile.exists()) {
305             myHandleFile.createNewFile();
306         }
307
308         ObjectOutputStream JavaDoc objectOut = new ObjectOutputStream JavaDoc(new FileOutputStream JavaDoc(myHandleFile));
309         objectOut.writeObject(mappingData.getHandle()); //writes the handle to the file
310
objectOut.flush();
311         objectOut.close();
312
313         return myHandleFile.getAbsolutePath();
314     }
315
316     /**
317      * creates a new CMPMappingDataObject
318      *
319      * @return a new CMPMappingDataObject
320      * @throws IOException if the object cannot be created
321      */

322     private CMPMappingDataObject getCMPMappingDataObject() throws IOException JavaDoc {
323         Properties JavaDoc p = new Properties JavaDoc();
324         p.put(Context.INITIAL_CONTEXT_FACTORY, "org.openejb.core.ivm.naming.InitContextFactory");
325
326         //lookup the bean
327
try {
328             InitialContext JavaDoc ctx = new InitialContext JavaDoc(p);
329             Object JavaDoc obj = ctx.lookup("mapping/webadmin/CMPMappingData");
330             //create a new instance
331
CMPMappingDataHome home = (CMPMappingDataHome) PortableRemoteObject.narrow(obj, CMPMappingDataHome.class);
332             return home.create();
333         } catch (Exception JavaDoc e) {
334             throw new IOException JavaDoc(e.getMessage());
335         }
336     }
337
338     /**
339      * this method gets the handle
340      *
341      * @param handleFile the handle to the object
342      * @return the configuration data object
343      * @throws IOException if the file is not found
344      */

345     private CMPMappingDataObject getHandle(String JavaDoc handleFile) throws IOException JavaDoc {
346         File JavaDoc myHandleFile = new File JavaDoc(handleFile);
347
348         //get the object
349
ObjectInputStream JavaDoc objectIn = new ObjectInputStream JavaDoc(new FileInputStream JavaDoc(myHandleFile));
350         //get the handle
351
Handle JavaDoc mappingHandle;
352         try {
353             mappingHandle = (Handle JavaDoc) objectIn.readObject();
354             return (CMPMappingDataObject) mappingHandle.getEJBObject();
355         } catch (Exception JavaDoc e) {
356             throw new IOException JavaDoc(e.getMessage());
357         }
358     }
359 }
Popular Tags