KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > j2ee > clientproject > SourceRoots


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

19
20 package org.netbeans.modules.j2ee.clientproject;
21
22 import java.beans.PropertyChangeEvent JavaDoc;
23 import java.beans.PropertyChangeListener JavaDoc;
24 import java.beans.PropertyChangeSupport JavaDoc;
25 import java.io.File JavaDoc;
26 import java.net.MalformedURLException JavaDoc;
27 import java.net.URL JavaDoc;
28 import java.net.URI JavaDoc;
29 import java.util.Arrays JavaDoc;
30 import java.util.ArrayList JavaDoc;
31 import java.util.Collections JavaDoc;
32 import java.util.Iterator JavaDoc;
33 import java.util.List JavaDoc;
34 import java.util.Map JavaDoc;
35 import java.util.HashMap JavaDoc;
36 import java.text.MessageFormat JavaDoc;
37 import org.openide.ErrorManager;
38 import org.openide.filesystems.FileObject;
39 import org.openide.filesystems.FileUtil;
40 import org.openide.util.WeakListeners;
41 import org.openide.util.Mutex;
42 import org.openide.util.NbBundle;
43 import org.w3c.dom.Element JavaDoc;
44 import org.w3c.dom.NodeList JavaDoc;
45 import org.w3c.dom.Document JavaDoc;
46 import org.netbeans.spi.project.support.ant.AntProjectHelper;
47 import org.netbeans.spi.project.support.ant.AntProjectEvent;
48 import org.netbeans.spi.project.support.ant.AntProjectListener;
49 import org.netbeans.spi.project.support.ant.EditableProperties;
50 import org.netbeans.spi.project.support.ant.PropertyEvaluator;
51 import org.netbeans.spi.project.support.ant.ReferenceHelper;
52 import org.netbeans.api.project.ProjectManager;
53 import org.netbeans.api.java.project.JavaProjectConstants;
54
55 /**
56  * This class represents a project source roots. It is used to obtain roots as Ant properties, FileObject's
57  * or URLs.
58  * @author Tomas Zezula
59  */

60 public final class SourceRoots {
61
62     public static final String JavaDoc PROP_ROOT_PROPERTIES = "rootProperties"; //NOI18N
63
public static final String JavaDoc PROP_ROOTS = "roots"; //NOI18N
64

65     public static final String JavaDoc DEFAULT_SOURCE_LABEL = NbBundle.getMessage(SourceRoots.class, "NAME_src.dir");
66     public static final String JavaDoc DEFAULT_TEST_LABEL = NbBundle.getMessage(SourceRoots.class, "NAME_test.src.dir");
67
68     private final UpdateHelper helper;
69     private final PropertyEvaluator evaluator;
70     private final ReferenceHelper refHelper;
71     private final String JavaDoc elementName;
72     private final String JavaDoc newRootNameTemplate;
73     private List JavaDoc<String JavaDoc> sourceRootProperties;
74     private List JavaDoc<String JavaDoc> sourceRootNames;
75     private List JavaDoc<FileObject> sourceRoots;
76     private List JavaDoc<URL JavaDoc> sourceRootURLs;
77     private final PropertyChangeSupport JavaDoc support;
78     private final ProjectMetadataListener listener;
79     private final boolean isTest;
80     private final File JavaDoc projectDir;
81
82     /**
83      * Creates new SourceRoots
84      * @param helper
85      * @param evaluator
86      * @param elementName the name of XML element under which are declared the roots
87      * @param newRootNameTemplate template for new property name of source root
88      */

89     SourceRoots (UpdateHelper helper, PropertyEvaluator evaluator, ReferenceHelper refHelper, String JavaDoc elementName, boolean isTest, String JavaDoc newRootNameTemplate) {
90         assert helper != null && evaluator != null && refHelper != null && elementName != null && newRootNameTemplate != null;
91         this.helper = helper;
92         this.evaluator = evaluator;
93         this.refHelper = refHelper;
94         this.elementName = elementName;
95         this.isTest = isTest;
96         this.newRootNameTemplate = newRootNameTemplate;
97         this.projectDir = FileUtil.toFile(this.helper.getAntProjectHelper().getProjectDirectory());
98         this.support = new PropertyChangeSupport JavaDoc(this);
99         this.listener = new ProjectMetadataListener();
100         this.evaluator.addPropertyChangeListener (WeakListeners.propertyChange(this.listener,this.evaluator));
101         this.helper.getAntProjectHelper().addAntProjectListener ((AntProjectListener)WeakListeners.create(AntProjectListener.class, this.listener,this.helper));
102     }
103
104
105     /**
106      * Returns the display names of soruce roots
107      * The returned array has the same length as an array returned by the getRootProperties.
108      * It may contain empty strings but not null.
109      * @return an array of String
110      */

111     public String JavaDoc[] getRootNames () {
112         return (String JavaDoc[]) ProjectManager.mutex().readAccess(new Mutex.Action() {
113             public Object JavaDoc run() {
114                 synchronized (SourceRoots.this) {
115                     if (sourceRootNames == null) {
116                         readProjectMetadata();
117                     }
118                 }
119                 return sourceRootNames.toArray (new String JavaDoc[sourceRootNames.size()]);
120             }
121         });
122     }
123
124     /**
125      * Returns names of Ant properties in the project.properties file holding the source roots.
126      * @return an array of String
127      */

128     public String JavaDoc[] getRootProperties () {
129         return (String JavaDoc[]) ProjectManager.mutex().readAccess(new Mutex.Action() {
130             public Object JavaDoc run() {
131                 synchronized (SourceRoots.this) {
132                     if (sourceRootProperties == null) {
133                         readProjectMetadata();
134                     }
135                 }
136                 return sourceRootProperties.toArray (new String JavaDoc[sourceRootProperties.size()]);
137             }
138         });
139     }
140
141     /**
142      * Returns the source roots
143      * @return an array of FileObject
144      */

145     public FileObject[] getRoots () {
146         return (FileObject[]) ProjectManager.mutex().readAccess(new Mutex.Action () {
147                 public Object JavaDoc run () {
148                     synchronized (this) {
149                         //Local caching
150
if (sourceRoots == null) {
151                             String JavaDoc[] srcProps = getRootProperties();
152                             List JavaDoc<FileObject> result = new ArrayList JavaDoc<FileObject>();
153                             for (int i = 0; i<srcProps.length; i++) {
154                                 String JavaDoc prop = evaluator.getProperty(srcProps[i]);
155                                 if (prop != null) {
156                                     FileObject f = helper.getAntProjectHelper().resolveFileObject(prop);
157                                     if (f == null) {
158                                         continue;
159                                     }
160                                     if (FileUtil.isArchiveFile(f)) {
161                                         f = FileUtil.getArchiveRoot(f);
162                                     }
163                                     result.add(f);
164                                 }
165                             }
166                             sourceRoots = Collections.unmodifiableList(result);
167                         }
168                     }
169                     return sourceRoots.toArray(new FileObject[sourceRoots.size()]);
170                 }
171         });
172     }
173
174     /**
175      * Returns the source roots as URLs.
176      * @return an array of URL
177      */

178     public URL JavaDoc[] getRootURLs() {
179         return (URL JavaDoc[]) ProjectManager.mutex().readAccess(new Mutex.Action () {
180             public Object JavaDoc run () {
181                 synchronized (this) {
182                     //Local caching
183
if (sourceRootURLs == null) {
184                         String JavaDoc[] srcProps = getRootProperties();
185                         List JavaDoc<URL JavaDoc> result = new ArrayList JavaDoc<URL JavaDoc>();
186                         for (int i = 0; i<srcProps.length; i++) {
187                             String JavaDoc prop = evaluator.getProperty(srcProps[i]);
188                             if (prop != null) {
189                                 File JavaDoc f = helper.getAntProjectHelper().resolveFile(prop);
190                                 try {
191                                     URL JavaDoc url = f.toURI().toURL();
192                                     if (!f.exists()) {
193                                         url = new URL JavaDoc(url.toExternalForm() + "/"); // NOI18N
194
}
195                                     result.add(url);
196                                 } catch (MalformedURLException JavaDoc e) {
197                                     ErrorManager.getDefault().notify(e);
198                                 }
199                             }
200                         }
201                         sourceRootURLs = Collections.unmodifiableList(result);
202                     }
203                 }
204                 return sourceRootURLs.toArray(new URL JavaDoc[sourceRootURLs.size()]);
205             }
206         });
207     }
208
209     /**
210      * Adds PropertyChangeListener
211      * @param listener
212      */

213     public void addPropertyChangeListener (PropertyChangeListener JavaDoc listener) {
214         this.support.addPropertyChangeListener (listener);
215     }
216
217     /**
218      * Removes PropertyChangeListener
219      * @param listener
220      */

221     public void removePropertyChangeListener (PropertyChangeListener JavaDoc listener) {
222         this.support.removePropertyChangeListener (listener);
223     }
224
225
226     /**
227      * Replaces the current roots by the new ones
228      * @param roots the URLs of new roots
229      * @param labels the names of roots
230      */

231     public void putRoots (final URL JavaDoc[] roots, final String JavaDoc[] labels) {
232         ProjectManager.mutex().writeAccess(
233                 new Mutex.Action () {
234                     public Object JavaDoc run() {
235                         String JavaDoc[] originalProps = getRootProperties();
236                         URL JavaDoc[] originalRoots = getRootURLs();
237                         Map JavaDoc<URL JavaDoc, String JavaDoc> oldRoots2props = new HashMap JavaDoc<URL JavaDoc, String JavaDoc>();
238                         for (int i=0; i<originalProps.length;i++) {
239                             oldRoots2props.put (originalRoots[i],originalProps[i]);
240                         }
241                         Map JavaDoc<URL JavaDoc,String JavaDoc> newRoots2lab = new HashMap JavaDoc<URL JavaDoc,String JavaDoc>();
242                         for (int i=0; i<roots.length;i++) {
243                             newRoots2lab.put (roots[i],labels[i]);
244                         }
245                         Element JavaDoc cfgEl = helper.getPrimaryConfigurationData(true);
246                         NodeList JavaDoc nl = cfgEl.getElementsByTagNameNS(AppClientProjectType.PROJECT_CONFIGURATION_NAMESPACE, elementName);
247                         assert nl.getLength() == 1 : "Illegal project.xml"; //NOI18N
248
Element JavaDoc ownerElement = (Element JavaDoc) nl.item(0);
249                         //Remove all old roots
250
NodeList JavaDoc rootsNodes = ownerElement.getElementsByTagNameNS(AppClientProjectType.PROJECT_CONFIGURATION_NAMESPACE, "root"); //NOI18N
251
while (rootsNodes.getLength()>0) {
252                             Element JavaDoc root = (Element JavaDoc) rootsNodes.item(0);
253                             ownerElement.removeChild(root);
254                         }
255                         //Remove all unused root properties
256
List JavaDoc newRoots = Arrays.asList(roots);
257                         Map JavaDoc<URL JavaDoc, String JavaDoc> propsToRemove = new HashMap JavaDoc<URL JavaDoc, String JavaDoc>(oldRoots2props);
258                         propsToRemove.keySet().removeAll(newRoots);
259                         EditableProperties props = helper.getProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH);
260                         for (Iterator JavaDoc<String JavaDoc> it = propsToRemove.values().iterator(); it.hasNext();) {
261                             String JavaDoc propName = it.next();
262                             props.remove(propName);
263                         }
264                         helper.putProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH,props);
265                         //Add the new roots
266
Document JavaDoc doc = ownerElement.getOwnerDocument();
267                         oldRoots2props.keySet().retainAll(newRoots);
268                         for (Iterator JavaDoc it = newRoots.iterator(); it.hasNext();) {
269                             URL JavaDoc newRoot = (URL JavaDoc) it.next ();
270                             String JavaDoc rootName = oldRoots2props.get (newRoot);
271                             if (rootName == null) {
272                                 //Root is new generate property for it
273
props = helper.getProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH);
274                                 String JavaDoc[] names = newRoot.getPath().split("/"); //NOI18N
275
rootName = MessageFormat.format(newRootNameTemplate,new Object JavaDoc[]{names[names.length-1],""}); //NOI18N
276
int rootIndex = 1;
277                                 while (props.containsKey(rootName)) {
278                                     rootIndex++;
279                                     rootName = MessageFormat.format(newRootNameTemplate,new Object JavaDoc[]{names[names.length-1],new Integer JavaDoc(rootIndex)});
280                                 }
281                                 File JavaDoc f = FileUtil.normalizeFile(new File JavaDoc(URI.create(newRoot.toExternalForm())));
282                                 File JavaDoc projDir = FileUtil.toFile(helper.getAntProjectHelper().getProjectDirectory());
283                                 String JavaDoc path = f.getAbsolutePath();
284                                 String JavaDoc prjPath = projDir.getAbsolutePath()+File.separatorChar;
285                                 if (path.startsWith(prjPath)) {
286                                     path = path.substring(prjPath.length());
287                                 }
288                                 else {
289                                     path = refHelper.createForeignFileReference(f, JavaProjectConstants.SOURCES_TYPE_JAVA);
290                                     props = helper.getProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH);
291                                 }
292                                 props.put(rootName,path);
293                                 helper.putProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH,props);
294                             }
295                             Element JavaDoc newRootNode = doc.createElementNS(AppClientProjectType.PROJECT_CONFIGURATION_NAMESPACE, "root"); //NOI18N
296
newRootNode.setAttribute("id",rootName); //NOI18N
297
String JavaDoc label = newRoots2lab.get (newRoot);
298                             if (label != null && label.length()>0 && !label.equals (getRootDisplayName(null,rootName))) { //NOI18N
299
newRootNode.setAttribute("name",label); //NOI18N
300
}
301                             ownerElement.appendChild (newRootNode);
302                         }
303                         helper.putPrimaryConfigurationData(cfgEl,true);
304                         return null;
305                     }
306                 }
307         );
308     }
309     
310     /**
311      * Translates root name into display name of source/test root
312      * @param rootName the name of root got from {@link SourceRoots#getRootNames}
313      * @param propName the name of property the root is stored in
314      * @return the label to be displayed
315      */

316     public String JavaDoc getRootDisplayName (String JavaDoc rootName, String JavaDoc propName) {
317         if (rootName == null || rootName.length() ==0) {
318             //If the prop is src.dir use the default name
319
if (isTest && "test.src.dir".equals(propName)) { //NOI18N
320
rootName = DEFAULT_TEST_LABEL;
321             }
322             else if (!isTest && "src.dir".equals(propName)) { //NOI18N
323
rootName = DEFAULT_SOURCE_LABEL;
324             }
325             else {
326                 //If the name is not given, it should be either a relative path in the project dir
327
//or absolute path when the root is not under the project dir
328
String JavaDoc propValue = evaluator.getProperty(propName);
329                 File JavaDoc sourceRoot = propValue == null ? null : helper.getAntProjectHelper().resolveFile(propValue);
330                 rootName = createInitialDisplayName(sourceRoot);
331             }
332         }
333         return rootName;
334     }
335     
336     /**
337      * Creates initial display name of source/test root
338      * @param sourceRoot the source root
339      * @return the label to be displayed
340      */

341     public String JavaDoc createInitialDisplayName (File JavaDoc sourceRoot) {
342         String JavaDoc rootName;
343         if (sourceRoot != null) {
344         String JavaDoc srPath = sourceRoot.getAbsolutePath();
345         String JavaDoc pdPath = projectDir.getAbsolutePath() + File.separatorChar;
346         if (srPath.startsWith(pdPath)) {
347             rootName = srPath.substring(pdPath.length());
348         }
349         else {
350             rootName = sourceRoot.getAbsolutePath();
351         }
352         }
353         else {
354             rootName = isTest ? DEFAULT_TEST_LABEL : DEFAULT_SOURCE_LABEL;
355         }
356         return rootName;
357     }
358     
359     /**
360      * Returns true if this SourceRoots instance represents source roots belonging to
361      * the tests compilation unit.
362      * @return boolean
363      */

364     public boolean isTest () {
365         return this.isTest;
366     }
367
368     private void resetCache (boolean isXMLChange, String JavaDoc propName) {
369         boolean fire = false;
370         synchronized (this) {
371             //In case of change reset local cache
372
if (isXMLChange) {
373                 this.sourceRootProperties = null;
374                 this.sourceRootNames = null;
375                 this.sourceRoots = null;
376                 this.sourceRootURLs = null;
377                 fire = true;
378             } else if (propName == null || (sourceRootProperties != null && sourceRootProperties.contains(propName))) {
379                 this.sourceRoots = null;
380                 this.sourceRootURLs = null;
381                 fire = true;
382             }
383         }
384         if (fire) {
385             if (isXMLChange) {
386                 this.support.firePropertyChange (PROP_ROOT_PROPERTIES,null,null);
387             }
388             this.support.firePropertyChange (PROP_ROOTS,null,null);
389         }
390     }
391
392     private void readProjectMetadata () {
393         Element JavaDoc cfgEl = helper.getPrimaryConfigurationData(true);
394         NodeList JavaDoc nl = cfgEl.getElementsByTagNameNS(AppClientProjectType.PROJECT_CONFIGURATION_NAMESPACE, elementName);
395         assert nl.getLength() == 0 || nl.getLength() == 1 : "Illegal project.xml"; //NOI18N
396
List JavaDoc<String JavaDoc> rootProps = new ArrayList JavaDoc<String JavaDoc>();
397         List JavaDoc<String JavaDoc> rootNames = new ArrayList JavaDoc<String JavaDoc>();
398         // It can be 0 in the case when the project is created by J2SEProjectGenerator and not yet customized
399
if (nl.getLength()==1) {
400             NodeList JavaDoc roots = ((Element JavaDoc)nl.item(0)).getElementsByTagNameNS(AppClientProjectType.PROJECT_CONFIGURATION_NAMESPACE, "root"); //NOI18N
401
for (int i=0; i<roots.getLength(); i++) {
402                 Element JavaDoc root = (Element JavaDoc) roots.item(i);
403                 String JavaDoc value = root.getAttribute("id"); //NOI18N
404
assert value.length() > 0 : "Illegal project.xml";
405                 rootProps.add(value);
406                 value = root.getAttribute("name"); //NOI18N
407
rootNames.add (value);
408             }
409         }
410         this.sourceRootProperties = Collections.unmodifiableList(rootProps);
411         this.sourceRootNames = Collections.unmodifiableList(rootNames);
412     }
413
414     private class ProjectMetadataListener implements PropertyChangeListener JavaDoc,AntProjectListener {
415
416         public void propertyChange(PropertyChangeEvent JavaDoc evt) {
417             resetCache (false,evt.getPropertyName());
418         }
419
420         public void configurationXmlChanged(AntProjectEvent ev) {
421             resetCache (true,null);
422         }
423
424         public void propertiesChanged(AntProjectEvent ev) {
425             //Handled by propertyChange
426
}
427     }
428
429 }
430
Popular Tags