KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > j2ee > oc4j > config > OC4JDatasourceManager


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.j2ee.oc4j.config;
21
22 import java.io.File JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.util.HashSet JavaDoc;
25 import java.util.Iterator JavaDoc;
26 import java.util.Set JavaDoc;
27 import javax.enterprise.deploy.spi.DeploymentManager JavaDoc;
28 import javax.enterprise.deploy.spi.exceptions.ConfigurationException JavaDoc;
29 import javax.management.MBeanServerConnection JavaDoc;
30 import javax.management.ObjectInstance JavaDoc;
31 import javax.management.ObjectName JavaDoc;
32 import org.netbeans.modules.j2ee.deployment.common.api.Datasource;
33 import org.netbeans.modules.j2ee.deployment.common.api.DatasourceAlreadyExistsException;
34 import org.netbeans.modules.j2ee.deployment.plugins.api.DatasourceManager;
35 import org.netbeans.modules.j2ee.oc4j.OC4JDeploymentManager;
36 import org.netbeans.modules.j2ee.oc4j.config.gen.ConnectionPool;
37 import org.netbeans.modules.j2ee.oc4j.config.gen.DataSources;
38 import org.netbeans.modules.j2ee.oc4j.config.gen.ManagedDataSource;
39 import org.netbeans.modules.j2ee.oc4j.config.gen.NativeDataSource;
40 import org.netbeans.modules.j2ee.oc4j.ide.OC4JErrorManager;
41 import org.netbeans.modules.j2ee.oc4j.util.OC4JPluginUtils;
42 import org.openide.ErrorManager;
43 import org.openide.filesystems.FileObject;
44 import org.openide.filesystems.FileUtil;
45 import org.openide.util.NbBundle;
46
47 /**
48  *
49  * @author Michal Mocnak
50  */

51 public class OC4JDatasourceManager implements DatasourceManager {
52     
53     private static final String JavaDoc DATA_SOURCES_XML = "data-sources.xml"; // NOI18N
54
private static final String JavaDoc CONFIG_DIR = File.separator + "j2ee" + File.separator +
55             "home" + File.separator + "config"; // NOI18N
56

57     // server's deployent manager
58
private OC4JDeploymentManager dm;
59     
60     // server's deploy dir
61
private FileObject serverDir;
62     
63     /** Creates a new instance of OC4JDatasourceManager */
64     public OC4JDatasourceManager(DeploymentManager JavaDoc dm) {
65         if (!(dm instanceof OC4JDeploymentManager)) {
66             throw new IllegalArgumentException JavaDoc("Only OC4JDeplomentManager is supported"); //NOI18N
67
}
68         
69         this.dm = (OC4JDeploymentManager) dm;
70         
71         serverDir = FileUtil.toFileObject(new File JavaDoc(this.dm.getProperties().getOC4JHomeLocation()));
72     }
73     
74     public Set JavaDoc<Datasource> getDatasources() {
75         if(OC4JPluginUtils.isLocalServer(dm.getInstanceProperties()))
76             return getLocalDatasources();
77         
78         return getRemoteDatasources();
79     }
80     
81     public void deployDatasources(Set JavaDoc<Datasource> datasources) throws ConfigurationException JavaDoc,
82             DatasourceAlreadyExistsException {
83         // Get deployed datasources
84
Set JavaDoc<Datasource> deployedDS = getDatasources();
85         
86         for (Datasource d : datasources) {
87             if(deployedDS.contains(d))
88                 continue;
89             
90             OC4JDatasource ds = (OC4JDatasource) d;
91             
92             try {
93                 String JavaDoc cpName = ds.getJndiName() + " Connection Pool";
94                 String JavaDoc cpClazz = ds.getDriverClassName();
95                 String JavaDoc cpUsername = ds.getUsername();
96                 String JavaDoc cpPassword = ds.getPassword();
97                 String JavaDoc cpUrl = ds.getUrl();
98                 
99                 // Connection pool deployment
100
deployConnectionPool(cpName, cpClazz, cpUsername, cpPassword, cpUrl);
101                 
102                 String JavaDoc mdsJndiName = ds.getJndiName();
103                 Integer JavaDoc mdsIdleTimeout = new Integer JavaDoc(ds.getIdleTimeoutMinutes());
104                 
105                 // Managed data source deployment
106
deployManagedDataSource(mdsJndiName, cpName, mdsIdleTimeout);
107                 
108             } catch(Exception JavaDoc e) {
109                 OC4JErrorManager.getInstance(dm).error(dm.getUri(), e, OC4JErrorManager.GENERIC_FAILURE);
110             }
111         }
112     }
113     
114     /**
115      * Deploy a connection pool into the server
116      *
117      * @param name connetion pool name
118      * @param clazz driver class name
119      * @param username username to access the database
120      * @param password password to access the database
121      * @param url connection url
122      */

123     public void deployConnectionPool(String JavaDoc name, String JavaDoc clazz, String JavaDoc username, String JavaDoc password, String JavaDoc url) {
124         if (null == name || null == clazz || null == username ||
125                 null == password || null == url)
126             throw new NullPointerException JavaDoc();
127         
128         try {
129             // Checks if the driver exists in the server
130
if (OC4JPluginUtils.isLocalServer(dm.getInstanceProperties()) &&
131                     !OC4JPluginUtils.checkClass(clazz, dm))
132                 return;
133             
134             // Creating environment
135
MBeanServerConnection JavaDoc server = dm.getJMXConnector();
136             
137             // Checks if the connection pool exists in the server
138
Iterator JavaDoc i = server.queryMBeans(new ObjectName JavaDoc("oc4j:j2eeType=JDBCResource,*"), null).iterator();
139             
140             while(i.hasNext()) {
141                 ObjectName JavaDoc elem = ((ObjectInstance JavaDoc) i.next()).getObjectName();
142                 String JavaDoc s = elem.getKeyProperty("name").substring(1, elem.getKeyProperty("name").length()-1);
143                 
144                 if (name.equals(s))
145                     return;
146             }
147             
148             Iterator JavaDoc j = server.queryMBeans(new ObjectName JavaDoc("oc4j:j2eeType=J2EEApplication,name=default,J2EEServer=standalone"), null).iterator();
149             ObjectName JavaDoc elem = ((ObjectInstance JavaDoc) j.next()).getObjectName();
150             
151             // Connection pool deployment
152
server.invoke(elem, "createJDBCConnectionPool", new Object JavaDoc[] {
153                 name, clazz, username, password, url}, new String JavaDoc[] {
154                 "java.lang.String",
155                 "java.lang.String",
156                 "java.lang.String",
157                 "java.lang.String",
158                 "java.lang.String"});
159         } catch (Exception JavaDoc e) {
160             OC4JErrorManager.getInstance(dm).error(dm.getUri(), e, OC4JErrorManager.GENERIC_FAILURE);
161         }
162     }
163     
164     /**
165      * Deploy a managed data source into the server
166      *
167      * @param jndiName jndi name of the resourse
168      * @param connectionPoolName connection pool name on which it will be mapped
169      * @param idleTimeout timeout value
170      */

171     public void deployManagedDataSource(String JavaDoc jndiName, String JavaDoc connectionPoolName, Integer JavaDoc idleTimeout) {
172         if (null == jndiName || null == connectionPoolName || null == idleTimeout)
173             throw new NullPointerException JavaDoc();
174         
175         try {
176             // Creating environment
177
MBeanServerConnection JavaDoc server = dm.getJMXConnector();
178             
179             // Checks if the Managed Data Source exists in the server
180
Iterator JavaDoc i = server.queryMBeans(new ObjectName JavaDoc("oc4j:j2eeType=JDBCDataSource,*"), null).iterator();
181             
182             while(i.hasNext()) {
183                 ObjectName JavaDoc elem = ((ObjectInstance JavaDoc) i.next()).getObjectName();
184                 String JavaDoc name = elem.getKeyProperty("name").substring(1, elem.getKeyProperty("name").length()-1);
185                 String JavaDoc pool = elem.getKeyProperty("JDBCResource").substring(1, elem.getKeyProperty("JDBCResource").length()-1);
186                 
187                 if(pool.length() == 0)
188                     continue;
189                 
190                 String JavaDoc s = (String JavaDoc) server.getAttribute(elem, "jndiName");
191                 
192                 if (jndiName.equals(s) || jndiName.equals(name))
193                     return;
194             }
195             
196             // Checks if the mapped connection pool exists in the server
197
Iterator JavaDoc j = server.queryMBeans(new ObjectName JavaDoc("oc4j:j2eeType=JDBCResource,name=\"" + connectionPoolName + "\",*"), null).iterator();
198             
199             if (!j.hasNext())
200                 return;
201             
202             Iterator JavaDoc k = server.queryMBeans(new ObjectName JavaDoc("oc4j:j2eeType=J2EEApplication,name=default,J2EEServer=standalone"), null).iterator();
203             ObjectName JavaDoc elem = ((ObjectInstance JavaDoc) k.next()).getObjectName();
204             
205             // Managed data source deployment
206
server.invoke(elem, "createManagedDataSource", new Object JavaDoc[] {
207                 jndiName, "", "", jndiName, idleTimeout, connectionPoolName, "",
208                 ""}, new String JavaDoc[] {
209                 "java.lang.String",
210                 "java.lang.String",
211                 "java.lang.String",
212                 "java.lang.String",
213                 "java.lang.Integer",
214                 "java.lang.String",
215                 "java.lang.String",
216                 "java.lang.String",});
217         } catch(Exception JavaDoc e) {
218             OC4JErrorManager.getInstance(dm).error(dm.getUri(), e, OC4JErrorManager.GENERIC_FAILURE);
219         }
220     }
221     
222     /**
223      * Undeploy a native data source from the server
224      *
225      * @param name native data source name
226      */

227     public void undeployNativeDataSource(String JavaDoc name) {
228         if (null == name)
229             throw new NullPointerException JavaDoc();
230         
231         try {
232             // Creating environment
233
MBeanServerConnection JavaDoc server = dm.getJMXConnector();
234             
235             Iterator JavaDoc i = server.queryMBeans(new ObjectName JavaDoc("oc4j:j2eeType=J2EEApplication,name=default,J2EEServer=standalone"), null).iterator();
236             ObjectName JavaDoc elem = ((ObjectInstance JavaDoc) i.next()).getObjectName();
237             
238             // Native Data Source undeployemnt
239
server.invoke(elem, "removeNativeDataSource", new Object JavaDoc[] {
240                 name,}, new String JavaDoc[] {"java.lang.String"});
241         } catch (Exception JavaDoc e) {
242             OC4JErrorManager.getInstance(dm).error(dm.getUri(), e, OC4JErrorManager.GENERIC_FAILURE);
243         }
244     }
245     
246     public void undeployManagedDataSource(String JavaDoc name) {
247         if (null == name)
248             throw new NullPointerException JavaDoc();
249         
250         try {
251             // Creating environment
252
MBeanServerConnection JavaDoc server = dm.getJMXConnector();
253             
254             Iterator JavaDoc i = server.queryMBeans(new ObjectName JavaDoc("oc4j:j2eeType=J2EEApplication,name=default,J2EEServer=standalone"), null).iterator();
255             ObjectName JavaDoc elem = ((ObjectInstance JavaDoc) i.next()).getObjectName();
256             
257             // Managed Data Source undeployemnt
258
server.invoke(elem, "removeManagedDataSource", new Object JavaDoc[] {
259                 name,}, new String JavaDoc[] {"java.lang.String"});
260         } catch (Exception JavaDoc e) {
261             OC4JErrorManager.getInstance(dm).error(dm.getUri(), e, OC4JErrorManager.GENERIC_FAILURE);
262         }
263     }
264     
265     public void undeployConnectionPool(String JavaDoc name) {
266         if (null == name)
267             throw new NullPointerException JavaDoc();
268         
269         try {
270             // Creating environment
271
MBeanServerConnection JavaDoc server = dm.getJMXConnector();
272             
273             Iterator JavaDoc i = server.queryMBeans(new ObjectName JavaDoc("oc4j:j2eeType=J2EEApplication,name=default,J2EEServer=standalone"), null).iterator();
274             ObjectName JavaDoc elem = ((ObjectInstance JavaDoc) i.next()).getObjectName();
275             
276             // Undeploying asociated managed data sources
277
Iterator JavaDoc j = server.queryMBeans(new ObjectName JavaDoc("oc4j:j2eeType=JDBCResource,name=\"" + name + "\",*"), null).iterator();
278             ObjectName JavaDoc pool = ((ObjectInstance JavaDoc) j.next()).getObjectName();
279             String JavaDoc[] array = (String JavaDoc[]) server.getAttribute(pool, "jdbcDataSources");
280             
281             for (String JavaDoc s : array) {
282                 String JavaDoc dsName = new ObjectName JavaDoc(s).getKeyProperty("name");
283                 
284                 // remove quotes
285
dsName = dsName.substring(1, dsName.length() - 1);
286                 
287                 // undeploy managed data source
288
undeployManagedDataSource(dsName);
289             }
290             
291             // Connection pool undeployemnt
292
server.invoke(elem, "removeDataSourceConnectionPool", new Object JavaDoc[] {
293                 name,}, new String JavaDoc[] {"java.lang.String"});
294         } catch (Exception JavaDoc e) {
295             OC4JErrorManager.getInstance(dm).error(dm.getUri(), e, OC4JErrorManager.GENERIC_FAILURE);
296         }
297     }
298     
299     private Set JavaDoc<Datasource> getLocalDatasources() {
300         
301         Set JavaDoc<Datasource> globalDS = new HashSet JavaDoc<Datasource>();
302         
303         if (serverDir == null || !serverDir.isValid() || !serverDir.isFolder() || !serverDir.canRead()) {
304             ErrorManager.getDefault().log(ErrorManager.USER,
305                     NbBundle.getMessage(OC4JDatasourceManager.class, "ERR_WRONG_DEPLOY_DIR"));
306             return globalDS;
307         }
308         
309         File JavaDoc dsFile = new File JavaDoc(FileUtil.toFile(serverDir), CONFIG_DIR + File.separator + DATA_SOURCES_XML);
310         
311         if(dsFile.exists()) {
312             try {
313                 DataSources datasources = DataSources.createGraph(dsFile);
314                 
315                 NativeDataSource nds[] = datasources.getNativeDataSource();
316                 for (NativeDataSource ds : nds) {
317                     if (ds.getJndiName().length() > 0) {
318                         globalDS.add(new OC4JDatasource(
319                                 ds.getJndiName(),
320                                 ds.getUrl(),
321                                 ds.getUser(),
322                                 ds.getPassword(),
323                                 ds.getDataSourceClass()));
324                     }
325                 }
326                 
327                 ManagedDataSource mds[] = datasources.getManagedDataSource();
328                 for (ManagedDataSource ds : mds) {
329                     if (ds.getJndiName().length() > 0) {
330                         String JavaDoc cpName = ds.getConnectionPoolName();
331                         ConnectionPool[] cps = datasources.getConnectionPool();
332                         for (ConnectionPool cp : cps) {
333                             if(cpName.equals(cp.getName())) {
334                                 globalDS.add(new OC4JDatasource(
335                                         ds.getJndiName(),
336                                         cp.getConnectionFactory().getUrl(),
337                                         cp.getConnectionFactory().getUser(),
338                                         cp.getConnectionFactory().getPassword(),
339                                         cp.getConnectionFactory().getFactoryClass()));
340                             }
341                         }
342                     }
343                 }
344             } catch(IOException JavaDoc ex) {
345                 ErrorManager.getDefault().log(ErrorManager.INFORMATIONAL, ex.getMessage());
346             }
347         }
348         
349         return globalDS;
350     }
351     
352     private Set JavaDoc<Datasource> getRemoteDatasources() {
353         Set JavaDoc<Datasource> datasources = new HashSet JavaDoc<Datasource>();
354         
355         MBeanServerConnection JavaDoc serverConnection = dm.getJMXConnector();
356         
357         try {
358             Iterator JavaDoc i = serverConnection.queryMBeans(new ObjectName JavaDoc("oc4j:j2eeType=JDBCDataSource,*"), null).iterator();
359             while(i.hasNext()) {
360                 ObjectName JavaDoc dsElem = ((ObjectInstance JavaDoc) i.next()).getObjectName();
361                 
362                 String JavaDoc jndiName = (String JavaDoc) serverConnection.getAttribute(dsElem, "jndiName");
363                 String JavaDoc pool = dsElem.getKeyProperty("JDBCResource").substring(1, dsElem.getKeyProperty("JDBCResource").length()-1);
364                 String JavaDoc username = (String JavaDoc) serverConnection.getAttribute(dsElem, "user");
365                 String JavaDoc password = (String JavaDoc) serverConnection.getAttribute(dsElem, "password");
366                 
367                 Iterator JavaDoc j = serverConnection.queryMBeans(new ObjectName JavaDoc("oc4j:j2eeType=JDBCResource,name=\""+pool+"\",*"), null).iterator();
368                 
369                 if(!j.hasNext())
370                     continue;
371                 
372                 ObjectName JavaDoc poolElem = ((ObjectInstance JavaDoc) j.next()).getObjectName();
373                 
374                 String JavaDoc url = (String JavaDoc) serverConnection.getAttribute(poolElem, "url");
375                 String JavaDoc factoryClassName = (String JavaDoc) serverConnection.getAttribute(poolElem, "factoryClass");
376                 
377                 Datasource ds = new OC4JDatasource(jndiName, url, username, password, factoryClassName);
378                 
379                 datasources.add(ds);
380             }
381         } catch(Exception JavaDoc ex) {
382             // Nothing to do
383
}
384         
385         return datasources;
386     }
387 }
Popular Tags