Source Code Cross Referenced for JAXBDataBinding.java in  » Web-Services-apache-cxf-2.0.1 » tools-wsdlto » org » apache » cxf » tools » wsdlto » databinding » jaxb » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Web Services apache cxf 2.0.1 » tools wsdlto » org.apache.cxf.tools.wsdlto.databinding.jaxb 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /**
002:         * Licensed to the Apache Software Foundation (ASF) under one
003:         * or more contributor license agreements. See the NOTICE file
004:         * distributed with this work for additional information
005:         * regarding copyright ownership. The ASF licenses this file
006:         * to you under the Apache License, Version 2.0 (the
007:         * "License"); you may not use this file except in compliance
008:         * with the License. You may obtain a copy of the License at
009:         *
010:         * http://www.apache.org/licenses/LICENSE-2.0
011:         *
012:         * Unless required by applicable law or agreed to in writing,
013:         * software distributed under the License is distributed on an
014:         * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015:         * KIND, either express or implied. See the License for the
016:         * specific language governing permissions and limitations
017:         * under the License.
018:         */package org.apache.cxf.tools.wsdlto.databinding.jaxb;
019:
020:        import java.io.File;
021:        import java.io.IOException;
022:        import java.io.Writer;
023:        import java.lang.reflect.Field;
024:        import java.util.ArrayList;
025:        import java.util.Collection;
026:        import java.util.HashMap;
027:        import java.util.HashSet;
028:        import java.util.List;
029:        import java.util.Map;
030:        import java.util.Set;
031:        import java.util.StringTokenizer;
032:        import java.util.Vector;
033:        import java.util.logging.Level;
034:        import java.util.logging.Logger;
035:
036:        import javax.xml.XMLConstants;
037:        import javax.xml.namespace.QName;
038:        import javax.xml.transform.dom.DOMSource;
039:        import javax.xml.validation.SchemaFactory;
040:
041:        import org.w3c.dom.DOMException;
042:        import org.w3c.dom.Document;
043:        import org.w3c.dom.Element;
044:        import org.w3c.dom.NamedNodeMap;
045:        import org.w3c.dom.Node;
046:        import org.w3c.dom.NodeList;
047:
048:        import org.xml.sax.InputSource;
049:        import org.xml.sax.SAXException;
050:
051:        import com.sun.codemodel.ClassType;
052:        import com.sun.codemodel.JClass;
053:        import com.sun.codemodel.JCodeModel;
054:        import com.sun.codemodel.JDefinedClass;
055:        import com.sun.codemodel.JMethod;
056:        import com.sun.codemodel.JType;
057:        import com.sun.tools.xjc.BadCommandLineException;
058:        import com.sun.tools.xjc.Options;
059:        import com.sun.tools.xjc.Plugin;
060:        import com.sun.tools.xjc.api.Mapping;
061:        import com.sun.tools.xjc.api.Property;
062:        import com.sun.tools.xjc.api.S2JJAXBModel;
063:        import com.sun.tools.xjc.api.TypeAndAnnotation;
064:        import com.sun.tools.xjc.api.XJC;
065:        import com.sun.tools.xjc.api.impl.s2j.SchemaCompilerImpl;
066:
067:        import org.apache.cxf.common.i18n.Message;
068:        import org.apache.cxf.common.logging.LogUtils;
069:        import org.apache.cxf.common.util.StringUtils;
070:        import org.apache.cxf.helpers.CastUtils;
071:        import org.apache.cxf.helpers.FileUtils;
072:        import org.apache.cxf.tools.common.ToolConstants;
073:        import org.apache.cxf.tools.common.ToolContext;
074:        import org.apache.cxf.tools.common.ToolException;
075:        import org.apache.cxf.tools.common.model.DefaultValueWriter;
076:        import org.apache.cxf.tools.util.ClassCollector;
077:        import org.apache.cxf.tools.util.JAXBUtils;
078:        import org.apache.cxf.tools.wsdlto.core.DataBindingProfile;
079:        import org.apache.cxf.tools.wsdlto.core.DefaultValueProvider;
080:        import org.apache.cxf.tools.wsdlto.core.RandomValueProvider;
081:
082:        public class JAXBDataBinding implements  DataBindingProfile {
083:            private static final Logger LOG = LogUtils
084:                    .getL7dLogger(JAXBDataBinding.class);
085:
086:            private static final Set<String> DEFAULT_TYPE_MAP = new HashSet<String>();
087:            private static final Map<String, String> JLDEFAULT_TYPE_MAP = new HashMap<String, String>();
088:
089:            private S2JJAXBModel rawJaxbModelGenCode;
090:            private ToolContext context;
091:            private DefaultValueProvider defaultValues;
092:
093:            static {
094:                DEFAULT_TYPE_MAP.add("boolean");
095:                DEFAULT_TYPE_MAP.add("int");
096:                DEFAULT_TYPE_MAP.add("long");
097:                DEFAULT_TYPE_MAP.add("short");
098:                DEFAULT_TYPE_MAP.add("byte");
099:                DEFAULT_TYPE_MAP.add("float");
100:                DEFAULT_TYPE_MAP.add("double");
101:                DEFAULT_TYPE_MAP.add("char");
102:                DEFAULT_TYPE_MAP.add("java.lang.String");
103:                DEFAULT_TYPE_MAP.add("javax.xml.namespace.QName");
104:                DEFAULT_TYPE_MAP.add("java.net.URI");
105:                DEFAULT_TYPE_MAP.add("java.math.BigInteger");
106:                DEFAULT_TYPE_MAP.add("java.math.BigDecimal");
107:                DEFAULT_TYPE_MAP.add("javax.xml.datatype.XMLGregorianCalendar");
108:                DEFAULT_TYPE_MAP.add("javax.xml.datatype.Duration");
109:
110:                JLDEFAULT_TYPE_MAP.put("java.lang.Character", "char");
111:                JLDEFAULT_TYPE_MAP.put("java.lang.Boolean", "boolean");
112:                JLDEFAULT_TYPE_MAP.put("java.lang.Integer", "int");
113:                JLDEFAULT_TYPE_MAP.put("java.lang.Long", "long");
114:                JLDEFAULT_TYPE_MAP.put("java.lang.Short", "short");
115:                JLDEFAULT_TYPE_MAP.put("java.lang.Byte", "byte");
116:                JLDEFAULT_TYPE_MAP.put("java.lang.Float", "float");
117:                JLDEFAULT_TYPE_MAP.put("java.lang.Double", "double");
118:                DEFAULT_TYPE_MAP.addAll(JLDEFAULT_TYPE_MAP.keySet());
119:            }
120:
121:            @SuppressWarnings("unchecked")
122:            public void initialize(ToolContext c) throws ToolException {
123:                this .context = c;
124:
125:                SchemaCompilerImpl schemaCompiler = (SchemaCompilerImpl) XJC
126:                        .createSchemaCompiler();
127:                ClassCollector classCollector = context
128:                        .get(ClassCollector.class);
129:                ClassNameAllocatorImpl allocator = new ClassNameAllocatorImpl(
130:                        classCollector);
131:
132:                schemaCompiler.setClassNameAllocator(allocator);
133:
134:                JAXBBindErrorListener listener = new JAXBBindErrorListener(
135:                        context.isVerbose());
136:                schemaCompiler.setErrorListener(listener);
137:                // Collection<SchemaInfo> schemas = serviceInfo.getSchemas();
138:                List<InputSource> jaxbBindings = context.getJaxbBindingFile();
139:                Map<String, Element> schemaLists = (Map<String, Element>) context
140:                        .get(ToolConstants.SCHEMA_MAP);
141:
142:                Set<String> keys = schemaLists.keySet();
143:                for (String key : keys) {
144:                    Element ele = schemaLists.get(key);
145:                    this .removeImportElement(ele);
146:                    String tns = ele.getAttribute("targetNamespace");
147:                    if (StringUtils.isEmpty(tns)) {
148:                        continue;
149:                    }
150:                    if (context.get(ToolConstants.CFG_VALIDATE_WSDL) != null) {
151:                        validateSchema(ele);
152:                    }
153:                    schemaCompiler.parseSchema(key, ele);
154:
155:                }
156:
157:                for (InputSource binding : jaxbBindings) {
158:                    schemaCompiler.parseSchema(binding);
159:                }
160:
161:                /*if (context.getPackageName() != null) {
162:                    schemaCompiler.forcePackageName(context.getPackageName());
163:                } else {*/
164:
165:                Map<String, String> nsPkgMap = context.getNamespacePackageMap();
166:                for (String ns : nsPkgMap.keySet()) {
167:                    File file = JAXBUtils.getPackageMappingSchemaBindingFile(
168:                            ns, context.mapPackageName(ns));
169:                    InputSource ins = new InputSource(file.toURI().toString());
170:                    schemaCompiler.parseSchema(ins);
171:                    FileUtils.delete(file);
172:                }
173:
174:                if (context.getPackageName() != null) {
175:                    schemaCompiler.setDefaultPackageName(context
176:                            .getPackageName());
177:                }
178:
179:                if (context.get(ToolConstants.CFG_XJC_ARGS) != null) {
180:                    String xjcArgs = (String) context
181:                            .get(ToolConstants.CFG_XJC_ARGS);
182:                    Vector<String> args = new Vector<String>();
183:                    StringTokenizer tokenizer = new StringTokenizer(xjcArgs,
184:                            ",", false);
185:                    while (tokenizer.hasMoreTokens()) {
186:                        String arg = tokenizer.nextToken();
187:                        args.add(arg);
188:                        LOG.log(Level.FINE, "xjc arg:" + arg);
189:                    }
190:                    Options opts = null;
191:                    try {
192:                        opts = getOptions(schemaCompiler);
193:                        // keep parseArguments happy, supply dummy required command-line opts
194:                        opts.addGrammar(new InputSource("null"));
195:                        opts.parseArguments(args.toArray(new String[] {}));
196:                    } catch (BadCommandLineException e) {
197:                        String msg = "XJC reported 'BadCommandLineException' for -xjc argument:"
198:                                + xjcArgs;
199:                        LOG.log(Level.FINE, msg, e);
200:                        if (opts != null) {
201:                            String pluginUsage = getPluginUsageString(opts);
202:                            if ("-X".equals(xjcArgs)) {
203:                                msg = pluginUsage;
204:                            } else {
205:                                msg += pluginUsage;
206:                            }
207:                        }
208:
209:                        throw new ToolException(msg, e);
210:                    }
211:                }
212:
213:                rawJaxbModelGenCode = schemaCompiler.bind();
214:
215:                addedEnumClassToCollector(schemaLists, allocator);
216:
217:                if (context.get(ToolConstants.CFG_DEFAULT_VALUES) != null) {
218:                    String cname = (String) context
219:                            .get(ToolConstants.CFG_DEFAULT_VALUES);
220:                    if (StringUtils.isEmpty(cname)) {
221:                        defaultValues = new RandomValueProvider();
222:                    } else {
223:                        if (cname.charAt(0) == '=') {
224:                            cname = cname.substring(1);
225:                        }
226:                        try {
227:                            defaultValues = (DefaultValueProvider) Class
228:                                    .forName(cname).newInstance();
229:                        } catch (Exception e) {
230:                            LOG.log(Level.SEVERE, e.getMessage());
231:                            throw new ToolException(e);
232:                        }
233:                    }
234:                }
235:            }
236:
237:            private String getPluginUsageString(Options opts) {
238:                StringBuffer buf = new StringBuffer();
239:                buf.append("\navaliable plugin options:\n");
240:                for (Plugin pl : opts.getAllPlugins()) {
241:                    buf.append(pl.getUsage());
242:                    buf.append('\n');
243:                }
244:                return buf.toString();
245:            }
246:
247:            // TODO  this can be repaced with schemaCompiler.getOptions() once we
248:            // move to a version => 2.0.3 for jaxb-xjc
249:            private Options getOptions(SchemaCompilerImpl schemaCompiler)
250:                    throws ToolException {
251:                try {
252:                    Field delegateField = schemaCompiler.getClass()
253:                            .getDeclaredField("opts");
254:                    delegateField.setAccessible(true);
255:                    return (Options) delegateField.get(schemaCompiler);
256:                } catch (Exception e) {
257:                    String msg = "Failed to access 'opts' field of XJC SchemaCompilerImpl, reason:"
258:                            + e;
259:                    LOG.log(Level.SEVERE, msg, e);
260:                    throw new ToolException(msg, e);
261:                }
262:            }
263:
264:            // JAXB bug. JAXB ClassNameCollector may not be invoked when generated
265:            // class is an enum. We need to use this method to add the missed file
266:            // to classCollector.
267:            private void addedEnumClassToCollector(
268:                    Map<String, Element> schemaList,
269:                    ClassNameAllocatorImpl allocator) {
270:                for (Element schemaElement : schemaList.values()) {
271:                    String targetNamespace = schemaElement
272:                            .getAttribute("targetNamespace");
273:                    if (StringUtils.isEmpty(targetNamespace)) {
274:                        continue;
275:                    }
276:                    String packageName = context
277:                            .mapPackageName(targetNamespace);
278:                    if (!addedToClassCollector(packageName)) {
279:                        allocator.assignClassName(packageName, "*");
280:                    }
281:                }
282:            }
283:
284:            private boolean addedToClassCollector(String packageName) {
285:                ClassCollector classCollector = context
286:                        .get(ClassCollector.class);
287:                List<String> files = (List<String>) classCollector
288:                        .getGeneratedFileInfo();
289:                for (String file : files) {
290:                    int dotIndex = file.lastIndexOf(".");
291:                    String sub = file.substring(0, dotIndex - 1);
292:                    if (sub.equals(packageName)) {
293:                        return true;
294:                    }
295:                }
296:                return false;
297:            }
298:
299:            private boolean isSuppressCodeGen() {
300:                return context.optionSet(ToolConstants.CFG_SUPPRESS_GEN);
301:            }
302:
303:            public void generate(ToolContext c) throws ToolException {
304:                initialize(c);
305:                if (rawJaxbModelGenCode == null) {
306:                    return;
307:                }
308:
309:                try {
310:                    String dir = (String) context
311:                            .get(ToolConstants.CFG_OUTPUTDIR);
312:
313:                    TypesCodeWriter fileCodeWriter = new TypesCodeWriter(
314:                            new File(dir), context.getExcludePkgList());
315:
316:                    if (rawJaxbModelGenCode instanceof  S2JJAXBModel) {
317:                        S2JJAXBModel schem2JavaJaxbModel = (S2JJAXBModel) rawJaxbModelGenCode;
318:                        JCodeModel jcodeModel = schem2JavaJaxbModel
319:                                .generateCode(null, null);
320:
321:                        if (!isSuppressCodeGen()) {
322:                            jcodeModel.build(fileCodeWriter);
323:                        }
324:
325:                        context.put(JCodeModel.class, jcodeModel);
326:                        for (String str : fileCodeWriter.getExcludeFileList()) {
327:                            context.getExcludeFileList().add(str);
328:                        }
329:                    }
330:                    return;
331:                } catch (IOException e) {
332:                    Message msg = new Message("FAIL_TO_GENERATE_TYPES", LOG);
333:                    throw new ToolException(msg);
334:                }
335:            }
336:
337:            public String getType(QName qname, boolean element) {
338:                TypeAndAnnotation typeAnno = rawJaxbModelGenCode
339:                        .getJavaType(qname);
340:                if (element) {
341:                    Mapping mapping = rawJaxbModelGenCode.get(qname);
342:                    if (mapping != null) {
343:                        typeAnno = mapping.getType();
344:                    }
345:                }
346:
347:                if (typeAnno != null && typeAnno.getTypeClass() != null) {
348:                    return typeAnno.getTypeClass().fullName();
349:                }
350:                return null;
351:
352:            }
353:
354:            public String getWrappedElementType(QName wrapperElement, QName item) {
355:                Mapping mapping = rawJaxbModelGenCode.get(wrapperElement);
356:                if (mapping != null) {
357:                    List<? extends Property> propList = mapping
358:                            .getWrapperStyleDrilldown();
359:                    for (Property pro : propList) {
360:                        if (pro.elementName().getNamespaceURI().equals(
361:                                item.getNamespaceURI())
362:                                && pro.elementName().getLocalPart().equals(
363:                                        item.getLocalPart())) {
364:                            return pro.type().fullName();
365:                        }
366:                    }
367:                }
368:                return null;
369:            }
370:
371:            private void removeImportElement(Element element) {
372:                NodeList nodeList = element.getElementsByTagNameNS(
373:                        ToolConstants.SCHEMA_URI, "import");
374:                List<Node> ns = new ArrayList<Node>();
375:                for (int tmp = 0; tmp < nodeList.getLength(); tmp++) {
376:
377:                    Node importNode = nodeList.item(tmp);
378:                    ns.add(importNode);
379:                }
380:                for (Node item : ns) {
381:                    Node schemaNode = item.getParentNode();
382:                    schemaNode.removeChild(item);
383:                }
384:
385:            }
386:
387:            public Node cloneNode(Document document, Node node, boolean deep)
388:                    throws DOMException {
389:                if (document == null || node == null) {
390:                    return null;
391:                }
392:                int type = node.getNodeType();
393:
394:                if (node.getOwnerDocument() == document) {
395:                    return node.cloneNode(deep);
396:                }
397:                Node clone;
398:                switch (type) {
399:                case Node.CDATA_SECTION_NODE:
400:                    clone = document.createCDATASection(node.getNodeValue());
401:                    break;
402:                case Node.COMMENT_NODE:
403:                    clone = document.createComment(node.getNodeValue());
404:                    break;
405:                case Node.ENTITY_REFERENCE_NODE:
406:                    clone = document.createEntityReference(node.getNodeName());
407:                    break;
408:                case Node.ELEMENT_NODE:
409:                    clone = document.createElement(node.getNodeName());
410:                    NamedNodeMap attributes = node.getAttributes();
411:                    for (int i = 0; i < attributes.getLength(); i++) {
412:                        ((Element) clone).setAttribute(attributes.item(i)
413:                                .getNodeName(), attributes.item(i)
414:                                .getNodeValue());
415:                    }
416:                    break;
417:
418:                case Node.TEXT_NODE:
419:                    clone = document.createTextNode(node.getNodeValue());
420:                    break;
421:                default:
422:                    return null;
423:                }
424:                if (deep && type == Node.ELEMENT_NODE) {
425:                    Node child = node.getFirstChild();
426:                    while (child != null) {
427:                        clone.appendChild(cloneNode(document, child, true));
428:                        child = child.getNextSibling();
429:                    }
430:                }
431:                return clone;
432:            }
433:
434:            public void validateSchema(Element ele) throws ToolException {
435:                SchemaFactory schemaFact = SchemaFactory
436:                        .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
437:                DOMSource domSrc = new DOMSource(ele);
438:                try {
439:                    schemaFact.newSchema(domSrc);
440:                } catch (SAXException e) {
441:                    if (e.getLocalizedMessage().indexOf("src-resolve.4.2") > -1) {
442:                        //Ignore schema resolve error and do nothing
443:                    } else {
444:                        throw new ToolException("Schema Error : "
445:                                + e.getLocalizedMessage(), e);
446:                    }
447:                }
448:            }
449:
450:            public DefaultValueWriter createDefaultValueWriter(QName qname,
451:                    boolean element) {
452:                if (defaultValues == null) {
453:                    return null;
454:                }
455:                TypeAndAnnotation typeAnno = rawJaxbModelGenCode
456:                        .getJavaType(qname);
457:                if (element) {
458:                    Mapping mapping = rawJaxbModelGenCode.get(qname);
459:                    if (mapping != null) {
460:                        typeAnno = mapping.getType();
461:                    }
462:                }
463:                if (typeAnno != null) {
464:                    final JType type = typeAnno.getTypeClass();
465:                    return new JAXBDefaultValueWriter(type);
466:                }
467:                return null;
468:            }
469:
470:            public DefaultValueWriter createDefaultValueWriterForWrappedElement(
471:                    QName wrapperElement, QName item) {
472:                if (defaultValues != null) {
473:                    Mapping mapping = rawJaxbModelGenCode.get(wrapperElement);
474:                    if (mapping != null) {
475:                        List<? extends Property> propList = mapping
476:                                .getWrapperStyleDrilldown();
477:                        for (Property pro : propList) {
478:                            if (pro.elementName().getNamespaceURI().equals(
479:                                    item.getNamespaceURI())
480:                                    && pro.elementName().getLocalPart().equals(
481:                                            item.getLocalPart())) {
482:                                return new JAXBDefaultValueWriter(pro.type());
483:                            }
484:                        }
485:                    }
486:                }
487:                return null;
488:            }
489:
490:            private class JAXBDefaultValueWriter implements  DefaultValueWriter {
491:                final JType type;
492:
493:                JAXBDefaultValueWriter(JType tp) {
494:                    type = tp;
495:                }
496:
497:                public void writeDefaultValue(Writer writer, String indent,
498:                        String path, String varName) throws IOException {
499:                    path = path + "/" + varName;
500:                    writeDefaultValue(writer, indent, path, varName, type);
501:                }
502:
503:                public void writeDefaultValue(Writer writer, String indent,
504:                        String path, String varName, JType tp)
505:                        throws IOException {
506:                    writer.write(tp.fullName());
507:                    writer.write(" ");
508:                    writer.write(varName);
509:                    writer.write(" = ");
510:                    if (tp.isArray()) {
511:                        writer.write("new ");
512:                        writer.write(tp.fullName());
513:                        writer.write(" {};");
514:                    } else if (DEFAULT_TYPE_MAP.contains(tp.fullName())) {
515:                        writeDefaultType(writer, tp, path);
516:                        writer.write(";");
517:                    } else if (tp instanceof  JDefinedClass) {
518:                        JDefinedClass jdc = (JDefinedClass) tp;
519:                        if (jdc.getClassType() == ClassType.ENUM) {
520:                            //no way to get the field list as it's private with 
521:                            //no accessors :-(
522:                            try {
523:                                Field f = jdc.getClass().getDeclaredField(
524:                                        "enumConstantsByName");
525:                                f.setAccessible(true);
526:                                Map map = (Map) f.get(jdc);
527:                                Set<String> values = CastUtils.cast(map
528:                                        .keySet());
529:                                String first = defaultValues.chooseEnumValue(
530:                                        path, values);
531:                                writer.write(tp.fullName());
532:                                writer.write(".");
533:                                writer.write(first);
534:                                writer.write(";");
535:                            } catch (Exception e) {
536:                                IOException ex = new IOException(e.getMessage());
537:                                ex.initCause(e);
538:                                throw ex;
539:                            }
540:                        } else {
541:                            writer.write("new ");
542:                            writer.write(tp.fullName());
543:                            writer.write("();");
544:                            fillInFields(writer, indent, path, varName, jdc);
545:                        }
546:                    } else {
547:                        boolean found = false;
548:                        JType tp2 = tp.erasure();
549:                        try {
550:                            Field f = tp2.getClass().getDeclaredField("_class");
551:                            f.setAccessible(true);
552:                            Class<?> cls = (Class) f.get(tp2);
553:                            if (List.class.isAssignableFrom(cls)) {
554:                                found = true;
555:
556:                                writer.write("new ");
557:                                writer.write(tp.fullName()
558:                                        .replace("java.util.List",
559:                                                "java.util.ArrayList"));
560:                                writer.write("();");
561:
562:                                f = tp.getClass().getDeclaredField("args");
563:                                f.setAccessible(true);
564:                                List<JClass> lcl = CastUtils.cast((List) f
565:                                        .get(tp));
566:                                JClass cl = lcl.get(0);
567:
568:                                int cnt = defaultValues.getListLength(path
569:                                        + "/" + varName);
570:                                for (int x = 0; x < cnt; x++) {
571:
572:                                    writer.write("\n");
573:                                    writer.write(indent);
574:                                    writeDefaultValue(writer, indent, path
575:                                            + "/" + varName + "Val", varName
576:                                            + "Val" + cnt, cl);
577:                                    writer.write("\n");
578:                                    writer.write(indent);
579:                                    writer.write(varName);
580:                                    writer.write(".add(");
581:                                    writer.write(varName + "Val" + cnt);
582:                                    writer.write(");");
583:                                }
584:                            }
585:                        } catch (Exception e) {
586:                            //ignore
587:                        }
588:
589:                        if (!found) {
590:                            //System.err.println("No idea what to do with " + tp.fullName());
591:                            //System.err.println("        class " + tp.getClass().getName());
592:                            writer.write("null;");
593:                        }
594:                    }
595:                }
596:
597:                public void fillInFields(Writer writer, String indent,
598:                        String path, String varName, JDefinedClass tp)
599:                        throws IOException {
600:                    JClass sp = tp._extends();
601:                    if (sp instanceof  JDefinedClass) {
602:                        fillInFields(writer, indent, path, varName,
603:                                (JDefinedClass) sp);
604:                    }
605:
606:                    Collection<JMethod> methods = tp.methods();
607:                    for (JMethod m : methods) {
608:                        if (m.name().startsWith("set")) {
609:                            writer.write("\n");
610:                            writer.write(indent);
611:                            if (DEFAULT_TYPE_MAP.contains(m.listParamTypes()[0]
612:                                    .fullName())) {
613:                                writer.write(varName);
614:                                writer.write(".");
615:                                writer.write(m.name());
616:                                writer.write("(");
617:                                writeDefaultType(writer, m.listParamTypes()[0],
618:                                        path + "/" + m.name().substring(3));
619:                                writer.write(");");
620:                            } else {
621:                                writeDefaultValue(writer, indent, path + "/"
622:                                        + m.name().substring(3), varName
623:                                        + m.name().substring(3), m
624:                                        .listParamTypes()[0]);
625:                                writer.write("\n");
626:                                writer.write(indent);
627:                                writer.write(varName);
628:                                writer.write(".");
629:                                writer.write(m.name());
630:                                writer.write("(");
631:                                writer.write(varName + m.name().substring(3));
632:                                writer.write(");");
633:                            }
634:                        } else if (m.type().fullName().startsWith(
635:                                "java.util.List")) {
636:                            writer.write("\n");
637:                            writer.write(indent);
638:                            writeDefaultValue(writer, indent, path + "/"
639:                                    + m.name().substring(3), varName
640:                                    + m.name().substring(3), m.type());
641:                            writer.write("\n");
642:                            writer.write(indent);
643:                            writer.write(varName);
644:                            writer.write(".");
645:                            writer.write(m.name());
646:                            writer.write("().addAll(");
647:                            writer.write(varName + m.name().substring(3));
648:                            writer.write(");");
649:                        }
650:                    }
651:                }
652:
653:                private void writeDefaultType(Writer writer, JType t,
654:                        String path) throws IOException {
655:                    String name = t.fullName();
656:                    writeDefaultType(writer, name, path);
657:
658:                }
659:
660:                private void writeDefaultType(Writer writer, String name,
661:                        String path) throws IOException {
662:                    if (JLDEFAULT_TYPE_MAP.containsKey(name)) {
663:                        writer.append(name.substring("java.lang.".length()))
664:                                .append(".valueOf(");
665:                        writeDefaultType(writer, JLDEFAULT_TYPE_MAP.get(name),
666:                                path);
667:                        writer.append(")");
668:                    } else if ("boolean".equals(name)) {
669:                        writer
670:                                .append(defaultValues.getBooleanValue(path) ? "true"
671:                                        : "false");
672:                    } else if ("int".equals(name)) {
673:                        writer.append(Integer.toString(defaultValues
674:                                .getIntValue(path)));
675:                    } else if ("long".equals(name)) {
676:                        writer
677:                                .append(
678:                                        Long.toString(defaultValues
679:                                                .getLongValue(path))).append(
680:                                        "l");
681:                    } else if ("short".equals(name)) {
682:                        writer.append("(short)").append(
683:                                Short.toString(defaultValues
684:                                        .getShortValue(path)));
685:                    } else if ("byte".equals(name)) {
686:                        writer.append("(byte)")
687:                                .append(
688:                                        Byte.toString(defaultValues
689:                                                .getByteValue(path)));
690:                    } else if ("float".equals(name)) {
691:                        writer.append(
692:                                Float.toString(defaultValues
693:                                        .getFloatValue(path))).append("f");
694:                    } else if ("double".equals(name)) {
695:                        writer.append(Double.toString(defaultValues
696:                                .getDoubleValue(path)));
697:                    } else if ("char".equals(name)) {
698:                        writer.append("(char)").append(
699:                                Character.toString(defaultValues
700:                                        .getCharValue(path)));
701:                    } else if ("java.lang.String".equals(name)) {
702:                        writer.append("\"").append(
703:                                defaultValues.getStringValue(path))
704:                                .append("\"");
705:                    } else if ("javax.xml.namespace.QName".equals(name)) {
706:                        QName qn = defaultValues.getQNameValue(path);
707:                        writer.append("new javax.xml.namespace.QName(\"")
708:                                .append(qn.getNamespaceURI()).append("\", \"")
709:                                .append(qn.getLocalPart()).append("\")");
710:                    } else if ("java.net.URI".equals(name)) {
711:                        writer.append("new java.net.URI(\"")
712:                                .append(
713:                                        defaultValues.getURIValue(path)
714:                                                .toASCIIString()).append("\")");
715:                    } else if ("java.math.BigInteger".equals(name)) {
716:                        writer.append("new java.math.BigInteger(\"").append(
717:                                defaultValues.getBigIntegerValue(path)
718:                                        .toString()).append("\")");
719:                    } else if ("java.math.BigDecimal".equals(name)) {
720:                        writer.append("new java.math.BigDecimal(\"").append(
721:                                defaultValues.getBigDecimalValue(path)
722:                                        .toString()).append("\")");
723:                    } else if ("javax.xml.datatype.XMLGregorianCalendar"
724:                            .equals(name)) {
725:                        writer
726:                                .append(
727:                                        "javax.xml.datatype.DatatypeFactory.newInstance().newXMLGregorianCalendar(\"")
728:                                .append(
729:                                        defaultValues
730:                                                .getXMLGregorianCalendarValueString(path))
731:                                .append("\")");
732:                    } else if ("javax.xml.datatype.Duration".equals(name)) {
733:                        writer
734:                                .append(
735:                                        "javax.xml.datatype.DatatypeFactory.newInstance().newDuration(\"")
736:                                .append(
737:                                        defaultValues
738:                                                .getDurationValueString(path))
739:                                .append("\")");
740:                    }
741:                }
742:            }
743:
744:        }
w_w___w___.j___a__va__2s___._c_o__m___ | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.