KickJava   Java API By Example, From Geeks To Geeks.

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

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

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

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

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

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

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

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

208     public void addPropertyChangeListener (PropertyChangeListener JavaDoc listener) {
209         this.support.addPropertyChangeListener (listener);
210     }
211
212     /**
213      * Removes PropertyChangeListener
214      * @param listener
215      */

216     public void removePropertyChangeListener (PropertyChangeListener JavaDoc listener) {
217         this.support.removePropertyChangeListener (listener);
218     }
219
220
221     /**
222      * Replaces the current roots by the new ones
223      * @param roots the URLs of new roots
224      * @param labels the names of roots
225      */

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

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

336     public String JavaDoc createInitialDisplayName (File JavaDoc sourceRoot) {
337         String JavaDoc rootName;
338         if (sourceRoot != null) {
339             String JavaDoc srPath = sourceRoot.getAbsolutePath();
340             String JavaDoc pdPath = projectDir.getAbsolutePath() + File.separatorChar;
341             if (srPath.startsWith(pdPath)) {
342                 rootName = srPath.substring(pdPath.length());
343             }
344             else {
345                 rootName = sourceRoot.getAbsolutePath();
346             }
347         }
348         else {
349             rootName = isTest ? DEFAULT_TEST_LABEL : DEFAULT_SOURCE_LABEL;
350         }
351         return rootName;
352     }
353
354     private void resetCache (boolean isXMLChange, String JavaDoc propName) {
355         boolean fire = false;
356         synchronized (this) {
357             //In case of change reset local cache
358
if (isXMLChange) {
359                 this.sourceRootProperties = null;
360                 this.sourceRootNames = null;
361                 this.sourceRoots = null;
362                 this.sourceRootURLs = null;
363                 fire = true;
364             } else if (propName == null || (sourceRootProperties != null && sourceRootProperties.contains(propName))) {
365                 this.sourceRoots = null;
366                 this.sourceRootURLs = null;
367                 fire = true;
368             }
369         }
370         if (fire) {
371             if (isXMLChange) {
372                 this.support.firePropertyChange (PROP_ROOT_PROPERTIES,null,null);
373             }
374             this.support.firePropertyChange (PROP_ROOTS,null,null);
375         }
376     }
377
378     private void readProjectMetadata () {
379         Element JavaDoc cfgEl = helper.getPrimaryConfigurationData(true);
380         NodeList JavaDoc nl = cfgEl.getElementsByTagNameNS(EjbJarProjectType.PROJECT_CONFIGURATION_NAMESPACE, elementName);
381         assert nl.getLength() == 0 || nl.getLength() == 1 : "Illegal project.xml"; //NOI18N
382
List JavaDoc rootProps = new ArrayList JavaDoc ();
383         List JavaDoc rootNames = new ArrayList JavaDoc ();
384         // It can be 0 in the case when the project is created by EjbJarProjectGenerator and not yet customized
385
if (nl.getLength()==1) {
386             NodeList JavaDoc roots = ((Element JavaDoc)nl.item(0)).getElementsByTagNameNS(EjbJarProjectType.PROJECT_CONFIGURATION_NAMESPACE, "root"); //NOI18N
387
for (int i=0; i<roots.getLength(); i++) {
388                 Element JavaDoc root = (Element JavaDoc) roots.item(i);
389                 String JavaDoc value = root.getAttribute("id"); //NOI18N
390
assert value.length() > 0 : "Illegal project.xml";
391                 rootProps.add(value);
392                 value = root.getAttribute("name"); //NOI18N
393
rootNames.add (value);
394             }
395         }
396         this.sourceRootProperties = Collections.unmodifiableList(rootProps);
397         this.sourceRootNames = Collections.unmodifiableList(rootNames);
398     }
399
400     private class ProjectMetadataListener implements PropertyChangeListener JavaDoc,AntProjectListener {
401
402         public void propertyChange(PropertyChangeEvent JavaDoc evt) {
403             resetCache (false,evt.getPropertyName());
404         }
405
406         public void configurationXmlChanged(AntProjectEvent ev) {
407             resetCache (true,null);
408         }
409
410         public void propertiesChanged(AntProjectEvent ev) {
411             //Handled by propertyChange
412
}
413     }
414
415     public boolean isTest() {
416         return isTest;
417     }
418 }
419
Popular Tags