KickJava   Java API By Example, From Geeks To Geeks.

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


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.web.project;
21
22 import java.awt.*;
23 import java.io.File JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.util.Stack JavaDoc;
26 import java.util.Vector JavaDoc;
27
28 import javax.swing.*;
29
30 import org.openide.filesystems.FileObject;
31 import org.openide.filesystems.FileStateInvalidException;
32 import org.openide.filesystems.FileUtil;
33
34 import org.netbeans.spi.project.support.ant.PropertyUtils;
35 import org.netbeans.spi.project.support.ant.AntProjectHelper;
36 import org.netbeans.spi.project.support.ant.EditableProperties;
37 import org.netbeans.api.java.platform.JavaPlatform;
38 import org.netbeans.api.java.platform.JavaPlatformManager;
39
40 public class Utils {
41
42     // COPIED FROM TOMCAT
43
private static final String JavaDoc javaKeywords[] = {
44         "abstract", "assert", "boolean", "break", "byte", "case",
45         "catch", "char", "class", "const", "continue",
46         "default", "do", "double", "else", "enum", "extends",
47         "final", "finally", "float", "for", "goto",
48         "if", "implements", "import", "instanceof", "int",
49         "interface", "long", "native", "new", "package",
50         "private", "protected", "public", "return", "short",
51         "static", "strictfp", "super", "switch", "synchronized",
52         "this", "throws", "transient", "try", "void",
53         "volatile", "while" };
54
55     private static final String JavaDoc JSP_PACKAGE_NAME = "org.apache.jsp";
56     
57     private static final String JavaDoc PLATFORM_ANT_NAME = "platform.ant.name"; //NOI18N
58
public static final String JavaDoc SPECIFICATION_J2SE = "j2se"; //NOI18N
59

60     public static File JavaDoc getRoot(File JavaDoc f) {
61         File JavaDoc rootF = f;
62         while (rootF.getParentFile() != null) {
63             rootF = rootF.getParentFile();
64         }
65         return rootF;
66     }
67
68     public static FileObject getValidDir(File JavaDoc dir) throws IOException JavaDoc {
69         Stack JavaDoc stack = new Stack JavaDoc ();
70         while (!dir.exists()) {
71             stack.push (dir.getName());
72             dir = dir.getParentFile();
73         }
74         FileObject dirFO = FileUtil.toFileObject (dir);
75         if (dirFO == null) {
76             refreshFileSystem(dir);
77             dirFO = FileUtil.toFileObject (dir);
78         }
79         assert dirFO != null;
80         while (!stack.isEmpty()) {
81             dirFO = dirFO.createFolder((String JavaDoc)stack.pop());
82         }
83         return dirFO;
84     }
85     
86     private static void refreshFileSystem (final File JavaDoc dir) throws FileStateInvalidException {
87         File JavaDoc rootF = dir;
88         while (rootF.getParentFile() != null) {
89             rootF = rootF.getParentFile();
90         }
91         FileObject dirFO = FileUtil.toFileObject(rootF);
92         assert dirFO != null : "At least disk roots must be mounted! " + rootF; // NOI18N
93
dirFO.getFileSystem().refresh(false);
94     }
95     
96     public static FileObject getValidEmptyDir(File JavaDoc dir) throws IOException JavaDoc {
97         final FileObject fo = getValidDir(dir);
98         if (fo.getChildren().length != 0) {
99             throw new IOException JavaDoc("Dir has to be empty: " + dir);
100         }
101         return fo;
102     }
103
104     /** Create a valid default for context path from project name.
105      */

106     public static String JavaDoc createDefaultContext(String JavaDoc projectName) {
107         return "/" + PropertyUtils.getUsablePropertyName(projectName);
108     }
109     
110     /**
111      * Updates property file at given location of ant based project
112      * @param h helper of the project
113      * @param path a relative URI in the project directory
114      * @param ep new or updated properties
115      */

116     public static void updateProperties(AntProjectHelper h, String JavaDoc path, EditableProperties ep) {
117         EditableProperties properties = h.getProperties(path);
118         properties.putAll(ep);
119         h.putProperties(path, properties);
120     }
121
122     /**
123      * Recursively checks whether the file lies underneath or equals the folder
124      * @param folder the root of folders hierarchy to search in
125      * @param file the file to search for
126      * @return <code>true</code>, if <code>file</code> lies somewhere underneath or equals the <code>folder</code>,
127      * <code>false</code> otherwise
128      */

129     public static boolean isParentOrEqual(File JavaDoc folder, File JavaDoc file) {
130         if(folder != null || file != null) {
131             folder = FileUtil.normalizeFile(folder);
132             file = FileUtil.normalizeFile(file);
133             while(file != null) {
134                 if(file.equals(folder)) {
135                     return true;
136                 }
137                 file = file.getParentFile();
138             }
139         }
140         return false;
141     }
142
143     /**
144      * Searches Java platform according to platform name
145      * Specification of the platform has to be J2SE
146      * @param platformName
147      * @return related JavaPlatform object if found, otherwise null
148      */

149     public static JavaPlatform findJ2seJavaPlatform(String JavaDoc platformName) {
150         return findJavaPlatform(platformName, SPECIFICATION_J2SE);
151     }
152
153     /**
154      * Searches Java platform according to platform name
155      * The platform sepecification does not need to be J2SE
156      * @param platformName
157      * @return related JavaPlatform object if found, otherwise null
158      */

159     public static JavaPlatform findJavaPlatform(String JavaDoc platformName) {
160         return findJavaPlatform(platformName, null);
161     }
162
163     private static JavaPlatform findJavaPlatform(String JavaDoc platformName, String JavaDoc specFilter) {
164         if(platformName != null) {
165             JavaPlatform[] platforms = JavaPlatformManager.getDefault().getInstalledPlatforms();
166             for(int i = 0; i < platforms.length; i++) {
167                 JavaPlatform platform = platforms[i];
168                 String JavaDoc antName = (String JavaDoc)platform.getProperties().get(PLATFORM_ANT_NAME);
169                 if (antName != null && antName.equals(platformName)) {
170                     if(specFilter == null || specFilter.equalsIgnoreCase(platform.getSpecification().getName()))
171                     return platform;
172                 }
173             }
174         }
175         return null;
176     }
177
178     // COPIED FROM TOMCAT
179
/** Returns a slash-delimited resource path for the servlet generated from
180      * JSP, given a resource path of the original JSP. Uses code copied from Tomcat.
181      * Note: does not handle tag files yet, only JSP files.
182      */

183     static String JavaDoc getGeneratedJavaResource(String JavaDoc jspUri) {
184         int iSep = jspUri.lastIndexOf('/');
185         String JavaDoc packageName = (iSep > 0) ? makeJavaPackage(jspUri.substring(0,iSep)) : ""; // NOI18N
186
if (packageName.length() == 0) {
187             packageName = JSP_PACKAGE_NAME;
188         }
189         else {
190             packageName = JSP_PACKAGE_NAME + "." + packageName; // NOI18N
191
}
192         String JavaDoc className = makeJavaIdentifier(jspUri.substring(iSep + 1));
193         return packageName.replace('.', '/') + "/" + className + ".java"; // NOI18N
194
}
195     
196     // COPIED FROM TOMCAT
197
/**
198      * Converts the given path to a Java package or fully-qualified class name
199      *
200      * @param path Path to convert
201      *
202      * @return Java package corresponding to the given path
203      */

204     private static final String JavaDoc makeJavaPackage(String JavaDoc path) {
205         String JavaDoc classNameComponents[] = split(path,"/");
206         StringBuffer JavaDoc legalClassNames = new StringBuffer JavaDoc();
207         for (int i = 0; i < classNameComponents.length; i++) {
208             legalClassNames.append(makeJavaIdentifier(classNameComponents[i]));
209             if (i < classNameComponents.length - 1) {
210                 legalClassNames.append('.');
211             }
212         }
213         return legalClassNames.toString();
214     }
215     
216     // COPIED FROM TOMCAT
217
/**
218      * Splits a string into it's components.
219      * @param path String to split
220      * @param pat Pattern to split at
221      * @return the components of the path
222      */

223     private static final String JavaDoc [] split(String JavaDoc path, String JavaDoc pat) {
224         Vector JavaDoc comps = new Vector JavaDoc();
225         int pos = path.indexOf(pat);
226         int start = 0;
227         while( pos >= 0 ) {
228             if(pos > start ) {
229                 String JavaDoc comp = path.substring(start,pos);
230                 comps.add(comp);
231             }
232             start = pos + pat.length();
233             pos = path.indexOf(pat,start);
234         }
235         if( start < path.length()) {
236             comps.add(path.substring(start));
237         }
238         String JavaDoc [] result = new String JavaDoc[comps.size()];
239         for(int i=0; i < comps.size(); i++) {
240             result[i] = (String JavaDoc)comps.elementAt(i);
241         }
242         return result;
243     }
244             
245     // COPIED FROM TOMCAT
246
/**
247      * Converts the given identifier to a legal Java identifier
248      *
249      * @param identifier Identifier to convert
250      *
251      * @return Legal Java identifier corresponding to the given identifier
252      */

253     private static final String JavaDoc makeJavaIdentifier(String JavaDoc identifier) {
254         StringBuffer JavaDoc modifiedIdentifier =
255             new StringBuffer JavaDoc(identifier.length());
256         if (!Character.isJavaIdentifierStart(identifier.charAt(0))) {
257             modifiedIdentifier.append('_');
258         }
259         for (int i = 0; i < identifier.length(); i++) {
260             char ch = identifier.charAt(i);
261             if (Character.isJavaIdentifierPart(ch) && ch != '_') {
262                 modifiedIdentifier.append(ch);
263             } else if (ch == '.') {
264                 modifiedIdentifier.append('_');
265             } else {
266                 modifiedIdentifier.append(mangleChar(ch));
267             }
268         }
269         if (isJavaKeyword(modifiedIdentifier.toString())) {
270             modifiedIdentifier.append('_');
271         }
272         return modifiedIdentifier.toString();
273     }
274     
275     // COPIED FROM TOMCAT
276
/**
277      * Mangle the specified character to create a legal Java class name.
278      */

279     private static final String JavaDoc mangleChar(char ch) {
280         char[] result = new char[5];
281         result[0] = '_';
282         result[1] = Character.forDigit((ch >> 12) & 0xf, 16);
283         result[2] = Character.forDigit((ch >> 8) & 0xf, 16);
284         result[3] = Character.forDigit((ch >> 4) & 0xf, 16);
285         result[4] = Character.forDigit(ch & 0xf, 16);
286         return new String JavaDoc(result);
287     }
288
289     // COPIED FROM TOMCAT
290
/**
291      * Test whether the argument is a Java keyword
292      */

293     private static boolean isJavaKeyword(String JavaDoc key) {
294         int i = 0;
295         int j = javaKeywords.length;
296         while (i < j) {
297             int k = (i+j)/2;
298             int result = javaKeywords[k].compareTo(key);
299             if (result == 0) {
300                 return true;
301             }
302             if (result < 0) {
303                 i = k+1;
304             } else {
305                 j = k;
306             }
307         }
308         return false;
309     }
310
311     public static Color getErrorColor() {
312         // inspired by org.openide.WizardDescriptor
313
Color c = UIManager.getColor("nb.errorForeground"); //NOI18N
314
return c == null ? new Color(89,79,191) : c;
315     }
316     
317     public static String JavaDoc toClasspathString(File JavaDoc[] classpathEntries) {
318         if (classpathEntries == null) {
319             return "";
320         }
321         StringBuffer JavaDoc classpath = new StringBuffer JavaDoc();
322         for (int i = 0; i < classpathEntries.length; i++) {
323             classpath.append(classpathEntries[i].getAbsolutePath());
324             if (i + 1 < classpathEntries.length) {
325                 classpath.append(':'); // NOI18N
326
}
327         }
328         return classpath.toString();
329     }
330 }
Popular Tags