KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > schema2beansdev > gen > JavaUtil


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.schema2beansdev.gen;
21
22 import java.util.*;
23 import java.io.*;
24
25 /**
26  * Various utility methods dealing with Java
27  */

28 public class JavaUtil {
29     // This class is not for instantiating.
30
private JavaUtil() {
31     }
32
33     /**
34      * Convert primitives into Objects and leave objects as is.
35      * @param expr the text expression representing some value
36      * @param classType the current type of @param expr
37      * ('age', 'int') -> 'new java.lang.Integer(age)'
38      * ('age', 'Integer') -> 'age'
39      */

40     static public String JavaDoc toObject(String JavaDoc expr, String JavaDoc classType) {
41         classType = classType.intern();
42         if ("boolean" == classType)
43             return "("+expr+" ? java.lang.Boolean.TRUE : java.lang.Boolean.FALSE)";
44         else {
45             String JavaDoc objClass = (String JavaDoc) toObjectType.get(classType);
46             if (objClass == null) {
47                 return expr;
48             }
49             return "new "+objClass+"("+expr+")";
50         }
51     }
52     static public String JavaDoc toObject(String JavaDoc expr, String JavaDoc classType, boolean j2me) {
53         if (j2me) {
54             if ("boolean".equals(classType))
55                 return "new java.lang.Boolean("+expr+")";
56         }
57         return toObject(expr, classType);
58     }
59     
60     static private Map toObjectType;
61     static {
62         toObjectType = new HashMap();
63         toObjectType.put("int", "java.lang.Integer");
64         toObjectType.put("char", "java.lang.Character");
65         toObjectType.put("long", "java.lang.Long");
66         toObjectType.put("short", "java.lang.Short");
67         toObjectType.put("byte", "java.lang.Byte");
68         toObjectType.put("float", "java.lang.Float");
69         toObjectType.put("double", "java.lang.Double");
70         toObjectType.put("boolean", "java.lang.Boolean");
71     }
72
73     /**
74      * Take a Java primitive and return it's object type.
75      * Return the same type if there isn't an object version.
76      */

77     static public String JavaDoc toObjectType(String JavaDoc classType) {
78         String JavaDoc objClass = (String JavaDoc) toObjectType.get(classType);
79         if (objClass == null)
80             return classType;
81         return objClass;
82     }
83
84     static private Map fromObjectType;
85     static {
86         fromObjectType = new HashMap();
87         fromObjectType.put("java.lang.Integer", "int");
88         fromObjectType.put("java.lang.Character", "char");
89         fromObjectType.put("java.lang.Long", "long");
90         fromObjectType.put("java.lang.Short", "short");
91         fromObjectType.put("java.lang.Byte", "byte");
92         fromObjectType.put("java.lang.Float", "float");
93         fromObjectType.put("java.lang.Double", "double");
94         fromObjectType.put("java.lang.Boolean", "boolean");
95         fromObjectType.put("Integer", "int");
96         fromObjectType.put("Character", "char");
97         fromObjectType.put("Long", "long");
98         fromObjectType.put("Short", "short");
99         fromObjectType.put("Byte", "byte");
100         fromObjectType.put("Float", "float");
101         fromObjectType.put("Double", "double");
102         fromObjectType.put("Boolean", "boolean");
103     }
104
105     /**
106      * Take a Java boxed object (like Integer) and return it's primitive type.
107      * Return the same type if there isn't a primitive version.
108      */

109     static public String JavaDoc fromObjectType(String JavaDoc classType) {
110         String JavaDoc objClass = (String JavaDoc) fromObjectType.get(classType);
111         if (objClass == null)
112             return classType;
113         return objClass;
114     }
115
116     /**
117      * Convert expr into a String. Similar to toObject.
118      * @param expr the value to convert into a String
119      * @param type is the name of the current type
120      * ('String', 'value') -> 'value'
121      * ('int', '42') -> '""+42'
122      * ('Integer', 'age') -> 'age.toString()'
123      */

124     static public String JavaDoc typeToString(String JavaDoc type, String JavaDoc expr) {
125         type = (type == null) ? null : type.intern();
126         if ("String" == type || "java.lang.String" == type)
127             return expr;
128         if (type == "java.util.Calendar")
129             return "java.text.DateFormat.getInstance().format("+expr+".getTime())"; // See JavaBeansUtil for correctly printing out XML Schema format
130
if (type == "boolean")
131             return expr+" ? \"true\" : \"false\"";
132         if (isPrimitiveType(type))
133             return "\"\"+"+expr;
134         return expr+".toString()";
135     }
136     
137     /**
138      * @param expr is an Object type, and we will convert it
139      * to a primitive.
140      * eg: ('java.lang.Double', expr) -> '(java.lang.Double) expr'
141      * eg: ('int', 'obj') -> '((java.lang.Integer)obj).intValue()'
142      */

143     static public String JavaDoc fromObject(String JavaDoc type, String JavaDoc expr) {
144         type = type.intern();
145         if (type == "int")
146             return "((java.lang.Integer)"+expr+").intValue()";
147         if (type == "long")
148             return "((java.lang.Long)"+expr+").longValue()";
149         if (type == "short")
150             return "((java.lang.Short)"+expr+").shortValue()";
151         if (type == "byte")
152             return "((java.lang.Byte)"+expr+").byteValue()";
153         if (type == "float")
154             return "((java.lang.Float)"+expr+").floatValue()";
155         if (type == "double")
156             return "((java.lang.Double)"+expr+").doubleValue()";
157         if (type == "char")
158             return "((java.lang.Character)"+expr+").charValue()";
159         if (type == "boolean")
160             return "((java.lang.Boolean)"+expr+").booleanValue()";
161         return "("+type+")"+expr;
162     }
163
164     /**
165      * Is @param className immutable? An immutable object can hold state,
166      * but after it's been constructed that state cannot change.
167      */

168     static public boolean isImmutable(String JavaDoc className) {
169         className = className.intern();
170         return immutableTable.containsKey(className);
171     }
172     static private Map immutableTable;
173     static {
174         immutableTable = new HashMap();
175         immutableTable.put("String", null);
176         immutableTable.put("java.lang.String", null);
177         immutableTable.put("int", null);
178         immutableTable.put("short", null);
179         immutableTable.put("long", null);
180         immutableTable.put("boolean", null);
181         immutableTable.put("char", null);
182         immutableTable.put("float", null);
183         immutableTable.put("double", null);
184         immutableTable.put("byte", null);
185         immutableTable.put("java.lang.Boolean", null);
186         immutableTable.put("java.lang.Byte", null);
187         immutableTable.put("java.lang.Character", null);
188         immutableTable.put("java.lang.Double", null);
189         immutableTable.put("java.lang.Float", null);
190         immutableTable.put("java.lang.Integer", null);
191         immutableTable.put("java.lang.Long", null);
192         immutableTable.put("java.lang.Short", null);
193         immutableTable.put("Boolean", null);
194         immutableTable.put("Byte", null);
195         immutableTable.put("Character", null);
196         immutableTable.put("Double", null);
197         immutableTable.put("Float", null);
198         immutableTable.put("Integer", null);
199         immutableTable.put("Long", null);
200         immutableTable.put("Short", null);
201         immutableTable.put("java.math.BigInteger", null);
202         immutableTable.put("java.math.BigDecimal", null);
203         immutableTable.put("javax.xml.namespace.QName", null);
204         immutableTable.put("org.netbeans.modules.schema2beans.QName", null);
205         immutableTable.put("java.net.URI", null);
206     }
207
208     /**
209      * Take a String (@param value) and generate Java code to coerce it.
210      * eg: ('String', "Hello") -> '"Hello"'
211      * ('int', '10') -> '10'
212      * ('Integer', '43') -> 'new Integer(43)'
213      * ('java.util.Locale', 'Locale.US') -> 'Locale.US'
214      */

215     public static String JavaDoc instanceFrom(String JavaDoc type, String JavaDoc value) {
216         if (type == null)
217             return value;
218         type = type.intern();
219         if (type == "java.lang.String" || type == "String") {
220             StringBuffer JavaDoc buf = new StringBuffer JavaDoc("\"");
221             for (int i = 0; i < value.length(); ++i) {
222                 char c = value.charAt(i);
223                 buf.append(escapeCharForInstance(c, '"'));
224             }
225             buf.append("\"");
226             return buf.toString();
227         }
228         if (type == "java.lang.Character" || type == "Character") {
229             return "new "+type+"("+instanceFrom("char", value)+")";
230         }
231         if (type == "Double" || type == "java.lang.Double" || type == "Integer" ||
232             type == "java.lang.Integer" || type == "Boolean" ||
233             type == "java.lang.Boolean" || type == "Float" ||
234             type == "java.lang.Float" || type == "Short" ||
235             type == "java.lang.Short" || type == "Long" ||
236             type == "java.lang.Long")
237             return "new "+type+"("+value+")";
238         if (type == "char[]" || type == "char []")
239             return instanceFrom("java.lang.String", value)+".toCharArray()";
240         if (type == "char") {
241             char c = value.charAt(0);
242             return "'"+escapeCharForInstance(c, '\'')+"'";
243         }
244         if (type == "float")
245             return value+"f";
246         if (type == "java.math.BigDecimal" || type == "java.math.BigInteger") {
247             // We will never need to escape anything inside value here.
248
return "new "+type+"(\""+value+"\")";
249         }
250         return value;
251     }
252
253     /**
254      * A helper method for instanceFrom. We escape 1 char at a time here.
255      */

256     public static String JavaDoc escapeCharForInstance(char c, char illegalChar) {
257         if (c == illegalChar)
258             return "\\"+illegalChar;
259         if (c == '\\')
260             return "\\\\";
261         if (c == '\b')
262             return "\\b";
263         if (c == '\t')
264             return "\\t";
265         if (c == '\n')
266             return "\\n";
267         if (c == '\f')
268             return "\\f";
269         if (c == '\r')
270             return "\\r";
271         if (c < ' ' || c > '\177')
272             return uencode(c);
273         return ""+c;
274     }
275
276     /**
277      * Convert @param value2 (a literal) to @param type1 and then
278      * compare that to @param value1.
279      * @return Java code in a String, that returns negative, 0, or positive
280      * if value1 < value2, value1 == value2, or value1 > value2.
281      *
282      * ("foo", "java.math.BigDecimal", "1") -> 'foo.compareTo(new java.math.BigDecimal("1"))'
283      */

284     public static String JavaDoc compareTo(String JavaDoc value1, String JavaDoc type1, String JavaDoc value2) {
285         type1 = type1.intern();
286         String JavaDoc value2Instance = genParseText(type1, value2);
287         if (isPrimitiveType(type1)) {
288             if ("\"0\"".equals(value2))
289                 return value1;
290             return value1+" - "+value2Instance;
291         }
292         return value1+".compareTo("+value2Instance+")";
293     }
294
295     /**
296      * Just like compareTo, but the second value (@param value2Text) is
297      * unquoted text.
298      */

299     public static String JavaDoc compareToText(String JavaDoc value1, String JavaDoc type1, String JavaDoc value2Text) {
300         type1 = type1.intern();
301         if (type1 == "int" || type1 == "short")
302             return value1+" - "+value2Text;
303         if (type1 == "long")
304             return value1+" - "+value2Text+"L";
305         if (type1 == "float")
306             return value1+" - "+value2Text+"f";
307         if (type1 == "double")
308             return value1+" - "+value2Text+"d";
309         return compareTo(value1, type1, instanceFrom("java.lang.String", value2Text));
310     }
311
312     public static String JavaDoc genParseText(String JavaDoc type, String JavaDoc expr, boolean j2me) {
313         if (j2me)
314             return genParseTextME(type, expr);
315         else
316             return genParseText(type, expr);
317     }
318
319     /**
320      * Take a particular @param type (eg: "java.lang.Integer") and return a
321      * String that will parse the @param expr and make it into that type.
322      * The value of @param expr should be a String.
323      * eg: ('java.lang.Integer', 'node.getNodeValue()')
324      * -> 'new java.lang.Integer(node.getNodeValue())'
325      */

326     public static String JavaDoc genParseText(String JavaDoc type, String JavaDoc expr) {
327         if (type == null)
328             return expr;
329         type = type.intern();
330         if (type == "java.lang.String" || type == "String")
331             return expr;
332         if (type == "boolean") {
333             // The XML Schema spec part 2, section 3.2.2 says a boolean can
334
// have any of these literal values: true, false, 1, 0.
335
return "(\"true\".equalsIgnoreCase("+expr+") || \"1\".equals("+expr+"))";
336             //return "java.lang.Boolean.valueOf("+expr+").booleanValue()";
337
}
338         if (type == "java.lang.Boolean" || type == "Boolean")
339             return genParseText("boolean", expr)+"? java.lang.Boolean.TRUE : java.lang.Boolean.FALSE";
340         if (type == "java.lang.Integer" || type == "Integer" || type == "java.lang.Long" || type == "Long" || type == "java.lang.Short" || type == "Short" || type == "java.lang.Float" || type == "Float" || type == "java.lang.Double" || type == "Double" || type == "java.lang.Byte" || type == "Byte" || type == "java.math.BigDecimal" || type == "BigDecimal" || type == "java.math.BigInteger" || type == "BigInteger" || type == "java.lang.StringBuffer" || type == "StringBuffer" || type == "java.text.MessageFormat" || type == "java.text.AttributedString" || type == "java.util.StringTokenizer" || type == "java.net.URI" || type == "javax.xml.namespace.QName" || type == "org.netbeans.modules.schema2beans.QName" || type == "java.io.File") { // NOI18N
341
return "new "+type+"("+expr+")"; // NOI18N
342
}
343         if (type == "java.lang.Character")
344             return "new java.lang.Character(("+expr+").charAt(0))";
345         if (type == "char[]" || type == "char []")
346             return "("+expr+").toCharArray()";
347         if (type == "long")
348             return "Long.parseLong("+expr+")";
349         if (type == "int")
350             return "Integer.parseInt("+expr+")";
351         if (type == "byte")
352             return "Byte.parseByte("+expr+")";
353         if (type == "short")
354             return "Short.parseShort("+expr+")";
355         if (type == "float")
356             return "Float.parseFloat("+expr+")";
357         if (type == "double")
358             return "Double.parseDouble("+expr+")";
359         if (type == "char")
360             return "("+expr+").charAt(0)";
361         if ("java.util.Date"== type)
362             return "java.text.DateFormat.getInstance().parse("+expr+")";
363         if ("javax.xml.soap.SOAPElement" == type)
364             return "javax.xml.soap.SOAPElementFactory.newInstance().create("+expr+").addTextNode("+expr+")"; // The parameter to create probably isn't quite correct.
365
// See JavaBeansUtil for correctly printing out XML Schema format of java.util.Calendar
366
return "/* UNKNOWN type for parsing:"+type+"*/ "+expr;
367     }
368
369     /**
370      * Take a particular @param type (eg: "java.lang.Integer") and return a
371      * String that will parse the @param expr and make it into that type.
372      * The value of @param expr should be a String.
373      * These work in *MIDP/J2ME*.
374      * eg: ('java.lang.Integer', 'node.getNodeValue()')
375      * -> 'new java.lang.Integer(node.getNodeValue())'
376      */

377     static public String JavaDoc genParseTextME(String JavaDoc type, String JavaDoc name) {
378         String JavaDoc parm = name;
379         type = type.intern();
380         if (type == "String" || type == "java.lang.String")
381             return parm;
382         else if (type == "int")
383             parm = "java.lang.Integer.parseInt(" + name + ")";
384         else if(type == "short")
385             parm = "java.lang.Short.parseShort(" + name + ")";
386         else if(type == "long")
387             parm = "java.lang.Long.parseLong(" + name + ")";
388         else if (type == "boolean")
389             parm = "(\"true\".equals("+name+") || \"1\".equals("+name+") || \"TRUE\".equals("+name+") || \"True\".equals("+name+"))";
390         else if (type == "char")
391             parm = name + ".charAt(0)";
392         else if ("char[]" == type)
393             parm = name+".toCharArray()";
394         else if ("java.lang.Integer" == type)
395             parm = "new java.lang.Integer("+genParseTextME("int", name)+")";
396         else if ("java.lang.Long" == type)
397             parm = "new java.lang.Long("+genParseTextME("long", name)+")";
398         else if ("java.lang.Boolean" == type) {
399             // The .TRUE or .FALSE trick doesn't seem to compile.
400
//parm = "("+genParseTextME("boolean", name)+") ? java.lang.Boolean.TRUE : java.lang.Boolean.FALSE";
401
parm = "new java.lang.Boolean("+genParseTextME("boolean", name)+")";
402         } else if (type == "double")
403             parm = "java.lang.Double.parseDouble(" + name + ")";
404         else if (type == "float")
405             parm = "java.lang.Float.parseFloat(" + name + ")";
406         else if (type == "byte")
407             parm = "java.lang.Byte.parseByte(" + name + ")";
408         else if ("java.lang.Short" == type)
409             parm = "new "+type+"("+genParseTextME("short", name)+")";
410         else if ("java.lang.Byte" == type)
411             parm = "new "+type+"("+genParseTextME("byte", name)+")";
412         else if ("java.lang.Double" == type
413                  || "java.lang.Float" == type
414                  || "java.lang.StringBuffer" == type
415                  || "java.math.BigInteger" == type
416                  || "java.math.BigDecimal" == type)
417             parm = "new "+type+"("+name+")";
418         /*
419         else if ("java.util.Date" == type)
420             parm = "???";
421         */

422         else if ("java.lang.Character" == type)
423             parm = "new "+type+"("+name+".charAt(0))";
424         return parm;
425     }
426
427     /**
428      * Take a particular @param type (eg: "java.lang.Integer") and return a
429      * String that will parse the @param expr, making it into that type,
430      * and storing the value into @param var.
431      * The value of @param expr should be a String.
432      */

433     public static String JavaDoc genParseText(String JavaDoc type, String JavaDoc expr, String JavaDoc var) {
434         return genParseText(type, expr, var, false);
435     }
436     
437     public static String JavaDoc genParseText(String JavaDoc type, String JavaDoc expr, String JavaDoc var,
438                                       boolean j2me) {
439         if (type == null)
440             return expr;
441         type = type.intern();
442         StringBuffer JavaDoc out = new StringBuffer JavaDoc();
443         if (type == "java.util.Calendar") {
444             // See JavaBeansUtil for correctly printing out XML Schema format of java.util.Calendar
445
out.append(var);
446             out.append(" = ");
447             out.append("java.util.Calendar.getInstance(); ");
448             out.append(var);
449             out.append(".setTime(java.text.DateFormat.getInstance().parse(");
450             out.append(expr);
451             out.append("));");
452         } else {
453             out.append(var);
454             out.append(" = ");
455             out.append(genParseText(type, expr, j2me));
456             out.append(";");
457         }
458         return out.toString();
459     }
460
461     /**
462      * What exceptions might we encounter from doing the result of
463      * genParseText. These exceptions are ones that we'd have to declare.
464      */

465     public static List exceptionsFromParsingText(String JavaDoc type) {
466         return exceptionsFromParsingText(type, true);
467     }
468     
469     public static List exceptionsFromParsingText(String JavaDoc type, boolean fromParsing) {
470         List result = new ArrayList();
471         if (type == null)
472             return result;
473         type = type.intern();
474         if (type == "java.net.URI")
475             result.add("java.net.URISyntaxException");
476         if (fromParsing && type == "java.util.Calendar")
477             result.add("java.text.ParseException");
478         return result;
479     }
480
481     public static boolean isPrimitiveType(String JavaDoc className) {
482         if (className == null)
483             return false;
484         className = className.intern();
485         return ("long" == className || "int" == className ||
486                 "char" == className || "short" == className ||
487                 "double" == className || "float" == className ||
488                 "byte" == className || "boolean" == className);
489     }
490
491     public static Class JavaDoc getPrimitive(String JavaDoc className) {
492         className = className.intern();
493         if (className == "int")
494             return Integer.TYPE;
495         if (className == "long")
496             return Long.TYPE;
497         if (className == "float")
498             return Float.TYPE;
499         if (className == "double")
500             return Double.TYPE;
501         if (className == "byte")
502             return Byte.TYPE;
503         if (className == "boolean")
504             return Boolean.TYPE;
505         if (className == "char")
506             return Character.TYPE;
507         if (className == "short")
508             return Short.TYPE;
509         if (className == "void")
510             return Void.TYPE;
511         return null;
512     }
513
514     public static boolean canProduceNoXMLMetaChars(String JavaDoc className) {
515         className = fromObjectType(className).intern();
516         return ("long" == className || "int" == className ||
517                 "short" == className ||
518                 "double" == className || "float" == className ||
519                 "byte" == className || "boolean" == className ||
520                 "java.math.BigDecimal" == className ||
521                 "java.math.BigInteger" == className);
522     }
523
524     public static String JavaDoc nullValueForType(String JavaDoc type) {
525         type = type.intern();
526         if (type == "long" || type == "int" || type == "short" || type == "char" || type == "byte")
527             return "0";
528         if (type == "double")
529             return "0.0";
530         if (type == "float")
531             return "0.0f";
532         if (type == "boolean")
533             return "false";
534         return "null";
535     }
536
537     /**
538      * @param type is the name of a class
539      * @return a default value for that type.
540      * eg: X -> new X()
541      * java.math.BigDecimal -> new java.math.BigDecimal("0")
542      * Integer -> new Integer("0")
543      */

544     public static String JavaDoc genNewDefault(String JavaDoc type) {
545         type = type.intern();
546         if ("java.lang.String" == type || "String" == type)
547             return "\"\"";
548         if (isPrimitiveType(type))
549             return nullValueForType(type);
550         if (type == "java.lang.Boolean" || type == "Boolean")
551             return "java.lang.Boolean.FALSE";
552         if (type == "java.lang.Integer" || type == "Integer" || type == "java.lang.Long" || type == "Long" || type == "java.lang.Short" || type == "Short" || type == "java.lang.Float" || type == "Float" || type == "java.lang.Double" || type == "Double" || type == "java.lang.Byte" || type == "Byte" || type == "java.math.BigInteger" || type == "BigInteger" || type == "java.math.BigDecimal" || type == "BigDecimal") { // NOI18N
553
return "new "+type+"(\"0\")"; // NOI18N
554
}
555         if (type == "java.net.URI" || type == "javax.xml.namespace.QName" || type == "org.netbeans.modules.schema2beans.QName")
556             return "new "+type+"(\"\")"; // NOI18N
557
if (type == "java.lang.Character")
558             return "new java.lang.Character('0')";
559         if (type == "java.util.Calendar")
560             return "java.util.Calendar.getInstance()";
561         if (type == "byte[]")
562             return "new byte[0]";
563         if (type == "org.w3c.dom.Element")
564             return "null"; // No default value
565
return "new "+type+"()";
566     }
567
568     /**
569      * Given a scalar type, figure out how to make it into an int
570      * (ie, hash code).
571      */

572     static public String JavaDoc exprToInt(String JavaDoc type, String JavaDoc expr) {
573         type = type.intern();
574         if (type == "boolean")
575             return expr+" ? 0 : 1";
576         else if (type == "byte" || type == "char" || type == "short")
577             return "(int) "+expr;
578         else if (type == "int")
579             return expr;
580         else if (type == "long")
581             return "(int)("+expr+"^("+expr+">>>32))";
582         else if (type == "float")
583             return "Float.floatToIntBits("+expr+")";
584         else if (type == "double")
585             return exprToInt("long", "Double.doubleToLongBits("+expr+")");
586         else
587             return "("+expr+").hashCode()";
588     }
589
590     /**
591      * @return an expression to compare to expressions; this can be put right
592      * into an if statement.
593      * ('int', 'var1', 'var2') -> 'var1 == var2'
594      * ('String', 'word', '"hello"') -> 'word == null ? "hello" == null : word.equals("hello")'
595      * ('float', 'var1', 'var2') -> 'Float.floatToIntBits(var1) == Float.floatToIntBits(var2)'
596      */

597     static public String JavaDoc genEquals(String JavaDoc type, String JavaDoc attr1, String JavaDoc attr2) {
598         return genEquals(type, attr1, attr2, true);
599     }
600
601     /**
602      * @param attr1CanBeNull whether or not attr1 could be null.
603      */

604     static public String JavaDoc genEquals(String JavaDoc type, String JavaDoc attr1, String JavaDoc attr2,
605                                    boolean attr1CanBeNull) {
606         type = type.intern();
607         if (type == "float") {
608             return "Float.floatToIntBits("+attr1+") == Float.floatToIntBits("+attr2+")";
609         } else if (type == "double") {
610             return "Double.doubleToLongBits("+attr1+") == Double.doubleToLongBits("+attr2+")";
611         } else if (isPrimitiveType(type)) {
612             return attr1+" == "+attr2;
613         } else if (attr1CanBeNull) {
614             return attr1+" == null ? "+attr2+" == null : "+attr1+".equals("+attr2+")";
615         } else {
616             return attr1+".equals("+attr2+")";
617         }
618     }
619
620     /**
621      * Looks for the class and sees if it's cloneable.
622      */

623     public static boolean isCloneable(String JavaDoc className) {
624         if (className == null)
625             return false;
626         className = className.intern();
627         if (className == "java.util.Calendar")
628             return true;
629         try {
630             //System.out.println("Looking for class: "+className);
631
Class JavaDoc cls = Class.forName(className);
632             if (cls == null)
633                 return false;
634             //System.out.println("Found it");
635
if (Cloneable JavaDoc.class.isAssignableFrom(cls)) {
636                 System.out.println(className+" is cloneable.");
637                 return true;
638             }
639             return false;
640         } catch (ClassNotFoundException JavaDoc e) {
641             return false;
642         }
643     }
644
645     /**
646      * Is the class not an interface and not abstract; i.e., it's possible
647      * to call a constructor on this class. (Note that primitives fail.)
648      */

649     public static boolean isInstantiable(String JavaDoc className) {
650         if (className == null)
651             return false;
652         className = className.intern();
653         if (className == "String" || className == "java.lang.String")
654             return true;
655         try {
656             //System.out.println("Looking for class: "+className);
657
Class JavaDoc cls = Class.forName(className);
658             if (cls == null)
659                 return false;
660             //System.out.println("Found it: result="+cls.isInterface());
661
if (cls.isInterface())
662                 return false;
663             if (java.lang.reflect.Modifier.isAbstract(cls.getModifiers()))
664                 return false;
665             return true;
666         } catch (ClassNotFoundException JavaDoc e) {
667             if (className.indexOf('.') < 0)
668                 return isInstantiable("java.lang."+className);
669             return false;
670         }
671     }
672
673     /**
674      * checkValueToType will make sure that a given value is
675      * acceptable for a given type. To make the problem more
676      * tractable, this is limited to simple types.
677      * eg:
678      * ("java.lang.Integer", "1") -> true
679      * ("java.lang.Integer", "1.5") -> false
680      * ("java.lang.String", "ksadjflkjas24#@") -> true
681      * ("short", "12345") -> true
682      * ("short", "123456") -> false
683      * Note that the 'tostr' template in javaGenLibrary.xsl has very
684      * similar code and any changes should be made there too.
685      */

686     public static boolean checkValueToType(String JavaDoc type, String JavaDoc value) {
687         //System.out.println("checkValueToType: type="+type+" value='"+value+"'");
688
// We try to convert it (just like how javaGenLibrary.xsl
689
// would generate code for). If an IllegalArgumentException
690
// is thrown, then it's the wrong value for that type.
691
try { // BEGIN_NOI18N
692
if ("java.lang.String".equals(type) || "char[]".equals(type)
693                 || "char []".equals(type) || "char".equals(type)
694                 || "Character".equals(type) || "String".equals(type)
695                 || "java.lang.Character".equals(type))
696                 return true;
697             else if ("long".equals(type))
698                 Long.parseLong(value);
699             else if ("int".equals(type))
700                 Integer.parseInt(value);
701             else if ("byte".equals(type))
702                 Byte.parseByte(value);
703             else if ("short".equals(type))
704                 Short.parseShort(value);
705             else if ("float".equals(type))
706                 Float.parseFloat(value);
707             else if ("double".equals(type))
708                 Double.parseDouble(value);
709             else if ("boolean".equals(type))
710                 Boolean.valueOf(value).booleanValue();
711             else if ("java.lang.Double".equals(type))
712                 new java.lang.Double JavaDoc(value);
713             else if ("java.lang.Integer".equals(type))
714                 new java.lang.Integer JavaDoc(value);
715             else if ("java.lang.Boolean".equals(type))
716                 Boolean.valueOf(value);
717             else if ("java.lang.Float".equals(type))
718                 new java.lang.Float JavaDoc(value);
719             else if ("java.lang.Short".equals(type))
720                 new java.lang.Short JavaDoc(value);
721             else if ("java.lang.Long".equals(type))
722                 new java.lang.Long JavaDoc(value);
723             else if ("java.math.BigDecimal".equals(type))
724                 new java.math.BigDecimal JavaDoc(value);
725             else if ("java.math.BigInteger".equals(type))
726                 new java.math.BigInteger JavaDoc(value);
727             else if ("java.lang.StringBuffer".equals(type))
728                 new java.lang.StringBuffer JavaDoc(value);
729             else if ("java.text.MessageFormat".equals(type))
730                 new java.text.MessageFormat JavaDoc(value);
731             else if ("java.text.AttributedString".equals(type))
732                 new java.text.AttributedString JavaDoc(value);
733             else if ("java.util.StringTokenizer".equals(type))
734                 new java.util.StringTokenizer JavaDoc(value);
735             else { // END_NOI18N
736
/*
737                 // Should do some reflection and see if a valueOf method
738                 // exists and takes a single String as an argument.
739                 Class clz = getClass(type);
740                 if (clz != null) {
741                     java.lang.reflect.Method meth =
742                         clz.getMethod("valueOf", new Class[] {String.class});
743                     if (meth == null || !Modifier.isStatic(meth.getModifiers())) {
744                         return false;
745                     }
746                 } else {
747                     return false;
748                 }
749                 // Could try to invoke the method too, but do we
750                 // really want to invoke a method from some random class.
751                  */

752                 if ("".equals(value)) // NOI18N
753
return false; // Hack, should check value
754
return true; // for now
755
}
756         } catch (IllegalArgumentException JavaDoc e) {
757             return false;
758         /*
759         } catch (java.lang.ClassNotFoundException e) {
760             LogFlags.lgr.println(LogFlags.DEBUG, LogFlags.module,
761                                  LogFlags.DBG_VALIDATE, 100,
762                                  "checkValueToType got ClassNotFoundException for type='"+type+"' value='"+value+"'");
763             return false;
764         } catch (NoSuchMethodException e) {
765             LogFlags.lgr.println(LogFlags.DEBUG, LogFlags.module,
766                                  LogFlags.DBG_VALIDATE, 100,
767                                  "checkValueToType got NoSuchMethodException for type='"+type+"' value='"+value+"'");
768             return false;
769          */

770         }
771         return true;
772     }
773
774     static public String JavaDoc baseClassOfArray(String JavaDoc className) {
775         // Does this handle more than 1 dimensional arrays correctly
776
if (className.startsWith("[L") && className.endsWith(";")) { // NOI18N
777
return className.substring(2, className.length()-1);
778         }
779         return className.substring(0, className.length()-2);
780     }
781
782     /**
783      * This will return a name from @param fullClassName where everything upto
784      * and including the last '.' is removed.
785      * eg: "java.lang.String[]" -> "String[]"
786      * "java.util.ArrayList" -> "ArrayList"
787      */

788     static public String JavaDoc baseName(String JavaDoc fullClassName) {
789         int pos = fullClassName.lastIndexOf('.');
790         if (pos == -1)
791             return fullClassName;
792         return fullClassName.substring(pos+1, fullClassName.length());
793     }
794
795     private static final Class JavaDoc charArrayClass =
796         java.lang.reflect.Array.newInstance(java.lang.Character.TYPE, 0).getClass();
797
798     static public String JavaDoc getCanonicalClassName(Class JavaDoc cls) {
799         if (charArrayClass.isAssignableFrom(cls))
800             return "char[]"; // NOI18N
801
if (cls.isArray())
802             return baseClassOfArray(cls.getName())+"[]";
803         return cls.getName();
804     }
805
806     static public int getOptimialHashMapSize(Object JavaDoc[] keys) {
807         return getOptimialHashMapSize(keys, keys.length * 8);
808     }
809
810     /**
811      * Using reflection figure out the optimal initial capacity for a
812      * HashMap given some keys. This uses a load factor of 1.0f.
813      * By optimal, the table does not need resizing and there are
814      * no lists (or chaining) being done in a HashMap.Entry.
815      *
816      * @param maxSize the point at which to give up (the maximum size to try)
817      */

818     static public int getOptimialHashMapSize(Object JavaDoc[] keys, int maxSize) {
819         int keyLength = keys.length;
820         int defaultAnswer = keyLength + 1;
821         try {
822             java.lang.reflect.Field JavaDoc tableField = HashMap.class.getDeclaredField("table");
823             tableField.setAccessible(true);
824             for (int tableSize = keyLength + 1; tableSize <= maxSize;
825                  tableSize <<= 1) {
826                 //System.out.println("tableSize="+tableSize);
827
HashMap map = new HashMap(tableSize, 1.0f);
828                 for (int k = 0; k < keyLength; ++k) {
829                     map.put(keys[k], null);
830                 }
831                 Object JavaDoc[] table = (Object JavaDoc[]) tableField.get(map);
832                 int nullCount = 0;
833                 for (int i = 0; i < table.length; ++i) {
834                     //System.out.println("table["+i+"]="+table[i]);
835
if (table[i] == null)
836                         ++nullCount;
837                 }
838                 //System.out.println("nullCount="+nullCount);
839
if (table.length - nullCount != keyLength) {
840                     //System.out.println("A list had begun.");
841
continue;
842                 }
843                 return table.length;
844             }
845         } catch (java.lang.IllegalAccessException JavaDoc e) {
846             return defaultAnswer;
847         } catch (java.lang.NoSuchFieldException JavaDoc e) {
848             return defaultAnswer;
849         }
850         return defaultAnswer;
851     }
852
853     // Convert the @param in stream using native2ascii, assuming it's already
854
// UTF-8 encoded.
855
static public void native2ascii(Writer out, Reader in) throws java.io.IOException JavaDoc {
856         FilterWriter n2afilter = new N2AFilter(out);
857         copyStream(n2afilter, in);
858     }
859
860     static public class N2AFilter extends FilterWriter {
861         public N2AFilter(Writer writer) {
862             super(writer);
863         }
864
865         public void write(char[] cbuf) throws IOException {
866             write(cbuf, 0, cbuf.length);
867         }
868
869         public void write(int c) throws IOException {
870             write((char) c);
871         }
872
873         public void write(char c) throws IOException {
874             //System.out.println("c="+c);
875
if(c > '\177') {
876                 out.write(uencode(c));
877             } else {
878                 out.write(c);
879             }
880         }
881
882         public void write(char ac[], int off, int len) throws IOException {
883             int end = off+len;
884             for (int k = off; k < end; k++) {
885                 write(ac[k]);
886             }
887         }
888
889         public void write(String JavaDoc str) throws IOException {
890             write(str.toCharArray(), 0, str.length());
891         }
892
893         public void write(String JavaDoc str, int off, int len) throws IOException {
894             write(str.toCharArray(), off, len);
895         }
896     }
897
898     /**
899      * Take a character and return the \ u (Unicode) representation of it.
900      */

901     public static String JavaDoc uencode(char c) {
902         StringBuffer JavaDoc result = new StringBuffer JavaDoc("\\u");
903         String JavaDoc s1 = Integer.toHexString(c);
904         StringBuffer JavaDoc stringbuffer = new StringBuffer JavaDoc(s1);
905         stringbuffer.reverse();
906         int l = 4 - stringbuffer.length();
907         for(int i1 = 0; i1 < l; i1++)
908             stringbuffer.append('0');
909         
910         for(int j1 = 0; j1 < 4; j1++)
911             result.append(stringbuffer.charAt(3 - j1));
912         return result.toString();
913     }
914
915     public static final int BUFFER_SIZE = 4096;
916     /**
917      * copyStream is not really a Java Utility method, but it's needed by
918      * one of them, and so is here.
919      * @return the total length of the stream (in char's) copied.
920      */

921     public static int copyStream(Writer out, Reader in) throws java.io.IOException JavaDoc {
922         int len;
923         int totalLength = 0;
924         char[] buf = new char[BUFFER_SIZE];
925         while ((len = in.read(buf, 0, BUFFER_SIZE)) != -1) {
926             out.write(buf, 0, len);
927             totalLength += len;
928         }
929         out.flush();
930         return totalLength;
931     }
932
933     /**
934      * copyStream is not really a Java Utility method, but it's needed by
935      * one of them, and so is here.
936      * @return the total length of the stream (in char's) copied.
937      */

938     public static int copyStream(OutputStream out, InputStream in) throws java.io.IOException JavaDoc {
939         int len;
940         int totalLength = 0;
941         byte[] buf = new byte[BUFFER_SIZE];
942         while ((len = in.read(buf, 0, BUFFER_SIZE)) != -1) {
943             out.write(buf, 0, len);
944             totalLength += len;
945         }
946         out.flush();
947         return totalLength;
948     }
949
950     static public class InputMonitor implements Runnable JavaDoc {
951         private InputStream is;
952         private OutputStream out;
953         
954         public InputMonitor(InputStream is, OutputStream out) {
955             this.is = is;
956             this.out = out;
957         }
958
959         /**
960          * Copy the contents of the InputStream to the Writer.
961          * Remember to close the InputStream or else this Thread will
962          * never end.
963          */

964         public void run() {
965             //System.out.println("Starting InputMonitor thread");
966
try {
967                 int c;
968                 while ((c = is.read()) != -1) {
969                     byte ch = (byte)c;
970                     out.write(ch);
971                 }
972                 out.flush();
973             } catch (java.io.IOException JavaDoc e) {
974                 try {
975                     out.write(e.getMessage().getBytes());
976                 } catch (java.io.IOException JavaDoc e2) {
977                     // try only once.
978
}
979             }
980             //System.out.println("Finished InputMonitor thread");
981
}
982     }
983
984     private static Map reservedWords;
985     static {
986         reservedWords = new HashMap();
987         reservedWords.put("abstract", "_abstract");
988         reservedWords.put("assert", "_assert");
989         reservedWords.put("boolean", "_boolean");
990         reservedWords.put("break", "_break");
991         reservedWords.put("byte", "_byte");
992         reservedWords.put("case", "_case");
993         reservedWords.put("catch", "_catch");
994         reservedWords.put("char", "_char");
995         reservedWords.put("class", "_class");
996         reservedWords.put("const", "_const");
997         reservedWords.put("continue", "_continue");
998         reservedWords.put("default", "_default");
999         reservedWords.put("do", "_do");
1000        reservedWords.put("double", "_double");
1001        reservedWords.put("else", "_else");
1002        reservedWords.put("extends", "_extends");
1003        reservedWords.put("false", "_false");
1004        reservedWords.put("final", "_final");
1005        reservedWords.put("finally", "_finally");
1006        reservedWords.put("float", "_float");
1007        reservedWords.put("for", "_for");
1008        reservedWords.put("goto", "_goto");
1009        reservedWords.put("if", "_if");
1010        reservedWords.put("implements", "_implements");
1011        reservedWords.put("import", "_import");
1012        reservedWords.put("instanceof", "_instanceof");
1013        reservedWords.put("int", "_int");
1014        reservedWords.put("interface", "_interface");
1015        reservedWords.put("long", "_long");
1016        reservedWords.put("native", "_native");
1017        reservedWords.put("new", "_new");
1018        reservedWords.put("null", "_null");
1019        reservedWords.put("package", "_package");
1020        reservedWords.put("private", "_private");
1021        reservedWords.put("protected", "_protected");
1022        reservedWords.put("public", "_public");
1023        reservedWords.put("return", "_return");
1024        reservedWords.put("short", "_short");
1025        reservedWords.put("static", "_static");
1026        reservedWords.put("strictfp", "_strictfp");
1027        reservedWords.put("super", "_super");
1028        reservedWords.put("switch", "_switch");
1029        reservedWords.put("synchronized", "_synchronized");
1030        reservedWords.put("this", "_this");
1031        reservedWords.put("throw", "_throw");
1032        reservedWords.put("throws", "_throws");
1033        reservedWords.put("transient", "_transient");
1034        reservedWords.put("true", "_true");
1035        reservedWords.put("try", "_try");
1036        reservedWords.put("void", "_void");
1037        reservedWords.put("volatile", "_volatile");
1038        reservedWords.put("while", "_while");
1039    }
1040    public static boolean reservedWord(String JavaDoc name) {
1041        return reservedWords.containsKey(name);
1042    }
1043}
1044
Popular Tags