KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > j2ee > sun > ide > sunresources > beans > ResourceConfigurator


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  * ResourceConfiguration.java
21  *
22  * Created on August 22, 2005, 12:43 PM
23  */

24
25 package org.netbeans.modules.j2ee.sun.ide.sunresources.beans;
26
27 import java.io.BufferedOutputStream JavaDoc;
28 import java.io.File JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.io.InputStream JavaDoc;
31 import java.io.FileInputStream JavaDoc;
32 import java.io.FileOutputStream JavaDoc;
33 import java.util.ArrayList JavaDoc;
34 import java.util.Arrays JavaDoc;
35 import java.util.Enumeration JavaDoc;
36 import java.util.HashMap JavaDoc;
37 import java.util.HashSet JavaDoc;
38 import java.util.Iterator JavaDoc;
39 import java.util.List JavaDoc;
40 import java.util.ResourceBundle JavaDoc;
41
42 import javax.enterprise.deploy.spi.DeploymentManager JavaDoc;
43 import org.netbeans.modules.j2ee.deployment.common.api.DatasourceAlreadyExistsException;
44 import org.netbeans.modules.j2ee.deployment.common.api.Datasource;
45
46 import org.openide.DialogDisplayer;
47 import org.openide.NotifyDescriptor;
48 import org.openide.ErrorManager;
49 import org.openide.util.RequestProcessor;
50 import org.netbeans.api.db.explorer.DatabaseConnection;
51
52 import org.netbeans.modules.j2ee.sun.api.ResourceConfiguratorInterface;
53 import org.netbeans.modules.j2ee.sun.dd.api.DDProvider;
54 import org.netbeans.modules.j2ee.sun.dd.api.serverresources.AdminObjectResource;
55 import org.netbeans.modules.j2ee.sun.dd.api.serverresources.ConnectorConnectionPool;
56 import org.netbeans.modules.j2ee.sun.dd.api.serverresources.ConnectorResource;
57 import org.netbeans.modules.j2ee.sun.dd.api.serverresources.Resources;
58 import org.netbeans.modules.j2ee.sun.dd.api.serverresources.JdbcResource;
59 import org.netbeans.modules.j2ee.sun.dd.api.serverresources.PropertyElement;
60 import org.netbeans.modules.j2ee.sun.dd.api.serverresources.JdbcConnectionPool;
61 import org.netbeans.modules.j2ee.sun.share.serverresources.SunDatasource;
62 import org.netbeans.modules.j2ee.sun.sunresources.beans.DatabaseUtils;
63
64 import org.netbeans.modules.j2ee.sun.sunresources.beans.Field;
65 import org.netbeans.modules.j2ee.sun.sunresources.beans.FieldGroup;
66 import org.netbeans.modules.j2ee.sun.sunresources.beans.FieldGroupHelper;
67 import org.netbeans.modules.j2ee.sun.sunresources.beans.FieldHelper;
68 import org.netbeans.modules.j2ee.sun.sunresources.beans.Wizard;
69 import org.netbeans.modules.j2ee.sun.sunresources.beans.WizardConstants;
70 import org.openide.filesystems.FileObject;
71 import org.openide.filesystems.FileUtil;
72
73 /**
74  *
75  * @author Nitya Doraisamy
76  */

77 public class ResourceConfigurator implements ResourceConfiguratorInterface {
78     
79     public static final String JavaDoc __JMSResource = "jms"; // NOI18N
80
public static final String JavaDoc __JMSConnectionFactory = "jms_CF"; // NOI18N
81
public static final String JavaDoc __JdbcConnectionPool = "connection-pool"; // NOI18N
82

83     public static final String JavaDoc __SunResourceExt = "sun-resource"; // NOI18N
84

85     private final static char BLANK = ' ';
86     private final static char DOT = '.';
87     private final static char[] ILLEGAL_FILENAME_CHARS = {'/', '\\', ':', '*', '?', '"', '<', '>', '|', ',', '=', ';' };
88     // private final static char[] ILLEGAL_RESOURCE_NAME_CHARS = {':', '*', '?', '"', '<', '>', '|', ',' };
89
private final static char REPLACEMENT_CHAR = '_';
90     private final static char DASH = '-';
91     
92     public static final String JavaDoc __ConnectionPool = "ConnectionPool"; // NOI18N
93
private static final String JavaDoc DATAFILE = "org/netbeans/modules/j2ee/sun/sunresources/beans/CPWizard.xml"; // NOI18N
94

95     private boolean showMsg = false;
96     private DeploymentManager JavaDoc currentDM = null;
97     
98     ResourceBundle JavaDoc bundle = ResourceBundle.getBundle("org.netbeans.modules.j2ee.sun.ide.sunresources.beans.Bundle");// NOI18N
99

100     /**
101      * Creates a new instance of ResourceConfigurator
102      */

103     public ResourceConfigurator() {
104     }
105     
106     public void setDeploymentManager(DeploymentManager JavaDoc dm) {
107         this.currentDM = dm;
108     }
109     
110     /** Returns whether or not the specific JMS resource alread exists.
111      *
112      * @param jndiName Jndi name identifying the JMS resource.
113      * @param dir Folder where the resources should be stored. Can be null,
114      * in which case this method will return false.
115      *
116      * @returns true if the resource exists in the resource, or false for all
117      * other possibilities.
118      */

119     public boolean isJMSResourceDefined(String JavaDoc jndiName, File JavaDoc dir) {
120         return resourceAlreadyDefined(jndiName, dir, __JMSResource);
121     }
122
123     /** Creates a new JMS resource with the specified values.
124      *
125      * @param jndiName jndi-name that identifies this JMS resource.
126      * @param msgDstnType type of message destination.
127      * @param msgDstnName name of the message destination.
128      * @param ejbName name of ejb.
129      * @param dir Folder where the resource should be stored. Should not be null.
130      */

131     public void createJMSResource(String JavaDoc jndiName, String JavaDoc msgDstnType, String JavaDoc msgDstnName, String JavaDoc ejbName, File JavaDoc dir) {
132         try {
133             Resources resources = DDProvider.getDefault().getResourcesGraph();
134             AdminObjectResource aoresource = resources.newAdminObjectResource();
135             aoresource.setJndiName(jndiName);
136             aoresource.setResType(msgDstnType);
137             aoresource.setResAdapter(WizardConstants.__JmsResAdapter);
138             aoresource.setEnabled("true"); // NOI18N
139
aoresource.setDescription(""); // NOI18N
140
PropertyElement prop = aoresource.newPropertyElement();
141             prop.setName("Name"); // NOI18N
142
prop.setValue(ejbName);
143             aoresource.addPropertyElement(prop);
144             resources.addAdminObjectResource(aoresource);
145             
146             createFile(dir, jndiName, __JMSResource, resources);
147             
148             resources = DDProvider.getDefault().getResourcesGraph();
149             ConnectorResource connresource = resources.newConnectorResource();
150             ConnectorConnectionPool connpoolresource = resources.newConnectorConnectionPool();
151             
152             String JavaDoc connectionFactoryJndiName= "jms/" + msgDstnName + "Factory"; // NOI18N
153
connresource.setJndiName(connectionFactoryJndiName);
154             connresource.setDescription("");
155             connresource.setEnabled("true");
156             connresource.setPoolName(connectionFactoryJndiName);
157
158             connpoolresource.setName(connectionFactoryJndiName);
159             connpoolresource.setResourceAdapterName(WizardConstants.__JmsResAdapter);
160     
161             if(msgDstnType.equals(WizardConstants.__QUEUE)) {
162                 connpoolresource.setConnectionDefinitionName(WizardConstants.__QUEUE_CNTN_FACTORY);
163             } else {
164                 if(msgDstnType.equals(WizardConstants.__TOPIC)) {
165                     connpoolresource.setConnectionDefinitionName(WizardConstants.__TOPIC_CNTN_FACTORY);
166                 } else {
167                     assert false; //control should never reach here
168
}
169             }
170             resources.addConnectorResource(connresource);
171             resources.addConnectorConnectionPool(connpoolresource);
172             
173             createFile(dir, jndiName, __JMSConnectionFactory, resources);
174         } catch(IOException JavaDoc ex) {
175             // XXX Report I/O Exception to the user. We should do a nicely formatted
176
// message identifying the problem.
177
ErrorManager.getDefault().notify(ErrorManager.EXCEPTION, ex);
178         }
179     }
180     
181     public void createJDBCDataSourceFromRef(String JavaDoc refName, String JavaDoc databaseInfo, File JavaDoc dir) {
182         /*try {
183             String name = refName;
184             if(databaseInfo != null) {
185                 String vendorName = convertToValidName(databaseInfo);
186                 if(vendorName != null) {
187                     name = vendorName;
188                 }
189                 
190                 if(vendorName.equals("derby_embedded")){ //NOI18N
191                     NotifyDescriptor d = new NotifyDescriptor.Message(bundle.getString("Err_UnSupportedDerby"), NotifyDescriptor.WARNING_MESSAGE); // NOI18N
192                     DialogDisplayer.getDefault().notify(d);
193                     return;
194                 }
195                 
196                 // Is connection pool already defined
197                 String poolName = generatePoolName(name, dir, databaseInfo);
198                 if(poolName == null) {
199                     if(resourceAlreadyDefined(refName, dir, __JdbcResource)) {
200                         return;
201                     } else {
202                         createJDBCResource(name, refName, databaseInfo, dir);
203                     }
204                 } else {
205                     name = poolName;
206                     createCPPoolResource(name, refName, databaseInfo, dir);
207                     createJDBCResource(name, refName, databaseInfo, dir);
208                 }
209             }
210         } catch(IOException ex) {
211             // XXX Report I/O Exception to the user. We should do a nicely formatted
212             // message identifying the problem.
213             ErrorManager.getDefault().notify(ErrorManager.EXCEPTION, ex);
214         }*/

215     }
216     
217     public String JavaDoc createJDBCDataSourceForCmp(String JavaDoc beanName, String JavaDoc databaseInfo, File JavaDoc dir) {
218         /*String name = "jdbc/" + beanName; // NOI18N
219         String jndiName = name;
220         try {
221             if(databaseInfo != null) {
222                 String vendorName = convertToValidName(databaseInfo);
223                 if(vendorName != null) {
224                     name = vendorName;
225                 }
226                 
227                 if(vendorName.equals("derby_embedded")){ //NOI18N
228                     NotifyDescriptor d = new NotifyDescriptor.Message(bundle.getString("Err_UnSupportedDerby"), NotifyDescriptor.WARNING_MESSAGE); // NOI18N
229                     DialogDisplayer.getDefault().notify(d);
230                     return null;
231                 }
232                 // Return if resource already defined
233                 String poolName = generatePoolName(name, dir, databaseInfo);
234                 if(poolName == null) {
235                     return null;
236                 } else {
237                     name = poolName;
238                 }
239
240                 jndiName = "jdbc/" + name;
241
242                 createCPPoolResource(name, jndiName, databaseInfo, dir);
243                 createJDBCResource(name, jndiName, databaseInfo, dir);
244
245                 if(this.showMsg) {
246                     String mess = MessageFormat.format(bundle.getString("LBL_UnSupportedDriver"), new Object [] { jndiName }); // NOI18N
247                     showInformation(mess);
248                     this.showMsg = false;
249                 }
250             }
251         } catch(IOException ex) {
252             // XXX Report I/O Exception to the user. We should do a nicely formatted
253             // message identifying the problem.
254             ErrorManager.getDefault().notify(ErrorManager.EXCEPTION, ex);
255         }
256         
257         return jndiName;
258          */

259         return null;
260     }
261     
262     // Utility methods needed in case of sun resource creations
263
private void createFile(File JavaDoc targetFolder, String JavaDoc beanName, String JavaDoc resourceType, Resources res) throws IOException JavaDoc {
264         //jdbc and jdo jndi names might be of format jdbc/ and jdo/
265
if(resourceType.indexOf("/") != -1) { // NOI18N
266
resourceType = resourceType.substring(0, resourceType.indexOf("/")) + "_" + // NOI18N
267
resourceType.substring(resourceType.indexOf("/")+1, resourceType.length()); // NOI18N
268
}
269         if(resourceType.indexOf("\\") != -1) { // NOI18N
270
resourceType = resourceType.substring(0, resourceType.indexOf("\\")) + "_" + // NOI18N
271
resourceType.substring(resourceType.indexOf("\\")+1, resourceType.length()); // NOI18N
272
}
273
274         ensureFolderExists(targetFolder);
275         String JavaDoc filename = getFileName(beanName, resourceType);
276         File JavaDoc resourceFile = new File JavaDoc(targetFolder, filename);
277
278         // XXX This will default to UTF-8 encoding (deep inside schema2beans).
279
// Is this acceptable or should this be upgraded to allow the encoding to
280
// be specified?
281
if(!resourceFile.exists()) {
282             res.write(new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(resourceFile)));
283         }
284     }
285     
286     private boolean isLegalFilename(String JavaDoc filename) {
287         for(int i = 0; i < ILLEGAL_FILENAME_CHARS.length; i++) {
288             if(filename.indexOf(ILLEGAL_FILENAME_CHARS[i]) >= 0) {
289                 return false;
290             }
291         }
292         
293         return true;
294     }
295     
296     private boolean isFriendlyFilename(String JavaDoc filename) {
297         if(filename.indexOf(BLANK) >= 0 || filename.indexOf(DOT) >= 0) {
298             return false;
299         }
300         
301         return isLegalFilename(filename);
302     }
303     
304     private String JavaDoc makeLegalFilename(String JavaDoc filename) {
305         for(int i = 0; i < ILLEGAL_FILENAME_CHARS.length; i++) {
306             filename = filename.replace(ILLEGAL_FILENAME_CHARS[i], REPLACEMENT_CHAR);
307         }
308         
309         return filename;
310     }
311     
312     private String JavaDoc makeShorterLegalFilename(String JavaDoc filename) {
313         //To clean up the default generation a little
314
if(filename.indexOf("://") != -1) { // NOI18N
315
filename = filename.substring(0, filename.indexOf("://")) + "_" + // NOI18N
316
filename.substring(filename.indexOf("://")+3, filename.length()); // NOI18N
317
}
318         if(filename.indexOf("//") != -1) { // NOI18N
319
filename = filename.substring(0, filename.indexOf("//")) + "_" + // NOI18N
320
filename.substring(filename.indexOf("//")+2, filename.length()); // NOI18N
321
}
322         filename = makeLegalFilename(filename);
323         
324         return filename;
325     }
326     
327     private void ensureFolderExists(File JavaDoc folder) throws IOException JavaDoc {
328         if(!folder.exists()) {
329             folder.mkdir();
330         }
331     }
332     
333     private String JavaDoc getFileName(String JavaDoc beanName, String JavaDoc resourceType) {
334         
335         assert (beanName != null);
336         assert (beanName.length() != 0);
337         
338         assert (resourceType != null);
339         assert (resourceType.length() != 0);
340         
341         String JavaDoc fileName = resourceType;
342         
343         if(!isFriendlyFilename(beanName)) {
344             beanName = makeLegalFilename(beanName);
345         }
346         
347         if(!isFriendlyFilename(fileName)) {
348             fileName = makeLegalFilename(fileName);
349         }
350         
351         fileName = fileName + DASH + beanName + DOT + __SunResourceExt;
352         return fileName;
353     }
354     
355     private JdbcConnectionPool setDerbyProps(String JavaDoc vendorName, String JavaDoc url, JdbcConnectionPool jdbcConnectionPool){
356         url = stripExtraDBInfo(url);
357         String JavaDoc workingUrl = url.substring(url.indexOf("//") + 2, url.length()); //NOI18N
358
String JavaDoc hostName = getDerbyServerName(workingUrl);
359         PropertyElement servName = jdbcConnectionPool.newPropertyElement();
360         servName.setName(WizardConstants.__ServerName);
361         servName.setValue(hostName);
362         
363         String JavaDoc portNumber = getDerbyPortNo(workingUrl);
364         PropertyElement portno = jdbcConnectionPool.newPropertyElement();
365         portno.setName(WizardConstants.__DerbyPortNumber);
366         portno.setValue(portNumber);
367         
368         String JavaDoc databaseName = getDerbyDatabaseName(workingUrl);
369         PropertyElement dbName = jdbcConnectionPool.newPropertyElement();
370         dbName.setName(WizardConstants.__DerbyDatabaseName);
371         dbName.setValue(databaseName);
372         
373         String JavaDoc connectionAttr = getDerbyConnAttrs(workingUrl);
374         if(! connectionAttr.equals("")) { //NOI18N
375
PropertyElement connAttr = jdbcConnectionPool.newPropertyElement();
376             connAttr.setName(WizardConstants.__DerbyConnAttr);
377             connAttr.setValue(connectionAttr);
378             jdbcConnectionPool.addPropertyElement(connAttr);
379         }
380         jdbcConnectionPool.addPropertyElement(servName);
381         jdbcConnectionPool.addPropertyElement(portno);
382         jdbcConnectionPool.addPropertyElement(dbName);
383         return jdbcConnectionPool;
384     }
385      
386     
387     /**
388      * Parses incoming url to create additional properties required by server
389      * example of url : jdbc:sun:db2://serverName:portNumber;databaseName=databaseName
390      * jdbc:sun:sqlserver://serverName[:portNumber]
391      */

392     private JdbcConnectionPool setAdditionalProps(String JavaDoc vendorName, String JavaDoc url, JdbcConnectionPool jdbcConnectionPool){
393         url = stripExtraDBInfo(url);
394         String JavaDoc workingUrl = url;
395         if(vendorName.equals("sybase2")){ //NOI18N
396
int index = url.indexOf("Tds:"); //NOI18N
397
if(index != -1){
398                 workingUrl = url.substring(index + 4, url.length()); //NOI18N
399
} else {
400                 return jdbcConnectionPool;
401             }
402         }else {
403             workingUrl = url.substring(url.indexOf("//") + 2, url.length()); //NOI18N
404
}
405         String JavaDoc hostName = getUrlServerName(workingUrl);
406         PropertyElement servName = jdbcConnectionPool.newPropertyElement();
407         servName.setName(WizardConstants.__ServerName);
408         servName.setValue(hostName);
409         
410         String JavaDoc portNumber = getUrlPortNo(workingUrl);
411         PropertyElement portno = jdbcConnectionPool.newPropertyElement();
412         portno.setName(WizardConstants.__PortNumber);
413         portno.setValue(portNumber);
414         
415         if(Arrays.asList(WizardConstants.VendorsDBNameProp).contains(vendorName)) { //NOI18N
416
PropertyElement dbName = jdbcConnectionPool.newPropertyElement();
417             String JavaDoc databaseName = "";
418             if(vendorName.equals("sun_oracle") || vendorName.equals("datadirect_oracle")) { //NOI18N
419
databaseName = getUrlSIDName(workingUrl);
420                 dbName.setName(WizardConstants.__SID);
421             }else{
422                 databaseName = getUrlDatabaseName(workingUrl);
423                 dbName.setName(WizardConstants.__DatabaseName);
424                 if(databaseName.equals("")) { //NOI18N
425
databaseName = getUrlDbName(workingUrl);
426                 }
427             }
428             dbName.setValue(databaseName);
429             jdbcConnectionPool.addPropertyElement(dbName);
430         }
431         jdbcConnectionPool.addPropertyElement(servName);
432         jdbcConnectionPool.addPropertyElement(portno);
433         return jdbcConnectionPool;
434     }
435     
436     private JdbcConnectionPool setDBProp(String JavaDoc vendorName, String JavaDoc url, JdbcConnectionPool jdbcConnectionPool){
437         url = stripExtraDBInfo(url);
438         String JavaDoc workingUrl = url.substring(url.indexOf("//") + 2, url.length()); //NOI18N
439
String JavaDoc databaseName = getUrlDatabaseName(workingUrl);
440         PropertyElement dbName = jdbcConnectionPool.newPropertyElement();
441         dbName.setName(WizardConstants.__DerbyDatabaseName);
442         dbName.setValue(databaseName);
443         
444         jdbcConnectionPool.addPropertyElement(dbName);
445         return jdbcConnectionPool;
446     }
447     
448     private String JavaDoc getDatasourceClassName(String JavaDoc vendorName, boolean isXA, Wizard wizard) {
449         if(vendorName == null) {
450             return null;
451         }
452         
453         try {
454             FieldGroup generalGroup = FieldGroupHelper.getFieldGroup(wizard, WizardConstants.__General);
455             
456             Field dsField = null;
457             if (isXA) {
458                 dsField = FieldHelper.getField(generalGroup, WizardConstants.__XADatasourceClassname);
459             } else {
460                 dsField = FieldHelper.getField(generalGroup, WizardConstants.__DatasourceClassname);
461             }
462             return FieldHelper.getConditionalFieldValue(dsField, vendorName);
463         } catch(Exception JavaDoc ex) {
464             // This should really a Schema2BeansException, but for classloader and dependency
465
// purposes we're catching Exception instead.
466

467             // XXX why do we suppress this?
468
// Unable to create Wizard object -- supppress.
469
}
470         
471         return null;
472     }
473     
474     
475     public static String JavaDoc getDatabaseVendorName(String JavaDoc url, Wizard wizard) {
476         String JavaDoc vendorName = "";
477         try {
478             if(wizard == null) {
479                wizard = getWizardInfo();
480             }
481             FieldGroup propGroup = FieldGroupHelper.getFieldGroup(wizard, WizardConstants.__PropertiesURL);
482             Field urlField = FieldHelper.getField(propGroup, "vendorUrls"); // NOI18N
483
vendorName = FieldHelper.getOptionNameFromValue(urlField, url);
484         } catch(Exception JavaDoc ex) {
485             // This should really a Schema2BeansException, but for classloader and dependency
486
// purposes we're catching Exception instead.
487

488             // XXX why do we suppress this?
489
// Unable to create Wizard object -- supppress.
490
}
491         
492         return vendorName;
493     }
494     
495     private String JavaDoc convertToValidName(String JavaDoc database) {
496         database = stripExtraDBInfo(database);
497         String JavaDoc vendorName = getDatabaseVendorName(database, null);
498         if(vendorName != null) {
499             if(!vendorName.equals("")) { // NOI18N
500
if(!isFriendlyFilename(vendorName)) {
501                     vendorName = makeLegalFilename(vendorName);
502                 }
503                 this.showMsg = false;
504             } else {
505                 this.showMsg = true;
506                 vendorName = makeShorterLegalFilename(database);
507             }
508         }
509         return vendorName;
510     }
511     
512     private String JavaDoc getDatabaseName(String JavaDoc database) {
513         String JavaDoc result = null;
514         int index = database.lastIndexOf('/') + 1;
515         if(index > 0) {
516             result = database.substring(index);
517         }
518         return result;
519     }
520     
521     private String JavaDoc getResourceType(boolean isXA) {
522         if(isXA) {
523             return "javax.sql.XADataSource"; // NOI18N
524
} else {
525             return "javax.sql.DataSource"; // NOI18N
526
}
527     }
528     
529     private boolean resourceAlreadyDefined(String JavaDoc resName, File JavaDoc dir, String JavaDoc resType) {
530         boolean result = false;
531         if(dir != null && dir.exists()) {
532             String JavaDoc filename = getFileName(resName, resType);
533             File JavaDoc resourceFile = new File JavaDoc(dir, filename);
534             if(resourceFile.exists()) {
535                 result = true;
536             }
537         }
538         
539         return result;
540     }
541     
542     private String JavaDoc isSameDatabaseConnection(File JavaDoc resourceFile, String JavaDoc databaseUrl, String JavaDoc username, String JavaDoc password) {
543         String JavaDoc poolJndiName = null;
544         try {
545             FileInputStream JavaDoc in = new FileInputStream JavaDoc(resourceFile);
546             Resources resources = DDProvider.getDefault().getResourcesGraph(in);
547             
548             // identify JDBC Resources xml
549
JdbcConnectionPool[] pools = (JdbcConnectionPool[])resources.getJdbcConnectionPool();
550             if(pools.length != 0) {
551                 JdbcConnectionPool connPool = pools[0];
552                 PropertyElement[] pl = (PropertyElement[])connPool.getPropertyElement();
553                 if(databaseUrl.startsWith("jdbc:derby:")){ //NOI18N
554
databaseUrl = stripExtraDBInfo(databaseUrl);
555                     String JavaDoc workingUrl = databaseUrl.substring(databaseUrl.indexOf("//") + 2, databaseUrl.length());
556                     String JavaDoc hostName = getDerbyServerName(workingUrl);
557                     String JavaDoc portNumber = getDerbyPortNo(workingUrl);
558                     String JavaDoc databaseName = getDerbyDatabaseName(workingUrl);
559                     String JavaDoc hostProp = null;
560                     String JavaDoc portProp = null;
561                     String JavaDoc dbProp = null;
562                     String JavaDoc dbUser = null;
563                     String JavaDoc dbPwd = null;
564                     for(int i=0; i<pl.length; i++) {
565                         String JavaDoc prop = pl[i].getName();
566                         if(prop.equalsIgnoreCase(WizardConstants.__ServerName)) {
567                             hostProp = pl[i].getValue();
568                         }else if(prop.equals(WizardConstants.__DerbyPortNumber)){
569                             portProp = pl[i].getValue();
570                         }else if(prop.equals(WizardConstants.__DerbyDatabaseName)){
571                             dbProp = pl[i].getValue();
572                         }else if(prop.equals(WizardConstants.__User)){
573                             dbUser = pl[i].getValue();
574                         }else if(prop.equals(WizardConstants.__Password)){
575                             dbPwd = pl[i].getValue();
576                         }
577                     }
578                     if(hostName.equals(hostProp) && portNumber.equals(portProp) &&
579                             databaseName.equals(dbProp)){
580                         if(dbUser != null && dbPwd != null && dbUser.equals(username) && dbPwd.equals(password)){
581                             poolJndiName = connPool.getName();
582                         }
583                     }
584                 }else{
585                     String JavaDoc hostName = ""; //NOI18N
586
String JavaDoc portNumber = ""; //NOI18N
587
String JavaDoc databaseName = ""; //NOI18N
588
String JavaDoc sid = ""; //NOI18N
589
String JavaDoc user = ""; //NOI18N
590
String JavaDoc pwd = ""; //NOI18N
591
for(int i=0; i<pl.length; i++) {
592                         String JavaDoc prop = pl[i].getName();
593                         if(prop.equalsIgnoreCase(WizardConstants.__ServerName)) {
594                             hostName = pl[i].getValue();
595                         }else if(prop.equals(WizardConstants.__PortNumber)){
596                             portNumber = pl[i].getValue();
597                         }else if(prop.equals(WizardConstants.__DatabaseName)){
598                             databaseName = pl[i].getValue();
599                         }else if(prop.equals(WizardConstants.__SID)){
600                             sid = pl[i].getValue();
601                         }else if(prop.equals(WizardConstants.__User)){
602                             user = pl[i].getValue();
603                         }else if(prop.equals(WizardConstants.__Password)){
604                             pwd = pl[i].getValue();
605                         }
606                     }
607                     String JavaDoc serverPort = hostName + ":" + portNumber; //NOI18N
608
if((databaseUrl.indexOf(serverPort) != -1 ) &&
609                        ((databaseUrl.indexOf(databaseName) != -1) || (databaseUrl.indexOf(sid) != -1))){
610                             if((username != null && user.equals(username)) && (password != null && pwd.equals(password))){
611                                 poolJndiName = connPool.getName();
612                             }
613                     }
614                         
615                     for(int i=0; i<pl.length; i++) {
616                         String JavaDoc prop = pl[i].getName();
617                         if(prop.equals("URL") || prop.equals("databaseName")) { // NOI18N
618
String JavaDoc urlValue = pl[i].getValue();
619                             if(urlValue.equals(databaseUrl)) {
620                                 if((username != null && user.equals(username)) && (password != null && pwd.equals(password))){
621                                     poolJndiName = connPool.getName();
622                                     break;
623                                 }
624                             }
625                         }
626                     } //for
627
}
628             }
629             in.close();
630         } catch(IOException JavaDoc ex) {
631             // Could not check local file
632
}
633         return poolJndiName;
634     }
635     
636     private String JavaDoc stripExtraDBInfo(String JavaDoc dbConnectionString) {
637         if(dbConnectionString.indexOf("[") != -1) { //NOI18N
638
dbConnectionString = dbConnectionString.substring(0, dbConnectionString.indexOf("[")).trim(); // NOI18N
639
}
640         return dbConnectionString;
641     }
642     
643     public static void showInformation(final String JavaDoc msg) {
644         // Asynchronous message posting. Placed on AWT thread automatically by DialogDescriptor.
645
RequestProcessor.getDefault().post(new Runnable JavaDoc() {
646             public void run() {
647                 NotifyDescriptor d = new NotifyDescriptor.Message(msg, NotifyDescriptor.WARNING_MESSAGE);
648                 DialogDisplayer.getDefault().notify(d);
649             }
650         });
651     }
652     
653     private static Wizard getWizardInfo(){
654         Wizard wizard = null;
655         try {
656             InputStream JavaDoc in = Wizard.class.getClassLoader().getResourceAsStream(DATAFILE);
657             wizard = Wizard.createGraph(in);
658             in.close();
659         } catch(Exception JavaDoc ex) {
660             // XXX Report I/O Exception to the user. We should do a nicely formatted
661
// message identifying the problem.
662
ErrorManager.getDefault().notify(ErrorManager.EXCEPTION, ex);
663         }
664         return wizard;
665     }
666     
667     private String JavaDoc getDerbyServerName(String JavaDoc url){
668         String JavaDoc hostName = ""; //NOI18N
669
int index = url.indexOf(":"); //NOI18N
670
if(index != -1) {
671             hostName = url.substring(0, index);
672         }else{
673             index = url.indexOf("/"); //NOI18N
674
if(index != -1){
675                 hostName = url.substring(0, index);
676             }
677         }
678         return hostName;
679     }
680     
681     private String JavaDoc getDerbyPortNo(String JavaDoc url){
682         String JavaDoc portNumber = "1527"; //NOI18N
683
int index = url.indexOf(":"); //NOI18N
684
if(index != -1) {
685             portNumber = url.substring(index + 1, url.indexOf("/")); //NOI18N
686
}
687         return portNumber;
688     }
689     
690     private String JavaDoc getDerbyDatabaseName(String JavaDoc url){
691         String JavaDoc databaseName = ""; //NOI18N
692
int index = url.indexOf("/"); //NOI18N
693
if(index != -1){
694             int colonIndex = url.indexOf(";"); //NOI18N
695
if(colonIndex != -1) {
696                 databaseName = url.substring(index + 1, colonIndex);
697             } else {
698                 databaseName = url.substring(index + 1, url.length());
699             }
700         }
701         return databaseName;
702     }
703     
704     private String JavaDoc getDerbyConnAttrs(String JavaDoc url){
705         String JavaDoc connAttr = ""; //NOI18N
706
int colonIndex = url.indexOf(";"); //NOI18N
707
if(colonIndex != -1) {
708             connAttr = url.substring(colonIndex, url.length());
709         }
710         return connAttr;
711     }
712     
713     private String JavaDoc getUrlServerName(String JavaDoc url){
714         String JavaDoc hostName = ""; //NOI18N
715
int index = url.indexOf(":"); //NOI18N
716
if(index != -1) {
717             hostName = url.substring(0, index);
718         }else{
719             index = url.indexOf("/"); //NOI18N
720
if(index != -1) {
721                 hostName = url.substring(0, index);
722             }else{
723                 index= url.indexOf(";"); //NOI18N
724
if(index != -1) {
725                     hostName = url.substring(0, index);
726                 }
727             }
728         }
729         return hostName;
730     }
731     
732     private String JavaDoc getUrlPortNo(String JavaDoc url){
733         String JavaDoc portNumber = ""; //NOI18N
734
int index = url.indexOf(":"); //NOI18N
735
if(index != -1){
736             int slashIndex = url.indexOf("/"); //NOI18N
737
int colonIndex = url.indexOf(";"); //NOI18N
738
if(slashIndex != -1)
739                 portNumber = url.substring(index + 1, slashIndex);
740             else{
741                 if(colonIndex != -1)
742                     portNumber = url.substring(index + 1, colonIndex);
743                 else
744                     portNumber = url.substring(index + 1, url.length());
745             }
746         }
747         return portNumber;
748     }
749     
750     /**
751      * Parses incoming url to create DatabaseName additional properties required by server
752      * example of url : jdbc:sun:db2://serverName:portNumber;databaseName=databaseName
753      * "jdbc:sun:sqlserver://sunsqlserverHost:3333;databaseName=sunsqlserverdb;selectMethod=cursor"
754      */

755     private String JavaDoc getUrlDatabaseName(String JavaDoc url){
756         String JavaDoc databaseName = ""; //NOI18N
757
int dbIndex = url.indexOf(";databaseName="); //NOI18N
758
if(dbIndex != -1){
759             int eqIndex = url.indexOf("=", dbIndex); //NOI18N
760
int lenIndex = url.indexOf(";", eqIndex); //NOI18N
761
if(lenIndex != -1){
762                 databaseName = url.substring(eqIndex + 1, lenIndex);
763             }else{
764                 databaseName = url.substring(eqIndex + 1, url.length());
765             }
766         }
767         return databaseName;
768     }
769     /**
770      * Parses incoming url(sun:oracle) to create SID additional properties required by server
771      * example of url : jdbc:sun:oracle://serverName[:portNumber][;SID=databaseName]
772      */

773     private String JavaDoc getUrlSIDName(String JavaDoc url){
774         String JavaDoc databaseName = ""; //NOI18N
775
int sidIndex = url.indexOf(";SID="); //NOI18N
776
if(sidIndex != -1){
777             int eqIndex = url.indexOf("=", sidIndex); //NOI18N
778
databaseName = url.substring(eqIndex + 1, url.length());
779         }
780         return databaseName;
781     }
782     /**
783      * Parses incoming url. to create SID additional properties required by server
784      * examples of url
785      * - jdbc:derby://serverName:portNumber/databaseName;create=true
786      * - jdbc:mysql://host:port/database?relaxAutoCommit="true"
787      * - jdbc:vendor://host:port/database
788      */

789     private String JavaDoc getUrlDbName(String JavaDoc url){
790         String JavaDoc databaseName = ""; //NOI18N
791
int slashIndex = url.indexOf("/"); //NOI18N
792
int clIndex = url.indexOf(";", slashIndex); //NOI18N
793
int scIndex = url.indexOf(":", slashIndex); //NOI18N
794
int qIndex = url.indexOf("?", slashIndex); //NOI18N
795
if(slashIndex != -1){
796             if(clIndex != -1)
797                 databaseName = url.substring(slashIndex + 1, clIndex);
798             else if(scIndex != -1)
799                 databaseName = url.substring(slashIndex + 1, scIndex);
800             else if(qIndex != -1)
801                 databaseName = url.substring(slashIndex + 1, qIndex);
802             else
803                 databaseName = url.substring(slashIndex + 1, url.length());
804                 
805         }
806         return databaseName;
807     }
808     
809     /***************************************** DS Management API *****************************************************************************/
810     
811     /**
812      * Returns Set of SunDataSource's(JDBC Resources) that are deployed on the server.
813      * Called from SunDataSourceManager.
814      * SunDataSource is a combination of JDBC & JDBC Connection Pool Resources.
815      * @return Set containing SunDataSource
816      */

817     public HashSet JavaDoc getServerDataSources() {
818         return ResourceUtils.getServerDataSources(this.currentDM);
819     }
820
821     /**
822      * Implementation of DS Management API in ConfigurationSupport
823      * SunDataSource is a combination of JDBC & JDBC Connection Pool Resources.
824      * Called through ConfigurationSupportImpl
825      * @return Returns Set of SunDataSource's(JDBC Resources) present in this J2EE project
826      * @param dir File providing location of the project's server resource directory
827      */

828     public HashSet JavaDoc getResources(File JavaDoc resourceDir) {
829         HashSet JavaDoc serverresources = getServerResourceFiles(resourceDir);
830         if (serverresources.size() == 0) {
831             return serverresources;
832         }
833
834         HashSet JavaDoc dsources = new HashSet JavaDoc();
835         HashMap JavaDoc connPools = getConnectionPools(serverresources);
836         List JavaDoc dataSources = getJdbcResources(serverresources);
837         for(int i=0; i<dataSources.size(); i++){
838             JdbcResource datasourceBean = (JdbcResource)dataSources.get(i);
839             String JavaDoc poolName = datasourceBean.getPoolName();
840             try{
841                 JdbcConnectionPool connectionPoolBean =(JdbcConnectionPool)connPools.get(poolName);
842                 String JavaDoc url = "";
843                 String JavaDoc username = "";
844                 String JavaDoc password = "";
845                 String JavaDoc driverClass = "";
846                 String JavaDoc serverName = "";
847                 String JavaDoc portNo = "";
848                 String JavaDoc dbName = "";
849                 String JavaDoc sid = "";
850                 if(connectionPoolBean != null){
851                     PropertyElement[] props = connectionPoolBean.getPropertyElement();
852                     driverClass = connectionPoolBean.getDatasourceClassname();
853                     HashMap JavaDoc properties = new HashMap JavaDoc();
854                     for (int j = 0; j < props.length; j++) {
855                         Object JavaDoc val = props[j].getValue();
856                         String JavaDoc propValue = "";
857                         if(val != null) {
858                             propValue = val.toString();
859                         }
860                         String JavaDoc propName = props[j].getName();
861                         if(propName.equalsIgnoreCase(WizardConstants.__DatabaseName)){
862                             if(driverClass.indexOf("pointbase") != -1) { //NOI18N
863
url = propValue;
864                             } else if(driverClass.indexOf("derby") != -1) { //NOI18N
865
dbName = propValue;
866                             } else {
867                                 dbName = propValue;
868                             }
869                         }else if(propName.equalsIgnoreCase(WizardConstants.__User)) {
870                             username = propValue;
871                         }else if(propName.equalsIgnoreCase(WizardConstants.__Password)){
872                             password = propValue;
873                         }else if(propName.equalsIgnoreCase(WizardConstants.__Url)){
874                             url = propValue;
875                         }else if(propName.equalsIgnoreCase(WizardConstants.__ServerName)){
876                             serverName = propValue;
877                         }else if(propName.equalsIgnoreCase(WizardConstants.__DerbyPortNumber)){
878                             portNo = propValue;
879                         }else if(propName.equalsIgnoreCase(WizardConstants.__SID)){
880                             sid = propValue;
881                         }
882                     }
883                     
884                     if(driverClass.indexOf("derby") != -1){ //NOI18N
885
url = "jdbc:derby://";
886                         if(serverName != null){
887                             url = url + serverName;
888                             if(portNo != null) {
889                                 url = url + ":" + portNo; //NOI18N
890
}
891                             url = url + "/" + dbName ; //NOI8N
892
}
893                     }else if(url.equals("")) { //NOI18N
894
String JavaDoc urlPrefix = DatabaseUtils.getUrlPrefix(driverClass);
895                         String JavaDoc vName = getDatabaseVendorName(urlPrefix, null);
896                         if(serverName != null){
897                             if(vName.equals("sybase2")){ //NOI18N
898
url = urlPrefix + serverName;
899                             } else {
900                                 url = urlPrefix + "//" + serverName; //NOI18N
901
}
902                             if(portNo != null) {
903                                 url = url + ":" + portNo; //NOI18N
904
}
905                         }
906                         if(vName.equals("sun_oracle") || vName.equals("datadirect_oracle")) { //NOI18N
907
url = url + ";SID=" + sid; //NOI18N
908
}else if(Arrays.asList(WizardConstants.Reqd_DBName).contains(vName)) {
909                             url = url + ";databaseName=" + dbName; //NOI18N
910
}else if(Arrays.asList(WizardConstants.VendorsDBNameProp).contains(vName)) {
911                             url = url + "/" + dbName ; //NOI8N
912
}
913                     }
914                     
915                     DatabaseConnection databaseConnection = ResourceUtils.getDatabaseConnection(url);
916                     if(databaseConnection != null) {
917                         driverClass = databaseConnection.getDriverClass();
918                     }else{
919                         //Fix Issue 78212 - NB required driver classname
920
String JavaDoc drivername = DatabaseUtils.getDriverName(url);
921                         if(drivername != null) {
922                             driverClass = drivername;
923                         }
924                     }
925                     
926                     SunDatasource sunResource = new SunDatasource(datasourceBean.getJndiName(), url, username, password, driverClass);
927                     sunResource.setResourceDir(resourceDir);
928                     dsources.add(sunResource);
929                 }else{
930                     //Get Pool From Server
931
HashMap JavaDoc poolValues = ResourceUtils.getConnPoolValues(resourceDir, poolName);
932                     if(! poolValues.isEmpty()){
933                         username = (String JavaDoc)poolValues.get(WizardConstants.__User);
934                         password = (String JavaDoc)poolValues.get(WizardConstants.__Password);
935                         url = (String JavaDoc)poolValues.get(WizardConstants.__Url);
936                         driverClass = (String JavaDoc)poolValues.get(WizardConstants.__DriverClassName);
937                         if((url != null) && (! url.equals (""))) { //NOI18N
938
SunDatasource sunResource = new SunDatasource (datasourceBean.getJndiName (), url, username, password, driverClass);
939                             sunResource.setResourceDir (resourceDir);
940                             dsources.add (sunResource);
941                         }
942                     }
943                 }
944             }catch(Exception JavaDoc ex){
945                 //Should never happen
946
ErrorManager.getDefault().log(ErrorManager.INFORMATIONAL, "Cannot construct SunDatasource for jdbc resource : " + datasourceBean.getJndiName()
947                     + "with pool " + poolName); // NOI18N
948
}
949         }
950         return dsources;
951     }
952     
953     /**
954      * Create SunDataSource object's defined. Called from impl of
955      * ConfigurationSupport API (ConfigurationSupportImpl).
956      * SunDataSource is a combination of JDBC & JDBC Connection Pool
957      * Resources.
958      * @return Set containing SunDataSource
959      * @param jndiName JNDI Name of JDBC Resource
960      * @param url Url for database referred to by this JDBC Resource's Connection Pool
961      * @param username UserName for database referred to by this JDBC Resource's Connection Pool
962      * @param password Password for database referred to by this JDBC Resource's Connection Pool
963      * @param driver Driver ClassName for database referred to by this JDBC Resource's Connection Pool
964      * @param dir File providing location of the project's server resource directory
965      */

966     public Datasource createDataSource(String JavaDoc jndiName, String JavaDoc url, String JavaDoc username, String JavaDoc password, String JavaDoc driver, File JavaDoc dir) throws DatasourceAlreadyExistsException {
967         SunDatasource ds = null;
968         try {
969             if(isDataSourcePresent(jndiName, dir)){
970                 throw new DatasourceAlreadyExistsException(new SunDatasource(jndiName, url, username, password, driver));
971             }
972             if(url != null){
973                 String JavaDoc vendorName = convertToValidName(url);
974                 if(vendorName == null) {
975                     vendorName = jndiName;
976                 }else{
977                     if(vendorName.equals("derby_embedded")){ //NOI18N
978
NotifyDescriptor d = new NotifyDescriptor.Message(bundle.getString("Err_UnSupportedDerby"), NotifyDescriptor.WARNING_MESSAGE); // NOI18N
979
DialogDisplayer.getDefault().notify(d);
980                         return null;
981                     }
982                 }
983                 ensureFolderExists(dir);
984                 // Is connection pool already defined
985
String JavaDoc poolName = vendorName + WizardConstants.__ConnPoolSuffix;
986                 HashMap JavaDoc poolMap = updatePoolName(jndiName, poolName, dir, url, username, password);
987                 Object JavaDoc[] pools = poolMap.keySet().toArray();
988                 String JavaDoc newPoolName = (String JavaDoc)pools[0];
989                 Object JavaDoc resFile = poolMap.get(pools[0]);
990                 if(resFile != null) {
991                     if(resourceFileExists(jndiName, dir)) {
992                         ds = null;
993                     } else {
994                         createJDBCResource(jndiName, newPoolName, dir);
995                         ds = new SunDatasource(jndiName, url, username, password, driver);
996                     }
997                 } else {
998                     createCPPoolResource(newPoolName, url, username, password, driver, dir);
999                     createJDBCResource(jndiName, newPoolName, dir);
1000                    ds = new SunDatasource(jndiName, url, username, password, driver);
1001                }
1002            }
1003        } catch(IOException JavaDoc ex) {
1004            ErrorManager.getDefault().notify(ErrorManager.EXCEPTION, ex);
1005        }
1006        return ds;
1007    }
1008    
1009    private void createCPPoolResource(String JavaDoc name, String JavaDoc databaseUrl, String JavaDoc username, String JavaDoc password, String JavaDoc driver, File JavaDoc resourceDir) throws IOException JavaDoc {
1010        Resources resources = DDProvider.getDefault().getResourcesGraph();
1011        
1012        JdbcConnectionPool jdbcConnectionPool = resources.newJdbcConnectionPool();
1013        jdbcConnectionPool.setName(name);
1014        jdbcConnectionPool.setResType(getResourceType(false));
1015                      
1016        // XXX Refactor database abstractions into own object. For example,
1017
// due to lack of member data, we're parsing CPWizard.xml twice here,
1018
// once in getDatabaseVendorName() and again in getDatasourceClassName()
1019
Wizard wizard = getWizardInfo();
1020        String JavaDoc vendorName = getDatabaseVendorName(databaseUrl, wizard);
1021        String JavaDoc datasourceClassName = ""; // NOI18N
1022
if(!vendorName.equals("")) { // NOI18N
1023
datasourceClassName = getDatasourceClassName(vendorName, false, wizard);
1024        }
1025        
1026        if(datasourceClassName.equals("")) { // NOI18N
1027
datasourceClassName = DatabaseUtils.getDSClassName(databaseUrl);
1028            if(datasourceClassName == null || datasourceClassName.equals("")) { //NOI18N
1029
//String mess = MessageFormat.format(bundle.getString("LBL_NoDSClassName"), new Object [] { name }); // NOI18N
1030
//showInformation(mess);
1031
datasourceClassName = driver;
1032            }
1033        }
1034        if(datasourceClassName != null) {
1035            jdbcConnectionPool.setDatasourceClassname(datasourceClassName);
1036        }
1037        PropertyElement user = jdbcConnectionPool.newPropertyElement();
1038        user.setName(WizardConstants.__User); // NOI18N
1039
PropertyElement passElement = jdbcConnectionPool.newPropertyElement();
1040        passElement.setName(WizardConstants.__Password); // NOI18N
1041
String JavaDoc dbUser = username;
1042        String JavaDoc dbPassword = password;
1043        if(vendorName.equals("derby_net")) { //NOI18N)
1044
jdbcConnectionPool = setDerbyProps(vendorName, databaseUrl, jdbcConnectionPool);
1045            if(dbUser == null || dbUser.trim().length() == 0) {
1046                dbUser = "app"; //NOI18N
1047
}
1048            if(dbPassword == null || dbPassword.trim().length() == 0) {
1049                dbPassword = "app"; //NOI18N
1050
}
1051        }else {
1052            if(Arrays.asList(WizardConstants.VendorsExtraProps).contains(vendorName)) {
1053               jdbcConnectionPool = setAdditionalProps(vendorName, databaseUrl, jdbcConnectionPool);
1054            }else{
1055                PropertyElement databaseOrUrl = jdbcConnectionPool.newPropertyElement();
1056                if(vendorName.equals("pointbase")) { // NOI18N
1057
databaseOrUrl.setName(WizardConstants.__DatabaseName); // NOI18N
1058
} else {
1059                    databaseOrUrl.setName(WizardConstants.__Url); // NOI18N
1060
}
1061                databaseOrUrl.setValue(databaseUrl);
1062                jdbcConnectionPool.addPropertyElement(databaseOrUrl);
1063            }
1064        }
1065        user.setValue(dbUser);
1066        jdbcConnectionPool.addPropertyElement(user);
1067        passElement.setValue(dbPassword);
1068        jdbcConnectionPool.addPropertyElement(passElement);
1069        resources.addJdbcConnectionPool(jdbcConnectionPool);
1070        
1071        ResourceUtils.createFile(FileUtil.toFileObject(resourceDir), name, resources);
1072        try{
1073            Thread.sleep(1000);
1074        }catch(Exception JavaDoc ex){}
1075    }
1076    
1077    private void createJDBCResource(String JavaDoc jndiName, String JavaDoc poolName, File JavaDoc resourceDir) throws IOException JavaDoc {
1078        Resources resources = DDProvider.getDefault().getResourcesGraph();
1079        JdbcResource jdbcResource = resources.newJdbcResource();
1080        jdbcResource.setPoolName(poolName);
1081        jdbcResource.setJndiName(jndiName);
1082        resources.addJdbcResource(jdbcResource);
1083        ResourceUtils.createFile(FileUtil.toFileObject(resourceDir), jndiName, resources);
1084    }
1085    
1086    private HashSet JavaDoc getServerResourceFiles(File JavaDoc resourceDir) {
1087        HashSet JavaDoc serverresources = new HashSet JavaDoc();
1088        if(resourceDir.exists()){
1089            FileObject resDir = FileUtil.toFileObject(resourceDir);
1090            Enumeration JavaDoc files = resDir.getChildren(true);
1091            while (files.hasMoreElements()) {
1092                FileObject file = (FileObject) files.nextElement();
1093                if (!file.isFolder() && file.getNameExt().endsWith(".sun-resource") && file.canRead()) { //NOI18N
1094
serverresources.add(file);
1095                }
1096            }
1097        }
1098        return serverresources;
1099    }
1100    
1101    private List JavaDoc getJdbcResources(HashSet JavaDoc serverresources) {
1102        List JavaDoc dataSources = new ArrayList JavaDoc();
1103        for (Iterator JavaDoc it = serverresources.iterator(); it.hasNext();) {
1104            try {
1105                FileObject dsObj = (FileObject)it.next();
1106                File JavaDoc dsFile = FileUtil.toFile(dsObj);
1107                if(! dsFile.isDirectory()){
1108                    FileInputStream JavaDoc in = new FileInputStream JavaDoc(dsFile);
1109                    
1110                    Resources resources = DDProvider.getDefault().getResourcesGraph(in);
1111                    
1112                    // identify JDBC Resources xml
1113
JdbcResource[] dSources = resources.getJdbcResource();
1114                    if(dSources.length != 0){
1115                        dataSources.add(dSources[0]);
1116                    }
1117                }
1118            } catch (Exception JavaDoc ex) {
1119                ErrorManager.getDefault().notify(ex);
1120            }
1121        }
1122        return dataSources;
1123    }
1124    
1125    private HashMap JavaDoc getConnectionPools(HashSet JavaDoc serverresources) {
1126        HashMap JavaDoc connPools = new HashMap JavaDoc();
1127        for (Iterator JavaDoc it = serverresources.iterator(); it.hasNext();) {
1128            try {
1129                FileObject dsObj = (FileObject)it.next();
1130                File JavaDoc dsFile = FileUtil.toFile(dsObj);
1131                if(! dsFile.isDirectory()){
1132                    FileInputStream JavaDoc in = new FileInputStream JavaDoc(dsFile);
1133                    
1134                    Resources resources = DDProvider.getDefault().getResourcesGraph(in);
1135                    
1136                    // identify JDBC Connection Pool xml
1137
JdbcConnectionPool[] pools = resources.getJdbcConnectionPool();
1138                    if(pools.length != 0){
1139                        JdbcConnectionPool cp = pools[0];
1140                        connPools.put(cp.getName(), cp);
1141                    }
1142                }
1143            } catch (Exception JavaDoc ex) {
1144                ErrorManager.getDefault().notify(ex);
1145            }
1146        }
1147        return connPools;
1148    }
1149    
1150    private HashMap JavaDoc getPoolFiles(HashSet JavaDoc serverresources) {
1151        HashMap JavaDoc connPools = new HashMap JavaDoc();
1152        for (Iterator JavaDoc it = serverresources.iterator(); it.hasNext();) {
1153            try {
1154                FileObject dsObj = (FileObject)it.next();
1155                File JavaDoc dsFile = FileUtil.toFile(dsObj);
1156                
1157                if(! dsFile.isDirectory()){
1158                    FileInputStream JavaDoc in = new FileInputStream JavaDoc(dsFile);
1159                    
1160                    Resources resources = DDProvider.getDefault().getResourcesGraph(in);
1161                    
1162                    // identify JDBC Connection Pool xml
1163
JdbcConnectionPool[] pools = resources.getJdbcConnectionPool();
1164                    if(pools.length != 0){
1165                        connPools.put(dsObj.getName(), dsFile);
1166                    }
1167                }
1168            } catch (Exception JavaDoc ex) {
1169                ErrorManager.getDefault().notify(ex);
1170            }
1171        }
1172        return connPools;
1173    }
1174    
1175    private boolean isDataSourcePresent(String JavaDoc jndiName, File JavaDoc dir){
1176        boolean exists = false;
1177        HashMap JavaDoc serverResources = getDataSourceMap(getResources(dir));
1178        if(serverResources.containsKey(jndiName)) {
1179            exists = true;
1180        }
1181        return exists;
1182    }
1183    
1184    private HashMap JavaDoc getDataSourceMap(HashSet JavaDoc resources){
1185        HashMap JavaDoc dSources = new HashMap JavaDoc();
1186        for (Iterator JavaDoc it = resources.iterator(); it.hasNext();) {
1187            SunDatasource ds = (SunDatasource)it.next();
1188            dSources.put(ds.getJndiName(), ds);
1189        }
1190        return dSources;
1191    }
1192    
1193    /**
1194     *
1195     * @param dsJndiName JNDI Name of JDBC Datasource that uses/needs this Connection Pool
1196     * @param poolName Connection Pool for this JDBC Datasource
1197     * @param dir Resource Directory
1198     * @param url Database URL
1199     * @return Returns null if Connection Pool already exists for this database else return
1200     * unique Connection PoolName.
1201     *
1202     */

1203    private HashMap JavaDoc updatePoolName(String JavaDoc dsJndiName, String JavaDoc poolName, File JavaDoc dir, String JavaDoc url, String JavaDoc username, String JavaDoc password){
1204        HashMap JavaDoc poolAndFile = new HashMap JavaDoc();
1205        String JavaDoc cpName = poolName;
1206        HashSet JavaDoc resourceFiles = getServerResourceFiles(dir);
1207        HashMap JavaDoc poolFiles = getPoolFiles(resourceFiles);
1208        for(Iterator JavaDoc itr=poolFiles.values().iterator(); itr.hasNext();){
1209            File JavaDoc resourceFile = (File JavaDoc)itr.next();
1210            if(resourceFile != null && resourceFile.exists()) {
1211                String JavaDoc poolJndiName = isSameDatabaseConnection(resourceFile, url, username, password);
1212                if(poolJndiName != null){
1213                    cpName = poolJndiName;
1214                    poolAndFile.put(cpName, resourceFile);
1215                    break;
1216                }
1217            }
1218        }
1219        if(poolAndFile.size() == 0){
1220            cpName = FileUtil.findFreeFileName(FileUtil.toFileObject(dir), poolName, __SunResourceExt);
1221            poolAndFile.put(cpName, null);
1222        }
1223        return poolAndFile;
1224    }
1225    
1226    private File JavaDoc getResourceFile(String JavaDoc fileName, File JavaDoc dir){
1227        File JavaDoc resourceFile = null;
1228        if(dir != null && dir.exists()) {
1229            String JavaDoc filename = fileName + DOT + __SunResourceExt;
1230            resourceFile = new File JavaDoc(dir, filename);
1231        }
1232        return resourceFile;
1233    }
1234    
1235    private boolean resourceFileExists(String JavaDoc resName, File JavaDoc dir) {
1236        boolean result = false;
1237        if(dir != null && dir.exists()) {
1238            String JavaDoc filename = resName + DOT + __SunResourceExt;
1239            File JavaDoc resourceFile = new File JavaDoc(dir, filename);
1240            if(resourceFile.exists()) {
1241                result = true;
1242            }
1243        }
1244        return result;
1245    }
1246    
1247}
1248
1249
Popular Tags