KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > j2ee > jboss4 > config > WarDeploymentConfiguration


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.j2ee.jboss4.config;
21
22 import java.beans.PropertyChangeEvent JavaDoc;
23 import java.beans.PropertyChangeListener JavaDoc;
24 import java.io.ByteArrayInputStream JavaDoc;
25 import java.io.File JavaDoc;
26 import java.io.IOException JavaDoc;
27 import java.io.OutputStream JavaDoc;
28 import javax.enterprise.deploy.model.DDBean JavaDoc;
29 import javax.enterprise.deploy.model.DDBeanRoot JavaDoc;
30 import javax.enterprise.deploy.model.DeployableObject JavaDoc;
31 import javax.enterprise.deploy.model.XpathEvent JavaDoc;
32 import javax.enterprise.deploy.model.XpathListener JavaDoc;
33 import javax.enterprise.deploy.spi.exceptions.ConfigurationException JavaDoc;
34 import javax.swing.text.BadLocationException JavaDoc;
35 import javax.swing.text.StyledDocument JavaDoc;
36 import org.netbeans.modules.j2ee.jboss4.config.gen.EjbRef;
37 import org.netbeans.modules.j2ee.jboss4.config.gen.JbossWeb;
38 import org.netbeans.modules.j2ee.jboss4.config.gen.MessageDestinationRef;
39 import org.netbeans.modules.j2ee.jboss4.config.gen.ResourceRef;
40 import org.openide.DialogDisplayer;
41 import org.openide.ErrorManager;
42 import org.openide.NotifyDescriptor;
43 import org.openide.cookies.EditorCookie;
44 import org.openide.cookies.SaveCookie;
45 import org.openide.filesystems.FileUtil;
46 import org.openide.loaders.DataObject;
47 import org.openide.loaders.DataObjectNotFoundException;
48 import org.openide.util.NbBundle;
49
50 /**
51  * Web module deployment configuration handles creation and updating of the
52  * jboss-web.xml configuration file.
53  *
54  * @author sherold, lkotouc
55  */

56 public class WarDeploymentConfiguration extends JBDeploymentConfiguration
57         implements PropertyChangeListener JavaDoc, XpathListener JavaDoc {
58     
59     private static final String JavaDoc RESOURCE_REF = "/web-app/resource-ref"; // NOI18N
60
private static final String JavaDoc EJB_REF = "/web-app/ejb-ref"; // NOI18N
61
private static final String JavaDoc MSG_DEST_REF = "/web-app/message-destination-ref"; // NOI18N
62

63     private File JavaDoc jbossWebFile;
64     private JbossWeb jbossWeb;
65     
66     /**
67      * Creates a new instance of WarDeploymentConfiguration
68      */

69     public WarDeploymentConfiguration(DeployableObject JavaDoc deployableObject) {
70         super(deployableObject);
71     }
72     
73     /**
74      * WarDeploymentConfiguration initialization. This method should be called before
75      * this class is being used.
76      *
77      * @param file jboss-web.xml file.
78      * @param resourceDir directory containing definition for enterprise resources.
79      */

80     public void init(File JavaDoc file, File JavaDoc resourceDir) {
81         super.init(resourceDir);
82         this.jbossWebFile = file;
83         getJbossWeb();
84         if (deploymentDescriptorDO == null) {
85             try {
86                 deploymentDescriptorDO = deploymentDescriptorDO.find(FileUtil.toFileObject(jbossWebFile));
87                 deploymentDescriptorDO.addPropertyChangeListener(this);
88             } catch(DataObjectNotFoundException donfe) {
89                 ErrorManager.getDefault().notify(donfe);
90             }
91         }
92
93         if (deplObj != null && deplObj.getDDBeanRoot() != null ) {
94             //listen on the resource-ref element
95
DDBeanRoot JavaDoc root = deplObj.getDDBeanRoot();
96             root.addXpathListener(RESOURCE_REF, this);
97             root.addXpathListener(EJB_REF, this);
98             root.addXpathListener(MSG_DEST_REF, this);
99         }
100     }
101     
102     /**
103      * Return context path.
104      *
105      * @return context path or null, if the file is not parseable.
106      */

107     public String JavaDoc getContextPath() throws ConfigurationException JavaDoc {
108         JbossWeb jbossWeb = getJbossWeb();
109         if (jbossWeb == null) { // graph not parseable
110
throw new ConfigurationException JavaDoc("jboss-web.xml is not parseable, cannot read the context path value."); // NOI18N
111
}
112         return jbossWeb.getContextRoot();
113     }
114     
115     /**
116      * Set context path.
117      */

118     public void setContextPath(String JavaDoc contextPath) throws ConfigurationException JavaDoc {
119         // TODO: this contextPath fix code will be removed, as soon as it will
120
// be moved to the web project
121
if (!isCorrectCP(contextPath)) {
122             String JavaDoc ctxRoot = contextPath;
123             java.util.StringTokenizer JavaDoc tok = new java.util.StringTokenizer JavaDoc(contextPath,"/"); //NOI18N
124
StringBuffer JavaDoc buf = new StringBuffer JavaDoc(); //NOI18N
125
while (tok.hasMoreTokens()) {
126                 buf.append("/"+tok.nextToken()); //NOI18N
127
}
128             ctxRoot = buf.toString();
129             NotifyDescriptor desc = new NotifyDescriptor.Message(
130                     NbBundle.getMessage (WarDeploymentConfiguration.class, "MSG_invalidCP", contextPath),
131                     NotifyDescriptor.Message.INFORMATION_MESSAGE);
132             DialogDisplayer.getDefault().notify(desc);
133             contextPath = ctxRoot;
134         }
135         final String JavaDoc newContextPath = contextPath;
136         modifyJbossWeb(new JbossWebModifier() {
137             public void modify(JbossWeb jbossWeb) {
138                 jbossWeb.setContextRoot(newContextPath);
139             }
140         });
141     }
142     
143     /**
144      * Listen to jboss-web.xml document changes.
145      */

146     public synchronized void propertyChange(PropertyChangeEvent JavaDoc evt) {
147         if (evt.getPropertyName() == DataObject.PROP_MODIFIED &&
148                 evt.getNewValue() == Boolean.FALSE) {
149
150             if (evt.getSource() == deploymentDescriptorDO) // dataobject has been modified, jbossWeb graph is out of sync
151
jbossWeb = null;
152             else
153                 super.propertyChange(evt);
154         }
155     }
156    
157     public void fireXpathEvent(XpathEvent JavaDoc xpe) {
158         if (!xpe.isAddEvent())
159             return;
160
161         DDBean JavaDoc eventDDBean = xpe.getBean();
162         if (RESOURCE_REF.equals(eventDDBean.getXpath())) { //a new resource reference added
163
String JavaDoc[] desc = eventDDBean.getText("description"); // NOI18N
164
String JavaDoc[] name = eventDDBean.getText("res-ref-name"); // NOI18N
165
String JavaDoc[] type = eventDDBean.getText("res-type"); // NOI18N
166
if (name.length > 0 && type.length > 0) {
167                 try {
168                     if (desc.length > 0 && "javax.sql.DataSource".equals(type[0])) // NOI18N
169
addResReference(desc[0], name[0]);
170                     else
171                     if ("javax.mail.Session".equals(type[0])) // NOI18N
172
addMailReference(name[0]);
173                     if ("javax.jms.ConnectionFactory".equals(type[0])) // NOI18N
174
addConnectionFactoryReference(name[0]);
175                 } catch (ConfigurationException JavaDoc ce) {
176                     ErrorManager.getDefault().notify(ce);
177                 }
178             }
179         }
180         else if (EJB_REF.equals(eventDDBean.getXpath())) { // a new ejb reference added
181
String JavaDoc[] name = eventDDBean.getText("ejb-ref-name"); // NOI18N
182
String JavaDoc[] type = eventDDBean.getText("ejb-ref-type"); // NOI18N
183
if (name.length > 0 && type.length > 0
184                     && ("Session".equals(type[0]) || "Entity".equals(type[0]))) { // NOI18N
185
try {
186                     addEjbReference(name[0]);
187                 } catch (ConfigurationException JavaDoc ce) {
188                     ErrorManager.getDefault().notify(ce);
189                 }
190             }
191         }
192         else if (MSG_DEST_REF.equals(eventDDBean.getXpath())) { //a new message destination reference added
193
String JavaDoc[] name = eventDDBean.getText("message-destination-ref-name"); // NOI18N
194
String JavaDoc[] type = eventDDBean.getText("message-destination-type"); // NOI18N
195
if (name.length > 0) {
196                 
197                 String JavaDoc destPrefix = "";
198                 if (type.length > 0) {
199                     if (type[0].equals("javax.jms.Queue")) // NOI18N
200
destPrefix = JBOSS4_MSG_QUEUE_JNDI_PREFIX;
201                     else
202                     if (type[0].equals("javax.jms.Topic")) // NOI18N
203
destPrefix = JBOSS4_MSG_TOPIC_JNDI_PREFIX;
204                 }
205                 
206                 try {
207                     addMsgDestReference(name[0], destPrefix);
208                 } catch (ConfigurationException JavaDoc ce) {
209                     ErrorManager.getDefault().notify(ce);
210                 }
211             }
212         }
213         
214     }
215
216     /**
217      * Add a new resource reference.
218      *
219      * @param desc description
220      * @param name resource reference name
221      */

222     private void addResReference(final String JavaDoc desc, final String JavaDoc name) throws ConfigurationException JavaDoc {
223         modifyJbossWeb(new JbossWebModifier() {
224             public void modify(JbossWeb modifiedJbossWeb) {
225
226                 // check whether resource not already defined
227
ResourceRef resourceRefs[] = modifiedJbossWeb.getResourceRef();
228                 for (int i = 0; i < resourceRefs.length; i++) {
229                     String JavaDoc rrn = resourceRefs[i].getResRefName();
230                     if (name.equals(rrn)) {
231                         // already exists
232
return;
233                     }
234                 }
235
236                 //if it doesn't exist yet, create a new one
237
ResourceRef newRR = new ResourceRef();
238                 newRR.setResRefName(name);
239                 newRR.setJndiName(JBOSS4_DATASOURCE_JNDI_PREFIX + name);
240                 modifiedJbossWeb.addResourceRef(newRR);
241             }
242         });
243     }
244     
245     /**
246      * Add a new mail service reference.
247      *
248      * @param name mail service name
249      */

250     private void addMailReference(final String JavaDoc name) throws ConfigurationException JavaDoc {
251         modifyJbossWeb(new JbossWebModifier() {
252             public void modify(JbossWeb modifiedJbossWeb) {
253
254                 // check whether mail service not already defined
255
ResourceRef resourceRefs[] = modifiedJbossWeb.getResourceRef();
256                 for (int i = 0; i < resourceRefs.length; i++) {
257                     String JavaDoc rrn = resourceRefs[i].getResRefName();
258                     if (name.equals(rrn)) {
259                         // already exists
260
return;
261                     }
262                 }
263
264                 //if it doesn't exist yet, create a new one
265
ResourceRef newRR = new ResourceRef();
266                 newRR.setResRefName(name);
267                 newRR.setJndiName(JBOSS4_MAIL_SERVICE_JNDI_NAME);
268                 modifiedJbossWeb.addResourceRef(newRR);
269             }
270         });
271     }
272     
273     /**
274      * Add a new connection factory reference.
275      *
276      * @param name connection factory name
277      */

278     private void addConnectionFactoryReference(final String JavaDoc name) throws ConfigurationException JavaDoc {
279         modifyJbossWeb(new JbossWebModifier() {
280             public void modify(JbossWeb modifiedJbossWeb) {
281
282                 // check whether connection factory not already defined
283
ResourceRef resourceRefs[] = modifiedJbossWeb.getResourceRef();
284                 for (int i = 0; i < resourceRefs.length; i++) {
285                     String JavaDoc rrn = resourceRefs[i].getResRefName();
286                     if (name.equals(rrn)) {
287                         // already exists
288
return;
289                     }
290                 }
291
292                 //if it doesn't exist yet, create a new one
293
ResourceRef newRR = new ResourceRef();
294                 newRR.setResRefName(name);
295                 newRR.setJndiName(JBOSS4_CONN_FACTORY_JNDI_NAME);
296                 modifiedJbossWeb.addResourceRef(newRR);
297             }
298         });
299     }
300     
301     /**
302      * Add a new message destination reference.
303      *
304      * @param name message destination name
305      * @param destPrefix MDB destination prefix
306      */

307     private void addMsgDestReference(final String JavaDoc name, final String JavaDoc destPrefix) throws ConfigurationException JavaDoc {
308         modifyJbossWeb(new JbossWebModifier() {
309             public void modify(JbossWeb modifiedJbossWeb) {
310
311                 // check whether message destination not already defined
312
MessageDestinationRef mdRefs[] = modifiedJbossWeb.getMessageDestinationRef();
313                 for (int i = 0; i < mdRefs.length; i++) {
314                     String JavaDoc mdrn = mdRefs[i].getMessageDestinationRefName();
315                     if (name.equals(mdrn)) {
316                         // already exists
317
return;
318                     }
319                 }
320
321                 //if it doesn't exist yet, create a new one
322
MessageDestinationRef mdr = new MessageDestinationRef();
323                 mdr.setMessageDestinationRefName(name);
324                 String JavaDoc jndiName = name;
325                 if (name.startsWith("jms/")) // prefix automatically prepended to the selected message destination during 'Send JMS Message' action
326
jndiName = destPrefix + name.substring("jms/".length()); //replace 'jms/' with the correct prefix
327
mdr.setJndiName(jndiName);
328                 modifiedJbossWeb.addMessageDestinationRef(mdr);
329             }
330         });
331     }
332     
333     /**
334      * Add a new ejb reference.
335      *
336      * @param name ejb reference name
337      */

338     private void addEjbReference(final String JavaDoc name) throws ConfigurationException JavaDoc {
339         modifyJbossWeb(new JbossWebModifier() {
340             public void modify(JbossWeb modifiedJbossWeb) {
341
342                 // check whether resource not already defined
343
EjbRef ejbRefs[] = modifiedJbossWeb.getEjbRef();
344                 for (int i = 0; i < ejbRefs.length; i++) {
345                     String JavaDoc ern = ejbRefs[i].getEjbRefName();
346                     if (name.equals(ern)) {
347                         // already exists
348
return;
349                     }
350                 }
351
352                 //if it doesn't exist yet, create a new one
353
EjbRef newER = new EjbRef();
354                 newER.setEjbRefName(name);
355                 String JavaDoc jndiName = name;
356                 if (jndiName.indexOf('/') != -1) {
357                     jndiName = jndiName.substring(jndiName.lastIndexOf('/') + 1);
358                 }
359                 newER.setJndiName(jndiName);
360                 modifiedJbossWeb.addEjbRef(newER);
361             }
362         });
363     }
364     
365     /**
366      * Return JbossWeb graph. If it was not created yet, load it from the file
367      * and cache it. If the file does not exist, generate it.
368      *
369      * @return JbossWeb graph or null if the jboss-web.xml file is not parseable.
370      */

371     public synchronized JbossWeb getJbossWeb() {
372         if (jbossWeb == null) {
373             try {
374                 if (jbossWebFile.exists()) {
375                     // load configuration if already exists
376
try {
377                         jbossWeb = JbossWeb.createGraph(jbossWebFile);
378                     } catch (IOException JavaDoc ioe) {
379                         ErrorManager.getDefault().notify(ioe);
380                     } catch (RuntimeException JavaDoc re) {
381                         // jboss-web.xml is not parseable, do nothing
382
}
383                 } else {
384                     // create jboss-web.xml if it does not exist yet
385
jbossWeb = generateJbossWeb();
386                     writefile(jbossWebFile, jbossWeb);
387                 }
388             } catch (ConfigurationException JavaDoc ce) {
389                 ErrorManager.getDefault().notify(ce);
390             }
391         }
392         return jbossWeb;
393     }
394     
395     // JSR-88 methods ---------------------------------------------------------
396

397     public void save(OutputStream JavaDoc os) throws ConfigurationException JavaDoc {
398         JbossWeb jbossWeb = getJbossWeb();
399         if (jbossWeb == null) {
400             throw new ConfigurationException JavaDoc("Cannot read configuration, it is probably in an inconsistent state."); // NOI18N
401
}
402         try {
403             jbossWeb.write(os);
404         } catch (IOException JavaDoc ioe) {
405             throw new ConfigurationException JavaDoc(ioe.getLocalizedMessage());
406         }
407     }
408     
409     // private helper methods -------------------------------------------------
410

411     /**
412      * Perform jbossWeb changes defined by the jbossWeb modifier. Update editor
413      * content and save changes, if appropriate.
414      *
415      * @param modifier
416      */

417     private void modifyJbossWeb(JbossWebModifier modifier) throws ConfigurationException JavaDoc {
418         assert deploymentDescriptorDO != null : "DataObject has not been initialized yet"; // NIO18N
419
try {
420             // get the document
421
EditorCookie editor = (EditorCookie)deploymentDescriptorDO.getCookie(EditorCookie.class);
422             StyledDocument JavaDoc doc = editor.getDocument();
423             if (doc == null) {
424                 doc = editor.openDocument();
425             }
426             
427             // get the up-to-date model
428
JbossWeb newJbossWeb = null;
429             try {
430                 // try to create a graph from the editor content
431
byte[] docString = doc.getText(0, doc.getLength()).getBytes();
432                 newJbossWeb = JbossWeb.createGraph(new ByteArrayInputStream JavaDoc(docString));
433             } catch (RuntimeException JavaDoc e) {
434                 JbossWeb oldJbossWeb = getJbossWeb();
435                 if (oldJbossWeb == null) {
436                     // neither the old graph is parseable, there is not much we can do here
437
// TODO: should we notify the user?
438
throw new ConfigurationException JavaDoc("Configuration data are not parseable cannot perform changes."); // NOI18N
439
}
440                 // current editor content is not parseable, ask whether to override or not
441
NotifyDescriptor notDesc = new NotifyDescriptor.Confirmation(
442                         NbBundle.getMessage(WarDeploymentConfiguration.class, "MSG_jbossWebXmlNotValid"),
443                         NotifyDescriptor.OK_CANCEL_OPTION);
444                 Object JavaDoc result = DialogDisplayer.getDefault().notify(notDesc);
445                 if (result == NotifyDescriptor.CANCEL_OPTION) {
446                     // keep the old content
447
return;
448                 }
449                 // use the old graph
450
newJbossWeb = oldJbossWeb;
451             }
452             
453             // perform changes
454
modifier.modify(newJbossWeb);
455             
456             // save, if appropriate
457
boolean modified = deploymentDescriptorDO.isModified();
458             replaceDocument(doc, newJbossWeb);
459             if (!modified) {
460                 SaveCookie cookie = (SaveCookie)deploymentDescriptorDO.getCookie(SaveCookie.class);
461                 cookie.save();
462             }
463             jbossWeb = newJbossWeb;
464         } catch (BadLocationException JavaDoc ble) {
465             throw (ConfigurationException JavaDoc)(new ConfigurationException JavaDoc().initCause(ble));
466         } catch (IOException JavaDoc ioe) {
467             throw (ConfigurationException JavaDoc)(new ConfigurationException JavaDoc().initCause(ioe));
468         }
469     }
470     
471     /**
472      * Generate JbossWeb graph.
473      */

474     private JbossWeb generateJbossWeb() {
475         JbossWeb jbossWeb = new JbossWeb();
476         jbossWeb.setContextRoot(""); // NOI18N
477
return jbossWeb;
478     }
479     
480     // TODO: this contextPath fix code will be removed, as soon as it will
481
// be moved to the web project
482
private boolean isCorrectCP(String JavaDoc contextPath) {
483         boolean correct=true;
484         if (!contextPath.equals("") && !contextPath.startsWith("/")) correct=false; //NOI18N
485
else if (contextPath.endsWith("/")) correct=false; //NOI18N
486
else if (contextPath.indexOf("//")>=0) correct=false; //NOI18N
487
return correct;
488     }
489     
490     
491     // private helper interface -----------------------------------------------
492

493     private interface JbossWebModifier {
494         void modify(JbossWeb modifiedJbossWeb);
495     }
496 }
497
Popular Tags