1 19 20 package org.netbeans.modules.schema2beans; 21 22 import java.io.*; 23 import java.beans.*; 24 import java.lang.reflect.*; 25 import java.util.*; 26 import java.text.*; 27 import org.w3c.dom.*; 28 29 38 public class JavaBeansUtil { 39 private JavaBeansUtil() {} 40 41 48 public static void writeBeanProperty(Object obj, Writer out, String propertyName) throws IOException, java.beans.IntrospectionException { 49 BeanWriter beanOut = new XmlBeanWriter(out); 50 writeBeanProperty(obj, beanOut, propertyName); 51 } 52 53 57 public static void writeBeanProperty(Object obj, BeanWriter out, String propertyName) throws IOException, java.beans.IntrospectionException { 58 writeBeanProperty(obj, out, new HashMap(), propertyName); 59 } 60 61 64 public static interface BeanWriter { 65 public void beginPropertyName(String propertyName) throws IOException; 66 public void endPropertyName(String propertyName) throws IOException; 67 public void writeLeafObject(Object obj) throws IOException; 68 public void beginInnerNode() throws IOException; 69 public void endInnerNode() throws IOException; 70 } 71 72 75 public static abstract class IndentingBeanWriter implements BeanWriter { 76 protected String indentBy; 77 protected String indent; 78 protected int indentLevel = 0; 79 protected List indentions; 80 81 public IndentingBeanWriter() { 82 this("", "\t"); 83 } 84 85 public IndentingBeanWriter(String indentBy) { 86 this("", indentBy); 87 } 88 89 public IndentingBeanWriter(String indent, String indentBy) { 90 this.indent = indent; 91 this.indentBy = indentBy; 92 this.indentions = new ArrayList(); 93 this.indentions.add(indent); } 95 96 public void beginInnerNode() throws IOException { 97 ++indentLevel; 98 int indentionsSize = indentions.size(); 99 if (indentionsSize <= indentLevel) { 100 indent = (String ) indentions.get(indentionsSize-1); 101 do { 102 indent += indentBy; 103 indentions.add(indent); 104 ++indentionsSize; 105 } while (indentionsSize <= indentLevel); 106 } else { 107 indent = (String ) indentions.get(indentLevel); 108 } 109 } 110 111 public void endInnerNode() throws IOException { 112 --indentLevel; 113 indent = (String ) indentions.get(indentLevel); 114 } 115 } 116 117 public static class XmlBeanWriter extends IndentingBeanWriter implements BeanWriter { 118 protected Writer out; 119 120 public XmlBeanWriter(Writer out) { 121 super(); 122 this.out = out; 123 } 124 125 public XmlBeanWriter(Writer out, String indentBy) { 126 super(indentBy); 127 this.out = out; 128 } 129 130 public XmlBeanWriter(Writer out, String indent, String indentBy) { 131 super(indent, indentBy); 132 this.out = out; 133 } 134 135 public void beginPropertyName(String propertyName) throws IOException { 136 out.write(indent); 137 out.write("<"+propertyName+">"); 138 } 139 140 public void endPropertyName(String propertyName) throws IOException { 141 out.write("</"+propertyName+">\n"); 142 } 143 144 public void writeLeafObject(Object obj) throws IOException { 145 XMLUtil.printXML(out, obj.toString(), false); 146 } 147 148 public void beginInnerNode() throws IOException { 149 super.beginInnerNode(); 150 out.write("\n"); 151 } 152 153 public void endInnerNode() throws IOException { 154 super.endInnerNode(); 155 out.write(indent); 156 } 157 } 158 159 public static class HtmlBeanWriter extends IndentingBeanWriter implements BeanWriter { 160 protected Writer out; 161 162 public HtmlBeanWriter(Writer out) { 163 super(); 164 this.out = out; 165 } 166 167 public HtmlBeanWriter(Writer out, String indentBy) { 168 super(indentBy); 169 this.out = out; 170 } 171 172 public HtmlBeanWriter(Writer out, String indent, String indentBy) { 173 super(indent, indentBy); 174 this.out = out; 175 } 176 177 public void beginPropertyName(String propertyName) throws IOException { 178 out.write(indent); 179 out.write("<tr>"); 180 out.write("<th>"+propertyName+"</th>"); 181 } 182 183 public void endPropertyName(String propertyName) throws IOException { 184 out.write("</tr>"); 185 out.write("\n"); 186 } 187 188 public void writeLeafObject(Object obj) throws IOException { 189 out.write("<td>"); 191 XMLUtil.printXML(out, obj.toString(), false); 192 out.write("</td>"); 193 } 194 195 public void beginInnerNode() throws IOException { 196 super.beginInnerNode(); 197 out.write("<td><table width=\"100%\" border=\"1\">"); 199 out.write("\n"); 200 } 201 202 public void endInnerNode() throws IOException { 203 super.endInnerNode(); 204 out.write(indent); 205 out.write("</table></td>"); 206 } 207 } 208 209 public static void writeBeanProperty(Object obj, BeanWriter out, Map skipChildren, String propertyName) throws IOException, java.beans.IntrospectionException { 210 if (obj == null) 211 return; 212 out.beginPropertyName(propertyName); 213 if (!isJavaBeanType(obj.getClass())) { 214 out.writeLeafObject(obj); 216 } else { 217 out.beginInnerNode(); 219 writeBean(obj, out, skipChildren); 220 out.endInnerNode(); 221 } 222 out.endPropertyName(propertyName); 223 } 224 225 229 public static void writeBean(Object obj, Writer out) throws IOException, java.beans.IntrospectionException { 230 BeanWriter beanOut = new XmlBeanWriter(out); 231 writeBean(obj, beanOut); 232 } 233 234 public static void writeBean(Object obj, BeanWriter out) throws IOException, java.beans.IntrospectionException { 235 writeBean(obj, out, new HashMap()); 236 } 237 238 public static void writeBean(Object obj, BeanWriter out, Map skipChildren) throws IOException, java.beans.IntrospectionException { 239 if (obj == null) 241 return; 242 if (skipChildren.containsKey(obj)) 244 return; 245 skipChildren.put(obj, null); 246 247 Class objCls = obj.getClass(); 248 258 259 BeanInfo bi = Introspector.getBeanInfo(objCls); 260 PropertyDescriptor[] pds = bi.getPropertyDescriptors(); 261 for (int i = 0 ; i < pds.length; ++i) { 262 PropertyDescriptor pd = pds[i]; 263 Method reader = pd.getReadMethod(); 264 if (reader == null) 265 continue; 266 Class propertyType = pd.getPropertyType(); 267 String propertyName = pd.getName(); 268 Class declaringClass = reader.getDeclaringClass(); 271 if (declaringClass.equals(Object .class)) 274 continue; 275 if (propertyType == null) 276 continue; 277 Object childObj = null; 278 try { 279 childObj = reader.invoke(obj, null); 280 } catch (java.lang.reflect.InvocationTargetException e) { 281 e.printStackTrace(); 282 } catch (java.lang.IllegalAccessException e) { 283 e.printStackTrace(); 284 } 285 if (childObj != null) { 286 if (childObj instanceof Collection) { 287 Iterator it = ((Collection)childObj).iterator(); 289 while (it.hasNext()) { 290 Object childElement = it.next(); 291 writeBeanProperty(childElement, out, skipChildren, 292 propertyName); 293 } 294 } else if (childObj.getClass().isArray()) { 295 int size = Array.getLength(childObj); 297 for (int j = 0; j < size; ++j) { 298 Object childElement = Array.get(childObj, j); 299 writeBeanProperty(childElement, out, skipChildren, 300 propertyName); 301 } 302 } else { 303 writeBeanProperty(childObj, out, skipChildren, 304 propertyName); 305 } 306 } 307 } 308 skipChildren.remove(obj); 309 } 310 311 317 public static Object readBean(Class cls, java.io.InputStream in) throws javax.xml.parsers.ParserConfigurationException , org.xml.sax.SAXException , java.io.IOException , java.beans.IntrospectionException , java.lang.NoSuchMethodException , java.lang.InstantiationException , java.lang.IllegalAccessException , java.lang.reflect.InvocationTargetException { 318 Constructor construct = cls.getConstructor(new Class [0]); 319 Object newValue = construct.newInstance(new Object [0]); 320 readBean(newValue, in); 321 return newValue; 322 } 323 324 330 public static void readBean(Object obj, java.io.InputStream in) throws javax.xml.parsers.ParserConfigurationException , org.xml.sax.SAXException , java.io.IOException , java.beans.IntrospectionException { 331 readBean(obj, new org.xml.sax.InputSource (in), false, null, null); 332 } 333 334 340 public static void readBeanNoEntityResolver(Object obj, java.io.InputStream in) throws javax.xml.parsers.ParserConfigurationException , org.xml.sax.SAXException , java.io.IOException , java.beans.IntrospectionException { 341 readBean(obj, new org.xml.sax.InputSource (in), false, 342 new org.xml.sax.EntityResolver () { 343 public org.xml.sax.InputSource resolveEntity(String publicId, String systemId) { 344 java.io.ByteArrayInputStream bin = new java.io.ByteArrayInputStream (new byte[0]); 345 return new org.xml.sax.InputSource (bin); 346 } 347 } 348 , null); 349 } 350 351 public static void readBean(Object obj, org.xml.sax.InputSource in, boolean validate, org.xml.sax.EntityResolver er, org.xml.sax.ErrorHandler eh) throws javax.xml.parsers.ParserConfigurationException , org.xml.sax.SAXException , java.io.IOException , java.beans.IntrospectionException { 352 javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance(); 353 dbf.setValidating(validate); 354 javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); 355 if (er != null) db.setEntityResolver(er); 356 if (eh != null) db.setErrorHandler(eh); 357 org.w3c.dom.Document doc = db.parse(in); 358 readBean(obj, doc); 359 } 360 361 367 public static Object readBean(Class cls, org.w3c.dom.Document document) throws java.beans.IntrospectionException , java.lang.NoSuchMethodException , java.lang.InstantiationException , java.lang.IllegalAccessException , java.lang.reflect.InvocationTargetException { 368 Constructor construct = cls.getConstructor(new Class [0]); 369 Object newValue = construct.newInstance(new Object [0]); 370 readBean(newValue, document); 371 return newValue; 372 } 373 374 380 public static void readBean(Object obj, org.w3c.dom.Document document) throws java.beans.IntrospectionException { 381 readBean(obj, document.getDocumentElement()); 382 } 383 384 public static void readBean(Object obj, Node node) throws java.beans.IntrospectionException { 385 if (obj == null) 386 return; 387 int errorCount = 0; 388 Class objCls = obj.getClass(); 389 BeanInfo bi = Introspector.getBeanInfo(objCls); 390 PropertyDescriptor[] pds = bi.getPropertyDescriptors(); 391 Map propertyWriters = new HashMap(); Map propertyTypes = new HashMap(); for (int i = 0 ; i < pds.length; ++i) { 394 PropertyDescriptor pd = pds[i]; 395 Method writer = pd.getWriteMethod(); 396 if (writer == null) 397 continue; 398 Class propertyType = pd.getPropertyType(); 399 String propertyName = pd.getName(); 400 Class declaringClass = writer.getDeclaringClass(); 401 if (declaringClass == null || declaringClass.equals(Object .class)) 403 continue; 404 if (propertyType == null) 405 continue; 406 propertyWriters.put(propertyName, writer); 407 propertyTypes.put(propertyName, propertyType); 408 } 409 410 Map propertiesNewValues = new HashMap(); 411 if (node.hasAttributes()) { 412 org.w3c.dom.NamedNodeMap attrs = node.getAttributes(); 413 for (int i = 0; i < attrs.getLength(); ++i) { 414 Attr attr = (Attr) attrs.item(i); 415 String attrName = attr.getName(); 416 if (!propertyWriters.containsKey(attrName)) { 417 attrName = Common.convertName(attrName); 418 if (!propertyWriters.containsKey(attrName)) { 419 attrName = Introspector.decapitalize(attrName); 420 if (!propertyWriters.containsKey(attrName)) { 421 ++errorCount; 422 System.out.println("Found attribute and did not find property in Java Bean: "+attr.getName()); 423 continue; 424 } 425 } 426 } 427 Object newValue = convertValue((Class )propertyTypes.get(attrName), 428 attr.getValue()); 429 propertiesNewValues.put(attrName, newValue); 430 } 431 } 432 org.w3c.dom.NodeList children = node.getChildNodes(); 433 for (int i = 0, size = children.getLength(); i < size; ++i) { 434 org.w3c.dom.Node childNode = children.item(i); 435 if (!(childNode instanceof Element)) 436 continue; 437 String childNodeName = (childNode.getLocalName() == null ? childNode.getNodeName().intern() : childNode.getLocalName().intern()); 438 if (!propertyWriters.containsKey(childNodeName)) { 440 childNodeName = Common.convertName(childNodeName); 441 if (!propertyWriters.containsKey(childNodeName)) { 442 childNodeName = Introspector.decapitalize(childNodeName); 443 if (!propertyWriters.containsKey(childNodeName)) { 444 ++errorCount; 445 System.out.println("Found element and did not find property in Java Bean: "+childNode.getNodeName()); 446 continue; 447 } 448 } 449 } 450 Class propertyType = (Class ) propertyTypes.get(childNodeName); 451 Object newValue = null; 452 if (isJavaBeanType(propertyType)) { 453 Class propertyTypeOnce = propertyType; 454 if (propertyType.isArray()) 455 propertyTypeOnce = propertyType.getComponentType(); 456 try { 457 Constructor construct = propertyTypeOnce.getConstructor(new Class [0]); 459 newValue = construct.newInstance(new Object [0]); 460 readBean(newValue, childNode); 461 } catch (java.lang.NoSuchMethodException e) { 462 e.printStackTrace(); 463 ++errorCount; 464 } catch (java.lang.InstantiationException e) { 465 e.printStackTrace(); 466 ++errorCount; 467 } catch (java.lang.IllegalAccessException e) { 468 e.printStackTrace(); 469 ++errorCount; 470 } catch (java.lang.reflect.InvocationTargetException e) { 471 e.printStackTrace(); 472 ++errorCount; 473 } 474 } else { 475 String nodeValue; 476 if (childNode.getFirstChild() == null) 477 nodeValue = ""; 478 else 479 nodeValue = childNode.getFirstChild().getNodeValue(); 480 Class typeOfNewValue = propertyType; 481 if (propertyType.isArray()) 482 typeOfNewValue = propertyType.getComponentType(); 483 newValue = convertValue(typeOfNewValue, nodeValue); 484 } 485 if (propertyType.isArray()) { 487 List values = (List) propertiesNewValues.get(childNodeName); 488 if (values == null) { 489 values = new ArrayList(); 490 propertiesNewValues.put(childNodeName, values); 491 } 492 values.add(newValue); 493 } else { 494 propertiesNewValues.put(childNodeName, newValue); 495 } 496 } 497 498 for (Iterator it = propertiesNewValues.keySet().iterator(); 499 it.hasNext(); ) { 500 String propertyName = (String ) it.next(); 501 Class propertyType = (Class ) propertyTypes.get(propertyName); 502 Method writer = (Method) propertyWriters.get(propertyName); 503 504 Object newValue; 506 if (propertyType.isArray()) { 507 List values = (List) propertiesNewValues.get(propertyName); 509 newValue = Array.newInstance(propertyType.getComponentType(), 510 values.size()); 511 for (int i = 0; i < values.size(); ++i) { 513 Array.set(newValue, i, values.get(i)); 515 } 516 } else { 517 newValue = propertiesNewValues.get(propertyName); 518 } 519 520 try { 522 writer.invoke(obj, new Object [] {newValue}); 523 } catch (java.lang.reflect.InvocationTargetException e) { 524 e.printStackTrace(); 525 ++errorCount; 526 } catch (java.lang.IllegalAccessException e) { 527 e.printStackTrace(); 528 ++errorCount; 529 } 530 } 531 } 532 533 534 538 public static void copyBean(Object src, Object dest) throws java.beans.IntrospectionException { 539 copyBean(src, dest, Collections.EMPTY_MAP); 540 } 541 542 548 public static void copyBean(Object src, Object dest, Map nameMapping) throws java.beans.IntrospectionException { 549 if (src == null) 550 return; 551 Class srcCls = src.getClass(); 552 BeanInfo bi = Introspector.getBeanInfo(srcCls); 553 PropertyDescriptor[] pds = bi.getPropertyDescriptors(); 554 Map propertyReaders = new HashMap(); Map propertyTypes = new HashMap(); for (int i = 0 ; i < pds.length; ++i) { 557 PropertyDescriptor pd = pds[i]; 558 Method reader = pd.getReadMethod(); 559 if (reader == null) 560 continue; 561 Class propertyType = pd.getPropertyType(); 562 String propertyName = pd.getName(); 563 Class declaringClass = reader.getDeclaringClass(); 564 if (declaringClass == null || declaringClass.equals(Object .class)) 566 continue; 567 if (propertyType == null) 568 continue; 569 if (nameMapping.containsKey(propertyName)) 570 propertyName = (String ) nameMapping.get(propertyName); 571 propertyReaders.put(propertyName, reader); 572 propertyTypes.put(propertyName, propertyType); 573 } 574 575 Class destCls = dest.getClass(); 576 bi = Introspector.getBeanInfo(destCls); 577 pds = bi.getPropertyDescriptors(); 578 for (int i = 0 ; i < pds.length; ++i) { 579 PropertyDescriptor pd = pds[i]; 580 Method writer = pd.getWriteMethod(); 581 if (writer == null) 582 continue; 583 Class propertyType = pd.getPropertyType(); 584 String propertyName = pd.getName(); 585 Class declaringClass = writer.getDeclaringClass(); 586 if (declaringClass == null || declaringClass.equals(Object .class)) 587 continue; 588 if (propertyType == null) 589 continue; 590 if (propertyReaders.containsKey(propertyName)) { 591 try { 594 Method reader = (Method) propertyReaders.get(propertyName); 595 Object srcValue = reader.invoke(src, null); 596 if (isJavaBeanType(propertyType)) { 598 Class propertyTypeOnce = propertyType; 599 int size = 1; 600 Object destValue = null; 601 if (propertyType.isArray()) { 602 propertyTypeOnce = propertyType.getComponentType(); 603 size = Array.getLength(srcValue); 604 destValue = Array.newInstance(propertyTypeOnce, size); 605 } 606 for (int index = 0; index < size; ++index) { 607 Constructor construct = propertyTypeOnce.getConstructor(new Class [0]); 608 Object srcValueOnce; 609 Object destValueOnce = construct.newInstance(new Object [0]); 610 if (propertyType.isArray()) { 611 Array.set(destValue, index, destValueOnce); 612 srcValueOnce = Array.get(srcValue, index); 613 } else { 614 destValue = destValueOnce; 615 srcValueOnce = srcValue; 616 } 617 copyBean(srcValueOnce, destValueOnce, nameMapping); 618 } 621 writer.invoke(dest, new Object [] {destValue}); 622 } else if (propertyType.isAssignableFrom((Class )propertyTypes.get(propertyName))) { 623 writer.invoke(dest, new Object [] {srcValue}); 624 } else { 625 continue; 627 } 628 } catch (java.lang.IllegalAccessException e) { 629 e.printStackTrace(); 630 } catch (java.lang.reflect.InvocationTargetException e) { 631 e.printStackTrace(); 632 } catch (java.lang.NoSuchMethodException e) { 633 e.printStackTrace(); 634 } catch (java.lang.InstantiationException e) { 635 e.printStackTrace(); 636 } 637 } 638 } 639 } 640 641 647 public static boolean isJavaBeanType(Class type) { 648 if (Collection.class.isAssignableFrom(type)) 649 return false; 650 if (type.isArray()) { 651 return isJavaBeanType(type.getComponentType()); 652 } 653 String typeName = type.getName().intern(); 654 if (typeName == "java.lang.String"|| 655 typeName == "java.lang.Integer"|| typeName == "int" || 656 typeName == "java.lang.Character"|| typeName == "char" || 657 typeName == "java.lang.Long"|| typeName == "long" || 658 typeName == "java.lang.Float"|| typeName == "float" || 659 typeName == "java.lang.Double"|| typeName == "double" || 660 typeName == "java.lang.Boolean"|| typeName == "boolean" || 661 typeName == "java.lang.Short"|| typeName == "short" || 662 typeName == "java.lang.Byte"|| typeName == "byte" || 663 typeName == "java.math.BigDecimal"|| 664 typeName == "java.math.BigInteger"|| 665 typeName == "java.lang.Object" || 666 typeName == "java.util.Calendar" || typeName == "java.util.Date" || 667 typeName == "java.util.GregorianCalendar" || 668 typeName == "javax.xml.namespace.QName" || 669 typeName == "java.net.URL" || typeName == "java.net.URI") 670 return false; 671 return true; 672 } 673 674 679 public static Object convertValue(Class type, String value) { 680 String typeName = type.getName().intern(); 681 if (typeName == "java.lang.String") 682 return value; 683 if (typeName == "java.lang.Boolean" || typeName == "boolean") 684 return Boolean.valueOf(value); 685 if (typeName == "java.lang.Integer" || typeName == "int") 686 return Integer.valueOf(value); 687 if (typeName == "java.lang.Long" || typeName == "long") 688 return Long.valueOf(value); 689 if (typeName == "java.lang.Float" || typeName == "float") 690 return Float.valueOf(value); 691 if (typeName == "java.lang.Double" || typeName == "double") 692 return Double.valueOf(value); 693 if (typeName == "java.lang.Byte" || typeName == "byte") 694 return Byte.valueOf(value); 695 if (typeName == "java.lang.Short" || typeName == "short") 696 return Short.valueOf(value); 697 if (typeName == "java.lang.Character" || typeName == "char") 698 return new Character (value.charAt(0)); 699 if (typeName == "java.net.URL") { 700 try { 701 return new java.net.URL (value); 702 } catch (java.net.MalformedURLException e) { 703 throw new RuntimeException (e); 704 } 705 } 706 if (typeName == "java.net.URI") { 707 try { 708 return new java.net.URI (value); 709 } catch (java.net.URISyntaxException e) { 710 throw new RuntimeException (e); 711 } 712 } 713 if (typeName == "java.math.BigDecimal") 714 return new java.math.BigDecimal (value); 715 if (typeName == "java.math.BigInteger") 716 return new java.math.BigInteger (value); 717 if (typeName == "java.util.Calendar") { 718 TimeZone tz = TimeZone.getDefault(); 724 Calendar cal = Calendar.getInstance(tz); 725 Date date = null; 726 String [] possibleFormats = {"yyyy-MM-dd'T'HH:mm:ss.S", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd"}; java.text.ParsePosition pos = null; 728 for (int formatNum = 0; formatNum < possibleFormats.length; ++formatNum) { 729 pos = new java.text.ParsePosition (0); 730 java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat (possibleFormats[formatNum]); 731 formatter.setCalendar(cal); 732 date = formatter.parse(value, pos); 733 if (date != null) { 734 break; 735 } 736 } 737 if (date == null) { 738 throw new java.lang.RuntimeException (Common.getMessage("MSG_BadParse", value)); 739 } 740 cal.setTime(date); 741 return cal; 742 } 743 744 Constructor c = null; 745 746 try { 747 Class [] cc = new Class [] {java.lang.String .class}; 748 c = type.getDeclaredConstructor(cc); 749 Object [] p = new Object [] {value}; 750 return c.newInstance(p); 751 } catch (NoSuchMethodException me) { 752 throw new RuntimeException (me); 753 } catch (java.lang.InstantiationException e) { 754 throw new RuntimeException (e); 755 } catch (java.lang.IllegalAccessException e) { 756 throw new RuntimeException (e); 757 } catch (java.lang.reflect.InvocationTargetException e) { 758 throw new RuntimeException (e); 759 } 760 } 761 762 767 public static void genReadType(Writer out, String typeName) throws IOException { 768 typeName = typeName.intern(); 769 if (typeName == "java.util.Calendar") { 770 out.write("public static java.util.Calendar stringToCalendar(String value) throws java.text.ParseException {\n"); 771 out.write("java.util.TimeZone tz = java.util.TimeZone.getDefault();\n"); 772 out.write("java.util.Calendar cal = java.util.Calendar.getInstance(tz);\n"); 773 out.write("java.util.Date date = null;\n"); 774 out.write("String[] possibleFormats = {\"yyyy-MM-dd'T'HH:mm:ss.S\", \"yyyy-MM-dd'T'HH:mm:ss\", \"yyyy-MM-dd\"}; // NOI18N\n"); 775 out.write("java.text.ParsePosition pos = null;\n"); 776 out.write("for (int formatNum = 0; formatNum < possibleFormats.length; ++formatNum) {\n"); 777 out.write("pos = new java.text.ParsePosition(0);\n"); 778 out.write("java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(possibleFormats[formatNum]);\n"); 779 out.write("formatter.setCalendar(cal);\n"); 780 out.write("date = formatter.parse(value, pos);\n"); 781 out.write("if (date != null) {\n"); 782 out.write("break;\n"); 783 out.write("}\n"); 784 out.write("}\n"); 785 out.write("if (date == null) {\n"); 786 out.write("throw new java.text.ParseException(\"Bad time/date parse of \"+value, pos.getErrorIndex());\n"); 787 out.write("}\n"); 788 out.write("int len = value.length();\n"); 789 out.write("if (pos.getIndex() < len) {\n"); 790 out.write("if (value.charAt(pos.getIndex()) == 'Z') {\n"); 791 out.write("// The Timezone is UTC\n"); 792 out.write("tz = java.util.TimeZone.getTimeZone(\"GMT\");\n"); 793 out.write("cal.setTimeZone(tz);\n"); 794 out.write("} else {\n"); 795 out.write("tz = java.util.TimeZone.getTimeZone(\"GMT\"+value.substring(pos.getIndex(), len));\n"); 796 out.write("cal.setTimeZone(tz);\n"); 797 out.write("}\n"); 798 out.write("}\n"); 799 out.write("cal.setTime(date);\n"); 800 out.write("return cal;\n"); 801 out.write("}\n"); 802 } else if (typeName == "base64Binary") { 803 out.write("public static byte[] decodeBase64BinaryString(String text) {\n"); 804 out.write("final int decodeBase64Table[] = {62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51};\n"); 805 out.write("StringBuffer cleanedEncoding = new StringBuffer();\n"); 806 out.write("int len = text.length();\n"); 807 out.write("// Get rid of extraneous characters (like whitespace).\n"); 808 out.write("for (int i = 0; i < len; ++i) {\n"); 809 out.write("if (text.charAt(i) > 0x20) {\n"); 810 out.write("cleanedEncoding.append(text.charAt(i));\n"); 811 out.write("}\n"); 812 out.write("}\n"); 813 out.write("char[] encodedText = cleanedEncoding.toString().toCharArray();\n"); 814 out.write("len = encodedText.length;\n"); 815 out.write("if (len == 0) {\n"); 816 out.write("return new byte[0];\n"); 817 out.write("}\n"); 818 out.write("int howManyBlocks = len / 4;\n"); 819 out.write("int partialLen = 3;\n"); 820 out.write("if (encodedText[len-1] == '=') {\n"); 821 out.write("partialLen -= 1;\n"); 822 out.write("if (encodedText[len-2] == '=') {\n"); 823 out.write("partialLen -= 1;\n"); 824 out.write("}\n"); 825 out.write("}\n"); 826 out.write("int resultLen = partialLen + (howManyBlocks - 1) * 3;\n"); 827 out.write("byte[] result = new byte[resultLen];\n"); 828 out.write("int resultIndex = 0;\n"); 829 out.write("int encodedTextIndex = 0;\n"); 830 out.write("for (int blockNum = 0; blockNum < howManyBlocks; ++blockNum) {\n"); 831 out.write("int a = decodeBase64Table[encodedText[encodedTextIndex++] - '+'];\n"); 832 out.write("int b = decodeBase64Table[encodedText[encodedTextIndex++] - '+'];\n"); 833 out.write("int c = decodeBase64Table[encodedText[encodedTextIndex++] - '+'];\n"); 834 out.write("int d = decodeBase64Table[encodedText[encodedTextIndex++] - '+'];\n"); 835 836 out.write("result[resultIndex++] = (byte) ( (b >> 4) | (a << 2) );\n"); 837 out.write("if (resultIndex < resultLen) {\n"); 838 out.write("result[resultIndex++] = (byte) ( ((b & 0xf) << 4) | (c >> 2) );\n"); 839 out.write("}\n"); 840 out.write("if (resultIndex < resultLen) {\n"); 841 out.write("result[resultIndex++] = (byte) ( ((c & 0x3) << 6) | d);\n"); 842 out.write("}\n"); 843 out.write("}\n"); 844 out.write("return result;\n"); 845 out.write("}\n"); 846 } 847 } 848 849 854 public static void genWriteType(Writer out, String typeName) throws IOException { 855 typeName = typeName.intern(); 856 if (typeName == "java.util.Calendar") { 857 out.write("public static String calendarToString(java.util.Calendar cal) {\n"); 858 out.write("java.util.Date date = cal.getTime();\n"); 859 out.write("java.text.SimpleDateFormat formatter;\n"); 860 out.write("if (cal.get(java.util.Calendar.HOUR) == 0 && cal.get(java.util.Calendar.MINUTE) == 0 && cal.get(java.util.Calendar.SECOND) == 0) {\n"); 861 out.write("formatter = new java.text.SimpleDateFormat(\"yyyy-MM-dd\"); // NOI18N\n"); 862 out.write("} else if (cal.get(java.util.Calendar.MILLISECOND) == 0) {\n"); 863 out.write("formatter = new java.text.SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss\"); // NOI18N\n"); 864 out.write("} else {\n"); 865 out.write("formatter = new java.text.SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss.S\"); // NOI18N\n"); 866 out.write("}\n"); 867 out.write("String result = formatter.format(date);\n"); 868 out.write("if (java.util.TimeZone.getDefault().hasSameRules(cal.getTimeZone())) {\n"); 869 out.write("return result;\n"); 870 out.write("}\n"); 871 out.write("int offset = cal.getTimeZone().getOffset(0);\n"); 872 out.write("if (offset == 0) {\n"); 873 out.write("return result+\"Z\";\n"); 874 out.write("}\n"); 875 out.write("int seconds = offset / 1000;\n"); 876 out.write("if (seconds > 0) {\n"); 877 out.write("result += \"+\";\n"); 878 out.write("} else {\n"); 879 out.write("seconds = -1 * seconds;\n"); 880 out.write("result += \"-\";\n"); 881 out.write("}\n"); 882 out.write("int hours = seconds / 3600;\n"); 883 out.write("if (hours < 10) {\n"); 884 out.write("result += \"0\";\n"); 885 out.write("}\n"); 886 out.write("result += hours + \":\";\n"); 887 out.write("int minutes = (seconds / 60) % 60;\n"); 888 out.write("if (minutes < 10) {\n"); 889 out.write("result += \"0\";\n"); 890 out.write("}\n"); 891 out.write("result += minutes;\n"); 892 out.write("return result;\n"); 893 out.write("}\n"); 894 } else if (typeName == "base64Binary") { 895 out.write("public static String encodeBase64BinaryString(byte[] instance) {\n"); 896 out.write("final char encodeBase64Table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};\n"); 897 out.write("byte[] value = (byte[]) instance;\n"); 898 out.write("int len = value.length;\n"); 899 out.write("if (len == 0) {\n"); 900 out.write("return \"\";\n"); 901 out.write("}\n"); 902 out.write("int howManyBlocks = len / 3;\n"); 903 out.write("int partialLen = len % 3;\n"); 904 out.write("if (partialLen != 0) {\n"); 905 out.write("howManyBlocks += 1;\n"); 906 out.write("}\n"); 907 out.write("int resultLen = howManyBlocks * 4;\n"); 908 out.write("StringBuffer result = new StringBuffer(resultLen);\n"); 909 out.write("int valueIndex = 0;\n"); 910 out.write("for (int blockNum = 0; blockNum < howManyBlocks; ++blockNum) {\n"); 911 out.write("int a = value[valueIndex++];\n"); 912 out.write("int b;\n"); 913 out.write("int c;\n"); 914 out.write("if (valueIndex < len) {\n"); 915 out.write("b = value[valueIndex++];\n"); 916 out.write("} else {\n"); 917 out.write("b = 0;\n"); 918 out.write("}\n"); 919 out.write("if (valueIndex < len) {\n"); 920 out.write("c = value[valueIndex++];\n"); 921 out.write("} else {\n"); 922 out.write("c = 0;\n"); 923 out.write("}\n"); 924 out.write("if (a < 0) {\n"); 925 out.write("a += 256;\n"); 926 out.write("}\n"); 927 out.write("if (b < 0) {\n"); 928 out.write("b += 256;\n"); 929 out.write("}\n"); 930 out.write("if (c < 0) {\n"); 931 out.write("c += 256;\n"); 932 out.write("}\n"); 933 out.write("result.append(encodeBase64Table[a >> 2]);\n"); 934 out.write("result.append(encodeBase64Table[((a & 0x3) << 4) | (b >> 4)]);\n"); 935 out.write("result.append(encodeBase64Table[((b & 0xf) << 2) | (c >> 6)]);\n"); 936 out.write("result.append(encodeBase64Table[c & 0x3f]);\n"); 937 out.write("}\n"); 938 out.write("if (partialLen == 1) {\n"); 939 out.write("result.setCharAt(resultLen - 1, '=');\n"); 940 out.write("result.setCharAt(resultLen - 2, '=');\n"); 941 out.write("} else if (partialLen == 2) {\n"); 942 out.write("result.setCharAt(resultLen - 1, '=');\n"); 943 out.write("}\n"); 944 out.write("return result.toString();\n"); 945 out.write("}\n"); 946 } 947 } 948 949 951 956 public static Object dummyBean(Class cls, int arraySize) throws java.beans.IntrospectionException { 957 958 if (!isJavaBeanType(cls)) { 960 return dummyValue(cls, arraySize); 961 } 962 963 Object obj = null; 964 try { 965 Constructor construct = cls.getConstructor(new Class [0]); 966 obj = construct.newInstance(new Object [0]); 967 } catch (java.lang.NoSuchMethodException e) { 968 e.printStackTrace(); 969 return null; 970 } catch (java.lang.InstantiationException e) { 971 e.printStackTrace(); 972 return null; 973 } catch (java.lang.IllegalAccessException e) { 974 e.printStackTrace(); 975 return null; 976 } catch (java.lang.reflect.InvocationTargetException e) { 977 e.printStackTrace(); 978 return null; 979 } 980 981 BeanInfo bi = Introspector.getBeanInfo(cls); 983 PropertyDescriptor[] pds = bi.getPropertyDescriptors(); 984 985 for (int i = 0 ; i < pds.length; ++i) { 986 PropertyDescriptor pd = pds[i]; 987 Method writer = pd.getWriteMethod(); 988 if (writer == null) continue; 989 Class propertyType = pd.getPropertyType(); 990 String propertyName = pd.getName(); 991 Class declaringClass = writer.getDeclaringClass(); 992 if (declaringClass == null || declaringClass.equals(Object .class)) continue; 993 if (propertyType == null) continue; 994 995 Object newValue=null; 996 Object baseValue=null; 997 if (isJavaBeanType(propertyType)) { 998 Class baseType = propertyType; 999 if (propertyType.isArray()) 1000 baseType = propertyType.getComponentType(); 1001 baseValue = dummyBean(baseType, arraySize); 1002 if (propertyType.isArray()) { 1003 newValue = Array.newInstance(baseType, arraySize); 1005 for (int ii=0; ii<arraySize; ++ii) { 1006 Array.set(newValue, ii, baseValue); 1007 } 1008 } else { 1009 newValue = baseValue; 1010 } 1011 } else { 1012 Class baseType = propertyType; 1013 if (propertyType.isArray()) 1014 baseType = propertyType.getComponentType(); 1015 baseValue = dummyValue(baseType, arraySize); 1016 if (propertyType.isArray()) { 1017 newValue = Array.newInstance(baseType, arraySize); 1019 for (int ii=0; ii<arraySize; ++ii) { 1020 Array.set(newValue, ii, baseValue); 1021 } 1022 } else { 1023 newValue = baseValue; 1024 } 1025 } 1026 1027 try { 1029 writer.invoke(obj, new Object [] {newValue}); 1030 } catch (java.lang.reflect.InvocationTargetException e) { 1031 e.printStackTrace(); 1033 } catch (java.lang.IllegalAccessException e) { 1034 e.printStackTrace(); 1036 } 1037 } 1038 1039 return obj; 1041 } 1042 1043 1044 1049 public static Object dummyValue(Class type, int arraySize) { 1050 String typeName = type.getName().intern(); 1051 if (Collection.class.isAssignableFrom(type)) { 1052 ArrayList lst = new ArrayList(); 1054 for (int ii=0; ii < arraySize; ++ii) { 1055 lst.add("collection-element"); 1056 } 1057 return lst; 1058 } else if (typeName == "java.lang.String") 1059 return "string"; 1060 else if (typeName == "java.lang.Boolean" || typeName == "boolean") 1061 return Boolean.FALSE; 1062 else if (typeName == "java.lang.Integer" || typeName == "int") 1063 return Integer.valueOf("1"); 1064 else if (typeName == "java.lang.Long" || typeName == "long") 1065 return Long.valueOf("1"); 1066 else if (typeName == "java.lang.Float" || typeName == "float") 1067 return Float.valueOf("1.0"); 1068 else if (typeName == "java.lang.Double" || typeName == "double") 1069 return Double.valueOf("1.0"); 1070 else if (typeName == "java.lang.Byte" || typeName == "byte") 1071 return Byte.valueOf("1"); 1072 else if (typeName == "java.lang.Short" || typeName == "short") 1073 return Short.valueOf("1"); 1074 else if (typeName == "java.lang.Character" || typeName == "char") 1075 return new Character ('C'); 1076 else if (typeName == "java.math.BigDecimal") 1077 return new java.math.BigDecimal ("1.0"); 1078 else if (typeName == "java.math.BigInteger") 1079 return new java.math.BigInteger ("1"); 1080 else if (typeName == "java.util.Calendar") { 1081 Calendar cal = Calendar.getInstance(); 1082 cal.setTime(new Date()); 1083 return cal; 1084 } else { 1085 Constructor c = null; 1087 1088 try { 1089 Class [] cc = new Class [] {java.lang.String .class}; 1090 c = type.getDeclaredConstructor(cc); 1091 Object [] p = new Object [] {"string"}; 1092 return c.newInstance(p); 1093 } catch (NoSuchMethodException e) { 1094 e.printStackTrace(); 1095 return null; 1096 } catch (java.lang.InstantiationException e) { 1097 e.printStackTrace(); 1098 return null; 1099 } catch (java.lang.IllegalAccessException e) { 1100 e.printStackTrace(); 1101 return null; 1102 } catch (java.lang.reflect.InvocationTargetException e) { 1103 e.printStackTrace(); 1104 return null; 1105 } 1106 } 1107 } 1108} 1109 | Popular Tags |