KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > web > project > WebProject


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-2007 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.web.project;
21
22 import java.beans.PropertyChangeEvent JavaDoc;
23 import java.beans.PropertyChangeListener JavaDoc;
24 import java.beans.PropertyChangeSupport JavaDoc;
25 import java.io.*;
26 import java.util.*;
27 import javax.swing.Icon JavaDoc;
28 import javax.swing.ImageIcon JavaDoc;
29 import javax.swing.JButton JavaDoc;
30 import javax.swing.SwingUtilities JavaDoc;
31 import org.netbeans.modules.j2ee.deployment.devmodules.api.Deployment;
32 import org.netbeans.modules.j2ee.deployment.devmodules.api.J2eeModule;
33 import org.netbeans.modules.web.project.jaxws.WebJAXWSMetadataFinder;
34 import org.netbeans.modules.web.project.jaxws.WebProjectJAXWSClientSupport;
35 import org.netbeans.modules.web.project.jaxws.WebProjectJAXWSSupport;
36 import org.netbeans.modules.websvc.api.jaxws.client.JAXWSClientSupport;
37 import org.netbeans.modules.websvc.api.jaxws.project.WSUtils;
38 import org.netbeans.modules.websvc.jaxws.api.JAXWSSupport;
39 import org.netbeans.modules.websvc.api.jaxws.project.config.JaxWsModel;
40 import org.netbeans.modules.websvc.api.jaxws.project.config.JaxWsModelProvider;
41 import org.netbeans.modules.websvc.api.jaxws.project.GeneratedFilesHelper;
42 import org.netbeans.modules.websvc.jaxws.spi.JAXWSSupportFactory;
43 import org.netbeans.modules.websvc.spi.client.WebServicesClientSupportFactory;
44 import org.netbeans.modules.websvc.spi.jaxws.client.JAXWSClientSupportFactory;
45 import org.openide.DialogDisplayer;
46 import org.openide.NotifyDescriptor;
47 import org.openide.util.NbBundle;
48 import org.openide.util.RequestProcessor;
49 import org.openide.util.WeakListeners;
50 import org.w3c.dom.Element JavaDoc;
51 import org.w3c.dom.Node JavaDoc;
52 import org.w3c.dom.NodeList JavaDoc;
53 import org.w3c.dom.Text JavaDoc;
54 import org.openide.filesystems.FileLock;
55 import org.openide.ErrorManager;
56 import org.openide.filesystems.FileChangeAdapter;
57 import org.openide.filesystems.FileChangeListener;
58 import org.openide.filesystems.FileEvent;
59 import org.openide.filesystems.FileRenameEvent;
60 import org.openide.filesystems.FileObject;
61 import org.openide.filesystems.FileStateInvalidException;
62 import org.openide.filesystems.FileUtil;
63 import org.openide.filesystems.FileAttributeEvent;
64 import org.openide.loaders.DataObject;
65 import org.openide.util.Lookup;
66 import org.openide.util.Mutex;
67 import org.openide.util.Utilities;
68 import org.openide.util.lookup.Lookups;
69 import org.netbeans.modules.web.api.webmodule.WebModule;
70 import org.netbeans.modules.web.spi.webmodule.WebModuleFactory;
71 import org.netbeans.api.java.classpath.ClassPath;
72 import org.netbeans.api.java.classpath.GlobalPathRegistry;
73 import org.netbeans.api.project.Project;
74 import org.netbeans.api.project.ProjectManager;
75 import org.netbeans.api.project.ant.AntArtifact;
76 import org.netbeans.modules.web.project.classpath.ClassPathProviderImpl;
77 import org.netbeans.modules.web.project.classpath.WebProjectClassPathExtender;
78 import org.netbeans.modules.web.project.queries.*;
79 import org.netbeans.modules.web.project.ui.WebLogicalViewProvider;
80 import org.netbeans.modules.web.project.ui.customizer.WebProjectProperties;
81 import org.netbeans.spi.project.AuxiliaryConfiguration;
82 import org.netbeans.api.project.ProjectInformation;
83 import org.netbeans.modules.j2ee.common.ui.BrokenServerSupport;
84 import org.netbeans.modules.j2ee.deployment.devmodules.api.J2eePlatform;
85 import org.netbeans.spi.project.SubprojectProvider;
86 import org.netbeans.spi.project.ant.AntArtifactProvider;
87 import org.netbeans.spi.project.support.LookupProviderSupport;
88 import org.netbeans.spi.project.support.ant.AntProjectEvent;
89 import org.netbeans.spi.project.support.ant.AntProjectHelper;
90 import org.netbeans.spi.project.support.ant.AntProjectListener;
91 import org.netbeans.spi.project.support.ant.ProjectXmlSavedHook;
92 import org.netbeans.spi.project.ui.PrivilegedTemplates;
93 import org.netbeans.spi.project.ui.RecommendedTemplates;
94 import org.netbeans.spi.project.ui.support.UILookupMergerSupport;
95 import org.netbeans.spi.project.support.ant.ReferenceHelper;
96 import org.netbeans.spi.project.support.ant.PropertyEvaluator;
97 import org.netbeans.spi.project.ui.ProjectOpenedHook;
98 import org.netbeans.modules.web.api.webmodule.WebProjectConstants;
99 import org.netbeans.modules.web.project.ui.customizer.CustomizerProviderImpl;
100 import org.netbeans.spi.java.project.support.ui.BrokenReferencesSupport;
101 import org.netbeans.spi.project.support.ant.EditableProperties;
102 import org.netbeans.modules.websvc.api.webservices.WebServicesSupport;
103 import org.netbeans.modules.websvc.api.client.WebServicesClientSupport;
104 import org.netbeans.modules.websvc.spi.webservices.WebServicesSupportFactory;
105
106 /**
107  * Represents one plain Web project.
108  * @author Jesse Glick, et al., Pavel Buzek
109  */

110 public final class WebProject implements Project, AntProjectListener, FileChangeListener, PropertyChangeListener JavaDoc {
111     private static final Icon JavaDoc WEB_PROJECT_ICON = new ImageIcon JavaDoc(Utilities.loadImage("org/netbeans/modules/web/project/ui/resources/webProjectIcon.gif")); // NOI18
112

113     private final AntProjectHelper helper;
114     private final PropertyEvaluator eval;
115     private final ReferenceHelper refHelper;
116     private final GeneratedFilesHelper genFilesHelper;
117     private final Lookup lookup;
118     private final ProjectWebModule webModule;
119     private FileObject libFolder = null;
120     private CopyOnSaveSupport css;
121     private WebModule apiWebModule;
122     private WebServicesSupport apiWebServicesSupport;
123     private JAXWSSupport apiJaxwsSupport;
124     private WebServicesClientSupport apiWebServicesClientSupport;
125     private JAXWSClientSupport apiJAXWSClientSupport;
126     private WebContainerImpl enterpriseResourceSupport;
127     private FileWatch webPagesFileWatch;
128     private PropertyChangeListener JavaDoc j2eePlatformListener;
129     private SourceRoots sourceRoots;
130     private SourceRoots testRoots;
131     private final UpdateHelper updateHelper;
132     private final AuxiliaryConfiguration aux;
133     private final WebProjectClassPathExtender classPathExtender;
134     private PropertyChangeListener JavaDoc evalListener;
135     private JaxWsModel jaxWsModel;
136     private JaxWsListener jaxWsListener;
137     private FileObject jaxWsFo;
138     private JaxWsModel.ServiceListener jaxWsServiceListener;
139
140     private class FileWatch implements AntProjectListener, FileChangeListener {
141
142         private String JavaDoc propertyName;
143
144         private FileObject fileObject = null;
145         private boolean watchRename = false;
146
147         public FileWatch(String JavaDoc property) {
148             this.propertyName = property;
149         }
150
151         public void init() {
152             helper.addAntProjectListener(this);
153             updateFileChangeListener();
154         }
155
156         public void reset() {
157             helper.removeAntProjectListener(this);
158             setFileObject(null);
159         }
160
161         public void updateFileChangeListener() {
162             File resolvedFile;
163             FileObject fo = null;
164             String JavaDoc propertyValue = helper.getStandardPropertyEvaluator().getProperty(propertyName);
165             if (propertyValue != null) {
166                 String JavaDoc resolvedPath = helper.resolvePath(propertyValue);
167                 resolvedFile = new File(resolvedPath).getAbsoluteFile();
168                 if (resolvedFile != null) {
169                     File f = resolvedFile;
170                     while (f != null && (fo = FileUtil.toFileObject(f)) == null) {
171                         f = f.getParentFile();
172                     }
173                     watchRename = f == resolvedFile;
174                 } else {
175                     watchRename = false;
176                 }
177             } else {
178                 resolvedFile = null;
179                 watchRename = false;
180             }
181             setFileObject(fo);
182         }
183
184         private void setFileObject(FileObject fo) {
185             if (!isEqual(fo, fileObject)) {
186                 if (fileObject != null) {
187                     fileObject.removeFileChangeListener(this);
188                 }
189                 fileObject = fo;
190                 if (fileObject != null) {
191                     fileObject.addFileChangeListener(this);
192                 }
193             }
194         }
195
196         private boolean isEqual(Object JavaDoc object1, Object JavaDoc object2) {
197             if (object1 == object2) {
198                 return true;
199             }
200             if(object1 == null) {
201                 return false;
202             }
203             return object1.equals(object2);
204         }
205
206         // AntProjectListener
207

208         public void configurationXmlChanged(AntProjectEvent ev) {
209             updateFileChangeListener();
210         }
211
212         public void propertiesChanged(AntProjectEvent ev) {
213             updateFileChangeListener();
214         }
215
216         // FileChangeListener
217

218         public void fileFolderCreated(FileEvent fe) {
219             updateFileChangeListener();
220         }
221
222         public void fileDataCreated(FileEvent fe) {
223             updateFileChangeListener();
224         }
225
226         public void fileChanged(FileEvent fe) {
227             updateFileChangeListener();
228         }
229
230         public void fileDeleted(FileEvent fe) {
231             updateFileChangeListener();
232         }
233
234         public void fileRenamed(FileRenameEvent fe) {
235             if(watchRename && fileObject.isValid()) {
236                 File f = new File(helper.getStandardPropertyEvaluator().getProperty(propertyName));
237                 if(f.getName().equals(fe.getName())) {
238                     EditableProperties properties = new EditableProperties(true);
239                     properties.setProperty(propertyName, new File(f.getParentFile(), fe.getFile().getName()).getPath());
240                     Utils.updateProperties(helper, AntProjectHelper.PROJECT_PROPERTIES_PATH, properties);
241                     getWebProjectProperties().store();
242                 }
243             }
244             updateFileChangeListener();
245         }
246
247         public void fileAttributeChanged(FileAttributeEvent fe) {
248         }
249     };
250     
251     WebProject(final AntProjectHelper helper) throws IOException {
252         this.helper = helper;
253         eval = createEvaluator();
254         aux = helper.createAuxiliaryConfiguration();
255         refHelper = new ReferenceHelper(helper, aux, eval);
256         genFilesHelper = new GeneratedFilesHelper(helper);
257         this.updateHelper = new UpdateHelper (this, this.helper, this.aux, UpdateHelper.createDefaultNotifier());
258         webModule = new ProjectWebModule (this, updateHelper);
259         apiWebModule = WebModuleFactory.createWebModule (webModule);
260         WebProjectWebServicesSupport webProjectWebServicesSupport = new WebProjectWebServicesSupport(this, helper, refHelper);
261         WebProjectJAXWSSupport jaxwsSupport = new WebProjectJAXWSSupport(this, helper);
262         WebProjectJAXWSClientSupport jaxWsClientSupport = new WebProjectJAXWSClientSupport(this);
263         WebProjectWebServicesClientSupport webProjectWebServicesClientSupport = new WebProjectWebServicesClientSupport(this, helper, refHelper);
264         apiWebServicesSupport = WebServicesSupportFactory.createWebServicesSupport (webProjectWebServicesSupport);
265         apiJaxwsSupport = JAXWSSupportFactory.createJAXWSSupport(jaxwsSupport);
266         apiWebServicesClientSupport = WebServicesClientSupportFactory.createWebServicesClientSupport (webProjectWebServicesClientSupport);
267         apiJAXWSClientSupport = JAXWSClientSupportFactory.createJAXWSClientSupport(jaxWsClientSupport);
268         enterpriseResourceSupport = new WebContainerImpl(this, refHelper, helper);
269         classPathExtender = new WebProjectClassPathExtender(this, updateHelper, evaluator(), refHelper);
270         lookup = createLookup(aux);
271         helper.addAntProjectListener(this);
272         css = new CopyOnSaveSupport();
273         webPagesFileWatch = new FileWatch(WebProjectProperties.WEB_DOCBASE_DIR);
274     }
275
276     public FileObject getProjectDirectory() {
277         return helper.getProjectDirectory();
278     }
279
280     public UpdateHelper getUpdateHelper() {
281         return updateHelper;
282     }
283     
284     public String JavaDoc toString() {
285         return "WebProject[" + getProjectDirectory() + "]"; // NOI18N
286
}
287     
288     private PropertyEvaluator createEvaluator() {
289         // XXX might need to use a custom evaluator to handle active platform substitutions... TBD
290
// It is currently safe to not use the UpdateHelper for PropertyEvaluator; UH.getProperties() delegates to APH
291
PropertyEvaluator e = helper.getStandardPropertyEvaluator();
292         evalListener = WeakListeners.propertyChange(this, e);
293         e.addPropertyChangeListener(evalListener);
294         return e;
295     }
296     
297     PropertyEvaluator evaluator() {
298         return eval;
299     }
300     
301     public ReferenceHelper getReferenceHelper () {
302         return this.refHelper;
303     }
304
305     public Lookup getLookup() {
306         return lookup;
307     }
308
309     public AntProjectHelper getAntProjectHelper() {
310         return helper;
311     }
312
313     private Lookup createLookup(AuxiliaryConfiguration aux) {
314         SubprojectProvider spp = refHelper.createSubprojectProvider();
315         Lookup base = Lookups.fixed(new Object JavaDoc[] {
316             new Info(),
317             aux,
318             helper.createCacheDirectoryProvider(),
319             spp,
320             new ProjectWebModuleProvider (),
321             new ProjectWebServicesSupportProvider(),
322             webModule, //implements J2eeModuleProvider
323
enterpriseResourceSupport,
324             new WebActionProvider( this, this.updateHelper ),
325             new WebLogicalViewProvider(this, this.updateHelper, evaluator (), refHelper),
326             new CustomizerProviderImpl(this, this.updateHelper, evaluator(), refHelper),
327             new ClassPathProviderImpl(this.helper, evaluator(), getSourceRoots(),getTestSourceRoots()),
328             new CompiledSourceForBinaryQuery(this.helper, evaluator(),getSourceRoots(),getTestSourceRoots()),
329             new JavadocForBinaryQueryImpl(this.helper, evaluator()),
330             new AntArtifactProviderImpl(),
331             new ProjectXmlSavedHookImpl(),
332             new ProjectOpenedHookImpl(),
333             new UnitTestForSourceQueryImpl(getSourceRoots(),getTestSourceRoots()),
334             new SourceLevelQueryImpl(evaluator()),
335             new WebSources (this.helper, evaluator(), getSourceRoots(), getTestSourceRoots()),
336             new WebSharabilityQuery (this.helper, evaluator(), getSourceRoots(), getTestSourceRoots()), //Does not use APH to get/put properties/cfgdata
337
new RecommendedTemplatesImpl(),
338             new WebFileBuiltQuery (this.helper, evaluator(),getSourceRoots(),getTestSourceRoots()),
339             classPathExtender,
340             new WebProjectOperations(this),
341             new WebPersistenceProvider(this, evaluator()),
342             new WebJAXWSMetadataFinder(this),
343             getJaxWsModel(),
344             new WebPersistenceProviderSupplier(this),
345             new WebEMGenStrategyResolver(),
346             new WebJPADataSourceSupport(this),
347             new WebServerStatusProvider(this),
348             new WebJPAModuleInfo(this),
349             UILookupMergerSupport.createPrivilegedTemplatesMerger(),
350             UILookupMergerSupport.createRecommendedTemplatesMerger(),
351             LookupProviderSupport.createSourcesMerger(),
352             this, // never cast an externally obtained Project to J2SEProject - use lookup instead
353
});
354         return LookupProviderSupport.createCompositeLookup(base, "Projects/org-netbeans-modules-web-project/Lookup"); //NOI18N
355
}
356
357     public void configurationXmlChanged(AntProjectEvent ev) {
358         if (ev.getPath().equals(AntProjectHelper.PROJECT_XML_PATH)) {
359             // Could be various kinds of changes, but name & displayName might have changed.
360
Info info = (Info)getLookup().lookup(ProjectInformation.class);
361             info.firePropertyChange(ProjectInformation.PROP_NAME);
362             info.firePropertyChange(ProjectInformation.PROP_DISPLAY_NAME);
363         }
364     }
365
366     public void propertiesChanged(AntProjectEvent ev) {
367         // currently ignored (probably better to listen to evaluator() if you need to)
368
}
369     
370     String JavaDoc getBuildXmlName () {
371         String JavaDoc storedName = helper.getStandardPropertyEvaluator ().getProperty (WebProjectProperties.BUILD_FILE);
372         return storedName == null ? GeneratedFilesHelper.BUILD_XML_PATH : storedName;
373     }
374     
375     // Package private methods -------------------------------------------------
376

377     /**
378      * Returns the source roots of this project
379      * @return project's source roots
380      */

381     public synchronized SourceRoots getSourceRoots() {
382         if (this.sourceRoots == null) { //Local caching, no project metadata access
383
this.sourceRoots = new SourceRoots(this.updateHelper, evaluator(), getReferenceHelper(), "source-roots", false, "src.{0}{1}.dir"); //NOI18N
384
}
385         return this.sourceRoots;
386     }
387     
388     public synchronized SourceRoots getTestSourceRoots() {
389         if (this.testRoots == null) { //Local caching, no project metadata access
390
this.testRoots = new SourceRoots(this.updateHelper, evaluator(), getReferenceHelper(), "test-roots", true, "test.{0}{1}.dir"); //NOI18N
391
}
392         return this.testRoots;
393     }
394
395     File getTestClassesDirectory() {
396         String JavaDoc testClassesDir = evaluator().getProperty(WebProjectProperties.BUILD_TEST_CLASSES_DIR);
397         if (testClassesDir == null) {
398             return null;
399         }
400         return helper.resolveFile(testClassesDir);
401     }
402     
403     public ProjectWebModule getWebModule () {
404         return webModule;
405     }
406
407     public WebModule getAPIWebModule () {
408         return apiWebModule;
409     }
410     
411     WebServicesSupport getAPIWebServicesSupport () {
412             return apiWebServicesSupport;
413     }
414     
415     JAXWSSupport getAPIJAXWSSupport () {
416             return apiJaxwsSupport;
417     }
418     
419     WebServicesClientSupport getAPIWebServicesClientSupport () {
420             return apiWebServicesClientSupport;
421     }
422     
423     JAXWSClientSupport getAPIJAXWSClientSupport () {
424             return apiJAXWSClientSupport;
425     }
426     
427     public void fileAttributeChanged (org.openide.filesystems.FileAttributeEvent fe) {
428     }
429     
430     public void fileChanged (org.openide.filesystems.FileEvent fe) {
431     }
432     
433     public void fileDataCreated (org.openide.filesystems.FileEvent fe) {
434         FileObject fo = fe.getFile ();
435         checkLibraryFolder (fo);
436     }
437     
438     public void fileDeleted (org.openide.filesystems.FileEvent fe) {
439     }
440     
441     public void fileFolderCreated (org.openide.filesystems.FileEvent fe) {
442     }
443     
444     public void fileRenamed (org.openide.filesystems.FileRenameEvent fe) {
445         FileObject fo = fe.getFile ();
446         checkLibraryFolder (fo);
447     }
448     
449     public WebProjectProperties getWebProjectProperties() {
450         return new WebProjectProperties (this, updateHelper, eval, refHelper);
451     }
452
453     private void checkLibraryFolder (FileObject fo) {
454         if (!FileUtil.isArchiveFile(fo))
455             return;
456         
457         if (fo.getParent ().equals (libFolder)) {
458             try {
459                 classPathExtender.addArchiveFile(fo);
460             }
461             catch (IOException e) {
462                 ErrorManager.getDefault().notify(e);
463             }
464         }
465     }
466
467     /** Return configured project name. */
468     public String JavaDoc getName() {
469         return (String JavaDoc) ProjectManager.mutex().readAccess(new Mutex.Action() {
470             public Object JavaDoc run() {
471                 Element JavaDoc data = helper.getPrimaryConfigurationData(true);
472                 // XXX replace by XMLUtil when that has findElement, findText, etc.
473
NodeList JavaDoc nl = data.getElementsByTagNameNS(WebProjectType.PROJECT_CONFIGURATION_NAMESPACE, "name");
474                 if (nl.getLength() == 1) {
475                     nl = nl.item(0).getChildNodes();
476                     if (nl.getLength() == 1 && nl.item(0).getNodeType() == Node.TEXT_NODE) {
477                         return ((Text JavaDoc) nl.item(0)).getNodeValue();
478                     }
479                 }
480                 return "???"; // NOI18N
481
}
482         });
483     }
484     
485     /** Store configured project name. */
486     public void setName(final String JavaDoc name) {
487         ProjectManager.mutex().writeAccess(new Mutex.Action() {
488             public Object JavaDoc run() {
489                 Element JavaDoc data = helper.getPrimaryConfigurationData(true);
490                 // XXX replace by XMLUtil when that has findElement, findText, etc.
491
NodeList JavaDoc nl = data.getElementsByTagNameNS(WebProjectType.PROJECT_CONFIGURATION_NAMESPACE, "name");
492                 Element JavaDoc nameEl;
493                 if (nl.getLength() == 1) {
494                     nameEl = (Element JavaDoc) nl.item(0);
495                     NodeList JavaDoc deadKids = nameEl.getChildNodes();
496                     while (deadKids.getLength() > 0) {
497                         nameEl.removeChild(deadKids.item(0));
498                     }
499                 } else {
500                     nameEl = data.getOwnerDocument().createElementNS(WebProjectType.PROJECT_CONFIGURATION_NAMESPACE, "name");
501                     data.insertBefore(nameEl, /* OK if null */data.getChildNodes().item(0));
502                 }
503                 nameEl.appendChild(data.getOwnerDocument().createTextNode(name));
504                 helper.putPrimaryConfigurationData(data, true);
505                 return null;
506             }
507         });
508     }
509
510     public void registerJ2eePlatformListener(final J2eePlatform platform) {
511         // listen to classpath changes
512
j2eePlatformListener = new PropertyChangeListener JavaDoc() {
513             public void propertyChange(PropertyChangeEvent JavaDoc evt) {
514                 if (evt.getPropertyName().equals(J2eePlatform.PROP_CLASSPATH)) {
515                     ProjectManager.mutex().writeAccess(new Mutex.Action() {
516                         public Object JavaDoc run() {
517                             EditableProperties ep = helper.getProperties(AntProjectHelper.PRIVATE_PROPERTIES_PATH);
518                             String JavaDoc classpath = Utils.toClasspathString(platform.getClasspathEntries());
519                             ep.setProperty(WebProjectProperties.J2EE_PLATFORM_CLASSPATH, classpath);
520                             helper.putProperties(AntProjectHelper.PRIVATE_PROPERTIES_PATH, ep);
521                             try {
522                                 ProjectManager.getDefault().saveProject(WebProject.this);
523                             } catch (IOException e) {
524                                 ErrorManager.getDefault().notify(e);
525                             }
526                             return null;
527                         }
528                     });
529                 }
530             }
531         };
532         platform.addPropertyChangeListener(j2eePlatformListener);
533     }
534     
535     public void unregisterJ2eePlatformListener(J2eePlatform platform) {
536         if (j2eePlatformListener != null) {
537             platform.removePropertyChangeListener(j2eePlatformListener);
538         }
539     }
540     // Private innerclasses ----------------------------------------------------
541

542     private final class Info implements ProjectInformation {
543         
544         private final PropertyChangeSupport JavaDoc pcs = new PropertyChangeSupport JavaDoc(this);
545         
546         Info() {}
547         
548         void firePropertyChange(String JavaDoc prop) {
549             pcs.firePropertyChange(prop, null, null);
550         }
551         
552         public String JavaDoc getName() {
553             return WebProject.this.getName();
554         }
555         
556         public String JavaDoc getDisplayName() {
557             return (String JavaDoc) ProjectManager.mutex().readAccess(new Mutex.Action() {
558                 public Object JavaDoc run() {
559                     Element JavaDoc data = updateHelper.getPrimaryConfigurationData(true);
560                     // XXX replace by XMLUtil when that has findElement, findText, etc.
561
NodeList JavaDoc nl = data.getElementsByTagNameNS(WebProjectType.PROJECT_CONFIGURATION_NAMESPACE, "name"); // NOI18N
562
if (nl.getLength() == 1) {
563                         nl = nl.item(0).getChildNodes();
564                         if (nl.getLength() == 1 && nl.item(0).getNodeType() == Node.TEXT_NODE) {
565                             return ((Text JavaDoc) nl.item(0)).getNodeValue();
566                         }
567                     }
568                     return "???"; // NOI18N
569
}
570             });
571         }
572         
573         public Icon JavaDoc getIcon() {
574             return WEB_PROJECT_ICON;
575         }
576         
577         public Project getProject() {
578             return WebProject.this;
579         }
580         
581         public void addPropertyChangeListener(PropertyChangeListener JavaDoc listener) {
582             pcs.addPropertyChangeListener(listener);
583         }
584         
585         public void removePropertyChangeListener(PropertyChangeListener JavaDoc listener) {
586             pcs.removePropertyChangeListener(listener);
587         }
588         
589     }
590     
591     private final class ProjectXmlSavedHookImpl extends ProjectXmlSavedHook {
592         
593         ProjectXmlSavedHookImpl() {}
594         
595         protected void projectXmlSaved() throws IOException {
596             int flags = genFilesHelper.getBuildScriptState(
597                 GeneratedFilesHelper.BUILD_IMPL_XML_PATH,
598                 WebProject.class.getResource("resources/build-impl.xsl"),jaxWsFo);
599             if ((flags & GeneratedFilesHelper.FLAG_MODIFIED) != 0) {
600                 RequestProcessor.getDefault().post(new Runnable JavaDoc () {
601                     public void run () {
602                         JButton JavaDoc updateOption = new JButton JavaDoc (NbBundle.getMessage(WebProject.class, "CTL_Regenerate"));
603                         if (DialogDisplayer.getDefault().notify(
604                             new NotifyDescriptor (NbBundle.getMessage(WebProject.class,"TXT_BuildImplRegenerate"),
605                                 NbBundle.getMessage(WebProject.class,"TXT_BuildImplRegenerateTitle"),
606                                 NotifyDescriptor.DEFAULT_OPTION,
607                                 NotifyDescriptor.WARNING_MESSAGE,
608                                 new Object JavaDoc[] {
609                                     updateOption,
610                                     NotifyDescriptor.CANCEL_OPTION
611                                 },
612                                 updateOption)) == updateOption) {
613                             try {
614                                 genFilesHelper.generateBuildScriptFromStylesheet(
615                                     GeneratedFilesHelper.BUILD_IMPL_XML_PATH,
616                                     WebProject.class.getResource("resources/build-impl.xsl"),jaxWsFo);
617                             } catch (IOException e) {
618                                 ErrorManager.getDefault().notify(e);
619                             } catch (IllegalStateException JavaDoc e) {
620                                 ErrorManager.getDefault().notify(e);
621                             }
622                         }
623                     }
624                 });
625             } else {
626                 genFilesHelper.refreshBuildScript(
627                     GeneratedFilesHelper.BUILD_IMPL_XML_PATH,
628                     WebProject.class.getResource("resources/build-impl.xsl"),
629                     jaxWsFo, false);
630             }
631             genFilesHelper.refreshBuildScript(
632                 getBuildXmlName (),
633                 WebProject.class.getResource("resources/build.xsl"),
634                 jaxWsFo, false);
635         }
636         
637     }
638     
639     final class ProjectOpenedHookImpl extends ProjectOpenedHook {
640         
641         ProjectOpenedHookImpl() {}
642         
643         protected void projectOpened() {
644             // Make it easier to run headless builds on the same machine at least.
645
ProjectManager.mutex().writeAccess(new Mutex.Action() {
646                 public Object JavaDoc run() {
647                     EditableProperties ep = updateHelper.getProperties(AntProjectHelper.PRIVATE_PROPERTIES_PATH);
648                     File buildProperties = new File(System.getProperty("netbeans.user"), "build.properties"); // NOI18N
649
ep.setProperty("user.properties.file", buildProperties.getAbsolutePath()); //NOI18N
650

651                     // set jaxws.endorsed.dir property (for endorsed mechanism to be used with wsimport, wsgen)
652
WSUtils.setJaxWsEndorsedDirProperty(ep);
653                     
654                     EditableProperties props = updateHelper.getProperties (AntProjectHelper.PROJECT_PROPERTIES_PATH); //Reread the properties, PathParser changes them
655
if (props.getProperty(WebProjectProperties.WAR_PACKAGE) == null)
656                         props.setProperty(WebProjectProperties.WAR_PACKAGE, "true"); //NOI18N
657
//update lib references in private properties
658
ArrayList l = new ArrayList ();
659                     l.addAll(classPathExtender.getClassPathSupport().itemsList(props.getProperty(WebProjectProperties.JAVAC_CLASSPATH), WebProjectProperties.TAG_WEB_MODULE_LIBRARIES));
660                     l.addAll(classPathExtender.getClassPathSupport().itemsList(props.getProperty(WebProjectProperties.WAR_CONTENT_ADDITIONAL), WebProjectProperties.TAG_WEB_MODULE__ADDITIONAL_LIBRARIES));
661                     WebProjectProperties.storeLibrariesLocations(l.iterator(), ep);
662                     updateHelper.putProperties(AntProjectHelper.PRIVATE_PROPERTIES_PATH, ep);
663                     updateHelper.putProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH, props);
664                     
665                     try {
666                         ProjectManager.getDefault().saveProject(WebProject.this);
667                     } catch (IOException e) {
668                         ErrorManager.getDefault().notify(e);
669                     }
670                     return null;
671                 }
672             });
673             try {
674                 //DDDataObject initialization to be ready to listen on changes (#45771)
675
try {
676                     FileObject ddFO = webModule.getDeploymentDescriptor();
677                     if (ddFO != null) {
678                         DataObject dobj = DataObject.find(ddFO);
679                     }
680                 } catch (org.openide.loaders.DataObjectNotFoundException ex) {
681                     //PENDING
682
}
683                 
684                 // Register copy on save support
685
css.initialize();
686                 
687                 
688                 // Check up on build scripts.
689
if (updateHelper.isCurrent()) {
690                     int flags = genFilesHelper.getBuildScriptState(
691                         GeneratedFilesHelper.BUILD_IMPL_XML_PATH,
692                         WebProject.class.getResource("resources/build-impl.xsl"),jaxWsFo);
693                     if ((flags & GeneratedFilesHelper.FLAG_MODIFIED) != 0
694                         && (flags & (GeneratedFilesHelper.FLAG_OLD_PROJECT_XML | GeneratedFilesHelper.FLAG_OLD_JAX_WS)) != 0) {
695                         JButton JavaDoc updateOption = new JButton JavaDoc (NbBundle.getMessage(WebProject.class, "CTL_Regenerate"));
696                         if (DialogDisplayer.getDefault().notify(
697                             new NotifyDescriptor (NbBundle.getMessage(WebProject.class,"TXT_BuildImplRegenerate"),
698                                 NbBundle.getMessage(WebProject.class,"TXT_BuildImplRegenerateTitle"),
699                                 NotifyDescriptor.DEFAULT_OPTION,
700                                 NotifyDescriptor.WARNING_MESSAGE,
701                                 new Object JavaDoc[] {
702                                     updateOption,
703                                     NotifyDescriptor.CANCEL_OPTION
704                                 },
705                                 updateOption)) == updateOption) {
706                             genFilesHelper.generateBuildScriptFromStylesheet(
707                                 GeneratedFilesHelper.BUILD_IMPL_XML_PATH,
708                                 WebProject.class.getResource("resources/build-impl.xsl"), jaxWsFo);
709                         }
710                     } else {
711                         genFilesHelper.refreshBuildScript(
712                             GeneratedFilesHelper.BUILD_IMPL_XML_PATH,
713                             WebProject.class.getResource("resources/build-impl.xsl"),
714                             jaxWsFo, true);
715                     }
716                     genFilesHelper.refreshBuildScript(
717                         getBuildXmlName(),
718                         WebProject.class.getResource("resources/build.xsl"),
719                         jaxWsFo, true);
720                     
721                     WebProjectProperties wpp = getWebProjectProperties();
722                     String JavaDoc servInstID = (String JavaDoc) wpp.get(WebProjectProperties.J2EE_SERVER_INSTANCE);
723                     J2eePlatform platform = Deployment.getDefault().getJ2eePlatform(servInstID);
724                     if (platform != null) {
725                         // updates j2ee.platform.cp & wscompile.cp & reg. j2ee platform listener
726
WebProjectProperties.setServerInstance(WebProject.this, WebProject.this.updateHelper, servInstID);
727                     } else {
728                         // if there is some server instance of the type which was used
729
// previously do not ask and use it
730
String JavaDoc serverType = (String JavaDoc) wpp.get(WebProjectProperties.J2EE_SERVER_TYPE);
731                         if (serverType != null) {
732                             String JavaDoc[] servInstIDs = Deployment.getDefault().getInstancesOfServer(serverType);
733                             if (servInstIDs.length > 0) {
734                                 WebProjectProperties.setServerInstance(WebProject.this, WebProject.this.updateHelper, servInstIDs[0]);
735                                 platform = Deployment.getDefault().getJ2eePlatform(servInstIDs[0]);
736                             }
737                         }
738                         if (platform == null) {
739                             BrokenServerSupport.showAlert();
740                         }
741                     }
742                 }
743                 
744             } catch (IOException e) {
745                 ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
746             }
747             
748             // register project's classpaths to GlobalPathRegistry
749
ClassPathProviderImpl cpProvider = (ClassPathProviderImpl)lookup.lookup(ClassPathProviderImpl.class);
750             GlobalPathRegistry.getDefault().register(ClassPath.BOOT, cpProvider.getProjectClassPaths(ClassPath.BOOT));
751             GlobalPathRegistry.getDefault().register(ClassPath.SOURCE, cpProvider.getProjectClassPaths(ClassPath.SOURCE));
752             GlobalPathRegistry.getDefault().register(ClassPath.COMPILE, cpProvider.getProjectClassPaths(ClassPath.COMPILE));
753             
754             // initialize the server configuration
755
// it MUST BE called AFTER classpaths are registered to GlobalPathRegistry!
756
// DDProvider (used here) needs classpath set correctly when resolving Java Extents for annotations
757
webModule.getConfigSupport().ensureConfigurationReady();
758             
759             //check the config context path
760
String JavaDoc ctxRoot = webModule.getContextPath ();
761             if (ctxRoot == null) {
762                 String JavaDoc sysName = getProjectDirectory ().getName (); //NOI18N
763
sysName = Utils.createDefaultContext(sysName); //NOI18N
764
webModule.setContextPath (sysName);
765             }
766
767             WebLogicalViewProvider logicalViewProvider = (WebLogicalViewProvider) WebProject.this.getLookup().lookup (WebLogicalViewProvider.class);
768             if (logicalViewProvider != null && logicalViewProvider.hasBrokenLinks()) {
769                 BrokenReferencesSupport.showAlert();
770             }
771             webPagesFileWatch.init();
772             
773             if (getWebProjectProperties().get("jsf.pagebean.package") != null) {
774                 SwingUtilities.invokeLater(new Runnable JavaDoc() {
775                     public void run() {
776                         DialogDisplayer.getDefault().notify(
777                                 new NotifyDescriptor.Message(NbBundle.getMessage(WebProject.class,
778                                 "MSG_Creator_Project"), NotifyDescriptor.WARNING_MESSAGE));
779                     }
780                 });
781             }
782         }
783
784         protected void projectClosed() {
785             webPagesFileWatch.reset();
786
787             // listen to j2ee platform classpath changes
788
WebProjectProperties wpp = getWebProjectProperties();
789             String JavaDoc servInstID = (String JavaDoc)wpp.get(WebProjectProperties.J2EE_SERVER_INSTANCE);
790             J2eePlatform platform = Deployment.getDefault().getJ2eePlatform(servInstID);
791             if (platform != null) {
792                 unregisterJ2eePlatformListener(platform);
793             }
794             
795             // unregister the property change listener on the prop evaluator
796
if (evalListener != null) {
797                 evaluator().removePropertyChangeListener(evalListener);
798             }
799             
800             // remove file change listener from jax-ws.xml
801
if (jaxWsFo!=null) jaxWsFo.removeFileChangeListener(jaxWsListener);
802             
803             // remove ServiceListener from jaxWsModel
804
if (jaxWsModel!=null) jaxWsModel.removeServiceListener(jaxWsServiceListener);
805
806             // Probably unnecessary, but just in case:
807
try {
808                 ProjectManager.getDefault().saveProject(WebProject.this);
809             } catch (IOException e) {
810                 ErrorManager.getDefault().notify(e);
811             }
812             
813             // Unregister copy on save support
814
try {
815                 css.cleanup();
816             }
817             catch (FileStateInvalidException e) {
818                 ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
819             }
820             
821             // unregister project's classpaths to GlobalPathRegistry
822
ClassPathProviderImpl cpProvider = (ClassPathProviderImpl)lookup.lookup(ClassPathProviderImpl.class);
823             GlobalPathRegistry.getDefault().unregister(ClassPath.BOOT, cpProvider.getProjectClassPaths(ClassPath.BOOT));
824             GlobalPathRegistry.getDefault().unregister(ClassPath.SOURCE, cpProvider.getProjectClassPaths(ClassPath.SOURCE));
825             GlobalPathRegistry.getDefault().unregister(ClassPath.COMPILE, cpProvider.getProjectClassPaths(ClassPath.COMPILE));
826         }
827         
828     }
829     
830     /**
831      * Exports the main JAR as an official build product for use from other scripts.
832      * The type of the artifact will be {@link AntArtifact#TYPE_JAR}.
833      */

834     private final class AntArtifactProviderImpl implements AntArtifactProvider {
835
836         public AntArtifact[] getBuildArtifacts() {
837             return new AntArtifact[] {
838                 helper.createSimpleAntArtifact(WebProjectConstants.ARTIFACT_TYPE_WAR, "dist.war", evaluator(), "dist", "clean"), // NOI18N
839
helper.createSimpleAntArtifact(WebProjectConstants.ARTIFACT_TYPE_WAR_EAR_ARCHIVE, "dist.ear.war", evaluator(), "dist-ear", "clean-ear") // NOI18N
840
};
841         }
842
843     }
844     
845     // List of primarily supported templates
846

847     private static final String JavaDoc[] TYPES = new String JavaDoc[] {
848         "java-classes", // NOI18N
849
"java-main-class", // NOI18N
850
"java-beans", // NOI18N
851
"persistence", // NOI18N
852
"oasis-XML-catalogs", // NOI18N
853
"XML", // NOI18N
854
"ant-script", // NOI18N
855
"ant-task", // NOI18N
856
"servlet-types", // NOI18N
857
"web-types", // NOI18N
858
"web-types-server", // NOI18N
859
"web-services", // NOI18N
860
"web-service-clients", // NOI18N
861
"wsdl", // NOI18N
862
"j2ee-types", // NOI18N
863
"junit", // NOI18N
864
"simple-files" // NOI18N
865
};
866
867     private static final String JavaDoc[] TYPES_ARCHIVE = new String JavaDoc[] {
868         "deployment-descriptor", // NOI18N
869
"XML", // NOI18N
870
};
871     
872     private static final String JavaDoc[] PRIVILEGED_NAMES = new String JavaDoc[] {
873         "Templates/JSP_Servlet/JSP.jsp", // NOI18N
874
"Templates/JSP_Servlet/Html.html", // NOI18N
875
"Templates/JSP_Servlet/Servlet.java", // NOI18N
876
"Templates/Classes/Class.java", // NOI18N
877
"Templates/Classes/Package", // NOI18N
878
"Templates/WebServices/WebService.java", // NOI18N
879
"Templates/WebServices/WebServiceClient", // NOI18N
880
"Templates/Other/Folder", // NOI18N
881
};
882     
883     private static final String JavaDoc[] PRIVILEGED_NAMES_EE5 = new String JavaDoc[] {
884         "Templates/JSP_Servlet/JSP.jsp", // NOI18N
885
"Templates/JSP_Servlet/Html.html", // NOI18N
886
"Templates/JSP_Servlet/Servlet.java", // NOI18N
887
"Templates/Classes/Class.java", // NOI18N
888
"Templates/Classes/Package", // NOI18N
889
"Templates/Persistence/Entity.java", // NOI18N
890
"Templates/Persistence/RelatedCMP", // NOI18N
891
"Templates/Persistence/JsfFromDB", // NOI18N
892
"Templates/WebServices/WebService.java", // NOI18N
893
"Templates/WebServices/WebServiceFromWSDL.java", // NOI18N
894
"Templates/WebServices/WebServiceClient", // NOI18N
895
"Templates/Other/Folder", // NOI18N
896
};
897
898     private static final String JavaDoc[] PRIVILEGED_NAMES_ARCHIVE = new String JavaDoc[] {
899         "Templates/JSP_Servlet/webXml", // NOI18N ---
900
};
901     
902     private final class RecommendedTemplatesImpl implements RecommendedTemplates, PrivilegedTemplates {
903         RecommendedTemplatesImpl () {
904         }
905         
906         private boolean isEE5 = false;
907         private boolean checked = false;
908         private boolean isArchive = false;
909
910         public String JavaDoc[] getRecommendedTypes() {
911             String JavaDoc[] retVal = null;
912             checkEnvironment();
913             if (isArchive) {
914                 retVal = TYPES_ARCHIVE;
915             } else {
916                 retVal = TYPES;
917             }
918            
919             return retVal;
920         }
921         
922         public String JavaDoc[] getPrivilegedTemplates() {
923             String JavaDoc[] retVal = null;
924             checkEnvironment();
925             if (isArchive) {
926                 retVal = PRIVILEGED_NAMES_ARCHIVE;
927             } else if (isEE5) {
928                 retVal = PRIVILEGED_NAMES_EE5;
929             } else {
930                 retVal = PRIVILEGED_NAMES;
931             }
932             return retVal;
933         }
934         
935         private void checkEnvironment() {
936             if (!checked) {
937                 final Object JavaDoc srcType = helper.getStandardPropertyEvaluator().
938                         getProperty(WebProjectProperties.JAVA_SOURCE_BASED);
939                 if ("false".equals(srcType)) {
940                     isArchive = true;
941                 }
942                 isEE5 = J2eeModule.JAVA_EE_5.equals(getAPIWebModule().getJ2eePlatformVersion());
943                 checked = true;
944             }
945         }
946         
947     }
948
949     public class CopyOnSaveSupport extends FileChangeAdapter implements PropertyChangeListener JavaDoc {
950         private FileObject docBase = null;
951
952         /** Creates a new instance of CopyOnSaveSupport */
953         public CopyOnSaveSupport() {
954         }
955
956         public void initialize() throws FileStateInvalidException {
957             docBase = getWebModule().getDocumentBase();
958             if (docBase != null) {
959                 docBase.getFileSystem().addFileChangeListener(this);
960             }
961             ProjectInformation info = (ProjectInformation) getLookup().lookup(ProjectInformation.class);
962             info.addPropertyChangeListener (this);
963         }
964
965         public void cleanup() throws FileStateInvalidException {
966             if (docBase != null) {
967                 docBase.getFileSystem().removeFileChangeListener(this);
968             }
969         }
970
971         public void propertyChange(PropertyChangeEvent JavaDoc evt) {
972             if (evt.getPropertyName().equals(WebProjectProperties.WEB_DOCBASE_DIR)) {
973                 try {
974                     cleanup();
975                     initialize();
976                 } catch (org.openide.filesystems.FileStateInvalidException e) {
977                     ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
978                 }
979             }
980         }
981     
982         /** Fired when a file is changed.
983         * @param fe the event describing context where action has taken place
984         */

985         public void fileChanged (FileEvent fe) {
986             try {
987                 handleCopyFileToDestDir(fe.getFile());
988             }
989             catch (IOException e) {
990                 ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
991             }
992         }
993
994         public void fileDataCreated (FileEvent fe) {
995             try {
996                 handleCopyFileToDestDir(fe.getFile());
997             }
998             catch (IOException e) {
999                 ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
1000            }
1001        }
1002        
1003        public void fileRenamed(FileRenameEvent fe) {
1004            try {
1005                FileObject fo = fe.getFile();
1006                FileObject docBase = getWebModule().getDocumentBase();
1007                if (docBase != null && FileUtil.isParentOf(docBase, fo)) {
1008                    // inside docbase
1009
handleCopyFileToDestDir(fo);
1010                    FileObject parent = fo.getParent();
1011                    String JavaDoc path;
1012                    if (FileUtil.isParentOf(docBase, parent)) {
1013                        path = FileUtil.getRelativePath(docBase, fo.getParent()) +
1014                            "/" + fe.getName() + "." + fe.getExt();
1015                    }
1016                    else {
1017                        path = fe.getName() + "." + fe.getExt();
1018                    }
1019                    if (!isSynchronizationAppropriate(path))
1020                        return;
1021                    handleDeleteFileInDestDir(path);
1022                }
1023            }
1024            catch (IOException e) {
1025                ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
1026            }
1027        }
1028        
1029        public void fileDeleted(FileEvent fe) {
1030            try {
1031                FileObject fo = fe.getFile();
1032                FileObject docBase = getWebModule().getDocumentBase();
1033                if (docBase != null && FileUtil.isParentOf(docBase, fo)) {
1034                    // inside docbase
1035
String JavaDoc path = FileUtil.getRelativePath(docBase, fo);
1036                    if (!isSynchronizationAppropriate(path))
1037                        return;
1038                    handleDeleteFileInDestDir(path);
1039                }
1040            }
1041            catch (IOException e) {
1042                ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
1043            }
1044        }
1045        
1046        private boolean isSynchronizationAppropriate(String JavaDoc filePath) {
1047            if (filePath.startsWith("WEB-INF/classes")) {
1048                return false;
1049            }
1050            if (filePath.startsWith("WEB-INF/src")) {
1051                return false;
1052            }
1053            if (filePath.startsWith("WEB-INF/lib")) {
1054                return false;
1055            }
1056            return true;
1057        }
1058        
1059        private void handleDeleteFileInDestDir(String JavaDoc resourcePath) throws IOException {
1060            FileObject webBuildBase = getWebModule().getContentDirectory();
1061            if (webBuildBase != null) {
1062                // project was built
1063
FileObject toDelete = webBuildBase.getFileObject(resourcePath);
1064                if (toDelete != null) {
1065                    toDelete.delete();
1066                }
1067            }
1068        }
1069        
1070        /** Copies a content file to an appropriate destination directory,
1071         * if applicable and relevant.
1072         */

1073        private void handleCopyFileToDestDir(FileObject fo) throws IOException {
1074            if (!fo.isVirtual()) {
1075                FileObject docBase = getWebModule().getDocumentBase();
1076                if (docBase != null && FileUtil.isParentOf(docBase, fo)) {
1077                    // inside docbase
1078
String JavaDoc path = FileUtil.getRelativePath(docBase, fo);
1079                    if (!isSynchronizationAppropriate(path))
1080                        return;
1081                    FileObject webBuildBase = getWebModule().getContentDirectory();
1082                    if (webBuildBase != null) {
1083                        // project was built
1084
if (FileUtil.isParentOf(docBase, webBuildBase) || FileUtil.isParentOf(webBuildBase, docBase)) {
1085                            //cannot copy into self
1086
return;
1087                        }
1088                        FileObject destFile = ensureDestinationFileExists(webBuildBase, path, fo.isFolder());
1089                        if (!fo.isFolder()) {
1090                            InputStream is = null;
1091                            OutputStream os = null;
1092                            FileLock fl = null;
1093                            try {
1094                                is = fo.getInputStream();
1095                                fl = destFile.lock();
1096                                os = destFile.getOutputStream(fl);
1097                                FileUtil.copy(is, os);
1098                            }
1099                            finally {
1100                                if (is != null) {
1101                                    is.close();
1102                                }
1103                                if (os != null) {
1104                                    os.close();
1105                                }
1106                                if (fl != null) {
1107                                    fl.releaseLock();
1108                                }
1109                            }
1110                            //System.out.println("copied + " + FileUtil.copy(fo.getInputStream(), destDir, fo.getName(), fo.getExt()));
1111
}
1112                    }
1113                }
1114            }
1115        }
1116
1117        /** Returns the destination (parent) directory needed to create file with relative path path under webBuilBase
1118         */

1119        private FileObject ensureDestinationFileExists(FileObject webBuildBase, String JavaDoc path, boolean isFolder) throws IOException {
1120            FileObject current = webBuildBase;
1121            StringTokenizer st = new StringTokenizer(path, "/");
1122            while (st.hasMoreTokens()) {
1123                String JavaDoc pathItem = st.nextToken();
1124                FileObject newCurrent = current.getFileObject(pathItem);
1125                if (newCurrent == null) {
1126                    // need to create it
1127
if (isFolder || st.hasMoreTokens()) {
1128                        // create a folder
1129
newCurrent = FileUtil.createFolder(current, pathItem);
1130                    }
1131                    else {
1132                        newCurrent = FileUtil.createData(current, pathItem);
1133                    }
1134                }
1135                current = newCurrent;
1136            }
1137            return current;
1138        }
1139    }
1140    
1141    public void propertyChange(PropertyChangeEvent JavaDoc evt) {
1142        if (evt.getPropertyName().equals(WebProjectProperties.JAVAC_CLASSPATH) ||
1143                evt.getPropertyName().equals(WebProjectProperties.WAR_CONTENT_ADDITIONAL)) {
1144            ProjectManager.mutex().postWriteRequest(new Runnable JavaDoc () {
1145                public void run() {
1146            if (ProjectManager.getDefault().isValid(((ProjectInformation) getLookup().lookup(ProjectInformation.class)).getProject())) {
1147            EditableProperties props = helper.getProperties (AntProjectHelper.PROJECT_PROPERTIES_PATH); //Reread the properties, PathParser changes them
1148
//update lib references in private properties
1149
EditableProperties privateProps = helper.getProperties(AntProjectHelper.PRIVATE_PROPERTIES_PATH);
1150            ArrayList l = new ArrayList ();
1151            l.addAll(classPathExtender.getClassPathSupport().itemsList(props.getProperty(WebProjectProperties.JAVAC_CLASSPATH), WebProjectProperties.TAG_WEB_MODULE_LIBRARIES));
1152            l.addAll(classPathExtender.getClassPathSupport().itemsList(props.getProperty(WebProjectProperties.WAR_CONTENT_ADDITIONAL), WebProjectProperties.TAG_WEB_MODULE__ADDITIONAL_LIBRARIES));
1153            WebProjectProperties.storeLibrariesLocations(l.iterator(), privateProps);
1154            helper.putProperties(AntProjectHelper.PRIVATE_PROPERTIES_PATH, privateProps);
1155            }
1156                }
1157            });
1158        }
1159    }
1160    
1161    /** copy jax-ws.xml from resource to nbproject directory,
1162     * generate JaxWsModel,
1163     * add FileChangeListener to jax-ws.xml file object
1164     */

1165    public void createJaxWsFileObject() throws IOException {
1166        FileObject projectDir = helper.getProjectDirectory();
1167        WSUtils.retrieveJaxWsFromResource(projectDir);
1168        
1169        jaxWsFo = findJaxWsFileObject(projectDir);
1170        if (jaxWsFo!=null) {
1171            jaxWsListener = new JaxWsListener();
1172            jaxWsFo.addFileChangeListener(jaxWsListener);
1173         
1174            if (jaxWsModel!=null) {
1175                jaxWsModel.setJaxWsFile(jaxWsFo);
1176            } else {
1177                jaxWsModel = JaxWsModelProvider.getDefault().getJaxWsModel(jaxWsFo);
1178                if (jaxWsModel!=null) {
1179                    attachServiceListener(jaxWsModel);
1180                }
1181            }
1182        }
1183    }
1184    
1185    public FileObject findJaxWsFileObject() {
1186        return findJaxWsFileObject(helper.getProjectDirectory());
1187    }
1188    
1189    private FileObject findJaxWsFileObject(FileObject projectDir) {
1190        return projectDir.getFileObject(GeneratedFilesHelper.JAX_WS_XML_PATH);
1191    }
1192    
1193    private JaxWsModel getJaxWsModel() {
1194        if (jaxWsModel==null)
1195            try {
1196                final FileObject projectDir = helper.getProjectDirectory();
1197                jaxWsFo = findJaxWsFileObject(projectDir);
1198                if (jaxWsFo==null) {
1199                    // create jaxWsModel from the resource
1200
jaxWsModel = JaxWsModelProvider.getDefault().getJaxWsModel(
1201                            WSUtils.class.getResourceAsStream("/org/netbeans/modules/websvc/jaxwsmodel/resources/jax-ws.xml"));//NOI18N
1202
jaxWsModel.setJaxWsFile(projectDir);
1203                } else {
1204                    jaxWsListener = new JaxWsListener();
1205                    try {
1206                        jaxWsModel = JaxWsModelProvider.getDefault().getJaxWsModel(jaxWsFo);
1207                        jaxWsFo.addFileChangeListener(jaxWsListener);
1208                    } catch (RuntimeException JavaDoc ex) {
1209                        // create jaxWsModel from the resource
1210
jaxWsModel = JaxWsModelProvider.getDefault().getJaxWsModel(
1211                                WSUtils.class.getResourceAsStream("/org/netbeans/modules/websvc/jaxwsmodel/resources/jax-ws.xml"));//NOI18N
1212
jaxWsModel.setJaxWsFile(projectDir);
1213                        final FileObject oldJaxWsFo = jaxWsFo;
1214                        jaxWsFo=null;
1215                        final RuntimeException JavaDoc exception = ex;
1216                        RequestProcessor.getDefault().post(new Runnable JavaDoc() {
1217                            public void run() {
1218                                try {
1219                                    jaxWsFo = WSUtils.backupAndGenerateJaxWs(projectDir, oldJaxWsFo, exception);
1220                                    if (jaxWsFo!=null) {
1221                                        jaxWsModel.setJaxWsFile(jaxWsFo);
1222                                        jaxWsFo.addFileChangeListener(jaxWsListener);
1223                                    }
1224                                } catch (IOException ex) {
1225                                    ErrorManager.getDefault().log(ex.getLocalizedMessage());
1226                                }
1227                            }
1228                        });
1229                    }
1230                }
1231                if (jaxWsModel!=null) {
1232                    attachServiceListener(jaxWsModel);
1233                }
1234            } catch (IOException ex) {
1235                ErrorManager.getDefault().log(ex.getLocalizedMessage());
1236            }
1237        return jaxWsModel;
1238    }
1239    
1240    private void attachServiceListener(JaxWsModel jaxWsModel) {
1241        jaxWsServiceListener = new JaxWsModel.ServiceListener() {
1242            public void serviceAdded(String JavaDoc name, String JavaDoc implementationClass) {
1243                getAPIJAXWSSupport().addService(name, implementationClass, isJsr109Supported() && isJavaEE5(WebProject.this));
1244            }
1245
1246            public void serviceRemoved(String JavaDoc name) {
1247                getAPIJAXWSSupport().serviceFromJavaRemoved(name);
1248            }
1249        };
1250        jaxWsModel.addServiceListener(jaxWsServiceListener);
1251    }
1252    
1253    public boolean isJavaEE5(Project project) {
1254        return J2eeModule.JAVA_EE_5.equals(getAPIWebModule().getJ2eePlatformVersion());
1255    }
1256    
1257    private boolean isJsr109Supported() {
1258        boolean jsr109Supported = true;
1259        String JavaDoc serverInstance = evaluator().getProperty(WebProjectProperties.J2EE_SERVER_INSTANCE);
1260        if (serverInstance != null) {
1261            J2eePlatform j2eePlatform = Deployment.getDefault().getJ2eePlatform(serverInstance);
1262            if (j2eePlatform != null) {
1263                jsr109Supported = j2eePlatform.isToolSupported(J2eePlatform.TOOL_JSR109);
1264            }
1265        }
1266        return jsr109Supported;
1267    }
1268   
1269    private class JaxWsListener extends FileChangeAdapter {
1270        public void fileChanged(FileEvent fe) {
1271            try {
1272                final JaxWsModel newModel = JaxWsModelProvider.getDefault().getJaxWsModel(fe.getFile());
1273                RequestProcessor.getDefault().post(new Runnable JavaDoc() {
1274                    public void run() {
1275                        if (jaxWsModel!=null && newModel!=null) jaxWsModel.merge(newModel);
1276                        try {
1277                            genFilesHelper.refreshBuildScript(
1278                            GeneratedFilesHelper.BUILD_IMPL_XML_PATH,
1279                            WebProject.class.getResource("resources/build-impl.xsl"),
1280                            jaxWsFo, false);
1281                        } catch (IOException ex) {}
1282                    }
1283                    
1284                });
1285                
1286            } catch (IOException ex) {}
1287        }
1288    }
1289}
1290
Popular Tags