KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > j2ee > sun > share > configbean > SunONEDeploymentConfiguration


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 package org.netbeans.modules.j2ee.sun.share.configbean;
20
21 import java.beans.PropertyVetoException JavaDoc;
22 import java.io.BufferedOutputStream JavaDoc;
23 import java.io.ByteArrayInputStream JavaDoc;
24 import java.io.ByteArrayOutputStream JavaDoc;
25 import java.io.File JavaDoc;
26 import java.io.FileInputStream JavaDoc;
27 import java.io.InputStream JavaDoc;
28 import java.io.IOException JavaDoc;
29 import java.io.OutputStream JavaDoc;
30 import java.lang.ref.WeakReference JavaDoc;
31 import java.util.ArrayList JavaDoc;
32 import java.util.HashMap JavaDoc;
33 import java.util.HashSet JavaDoc;
34 import java.util.Iterator JavaDoc;
35 import java.util.LinkedHashMap JavaDoc;
36 import java.util.List JavaDoc;
37 import java.util.Map JavaDoc;
38 import java.util.Set JavaDoc;
39 import java.util.WeakHashMap JavaDoc;
40
41 import javax.enterprise.deploy.model.DDBean JavaDoc;
42 import javax.enterprise.deploy.model.DDBeanRoot JavaDoc;
43 import javax.enterprise.deploy.model.DeployableObject JavaDoc;
44 import javax.enterprise.deploy.shared.ModuleType JavaDoc;
45 import javax.enterprise.deploy.spi.DConfigBean JavaDoc;
46 import javax.enterprise.deploy.spi.DConfigBeanRoot JavaDoc;
47 import javax.enterprise.deploy.spi.DeploymentManager JavaDoc;
48 import javax.enterprise.deploy.spi.exceptions.BeanNotFoundException JavaDoc;
49 import javax.enterprise.deploy.spi.exceptions.ConfigurationException JavaDoc;
50 import javax.enterprise.deploy.spi.exceptions.InvalidModuleException JavaDoc;
51 import javax.enterprise.deploy.spi.exceptions.OperationUnsupportedException JavaDoc;
52 import org.openide.filesystems.FileSystem;
53
54 import org.xml.sax.SAXException JavaDoc;
55
56 import org.openide.DialogDisplayer;
57 import org.openide.ErrorManager;
58 import org.openide.NotifyDescriptor;
59 import org.openide.filesystems.FileLock;
60 import org.openide.filesystems.FileObject;
61 import org.openide.filesystems.FileUtil;
62 import org.openide.loaders.DataObject;
63 import org.openide.loaders.DataObjectNotFoundException;
64 import org.openide.util.NbBundle;
65 import org.openide.util.RequestProcessor;
66
67 import org.netbeans.api.project.FileOwnerQuery;
68 import org.netbeans.api.project.Project;
69 import org.netbeans.api.project.ProjectInformation;
70 import org.netbeans.api.project.ProjectUtils;
71 import org.netbeans.modules.schema2beans.Schema2BeansRuntimeException;
72 import org.netbeans.modules.j2ee.deployment.common.api.Datasource;
73 import org.netbeans.modules.j2ee.deployment.common.api.DatasourceAlreadyExistsException;
74 import org.netbeans.modules.j2ee.deployment.devmodules.api.J2eeModule;
75 import org.netbeans.modules.j2ee.deployment.devmodules.spi.J2eeModuleProvider;
76 import org.netbeans.modules.j2ee.deployment.devmodules.spi.InstanceListener;
77 import org.netbeans.modules.j2ee.deployment.plugins.api.InstanceProperties;
78
79 import org.netbeans.modules.j2ee.sun.dd.api.CommonDDBean;
80 import org.netbeans.modules.j2ee.sun.dd.api.DDProvider;
81 import org.netbeans.modules.j2ee.sun.dd.api.DDException;
82 import org.netbeans.modules.j2ee.sun.dd.api.common.MessageDestination;
83 import org.netbeans.modules.j2ee.sun.dd.api.ejb.CmpResource;
84 import org.netbeans.modules.j2ee.sun.dd.api.ejb.MdbConnectionFactory;
85 import org.netbeans.modules.j2ee.sun.dd.api.web.SunWebApp;
86
87 import org.netbeans.modules.j2ee.sun.api.ResourceConfiguratorInterface;
88 import org.netbeans.modules.j2ee.sun.api.SunDeploymentManagerInterface;
89 import org.netbeans.modules.j2ee.sun.api.SunDeploymentConfigurationInterface;
90
91 import org.netbeans.modules.j2ee.sun.share.Constants;
92 import org.netbeans.modules.j2ee.sun.share.plan.DeploymentPlan;
93 import org.netbeans.modules.j2ee.sun.share.plan.FileEntry;
94 import org.netbeans.modules.j2ee.sun.share.config.ConfigDataObject;
95 import org.netbeans.modules.j2ee.sun.share.config.ConfigurationStorage;
96 import org.netbeans.modules.j2ee.sun.share.config.DDRoot;
97 import org.netbeans.modules.j2ee.sun.share.config.DDFilesListener;
98 import org.netbeans.modules.j2ee.sun.share.config.StandardDDImpl;
99
100
101 /** Manages the deployment plan I/O and access for initializing DConfigBeans
102  *
103  * @author Vince Kraemer
104  * @author Peter Williams
105  */

106 public class SunONEDeploymentConfiguration implements Constants, SunDeploymentConfigurationInterface { //, InstanceListener {
107

108     // !PW FIXME workaround for linking ConfigDataObjects w/ the correct Deployment
109
// Configuration object. Key is primary File for configuration.
110
private static WeakHashMap JavaDoc configurationMap = new WeakHashMap JavaDoc();
111
112     public static void addConfiguration(File JavaDoc key, SunONEDeploymentConfiguration config) {
113         configurationMap.put(key, new WeakReference JavaDoc(config));
114     }
115     
116     public static void removeConfiguration(File JavaDoc key) {
117         configurationMap.remove(key);
118     }
119     
120     public static SunONEDeploymentConfiguration getConfiguration(File JavaDoc key) {
121         SunONEDeploymentConfiguration config = null;
122         WeakReference JavaDoc ref = (WeakReference JavaDoc) configurationMap.get(key);
123         if(ref != null) {
124             config = (SunONEDeploymentConfiguration) ref.get();
125         }
126         return config;
127     }
128     
129     private DeployableObject JavaDoc dObj;
130     private Map JavaDoc contentMap = new HashMap JavaDoc();
131     private Map JavaDoc beanMap = new HashMap JavaDoc();
132     private Map JavaDoc priorBeanMap = new HashMap JavaDoc();
133     
134     private final Object JavaDoc storageMonitor = new Object JavaDoc();
135     private ConfigurationStorage storage = null;
136     
137     /*
138      * value to hold the module name used by the IDE to define the deployable object
139      * this is a jsr88 extension for directory deployment: we need to find a good
140      * dir name to put the bits that will be deployed.
141      * */

142     private String JavaDoc deploymentModuleName="_default_"; // NOI18N
143

144     /** Configuration files and the directory they belong in, as specified by init.
145      */

146     private File JavaDoc [] configFiles;
147     private File JavaDoc resourceDir;
148     private boolean keepUpdated;
149     
150     private DDFilesListener ddFilesListener;
151     
152     private static final RequestProcessor resourceProcessor = new RequestProcessor("sun-resource-ref"); // NOI18N
153

154     /** Available server targets:
155      */

156     private ASDDVersion appServerVersion;
157     private ASDDVersion minASVersion;
158     private ASDDVersion maxASVersion;
159     private boolean deferredAppServerChange;
160
161     
162     /** Creates a new instance of SunONEDeploymentConfiguration
163      * @param dObj The deployable object this object configures
164      * @param dm The DeploymentManager that created the DeploymentConfiguration
165      */

166     public SunONEDeploymentConfiguration(DeployableObject JavaDoc dObj) {
167         this.dObj = dObj;
168         
169         // Default to 8.1 in new beans. This is set by the bean parser
170
// in the appropriate root type, if reading from existing file(s).
171
this.appServerVersion = ASDDVersion.SUN_APPSERVER_8_1;
172         this.deferredAppServerChange = false;
173     }
174
175     /**
176      * SunONEDeploymentConfiguration initialization. This method should be called before
177      * this class is being used.
178      *
179      * @param configFiles Sun specific DD files referenced by this J2EE module,
180      * e.g. sun-web.xml, sun-ejb-jar.xml, sun-cmp-mappings.xml, etc.
181      * @param resourceDir Directory that the sun resource files will be created in.
182      */

183     public void init(File JavaDoc[] cfgFiles, File JavaDoc resourceDir, boolean keepUpdated) throws ConfigurationException JavaDoc {
184         // cfgFiles array checked for validity by caller in appsrv module (ConfigurationSupportImpl.java)
185
configFiles = new File JavaDoc[cfgFiles.length];
186         for(int i = 0; i < cfgFiles.length; i++) { // Array is too short to justify arraycopy.
187
configFiles[i] = cfgFiles[i];
188         }
189         
190         // configFiles array is just one file except for EJB modules, where it's two.
191
//
192
// IZ 76455 - A regression is now causing sun-cmp-mappings.xml to be the first
193
// entry now. Rather than isolate and fix the regression, I'm just going to
194
// normalize the array here to ensure that sun-ejb-jar.xml is always first
195
// since other code depends on the main configuration file being the first entry
196
// in this list.
197
//
198
if(configFiles.length == 2 && configFiles[1] != null && "sun-ejb-jar.xml".equals(configFiles[1].getName())) { // NOI18N
199
File JavaDoc tmp = configFiles[0];
200             configFiles[0] = configFiles[1];
201             configFiles[1] = tmp;
202         }
203             
204         this.resourceDir = resourceDir;
205         this.keepUpdated = keepUpdated;
206
207         addConfiguration(configFiles[0], this);
208         
209         // !PW FIXME web freeform project does not implement J2eeModulePrvoider. This section
210
// and any related code could be reworked to use WebModule api directly and thereby enable
211
// sun-web.xml gui descriptor editing for web freeform.
212
J2eeModuleProvider provider = getProvider(configFiles[0].getParentFile());
213         if(provider == null) {
214             throw new ConfigurationException JavaDoc("No Project and/or J2eeModuleProvider located for " + configFiles[0].getPath()); // NOI18N
215
}
216
217         // -------- prototype ------- checking server version
218
// provider.addInstanceListener(this);
219
// String instance = provider.getServerInstanceID();
220
// String serverType = provider.getServerID();
221
// System.out.println("SunONEDeploymentConfiguration::init: instance: " + instance + ", serverType: " + serverType);
222
// -------- end prototype ------- checking server version
223

224         // Determine what the available server types can be (WS 6.0, AS 7.0, AS 8.1, AS 9.0)
225
// based on j2ee spec version.
226
J2eeModule j2eeModule = provider.getJ2eeModule();
227         minASVersion = computeMinASVersion((ModuleType JavaDoc) j2eeModule.getModuleType(), j2eeModule.getModuleVersion());
228         maxASVersion = computeMaxASVersion();
229
230         appServerVersion = maxASVersion;
231
232 // // Connectors are not supported by the configuration editor since sun-ra.xml is deprecated.
233
// // To avoid failing initialization here when encountering that file, we will ignore it explicitly.
234
// if("sun-ra.xml".equals(configFiles[0].getName())) {
235
// return;
236
// }
237

238         if(keepUpdated) {
239             // This forces the creation of the DConfigBean tree.
240
if(!ensureConfigurationLoaded()) {
241                 throw new ConfigurationException JavaDoc("DConfigBean storage failed initialization for " + configFiles[0].getName());
242             } else {
243                 // If this is J2EE 1.4 or earlier and configuration does not exist, save it.
244
BaseRoot masterRoot = getMasterDCBRoot();
245                 if(masterRoot != null &&
246                         J2EEVersion.J2EE_1_4.compareSpecification(masterRoot.getJ2EEModuleVersion()) >= 0 &&
247                         !configFiles[0].exists()
248                         ) {
249                     getStorage().setChanged();
250                 }
251             }
252         
253             // This listener listens to the lifecycle and changes affecting the
254
// standard deployment descriptors (web.xml, ejb-jar.xml, application.xml,
255
// and webservices.xml for now). In particular it is used to detect
256
// the creation and deletion of webservices.xml so that we can properly
257
// add and remove the WebServices root DConfigBean that is bound to
258
// the DDBean at the root of webservices.xml.
259
ddFilesListener = new DDFilesListener(this, provider);
260         }
261     }
262     
263     public void dispose() {
264 // J2eeModuleProvider provider = getProvider(configFiles[0].getParentFile());
265
// if(provider != null) {
266
// provider.removeInstanceListener(this);
267
// String instance = provider.getServerInstanceID();
268
// String serverType = provider.getServerID();
269
// System.out.println("SunONEDeploymentConfiguration::dispose: instance: " + instance + ", serverType: " + serverType);
270
// }
271

272         SunONEDeploymentConfiguration storedCfg = getConfiguration(configFiles[0]);
273         if(storedCfg != this) {
274             ErrorManager.getDefault().log(ErrorManager.INFORMATIONAL,
275                     "Stored DeploymentConfiguration (" + storedCfg + ") instance not the one being disposed of (" + this + ").");
276         }
277         
278         if(storedCfg != null) {
279             removeConfiguration(configFiles[0]);
280         }
281     }
282     
283     public void updateResourceDir(File JavaDoc resourceDir) {
284         this.resourceDir = resourceDir;
285     }
286     
287     private void postResourceError(String JavaDoc resourceMsg) {
288         // Unable to create JDBC data source for CMP.
289
// JNDI name of CMP resource field not set.
290
String JavaDoc folderMsg;
291         String JavaDoc projectName = getProjectName(configFiles[0]);
292         if(projectName != null) {
293             folderMsg = NbBundle.getMessage(SunONEDeploymentConfiguration.class,
294                     "ERR_NoResourceFolderForProject", projectName); // NOI18N
295
} else {
296             folderMsg = NbBundle.getMessage(SunONEDeploymentConfiguration.class,
297                     "ERR_NoResourceFolderUnknown"); // NOI18N
298
}
299
300         final String JavaDoc text = folderMsg + " " + resourceMsg;
301         resourceProcessor.post(new Runnable JavaDoc() {
302             public void run() {
303                 NotifyDescriptor.Message msg = new NotifyDescriptor.Message(text, NotifyDescriptor.WARNING_MESSAGE);
304                 DialogDisplayer.getDefault().notify(msg);
305             }
306         });
307     }
308     
309     public void ensureResourceDefined(DDBean JavaDoc ddBean) {
310         // Determine type of ddbean we have so we know what resource to create.
311
String JavaDoc xpath = ddBean.getXpath();
312         int finalSlashIndex = xpath.lastIndexOf('/') + 1;
313         String JavaDoc type = (finalSlashIndex < xpath.length()) ? xpath.substring(finalSlashIndex) : ""; //NOI18N
314

315         if("message-driven".equals(type)) { //NOI18N
316
// Find the DConfigBean for this ddBean. This is actually quite complicated since
317
// the DDBean passed in is from j2eeserver, not from the DDBean tree used and managed
318
// by the plugin.
319
BaseEjb theEjbDCB = getEjbDConfigBean(ddBean);
320             
321             if(theEjbDCB == null) {
322                 ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, new IllegalStateException JavaDoc("EJB DConfigBean cannot be found for DDBean: " + ddBean));
323                 return;
324             }
325             
326             ResourceConfiguratorInterface rci = getResourceConfigurator();
327             String JavaDoc jndiName = theEjbDCB.getJndiName(); // correct for 2.1. For 3.0, if null, have to ask DD for default.
328

329             if(isEJB3()) {
330                 String JavaDoc ejbName = getField(ddBean, "ejb-name");
331                 
332                 if(!Utils.notEmpty(jndiName)) {
333                     // If the user has not explicitly set a jndi name in the server specific descriptor
334
// then the jndi name is specified by the mapped-name field if set, otherwise, the ejb-name.
335
jndiName = getField(ddBean, "mapped-name", ejbName); //NOI18N
336
}
337                 
338                 if(!rci.isJMSResourceDefined(jndiName, resourceDir)) {
339                     // attempt to get activation-config property "destinationType" -- if present, must be one of
340
// javax.jms.Queue or javax.jms.Topic, otherwise, default to Queue.
341
String JavaDoc destinationType = "javax.jms.Queue"; // NOI18N
342
try {
343                         DDBean JavaDoc[] activationNameFields = ddBean.getChildBean("activation-config/activation-config-property/activation-config-property-name");
344                         for(int i = 0; i < activationNameFields.length; i++) {
345                             if("destinationType".equals(activationNameFields[i].getText())) {
346                                 DDBean JavaDoc[] activationValueFields = activationNameFields[i].getChildBean("../activation-config-property-value");
347                                 if(activationValueFields.length > 0) {
348                                     String JavaDoc value = activationValueFields[0].getText();
349                                     if(Utils.notEmpty(value)) {
350                                         destinationType = value;
351                                         break;
352                                     }
353                                 }
354                             }
355                         }
356                     } catch(Exception JavaDoc ex) {
357                         // It's possible that an exception here could normal. Log for now and suppress
358
// later if I confirm that it is normal.
359
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
360                     }
361
362                     // Check message destination but default to the above data if not specified.
363
String JavaDoc messageDestinationName = getField(ddBean, "message-destination-link", ejbName); // NOI18N
364
String JavaDoc messageDestinationType = getField(ddBean, "message-destination-type", destinationType); // NOI18N
365

366                     if(resourceDir == null) {
367                         // Unable to create JMS resource for message driven bean.
368
postResourceError(NbBundle.getMessage(SunONEDeploymentConfiguration.class,
369                                 "ERR_NoJMSResource", theEjbDCB.getEjbName())); // NOI18N
370
// fall through and continue creating the remaining configuration elements though.
371
} else {
372                         rci.createJMSResource(jndiName, messageDestinationType, messageDestinationName, ejbName, resourceDir);
373                     }
374                 }
375             } else {
376                 if(!rci.isJMSResourceDefined(jndiName, resourceDir)) {
377                     String JavaDoc ejbName = getField(ddBean, "ejb-name"); //NOI18N
378
String JavaDoc messageDestinationName = getField(ddBean, "message-destination-link"); // NOI18N
379
String JavaDoc messageDestinationType = getField(ddBean, "message-destination-type"); // NOI18N
380

381                     if(resourceDir == null) {
382                         // Unable to create JMS resource for message driven bean.
383
postResourceError(NbBundle.getMessage(SunONEDeploymentConfiguration.class,
384                                 "ERR_NoJMSResource", theEjbDCB.getEjbName())); // NOI18N
385
// fall through and continue creating the remaining configuration elements though.
386
} else {
387                         rci.createJMSResource(jndiName, messageDestinationType, messageDestinationName, ejbName, resourceDir);
388                     }
389
390                     MdbConnectionFactory mcf = getStorageFactory().createMdbConnectionFactory();
391                     String JavaDoc connectionFactoryJndiName= "jms/" + messageDestinationName + "Factory"; //NOI18N
392
mcf.setJndiName(connectionFactoryJndiName);
393                     try {
394                         ((MDEjb) theEjbDCB).setMdbConnectionFactory(mcf);
395                     } catch (PropertyVetoException JavaDoc ex) {
396                         ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
397                     }
398
399                     MessageDestination md = getStorageFactory().createMessageDestination();
400                     md.setMessageDestinationName(messageDestinationName);
401                     md.setJndiName(theEjbDCB.getJndiName());
402                     EjbJarRoot root = (EjbJarRoot) theEjbDCB.getParent();
403                     try {
404                         root.addMessageDestination(md);
405                     } catch (PropertyVetoException JavaDoc ex) {
406                         ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
407                     }
408                 }
409             }
410         } else if("resource-ref".equals(type)) { //NOI18N
411
if(ddBean instanceof StandardDDImpl) {
412                 Object JavaDoc o = getDCBCache().get(ddBean);
413                 if(o instanceof ResourceRef) {
414                     ResourceRef theResRefDCB = (ResourceRef) o;
415                     final String JavaDoc refName = getField(ddBean, "res-ref-name"); //NOI18N
416
final String JavaDoc description = getField(ddBean, "description"); //NOI18N
417
final File JavaDoc targetDir = resourceDir;
418
419                     // Only execute resource autocreation code if the description field has contents
420
// (Note the contents might still fail to parse, but the parser is not accessible
421
// from here in the current code base.)
422
if(Utils.notEmpty(description)) {
423                         if(resourceDir == null) {
424                             // Unable to create JDBC data source for resource ref.
425
postResourceError(NbBundle.getMessage(SunONEDeploymentConfiguration.class,
426                                     "ERR_NoRefJdbcDataSource", theResRefDCB.getResRefName())); // NOI18N
427
return;
428                         }
429
430                         /** !PW This mechanism is from the original incarnation of this code from
431                          * appsrv plugin module in NB 4.1. There should be a more stable
432                          * way to solve any such timing issue. This method is likelky
433                          * unstable.
434                          */

435                         /* Creating a RequestProcessor to create resources seperately to
436                          * prevent NPE while initial loading of IDE because of call to
437                          * access DatabaseRuntimeManager.getConnection(). This NPE
438                          * causes failure while loading WebServices Registry in Runtime Tab
439                          */

440                         resourceProcessor.post(new Runnable JavaDoc() {
441                             public void run() {
442                                 ResourceConfiguratorInterface rci = getResourceConfigurator();
443                                 if(rci != null) {
444                                     rci.createJDBCDataSourceFromRef(refName, description, targetDir);
445                                 }
446                             }
447                         }, 500);
448                     }
449                 } else {
450                     ErrorManager.getDefault().log(ErrorManager.INFORMATIONAL, "No ResourceRef DConfigBean found bound to resource-ref DDBean: " + ddBean); // NOI18N
451
}
452             } else {
453                 ErrorManager.getDefault().log(ErrorManager.INFORMATIONAL, "DDBean from wrong tree in ensureResourceDefined: " + ddBean); // NOI18N
454
}
455         } else if("entity".equals(type)) { //NOI18N
456
ensureResourceDefinedForEjb(ddBean, null);
457         }
458     }
459
460     public void ensureResourceDefinedForEjb(DDBean JavaDoc ddBean, String JavaDoc jndiName) {
461         // Find the DConfigBean for this ddBean. This is actually quite complicated since
462
// the DDBean passed in is from j2eeserver, not from the DDBean tree used and managed
463
// by the plugin.
464
BaseEjb theEjbDCB = getEjbDConfigBean(ddBean);
465
466         if(theEjbDCB == null) {
467             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, new IllegalStateException JavaDoc("EJB DConfigBean cannot be found for DDBean: " + ddBean)); // NOI18N
468
return;
469         }
470
471         if(theEjbDCB instanceof CmpEntityEjb) {
472             ResourceConfiguratorInterface rci = getResourceConfigurator();
473             CmpEntityEjb cmpEjbDCB = (CmpEntityEjb) theEjbDCB;
474
475             if(resourceDir == null) {
476                 // Unable to create JDBC data source for CMP.
477
// JNDI name of CMP resource field not set.
478
postResourceError(NbBundle.getMessage(SunONEDeploymentConfiguration.class,
479                         "ERR_NoCmpOrJdbcDataSource", cmpEjbDCB.getEjbName())); // NOI18N
480
return;
481             }
482
483             if (jndiName == null) {
484                 String JavaDoc description = getField(ddBean, "description"); //NOI18N
485
jndiName = rci.createJDBCDataSourceForCmp(cmpEjbDCB.getEjbName(), description, resourceDir);
486             }
487
488             // Set the CmpResource jndi-name if not already defined.
489
if(jndiName != null) {
490                 Base parentDCB = cmpEjbDCB.getParent();
491                 if(parentDCB instanceof EjbJarRoot) {
492                     EjbJarRoot ejbJarRoot = (EjbJarRoot) parentDCB;
493                     CmpResource cmpResource = null;
494                     if(ejbJarRoot.getCmpResource() == null) {
495                         cmpResource = getStorageFactory().createCmpResource();
496                     } else {
497                         cmpResource = (CmpResource)ejbJarRoot.getCmpResource().clone();
498                     }
499                     cmpResource.setJndiName(jndiName);
500                     try {
501                         ejbJarRoot.setCmpResource(cmpResource);
502                     } catch(PropertyVetoException JavaDoc ex) {
503                         // Should never happen
504
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
505                     }
506                 } else {
507                     // Should never happen
508
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, new IllegalStateException JavaDoc("CmpEntityBean DConfigBean parent is of wrong type: " + parentDCB)); // NOI18N
509
}
510             }
511         }
512     }
513     
514     private boolean isEJB3() {
515         boolean result = false;
516         
517         String JavaDoc j2eeModuleVersion = dObj.getModuleDTDVersion();
518         EjbJarVersion ejbJarVersion = EjbJarVersion.getEjbJarVersion(j2eeModuleVersion);
519         if(EjbJarVersion.EJBJAR_3_0.compareTo(ejbJarVersion) <= 0) {
520             result = true;
521         }
522         
523         return result;
524     }
525     
526     private ASDDVersion computeMinASVersion(ModuleType JavaDoc moduleType, String JavaDoc j2eeModuleVersion) {
527         ASDDVersion result = ASDDVersion.SUN_APPSERVER_7_0;
528
529         if(ModuleType.WAR.equals(moduleType)) {
530             ServletVersion servletVersion = ServletVersion.getServletVersion(j2eeModuleVersion);
531             if(ServletVersion.SERVLET_2_4.equals(servletVersion)) {
532                 result = ASDDVersion.SUN_APPSERVER_8_1;
533             } else if(ServletVersion.SERVLET_2_5.equals(servletVersion)) {
534                 result = ASDDVersion.SUN_APPSERVER_9_0;
535             }
536         } else if(ModuleType.EJB.equals(moduleType)) {
537             EjbJarVersion ejbJarVersion = EjbJarVersion.getEjbJarVersion(j2eeModuleVersion);
538             if(EjbJarVersion.EJBJAR_2_1.equals(ejbJarVersion)) {
539                 result = ASDDVersion.SUN_APPSERVER_8_1;
540             } else if(EjbJarVersion.EJBJAR_3_0.equals(ejbJarVersion)) {
541                 result = ASDDVersion.SUN_APPSERVER_9_0;
542             }
543         } else if(ModuleType.EAR.equals(moduleType)) {
544             ApplicationVersion applicationVersion = ApplicationVersion.getApplicationVersion(j2eeModuleVersion);
545             if(ApplicationVersion.APPLICATION_1_4.equals(applicationVersion)) {
546                 result = ASDDVersion.SUN_APPSERVER_8_1;
547             } else if(ApplicationVersion.APPLICATION_5_0.equals(applicationVersion)) {
548                 result = ASDDVersion.SUN_APPSERVER_9_0;
549             }
550         } else if(ModuleType.CAR.equals(moduleType)) {
551             AppClientVersion appClientVersion = AppClientVersion.getAppClientVersion(j2eeModuleVersion);
552             if(AppClientVersion.APP_CLIENT_1_4.equals(appClientVersion)) {
553                 result = ASDDVersion.SUN_APPSERVER_8_1;
554             } else if(AppClientVersion.APP_CLIENT_5_0.equals(appClientVersion)) {
555                 result = ASDDVersion.SUN_APPSERVER_9_0;
556             }
557         } else {
558             ErrorManager.getDefault().log(ErrorManager.INFORMATIONAL, "Unsupported J2EE module type: " + moduleType); // NOI18N
559
result = ASDDVersion.SUN_APPSERVER_8_1;
560         }
561         
562         return result;
563     }
564     
565     private ASDDVersion computeMaxASVersion() {
566         // This is min of (current server target, 9.0) so if we can figure out the
567
// target server, use that, otherwise, use 9.0.
568
ASDDVersion result = getTargetAppServerVersion();
569         if(result == null) {
570             result = ASDDVersion.SUN_APPSERVER_9_0;
571             ErrorManager.getDefault().log(ErrorManager.WARNING, NbBundle.getMessage(
572                     SunONEDeploymentConfiguration.class, "ERR_UnidentifiedTargetServer", result.toString())); // NOI18N
573
}
574         return result;
575     }
576     
577     public ASDDVersion getMinASVersion() {
578         return minASVersion;
579     }
580     
581     public ASDDVersion getMaxASVersion() {
582         return maxASVersion;
583     }
584
585     public StorageBeanFactory getStorageFactory() {
586         return appServerVersion.getStorageFactory();
587     }
588     
589     /** Get the AppServer version to be used for saving deployment descriptors.
590      * Note that this is different than the version of the connected target
591      * application server (which can be queried by the appropriate method on
592      * SunONEDeploymentConfiguration.)
593      *
594      * @return ASDDVersion enum for the appserver version
595      */

596     public ASDDVersion getAppServerVersion() {
597         return appServerVersion;
598     }
599
600     /** Set the AppServer version to be used for saving deployment descriptors.
601      * This version should be greater or equal to "minASVersion" and lesser or
602      * equal to "maxASVersion", as specified by the configuration, otherwise an
603      * IllegalArgumentException will be thrown.
604      *
605      * @param asVersion enum for the appserver version (cannot be null)
606      */

607     public void setAppServerVersion(ASDDVersion asVersion) {
608         if(asVersion.compareTo(getMinASVersion()) < 0) {
609             throw new IllegalArgumentException JavaDoc(asVersion.toString() +
610                 " is lower than required minimum version " + getMinASVersion().toString());
611         }
612     
613         if(asVersion.compareTo(getMaxASVersion()) > 0) {
614             throw new IllegalArgumentException JavaDoc(asVersion.toString() +
615                 " is higher than required maximum version " + getMaxASVersion().toString());
616         }
617         
618         if(!asVersion.equals(appServerVersion) || deferredAppServerChange) {
619             appServerVersion = asVersion;
620             ConfigurationStorage storage = getStorage();
621             if(storage != null) {
622                 deferredAppServerChange = false;
623                 storage.setChanged();
624             }
625         }
626     }
627
628     /** Set the AppServer version to be used for saving deployment descriptors.
629      *
630      * This method is only for use by the DConfigBean tree, used to set the version
631      * while the configuration is being loaded (and thus should not and cannot be
632      * saved, which the public version would do.) Instead, this changes the version
633      * and marks the change unsaved. The version passed in here is the version
634      * actually found in the descriptor file as specified by the DOCTYPE, hence
635      * no range validation. What recourse to take if the version found is actually
636      * outside the "valid range" is as yet an unsupported scenario.
637      *
638      * @param asVersion enum for the appserver version.
639      */

640     void internalSetAppServerVersion(ASDDVersion asVersion) {
641         if(!asVersion.equals(appServerVersion)) {
642             appServerVersion = asVersion;
643             deferredAppServerChange = true;
644         }
645     }
646     
647     /** Returns the configuration files list for this deployment configuration instance.
648      *
649      * @return File array of the files managed by this deployment configuration.
650      */

651     public File JavaDoc [] getConfigFiles() {
652         return configFiles;
653     }
654     
655     private BaseEjb getEjbDConfigBean(DDBean JavaDoc ejbDDBean) {
656         BaseEjb theEjbDCB = null;
657         
658         try {
659             DDBean JavaDoc realEjbDDBean = getStorage().normalizeEjbDDBean(ejbDDBean);
660             DDBeanRoot JavaDoc ddBeanRoot = realEjbDDBean.getRoot();
661             DConfigBeanRoot JavaDoc dcbRoot = getDConfigBeanRoot(ddBeanRoot);
662             DConfigBean JavaDoc dcb = dcbRoot.getDConfigBean(realEjbDDBean);
663             if(dcb instanceof BaseEjb) {
664                 theEjbDCB = (BaseEjb) dcb;
665             }
666         } catch(ConfigurationException JavaDoc ex) {
667             // I don't expect this exception to be thrown, but it might be. If it is,
668
// it's probably a programmer error somewhere.
669
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
670         } catch(NullPointerException JavaDoc ex) {
671             // If one of above values ends up being null, we definitely want to
672
// log that it happened. But for reporting purposes, we'll return
673
// null and let the caller's IllegalStateException take precedence.
674
// This would probably also be caused only by programmer error.
675
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
676         }
677         
678         return theEjbDCB;
679     }
680     
681     /** Extract value of singular child field from a DDBean
682      */

683     private String JavaDoc getField(DDBean JavaDoc bean, String JavaDoc fieldId) {
684         String JavaDoc result = null;
685
686         try {
687             DDBean JavaDoc[] childFields = bean.getChildBean(fieldId);
688             if(childFields.length > 0) {
689                result = childFields[0].getText();
690             }
691         } catch(Exception JavaDoc ex) {
692             // If our code is written correctly, exceptions here should not happen.
693
// However, if the fieldId does not exist for this DD, or a few other
694
// types of programming errors, we could get a runtime exception here.
695
// This is here for runtime safety and to trap and log bugs.
696
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
697         }
698         
699         return result;
700     }
701     
702     private String JavaDoc getField(DDBean JavaDoc bean, String JavaDoc fieldId, String JavaDoc defaultValue) {
703         String JavaDoc result = getField(bean, fieldId);
704
705         if(!Utils.notEmpty(result)) {
706             result = defaultValue;
707         }
708         
709         return result;
710     }
711     
712     private ResourceConfiguratorInterface getResourceConfigurator() {
713         ResourceConfiguratorInterface rci = null;
714         DeploymentManager JavaDoc dm = getDeploymentManager();
715         if(dm instanceof SunDeploymentManagerInterface) {
716             SunDeploymentManagerInterface sdmi = (SunDeploymentManagerInterface) dm;
717             rci = sdmi.getResourceConfigurator();
718         } else {
719             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, new IllegalStateException JavaDoc("Invalid DeploymentManager: " + dm));
720         }
721         return rci;
722     }
723     
724     private DeploymentManager JavaDoc getDeploymentManager() {
725         DeploymentManager JavaDoc dm = null;
726         J2eeModuleProvider provider = getProvider(configFiles[0]);
727         if(provider != null) {
728             InstanceProperties ip = provider.getInstanceProperties();
729             if(ip != null) {
730                 dm = ip.getDeploymentManager();
731             } else {
732                 ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, new NullPointerException JavaDoc("Null Server InstanceProperties: " + ip));
733             }
734         } else {
735             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, new NullPointerException JavaDoc("Null J2eeModuleProvider: " + provider));
736         }
737         return dm;
738     }
739     
740     private J2eeModuleProvider getProvider(File JavaDoc file) {
741         J2eeModuleProvider provider = null;
742         if(file != null) {
743             FileObject fo = FileUtil.toFileObject(file);
744             if(fo != null) {
745                 Project project = FileOwnerQuery.getOwner(fo);
746                 if (project != null) {
747                     org.openide.util.Lookup lookup = project.getLookup();
748                     provider = (J2eeModuleProvider) lookup.lookup(J2eeModuleProvider.class);
749                 }
750             } else {
751                 File JavaDoc parent = file.getParentFile();
752                 if(parent != null) {
753                     provider = getProvider(parent);
754                 }
755             }
756         }
757         return provider;
758     }
759     
760     private String JavaDoc getProjectName(File JavaDoc file) {
761         String JavaDoc result = null;
762         FileObject fo = FileUtil.toFileObject(file);
763         if(fo != null) {
764             Project project = FileOwnerQuery.getOwner(fo);
765             if (project != null) {
766                 ProjectInformation info = ProjectUtils.getInformation(project);
767                 if(info != null) {
768                     result = info.getName();
769                 }
770             }
771         }
772         return result;
773     }
774
775     
776     /** Retrieves DConfigBeanRoot associated with the specified DDBean root. If
777      * this DCB has already created, retrieves it from cache, otherwise creates
778      * a new DCB via factory mechanism.
779      *
780      * @param dDBeanRoot
781      * @throws ConfigurationException
782      * @return
783      */

784     public DConfigBeanRoot JavaDoc getDConfigBeanRoot(DDBeanRoot JavaDoc dDBeanRoot) throws ConfigurationException JavaDoc {
785 /*
786  * dcbroot = rootcache.get(ddroot)
787  * if dcbroot == null
788  * factory = lookup(moduletype)
789  * dcbroot = factory.create(ddroot)
790  * cache.add(dcbroot)
791  * return dcbroot
792  */

793         if (null == dDBeanRoot) {
794             throw Utils.makeCE("ERR_DDBeanIsNull", null, null);
795         }
796         
797         if (null == dDBeanRoot.getXpath()) {
798             throw Utils.makeCE("ERR_DDBeanHasNullXpath", null, null);
799         }
800
801         // If DDBean is not from our internal tree, normalize it to one that is.
802
if(!(dDBeanRoot instanceof DDRoot)) {
803             // If the root cache is empty, then it is likely that
804
if(getDCBRootCache().entrySet().size() == 0) {
805                 throw Utils.makeCE("ERR_CannotNormalizeDDBean",
806                         new Object JavaDoc [] { dDBeanRoot.getClass().getName() }, null);
807             }
808             dDBeanRoot = getStorage().normalizeDDBeanRoot(dDBeanRoot);
809         }
810         
811         BaseRoot rootDCBean = (BaseRoot) getDCBRootCache().get(dDBeanRoot);
812         
813         if(null == rootDCBean) {
814             DCBFactory factory = (DCBFactory) getDCBFactoryMap().get(dDBeanRoot.getXpath());
815             if(factory != null) {
816                 rootDCBean = (BaseRoot) factory.createDCB(dDBeanRoot, null);
817                 if(rootDCBean != null) {
818                     getDCBCache().put(dDBeanRoot, rootDCBean);
819                     getDCBRootCache().put(dDBeanRoot, rootDCBean);
820                 }
821             }
822         }
823         
824         return rootDCBean;
825     }
826     
827     /**
828      * @return
829      */

830     public DeployableObject JavaDoc getDeployableObject() {
831         return dObj;
832     }
833     
834     /** JSR88: Removes the DConfigBeanRoot and all its children.
835      *
836      * @param dConfigBeanRoot The DConfigBeanRoot to remove.
837      * @throws BeanNotFoundException
838      */

839     public void removeDConfigBean(DConfigBeanRoot JavaDoc dConfigBeanRoot) throws BeanNotFoundException JavaDoc {
840         jsr88Logger.entering(this.getClass().toString(), "removeDConfigBean", dConfigBeanRoot);
841         
842         if(null != dConfigBeanRoot) {
843             DDBeanRoot JavaDoc key = (DDBeanRoot JavaDoc) dConfigBeanRoot.getDDBean();
844             
845             // Find DConfigBean directly in cache.
846
BaseRoot deadBean = (BaseRoot) getDCBCache().get(key);
847             if(deadBean != null) {
848                 // Remove the children first. Each child also removes it's own
849
// children so this will remove the entire tree when it's done.
850

851                 // Can't use iterator here or we will possibly get a ConcurrentModificationException
852
// as the children clean themselves up.
853
Object JavaDoc children[] = deadBean.getChildren().toArray();
854                 for(int i = 0; i < children.length; i++) {
855                     try {
856                         deadBean.removeDConfigBean((Base) children[i]);
857                     } catch(BeanNotFoundException JavaDoc ex) {
858                         // This would suggest a corrupt tree or bad code somewhere if it happens.
859
// Catch & log it and continue cleaning the tree.
860
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
861                     }
862                 }
863
864                 // Remove this bean from both general and root caches.
865
getDCBCache().remove(key);
866                 getDCBRootCache().remove(key);
867                 
868                 // cleanup bean before throwing away
869
deadBean.cleanup();
870                 deadBean = null;
871             } else {
872                 // If not found, throw appropriate exception per spec.
873
throw new BeanNotFoundException JavaDoc(NbBundle.getMessage(SunONEDeploymentConfiguration.class,
874                         "ERR_DConfigBeanRootNotFoundOnRemove", dConfigBeanRoot.toString()));
875             }
876         }
877         
878         jsr88Logger.exiting(this.getClass().toString(), "removeDConfigBean", dConfigBeanRoot);
879     }
880     
881     /** Restore the configuration object from a deployment plan .
882      * This method reads the plan from the InputStream. The plan is
883      * not completely parsed, though. When a config bean needs to use data
884      * is in the content, it will be converted into a bean graph.
885      * @param inputStream
886      * @throws ConfigurationException
887      */

888     public void restore(InputStream JavaDoc inputStream) throws ConfigurationException JavaDoc {
889         jsr88Logger.entering(this.getClass().toString(), "restore", inputStream);
890         
891         restoreDConfigBean(inputStream, null);
892         
893         jsr88Logger.exiting(this.getClass().toString(), "restore", inputStream);
894     }
895     
896     /**
897      * @param inputStream
898      * @param dDBeanRoot
899      * @throws ConfigurationException
900      * @return
901      */

902     public DConfigBeanRoot JavaDoc restoreDConfigBean(InputStream JavaDoc inputStream, DDBeanRoot JavaDoc dDBeanRoot) throws ConfigurationException JavaDoc {
903         //Find the section of the deployment plan that implements the bean.
904
jsr88Logger.finest("S1DepConfig:restoreDConfigBean(jiIS,DDBeanRoot)");
905         // this stream has deployment plan format.
906
//
907
//jsr88Logger.finest("S1DepConfig:restore(jiIS)");
908

909         DeploymentPlan dp = null;
910         
911         // Flush bean cache. This forces reparsing of the new tree we load here.
912
beanMap.clear();
913         
914         try {
915             if (null != inputStream) {
916                 try {
917                     if (this.dObj.getType().equals(ModuleType.WAR)) {
918                         // read the sun-web.xml file in and conjure a
919
// deployment plan file object for it.
920
try {
921                             SunWebApp sunW = DDProvider.getDefault().getWebDDRoot(inputStream);
922                             dp = DeploymentPlan.createGraph();
923                             FileEntry fe = new FileEntry();
924                             fe.setName("sun-web.xml");
925                             String JavaDoc s = new String JavaDoc();
926                             java.io.StringWriter JavaDoc strWriter = new java.io.StringWriter JavaDoc();
927                             sunW.write(strWriter);
928                             fe.setContent(strWriter.toString());
929                             dp.addFileEntry(fe);
930                         } catch(DDException ex) {
931                             // bad sun-web.xml file in stream.
932
jsr88Logger.finest(ex.getClass().getName() + " while processing sun-web.xml into a deployment plan: " + ex.getLocalizedMessage());
933                             dp = DeploymentPlan.createGraph();
934                         } catch(SAXException JavaDoc ex) {
935                             // bad sun-web.xml file in stream.
936
jsr88Logger.finest(ex.getClass().getName() + " while processing sun-web.xml into a deployment plan: " + ex.getLocalizedMessage());
937                             dp = DeploymentPlan.createGraph();
938                         } catch(IOException JavaDoc ex) {
939                             // error reading sun-web.xml file from stream.
940
jsr88Logger.finest(ex.getClass().getName() + " while processing sun-web.xml into a deployment plan: " + ex.getLocalizedMessage());
941                             dp = DeploymentPlan.createGraph();
942                         }
943                     } else {
944                         dp = DeploymentPlan.createGraph(inputStream);
945                     }
946                 } catch (Schema2BeansRuntimeException s2bre) {
947                     // vbk--todo : do more investigation before creating an
948
// empty plan object.
949
jsr88Logger.finest("the stream did not have a deployment plan");
950                     dp = DeploymentPlan.createGraph();
951                 }
952             } else {
953                 jsr88Logger.finest("the stream was null");
954             }
955             FileEntry [] entries = new FileEntry[0];
956             if (null != dp) {
957                 FileEntry tentries[] = dp.getFileEntry();
958                 if (null != tentries) {
959                     entries = tentries;
960                 }
961             }
962             for (int i = 0; i < entries.length ; i++) {
963                 String JavaDoc key = Utils.getFQNKey(entries[i].getUri(), entries[i].getName()); // !PW This is FileEntry.getUri(), not Base.getUri()
964
contentMap.put(key, entries[i].getContent().getBytes());
965             }
966         } catch(Schema2BeansRuntimeException ex) {
967             jsr88Logger.finest("Schema2Beans threw a Runtime Exception");
968         } catch (Exception JavaDoc ex) {
969             jsr88Logger.finest("foo");
970             ConfigurationException JavaDoc ce =
971             new ConfigurationException JavaDoc("bad plan stream");
972             ce.initCause(ex);
973             //throw ce;
974
}
975         
976         // find the DConfigBean that corresponds to the
977
// DDBeanRoot
978
//
979
List JavaDoc pending = new ArrayList JavaDoc();
980         BaseRoot rootToRestore = null;
981         
982         if (null == dDBeanRoot) {
983             // no rootbean, add roots from this deployment configuration
984
Iterator JavaDoc rootIter = getDCBRootCache().entrySet().iterator();
985             while(rootIter.hasNext()) {
986                 pending.add(((Map.Entry JavaDoc) rootIter.next()).getValue());
987             }
988             
989             rootToRestore = getMasterDCBRoot();
990         } else {
991             rootToRestore = (BaseRoot) getDCBRootCache().get(dDBeanRoot);
992             if(null != rootToRestore) {
993                 pending.add(rootToRestore);
994             }
995         }
996         
997         int index = 0;
998         while (index < pending.size()) {
999             Base current = (Base) pending.get(index);
1000            try {
1001                current.loadFromPlanFile(this);
1002            }
1003            catch (java.lang.IllegalStateException JavaDoc ise) {
1004                jsr88Logger.throwing(current.getClass().toString(), "loadFromPlanFile", ise);
1005                assert ise == null;
1006            }
1007            pending.addAll(current.getChildren());
1008            index++;
1009        }
1010        
1011        return rootToRestore;
1012    }
1013    
1014    /**
1015     * @param outputStream
1016     * @throws ConfigurationException
1017     */

1018    public void save(OutputStream JavaDoc outputStream) throws ConfigurationException JavaDoc {
1019        jsr88Logger.entering(this.getClass().toString(), "save", outputStream);
1020        
1021        saveDConfigBean(outputStream, null);
1022        
1023        jsr88Logger.exiting(this.getClass().toString(), "save", outputStream);
1024    }
1025    
1026    /**
1027     * @param outputStream
1028     * @param rootBean
1029     * @throws ConfigurationException
1030     */

1031    public void saveDConfigBean(OutputStream JavaDoc outputStream, DConfigBeanRoot JavaDoc rootBean) throws ConfigurationException JavaDoc {
1032        Object JavaDoc [] params = new Object JavaDoc[] {outputStream, rootBean} ;
1033        jsr88Logger.entering(this.getClass().toString(), "save", params);
1034        
1035        boolean useUriDataAtSave = false;
1036// if(null == rootBean || rootBean instanceof AppRoot) {
1037
// useUriDataAtSave = true;
1038
// }
1039

1040        Map JavaDoc outputGraphs = new LinkedHashMap JavaDoc();
1041        Map JavaDoc cmpGraphs = new LinkedHashMap JavaDoc(); // !PW FIXME added for beta -- remove after switching to DD API
1042

1043        try {
1044            // Build the map of output bean graphs by calling addToGraphs() on
1045
// each root bean we have (or the one passed in, if any).
1046
//
1047
if(rootBean == null) {
1048                Iterator JavaDoc rootIter = getDCBRootCache().entrySet().iterator();
1049                while(rootIter.hasNext()) {
1050                    Base dcb = (Base) ((Map.Entry JavaDoc) rootIter.next()).getValue();
1051                    dcb.addToGraphs(outputGraphs, null, "");
1052
1053                    // !PW FIXME code to retrieve the CMP snippet for beta since it's still base bean type.
1054
if(dcb instanceof EjbJarRoot) {
1055                        EjbJarRoot ejbJar = (EjbJarRoot) dcb;
1056                        Snippet cmpSnippet = ejbJar.getCmpMappingSnippet();
1057                        if(cmpSnippet.hasDDSnippet()) {
1058                            String JavaDoc snippetKey = Utils.getFQNKey(ejbJar.getUriText(), cmpSnippet.getFileName());
1059                            cmpGraphs.put(snippetKey, cmpSnippet.getCmpDDSnippet());
1060                        }
1061                    }
1062                }
1063            } else {
1064                ((Base) rootBean).addToGraphs(outputGraphs, null, "");
1065                
1066                // !PW FIXME code to retrieve the CMP snippet for beta since it's still base bean type.
1067
if(rootBean instanceof EjbJarRoot) {
1068                    EjbJarRoot ejbJar = (EjbJarRoot) rootBean;
1069                    Snippet cmpSnippet = ejbJar.getCmpMappingSnippet();
1070                    if(cmpSnippet.hasDDSnippet()) {
1071                        String JavaDoc snippetKey = Utils.getFQNKey(ejbJar.getUriText(), cmpSnippet.getFileName());
1072                        cmpGraphs.put(snippetKey, cmpSnippet.getCmpDDSnippet());
1073                    }
1074                }
1075            }
1076            
1077            // combine the sun-XXX deployment descriptor bean graphs
1078
// in a deployment plan file graph.
1079
Set JavaDoc keys = outputGraphs.keySet();
1080            Iterator JavaDoc iter = keys.iterator();
1081            DeploymentPlan dp = new DeploymentPlan();
1082            CommonDDBean bean = null;
1083            while (iter.hasNext()) {
1084                Object JavaDoc k = iter.next();
1085                bean = (CommonDDBean) outputGraphs.get(k);
1086                if (null != bean) {
1087                    String JavaDoc keyString = (String JavaDoc) k;
1088                    String JavaDoc uri = Utils.getUriFromKey(keyString);
1089                    String JavaDoc fname = Utils.getFilenameFromKey(keyString);
1090                    FileEntry fe = new FileEntry();
1091                    fe.setName(fname);
1092                    if (useUriDataAtSave && uri.length() > 0) {
1093                        fe.setUri(uri);
1094                    }
1095                    String JavaDoc s = new String JavaDoc();
1096                    java.io.StringWriter JavaDoc strWriter = new java.io.StringWriter JavaDoc();
1097                    bean.write(strWriter);
1098                    fe.setContent(strWriter.toString());
1099                    dp.addFileEntry(fe);
1100                } else {
1101                    jsr88Logger.warning("no bean for key: " + k);
1102                }
1103            }
1104            
1105            // !PW FIXME also add cmp graphs
1106
keys = cmpGraphs.keySet();
1107            iter = keys.iterator();
1108            while (iter.hasNext()) {
1109                Object JavaDoc k = iter.next();
1110                org.netbeans.modules.schema2beans.BaseBean cmpRoot =
1111                    (org.netbeans.modules.schema2beans.BaseBean) cmpGraphs.get(k);
1112                if (null != cmpRoot) {
1113                    String JavaDoc keyString = (String JavaDoc) k;
1114                    String JavaDoc uri = Utils.getUriFromKey(keyString);
1115                    String JavaDoc fname = Utils.getFilenameFromKey(keyString);
1116                    FileEntry fe = new FileEntry();
1117                    fe.setName(fname);
1118                    if (useUriDataAtSave && uri.length() > 0) {
1119                        fe.setUri(uri);
1120                    }
1121                    java.io.StringWriter JavaDoc strWriter = new java.io.StringWriter JavaDoc();
1122                    cmpRoot.write(strWriter);
1123                    fe.setContent(strWriter.toString());
1124                    dp.addFileEntry(fe);
1125                } else {
1126                    jsr88Logger.warning("no bean for key: " + k);
1127                }
1128            }
1129            
1130            if (this.dObj.getType().equals(ModuleType.WAR)) {
1131                if (null != bean) {
1132                    bean.write(outputStream);
1133                }
1134            } else {
1135                dp.write(outputStream);
1136            }
1137        } catch (Exception JavaDoc ex) {
1138            ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
1139            ConfigurationException JavaDoc ce = new ConfigurationException JavaDoc("Sun Deployment Descriptor Error"); // NOI18N
1140
ce.initCause(ex);
1141        }
1142        jsr88Logger.exiting(this.getClass().toString(), "Save", params); // NOI18N
1143
}
1144    
1145    /** Get the schema2beans object graph that provides data for a DConfigBean
1146     * @param uri The uri for the descriptor source
1147     * @param fileName the name of the descriptor file
1148     * @param parser the ConfigParser that converts a stream into a bean graph
1149     * @param finder The ConfigFinder that accepts the parser's return value
1150     * and finds the subgraph for a DConfigBean
1151     * @return An Object to initialize the values in the DConfigBean
1152     */

1153    Object JavaDoc getBeans(String JavaDoc uri, String JavaDoc fileName, ConfigParser parser,
1154        ConfigFinder finder) {
1155        String JavaDoc key = Utils.getFQNKey(uri, fileName);
1156        Object JavaDoc root = beanMap.get(key);
1157        
1158        if(root == null) {
1159            // parse the content
1160
byte[] content = (byte[]) contentMap.get(key);
1161            if(content == null) {
1162                return null;
1163            }
1164            
1165            if(parser == null) {
1166                jsr88Logger.severe("Missing parser");
1167                return null;
1168            }
1169            
1170            try {
1171                root = parser.parse(new ByteArrayInputStream JavaDoc(content));
1172            } catch(Exception JavaDoc ex) {
1173                ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
1174                root = priorBeanMap.remove(key);
1175                if(root == null) {
1176                    // No prior map, just return null (otherwise, put into main map
1177
// same as for newly parsed root.
1178
return null;
1179                }
1180            }
1181            
1182            beanMap.put(key, root);
1183        }
1184        
1185        Object JavaDoc result = finder.find(root);
1186        return result;
1187    }
1188    
1189    /* ------------------------- Utility Functions ------------------------
1190     */

1191    /** Loads and initializes the DConfigBean tree for this DeploymentConfiguration
1192     * instance if it has not already been done yet.
1193     */

1194    public boolean ensureConfigurationLoaded() {
1195        // Retrieve storage, forcing it to be created if necessary, and initialized.
1196
boolean result = (getStorage() != null);
1197        return result;
1198    }
1199
1200    /** Retrieves the ConfigurationStorage instance from the primary DataObject
1201     * representing the saved version of this configuration. The storage object
1202     * should be created if necessary. This will initialize the entire DConfigBean
1203     * tree.
1204     */

1205    public ConfigurationStorage getStorage() {
1206        ConfigurationStorage theStorage = null;
1207
1208        // !PW Do we need to do this? What about the secondary file? Need to convert to file based as well.
1209
// getPrimaryFile().refresh(); //check for external changes
1210

1211        synchronized (storageMonitor) {
1212            theStorage = storage;
1213        }
1214        
1215        if(theStorage == null) {
1216            // 0nly lookup the provider when we need to, but additionally, do it
1217
// outside of any locks on configuration initialization.
1218
J2eeModuleProvider provider = getProvider(configFiles[0].getParentFile());
1219            if(provider == null) {
1220                // We get this if someone calls getStorage() on a project for which this is true
1221
// _and_ the project was never initialized (or failed initialization and the user continued).
1222
throw new IllegalStateException JavaDoc("No Project and/or J2eeModuleProvider located for " + configFiles[0].getPath());
1223            }
1224            
1225            synchronized (storageMonitor) {
1226                if(storage == null) {
1227                    try {
1228                        storage = new ConfigurationStorage(provider, this);
1229                    } catch (IOException JavaDoc ex) {
1230                        ErrorManager.getDefault().notify(ex);
1231                    } catch(InvalidModuleException JavaDoc ex) {
1232                        ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
1233                    } catch(SAXException JavaDoc ex) {
1234                        ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
1235                    } catch(ConfigurationException JavaDoc ex) {
1236                        ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
1237                    }
1238                }
1239                theStorage = storage;
1240            }
1241        }
1242        
1243        return theStorage;
1244    }
1245    
1246    /** If this module is a web application, retrieve the WebAppRoot bean for it.
1247     * You do not need to call ensureConfigurationLoaded() before calling this
1248     * method, as this method will do so itself when it normalizes the DDRoot.
1249     */

1250    public WebAppRoot getWebAppRoot() {
1251        WebAppRoot war = null;
1252        
1253        DDBeanRoot JavaDoc root = dObj.getDDBeanRoot();
1254        if(null != root) {
1255            try {
1256                ConfigurationStorage storage = getStorage();
1257                if(storage != null) {
1258                    DConfigBeanRoot JavaDoc dcbRoot = getDConfigBeanRoot(storage.normalizeDDBeanRoot(root));
1259                    if(dcbRoot instanceof WebAppRoot) {
1260                        war = (WebAppRoot) dcbRoot;
1261                    }
1262                }
1263            } catch (ConfigurationException JavaDoc ex) {
1264                ErrorManager.getDefault().notify(ErrorManager.EXCEPTION, ex);
1265            }
1266        } else {
1267            ErrorManager.getDefault().log(ErrorManager.INFORMATIONAL, "DeployableObject with null DDBeanRoot!!!");
1268        }
1269        
1270        return war;
1271    }
1272
1273    /** If this module is a ejbjar, retrieve the EjbJarRoot bean for it.
1274     * You do not need to call ensureConfigurationLoaded() before calling this
1275     * method, as this method will do so itself when it normalizes the DDRoot.
1276     */

1277    public EjbJarRoot getEjbJarRoot() {
1278        EjbJarRoot ejbJar = null;
1279        
1280        DDBeanRoot JavaDoc root = dObj.getDDBeanRoot();
1281        if(null != root) {
1282            try {
1283                ConfigurationStorage storage = getStorage();
1284                if(storage != null) {
1285                    DConfigBeanRoot JavaDoc dcbRoot = getDConfigBeanRoot(storage.normalizeDDBeanRoot(root));
1286                    if(dcbRoot instanceof EjbJarRoot) {
1287                        ejbJar = (EjbJarRoot) dcbRoot;
1288                    }
1289                }
1290            } catch (ConfigurationException JavaDoc ex) {
1291                ErrorManager.getDefault().notify(ErrorManager.EXCEPTION, ex);
1292            }
1293        } else {
1294            ErrorManager.getDefault().log(ErrorManager.INFORMATIONAL, "DeployableObject with null DDBeanRoot!!!");
1295        }
1296        
1297        return ejbJar;
1298    }
1299    
1300    /** Set the context root of the module this DeploymentConfiguration represents,
1301     * if the deployable object is a WAR file.
1302     */

1303    public void setContextRoot(String JavaDoc contextRoot){
1304        if (dObj.getType().equals(ModuleType.WAR)) {
1305            WebAppRoot war = getWebAppRoot();
1306            if(war != null) {
1307                try {
1308                    war.setContextRoot(contextRoot);
1309                } catch(java.beans.PropertyVetoException JavaDoc ex){
1310                    // !PW Should not happen.
1311
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
1312                }
1313            }
1314        } else {
1315            ErrorManager.getDefault().log(ErrorManager.INFORMATIONAL, "SunONEDeploymentConfiguration.setContextRoot() invoked on incorrect module type: " + dObj.getType());
1316        }
1317    }
1318    
1319    /** Get the context root of the module this DeploymentConfiguration represents,
1320     * if the deployable object is a WAR file.
1321     */

1322    public String JavaDoc getContextRoot() {
1323        String JavaDoc contextRoot = null;
1324        if (dObj.getType().equals(ModuleType.WAR)) {
1325            WebAppRoot war = getWebAppRoot();
1326            if(war != null) {
1327                contextRoot = war.getContextRoot();
1328            } else {
1329                ErrorManager.getDefault().log(ErrorManager.INFORMATIONAL, "SunONEDeploymentConfiguration.getContextRoot(): No WebAppRoot DConfigBean found for module.");
1330            }
1331        } else {
1332            ErrorManager.getDefault().log(ErrorManager.INFORMATIONAL, "SunONEDeploymentConfiguration.getContextRoot() invoked on incorrect module type: " + dObj.getType());
1333        }
1334        return contextRoot;
1335    }
1336    
1337    /* Get the deploymentModuleName value which is usually passed in by an IDE
1338     * to define a good value for a directory name used for dir deploy actions.
1339     **/

1340    public String JavaDoc getDeploymentModuleName(){
1341        return deploymentModuleName;
1342    }
1343    
1344    /* Set the deploymentModuleName value which is usually passed in by an IDE
1345     * to define a good value for a directory name used for dir deploy actions.
1346     **/

1347    public void setDeploymentModuleName(String JavaDoc s){
1348        deploymentModuleName = s;
1349    }
1350
1351    /** If this module has any webservices, retrieve the root DConfigBean of that
1352     * portion of the tree.
1353     */

1354    public WebServices getWebServicesRoot() {
1355        WebServices wsr = null;
1356        
1357        Map JavaDoc rootMap = getDCBRootCache();
1358        if(rootMap.size() > 1) {
1359            // Grab second entry in map (backing map is LinkedHashMap, so second
1360
// entry is the one we want.)
1361
Iterator JavaDoc rootIterator = rootMap.entrySet().iterator();
1362            rootIterator.next();
1363            Object JavaDoc root = ((Map.Entry JavaDoc) rootIterator.next()).getValue();
1364            if(root instanceof WebServices) {
1365                wsr = (WebServices) root;
1366            }
1367        }
1368        
1369        return wsr;
1370    }
1371
1372    
1373    /* ------------------------------------------------------------------------
1374     * DDBeanRoot -> DConfigBeanRoot cache support
1375     *
1376     * moduleDCBCache is a map containing all root beans this configuration
1377     * is responsible for.
1378     * completeDCBCache is the DCB cache for all DCB's by this configuration,
1379     * it's root DCB's and their children. Essentially all DCB's involved
1380     * in a particular invocation of JSR-88.
1381     * patchCache is a list of any unpatched reference DCB's created as children
1382     * of AppRoot (for now, could be anywhere we use a reference). The key
1383     * for such references is the ddBeanRoot they expect to be a reference to.
1384     */

1385    private Map JavaDoc moduleDCBCache = new LinkedHashMap JavaDoc(13);
1386    private Map JavaDoc completeDCBCache = new LinkedHashMap JavaDoc(63);
1387    private Map JavaDoc patchCache = new LinkedHashMap JavaDoc(13);
1388    
1389    /** Retrieve the cache containing all DConfigBeans owned by this configuration.
1390     *
1391     * @return Map containing all DConfigBeans owned by this configuration.
1392     */

1393    Map JavaDoc getDCBCache() {
1394        return completeDCBCache;
1395    }
1396    
1397    /** Retrieve the cache containing all root DConfigBeans owned by this configuration.
1398     *
1399     * @return Map containing all root DConfigBeans owned by this configuration.
1400     */

1401    Map JavaDoc getDCBRootCache() {
1402        return moduleDCBCache;
1403    }
1404    
1405    /** Retrieve the cache containing all reference DConfigBeans that are currently
1406     * unpatched (no matching regular bean has been created for them yet.) owned
1407     * by this configuration.
1408     *
1409     * @return Map containing all unpatched reference DConfigBeans owned by this
1410     * configuration.
1411     */

1412    Map JavaDoc getPatchList() {
1413        return patchCache;
1414    }
1415    
1416    /** Retrieves the "master" DConfigBean root for this configuration (as opposed
1417     * to just any root bean -- EAR files have multiple DConfigBeanRoots, the
1418     * one representing sun-application.xml is the master in that case.) For right
1419     * now the logic just picks the first root in the cache on the assumption
1420     * that the master was the first one created. However there is no guarantee
1421     * that will work so we should come up with something better.
1422     *
1423     * @return The DConfigBeanRoot owned by this configuration that is deemed to
1424     * be the "master" root bean. For example, in an EAR file, the master root
1425     * bean is the bean representing sun-application.xml.
1426     */

1427    BaseRoot getMasterDCBRoot() {
1428        BaseRoot masterRoot = null;
1429        Iterator JavaDoc rootIterator = moduleDCBCache.entrySet().iterator();
1430        while(rootIterator.hasNext()) {
1431            BaseRoot tmpRoot = (BaseRoot) ((Map.Entry JavaDoc) rootIterator.next()).getValue();
1432            // Only accept this root if is _not_ the root of webservices.xml or equivalent annotation
1433
// WebServices is occasionally now showing up as the first element in this list though I
1434
// am not sure how. It is never the masterroot, so we should never return it.
1435
if(!(tmpRoot instanceof WebServices)) {
1436                masterRoot = tmpRoot;
1437                break;
1438            }
1439        }
1440        return masterRoot;
1441    }
1442    
1443    /* ------------------------------------------------------------------------
1444     * XPath to factory mapping support
1445     */

1446    private Map JavaDoc dcbFactoryMap = null;
1447    
1448    /** Retrieve the factory manager for this DConfigBean. If one has not been
1449     * constructed yet, create it.
1450     * @return
1451     */

1452    private Map JavaDoc getDCBFactoryMap() {
1453        if(dcbFactoryMap == null) {
1454            dcbFactoryMap = new HashMap JavaDoc(17);
1455            
1456            // Only factories that create a BaseRoot bean with no parent are
1457
// allowed here, e.g. DCBTopRootFactory.
1458
dcbFactoryMap.put("/application", new DCBTopRootFactory(AppRoot.class)); // EAR // NOI18N
1459
dcbFactoryMap.put("/ejb-jar", new DCBTopRootFactory(EjbJarRoot.class)); // EJB // NOI18N
1460
dcbFactoryMap.put("/web-app", new DCBTopRootFactory(WebAppRoot.class)); // WAR // NOI18N
1461
dcbFactoryMap.put("/application-client", new DCBTopRootFactory(AppClientRoot.class)); // CAR // NOI18N
1462
// dcbFactoryMap.put("/connector", new DCBTopRootFactory(ConnectorRoot.class)); // RAR // NOI18N
1463
}
1464        
1465        return dcbFactoryMap;
1466    }
1467    
1468    /** Factory that knows how to create and initialize root DConfigBeans from a
1469     * DDBeanRoot passed in by the tool side of JSR-88.
1470     */

1471    private class DCBTopRootFactory implements DCBFactory {
1472        
1473        private Class JavaDoc dcbRootClass;
1474        
1475        DCBTopRootFactory(Class JavaDoc c) {
1476            dcbRootClass = c;
1477        }
1478        
1479        public Base createDCB(DDBean JavaDoc ddBean, Base dcbParent) throws ConfigurationException JavaDoc {
1480            if(ddBean == null) {
1481                throw Utils.makeCE("ERR_RootDDBeanIsNull", null, null); // NOI18N
1482
}
1483            
1484            if(!(ddBean instanceof DDBeanRoot JavaDoc)) {
1485                Object JavaDoc [] args = new Object JavaDoc [1];
1486                args[0] = dcbRootClass.getName();
1487                throw Utils.makeCE("ERR_RootDDBeanWrongType", args, null); // NOI18N
1488
}
1489            
1490            DDBeanRoot JavaDoc ddbRoot = (DDBeanRoot JavaDoc) ddBean;
1491            BaseRoot newDCB = null;
1492            
1493            try {
1494                newDCB = (BaseRoot) dcbRootClass.newInstance();
1495                newDCB.init(ddbRoot, SunONEDeploymentConfiguration.this, ddbRoot);
1496            } catch(InstantiationException JavaDoc ex) {
1497                Object JavaDoc [] args = new Object JavaDoc [1];
1498                args[0] = dcbRootClass.getName();
1499                throw Utils.makeCE("ERR_UnexpectedInstantiateException", args, ex); // NOI18N
1500
} catch(IllegalAccessException JavaDoc ex) {
1501                Object JavaDoc [] args = new Object JavaDoc [1];
1502                args[0] = dcbRootClass.getName();
1503                throw Utils.makeCE("ERR_UnexpectedIllegalAccessException", args, ex); // NOI18N
1504
} catch (RuntimeException JavaDoc ex) {
1505                throw Utils.makeCE("ERR_UnexpectedRuntimeException", null, ex); // NOI18N
1506
}
1507            
1508            return newDCB;
1509        }
1510    }
1511    
1512    // New methods to support the studio
1513

1514    static private int BUF_LEN = 1024;
1515    
1516    // MS5 -- deal with the schema files...
1517
public void addFileToPlanForModule(File JavaDoc f, DeployableObject JavaDoc mod, ConfigurationStorage storage) throws ConfigurationException JavaDoc {
1518        // find the uri
1519
String JavaDoc uri = getUriForDeployableObject(mod, storage);
1520        // create the key
1521
String JavaDoc fname = f.getName();
1522        String JavaDoc key = Utils.getFQNKey(uri,fname);
1523        // read in the file's content
1524
ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
1525        FileInputStream JavaDoc fis = null;
1526        int totalRead = 0;
1527        try {
1528            fis = new FileInputStream JavaDoc(f);
1529            byte[] buf = new byte[BUF_LEN];
1530            int lastRead = 0;
1531            do {
1532                lastRead = fis.read(buf);
1533                if (lastRead > -1) {
1534                    baos.write(buf, 0, lastRead);
1535                    totalRead += lastRead;
1536                }
1537            }
1538            while (lastRead > -1);
1539        }
1540        catch (java.io.FileNotFoundException JavaDoc fnfe) {
1541            // somebody was being mean to us --
1542
// log it. forget it. move on.
1543
}
1544        catch (java.io.IOException JavaDoc ioe) {
1545            // this is more drastic, Throw an exception here
1546
ConfigurationException JavaDoc ce = new ConfigurationException JavaDoc("Failed while reading"); // NOI18N
1547
ce.initCause(ioe);
1548            throw ce;
1549        }
1550        finally {
1551            if (null != fis) {
1552                try {
1553                    fis.close();
1554                } catch (java.io.IOException JavaDoc ioe) {
1555                    // log this and move on
1556
}
1557            }
1558        }
1559        //Document doc = GraphManager.createXmlDocument(fis, false);
1560
// convert it to the right form of xml
1561
//BaseBean bean = convertDocToBean(doc);
1562
// put it in the map
1563
if (totalRead > 0) {
1564            contentMap.put(key, baos.toByteArray());
1565        }
1566        else {
1567            // remove the old content
1568
contentMap.remove(key);
1569        }
1570        
1571        // Remove this entry from the beanMap, forcing it to be reparsed.
1572
// Flush bean cache. This forces reparsing of the new tree we load here.
1573
Object JavaDoc oldMap = beanMap.remove(key);
1574        
1575        // Save any prior bean map to fall back to in case parsing new content fails.
1576
if(oldMap != null) {
1577            priorBeanMap.put(key, oldMap);
1578        }
1579    }
1580    
1581    public void extractFileFromPlanForModule(File JavaDoc f, DeployableObject JavaDoc mod, ConfigurationStorage storage) throws IOException JavaDoc {
1582        // find the uri
1583
String JavaDoc uri = getUriForDeployableObject(mod, storage);
1584        final String JavaDoc fname = f.getName();
1585
1586        // create the key
1587
String JavaDoc key = Utils.getFQNKey(uri,fname);
1588
1589        // get the bean
1590
final byte[] content = (byte[]) contentMap.get(key);
1591
1592        // save it into the file
1593
if (null != content) {
1594            File JavaDoc parentFile = f.getParentFile();
1595            if(!parentFile.exists()) {
1596                parentFile.mkdirs();
1597            }
1598            
1599            final FileObject folder = FileUtil.toFileObject(parentFile);
1600            if(folder == null) {
1601                // cannot create folder!
1602
String JavaDoc errorMsg = NbBundle.getMessage(SunONEDeploymentConfiguration.class,
1603                        "ERR_SaveError", fname) + " " + // NOI18N
1604
NbBundle.getMessage(SunONEDeploymentConfiguration.class,
1605                        "ERR_FailedToCreateConfigFolder", parentFile.getAbsolutePath()); // NOI18N
1606
throw new IOException JavaDoc(errorMsg);
1607            } else if(!folder.isFolder()) {
1608                // config "folder" is not a folder!!!
1609
String JavaDoc errorMsg = NbBundle.getMessage(SunONEDeploymentConfiguration.class,
1610                        "ERR_SaveError", fname) + " " + // NOI18N
1611
NbBundle.getMessage(SunONEDeploymentConfiguration.class,
1612                        "ERR_ConfigFolderNotDirectory", parentFile.getAbsolutePath()); // NOI18N
1613
throw new IOException JavaDoc(errorMsg);
1614            }
1615            
1616            FileSystem fs = folder.getFileSystem();
1617            fs.runAtomicAction(new FileSystem.AtomicAction() {
1618                public void run() throws IOException JavaDoc {
1619                    FileLock lock = null;
1620                    OutputStream JavaDoc out = null;
1621                    try {
1622                        FileObject configFO = folder.getFileObject(fname);
1623                        if (configFO == null) {
1624                            configFO = folder.createData(fname);
1625                        }
1626                        lock = configFO.lock();
1627                        out = new BufferedOutputStream JavaDoc(configFO.getOutputStream(lock), 4096);
1628                        out.write(content);
1629                    } finally {
1630                        if (out != null) {
1631                            try { out.close(); } catch(IOException JavaDoc ioe) {}
1632                        }
1633                        if (lock != null) {
1634                            lock.releaseLock();
1635                        }
1636                    }
1637                }
1638            });
1639        }
1640    }
1641    
1642    private String JavaDoc getUriForDeployableObject(DeployableObject JavaDoc mod, ConfigurationStorage storage) {
1643        // Logic here duplicates logic from the BaseRoot derived classes that implement
1644
// getUriText(). The reason is that the DConfigBean's do not necessarily exist
1645
// at times when this routine is needed and we don't want to be creating them at
1646
// that point for performance and other reasons.
1647
String JavaDoc rootUri = ""; // NOI18N
1648
if(ModuleType.EAR.equals(mod.getType())) {
1649            rootUri = "EAR"; // NOI18N
1650
}
1651        return rootUri;
1652    }
1653    
1654    // this routine flushes the bean data into the content map
1655
//
1656
void updateContentMap(DConfigBeanRoot JavaDoc rootBean) throws ConfigurationException JavaDoc {
1657        jsr88Logger.entering(this.getClass().toString(), "save", rootBean); // NOI18N
1658

1659// boolean useUriDataAtSave = false;
1660
// if(null == rootBean || rootBean instanceof AppRoot) {
1661
// useUriDataAtSave = true;
1662
// }
1663

1664        Map JavaDoc outputGraphs = new LinkedHashMap JavaDoc();
1665        Map JavaDoc cmpGraphs = new LinkedHashMap JavaDoc(); // !PW FIXME added for beta -- remove after switching to DD API
1666
try {
1667            // Build the map of output bean graphs by calling addToGraphs() on
1668
// each root bean we have (or the one passed in, if any).
1669
//
1670
if(rootBean == null) {
1671                Iterator JavaDoc rootIter = getDCBRootCache().entrySet().iterator();
1672                while(rootIter.hasNext()) {
1673                    Base dcb = (Base) ((Map.Entry JavaDoc) rootIter.next()).getValue();
1674                    dcb.addToGraphs(outputGraphs, null, ""); // NOI18N
1675

1676                    // !PW FIXME code to retrieve the CMP snippet for beta since it's still base bean type.
1677
if(dcb instanceof EjbJarRoot) {
1678                        EjbJarRoot ejbJar = (EjbJarRoot) dcb;
1679                        Snippet cmpSnippet = ejbJar.getCmpMappingSnippet();
1680                        if(cmpSnippet.hasDDSnippet()) {
1681                            String JavaDoc snippetKey = Utils.getFQNKey(ejbJar.getUriText(), cmpSnippet.getFileName());
1682                            cmpGraphs.put(snippetKey, cmpSnippet.getCmpDDSnippet());
1683                        }
1684                    }
1685                }
1686            } else {
1687                ((Base) rootBean).addToGraphs(outputGraphs, null, "");
1688                // !PW FIXME code to retrieve the CMP snippet for beta since it's still base bean type.
1689
if(rootBean instanceof EjbJarRoot) {
1690                    EjbJarRoot ejbJar = (EjbJarRoot) rootBean;
1691                    Snippet cmpSnippet = ejbJar.getCmpMappingSnippet();
1692                    if(cmpSnippet.hasDDSnippet()) {
1693                        String JavaDoc snippetKey = Utils.getFQNKey(ejbJar.getUriText(), cmpSnippet.getFileName());
1694                        cmpGraphs.put(snippetKey, cmpSnippet.getCmpDDSnippet());
1695                    }
1696                }
1697            }
1698            
1699            // combine the sun-XXX deployment descriptor bean graphs
1700
// in a deployment plan file graph.
1701
Set JavaDoc keys = outputGraphs.keySet();
1702            Iterator JavaDoc iter = keys.iterator();
1703            DeploymentPlan dp = new DeploymentPlan();
1704            while (iter.hasNext()) {
1705                Object JavaDoc k = iter.next();
1706                CommonDDBean bean = (CommonDDBean) outputGraphs.get(k);
1707                if (null != bean) {
1708                    /*String keyString = (String) k;
1709                    String uri = Utils.getUriFromKey(keyString);
1710                    String fname = Utils.getFilenameFromKey(keyString);
1711                    FileEntry fe = new FileEntry();
1712                    fe.setName(fname);
1713                    if (useUriDataAtSave && uri.length() > 0) {
1714                        fe.setUri(uri);
1715                    }
1716                    java.io.StringWriter strWriter = new java.io.StringWriter();*/

1717                    ByteArrayOutputStream JavaDoc baos =
1718                        new ByteArrayOutputStream JavaDoc();
1719                    bean.write(baos);
1720                    contentMap.put(k, baos.toByteArray());
1721                    //fe.setContent(strWriter.toString());
1722
//dp.addFileEntry(fe);
1723
} else {
1724                    jsr88Logger.warning("no bean for key: " + k); // NOI18N
1725
}
1726            }
1727
1728            // !PW FIXME write out cmp graphs too.
1729
keys = cmpGraphs.keySet();
1730            iter = keys.iterator();
1731            while (iter.hasNext()) {
1732                Object JavaDoc k = iter.next();
1733                org.netbeans.modules.schema2beans.BaseBean cmpRoot =
1734                    (org.netbeans.modules.schema2beans.BaseBean) cmpGraphs.get(k);
1735                if (null != cmpRoot) {
1736                    ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
1737                    cmpRoot.write(baos);
1738                    contentMap.put(k, baos.toByteArray());
1739                } else {
1740                    jsr88Logger.warning("no bean for key: " + k); // NOI18N
1741
}
1742            }
1743            
1744            /*if (!this.dObj.getType().equals(ModuleType.EAR)) {
1745                if (null != bean) {
1746                    bean.write(outputStream);
1747                }
1748            } else {
1749                dp.write(outputStream);
1750            }*/

1751        } catch (Exception JavaDoc ex) {
1752            ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
1753            ConfigurationException JavaDoc ce = new ConfigurationException JavaDoc("Sun Deployment Descriptor Error"); // NOI18N
1754
ce.initCause(ex);
1755        }
1756        jsr88Logger.exiting(this.getClass().toString(), "save", rootBean); // NOI18N
1757
}
1758    
1759    private void refreshGraphFromContentMap(BaseRoot br) {
1760        List JavaDoc pending = new ArrayList JavaDoc();
1761        BaseRoot rootToRestore = br;
1762        
1763/* if (null == dDBeanRoot) {
1764            // no rootbean, add roots from this deployment configuration
1765            Iterator rootIter = getDCBRootCache().entrySet().iterator();
1766            while(rootIter.hasNext()) {
1767                pending.add(((Map.Entry) rootIter.next()).getValue());
1768            }
1769            
1770            rootToRestore = getMasterDCBRoot();
1771        } else {
1772            rootToRestore = (BaseRoot) getDCBRootCache().get(dDBeanRoot);
1773            if(null != rootToRestore) {*/

1774        pending.add(rootToRestore);
1775        
1776        
1777        int index = 0;
1778        while (index < pending.size()) {
1779            Base current = (Base) pending.get(index);
1780            try {
1781                current.loadFromPlanFile(this);
1782            }
1783            catch (java.lang.IllegalStateException JavaDoc ise) {
1784                jsr88Logger.throwing(current.getClass().toString(), "loadFromPlanFile", // NOI18N
1785
ise);
1786                assert ise == null;
1787            }
1788            pending.addAll(current.getChildren());
1789            index++;
1790        }
1791        
1792    }
1793    
1794    // Formerly DeploymentPlanSplitter read/write config files.
1795
public void readDeploymentPlanFiles(ConfigurationStorage storage, DDBeanRoot JavaDoc masterRootDDBean) throws ConfigurationException JavaDoc {
1796        boolean loadGraph = false;
1797
1798        contentMap.clear();
1799        BaseRoot masterRoot = (BaseRoot) getDConfigBeanRoot(masterRootDDBean);
1800        
1801        int len = getValidatedNumberOfFiles(configFiles);
1802        for (int i = 0; i < len; i++) {
1803            if(configFiles[i].exists()) {
1804                addFileToPlanForModule(configFiles[i], dObj, storage);
1805                loadGraph = true;
1806            }
1807        }
1808        
1809        // refresh the configuration...
1810
if(loadGraph) {
1811            if(masterRoot != null) {
1812                refreshGraphFromContentMap(masterRoot);
1813            } else {
1814                ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL,
1815                        new IllegalStateException JavaDoc("Loaded configuration data from disk but master DConfigBeanRoot is null.")); // NOI18N
1816
}
1817        }
1818        
1819        for (int j = 0; j < configFiles.length; j++) {
1820            FileObject fo = FileUtil.toFileObject(configFiles [j]);
1821            if(fo != null) {
1822                fo.refresh(true);
1823            }
1824        }
1825    }
1826    
1827    public void writeDeploymentPlanFiles(ConfigurationStorage storage) throws IOException JavaDoc, ConfigurationException JavaDoc {
1828        // Update content map, then write all files.
1829
updateContentMap(null);
1830
1831        int len = getValidatedNumberOfFiles(configFiles);
1832        for (int i = 0; i < len; i++) {
1833            extractFileFromPlanForModule(configFiles[i], dObj, storage);
1834        }
1835        
1836        for (int j = 0; j < configFiles.length; j++) {
1837            FileObject fo = FileUtil.toFileObject(configFiles [j]);
1838            if (fo != null) {
1839                fo.refresh(true);
1840            }
1841        }
1842    }
1843    
1844    int getValidatedNumberOfFiles(File JavaDoc[] files) throws ConfigurationException JavaDoc {
1845        int len = 0;
1846        if (null != files) {
1847            len = files.length;
1848        }
1849        
1850        // ?? This should check by module type
1851
if (len < 1) {
1852            throw new ConfigurationException JavaDoc("file list is too short"); // !PW should this be I18N????
1853
}
1854        
1855        return len;
1856    }
1857
1858// public void instanceAdded(String serverInstanceID) {
1859
// System.out.println("SunONEDeploymentConfiguration::instanceAdded: " + serverInstanceID);
1860
//
1861
// J2eeModuleProvider provider = getProvider(configFiles[0].getParentFile());
1862
// if(provider != null) {
1863
// String instance = provider.getServerInstanceID();
1864
// String serverType = provider.getServerID();
1865
// System.out.println("Current instance: " + instance + ", serverType: " + serverType);
1866
// }
1867
// }
1868
//
1869
// public void instanceRemoved(String serverInstanceID) {
1870
// System.out.println("SunONEDeploymentConfiguration::instanceRemoved: " + serverInstanceID);
1871
//
1872
// J2eeModuleProvider provider = getProvider(configFiles[0].getParentFile());
1873
// if(provider != null) {
1874
// String instance = provider.getServerInstanceID();
1875
// String serverType = provider.getServerID();
1876
// System.out.println("Current instance: " + instance + ", serverType: " + serverType);
1877
// }
1878
// }
1879
//
1880
// public void changeDefaultInstance(String oldServerInstanceID, String newServerInstanceID) {
1881
// System.out.println("SunONEDeploymentConfiguration::changeDefaultInstance: old instance" + oldServerInstanceID + ", new instance: " + newServerInstanceID);
1882
//
1883
// J2eeModuleProvider provider = getProvider(configFiles[0].getParentFile());
1884
// if(provider != null) {
1885
// String instance = provider.getServerInstanceID();
1886
// String serverType = provider.getServerID();
1887
// System.out.println("Current instance: " + instance + ", serverType: " + serverType);
1888
// }
1889
// }
1890

1891    // !PW FIXME replace these with more stable version of equivalent functionality
1892
// once Vince or j2eeserver crew can implement a good api for this.
1893
// this code will NOT work for remote servers.
1894
private ASDDVersion getTargetAppServerVersion() {
1895        ASDDVersion result = null;
1896        J2eeModuleProvider provider = getProvider(configFiles[0].getParentFile());
1897        String JavaDoc serverType = provider.getServerID();
1898        
1899// [/tools/as81ur2]deployer:Sun:AppServer::localhost:4848, serverType: J2EE
1900
// [/tools/as82]deployer:Sun:AppServer::localhost:4848, serverType: J2EE
1901
// [/tools/glassfish_b35]deployer:Sun:AppServer::localhost:4948, serverType: J2EE
1902

1903        if("J2EE".equals(serverType)) { // NOI18N
1904
String JavaDoc instance = provider.getServerInstanceID();
1905            if(Utils.notEmpty(instance)) {
1906                try {
1907                    String JavaDoc asInstallPath = instance.substring(1, instance.indexOf("deployer")-1);
1908                    File JavaDoc asInstallFolder = new File JavaDoc(asInstallPath);
1909                    if(asInstallFolder.exists()) {
1910                        result = getInstalledAppServerVersion(asInstallFolder);
1911                    }
1912                } catch(IndexOutOfBoundsException JavaDoc ex) {
1913                    // Can't identify server install folder.
1914
ErrorManager.getDefault().log(ErrorManager.WARNING, NbBundle.getMessage(
1915                            SunONEDeploymentConfiguration.class, "ERR_NoServerInstallLocation", instance)); // NOI18N
1916
} catch(NullPointerException JavaDoc ex) {
1917                    ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
1918                }
1919            }
1920        } else if("SUNWebserver7".equals(serverType)){ // NOI18N
1921
result = ASDDVersion.SUN_APPSERVER_8_1;
1922        }
1923        
1924        return result;
1925    }
1926    
1927    private ASDDVersion getInstalledAppServerVersion(File JavaDoc asInstallFolder) {
1928        File JavaDoc dtdFolder = new File JavaDoc(asInstallFolder, "lib/dtds/"); // NOI18N
1929
if(dtdFolder.exists()) {
1930            File JavaDoc domain12dtd = new File JavaDoc(dtdFolder, "sun-domain_1_2.dtd"); // NOI18N
1931
if(domain12dtd.exists()) {
1932                return ASDDVersion.SUN_APPSERVER_9_0;
1933            }
1934            File JavaDoc domain11dtd = new File JavaDoc(dtdFolder, "sun-domain_1_1.dtd"); // NOI18N
1935
if(domain11dtd.exists()) {
1936                return ASDDVersion.SUN_APPSERVER_8_1;
1937            }
1938            File JavaDoc domain10dtd = new File JavaDoc(dtdFolder, "sun-domain_1_0.dtd"); // NOI18N
1939
if(domain10dtd.exists()) {
1940                return ASDDVersion.SUN_APPSERVER_7_0;
1941            }
1942        }
1943        
1944        return null;
1945    }
1946    
1947    /**
1948     * Implementation of DS Management API in ConfigurationSupport
1949     * @return Returns true of plugin implements DS Management API's
1950     */

1951    public boolean isDatasourceCreationSupported() {
1952        return true;
1953    }
1954    
1955    /**
1956     * Implementation of DS Management API in ConfigurationSupport
1957     * @return Returns Set of SunDataSource's(JDBC Resources) present in this J2EE project
1958     * SunDataSource is a combination of JDBC & JDBC Connection Pool Resources.
1959     */

1960    public Set JavaDoc getDatasources() {
1961        Set JavaDoc datasources = new HashSet JavaDoc();
1962        ResourceConfiguratorInterface rci = getResourceConfigurator();
1963        if(resourceDir != null && resourceDir.exists()) {
1964           datasources = rci.getResources(resourceDir);
1965        }
1966        return datasources;
1967    }
1968    
1969    /**
1970     * Implementation of DS Management API in ConfigurationSupport
1971     * Creates DataSource objects for this J2EE Project
1972     * @param jndiName JNDI Name of JDBC Resource
1973     * @param url Url for database referred to by this JDBC Resource's Connection Pool
1974     * @param username UserName for database referred to by this JDBC Resource's Connection Pool
1975     * @param password Password for database referred to by this JDBC Resource's Connection Pool
1976     * @param driver Driver ClassName for database referred to by this JDBC Resource's Connection Pool
1977     * @return Set containing SunDataSource
1978     */

1979    public Datasource createDatasource(final String JavaDoc jndiName, final String JavaDoc url, final String JavaDoc username, final String JavaDoc password, final String JavaDoc driver)
1980            throws OperationUnsupportedException JavaDoc, ConfigurationException JavaDoc, DatasourceAlreadyExistsException {
1981        Datasource ds = null;
1982        if(resourceDir == null) {
1983            // Unable to create JDBC data source for resource ref.
1984
postResourceError(NbBundle.getMessage(SunONEDeploymentConfiguration.class,
1985                    "ERR_NoRefJdbcDataSource", jndiName)); // NOI18N
1986
throw new ConfigurationException JavaDoc(NbBundle.getMessage(SunONEDeploymentConfiguration.class,
1987                    "ERR_NoRefJdbcDataSource", jndiName)); // NOI18N
1988
}
1989
1990        ResourceConfiguratorInterface rci = getResourceConfigurator();
1991        if(rci != null) {
1992            ds = rci.createDataSource(jndiName, url, username, password, driver, resourceDir);
1993        }
1994        return ds;
1995    }
1996}
1997
Popular Tags