001: /*
002: * The contents of this file are subject to the terms of the Common Development
003: * and Distribution License (the License). You may not use this file except in
004: * compliance with the License.
005: *
006: * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
007: * or http://www.netbeans.org/cddl.txt.
008: *
009: * When distributing Covered Code, include this CDDL Header Notice in each file
010: * and include the License file at http://www.netbeans.org/cddl.txt.
011: * If applicable, add the following below the CDDL Header, with the fields
012: * enclosed by brackets [] replaced by your own identifying information:
013: * "Portions Copyrighted [year] [name of copyright owner]"
014: *
015: * The Original Software is NetBeans. The Initial Developer of the Original
016: * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
017: * Microsystems, Inc. All Rights Reserved.
018: */
019:
020: package org.netbeans.modules.iep.project.anttasks;
021:
022: import java.net.InetAddress;
023: import java.net.UnknownHostException;
024:
025: import java.rmi.server.UID;
026:
027: import java.util.HashSet;
028:
029: /**
030: * DOCUMENT ME!
031: *
032: * @author Bing Lu
033: */
034: public class NameUtil {
035: private static final java.util.logging.Logger mLog = java.util.logging.Logger
036: .getLogger(NameUtil.class.getName());
037:
038: /** Holds a list of reserved identifiers. */
039: private static final HashSet JAVA_KEYWORD = new HashSet();
040: static {
041: // Initialize "JAVA_KEYWORD".
042: String[] key = {
043: // Current and future keywords + primitive types + classes
044: // automatically imported (java.lang.*).
045: "abstract", "boolean", "break", "byte", "byvalue",
046: "case", "cast", "catch", "char", "class", "const",
047: "continue", "default", "do", "double", "else",
048: "extends", "false", "final", "finalize", "finally",
049: "float", "for", "future", "generic", "goto", "if",
050: "implements", "import", "inner", "instanceof",
051: "int",
052: "interface",
053: "long",
054: "native",
055: "new",
056: "null",
057: "operator",
058: "outer",
059: "package",
060: "private",
061: "protected",
062: "public",
063: "rest",
064: "return",
065: "short",
066: "static",
067: "strictfp",
068: "super",
069: "switch",
070: "synchronized",
071: "then",
072: "this",
073: "throw",
074: "throws",
075: "transient",
076: "true",
077: "try",
078: "var",
079: "void",
080: "volatile",
081: "while",
082: "widefp",
083: // classes in java.lang.* automatically imported
084: "AbstractMethodError", "ArithmeticException",
085: "ArrayIndexOutOfBoundsException",
086: "ArrayStoreException", "Boolean", "Byte", "Character",
087: "Class", "ClassCastException", "ClassCircularityError",
088: "ClassFormatError", "ClassLoader",
089: "ClassNotFoundException", "CloneNotSupportedException",
090: "Clonable", "Compiler", "Double", "Error", "Exception",
091: "ExceptionInInitializerError", "Float",
092: "IllegalAccessError", "IllegalAccessException",
093: "IllegalArgumentException",
094: "IllegalMonitorStateException",
095: "IllegalStateException", "IllegalThreadStateException",
096: "IncompatibleClassChangeError",
097: "IndexOutOfBoundsException", "InstantiationError",
098: "InstantiationException", "Integer", "InternalError",
099: "InterruptedException", "LinkageError", "Long", "Math",
100: "NegativeArraySizeException", "NoClassDefFoundError",
101: "NoSuchFieldError", "NoSuchFieldException",
102: "NoSuchMethodError", "NoSuchMethodException",
103: "NullPointerException", "Number",
104: "NumberFormatException", "Object", "OutOfMemoryError",
105: "Process", "Runnable", "Runtime", "RuntimeException",
106: "SecurityException", "SecurityManager", "Short",
107: "StackOverflowError", "String", "StringBuffer",
108: "StringIndexOutOfBoundsException", "System", "Thread",
109: "ThreadDeath", "ThreadGroup", "Throwable",
110: "UnknownError", "UnsatisfiedLinkError", "VerifyError",
111: "VirtualMachineError", "Void" };
112:
113: for (int i = 0; i < key.length; i++) {
114: JAVA_KEYWORD.add(key[i]);
115: }
116: }
117:
118: /**
119: * true if s in a legal java identifier that contains no $, s is not a Java keyword,
120: * and s is not a class name in java.lang.* package
121: */
122: public static boolean isLegalName(String s) {
123: for (int i = 0; i < s.length(); i++) {
124: char ch = s.charAt(i);
125: boolean isIdentifierChar = (i == 0) ? Character
126: .isJavaIdentifierStart(ch) : Character
127: .isJavaIdentifierPart(ch);
128: if (!isIdentifierChar || (ch == '$')) {
129: return false;
130: }
131: }
132:
133: if ((s.length() == 0) || isKeyword(s)) {
134: return false;
135: }
136: return true;
137: }
138:
139: public static boolean isKeyword(String s) {
140: return JAVA_KEYWORD.contains(s);
141: }
142:
143: //
144:
145: /**
146: * Given a string, strip it to a legal Java identifier. Characters that are
147: * not legal are removed; if the 1st char would be legal as 2nd but not as
148: * 1st, prefix "_"; if identifier is in list of reserved words, prefix "_";
149: * if no legal chars remain, return "_".
150: *
151: * @param str the string to make into a legal java identifier
152: * @return the legal java/XML identifier
153: */
154: public static String makeJavaId(String str) {
155:
156: StringBuffer sb = new StringBuffer(str.length());
157:
158: for (int i = 0; i < str.length(); i++) {
159: char c = str.charAt(i);
160: boolean isIdentifierChar =
161: //(i == 0)
162: //? Character.isJavaIdentifierStart(c) :
163: Character.isJavaIdentifierPart(c);
164:
165: if (!isIdentifierChar) { //|| (c == '$')) {
166: sb.append('_');
167: } else {
168: sb.append(c);
169: }
170: }
171:
172: if ((sb.length() == 0) || isJavaKeyword(sb.toString())
173: || !Character.isJavaIdentifierStart(sb.charAt(0))) {
174:
175: // Some kind of clash; prefix underscore.
176: sb.insert(0, '_');
177: }
178:
179: return sb.toString();
180: }
181:
182: /**
183: * Is given string a Java reserved keyword?
184: *
185: * @param s the string to test to see if it is a reserved Java keyword
186: * @return <code>true</code> if the given string is a java keyword and
187: * <code>false</code> if it is not
188: */
189: public static boolean isJavaKeyword(String s) {
190: return JAVA_KEYWORD.contains(s);
191: }
192:
193: /**
194: * Returns a legal java identifier that is globally unique.
195: *
196: * @return the uid value
197: */
198: public static String getJUid() {
199:
200: StringBuffer buf = null;
201: String uid = getUid();
202: String prefix = "id_";
203:
204: buf = new StringBuffer(prefix.length() + uid.length());
205:
206: buf.append(prefix);
207:
208: char[] chars = uid.toCharArray();
209:
210: for (int i = 0; i < chars.length; i++) {
211: if (Character.isJavaIdentifierPart(chars[i])) {
212: buf.append(chars[i]);
213: } else {
214: buf.append('_');
215: }
216: }
217:
218: return buf.toString();
219: }
220:
221: /**
222: * Creates a String identifier t
223: * hat is globally unique. It is unique under
224: * the following conditions: a) Any generating machine takes more than one
225: * second to reboot. AND b) Any generating machine's clock is never set
226: * backward.
227: *
228: * @return The uid value
229: */
230: private static String mIP;
231:
232: public static String getUid() {
233: String uid = (new UID()).toString();
234:
235: try {
236: if (mIP == null) {
237: mIP = InetAddress.getLocalHost().toString();
238: }
239: } catch (UnknownHostException e) {
240: e.printStackTrace();
241: mIP = "localhost";
242: }
243: return mIP + "/" + uid;
244: }
245:
246: private static boolean isAlphaNum(char c) {
247: return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z')
248: || ('0' <= c && c <= '9');
249: }
250:
251: private static final char[] HEX_DIGIT = new char[] { '0', '1', '2',
252: '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
253: 'F' };
254:
255: /**
256: * notation Converts a character c to _uXXXX_ notation where XXXX is the unicode of c
257: * @param c character
258: * @return _uXXXX_ notationed string
259: */
260: private static String unicode(char c) {
261: StringBuffer sb = new StringBuffer();
262: sb.append("_u");
263: sb.append(HEX_DIGIT[(c >> 12) & 0xF]);
264: sb.append(HEX_DIGIT[(c >> 8) & 0xF]);
265: sb.append(HEX_DIGIT[(c >> 4) & 0xF]);
266: sb.append(HEX_DIGIT[c & 0xF]);
267: sb.append('_');
268: return sb.toString();
269: }
270:
271: public static String makeAlphaNumId(String s) {
272: StringBuffer sb = new StringBuffer();
273: for (int i = 0; i < s.length(); i++) {
274: char c = s.charAt(i);
275: if (isAlphaNum(c)) {
276: sb.append(c);
277: } else {
278: sb.append(unicode(c));
279: }
280: }
281: return sb.toString();
282: }
283:
284: public static String makeAlphaNumId(String[] s) {
285: StringBuffer sb = new StringBuffer();
286: for (int i = 0; i < s.length; i++) {
287: sb.append(makeAlphaNumId(s[i]));
288: if (i < s.length - 1) {
289: sb.append("_");
290: }
291: }
292: return sb.toString();
293: }
294:
295: // FIX ME: see LinkImpl.getTargetNameSpaceButUrn() for reason
296: public static String makeAlphaNumIdForLink(String[] s) {
297: StringBuffer sb = new StringBuffer();
298: for (int i = 0; i < s.length; i++) {
299: sb.append(makeAlphaNumId(s[i]));
300: if (i < s.length - 2) {
301: sb.append(".");
302: } else if (i == s.length - 2) {
303: sb.append("_");
304: }
305: }
306: return sb.toString();
307: }
308:
309: /**
310: * The main program for the GenUtil class
311: *
312: * @param args The command line arguments
313: */
314: public static void main(String[] args) {
315: StringBuffer sb = new StringBuffer();
316: for (int i = 0; i < args.length; i++) {
317: sb.append(" " + args[i]);
318: }
319: System.out.println(makeAlphaNumId(sb.toString()));
320: }
321:
322: }
|