KickJava   Java API By Example, From Geeks To Geeks.

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


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  * ResourceUtils.java
21  *
22  * Created on September 17, 2003, 11:54 AM
23  */

24
25 package org.netbeans.modules.j2ee.sun.ide.sunresources.beans;
26
27 import java.io.File JavaDoc;
28 import java.io.Writer JavaDoc;
29 import java.io.FileInputStream JavaDoc;
30 import java.io.OutputStreamWriter JavaDoc;
31 import java.util.Arrays JavaDoc;
32 import java.util.Collections JavaDoc;
33
34 import java.util.Map JavaDoc;
35 import java.util.List JavaDoc;
36 import java.util.Vector JavaDoc;
37 import java.util.ArrayList JavaDoc;
38 import java.util.Properties JavaDoc;
39 import java.text.MessageFormat JavaDoc;
40 import java.util.HashMap JavaDoc;
41 import java.util.HashSet JavaDoc;
42 import java.util.ResourceBundle JavaDoc;
43
44 import javax.management.Attribute JavaDoc;
45 import javax.management.ObjectName JavaDoc;
46 import javax.management.AttributeList JavaDoc;
47 import org.netbeans.api.project.FileOwnerQuery;
48 import org.netbeans.api.project.Project;
49 import org.netbeans.modules.j2ee.deployment.devmodules.spi.J2eeModuleProvider;
50 import org.netbeans.modules.j2ee.sun.api.SunURIManager;
51
52 import org.openide.util.NbBundle;
53 import org.openide.ErrorManager;
54
55 import org.openide.filesystems.FileLock;
56 import org.openide.filesystems.FileUtil;
57 import org.openide.filesystems.FileObject;
58 import org.openide.filesystems.FileSystem;
59
60 import javax.enterprise.deploy.spi.DeploymentManager JavaDoc;
61 import org.netbeans.api.db.explorer.ConnectionManager;
62 import org.netbeans.api.db.explorer.DatabaseConnection;
63
64 import org.netbeans.modules.j2ee.sun.ide.editors.NameValuePair;
65 import org.netbeans.modules.j2ee.sun.sunresources.beans.WizardConstants;
66 import org.netbeans.modules.j2ee.sun.ide.editors.IsolationLevelEditor;
67 import org.netbeans.modules.j2ee.sun.ide.sunresources.wizards.ResourceConfigData;
68
69 import org.netbeans.modules.j2ee.deployment.plugins.api.InstanceProperties;
70
71 import org.netbeans.modules.j2ee.sun.api.SunDeploymentManagerInterface;
72 import org.netbeans.modules.j2ee.sun.api.ServerInterface;
73 import org.netbeans.modules.j2ee.sun.api.ServerLocationManager;
74
75 import org.netbeans.modules.j2ee.sun.dd.api.DDProvider;
76 import org.netbeans.modules.j2ee.sun.dd.api.serverresources.*;
77 import org.netbeans.modules.j2ee.sun.share.serverresources.SunDatasource;
78 import org.netbeans.modules.j2ee.sun.sunresources.beans.DatabaseUtils;
79
80 /*
81  *
82  * @author nityad
83  */

84 public class ResourceUtils implements WizardConstants{
85     
86     static final ResourceBundle JavaDoc bundle = ResourceBundle.getBundle("org.netbeans.modules.j2ee.sun.ide.sunresources.beans.Bundle");// NOI18N
87
static final String JavaDoc[] sysDatasources = {"jdbc/__TimerPool", "jdbc/__CallFlowPool", "jdbc/__default"}; //NOI18N
88
static final String JavaDoc[] sysConnpools = {"__CallFlowPool", "__TimerPool", "DerbyPool"}; //NOI18N
89
static final String JavaDoc SAMPLE_DATASOURCE = "jdbc/sample";
90     static final String JavaDoc SAMPLE_CONNPOOL = "SamplePool";
91     
92     /** Creates a new instance of ResourceUtils */
93     public ResourceUtils() {
94     }
95     
96     public static void saveNodeToXml(FileObject resFile, Resources res){
97         try {
98             res.write(FileUtil.toFile(resFile));
99         }catch(Exception JavaDoc ex){
100             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
101         }
102     }
103     
104     public static void register(Resources resource, SunDeploymentManagerInterface sunDm, boolean update, String JavaDoc resType) throws Exception JavaDoc {
105         if(sunDm.isRunning()){
106             ServerInterface mejb = sunDm.getManagement();
107             if(resType.equals(__JdbcConnectionPool)){
108                 register(resource.getJdbcConnectionPool(0), mejb, update);
109             }else if(resType.equals(__JdbcResource)){
110                 register(resource.getJdbcResource(0), mejb, update);
111             }else if(resType.equals(__PersistenceManagerFactoryResource)){
112                 register(resource.getPersistenceManagerFactoryResource(0), mejb, update);
113             }else if(resType.equals(__MailResource)){
114                 register(resource.getMailResource(0), mejb, update);
115             }else if(resType.equals(__JmsResource)){
116                 if(resource.getAdminObjectResource().length != 0){
117                     register(resource.getAdminObjectResource(0), mejb, update);
118                 }else{
119                     if(resource.getConnectorResource().length != 0 && resource.getConnectorConnectionPool().length != 0) {
120                         register(resource.getConnectorConnectionPool(0), mejb, update);
121                         register(resource.getConnectorResource(0), mejb, update);
122                     }
123                 }
124             }
125         }else{
126             throw new Exception JavaDoc(bundle.getString("Err_RegResServerStopped")); //NOI18N
127
}
128     }
129     
130     public static void register(JdbcConnectionPool resource, ServerInterface mejb, boolean update) throws Exception JavaDoc{
131         AttributeList JavaDoc attrList = ResourceUtils.getResourceAttributes(resource, mejb);
132         PropertyElement[] props = resource.getPropertyElement();
133         Properties JavaDoc propsList = getProperties(props);
134         Object JavaDoc[] params = new Object JavaDoc[]{attrList, propsList, null};
135         String JavaDoc resourceName = resource.getName();
136         if(!isResourceUpdated(resourceName, mejb, attrList, propsList, __GetJdbcConnectionPool)){
137             createResource(__CreateCP, params, mejb);
138         }
139     }
140     
141     public static void register(JdbcResource resource, ServerInterface mejb, boolean update) throws Exception JavaDoc{
142         AttributeList JavaDoc attrList = ResourceUtils.getResourceAttributes(resource);
143         PropertyElement[] props = resource.getPropertyElement();
144         Properties JavaDoc propsList = getProperties(props);
145         Object JavaDoc[] params = new Object JavaDoc[]{attrList, propsList, null};
146         String JavaDoc resourceName = resource.getJndiName();
147         if(!isResourceUpdated(resourceName, mejb, attrList, propsList, __GetJdbcResource)){
148             createResource(__CreateDS, params, mejb);
149         }
150     }
151        
152      public static void register(PersistenceManagerFactoryResource resource, ServerInterface mejb, boolean update) throws Exception JavaDoc{
153          AttributeList JavaDoc attrList = ResourceUtils.getResourceAttributes(resource);
154          PropertyElement[] props = resource.getPropertyElement();
155          Properties JavaDoc propsList = getProperties(props);
156          Object JavaDoc[] params = new Object JavaDoc[]{attrList, propsList, null};
157          String JavaDoc resourceName = resource.getJndiName();
158          if(!isResourceUpdated(resourceName, mejb, attrList, propsList, __GetPMFResource)){
159              createResource(__CreatePMF, params, mejb);
160          }
161      }
162      
163      public static void register(AdminObjectResource resource, ServerInterface mejb, boolean update) throws Exception JavaDoc{
164          AttributeList JavaDoc attrList = ResourceUtils.getResourceAttributes(resource);
165          PropertyElement[] props = resource.getPropertyElement();
166          Properties JavaDoc propsList = getProperties(props);
167          Object JavaDoc[] params = new Object JavaDoc[]{attrList, propsList, null};
168          String JavaDoc resourceName = resource.getJndiName();
169          if(!isResourceUpdated(resourceName, mejb, attrList, propsList, __GetAdmObjResource)){
170              createResource(__CreateAdmObj, params, mejb);
171          }
172      }
173     
174      public static void register(ConnectorResource resource, ServerInterface mejb, boolean update) throws Exception JavaDoc{
175          AttributeList JavaDoc attrList = ResourceUtils.getResourceAttributes(resource);
176          Properties JavaDoc propsList = new Properties JavaDoc();
177          Object JavaDoc[] params = new Object JavaDoc[]{attrList, propsList, null};
178          String JavaDoc resourceName = resource.getJndiName();
179          if(!isResourceUpdated(resourceName, mejb, attrList, propsList, __GetConnectorResource)){
180              createResource(__CreateConnector, params, mejb);
181          }
182      }
183      
184      public static void register(ConnectorConnectionPool resource, ServerInterface mejb, boolean update) throws Exception JavaDoc{
185          AttributeList JavaDoc attrList = ResourceUtils.getResourceAttributes(resource);
186          PropertyElement[] props = resource.getPropertyElement();
187          Properties JavaDoc propsList = getProperties(props);
188          Object JavaDoc[] params = new Object JavaDoc[]{attrList, propsList, null};
189          String JavaDoc resourceName = resource.getName();
190          if(!isResourceUpdated(resourceName, mejb, attrList, propsList, __GetConnPoolResource)){
191              createResource(__CreateConnPool, params, mejb);
192          }
193      }
194      
195      public static void register(MailResource resource, ServerInterface mejb, boolean update) throws Exception JavaDoc{
196          AttributeList JavaDoc attrList = ResourceUtils.getResourceAttributes(resource);
197          PropertyElement[] props = resource.getPropertyElement();
198          Properties JavaDoc propsList = getProperties(props);
199          Object JavaDoc[] params = new Object JavaDoc[]{attrList, propsList, null};
200          String JavaDoc resourceName = resource.getJndiName();
201          if(!isResourceUpdated(resourceName, mejb, attrList, propsList, __GetMailResource)){
202              createResource(__CreateMail, params, mejb);
203          }
204      }
205      
206      public static void register(JmsResource resource, ServerInterface mejb, boolean update) throws Exception JavaDoc{
207          AttributeList JavaDoc attrList = ResourceUtils.getResourceAttributes(resource);
208          PropertyElement[] props = resource.getPropertyElement();
209          Properties JavaDoc propsList = getProperties(props);
210          Object JavaDoc[] params = new Object JavaDoc[]{attrList, propsList, null};
211          String JavaDoc operName = NbBundle.getMessage(ResourceUtils.class, "CreateJMS"); //NOI18N
212
String JavaDoc resourceName = resource.getJndiName();
213          if(!isResourceUpdated(resourceName, mejb, attrList, propsList, WizardConstants.__GetJmsResource)){
214              createResource(operName, params, mejb);
215          }
216      }
217     
218      private static boolean isResourceUpdated(String JavaDoc resourceName, ServerInterface mejb, AttributeList JavaDoc attrList, Properties JavaDoc props, String JavaDoc operName ){
219         boolean isResUpdated = false;
220         try{
221             ObjectName JavaDoc objName = new ObjectName JavaDoc(MAP_RESOURCES);
222             ObjectName JavaDoc[] resourceObjects = null;
223             if(operName.equals(__GetPMFResource) || operName.equals(__GetJmsResource)){
224                 String JavaDoc[] signature = new String JavaDoc[]{"java.lang.String"}; //NOI18N
225
Object JavaDoc[] params = new Object JavaDoc[]{null};
226                 resourceObjects = (ObjectName JavaDoc[]) mejb.invoke(objName, operName, params, signature);
227             }else{
228                 resourceObjects = (ObjectName JavaDoc[]) mejb.invoke(objName, operName, null, null);
229             }
230             if(resourceObjects != null){
231                 ObjectName JavaDoc resOnServer = null;
232                 if(operName.equals(__GetJdbcConnectionPool) || operName.equals(__GetConnPoolResource))
233                     resOnServer = getResourceDeployed(resourceObjects, resourceName, false);
234                 else
235                     resOnServer = getResourceDeployed(resourceObjects, resourceName, true);
236                 if(resOnServer != null){
237                     isResUpdated = true;
238                     updateResourceAttributes(resOnServer, attrList, mejb);
239                     updateResourceProperties(resOnServer, props, mejb);
240                 }
241             }//Returned value is null for JMS.
242
}catch(Exception JavaDoc ex){
243             String JavaDoc errorMsg = MessageFormat.format(bundle.getString("Err_ResourceUpdate"), new Object JavaDoc[]{resourceName}); //NOI18N
244
System.out.println(errorMsg);
245         }
246         return isResUpdated;
247     }
248     
249     private static ObjectName JavaDoc getResourceDeployed(ObjectName JavaDoc[] resourceObjects, String JavaDoc resourceName, boolean useJndi){
250         for(int i=0; i<resourceObjects.length; i++){
251             ObjectName JavaDoc resObj = resourceObjects[i];
252             String JavaDoc jndiName = null;
253             if(useJndi)
254                 jndiName = resObj.getKeyProperty(__JndiName);
255             else
256                 jndiName = resObj.getKeyProperty(__Name);
257             
258             if(jndiName.equals(resourceName)){
259                 return resObj;
260             }
261         }
262         return null;
263     }
264     
265     public static void updateResourceAttributes(ObjectName JavaDoc objName, AttributeList JavaDoc attrList, ServerInterface mejb) throws Exception JavaDoc {
266          try{
267              Map JavaDoc attributeInfos = getResourceAttributeNames(objName, mejb);
268              String JavaDoc[] attrNames = (String JavaDoc[]) attributeInfos.keySet().toArray(new String JavaDoc[attributeInfos.size()]);
269              
270              //Attributes from server
271
AttributeList JavaDoc existAttrList = mejb.getAttributes(objName, attrNames);
272              for(int i=0; i<existAttrList.size(); i++){
273                 Attribute JavaDoc existAttr = (Attribute JavaDoc)existAttrList.get(i);
274                 String JavaDoc existAttrName = existAttr.getName();
275                 for(int j=0; j<attrList.size(); j++){
276                     Attribute JavaDoc resAttr = (Attribute JavaDoc)attrList.get(j);
277                     String JavaDoc resAttrName = resAttr.getName();
278                     if(existAttrName.equals(resAttrName)){
279                         if(resAttr.getValue() == null && existAttr.getValue() != null) {
280                             mejb.setAttribute(objName, resAttr);
281                         }else if(existAttr.getValue() == null) { //NOI18N
282
if((resAttr.getValue() != null) && (! resAttr.getValue().toString().equals("")))
283                                 mejb.setAttribute(objName, resAttr);
284                         }else{
285                             if(! resAttr.getValue().toString().equals(existAttr.getValue().toString())){
286                                 mejb.setAttribute(objName, resAttr);
287                             }
288                         }
289                     }//if
290
}//loop through project's resource Attributes
291
}
292          }catch(Exception JavaDoc ex){
293              throw new Exception JavaDoc(ex.getLocalizedMessage());
294          }
295      }
296     public static void updateResourceProperties(ObjectName JavaDoc objName, Properties JavaDoc props, ServerInterface mejb) throws Exception JavaDoc {
297          try{
298              String JavaDoc[] signature = new String JavaDoc[]{"javax.management.Attribute"}; //NOI18N
299
Object JavaDoc[] params = null;
300              //Get Extra Properties From Server
301
AttributeList JavaDoc attrList = (AttributeList JavaDoc)mejb.invoke(objName, WizardConstants.__GetProperties, null, null);
302              for(int i=0; i<attrList.size(); i++){
303                  Attribute JavaDoc oldAttr = (Attribute JavaDoc)attrList.get(i);
304                  String JavaDoc oldAttrName = oldAttr.getName();
305                  if(props.containsKey(oldAttrName)){
306                      if(oldAttr.getValue() != null){
307                          String JavaDoc oldAttrValue = oldAttr.getValue().toString();
308                          if(! props.getProperty(oldAttrName).equals(oldAttrValue)){
309                              Attribute JavaDoc attr = new Attribute JavaDoc(oldAttrName, props.getProperty(oldAttrName));
310                              params = new Object JavaDoc[]{attr};
311                              mejb.invoke(objName, WizardConstants.__SetProperty, params, signature);
312                          }
313                      }else{//Server extra property value not null
314
if(props.getProperty(oldAttrName) != null){
315                              Attribute JavaDoc attr = new Attribute JavaDoc(oldAttrName, props.getProperty(oldAttrName));
316                              params = new Object JavaDoc[]{attr};
317                              mejb.invoke(objName, WizardConstants.__SetProperty, params, signature);
318                          }
319                      }
320                  }else{
321                      //Modifies extra properties does not contain this property
322
//Remove from server resource
323
Attribute JavaDoc removeAttr = new Attribute JavaDoc(oldAttrName, null);
324                      params = new Object JavaDoc[]{removeAttr};
325                      mejb.invoke(objName, WizardConstants.__SetProperty, params, signature);
326                  }
327              }//loop through server extra properties
328
addNewExtraProperties(objName, props, attrList, mejb);
329          }catch(Exception JavaDoc ex){
330              throw new Exception JavaDoc(ex.getLocalizedMessage());
331          }
332      }
333      
334      private static Map JavaDoc getResourceAttributeNames(ObjectName JavaDoc objName, ServerInterface mejb) throws Exception JavaDoc {
335          try{
336              Map JavaDoc attributeInfos = new java.util.HashMap JavaDoc();
337              javax.management.MBeanInfo JavaDoc info = mejb.getMBeanInfo(objName);
338              javax.management.MBeanAttributeInfo JavaDoc[] attrs = info.getAttributes();
339              for (int i=0; i<attrs.length; i++) {
340                  if(attrs[i] != null){
341                      attributeInfos.put(attrs[i].getName(), attrs[i]);
342                  }
343              }
344              return attributeInfos;
345          }catch(Exception JavaDoc ex){
346              throw new Exception JavaDoc(ex.getLocalizedMessage());
347          }
348      }
349      
350      private static void addNewExtraProperties(ObjectName JavaDoc objName, Properties JavaDoc props, AttributeList JavaDoc attrList, ServerInterface mejb) throws Exception JavaDoc {
351          try{
352              String JavaDoc[] signature = new String JavaDoc[]{"javax.management.Attribute"}; //NOI18N
353
Object JavaDoc[] params = null;
354              if(props.size() > attrList.size()){
355                  java.util.Enumeration JavaDoc listProps = props.propertyNames();
356                  while(listProps.hasMoreElements()){
357                      String JavaDoc propName = listProps.nextElement().toString();
358                      if(! attrList.contains(propName)){
359                          Attribute JavaDoc attr = new Attribute JavaDoc(propName, props.getProperty(propName));
360                          params = new Object JavaDoc[]{attr};
361                          mejb.invoke(objName, WizardConstants.__SetProperty, params, signature);
362                      }
363                  }//while
364
}
365          }catch(Exception JavaDoc ex){
366              throw new Exception JavaDoc(ex.getLocalizedMessage());
367          }
368      }
369      
370     
371     
372     static final String JavaDoc MAP_RESOURCES = "com.sun.appserv:type=resources,category=config";//NOI18N
373
public static void createResource(String JavaDoc operName, Object JavaDoc[] params, ServerInterface mejb) throws Exception JavaDoc{
374         try{
375             ObjectName JavaDoc objName = new ObjectName JavaDoc(MAP_RESOURCES);
376             String JavaDoc[] signature = new String JavaDoc[]{"javax.management.AttributeList", "java.util.Properties", "java.lang.String"}; //NOI18N
377
mejb.invoke(objName, operName, params, signature);
378         }catch(Exception JavaDoc ex){
379             throw new Exception JavaDoc(ex.getLocalizedMessage());
380         }
381     }
382     
383     public static AttributeList JavaDoc getResourceAttributes(JdbcConnectionPool connPool, ServerInterface mejb){
384         AttributeList JavaDoc attrs = new AttributeList JavaDoc();
385         attrs.add(new Attribute JavaDoc(__Name, connPool.getName()));
386         attrs.add(new Attribute JavaDoc(__DatasourceClassname, connPool.getDatasourceClassname()));
387         attrs.add(new Attribute JavaDoc(__ResType, connPool.getResType()));
388         attrs.add(new Attribute JavaDoc(__SteadyPoolSize, connPool.getSteadyPoolSize()));
389         attrs.add(new Attribute JavaDoc(__MaxPoolSize, connPool.getMaxPoolSize()));
390         attrs.add(new Attribute JavaDoc(__MaxWaitTimeInMillis, connPool.getMaxWaitTimeInMillis()));
391         attrs.add(new Attribute JavaDoc(__PoolResizeQuantity, connPool.getPoolResizeQuantity()));
392         attrs.add(new Attribute JavaDoc(__IdleTimeoutInSeconds, connPool.getIdleTimeoutInSeconds()));
393         String JavaDoc isolation = connPool.getTransactionIsolationLevel();
394         if (isolation != null && (isolation.length() == 0 || isolation.equals(NbBundle.getMessage(IsolationLevelEditor.class, "LBL_driver_default"))) ){ //NOI18N
395
isolation = null;
396         }
397         attrs.add(new Attribute JavaDoc(__TransactionIsolationLevel, isolation));
398         attrs.add(new Attribute JavaDoc(__IsIsolationLevelGuaranteed, connPool.getIsIsolationLevelGuaranteed()));
399         attrs.add(new Attribute JavaDoc(__IsConnectionValidationRequired, connPool.getIsConnectionValidationRequired()));
400         attrs.add(new Attribute JavaDoc(__ConnectionValidationMethod, connPool.getConnectionValidationMethod()));
401         attrs.add(new Attribute JavaDoc(__ValidationTableName, connPool.getValidationTableName()));
402         attrs.add(new Attribute JavaDoc(__FailAllConnections, connPool.getFailAllConnections()));
403         attrs.add(new Attribute JavaDoc(__Description, connPool.getDescription()));
404         
405         if(is90Server(mejb)){
406             attrs.add(new Attribute JavaDoc(__NonTransactionalConnections, connPool.getNonTransactionalConnections()));
407             attrs.add(new Attribute JavaDoc(__AllowNonComponentCallers, connPool.getAllowNonComponentCallers()));
408         }
409         return attrs;
410     }
411     
412     public static AttributeList JavaDoc getResourceAttributes(JdbcResource jdbcResource){
413         AttributeList JavaDoc attrs = new AttributeList JavaDoc();
414         attrs.add(new Attribute JavaDoc(__JndiName, jdbcResource.getJndiName()));
415         attrs.add(new Attribute JavaDoc(__PoolName, jdbcResource.getPoolName()));
416         attrs.add(new Attribute JavaDoc(__JdbcObjectType, jdbcResource.getObjectType()));
417         attrs.add(new Attribute JavaDoc(__Enabled, jdbcResource.getEnabled()));
418         attrs.add(new Attribute JavaDoc(__Description, jdbcResource.getDescription()));
419         return attrs;
420     }
421     
422     public static AttributeList JavaDoc getResourceAttributes(PersistenceManagerFactoryResource pmResource){
423         AttributeList JavaDoc attrs = new AttributeList JavaDoc();
424         attrs.add(new Attribute JavaDoc(__JndiName, pmResource.getJndiName()));
425         attrs.add(new Attribute JavaDoc(__FactoryClass, pmResource.getFactoryClass()));
426         attrs.add(new Attribute JavaDoc(__JdbcResourceJndiName, pmResource.getJdbcResourceJndiName()));
427         attrs.add(new Attribute JavaDoc(__Enabled, pmResource.getEnabled()));
428         attrs.add(new Attribute JavaDoc(__Description, pmResource.getDescription()));
429         return attrs;
430     }
431     
432     public static AttributeList JavaDoc getResourceAttributes(AdminObjectResource aoResource){
433         AttributeList JavaDoc attrs = new AttributeList JavaDoc();
434         attrs.add(new Attribute JavaDoc(__JndiName, aoResource.getJndiName()));
435         attrs.add(new Attribute JavaDoc(__Description, aoResource.getDescription()));
436         attrs.add(new Attribute JavaDoc(__Enabled, aoResource.getEnabled()));
437         attrs.add(new Attribute JavaDoc(__JavaMessageResType, aoResource.getResType()));
438         attrs.add(new Attribute JavaDoc(__AdminObjResAdapterName, aoResource.getResAdapter()));
439         return attrs;
440     }
441     
442     public static AttributeList JavaDoc getResourceAttributes(ConnectorResource connResource){
443         AttributeList JavaDoc attrs = new AttributeList JavaDoc();
444         attrs.add(new Attribute JavaDoc(__JndiName, connResource.getJndiName()));
445         attrs.add(new Attribute JavaDoc(__PoolName, connResource.getPoolName()));
446         attrs.add(new Attribute JavaDoc(__Description, connResource.getDescription()));
447         attrs.add(new Attribute JavaDoc(__Enabled, connResource.getEnabled()));
448         return attrs;
449     }
450     
451     public static AttributeList JavaDoc getResourceAttributes(ConnectorConnectionPool connPoolResource){
452         AttributeList JavaDoc attrs = new AttributeList JavaDoc();
453         attrs.add(new Attribute JavaDoc(__Name, connPoolResource.getName()));
454         attrs.add(new Attribute JavaDoc(__ConnectorPoolResAdName, connPoolResource.getResourceAdapterName()));
455         attrs.add(new Attribute JavaDoc(__ConnectorPoolConnDefName, connPoolResource.getConnectionDefinitionName()));
456         return attrs;
457     }
458     
459     public static AttributeList JavaDoc getResourceAttributes(MailResource mailResource){
460         AttributeList JavaDoc attrs = new AttributeList JavaDoc();
461         attrs.add(new Attribute JavaDoc(__JndiName, mailResource.getJndiName()));
462         attrs.add(new Attribute JavaDoc(__StoreProtocol, mailResource.getStoreProtocol()));
463         attrs.add(new Attribute JavaDoc(__StoreProtocolClass, mailResource.getStoreProtocolClass()));
464         attrs.add(new Attribute JavaDoc(__TransportProtocol, mailResource.getTransportProtocol()));
465         attrs.add(new Attribute JavaDoc(__TransportProtocolClass, mailResource.getTransportProtocolClass()));
466         attrs.add(new Attribute JavaDoc(__Host, mailResource.getHost()));
467         attrs.add(new Attribute JavaDoc(__MailUser, mailResource.getUser()));
468         attrs.add(new Attribute JavaDoc(__From, mailResource.getFrom()));
469         attrs.add(new Attribute JavaDoc(__Debug, mailResource.getDebug()));
470         attrs.add(new Attribute JavaDoc(__Enabled, mailResource.getEnabled()));
471         attrs.add(new Attribute JavaDoc(__Description, mailResource.getDescription()));
472         return attrs;
473     }
474     
475     public static AttributeList JavaDoc getResourceAttributes(JmsResource jmsResource){
476         AttributeList JavaDoc attrs = new AttributeList JavaDoc();
477         attrs.add(new Attribute JavaDoc(__JavaMessageJndiName, jmsResource.getJndiName()));
478         attrs.add(new Attribute JavaDoc(__JavaMessageResType, jmsResource.getResType()));
479         attrs.add(new Attribute JavaDoc(__Enabled, jmsResource.getEnabled()));
480         attrs.add(new Attribute JavaDoc(__Description, jmsResource.getDescription()));
481         return attrs;
482     }
483     
484     private static Properties JavaDoc getProperties(PropertyElement[] props) throws Exception JavaDoc {
485         Properties JavaDoc propList = new Properties JavaDoc();
486         for(int i=0; i<props.length; i++){
487             String JavaDoc name = props[i].getName();
488             String JavaDoc value = props[i].getValue();
489             if(value != null && value.trim().length() != 0){
490                 propList.put(name, value);
491             }
492         }
493         return propList;
494     }
495     
496     public List JavaDoc getTargetServers(){
497         String JavaDoc instances [] = InstanceProperties.getInstanceList();
498         List JavaDoc targets = new ArrayList JavaDoc();
499         for (int i=0; i < instances.length; i++) {
500             if (instances[i].startsWith(SunURIManager.SUNSERVERSURI)) {
501                 targets.add(InstanceProperties.getInstanceProperties(instances[i]).getDeploymentManager());
502             }
503             else if (instances[i].startsWith("[")) {
504                 targets.add(InstanceProperties.getInstanceProperties(instances[i]).getDeploymentManager());
505             }
506         }
507         //This returns the deploymanager uri. Can we go from this to getting deployment manager??
508
//deployer:Sun:AppServer::localhost:4848
509
// String[] targetArray = instanceProperties.getInstanceList();
510
//}
511
return targets;
512     }
513     
514     public static void saveConnPoolDatatoXml(ResourceConfigData data) {
515         try{
516             Vector JavaDoc vec = data.getProperties();
517             Resources res = getResourceGraph();
518             JdbcConnectionPool connPool = res.newJdbcConnectionPool();
519             
520             String JavaDoc[] keys = data.getFieldNames();
521             for (int i = 0; i < keys.length; i++) {
522                 String JavaDoc key = keys[i];
523                 if (key.equals(__Properties)){
524                     Vector JavaDoc props = (Vector JavaDoc)data.getProperties();
525                     for (int j = 0; j < props.size(); j++) {
526                         NameValuePair pair = (NameValuePair)props.elementAt(j);
527                         PropertyElement prop = connPool.newPropertyElement();
528                         prop = populatePropertyElement(prop, pair);
529                         connPool.addPropertyElement(prop);
530                     }
531                 }else{
532                     String JavaDoc value = data.getString(key);
533                     if (key.equals(__Name)){
534                         connPool.setName(value);
535                         data.setTargetFile(value);
536                     }else if (key.equals(__DatasourceClassname))
537                         connPool.setDatasourceClassname(value);
538                     else if (key.equals(__ResType))
539                         connPool.setResType(value);
540                     else if (key.equals(__SteadyPoolSize))
541                         connPool.setSteadyPoolSize(value);
542                     else if (key.equals(__MaxPoolSize))
543                         connPool.setMaxPoolSize(value);
544                     else if (key.equals(__MaxWaitTimeInMillis))
545                         connPool.setMaxWaitTimeInMillis(value);
546                     else if (key.equals(__PoolResizeQuantity))
547                         connPool.setPoolResizeQuantity(value);
548                     else if (key.equals(__IdleTimeoutInSeconds))
549                         connPool.setIdleTimeoutInSeconds(value);
550                     else if (key.equals(__TransactionIsolationLevel)){
551                         if (value.equals(NbBundle.getMessage(IsolationLevelEditor.class, "LBL_driver_default"))){ //NOI18N
552
value = null;
553                         }
554                         connPool.setTransactionIsolationLevel(value);
555                     }else if (key.equals(__IsIsolationLevelGuaranteed))
556                         connPool.setIsIsolationLevelGuaranteed(value);
557                     else if (key.equals(__IsConnectionValidationRequired))
558                         connPool.setIsConnectionValidationRequired(value);
559                     else if (key.equals(__ConnectionValidationMethod))
560                         connPool.setConnectionValidationMethod(value);
561                     else if (key.equals(__ValidationTableName))
562                         connPool.setValidationTableName(value);
563                     else if (key.equals(__FailAllConnections))
564                         connPool.setFailAllConnections(value);
565                     else if (key.equals(__Description))
566                         connPool.setDescription(value);
567                     else if (key.equals(__NonTransactionalConnections))
568                         connPool.setNonTransactionalConnections(value);
569                     else if (key.equals(__AllowNonComponentCallers))
570                         connPool.setAllowNonComponentCallers(value);
571                 }
572                 
573             } //for
574
res.addJdbcConnectionPool(connPool);
575             createFile(data.getTargetFileObject(), data.getTargetFile(), res);
576         }catch(Exception JavaDoc ex){
577             System.out.println("Unable to saveConnPoolDatatoXml ");
578         }
579     }
580     
581     public static void saveJDBCResourceDatatoXml(ResourceConfigData dsData, ResourceConfigData cpData) {
582         try{
583             Resources res = getResourceGraph();
584             JdbcResource datasource = res.newJdbcResource();
585            
586             String JavaDoc[] keys = dsData.getFieldNames();
587             for (int i = 0; i < keys.length; i++) {
588                 String JavaDoc key = keys[i];
589                 if (key.equals(__Properties)){
590                     Vector JavaDoc props = (Vector JavaDoc)dsData.getProperties();
591                     for (int j = 0; j < props.size(); j++) {
592                         NameValuePair pair = (NameValuePair)props.elementAt(j);
593                         PropertyElement prop = datasource.newPropertyElement();
594                         prop = populatePropertyElement(prop, pair);
595                         datasource.addPropertyElement(prop);
596                     }
597                 }else{
598                     String JavaDoc value = dsData.getString(key);
599                     if (key.equals(__JndiName)){
600                         datasource.setJndiName(value);
601                         dsData.setTargetFile(value);
602                     }else if (key.equals(__PoolName))
603                         datasource.setPoolName(value);
604                     else if (key.equals(__JdbcObjectType))
605                         datasource.setObjectType(value);
606                     else if (key.equals(__Enabled))
607                         datasource.setEnabled(value);
608                     else if (key.equals(__Description))
609                         datasource.setDescription(value);
610                 }
611                 
612             } //for
613
res.addJdbcResource(datasource);
614             if(cpData != null){
615                 saveConnPoolDatatoXml(cpData);
616             }
617             createFile(dsData.getTargetFileObject(), dsData.getTargetFile(), res);
618         }catch(Exception JavaDoc ex){
619             ex.printStackTrace();
620             System.out.println("Unable to saveJDBCResourceDatatoXml ");
621         }
622     }
623     
624     public static void savePMFResourceDatatoXml(ResourceConfigData pmfData, ResourceConfigData dsData, ResourceConfigData cpData) {
625         try{
626             Resources res = getResourceGraph();
627             PersistenceManagerFactoryResource pmfresource = res.newPersistenceManagerFactoryResource();
628            
629             String JavaDoc[] keys = pmfData.getFieldNames();
630             for (int i = 0; i < keys.length; i++) {
631                 String JavaDoc key = keys[i];
632                 if (key.equals(__Properties)){
633                     Vector JavaDoc props = (Vector JavaDoc)pmfData.getProperties();
634                     for (int j = 0; j < props.size(); j++) {
635                         NameValuePair pair = (NameValuePair)props.elementAt(j);
636                         PropertyElement prop = pmfresource.newPropertyElement();
637                         prop = populatePropertyElement(prop, pair);
638                         pmfresource.addPropertyElement(prop);
639                     }
640                 }else{
641                     String JavaDoc value = pmfData.getString(key);
642                     if (key.equals(__JndiName)){
643                         pmfresource.setJndiName(value);
644                         pmfData.setTargetFile(value);
645                     }else if (key.equals(__FactoryClass))
646                         pmfresource.setFactoryClass(value);
647                     else if (key.equals(__JdbcResourceJndiName))
648                         pmfresource.setJdbcResourceJndiName(value);
649                     else if (key.equals(__Enabled))
650                         pmfresource.setEnabled(value);
651                     else if (key.equals(__Description))
652                         pmfresource.setDescription(value);
653                 }
654
655             } //for
656
res.addPersistenceManagerFactoryResource(pmfresource);
657             createFile(pmfData.getTargetFileObject(), pmfData.getTargetFile(), res);
658             
659             if(dsData != null){
660                 saveJDBCResourceDatatoXml(dsData, cpData);
661             }
662         }catch(Exception JavaDoc ex){
663             System.out.println("Unable to savePMFResourceDatatoXml ");
664         }
665     }
666     
667     public static void saveJMSResourceDatatoXml(ResourceConfigData jmsData) {
668         try{
669             Resources res = getResourceGraph();
670             String JavaDoc type = jmsData.getString(__ResType);
671             if(type.equals(__QUEUE) || type.equals(__TOPIC)){
672                 AdminObjectResource aoresource = res.newAdminObjectResource();
673                 aoresource.setDescription(jmsData.getString(__Description));
674                 aoresource.setEnabled(jmsData.getString(__Enabled));
675                 aoresource.setJndiName(jmsData.getString(__JndiName));
676                 aoresource.setResType(jmsData.getString(__ResType));
677                 aoresource.setResAdapter(__JmsResAdapter);
678                 Vector JavaDoc props = (Vector JavaDoc)jmsData.getProperties();
679                 for (int j = 0; j < props.size(); j++) {
680                     NameValuePair pair = (NameValuePair)props.elementAt(j);
681                     PropertyElement prop = aoresource.newPropertyElement();
682                     prop = populatePropertyElement(prop, pair);
683                     aoresource.addPropertyElement(prop);
684                 }
685                 
686                 res.addAdminObjectResource(aoresource);
687             }else{
688                 ConnectorResource connresource = res.newConnectorResource();
689                 connresource.setDescription(jmsData.getString(__Description));
690                 connresource.setEnabled(jmsData.getString(__Enabled));
691                 connresource.setJndiName(jmsData.getString(__JndiName));
692                 connresource.setPoolName(jmsData.getString(__JndiName));
693                 
694                 ConnectorConnectionPool connpoolresource = res.newConnectorConnectionPool();
695                 connpoolresource.setName(jmsData.getString(__JndiName));
696                 connpoolresource.setConnectionDefinitionName(jmsData.getString(__ResType));
697                 connpoolresource.setResourceAdapterName(__JmsResAdapter);
698                 
699                 Vector JavaDoc props = (Vector JavaDoc)jmsData.getProperties();
700                 for (int j = 0; j < props.size(); j++) {
701                     NameValuePair pair = (NameValuePair)props.elementAt(j);
702                     PropertyElement prop = connpoolresource.newPropertyElement();
703                     prop = populatePropertyElement(prop, pair);
704                     connpoolresource.addPropertyElement(prop);
705                 }
706                 
707                 res.addConnectorResource(connresource);
708                 res.addConnectorConnectionPool(connpoolresource);
709             }
710             
711             createFile(jmsData.getTargetFileObject(), jmsData.getTargetFile(), res);
712         }catch(Exception JavaDoc ex){
713             ex.printStackTrace();
714             System.out.println("Unable to saveJMSResourceDatatoXml ");
715         }
716     }
717     
718     public static void saveMailResourceDatatoXml(ResourceConfigData data) {
719         try{
720             Vector JavaDoc vec = data.getProperties();
721             Resources res = getResourceGraph();
722             MailResource mlresource = res.newMailResource();
723                         
724             String JavaDoc[] keys = data.getFieldNames();
725             for (int i = 0; i < keys.length; i++) {
726                 String JavaDoc key = keys[i];
727                 if (key.equals(__Properties)) {
728                     Vector JavaDoc props = (Vector JavaDoc)data.getProperties();
729                     for (int j = 0; j < props.size(); j++) {
730                         NameValuePair pair = (NameValuePair)props.elementAt(j);
731                         PropertyElement prop = mlresource.newPropertyElement();
732                         prop = populatePropertyElement(prop, pair);
733                         mlresource.addPropertyElement(prop);
734                     }
735                 }else{
736                     String JavaDoc value = data.getString(key);
737                     if (key.equals(__JndiName)){
738                         mlresource.setJndiName(value);
739                         data.setTargetFile(value);
740                     }else if (key.equals(__StoreProtocol))
741                         mlresource.setStoreProtocol(value);
742                     else if (key.equals(__StoreProtocolClass))
743                         mlresource.setStoreProtocolClass(value);
744                     else if (key.equals(__TransportProtocol))
745                         mlresource.setTransportProtocol(value);
746                     else if (key.equals(__TransportProtocolClass))
747                         mlresource.setTransportProtocolClass(value);
748                     else if (key.equals(__Host))
749                         mlresource.setHost(value);
750                     else if (key.equals(__MailUser))
751                         mlresource.setUser(value);
752                     else if (key.equals(__From))
753                         mlresource.setFrom(value);
754                     else if (key.equals(__Debug))
755                         mlresource.setDebug(value);
756                     else if (key.equals(__Description))
757                         mlresource.setDescription(value);
758                 }
759             } //for
760

761             res.addMailResource(mlresource);
762             createFile(data.getTargetFileObject(), data.getTargetFile(), res);
763         }catch(Exception JavaDoc ex){
764             System.out.println("Unable to saveMailResourceDatatoXml ");
765         }
766     }
767     
768     public static void createFile(FileObject targetFolder, String JavaDoc filename, final Resources res){
769         try{
770             //jdbc and jdo jndi names might be of format jdbc/ and jdo/
771
if(filename.indexOf("/") != -1){ //NOI18N
772
filename = filename.substring(0, filename.indexOf("/")) + "_" + filename.substring(filename.indexOf("/")+1, filename.length()); //NOI18N
773
}
774             if(filename.indexOf("\\") != -1){ //NOI18N
775
filename = filename.substring(0, filename.indexOf("\\")) + "_" + filename.substring(filename.indexOf("\\")+1, filename.length()); //NOI18N
776
}
777             String JavaDoc oldName = filename;
778             targetFolder = setUpExists(targetFolder);
779             filename = FileUtil.findFreeFileName(targetFolder, filename, __SunResourceExt);
780                     
781             final String JavaDoc resFileName = filename;
782             final FileObject resTargetFolder = targetFolder;
783             FileSystem fs = targetFolder.getFileSystem();
784             fs.runAtomicAction(new FileSystem.AtomicAction() {
785                 public void run() throws java.io.IOException JavaDoc {
786                     FileObject newfile = resTargetFolder.createData(resFileName, "sun-resource"); //NOI18N
787

788                     FileLock lock = newfile.lock();
789                     Writer JavaDoc w = null;
790                     try {
791                         Writer JavaDoc out = new OutputStreamWriter JavaDoc(newfile.getOutputStream(lock), "UTF8");
792                         res.write(out);
793                         out.flush();
794                         out.close();
795                     } catch(Exception JavaDoc ex){
796                         //Error writing file
797
} finally {
798                         lock.releaseLock();
799                     }
800                 }
801             });
802         }catch(Exception JavaDoc ex){
803             //Unable to create file
804
System.out.println("Error while creating file");
805         }
806     }
807     
808     public static String JavaDoc createUniqueFileName(String JavaDoc in_targetName, FileObject fo, String JavaDoc defName){
809         String JavaDoc targetName = in_targetName;
810         if (targetName == null || targetName.length() == 0)
811             targetName = defName;
812         
813         targetName = makeLegalFilename(targetName);
814         targetName = FileUtil.findFreeFileName(fo, targetName, __SunResourceExt);
815         targetName = revertToResName(targetName);
816         return targetName;
817     }
818     
819     public static List JavaDoc getRegisteredConnectionPools(ResourceConfigData data){
820         List JavaDoc connPools = new ArrayList JavaDoc();
821         try {
822             String JavaDoc OPER_OBJ_ConnPoolResource = "getJdbcConnectionPool"; //NOI18N
823
String JavaDoc keyProp = "name"; //NOI18N
824
InstanceProperties instanceProperties = getTargetServer(data.getTargetFileObject());
825             if(instanceProperties != null)
826                 connPools = getResourceNames(instanceProperties, OPER_OBJ_ConnPoolResource, keyProp);
827             connPools.removeAll(Arrays.asList(sysConnpools));
828             List JavaDoc projectCP = getProjectResources(data, __ConnectionPoolResource);
829             for(int i=0; i<projectCP.size(); i++){
830                 String JavaDoc localCP = projectCP.get(i).toString();
831                 if(! connPools.contains(localCP))
832                     connPools.add(localCP);
833             }
834         } catch (java.lang.NoClassDefFoundError JavaDoc ncdfe) {
835             // this happens durring unit tests for the DataSourceWizard
836
}
837         return connPools;
838     }
839     
840     public static List JavaDoc getRegisteredJdbcResources(ResourceConfigData data){
841         List JavaDoc dataSources = new ArrayList JavaDoc();
842         try {
843             String JavaDoc keyProp = "jndi-name"; //NOI18N
844
InstanceProperties instanceProperties = getTargetServer(data.getTargetFileObject());
845             if(instanceProperties != null)
846                 dataSources = getResourceNames(instanceProperties, WizardConstants.__GetJdbcResource, keyProp);
847             dataSources.removeAll(Arrays.asList(sysDatasources));
848             List JavaDoc projectDS = getProjectResources(data, __JDBCResource);
849             for(int i=0; i<projectDS.size(); i++){
850                 String JavaDoc localDS = projectDS.get(i).toString();
851                 if(! dataSources.contains(localDS))
852                     dataSources.add(localDS);
853             }
854         } catch (java.lang.NoClassDefFoundError JavaDoc ncdfe) {
855             // this happens durring unit tests for the PMFWizard
856
}
857         return dataSources;
858     }
859     
860     private static List JavaDoc getResourceNames(InstanceProperties instProps, String JavaDoc query, String JavaDoc keyProperty){
861         Object JavaDoc tmp = instProps.getDeploymentManager();
862         List JavaDoc retVal;
863         if (tmp instanceof SunDeploymentManagerInterface) {
864             SunDeploymentManagerInterface eightDM = (SunDeploymentManagerInterface)tmp;
865             retVal = getResourceNames(eightDM, query, keyProperty);
866         } else {
867             retVal = Collections.EMPTY_LIST;
868         }
869         return retVal;
870     }
871     
872     private static List JavaDoc getResourceNames(SunDeploymentManagerInterface eightDM, String JavaDoc query, String JavaDoc keyProperty){
873         List JavaDoc resList = new ArrayList JavaDoc();
874         String JavaDoc MAP_RESOURCES = "com.sun.appserv:type=resources,category=config";//NOI18N
875
try{
876             ServerInterface mejb = (ServerInterface)eightDM.getManagement();
877             ObjectName JavaDoc objName = new ObjectName JavaDoc(MAP_RESOURCES);
878             ObjectName JavaDoc[] beans = (ObjectName JavaDoc[])mejb.invoke(objName, query, null, null);
879             for(int i=0; i<beans.length; i++){
880                 String JavaDoc resName = ((ObjectName JavaDoc)beans[i]).getKeyProperty(keyProperty);
881                 resList.add(resName);
882             }
883         }catch(Exception JavaDoc ex){
884             //Suppress exception when unable to get resource names
885
//Possibe errors: deafult server is not Sun Application Server (classcast exception)
886
//Application server is not running.
887
}
888         return resList;
889     }
890     
891     private static List JavaDoc getProjectResources(ResourceConfigData data, String JavaDoc resourceType){
892         List JavaDoc projectResources = new ArrayList JavaDoc();
893         FileObject targetFolder = data.getTargetFileObject();
894         if(targetFolder != null){
895             FileObject setUpFolder = setUpExists(targetFolder);
896             java.util.Enumeration JavaDoc en = setUpFolder.getData(false);
897             while(en.hasMoreElements()){
898                 FileObject resourceFile = (FileObject)en.nextElement();
899                 File JavaDoc resource = FileUtil.toFile(resourceFile);
900                 if(resourceType.equals(__ConnectionPoolResource))
901                     projectResources = filterConnectionPools(resource, projectResources);
902                 else
903                     projectResources = filterDataSources(resource, projectResources);
904             }
905         }
906         return projectResources;
907     }
908     
909     private static List JavaDoc filterConnectionPools(File JavaDoc primaryFile, List JavaDoc projectCP){
910         try{
911             if(! primaryFile.isDirectory()){
912                 FileInputStream JavaDoc in = new FileInputStream JavaDoc(primaryFile);
913                 Resources resources = DDProvider.getDefault().getResourcesGraph(in);
914                 
915                 // identify JDBC Connection Pool xml
916
JdbcConnectionPool[] pools = resources.getJdbcConnectionPool();
917                 for(int i=0; i<pools.length; i++){
918                     projectCP.add(pools[i].getName());
919                 }
920             }
921         }catch(Exception JavaDoc exception){
922             //Could not get list of local Connection pools
923
}
924         return projectCP;
925     }
926     
927     private static List JavaDoc filterDataSources(File JavaDoc primaryFile, List JavaDoc projectDS){
928         try{
929             if(! primaryFile.isDirectory()){
930                 FileInputStream JavaDoc in = new FileInputStream JavaDoc(primaryFile);
931                 Resources resources = DDProvider.getDefault().getResourcesGraph(in);
932                 
933                 // identify JDBC Resources xml
934
JdbcResource[] dataSources = resources.getJdbcResource();
935                 for(int i=0; i<dataSources.length; i++){
936                     projectDS.add(dataSources[i].getJndiName());
937                 }
938             }
939         }catch(Exception JavaDoc exception){
940             //Could not get list of local Connection pools
941
}
942         return projectDS;
943     }
944     
945     public static FileObject setUpExists(FileObject targetFolder){
946         FileObject pkgLocation = getResourceDirectory(targetFolder);
947         if(pkgLocation == null){
948             //resource will be created under existing structure
949
return targetFolder;
950         }else{
951             return pkgLocation;
952         }
953     }
954     
955     private static Resources getResourceGraph(){
956         return DDProvider.getDefault().getResourcesGraph();
957     }
958     
959     private static PropertyElement populatePropertyElement(PropertyElement prop, NameValuePair pair){
960         prop.setName(pair.getParamName());
961         prop.setValue(pair.getParamValue());
962         return prop;
963     }
964     
965     //Obtained from com.iplanet.ias.util.io.FileUtils - Byron's
966
public static boolean isLegalFilename(String JavaDoc filename) {
967         for(int i = 0; i < ILLEGAL_FILENAME_CHARS.length; i++)
968             if(filename.indexOf(ILLEGAL_FILENAME_CHARS[i]) >= 0)
969                 return false;
970         
971         return true;
972     }
973     
974     public static boolean isFriendlyFilename(String JavaDoc filename) {
975         if(filename.indexOf(BLANK) >= 0 || filename.indexOf(DOT) >= 0)
976             return false;
977         
978         return isLegalFilename(filename);
979     }
980     
981     public static String JavaDoc makeLegalFilename(String JavaDoc filename) {
982         for(int i = 0; i < ILLEGAL_FILENAME_CHARS.length; i++)
983             filename = filename.replace(ILLEGAL_FILENAME_CHARS[i], REPLACEMENT_CHAR);
984         
985         return filename;
986     }
987     
988     public static boolean isLegalResourceName(String JavaDoc filename) {
989         for(int i = 0; i < ILLEGAL_RESOURCE_NAME_CHARS.length; i++)
990             if(filename.indexOf(ILLEGAL_RESOURCE_NAME_CHARS[i]) >= 0)
991                 return false;
992         
993         return true;
994     }
995     
996     public static FileObject getResourceDirectory(FileObject fo){
997         Project holdingProj = FileOwnerQuery.getOwner(fo);
998         FileObject resourceDir = null;
999         if (holdingProj != null){
1000            J2eeModuleProvider provider = (J2eeModuleProvider) holdingProj.getLookup().lookup(J2eeModuleProvider.class);
1001            if(provider != null){
1002                File JavaDoc resourceLoc = provider.getEnterpriseResourceDirectory ();
1003                if(resourceLoc != null){
1004                    if(resourceLoc.exists ()){
1005                        resourceDir = FileUtil.toFileObject (resourceLoc);
1006                    }else{
1007                        resourceLoc.mkdirs ();
1008                        resourceDir = FileUtil.toFileObject (resourceLoc);
1009                    }
1010                }
1011            } else { // TODO : retouche migration -- remove when java ee projects come back
1012
resourceDir = fo.getFileObject("setup");
1013            }
1014        }
1015        return resourceDir;
1016    }
1017    
1018    /***************************************** DS Management API *****************************************************************************/
1019    
1020    public static HashSet JavaDoc getServerDataSources(DeploymentManager JavaDoc dm){
1021        HashSet JavaDoc datasources = new HashSet JavaDoc();
1022        try {
1023            ObjectName JavaDoc configObjName = new ObjectName JavaDoc(WizardConstants.MAP_RESOURCES);
1024            SunDeploymentManagerInterface eightDM = (SunDeploymentManagerInterface)dm;
1025            ServerInterface mejb = (ServerInterface)eightDM.getManagement();
1026            List JavaDoc systemDS = Arrays.asList(sysDatasources);
1027            if(eightDM.isRunning()){
1028                updateSampleDatasource(eightDM, configObjName);
1029                ObjectName JavaDoc[] resourceObjects = (ObjectName JavaDoc[]) mejb.invoke(configObjName, WizardConstants.__GetJdbcResource, null, null);
1030                for(int i=0; i<resourceObjects.length; i++){
1031                    ObjectName JavaDoc objName = resourceObjects[i];
1032                    //Get Required values from JDBC Resource
1033
String JavaDoc dsJndiName = (String JavaDoc)mejb.getAttribute(objName, "jndi-name"); //NOI18N
1034
if(! systemDS.contains(dsJndiName)){
1035                        String JavaDoc poolName = (String JavaDoc)mejb.getAttribute(objName, "pool-name"); //NOI18N
1036
HashMap JavaDoc poolValues = fillInPoolValues(eightDM, configObjName, poolName);
1037                        if(! poolValues.isEmpty()){
1038                            String JavaDoc username = (String JavaDoc)poolValues.get(WizardConstants.__User);
1039                            String JavaDoc password = (String JavaDoc)poolValues.get(WizardConstants.__Password);
1040                            String JavaDoc url = (String JavaDoc)poolValues.get(WizardConstants.__Url);
1041                            String JavaDoc driverClassName = (String JavaDoc)poolValues.get(WizardConstants.__DriverClassName);
1042                            
1043                            SunDatasource ds = new SunDatasource(dsJndiName, url, username, password, driverClassName);
1044                            datasources.add(ds);
1045                        }
1046                    }
1047                } // for - each JDBC Resource
1048
} else{
1049                if(eightDM.isLocal()) {
1050                    datasources = formatXmlSunDatasources(eightDM.getSunDatasourcesFromXml());
1051                }
1052            }// Server Running
1053
} catch (Exception JavaDoc ex) {
1054            //Unable to get server datasources
1055
}
1056        return datasources;
1057    }
1058    
1059    private static void updateSampleDatasource(SunDeploymentManagerInterface eightDM, ObjectName JavaDoc configObjName){
1060        try{
1061            if(! eightDM.isLocal())
1062                return;
1063            List JavaDoc datasources = getResourceNames(eightDM, __GetJdbcResource, "jndi-name"); //NOI18N
1064
if(! datasources.contains(SAMPLE_DATASOURCE)){
1065                ServerInterface mejb = (ServerInterface)eightDM.getManagement();
1066                
1067                if(getConnectionPoolObjByName(mejb, configObjName, SAMPLE_CONNPOOL) == null){
1068                    AttributeList JavaDoc poolAttrs = new AttributeList JavaDoc();
1069                    Attribute JavaDoc attr = new Attribute JavaDoc("name", SAMPLE_CONNPOOL); //NOI18N
1070
poolAttrs.add(attr);
1071                    attr = new Attribute JavaDoc("datasource-classname", "org.apache.derby.jdbc.ClientDataSource"); //NOI18N
1072
poolAttrs.add(attr);
1073                    attr = new Attribute JavaDoc("res-type", "javax.sql.DataSource"); //NOI18N
1074
poolAttrs.add(attr);
1075                    
1076                    Properties JavaDoc propsList = new Properties JavaDoc();
1077                    propsList.put(__User, "app"); //NOI18N
1078
propsList.put(__Password, "app"); //NOI18N
1079
propsList.put(__ServerName, "localhost"); //NOI18N
1080
propsList.put(__DerbyPortNumber, "1527");
1081                    propsList.put(__DerbyDatabaseName, "sample"); //NOI18N
1082
Object JavaDoc[] poolParams = new Object JavaDoc[]{poolAttrs, propsList, null};
1083                    createResource(__CreateCP, poolParams, mejb);
1084                }
1085                
1086                AttributeList JavaDoc attrs = new AttributeList JavaDoc();
1087                attrs.add(new Attribute JavaDoc(__JndiName, SAMPLE_DATASOURCE));
1088                attrs.add(new Attribute JavaDoc(__PoolName, SAMPLE_CONNPOOL));
1089                attrs.add(new Attribute JavaDoc(__JdbcObjectType, "user")); //NOI18N
1090
attrs.add(new Attribute JavaDoc(__Enabled, "true")); //NOI18N
1091
Object JavaDoc[] params = new Object JavaDoc[]{attrs, new Properties JavaDoc(), null};
1092                createResource(__CreateDS, params, mejb);
1093            }
1094        }catch(Exception JavaDoc ex){}
1095    }
1096    
1097    public static HashMap JavaDoc fillInPoolValues(SunDeploymentManagerInterface eightDM, ObjectName JavaDoc configObjName, String JavaDoc poolName) throws Exception JavaDoc {
1098        HashMap JavaDoc connPoolAttrs = new HashMap JavaDoc();
1099        ServerInterface mejb = (ServerInterface)eightDM.getManagement();
1100        //Get Values from JDBC Connection Pool : driver
1101
ObjectName JavaDoc connPoolObj = getConnectionPoolByName(mejb, configObjName, poolName);
1102        String JavaDoc driverClassName = (String JavaDoc)mejb.getAttribute(connPoolObj, "datasource-classname"); //NOI18N
1103
String JavaDoc url = ""; //NOI18N
1104
String JavaDoc username = ""; //NOI18N
1105
String JavaDoc password = ""; //NOI18N
1106
String JavaDoc serverName = ""; //NOI18N
1107
String JavaDoc portNo = ""; //NOI18N
1108
String JavaDoc dbName = ""; //NOI18N
1109
String JavaDoc sid = ""; //NOI18N
1110

1111        AttributeList JavaDoc attrList = (AttributeList JavaDoc)mejb.invoke(connPoolObj, WizardConstants.__GetProperties, null, null);
1112        HashMap JavaDoc attrs = getObjMap(attrList);
1113        Object JavaDoc[] keys = attrs.keySet().toArray();
1114        for(int i=0; i<keys.length; i++){
1115            String JavaDoc keyName = (String JavaDoc)keys[i];
1116            if(keyName.equalsIgnoreCase(WizardConstants.__DatabaseName)){
1117                if(driverClassName.indexOf("pointbase") != -1){ //NOI18N
1118
url = getStringVal(attrs.get(keyName));
1119                }else{
1120                    dbName = getStringVal(attrs.get(keyName));
1121                }
1122            }else if(keyName.equalsIgnoreCase(WizardConstants.__User)) {
1123                username = getStringVal(attrs.get(keyName));
1124            }else if(keyName.equalsIgnoreCase(WizardConstants.__Password)) {
1125                password = getStringVal(attrs.get(keyName));
1126            }else if(keyName.equalsIgnoreCase(WizardConstants.__Url)) {
1127                url = getStringVal(attrs.get(keyName));
1128            }else if(keyName.equalsIgnoreCase(WizardConstants.__ServerName)) {
1129                serverName = getStringVal(attrs.get(keyName));
1130            }else if(keyName.equalsIgnoreCase(WizardConstants.__DerbyPortNumber)) {
1131                portNo = getStringVal(attrs.get(keyName));
1132            }else if(keyName.equalsIgnoreCase(WizardConstants.__SID)) {
1133                sid = getStringVal(attrs.get(keyName));
1134            }
1135        }
1136        
1137        if(driverClassName.indexOf("derby") != -1){ //NOI18N
1138
url = "jdbc:derby://"; //NOI18N
1139
if(serverName != null){
1140                url = url + serverName;
1141                if(portNo != null) {
1142                    url = url + ":" + portNo; //NOI18N
1143
}
1144                url = url + "/" + dbName ; //NOI8N
1145
}
1146        }else if(url.equals("")) { //NOI18N
1147
String JavaDoc urlPrefix = DatabaseUtils.getUrlPrefix(driverClassName);
1148            String JavaDoc vName = ResourceConfigurator.getDatabaseVendorName(urlPrefix, null);
1149            if(serverName != null){
1150                if(vName.equals("sybase2")){ //NOI18N
1151
url = urlPrefix + serverName;
1152                } else{
1153                    url = urlPrefix + "//" + serverName; //NOI18N
1154
}
1155                if(portNo != null) {
1156                    url = url + ":" + portNo; //NOI18N
1157
}
1158            }
1159            if(vName.equals("sun_oracle") || vName.equals("datadirect_oracle")) { //NOI18N
1160
url = url + ";SID=" + sid; //NOI18N
1161
}else if(Arrays.asList(WizardConstants.Reqd_DBName).contains(vName)) {
1162                url = url + ";databaseName=" + dbName; //NOI18N
1163
}else if(Arrays.asList(WizardConstants.VendorsDBNameProp).contains(vName)) {
1164                url = url + "/" + dbName ; //NOI8N
1165
}
1166        }
1167        
1168        if((! eightDM.isLocal()) && (url.indexOf("localhost") != -1)){ //NOI18N
1169
String JavaDoc hostName = eightDM.getHost();
1170            url = url.replaceFirst("localhost", hostName); //NOI18N
1171
}
1172        DatabaseConnection databaseConnection = getDatabaseConnection(url);
1173        if(databaseConnection != null){
1174            driverClassName = databaseConnection.getDriverClass();
1175        }else{
1176            //Fix Issue 78212 - NB required driver classname
1177
String JavaDoc drivername = DatabaseUtils.getDriverName(url);
1178            if(drivername != null) {
1179                driverClassName = drivername;
1180            }
1181        }
1182        
1183        connPoolAttrs.put(__User, username);
1184        connPoolAttrs.put(__Password, password);
1185        connPoolAttrs.put(__Url, url);
1186        connPoolAttrs.put(__DriverClassName, driverClassName);
1187        return connPoolAttrs;
1188    }
1189    
1190    private static ObjectName JavaDoc getConnectionPoolByName(ServerInterface mejb, ObjectName JavaDoc configObjName, String JavaDoc poolName) throws Exception JavaDoc {
1191        String JavaDoc[] signature = new String JavaDoc[]{"java.lang.String"}; //NOI18N
1192
Object JavaDoc[] params = new Object JavaDoc[]{poolName};
1193        ObjectName JavaDoc connPoolObj = (ObjectName JavaDoc) mejb.invoke(configObjName, WizardConstants.__GetJdbcConnectionPoolByName, params, signature);
1194        return connPoolObj;
1195    }
1196    
1197    private static ObjectName JavaDoc getConnectionPoolObjByName(ServerInterface mejb, ObjectName JavaDoc configObjName, String JavaDoc poolName) {
1198        ObjectName JavaDoc connPoolObj = null;
1199        try{
1200            connPoolObj = getConnectionPoolByName(mejb, configObjName, poolName);
1201        }catch(Exception JavaDoc ex){}
1202        return connPoolObj;
1203    }
1204        
1205    
1206    private static String JavaDoc getStringVal(Object JavaDoc val){
1207        String JavaDoc value = null;
1208        if (val != null)
1209            value = val.toString();
1210        return value;
1211    }
1212    
1213    private static HashMap JavaDoc getObjMap(AttributeList JavaDoc attrList){
1214        HashMap JavaDoc attrs = new HashMap JavaDoc();
1215        for(int k=0; k<attrList.size(); k++){
1216            Attribute JavaDoc currAttr = (Attribute JavaDoc)attrList.get(k);
1217            String JavaDoc pname = currAttr.getName();
1218            Object JavaDoc pObjvalue = currAttr.getValue();
1219            attrs.put(pname, pObjvalue);
1220        }
1221        return attrs;
1222    }
1223    
1224    public static String JavaDoc revertToResName(String JavaDoc filename) {
1225        if(filename.indexOf("jdbc_") != -1)
1226            filename = filename.replaceFirst("jdbc_", "jdbc/");
1227        if(filename.indexOf("mail_") != -1)
1228            filename = filename.replaceFirst("mail_", "mail/");
1229        if(filename.indexOf("jms_") != -1)
1230            filename = filename.replaceFirst("jms_", "jms/");
1231        return filename;
1232    }
1233    
1234    public static boolean isUniqueFileName(String JavaDoc in_targetName, FileObject fo, String JavaDoc defName){
1235        boolean isUniq = true;
1236        String JavaDoc targetName = in_targetName;
1237        if (targetName != null && targetName.length() != 0) {
1238              targetName = makeLegalFilename(targetName);
1239              targetName = targetName + "." + __SunResourceExt; //NOI18N
1240
File JavaDoc targFile = new File JavaDoc(fo.getPath(), targetName);
1241              if(targFile.exists())
1242                  isUniq = false;
1243        }
1244        return isUniq;
1245    }
1246    
1247    public static DatabaseConnection getDatabaseConnection(String JavaDoc url) {
1248        DatabaseConnection[] dbConns = ConnectionManager.getDefault().getConnections();
1249        for(int i=0; i<dbConns.length; i++){
1250            String JavaDoc dbConnUrl = ((DatabaseConnection)dbConns[i]).getDatabaseURL();
1251            if(dbConnUrl.startsWith(url))
1252                return ((DatabaseConnection)dbConns[i]);
1253        }
1254        return null;
1255    }
1256    
1257    public static InstanceProperties getTargetServer(FileObject fo){
1258        InstanceProperties serverName = null;
1259        Project holdingProj = FileOwnerQuery.getOwner(fo);
1260        if (holdingProj != null){
1261            J2eeModuleProvider modProvider = (J2eeModuleProvider) holdingProj.getLookup().lookup(J2eeModuleProvider.class);
1262            if(modProvider != null)
1263                serverName = modProvider.getInstanceProperties();
1264        }
1265        return serverName;
1266    }
1267    
1268    public static HashMap JavaDoc getConnPoolValues(File JavaDoc resourceDir, String JavaDoc poolName){
1269        HashMap JavaDoc poolValues = new HashMap JavaDoc();
1270        try{
1271            ObjectName JavaDoc configObjName = new ObjectName JavaDoc(WizardConstants.MAP_RESOURCES);
1272            InstanceProperties instanceProperties = getTargetServer(FileUtil.toFileObject(resourceDir));
1273            if(instanceProperties != null){
1274                SunDeploymentManagerInterface eightDM = (SunDeploymentManagerInterface)instanceProperties.getDeploymentManager();
1275                if(eightDM.isRunning()){
1276                    ServerInterface mejb = (ServerInterface)eightDM.getManagement();
1277                    poolValues = fillInPoolValues(eightDM, configObjName, poolName);
1278                }else{
1279                    if(eightDM.isLocal()){
1280                        HashMap JavaDoc poolMap = eightDM.getConnPoolsFromXml();
1281                        poolValues = formatPoolMap((HashMap JavaDoc)poolMap.get(poolName));
1282                    }
1283                }
1284            }
1285        }catch(Exception JavaDoc ex){ }
1286        return poolValues;
1287    }
1288    
1289    public static HashSet JavaDoc formatXmlSunDatasources(HashMap JavaDoc dsMap){
1290        HashSet JavaDoc datasources = new HashSet JavaDoc();
1291        String JavaDoc[] keys = (String JavaDoc[])dsMap.keySet().toArray(new String JavaDoc[dsMap.size()]);
1292        for(int i=0; i<keys.length; i++){
1293            String JavaDoc jndiName = keys[i];
1294            HashMap JavaDoc poolValues = (HashMap JavaDoc)dsMap.get(jndiName);
1295            poolValues = formatPoolMap(poolValues);
1296            
1297            String JavaDoc url = getStringVal(poolValues.get(__Url));
1298            String JavaDoc username = getStringVal(poolValues.get(__User));
1299            String JavaDoc password = getStringVal(poolValues.get(__Password));
1300            String JavaDoc driverClassName = getStringVal(poolValues.get(__DriverClassName)); //NOI18N
1301
if((url != null) && (! url.equals (""))) { //NOI18N
1302
SunDatasource ds = new SunDatasource (jndiName, url, username, password, driverClassName);
1303                datasources.add (ds);
1304            }
1305        }
1306
1307        return datasources;
1308    }
1309    
1310    private static HashMap JavaDoc formatPoolMap(HashMap JavaDoc poolValues){
1311        String JavaDoc driverClassName = getStringVal(poolValues.get("dsClassName")); //NOI18N
1312

1313        String JavaDoc url = ""; //NOI18N
1314
String JavaDoc serverName = getStringVal(poolValues.get(__ServerName));
1315        String JavaDoc portNo = getStringVal(poolValues.get(__DerbyPortNumber));
1316        String JavaDoc dbName = getStringVal(poolValues.get(__DerbyDatabaseName));
1317        String JavaDoc dbVal = getStringVal(poolValues.get(__DatabaseName));
1318        String JavaDoc portVal = getStringVal(poolValues.get(__PortNumber));
1319        String JavaDoc sid = getStringVal(poolValues.get(__SID));
1320        if(driverClassName.indexOf("pointbase") != -1){
1321            url = getStringVal(poolValues.get(__DatabaseName));
1322        }else if(driverClassName.indexOf("derby") != -1){
1323            if(serverName != null){
1324                url = "jdbc:derby://" + serverName;
1325                if(portNo != null) {
1326                    url = url + ":" + portNo; //NOI18N
1327
}
1328                url = url + "/" + dbName ; //NOI8N
1329
}
1330        }else{
1331            String JavaDoc in_url = getStringVal(poolValues.get(__Url));
1332            if(in_url != null) {
1333                url = in_url;
1334            }
1335            if(url.equals("")) { //NOI18N
1336
String JavaDoc urlPrefix = DatabaseUtils.getUrlPrefix(driverClassName);
1337                String JavaDoc vName = ResourceConfigurator.getDatabaseVendorName(urlPrefix, null);
1338                if(serverName != null){
1339                    if(vName.equals("sybase2")){ //NOI18N
1340
url = urlPrefix + serverName;
1341                    }else{
1342                         url = urlPrefix + "//" + serverName; //NOI18N
1343
}
1344                    if(portVal != null) {
1345                        url = url + ":" + portVal; //NOI18N
1346
}
1347                }
1348                if(vName.equals("sun_oracle") || vName.equals("datadirect_oracle")) { //NOI18N
1349
url = url + ";SID=" + sid; //NOI18N
1350
}else if(Arrays.asList(WizardConstants.Reqd_DBName).contains(vName)) {
1351                    url = url + ";databaseName=" + dbVal; //NOI18N
1352
}else if(Arrays.asList(WizardConstants.VendorsDBNameProp).contains(vName)) {
1353                    url = url + "/" + dbVal ; //NOI8N
1354
}
1355            }
1356        }
1357        
1358        DatabaseConnection databaseConnection = getDatabaseConnection(url);
1359        if(databaseConnection != null) {
1360            driverClassName = databaseConnection.getDriverClass();
1361        }else{
1362            //Fix Issue 78212 - NB required driver classname
1363
String JavaDoc drivername = DatabaseUtils.getDriverName(url);
1364            if(drivername != null) {
1365                driverClassName = drivername;
1366            }
1367        }
1368        
1369        poolValues.put(__Url, url);
1370        poolValues.put(__DriverClassName, driverClassName);
1371        
1372        return poolValues;
1373    }
1374    
1375    public static boolean is90Server(ServerInterface mejb){
1376        boolean is90Server = true;
1377        SunDeploymentManagerInterface sunDm = (SunDeploymentManagerInterface)mejb.getDeploymentManager();
1378        if(sunDm.isLocal()){
1379            is90Server = is90ServerLocal(sunDm);
1380        }else{
1381            try{
1382                ObjectName JavaDoc serverObj = new ObjectName JavaDoc("com.sun.appserv:j2eeType=J2EEServer,name=server,category=runtime"); //NOI18N
1383
String JavaDoc serverName = (String JavaDoc)mejb.getAttribute(serverObj, "serverVersion"); //NOI18N
1384
if((serverName != null) && (serverName.indexOf("8.") != -1)) //NOI18N
1385
is90Server = false;
1386            }catch(Exception JavaDoc ex){ }
1387        }
1388        return is90Server;
1389    }
1390     
1391    private static boolean is90ServerLocal(SunDeploymentManagerInterface sunDm){
1392        boolean isGlassfish = true;
1393        try{
1394            isGlassfish = ServerLocationManager.isGlassFish(sunDm.getPlatformRoot());
1395        }catch(Exception JavaDoc ex){ }
1396        return isGlassfish;
1397
1398    }
1399        
1400    private final static char BLANK = ' ';
1401    private final static char DOT = '.';
1402    private final static char REPLACEMENT_CHAR = '_';
1403    private final static char[] ILLEGAL_FILENAME_CHARS = {'/', '\\', ':', '*', '?', '"', '<', '>', '|', ',' };
1404    private final static char[] ILLEGAL_RESOURCE_NAME_CHARS = {':', '*', '?', '"', '<', '>', '|', ',' };
1405}
1406
Popular Tags