Source Code Cross Referenced for CodeGenerationUtility.java in  » Web-Services-AXIS2 » xmlbeans » org » apache » axis2 » xmlbeans » 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 AXIS2 » xmlbeans » org.apache.axis2.xmlbeans 
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:         */
019:
020:        package org.apache.axis2.xmlbeans;
021:
022:        import org.apache.axis2.description.AxisMessage;
023:        import org.apache.axis2.description.AxisOperation;
024:        import org.apache.axis2.description.AxisService;
025:        import org.apache.axis2.util.SchemaUtil;
026:        import org.apache.axis2.util.URLProcessor;
027:        import org.apache.axis2.util.XMLUtils;
028:        import org.apache.axis2.wsdl.WSDLConstants;
029:        import org.apache.axis2.wsdl.WSDLUtil;
030:        import org.apache.axis2.wsdl.codegen.CodeGenConfiguration;
031:        import org.apache.axis2.wsdl.codegen.extension.XMLBeansExtension;
032:        import org.apache.axis2.wsdl.databinding.DefaultTypeMapper;
033:        import org.apache.axis2.wsdl.databinding.JavaTypeMapper;
034:        import org.apache.axis2.wsdl.databinding.TypeMapper;
035:        import org.apache.axis2.wsdl.util.Constants;
036:        import org.apache.commons.logging.Log;
037:        import org.apache.commons.logging.LogFactory;
038:        import org.apache.ws.commons.schema.XmlSchema;
039:        import org.apache.ws.commons.schema.XmlSchemaCollection;
040:        import org.apache.xmlbeans.BindingConfig;
041:        import org.apache.xmlbeans.Filer;
042:        import org.apache.xmlbeans.SchemaGlobalElement;
043:        import org.apache.xmlbeans.SchemaProperty;
044:        import org.apache.xmlbeans.SchemaType;
045:        import org.apache.xmlbeans.SchemaTypeSystem;
046:        import org.apache.xmlbeans.XmlBeans;
047:        import org.apache.xmlbeans.XmlObject;
048:        import org.apache.xmlbeans.XmlOptions;
049:        import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument;
050:        import org.w3c.dom.Element;
051:        import org.xml.sax.EntityResolver;
052:        import org.xml.sax.InputSource;
053:        import org.xml.sax.SAXException;
054:
055:        import javax.xml.namespace.QName;
056:        import java.io.File;
057:        import java.io.FileOutputStream;
058:        import java.io.FileWriter;
059:        import java.io.IOException;
060:        import java.io.OutputStream;
061:        import java.io.StringReader;
062:        import java.io.StringWriter;
063:        import java.io.Writer;
064:        import java.io.InputStream;
065:        import java.io.ByteArrayOutputStream;
066:        import java.io.ByteArrayInputStream;
067:        import java.net.URL;
068:        import java.util.ArrayList;
069:        import java.util.Arrays;
070:        import java.util.HashMap;
071:        import java.util.Iterator;
072:        import java.util.List;
073:        import java.util.Map;
074:        import java.util.Stack;
075:        import java.util.StringTokenizer;
076:        import java.util.Vector;
077:
078:        /**
079:         * Framework-linked code used by XMLBeans data binding support. This is accessed via reflection from
080:         * the XMLBeans code generation extension when XMLBeans data binding is selected.
081:         */
082:        public class CodeGenerationUtility {
083:            public static final String SCHEMA_FOLDER = "schemas";
084:
085:            public static String MAPPINGS = "mappings";
086:            public static String MAPPING = "mapping";
087:            public static String MESSAGE = "message";
088:            public static String JAVA_NAME = "javaclass";
089:
090:            public static final String MAPPING_FOLDER = "Mapping";
091:            public static final String MAPPER_FILE_NAME = "mapper";
092:            public static final String SCHEMA_PATH = "/org/apache/axis2/wsdl/codegen/schema/";
093:
094:            private static final Log log = LogFactory
095:                    .getLog(CodeGenerationUtility.class);
096:            boolean debug = false;
097:
098:            /**
099:             * @param additionalSchemas
100:             * @throws RuntimeException
101:             */
102:            public static TypeMapper processSchemas(List schemas,
103:                    Element[] additionalSchemas, CodeGenConfiguration cgconfig,
104:                    String typeSystemName) throws RuntimeException {
105:                try {
106:
107:                    //check for the imported types. Any imported types are supposed to be here also
108:                    if (schemas == null || schemas.isEmpty()) {
109:                        //there are no types to be code generated
110:                        //However if the type mapper is left empty it will be a problem for the other
111:                        //processes. Hence the default type mapper is set to the configuration
112:                        return new DefaultTypeMapper();
113:                    }
114:
115:                    SchemaTypeSystem sts;
116:                    List completeSchemaList = new ArrayList();
117:                    List topLevelSchemaList = new ArrayList();
118:
119:                    //create the type mapper
120:                    //First try to take the one that is already there
121:                    TypeMapper mapper = cgconfig.getTypeMapper();
122:                    if (mapper == null) {
123:                        mapper = new JavaTypeMapper();
124:                    }
125:
126:                    //change the  default class name of the mapper to
127:                    //xmlbeans specific XMLObject
128:                    mapper.setDefaultMappingName(XmlObject.class.getName());
129:
130:                    Map nameSpacesMap = new HashMap();
131:                    List axisServices = cgconfig.getAxisServices();
132:                    AxisService axisService;
133:                    for (Iterator iter = axisServices.iterator(); iter
134:                            .hasNext();) {
135:                        axisService = (AxisService) iter.next();
136:                        nameSpacesMap.putAll(axisService.getNamespaceMap());
137:                    }
138:
139:                    // process all the schemas and make a list of all of them for
140:                    // resolving entities
141:                    for (int i = 0; i < schemas.size(); i++) {
142:                        XmlSchema schema = (XmlSchema) schemas.get(i);
143:                        XmlOptions options = new XmlOptions();
144:                        options.setLoadAdditionalNamespaces(nameSpacesMap); //add the namespaces
145:                        XmlSchema[] allSchemas = SchemaUtil
146:                                .getAllSchemas(schema);
147:                        for (int j = 0; j < allSchemas.length; j++) {
148:                            completeSchemaList.add(allSchemas[j]);
149:                        }
150:                    }
151:
152:                    //make another list of top level schemas for passing into XMLbeans
153:                    for (int i = 0; i < schemas.size(); i++) {
154:                        XmlSchema schema = (XmlSchema) schemas.get(i);
155:                        XmlOptions options = new XmlOptions();
156:                        options.setLoadAdditionalNamespaces(nameSpacesMap); //add the namespaces
157:                        topLevelSchemaList.add(XmlObject.Factory.parse(
158:                                getSchemaAsString(schema), options));
159:
160:                    }
161:
162:                    XmlSchemaCollection extras = new XmlSchemaCollection();
163:                    // add the third party schemas
164:                    //todo perhaps checking the namespaces would be a good idea to
165:                    //make the generated code work efficiently
166:                    for (int i = 0; i < additionalSchemas.length; i++) {
167:                        completeSchemaList.add(extras
168:                                .read(additionalSchemas[i]));
169:                        topLevelSchemaList.add(XmlObject.Factory.parse(
170:                                additionalSchemas[i], null));
171:                    }
172:
173:                    //compile the type system
174:                    Axis2EntityResolver er = new Axis2EntityResolver();
175:                    er.setSchemas((XmlSchema[]) completeSchemaList
176:                            .toArray(new XmlSchema[completeSchemaList.size()]));
177:                    er.setBaseUri(cgconfig.getBaseURI());
178:
179:                    String xsdConfigFile = (String) cgconfig.getProperties()
180:                            .get(XMLBeansExtension.XSDCONFIG_OPTION);
181:
182:                    sts = XmlBeans.compileXmlBeans(
183:                            // set the STS name; defaults to null, which makes the generated class
184:                            // include a unique (but random) STS name
185:                            typeSystemName, null,
186:                            convertToSchemaArray(topLevelSchemaList),
187:                            new Axis2BindingConfig(cgconfig
188:                                    .getUri2PackageNameMap(), xsdConfigFile),
189:                            XmlBeans.getContextTypeLoader(), new Axis2Filer(
190:                                    cgconfig), new XmlOptions()
191:                                    .setEntityResolver(er));
192:
193:                    // prune the generated schema type system and add the list of base64 types
194:                    cgconfig.putProperty(Constants.BASE_64_PROPERTY_KEY,
195:                            findBase64Types(sts));
196:                    cgconfig.putProperty(Constants.PLAIN_BASE_64_PROPERTY_KEY,
197:                            findPlainBase64Types(sts));
198:
199:                    SchemaTypeSystem internal = XmlBeans.getBuiltinTypeSystem();
200:                    SchemaType[] schemaTypes = internal.globalTypes();
201:                    for (int j = 0; j < schemaTypes.length; j++) {
202:                        mapper.addTypeMappingName(schemaTypes[j].getName(),
203:                                schemaTypes[j].getFullJavaName());
204:
205:                    }
206:
207:                    //get the schematypes and add the document types to the type mapper
208:                    schemaTypes = sts.documentTypes();
209:                    for (int j = 0; j < schemaTypes.length; j++) {
210:                        mapper.addTypeMappingName(schemaTypes[j]
211:                                .getDocumentElementName(), schemaTypes[j]
212:                                .getFullJavaName());
213:
214:                    }
215:
216:                    //process the unwrapped parameters
217:                    if (!cgconfig.isParametersWrapped()) {
218:                        //figure out the unwrapped operations
219:                        axisServices = cgconfig.getAxisServices();
220:                        for (Iterator servicesIter = axisServices.iterator(); servicesIter
221:                                .hasNext();) {
222:                            axisService = (AxisService) servicesIter.next();
223:                            for (Iterator operations = axisService
224:                                    .getOperations(); operations.hasNext();) {
225:                                AxisOperation op = (AxisOperation) operations
226:                                        .next();
227:
228:                                if (WSDLUtil.isInputPresentForMEP(op
229:                                        .getMessageExchangePattern())) {
230:                                    AxisMessage message = op
231:                                            .getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
232:                                    if (message != null
233:                                            && message
234:                                                    .getParameter(Constants.UNWRAPPED_KEY) != null) {
235:                                        SchemaGlobalElement xmlbeansElement = sts
236:                                                .findElement(message
237:                                                        .getElementQName());
238:                                        SchemaType sType = xmlbeansElement
239:                                                .getType();
240:
241:                                        SchemaProperty[] elementProperties = sType
242:                                                .getElementProperties();
243:                                        for (int i = 0; i < elementProperties.length; i++) {
244:                                            SchemaProperty elementProperty = elementProperties[i];
245:
246:                                            QName partQName = WSDLUtil
247:                                                    .getPartQName(
248:                                                            op
249:                                                                    .getName()
250:                                                                    .getLocalPart(),
251:                                                            WSDLConstants.INPUT_PART_QNAME_SUFFIX,
252:                                                            elementProperty
253:                                                                    .getName()
254:                                                                    .getLocalPart());
255:
256:                                            //this type is based on a primitive type- use the
257:                                            //primitive type name in this case
258:                                            String fullJaveName = elementProperty
259:                                                    .getType()
260:                                                    .getFullJavaName();
261:                                            if (elementProperty
262:                                                    .extendsJavaArray()) {
263:                                                fullJaveName = fullJaveName
264:                                                        .concat("[]");
265:                                            }
266:                                            mapper.addTypeMappingName(
267:                                                    partQName, fullJaveName);
268:                                            SchemaType primitiveType = elementProperty
269:                                                    .getType()
270:                                                    .getPrimitiveType();
271:
272:                                            if (primitiveType != null) {
273:                                                mapper
274:                                                        .addTypeMappingStatus(
275:                                                                partQName,
276:                                                                Boolean.TRUE);
277:                                            }
278:                                            if (elementProperty
279:                                                    .extendsJavaArray()) {
280:                                                mapper.addTypeMappingStatus(
281:                                                        partQName,
282:                                                        Constants.ARRAY_TYPE);
283:                                            }
284:                                        }
285:                                    }
286:                                }
287:
288:                                if (WSDLUtil.isOutputPresentForMEP(op
289:                                        .getMessageExchangePattern())) {
290:                                    AxisMessage message = op
291:                                            .getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
292:                                    if (message != null
293:                                            && message
294:                                                    .getParameter(Constants.UNWRAPPED_KEY) != null) {
295:                                        SchemaGlobalElement xmlbeansElement = sts
296:                                                .findElement(message
297:                                                        .getElementQName());
298:                                        SchemaType sType = xmlbeansElement
299:                                                .getType();
300:
301:                                        SchemaProperty[] elementProperties = sType
302:                                                .getElementProperties();
303:                                        for (int i = 0; i < elementProperties.length; i++) {
304:                                            SchemaProperty elementProperty = elementProperties[i];
305:
306:                                            QName partQName = WSDLUtil
307:                                                    .getPartQName(
308:                                                            op
309:                                                                    .getName()
310:                                                                    .getLocalPart(),
311:                                                            WSDLConstants.OUTPUT_PART_QNAME_SUFFIX,
312:                                                            elementProperty
313:                                                                    .getName()
314:                                                                    .getLocalPart());
315:
316:                                            //this type is based on a primitive type- use the
317:                                            //primitive type name in this case
318:                                            String fullJaveName = elementProperty
319:                                                    .getType()
320:                                                    .getFullJavaName();
321:                                            if (elementProperty
322:                                                    .extendsJavaArray()) {
323:                                                fullJaveName = fullJaveName
324:                                                        .concat("[]");
325:                                            }
326:                                            mapper.addTypeMappingName(
327:                                                    partQName, fullJaveName);
328:                                            SchemaType primitiveType = elementProperty
329:                                                    .getType()
330:                                                    .getPrimitiveType();
331:
332:                                            if (primitiveType != null) {
333:                                                mapper
334:                                                        .addTypeMappingStatus(
335:                                                                partQName,
336:                                                                Boolean.TRUE);
337:                                            }
338:                                            if (elementProperty
339:                                                    .extendsJavaArray()) {
340:                                                mapper.addTypeMappingStatus(
341:                                                        partQName,
342:                                                        Constants.ARRAY_TYPE);
343:                                            }
344:                                        }
345:                                    }
346:                                }
347:                            }
348:                        }
349:                    }
350:
351:                    //return mapper to be set in the config
352:                    return mapper;
353:
354:                } catch (Exception e) {
355:                    throw new RuntimeException(e);
356:                }
357:            }
358:
359:            /**
360:             * Populate the base64 types The algo is to look for simpletypes that have base64 content, and
361:             * then step out of that onestep and get the element. For now there's an extended check to see
362:             * whether the simple type is related to the Xmime:contentType!
363:             *
364:             * @param sts
365:             */
366:            private static List findBase64Types(SchemaTypeSystem sts) {
367:                List allSeenTypes = new ArrayList();
368:                List base64ElementQNamesList = new ArrayList();
369:                SchemaType outerType;
370:                //add the document types and global types
371:                allSeenTypes.addAll(Arrays.asList(sts.documentTypes()));
372:                allSeenTypes.addAll(Arrays.asList(sts.globalTypes()));
373:
374:                for (int i = 0; i < allSeenTypes.size(); i++) {
375:                    SchemaType sType = (SchemaType) allSeenTypes.get(i);
376:
377:                    if (sType.getContentType() == SchemaType.SIMPLE_CONTENT
378:                            && sType.getPrimitiveType() != null) {
379:                        if (org.apache.axis2.namespace.Constants.BASE_64_CONTENT_QNAME
380:                                .equals(sType.getPrimitiveType().getName())) {
381:                            outerType = sType.getOuterType();
382:                            //check the outer type further to see whether it has the contenttype attribute from
383:                            //XMime namespace
384:                            SchemaProperty[] properties = sType.getProperties();
385:                            for (int j = 0; j < properties.length; j++) {
386:                                if (org.apache.axis2.namespace.Constants.XMIME_CONTENT_TYPE_QNAME
387:                                        .equals(properties[j].getName())) {
388:                                    //add this only if it is a document type ??
389:                                    if (outerType.isDocumentType()) {
390:                                        base64ElementQNamesList.add(outerType
391:                                                .getDocumentElementName());
392:                                    }
393:                                    break;
394:                                }
395:                            }
396:                        }
397:                    }
398:                    //add any of the child types if there are any
399:                    allSeenTypes.addAll(Arrays
400:                            .asList(sType.getAnonymousTypes()));
401:                }
402:
403:                return base64ElementQNamesList;
404:            }
405:
406:            /**
407:             * @param sts
408:             * @return array list
409:             */
410:            private static List findPlainBase64Types(SchemaTypeSystem sts) {
411:                ArrayList allSeenTypes = new ArrayList();
412:
413:                allSeenTypes.addAll(Arrays.asList(sts.documentTypes()));
414:                allSeenTypes.addAll(Arrays.asList(sts.globalTypes()));
415:
416:                ArrayList base64Types = new ArrayList();
417:
418:                for (Iterator iterator = allSeenTypes.iterator(); iterator
419:                        .hasNext();) {
420:                    SchemaType stype = (SchemaType) iterator.next();
421:                    findPlainBase64Types(stype, base64Types, new ArrayList());
422:                }
423:
424:                return base64Types;
425:            }
426:
427:            /**
428:             * @param stype
429:             * @param base64Types
430:             */
431:            private static void findPlainBase64Types(SchemaType stype,
432:                    ArrayList base64Types, ArrayList processedTypes) {
433:
434:                SchemaProperty[] elementProperties = stype
435:                        .getElementProperties();
436:                QName name;
437:                SchemaType schemaType;
438:                for (int i = 0; i < elementProperties.length; i++) {
439:                    schemaType = elementProperties[i].getType();
440:                    name = elementProperties[i].getName();
441:                    if (!base64Types.contains(name)
442:                            && !processedTypes.contains(schemaType.getName())) {
443:                        processedTypes.add(stype.getName());
444:                        if (schemaType.isPrimitiveType()) {
445:                            SchemaType primitiveType = schemaType
446:                                    .getPrimitiveType();
447:                            if (org.apache.axis2.namespace.Constants.BASE_64_CONTENT_QNAME
448:                                    .equals(primitiveType.getName())) {
449:                                base64Types.add(name);
450:                            }
451:
452:                        } else {
453:                            findPlainBase64Types(schemaType, base64Types,
454:                                    processedTypes);
455:                        }
456:                    }
457:                }
458:
459:            }
460:
461:            /** Private class to generate the filer */
462:            private static class Axis2Filer implements  Filer {
463:
464:                private File location;
465:                private boolean flatten = false;
466:                private String resourceDirName;
467:                private String srcDirName;
468:                private static final String JAVA_FILE_EXTENSION = ".java";
469:
470:                private Axis2Filer(CodeGenConfiguration config) {
471:                    location = config.getOutputLocation();
472:                    flatten = config.isFlattenFiles();
473:                    resourceDirName = config.getResourceLocation();
474:                    srcDirName = config.getSourceLocation();
475:                }
476:
477:                public OutputStream createBinaryFile(String typename)
478:                        throws IOException {
479:                    File resourcesDirectory = flatten ? location : new File(
480:                            location, resourceDirName);
481:
482:                    if (!resourcesDirectory.exists()) {
483:                        resourcesDirectory.mkdirs();
484:                    }
485:                    File file = new File(resourcesDirectory, typename);
486:                    file.getParentFile().mkdirs();
487:                    file.createNewFile();
488:                    return new FileOutputStream(file);
489:                }
490:
491:                public Writer createSourceFile(String typename)
492:                        throws IOException {
493:                    typename = typename.replace('.', File.separatorChar);
494:
495:                    File outputDir = flatten ? location : new File(location,
496:                            srcDirName);
497:
498:                    if (!outputDir.exists()) {
499:                        outputDir.mkdirs();
500:                    }
501:                    File file = new File(outputDir, typename
502:                            + JAVA_FILE_EXTENSION);
503:                    file.getParentFile().mkdirs();
504:                    file.createNewFile();
505:                    return new FileWriter(file);
506:                }
507:            }
508:
509:            /**
510:             * Convert schema into a String
511:             *
512:             * @param schema
513:             */
514:            private static String getSchemaAsString(XmlSchema schema)
515:                    throws IOException {
516:                StringWriter writer = new StringWriter();
517:                schema.write(writer);
518:                return writer.toString();
519:            }
520:
521:            /**
522:             * Custom binding configuration for the code generator. This controls how the namespaces are
523:             * suffixed/prefixed
524:             */
525:            private static class Axis2BindingConfig extends BindingConfig {
526:
527:                private Map uri2packageMappings = null;
528:                private XSDConfig xsdConfig = null;
529:
530:                public Axis2BindingConfig(Map uri2packageMappings,
531:                        String xsdConfigfile) {
532:                    this .uri2packageMappings = uri2packageMappings;
533:                    if (this .uri2packageMappings == null) {
534:                        //make an empty one to avoid nasty surprises
535:                        this .uri2packageMappings = new HashMap();
536:                    }
537:
538:                    // Do we have an xsdconfig file?
539:                    if (xsdConfigfile != null) {
540:                        xsdConfig = new XSDConfig(xsdConfigfile);
541:                    }
542:                }
543:
544:                public String lookupPackageForNamespace(String uri) {
545:                    /* If the xsdconfig file has mappings, we'll use them instead of the -p option.
546:                     * If we have an xsdconfig file but no namespace to package mappings, then we'll
547:                     * defer to the -p option.
548:                     */
549:                    if (xsdConfig != null) {
550:                        if (xsdConfig.hasNamespaceToJavaPackageMappings) {
551:                            log.debug("RETURNING "
552:                                    + uri
553:                                    + " = "
554:                                    + xsdConfig.getNamespacesToJavaPackages()
555:                                            .get(uri));
556:                            return (String) xsdConfig
557:                                    .getNamespacesToJavaPackages().get(uri);
558:                        }
559:                    }
560:
561:                    if (uri2packageMappings.containsKey(uri)) {
562:                        return (String) uri2packageMappings.get(uri);
563:                    } else {
564:                        return URLProcessor.makePackageName(uri);
565:                    }
566:                }
567:
568:                public String lookupJavanameForQName(QName qname) {
569:                    /* The mappings are stored in the format:
570:                     * NAMESPACE:LOCAL_NAME, i.e.
571:                     * urn:weegietech:minerva:moduleType
572:                     */
573:                    if (xsdConfig != null) {
574:                        String key = qname.getNamespaceURI() + ":"
575:                                + qname.getLocalPart();
576:                        if (xsdConfig.getSchemaTypesToJavaNames().containsKey(
577:                                key)) {
578:                            log.debug("RETURNING "
579:                                    + qname.getLocalPart()
580:                                    + " = "
581:                                    + xsdConfig.getSchemaTypesToJavaNames()
582:                                            .get(key));
583:                            return (String) xsdConfig
584:                                    .getSchemaTypesToJavaNames().get(key);
585:                        } else {
586:                            return null;
587:                        }
588:                    } else {
589:                        return super .lookupJavanameForQName(qname);
590:                    }
591:
592:                }
593:            }
594:
595:            /**
596:             * Converts a given vector of schemaDocuments to XmlBeans processable schema objects. One
597:             * drawback we have here is the non-inclusion of untargeted namespaces
598:             *
599:             * @param vec
600:             * @return schema array
601:             */
602:            private static SchemaDocument.Schema[] convertToSchemaArray(List vec) {
603:                SchemaDocument[] schemaDocuments = (SchemaDocument[]) vec
604:                        .toArray(new SchemaDocument[vec.size()]);
605:                //remove duplicates
606:                Vector uniqueSchemas = new Vector(schemaDocuments.length);
607:                Vector uniqueSchemaTns = new Vector(schemaDocuments.length);
608:                SchemaDocument.Schema s;
609:                for (int i = 0; i < schemaDocuments.length; i++) {
610:                    s = schemaDocuments[i].getSchema();
611:                    if (!uniqueSchemaTns.contains(s.getTargetNamespace())) {
612:                        uniqueSchemas.add(s);
613:                        uniqueSchemaTns.add(s.getTargetNamespace());
614:                    } else if (s.getTargetNamespace() == null) {
615:                        uniqueSchemas.add(s);
616:                    }
617:                }
618:                return (SchemaDocument.Schema[]) uniqueSchemas
619:                        .toArray(new SchemaDocument.Schema[uniqueSchemas.size()]);
620:            }
621:
622:            /** Axis2 specific entity resolver */
623:            private static class Axis2EntityResolver implements  EntityResolver {
624:                private XmlSchema[] schemas;
625:                private String baseUri;
626:
627:                /**
628:                 * @param publicId - this is the target namespace
629:                 * @param systemId - this is the location (value of schemaLocation)
630:                 * @return
631:                 * @see EntityResolver#resolveEntity(String, String)
632:                 */
633:                public InputSource resolveEntity(String publicId,
634:                        String systemId) throws SAXException, IOException {
635:                    if (systemId.startsWith("project://local/")) {
636:                        systemId = systemId.substring("project://local/"
637:                                .length());
638:                    }
639:
640:                    StringTokenizer pathElements = new StringTokenizer(
641:                            systemId, "/");
642:                    Stack pathElementStack = new Stack();
643:                    while (pathElements.hasMoreTokens()) {
644:                        String pathElement = pathElements.nextToken();
645:                        if (".".equals(pathElement)) {
646:                        } else if ("..".equals(pathElement)) {
647:                            if (!pathElementStack.isEmpty())
648:                                pathElementStack.pop();
649:                        } else {
650:                            pathElementStack.push(pathElement);
651:                        }
652:                    }
653:                    StringBuffer pathBuilder = new StringBuffer();
654:                    for (Iterator iter = pathElementStack.iterator(); iter
655:                            .hasNext();) {
656:                        pathBuilder.append(File.separator + iter.next());
657:                    }
658:                    systemId = pathBuilder.toString().substring(1);
659:
660:                    log.info("Resolving schema with publicId [" + publicId
661:                            + "] and systemId [" + systemId + "]");
662:                    try {
663:                        for (int i = 0; i < schemas.length; i++) {
664:                            XmlSchema schema = schemas[i];
665:                            if (schema.getSourceURI() != null
666:                                    && schema.getSourceURI().endsWith(
667:                                            systemId.replaceAll("\\\\", "/"))) {
668:                                String path = schema.getSourceURI();
669:                                File f = getFileFromURI(path);
670:                                if (f.exists()) {
671:                                    InputSource source = new InputSource();
672:                                    source.setSystemId(schema.getSourceURI());
673:                                    return source;
674:                                } else {
675:                                    return new InputSource(
676:                                            getSchemaAsInputStream(schemas[i]));
677:                                }
678:                            }
679:
680:                        }
681:                        for (int i = 0; i < schemas.length; i++) {
682:                            XmlSchema schema = schemas[i];
683:                            if (schema.getTargetNamespace() != null
684:                                    && schema.getTargetNamespace().equals(
685:                                            publicId)) {
686:                                return new InputSource(
687:                                        getSchemaAsInputStream(schemas[i]));
688:                            }
689:                        }
690:                        if (systemId.indexOf(':') == -1) {
691:                            //if the base URI is missing then attache the file:/// to it
692:                            //if the systemId actually had a scheme then as per the URL
693:                            //constructor, the context URL scheme should be ignored
694:                            baseUri = (baseUri == null) ? "file:///" : baseUri;
695:                            URL url = new URL(baseUri + systemId);
696:                            InputSource source = new InputSource();
697:                            source.setSystemId(url.toString());
698:                            return source;
699:                        }
700:                        return XMLUtils.getEmptyInputSource();
701:                    } catch (Exception e) {
702:                        throw new SAXException(e);
703:                    }
704:                }
705:
706:                private File getFileFromURI(String path) {
707:                    if (path.startsWith("file:///")) {
708:                        path = path.substring(8);
709:                    } else if (path.startsWith("file://")) {
710:                        path = path.substring(7);
711:                    } else if (path.startsWith("file:/")) {
712:                        path = path.substring(6);
713:                    }
714:                    return new File(path);
715:                }
716:
717:                public XmlSchema[] getSchemas() {
718:                    return schemas;
719:                }
720:
721:                public void setSchemas(XmlSchema[] schemas) {
722:                    this .schemas = schemas;
723:                }
724:
725:                public String getBaseUri() {
726:                    return baseUri;
727:                }
728:
729:                public void setBaseUri(String baseUri) {
730:                    this .baseUri = baseUri;
731:                }
732:
733:                /**
734:                 * Convert schema into a InputStream
735:                 *
736:                 * @param schema
737:                 */
738:                private InputStream getSchemaAsInputStream(XmlSchema schema) {
739:                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
740:                    schema.write(baos);
741:                    return new ByteArrayInputStream(baos.toByteArray());
742:                }
743:            }
744:
745:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.