KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > tomcat5 > config > WebappConfiguration


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.tomcat5.config;
21
22 import java.beans.PropertyChangeEvent JavaDoc;
23 import java.beans.PropertyChangeListener JavaDoc;
24 import java.io.BufferedOutputStream JavaDoc;
25 import java.io.ByteArrayInputStream JavaDoc;
26 import java.io.File JavaDoc;
27 import java.io.IOException JavaDoc;
28 import java.io.InputStream JavaDoc;
29 import java.io.OutputStream JavaDoc;
30 import java.io.StringWriter JavaDoc;
31 import java.util.ArrayList JavaDoc;
32 import java.util.Collections JavaDoc;
33 import java.util.HashMap JavaDoc;
34 import java.util.HashSet JavaDoc;
35 import java.util.List JavaDoc;
36 import java.util.Set JavaDoc;
37 import javax.enterprise.deploy.model.DDBean JavaDoc;
38 import javax.enterprise.deploy.model.DDBeanRoot JavaDoc;
39 import javax.enterprise.deploy.model.DeployableObject JavaDoc;
40 import javax.enterprise.deploy.model.XpathEvent JavaDoc;
41 import javax.enterprise.deploy.model.XpathListener JavaDoc;
42 import javax.enterprise.deploy.spi.DConfigBeanRoot JavaDoc;
43 import javax.enterprise.deploy.spi.DeploymentConfiguration JavaDoc;
44 import javax.enterprise.deploy.spi.exceptions.BeanNotFoundException JavaDoc;
45 import javax.enterprise.deploy.spi.exceptions.ConfigurationException JavaDoc;
46 import javax.swing.text.BadLocationException JavaDoc;
47 import javax.swing.text.StyledDocument JavaDoc;
48 import org.netbeans.modules.j2ee.deployment.common.api.Datasource;
49 import org.netbeans.modules.j2ee.deployment.common.api.DatasourceAlreadyExistsException;
50 import org.netbeans.modules.schema2beans.BaseBean;
51 import org.netbeans.modules.schema2beans.Schema2BeansException;
52 import org.netbeans.modules.tomcat5.TomcatManager;
53 import org.netbeans.modules.tomcat5.TomcatManager.TomcatVersion;
54 import org.netbeans.modules.tomcat5.config.gen.Context;
55 import org.netbeans.modules.tomcat5.config.gen.Parameter;
56 import org.netbeans.modules.tomcat5.config.gen.ResourceParams;
57 import org.openide.DialogDisplayer;
58 import org.openide.ErrorManager;
59 import org.openide.NotifyDescriptor;
60 import org.openide.cookies.EditorCookie;
61 import org.openide.cookies.SaveCookie;
62 import org.openide.filesystems.FileLock;
63 import org.openide.filesystems.FileObject;
64 import org.openide.filesystems.FileSystem;
65 import org.openide.filesystems.FileUtil;
66 import org.openide.loaders.DataObject;
67 import org.openide.loaders.DataObjectNotFoundException;
68 import org.openide.text.NbDocument;
69 import org.openide.util.NbBundle;
70
71 /**
72  * Server specific configuration data related to Tomcat 5 server
73  *
74  * @author sherold
75  */

76 public class WebappConfiguration implements DeploymentConfiguration JavaDoc, PropertyChangeListener JavaDoc,
77         XpathListener JavaDoc {
78     
79     private final DeployableObject JavaDoc deplObj;
80     private final TomcatVersion tomcatVersion;
81     
82     private DataObject contextDataObject;
83     private File JavaDoc contextXml;
84     private Context context;
85     
86     private final String JavaDoc ATTR_PATH = "path"; // NOI18N
87

88     /** Creates a new instance of WebappConfiguration */
89     public WebappConfiguration (DeployableObject JavaDoc deplObj, TomcatVersion tomcatVersion) {
90         this.deplObj = deplObj;
91         this.tomcatVersion = tomcatVersion;
92     }
93     
94     /**
95      * WebappConfiguration initialization. This method should be called before
96      * this class is being used.
97      *
98      * @param contextXml context.xml file.
99      */

100     public void init(File JavaDoc contextXml) {
101         this.contextXml = contextXml;
102         getContext();
103         if (contextDataObject == null) {
104             try {
105                 contextDataObject = DataObject.find(FileUtil.toFileObject(contextXml));
106                 contextDataObject.addPropertyChangeListener(this);
107             } catch(DataObjectNotFoundException donfe) {
108                 ErrorManager.getDefault().notify(donfe);
109             }
110         }
111         // currently listen only to resource-ref changes
112
DDBeanRoot JavaDoc root = deplObj.getDDBeanRoot();
113         if (root != null) {
114             // TODO: if null, we should listen on creation of the web.xml file,
115
// there is, however, no api for it at this point
116
root.addXpathListener("/web-app/resource-ref", this); // NOI18N
117
}
118     }
119     
120     /**
121      * Return Context graph. If it was not created yet, load it from the file
122      * and cache it. If the file does not exist, generate it.
123      *
124      * @return Context graph or null if the context.xml file is not parseable.
125      */

126     public synchronized Context getContext() {
127         if (context == null) {
128             try {
129                 if (contextXml.exists()) {
130                     // load configuration if already exists
131
try {
132                         context = Context.createGraph(contextXml);
133                     } catch (IOException JavaDoc ioe) {
134                         ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ioe);
135                     } catch (RuntimeException JavaDoc re) {
136                         // context.xml is not parseable, do nothing
137
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, re);
138                     }
139                 } else {
140                     // create context.xml if it does not exist yet
141
context = genereateContext();
142                     writefile(contextXml);
143                 }
144             } catch (ConfigurationException JavaDoc ce) {
145                 ErrorManager.getDefault().notify(ce);
146             }
147         }
148         return context;
149     }
150     
151     /**
152      * Return context path.
153      *
154      * @return context path or null, if the file is not parseable.
155      */

156     public String JavaDoc getContextPath() throws ConfigurationException JavaDoc {
157         Context ctx = getContext();
158         if (ctx == null) { // graph not parseable
159
throw new ConfigurationException JavaDoc("Context.xml is not parseable, cannot read the context path value."); // NOI18N
160
}
161         return ctx.getAttributeValue(ATTR_PATH);
162     }
163     
164     
165     /**
166      * Get the module datasources defined in the context.xml file.
167      */

168     Set JavaDoc<Datasource> getDatasources() {
169         Context context = getContext();
170         if (context == null) { // graph not parseable
171
ErrorManager.getDefault().log(ErrorManager.INFORMATIONAL, "Context.xml is not parseable, cannot get the module datasources"); // NOI18N
172
return Collections.<Datasource>emptySet();
173         }
174         Set JavaDoc<Datasource> result = new HashSet JavaDoc<Datasource>();
175         int length = context.getResource().length;
176         if (tomcatVersion != TomcatVersion.TOMCAT_50) {
177             // Tomcat 5.5.x or Tomcat 6.0.x
178
for (int i = 0; i < length; i++) {
179                 String JavaDoc type = context.getResourceType(i);
180                 if ("javax.sql.DataSource".equals(type)) { // NOI18N
181
String JavaDoc name = context.getResourceName(i);
182                     String JavaDoc username = context.getResourceUsername(i);
183                     String JavaDoc url = context.getResourceUrl(i);
184                     String JavaDoc password = context.getResourcePassword(i);
185                     String JavaDoc driverClassName = context.getResourceDriverClassName(i);
186                     if (name != null && username != null && url != null && driverClassName != null) {
187                         // return the datasource only if all the needed params are non-null except the password param
188
result.add(new TomcatDatasource(username, url, password, name, driverClassName));
189                     }
190                 }
191             }
192         } else {
193             // Tomcat 5.0.x
194
ResourceParams[] resourceParams = context.getResourceParams();
195             for (int i = 0; i < length; i++) {
196                 String JavaDoc type = context.getResourceType(i);
197                 if ("javax.sql.DataSource".equals(type)) { // NOI18N
198
String JavaDoc name = context.getResourceName(i);
199                     // find the resource params for the selected resource
200
for (int j = 0; j < resourceParams.length; j++) {
201                         if (name.equals(resourceParams[j].getName())) {
202                             Parameter[] params = resourceParams[j].getParameter();
203                             HashMap JavaDoc paramNameValueMap = new HashMap JavaDoc(params.length);
204                             for (Parameter parameter : params) {
205                                 paramNameValueMap.put(parameter.getName(), parameter.getValue());
206                             }
207                             String JavaDoc username = (String JavaDoc) paramNameValueMap.get("username"); // NOI18N
208
String JavaDoc url = (String JavaDoc) paramNameValueMap.get("url"); // NOI18N
209
String JavaDoc password = (String JavaDoc) paramNameValueMap.get("password"); // NOI18N
210
String JavaDoc driverClassName = (String JavaDoc) paramNameValueMap.get("driverClassName"); // NOI18N
211
if (username != null && url != null && driverClassName != null) {
212                                 // return the datasource only if all the needed params are non-null except the password param
213
result.add(new TomcatDatasource(username, url, password, name, driverClassName));
214                             }
215                         }
216                     }
217                 }
218             }
219         }
220         return result;
221     }
222     
223     
224     Datasource createDatasource(String JavaDoc jndiName, String JavaDoc url, String JavaDoc username, String JavaDoc password, String JavaDoc driver)
225     throws ConfigurationException JavaDoc, DatasourceAlreadyExistsException {
226         return createJDBCReference(jndiName, url, username, password, driver);
227     }
228     
229     /**
230      * Set context path.
231      */

232     public void setContextPath(String JavaDoc contextPath) throws ConfigurationException JavaDoc {
233         // TODO: this contextPath fix code will be removed, as soon as it will
234
// be moved to the web project
235
if (!isCorrectCP(contextPath)) {
236             String JavaDoc ctxRoot = contextPath;
237             java.util.StringTokenizer JavaDoc tok = new java.util.StringTokenizer JavaDoc(contextPath,"/"); //NOI18N
238
StringBuffer JavaDoc buf = new StringBuffer JavaDoc(); //NOI18N
239
while (tok.hasMoreTokens()) {
240                 buf.append("/"+tok.nextToken()); //NOI18N
241
}
242             ctxRoot = buf.toString();
243             NotifyDescriptor desc = new NotifyDescriptor.Message(
244                     NbBundle.getMessage (WebappConfiguration.class, "MSG_invalidCP", contextPath),
245                     NotifyDescriptor.Message.INFORMATION_MESSAGE);
246             DialogDisplayer.getDefault().notify(desc);
247             contextPath = ctxRoot;
248         }
249         final String JavaDoc newContextPath = contextPath;
250         modifyContext(new ContextModifier() {
251             public void modify(Context context) {
252                 // if Tomcat 5.0.x update also logger prefix
253
if (tomcatVersion == TomcatVersion.TOMCAT_50) {
254                     String JavaDoc oldContextPath = context.getAttributeValue(ATTR_PATH);
255                     String JavaDoc oldPrefix = context.getLoggerPrefix();
256                     if (oldPrefix != null
257                             && oldPrefix.equals(computeLoggerPrefix(oldContextPath))) {
258                         context.setLoggerPrefix(computeLoggerPrefix(newContextPath));
259                     }
260                 }
261                 context.setAttributeValue(ATTR_PATH, newContextPath);
262             }
263         });
264     }
265     
266     /** Context data object */
267     public DataObject getContextDataObject() {
268         return contextDataObject;
269     }
270     
271     // PropertyChangeListener listener ----------------------------------------
272

273     /**
274      * Listen to context.xml document changes.
275      */

276     public void propertyChange(PropertyChangeEvent JavaDoc evt) {
277         if (evt.getPropertyName() == DataObject.PROP_MODIFIED &&
278                 evt.getNewValue() == Boolean.FALSE) {
279             // dataobject has been modified, context graph is out of sync
280
context = null;
281         }
282     }
283     
284     // XpathListener implementation -------------------------------------------
285

286     public void fireXpathEvent(XpathEvent JavaDoc xpe) {
287         DDBean JavaDoc eventDDBean = xpe.getBean();
288         if ("/web-app/resource-ref".equals(eventDDBean.getXpath())) { // NIO18N
289
// new resource reference added
290
if (xpe.isAddEvent()) {
291                 String JavaDoc[] name = eventDDBean.getText("res-ref-name"); // NOI18N
292
String JavaDoc[] type = eventDDBean.getText("res-type"); // NOI18N
293
if (name.length > 0 && type.length > 0) {
294                     try {
295                         addResReference(name[0], type[0]);
296                     } catch (ConfigurationException JavaDoc ce) {
297                         ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ce);
298                     }
299                 }
300             }
301         }
302     }
303     
304     // JSR-88 methods ---------------------------------------------------------
305

306     public DeployableObject JavaDoc getDeployableObject () {
307         return deplObj;
308     }
309     
310     public void save (OutputStream JavaDoc os) throws ConfigurationException JavaDoc {
311         Context ctx = getContext();
312         if (ctx == null) {
313             throw new ConfigurationException JavaDoc("Cannot read configuration, it is probably in an inconsistent state."); // NOI18N
314
}
315         try {
316             ctx.write(os);
317         } catch (IOException JavaDoc ioe) {
318             throw new ConfigurationException JavaDoc(ioe.getLocalizedMessage());
319         }
320     }
321     
322     // JSR-88 methods empty implementation ------------------------------------
323

324     public DConfigBeanRoot JavaDoc getDConfigBeanRoot (DDBeanRoot JavaDoc dDBeanRoot)
325     throws ConfigurationException JavaDoc {
326         return null;
327     }
328     
329     public void removeDConfigBean (DConfigBeanRoot JavaDoc dConfigBeanRoot)
330     throws BeanNotFoundException JavaDoc {
331         throw new BeanNotFoundException JavaDoc ("Bean not found in WebappConfiguration " + dConfigBeanRoot); // NOI18N
332
}
333     
334     public void restore (InputStream JavaDoc is)
335     throws ConfigurationException JavaDoc {
336     }
337     
338     public DConfigBeanRoot JavaDoc restoreDConfigBean (InputStream JavaDoc is, DDBeanRoot JavaDoc dDBeanRoot)
339     throws ConfigurationException JavaDoc {
340         return null;
341     }
342     
343     public void saveDConfigBean (OutputStream JavaDoc os, DConfigBeanRoot JavaDoc dConfigBeanRoot)
344     throws ConfigurationException JavaDoc {
345     }
346     
347     
348     // private helper methods -------------------------------------------------
349

350     /**
351      * Genereate Context graph.
352      */

353     private Context genereateContext() {
354         Context newContext = new Context();
355         String JavaDoc path = ""; // NOI18N
356
newContext.setAttributeValue(ATTR_PATH, path);
357
358         // if tomcat 5.0.x generate a logger
359
if (tomcatVersion == TomcatVersion.TOMCAT_50) {
360             // generate default logger
361
newContext.setLogger(true);
362             newContext.setLoggerClassName("org.apache.catalina.logger.FileLogger"); // NOI18N
363
newContext.setLoggerPrefix(computeLoggerPrefix(path));
364             newContext.setLoggerSuffix(".log"); // NOI18N
365
newContext.setLoggerTimestamp("true"); // NOI18N
366
}
367         return newContext;
368     }
369     
370     private Datasource createJDBCReference(final String JavaDoc name, final String JavaDoc url, final String JavaDoc username, final String JavaDoc password, final String JavaDoc driverClassName)
371     throws ConfigurationException JavaDoc, DatasourceAlreadyExistsException {
372         // check whether a resource of the given name is not already defined in the module
373
List JavaDoc<Datasource> conflictingDS = new ArrayList JavaDoc<Datasource>();
374         for (Datasource datasource : getDatasources()) {
375             if (name.equals(datasource.getJndiName())) {
376                 conflictingDS.add(datasource);
377             }
378         }
379         if (conflictingDS.size() > 0) {
380             throw new DatasourceAlreadyExistsException(conflictingDS);
381         }
382         if (tomcatVersion != TomcatVersion.TOMCAT_50) {
383             // Tomcat 5.5.x or Tomcat 6.0.x
384
modifyContext(new ContextModifier() {
385                 public void modify(Context context) {
386                     int idx = context.addResource(true);
387                     context.setResourceName(idx, name);
388                     context.setResourceAuth(idx, "Container"); // NOI18N
389
context.setResourceType(idx, "javax.sql.DataSource"); // NOI18N
390
context.setResourceDriverClassName(idx, driverClassName);
391                     context.setResourceUrl(idx, url);
392                     context.setResourceUsername(idx, username);
393                     context.setResourcePassword(idx, password);
394                     context.setResourceMaxActive(idx, "20"); // NOI18N
395
context.setResourceMaxIdle(idx, "10"); // NOI18N
396
context.setResourceMaxWait(idx, "-1"); // NOI18N
397
}
398             });
399         } else {
400             // Tomcat 5.0.x
401
modifyContext(new ContextModifier() {
402                 public void modify(Context context) {
403                     int idx = context.addResource(true);
404                     context.setResourceName(idx, name);
405                     context.setResourceAuth(idx, "Container"); // NOI18N
406
context.setResourceType(idx, "javax.sql.DataSource"); // NOI18N
407

408                     // check whether resource params not already defined
409
ResourceParams[] resourceParams = context.getResourceParams();
410                     for (int i = 0; i < resourceParams.length; i++) {
411                         if (name.equals(resourceParams[i].getName())) {
412                             // if this happens in means that for this ResourceParams
413
// element was no repspective Resource element - remove it
414
context.removeResourceParams(resourceParams[i]);
415                         }
416                     }
417                     ResourceParams newResourceParams = createResourceParams(
418                             name,
419                             new Parameter[] {
420                                 createParameter("factory", "org.apache.commons.dbcp.BasicDataSourceFactory"), // NOI18N
421
createParameter("driverClassName", driverClassName), // NOI18N
422
createParameter("url", url), // NOI18N
423
createParameter("username", username), // NOI18N
424
createParameter("password", password), // NOI18N
425
createParameter("maxActive", "20"), // NOI18N
426
createParameter("maxIdle", "10"), // NOI18N
427
createParameter("maxWait", "-1") // NOI18N
428
}
429                     );
430                     context.addResourceParams(newResourceParams);
431                 }
432             });
433         }
434         return new TomcatDatasource(username, url, password, name, driverClassName);
435     }
436     
437     /**
438      * Add a new resource reference.
439      *
440      * @param name resource reference name
441      */

442     private void addResReference(final String JavaDoc name, final String JavaDoc type) throws ConfigurationException JavaDoc {
443         if ("javax.sql.DataSource".equals(type)) { // NOI18N
444
modifyContext(new ContextModifier() {
445                 public void modify(Context context) {
446                     // check whether a resource of the given name is not already defined
447
int lengthResource = context.getResource().length;
448                     for (int i = 0; i < lengthResource; i++) {
449                         if (name.equals(context.getResourceName(i))) {
450                             // do nothing if already exists
451
return;
452                         }
453                     }
454                     // check whether a resource link of the given name is not already defined
455
int lengthResourceLink = context.getResourceLink().length;
456                     for (int i = 0; i < lengthResourceLink; i++) {
457                         if (name.equals(context.getResourceLinkName(i))) {
458                             // do nothing if already exists
459
return;
460                         }
461                     }
462                     // create a resource link to the global resource
463
// module datasources are created by explicite call ConfigurationSupportImpl.createDatasource
464
int idx = context.addResourceLink(true);
465                     context.setResourceLinkName(idx, name);
466                     context.setResourceLinkGlobal(idx, name);
467                     context.setResourceLinkType(idx, "javax.sql.DataSource"); // NOI18N
468
}
469             });
470         }
471     }
472     
473     /**
474      * Perform context changes defined by the context modifier. Update editor
475      * content and save changes, if appropriate.
476      *
477      * @param modifier
478      */

479     private void modifyContext(ContextModifier modifier) throws ConfigurationException JavaDoc {
480         assert contextDataObject != null : "DataObject has not been initialized yet"; // NIO18N
481
try {
482             // get the document
483
EditorCookie editor = (EditorCookie)contextDataObject.getCookie(EditorCookie.class);
484             StyledDocument JavaDoc doc = editor.getDocument();
485             if (doc == null) {
486                 doc = editor.openDocument();
487             }
488             
489             // get the up-to-date model
490
Context newContext = null;
491             try {
492                 // try to create a graph from the editor content
493
byte[] docString = doc.getText(0, doc.getLength()).getBytes();
494                 newContext = Context.createGraph(new ByteArrayInputStream JavaDoc(docString));
495             } catch (RuntimeException JavaDoc e) {
496                 Context oldContext = getContext();
497                 if (oldContext == null) {
498                     // neither the old graph is parseable, there is not much we can do here
499
// TODO: should we notify the user?
500
throw new ConfigurationException JavaDoc("Configuration data are not parseable cannot perform changes."); // NOI18N
501
}
502                 // current editor content is not parseable, ask whether to override or not
503
NotifyDescriptor notDesc = new NotifyDescriptor.Confirmation(
504                         NbBundle.getMessage(WebappConfiguration.class, "MSG_ContextXmlNotValid"),
505                         NotifyDescriptor.OK_CANCEL_OPTION);
506                 Object JavaDoc result = DialogDisplayer.getDefault().notify(notDesc);
507                 if (result == NotifyDescriptor.CANCEL_OPTION) {
508                     // keep the old content
509
return;
510                 }
511                 // use the old graph
512
newContext = oldContext;
513             }
514             
515             // perform changes
516
modifier.modify(newContext);
517             
518             // save, if appropriate
519
boolean modified = contextDataObject.isModified();
520             replaceDocument(doc, newContext);
521             if (!modified) {
522                 SaveCookie cookie = (SaveCookie)contextDataObject.getCookie(SaveCookie.class);
523                 if (cookie != null) {
524                     cookie.save();
525                 }
526             }
527             context = newContext;
528         } catch (BadLocationException JavaDoc ble) {
529             throw (ConfigurationException JavaDoc)(new ConfigurationException JavaDoc().initCause(ble));
530         } catch (IOException JavaDoc ioe) {
531             throw (ConfigurationException JavaDoc)(new ConfigurationException JavaDoc().initCause(ioe));
532         }
533     }
534     
535     private Parameter createParameter(String JavaDoc name, String JavaDoc value) {
536         Parameter parameter = new Parameter();
537         parameter.setName(name);
538         parameter.setValue(value);
539         return parameter;
540     }
541     
542     private ResourceParams createResourceParams(String JavaDoc name, Parameter[] parameters) {
543         ResourceParams resourceParams = new ResourceParams();
544         resourceParams.setName(name);
545         for (int i = 0; i < parameters.length; i++) {
546             resourceParams.addParameter(parameters[i]);
547         }
548         return resourceParams;
549     }
550     
551     /**
552      * Compute logger prefix based on context path. Cut off leading slash and
553      * escape other slashes, use ROOT prefix for empty context path.
554      */

555     private String JavaDoc computeLoggerPrefix(String JavaDoc contextPath) {
556         return contextPath.length() > 0
557                 ? contextPath.substring(1).replace('/', '_').concat(".") // NOI18N
558
: "ROOT."; // NOI18N
559
}
560     
561     private void writefile(final File JavaDoc file) throws ConfigurationException JavaDoc {
562         try {
563             FileObject cfolder = FileUtil.toFileObject(file.getParentFile());
564             if (cfolder == null) {
565                 File JavaDoc parentFile = file.getParentFile();
566                 try {
567                     cfolder = FileUtil.toFileObject(parentFile.getParentFile()).createFolder(parentFile.getName());
568                 } catch (IOException JavaDoc ioe) {
569                     throw new ConfigurationException JavaDoc(NbBundle.getMessage(WebappConfiguration.class, "MSG_FailedToCreateConfigFolder", parentFile.getAbsolutePath()));
570                 }
571             }
572             final FileObject folder = cfolder;
573             FileSystem fs = folder.getFileSystem();
574             fs.runAtomicAction(new FileSystem.AtomicAction() {
575                 public void run() throws IOException JavaDoc {
576                     OutputStream JavaDoc os = null;
577                     FileLock lock = null;
578                     try {
579                         String JavaDoc name = file.getName();
580                         FileObject configFO = folder.getFileObject(name);
581                         if (configFO == null) {
582                             configFO = folder.createData(name);
583                         }
584                         lock = configFO.lock();
585                         os = new BufferedOutputStream JavaDoc (configFO.getOutputStream(lock), 4086);
586                         Context ctx = getContext();
587                         // TODO notification needed
588
if (ctx != null) {
589                             ctx.write(os);
590                         }
591                     } finally {
592                         if (os != null) {
593                             try { os.close(); } catch(IOException JavaDoc ioe) {}
594                         }
595                         if (lock != null)
596                             lock.releaseLock();
597                     }
598                 }
599             });
600         } catch (IOException JavaDoc e) {
601             throw new ConfigurationException JavaDoc (e.getLocalizedMessage ());
602         }
603     }
604     
605     /**
606      * Replace the content of the document by the graph.
607      */

608     private void replaceDocument(final StyledDocument JavaDoc doc, BaseBean graph) {
609         final StringWriter JavaDoc out = new StringWriter JavaDoc();
610         try {
611             graph.write(out);
612         } catch (Schema2BeansException ex) {
613             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
614         } catch (IOException JavaDoc ioe) {
615             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ioe);
616         }
617         NbDocument.runAtomic(doc, new Runnable JavaDoc() {
618             public void run() {
619                 try {
620                     doc.remove(0, doc.getLength());
621                     doc.insertString(0, out.toString(), null);
622                 } catch (BadLocationException JavaDoc ble) {
623                     ErrorManager.getDefault().notify(ble);
624                 }
625             }
626         });
627     }
628     
629     // TODO: this contextPath fix code will be removed, as soon as it will
630
// be moved to the web project
631
private boolean isCorrectCP(String JavaDoc contextPath) {
632         boolean correct=true;
633         if (!contextPath.equals("") && !contextPath.startsWith("/")) correct=false; //NOI18N
634
else if (contextPath.endsWith("/")) correct=false; //NOI18N
635
else if (contextPath.indexOf("//")>=0) correct=false; //NOI18N
636
return correct;
637     }
638     
639     // private helper interface -----------------------------------------------
640

641     private interface ContextModifier {
642         void modify(Context context);
643     }
644 }
645
Popular Tags