summaryrefslogtreecommitdiffstats
path: root/sandbox/tools/xmlfromxsd/src/main/java/org/apache/tuscany/tools/xmlfromxsd/generate/XBbasedXMLGenerator.java
blob: 03029bdf436dcf1b5d854b87b2747849597a85e2 (plain)
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
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
package org.apache.tuscany.tools.xmlfromxsd.generate;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.wsdl.Definition;
import javax.wsdl.WSDLException;
import javax.wsdl.extensions.schema.Schema;
import javax.wsdl.factory.WSDLFactory;
import javax.wsdl.xml.WSDLReader;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.axis2.util.XMLUtils;
import org.apache.xmlbeans.SchemaType;
import org.apache.xmlbeans.SchemaTypeSystem;
import org.apache.xmlbeans.XmlBeans;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlOptions;
import org.apache.xmlbeans.impl.xsd2inst.SchemaInstanceGenerator;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import com.ibm.wsdl.util.xml.DOM2Writer;

public class XBbasedXMLGenerator extends SchemaInstanceGenerator implements XMLGenerator
{
	private XMLfromXSDConfiguration config = null;
	
	public XBbasedXMLGenerator(XMLfromXSDConfiguration config)
	{
		this.config = config;
		// config.setXsdInputStream(getClass().getResource(conf).openStream());
	}
	
	public void generateXML() throws Exception
	{
		SchemaTypeSystem sts = processXSDSources();
		SchemaType rootElementType = getRootElementSchemaType(sts);
		if ( rootElementType != null )
		{
			TuscanySampleXmlUtil xmlUtil = new TuscanySampleXmlUtil();
			xmlUtil.setGenerate_sample_data(config.isGenerateSampleData());
			String result = xmlUtil.createSampleForType(rootElementType);
	        config.getXmlOutputStream().write(result.getBytes());
	        //System.out.println(result);
		}
		else
		{
			System.out.println("Could not find a global element with name \"" + config.getRootElementLocalName() + "\"");
		}
	}
		
	protected SchemaType getRootElementSchemaType(SchemaTypeSystem sts)
	{
		SchemaType schemaType = null;
		
		if (sts == null)
        {
            System.out.println("No Schemas to process.");
        }
		else
		{
			//first check in the global types
			SchemaType[] globalTypes = sts.globalTypes();
	        for (int i = 0; i < globalTypes.length; i++)
	        {
	            if (config.getSchemaTypeName().equals(globalTypes[i].getName().getLocalPart()))
	            {
	            	schemaType = globalTypes[i];
	                break;
	            }
	        }
			
	        //next check for anonymous types defined inline within elements 
	        if ( schemaType == null )
	        {
		        SchemaType[] globalElems = sts.documentTypes();
		        for (int i = 0; i < globalElems.length; i++)
		        {
		            if (config.getSchemaTypeName().equals(globalElems[i].getDocumentElementName().getLocalPart()))
		            {
		            	schemaType = globalElems[i];
		                break;
		            }
		        }
	        }
		}
        return schemaType;
	}

	public void generateXML(XMLfromXSDConfiguration config) throws Exception
	{
		this.config = config;
		generateXML();
	}

	public XMLfromXSDConfiguration getConfig()
	{
		return config;
	}

	public void setConfig(XMLfromXSDConfiguration config)
	{
		this.config = config;
	}
	
	private Definition readInTheWSDLFile(InputStream wsdlStream) throws WSDLException 
	{
        WSDLReader reader = WSDLFactory.newInstance().newWSDLReader();
        reader.setFeature("javax.wsdl.importDocuments", true);

        /*File file = new File(uri);
        String baseURI;

        if (uri.startsWith("http://")){
            baseURI = uri;
        } else{
            if(file.getParentFile() == null){
               try {
                    baseURI = new File(".").getCanonicalFile().toURI().toString();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } else {
                baseURI = file.getParentFile().toURI().toString();
            }
        }
*/
        Document doc;
        try {
            doc = XMLUtils.newDocument(wsdlStream);
        } catch (ParserConfigurationException e) {
            throw new WSDLException(WSDLException.PARSER_ERROR,
                    "Parser Configuration Error",
                    e);
        } catch (SAXException e) {
            throw new WSDLException(WSDLException.PARSER_ERROR,
                    "Parser SAX Error",
                    e);

        } catch (IOException e) {
            throw new WSDLException(WSDLException.INVALID_WSDL, "IO Error", e);
        }

        return reader.readWSDL(config.getRootElementNamespaceURI(), doc);
    } 
	
	protected InputStream[] getXSDsFromWSDL(InputStream xsdInputStream) throws Exception 
	{
		Definition defn = readInTheWSDLFile(xsdInputStream);
		List list = defn.getTypes().getExtensibilityElements();
		
		InputStream[] xsdFragments = new InputStream[list.size()];
		
		Iterator iterator = list.iterator();
		Schema schemaElement = null;
		
		for ( int count = 0 ; count < list.size() ; ++count )
		{
			schemaElement  = (Schema)iterator.next();
			//System.out.println(" *** - " + element.getElementType().getNamespaceURI());
			//System.out.println(" **** - " + element + " & " + element.getClass().getPackage().getName());
			//System.out.println(DOM2Writer.nodeToString(element.getElement()));
			xsdFragments[count] = 
				new ByteArrayInputStream(DOM2Writer.nodeToString(schemaElement.getElement()).getBytes());
		}

		return xsdFragments;
	}
	
	protected  SchemaTypeSystem processXSDSources() throws Exception 
	{
		SchemaTypeSystem sts = null;
		if ( config.getXsdFileName().endsWith(XSD_FILE) )
		{
			sts =  processXSDs(new InputStream[]{ config.getXsdInputStream()} );
		}
		else if ( config.getXsdFileName().endsWith(WSDL_FILE) )
		{
			sts =  processXSDs(getXSDsFromWSDL(config.getXsdInputStream()));
		}
		return sts;
	}
	
	protected SchemaTypeSystem processXSDs(InputStream[] inputStreams)
	{
		List sdocs = new ArrayList();
        for (int i = 0; i < inputStreams.length; i++)
        {
            try
            {
                sdocs.add(XmlObject.Factory.parse(inputStreams[i],
                        (new XmlOptions()).setLoadLineNumbers().setLoadMessageDigest()));
            }
            catch (Exception e)
            {
                System.err.println("Can not load schema file: " + inputStreams[i] + ": ");
                e.printStackTrace();
            }
        }

        XmlObject[] schemas = (XmlObject[]) sdocs.toArray(new XmlObject[sdocs.size()]);
        
        SchemaTypeSystem sts = null;
        if (schemas.length > 0)
        {
            Collection errors = new ArrayList();
            XmlOptions compileOptions = new XmlOptions();
            /*if (dl)
                compileOptions.setCompileDownloadUrls();
            if (nopvr)
                compileOptions.setCompileNoPvrRule();
            if (noupa)
                compileOptions.setCompileNoUpaRule();
             */
            try
            {
                sts = XmlBeans.compileXsd(schemas, XmlBeans.getBuiltinTypeSystem(), compileOptions);
            }
            catch (Exception e)
            {
                if (errors.isEmpty() || !(e instanceof XmlException))
                    e.printStackTrace();

                System.out.println("Schema compilation errors: ");
                for (Iterator i = errors.iterator(); i.hasNext(); )
                    System.out.println(i.next());
            }
        }

        return sts;
	}
}