summaryrefslogtreecommitdiffstats
path: root/sca-java-1.x/tags/java-stable-20060304/sdo/impl/src/main/java/org/apache/tuscany/sdo/helper/XMLDocumentImpl.java
blob: 2626eb12ff05e4215bd227df7c2b8252d6537a9d (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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
/**
 *
 *  Copyright 2005 The Apache Software Foundation or its licensors, as applicable.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.apache.tuscany.sdo.helper;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.util.List;
import java.util.Map;

import org.apache.tuscany.sdo.SDOPackage;
import org.apache.tuscany.sdo.util.DataObjectUtil;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.util.ExtendedMetaData;
import org.eclipse.emf.ecore.xmi.XMLOptions;
import org.eclipse.emf.ecore.xmi.XMLParserPool;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.emf.ecore.xmi.impl.XMLOptionsImpl;
import org.eclipse.emf.ecore.xmi.impl.XMLParserPoolImpl;
import org.xml.sax.InputSource;

import commonj.sdo.DataObject;
import commonj.sdo.helper.XMLDocument;


/**
 * Represents an XML Document containing a tree of DataObjects.
 * 
 * An example XMLDocument fragment is:
 * <?xml version="1.0"?>
 * <purchaseOrder orderDate="1999-10-20">
 * 
 * created from this XML Schema fragment:
 * <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 *   <xsd:element name="purchaseOrder" type="PurchaseOrderType"/>
 *   <xsd:complexType name="PurchaseOrderType">
 *
 * Upon loading this XMLDocument:
 *   DataObject is an instance of Type PurchaseOrderType.
 *   RootElementURI is null because the XSD has no targetNamespace URI.
 *   RootElementName is purchaseOrder.
 *   Encoding is null because the document did not specify an encoding.
 *   XMLDeclaration is true because the document contained an XML declaration.
 *   XMLVersion is 1.0
 *   SchemaLocation and noNamespaceSchemaLocation are null because they are
 *     not specified in the document.
 * 
 * When saving the root element, if the type of the root dataObject is not the
 *   type of global element specified by rootElementURI and rootElementName, 
 *   or if a global element does not exist for rootElementURI and rootElementName,
 *   then an xsi:type declaration is written to record the root DataObject's Type.
 * 
 * When loading the root element and an xsi:type declaration is found
 *   it is used as the type of the root DataObject.  In this case,
 *   if validation is not being performed, it is not an error if the
 *   rootElementName is not a global element.
 */
public class XMLDocumentImpl implements XMLDocument
{
  protected ExtendedMetaData extendedMetaData;

  protected EObject rootObject;

  protected XMLResource resource;

  protected EStructuralFeature rootElement;

  protected EObject documentRoot;
  
  protected static XMLParserPool globalXMLParserPool = new XMLParserPoolImpl();
  
  //TODO clean up the options thing
  protected XMLDocumentImpl(ExtendedMetaData extendedMetaData, Object options)
  {
    this.extendedMetaData = extendedMetaData;
    ResourceSet resourceSet = DataObjectUtil.createResourceSet();
    
    if (options instanceof Map)
    {
      Class resourceFactoryClass = (Class)((Map)options).get("GENERATED_LOADER");
      if (resourceFactoryClass != null)
      {
        try
        {
          Object resourceFactory = resourceFactoryClass.newInstance();
          resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("*", resourceFactory);
        }
        catch (Exception e)
        {
          e.printStackTrace();
        }
      }
    }
  
    resource = (XMLResource)resourceSet.createResource(URI.createURI("http:///temp.xml"));
    
    XMLOptions xmlOptions = new XMLOptionsImpl();
    xmlOptions.setProcessAnyXML(true);
    resource.getDefaultLoadOptions().put(XMLResource.OPTION_XML_OPTIONS, xmlOptions);

    resource.getDefaultSaveOptions().put(XMLResource.OPTION_EXTENDED_META_DATA, extendedMetaData);
    resource.getDefaultLoadOptions().put(XMLResource.OPTION_EXTENDED_META_DATA, extendedMetaData);
    
    resource.getDefaultLoadOptions().put(XMLResource.OPTION_USE_PARSER_POOL, globalXMLParserPool);
    
    resource.getDefaultLoadOptions().put(XMLResource.OPTION_USE_DEPRECATED_METHODS, Boolean.FALSE);
    
    resource.getDefaultSaveOptions().put(XMLResource.OPTION_CONFIGURATION_CACHE, Boolean.TRUE);
    resource.getDefaultLoadOptions().put(XMLResource.OPTION_CONFIGURATION_CACHE, Boolean.TRUE);
    
    resource.getDefaultLoadOptions().put(XMLResource.OPTION_ANY_TYPE, SDOPackage.eINSTANCE.getAnyTypeDataObject());
    resource.getDefaultSaveOptions().put(XMLResource.OPTION_ANY_TYPE, SDOPackage.eINSTANCE.getAnyTypeDataObject());

    resource.getDefaultLoadOptions().put(XMLResource.OPTION_ANY_SIMPLE_TYPE, SDOPackage.eINSTANCE.getSimpleAnyTypeDataObject());
    resource.getDefaultSaveOptions().put(XMLResource.OPTION_ANY_SIMPLE_TYPE, SDOPackage.eINSTANCE.getSimpleAnyTypeDataObject());

    //resource.getDefaultLoadOptions().put(XMLResource.OPTION_USE_XML_NAME_TO_FEATURE_MAP, globalHashMap);

    //resource.getDefaultSaveOptions().put(XMLResource.OPTION_FORMATTED, Boolean.FALSE);
  }

  protected XMLDocumentImpl(ExtendedMetaData extendedMetaData)
  {
    this(extendedMetaData, null);
  }

  protected XMLDocumentImpl(ExtendedMetaData extendedMetaData, DataObject dataObject, String rootElementURI, String rootElementName)
  {
    this(extendedMetaData);

    rootObject = (EObject)dataObject;

    rootElement = extendedMetaData.getElement(rootElementURI, rootElementName);
    if (rootElement == null)
    {
      rootElement = ExtendedMetaData.INSTANCE.demandFeature(rootElementURI, rootElementName, true);
    }

    EClass documentRootClass = rootElement.getEContainingClass();
    documentRoot = EcoreUtil.create(documentRootClass);
    resource.getContents().add(documentRoot);
  }

  protected void save(OutputStream outputStream, Object options) throws IOException
  {
    EObject oldContainer = null;
    EReference oldContainmentReference = null;
    int oldContainmentIndex = -1;

    if (documentRoot != null)
    {
      //TODO also check if rootObject is directly contained in a resource
      oldContainer = rootObject.eContainer();
      if (oldContainer != null)
      {
        oldContainmentReference = rootObject.eContainmentFeature();
      }
      if (oldContainer != documentRoot || oldContainmentReference != rootElement)
      {
        if (oldContainmentReference != null && oldContainmentReference.isMany())
        {
          oldContainmentIndex = ((List)oldContainer.eGet(oldContainmentReference)).indexOf(rootObject);
        }
        documentRoot.eSet(rootElement, rootObject);
      }
    }

    resource.save(outputStream, (Map)options);

    if (oldContainer != null)
    {
      if (oldContainer != documentRoot || oldContainmentReference != rootElement)
      {
        if (oldContainmentReference.isMany())
        {
          ((List)oldContainer.eGet(oldContainmentReference)).add(oldContainmentIndex, rootObject);
        }
        else
        {
          oldContainer.eSet(oldContainmentReference, rootObject);
        }
      }
    }
    else if (documentRoot != null)
    {
      documentRoot.eSet(rootElement, null);
    }
  }

  protected void save(Writer outputWriter, Object options) throws IOException
  {
    // TODO temporary brute-force implementation ... to be replaced
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    save(outputStream, options);
    outputWriter.write(new String(outputStream.toByteArray()));
  }

  protected void load(InputStream inputStream, String locationURI, Object options) throws IOException
  {
    InputSource inputSource = new InputSource(inputStream);
    load(inputSource, locationURI, options);
  }

  protected void load(Reader inputReader, String locationURI, Object options) throws IOException
  {
    InputSource inputSource = new InputSource(inputReader);
    load(inputSource, locationURI, options);
  }

  protected void load(InputSource inputSource, String locationURI, Object options) throws IOException
  {
    rootObject = null;
    rootElement = null;
    documentRoot = null;

    if (locationURI != null)
    {
      inputSource.setSystemId(locationURI);
      resource.setURI(URI.createURI(locationURI));
    }

    resource.load(inputSource, (Map)options);

    if (!resource.getContents().isEmpty())
    {
      documentRoot = (EObject)resource.getContents().get(0);
      EClass documentRootClass = documentRoot.eClass();
      if ("".equals(extendedMetaData.getName(documentRootClass))) //TODO efficient way to check this? Maybe DataObject.getContainer should also check this?
      {
        if (!documentRoot.eContents().isEmpty())
        {
          rootObject = (EObject)documentRoot.eContents().get(0);
          rootElement = rootObject.eContainmentFeature();
          documentRoot.eUnset(rootElement);
        }
      }
      else
      {
        rootObject = documentRoot;
        documentRoot = null;
      }
    }
  }

  public DataObject getRootObject()
  {
    return (DataObject)rootObject;
  }

  public String getRootElementURI()
  {
    if (rootElement != null)
    {
      return extendedMetaData.getNamespace(rootElement);
    }
    else if (rootObject != null)
    {
      return extendedMetaData.getNamespace(rootObject.eClass());
    }
    return null;
  }

  public String getRootElementName()
  {
    if (rootElement != null)
    {
      return extendedMetaData.getName(rootElement);
    }
    else if (rootObject != null)
    {
      return extendedMetaData.getName(rootObject.eClass());
    }
    return null;
  }

  public String getEncoding()
  {
    return resource.getEncoding();
  }

  public void setEncoding(String encoding)
  {
    resource.setEncoding(encoding);
  }

  public boolean isXMLDeclaration()
  {
    return Boolean.FALSE.equals(resource.getDefaultSaveOptions().get(XMLResource.OPTION_DECLARE_XML));
  }

  public void setXMLDeclaration(boolean xmlDeclaration)
  {
    resource.getDefaultSaveOptions().put(XMLResource.OPTION_DECLARE_XML, xmlDeclaration ? Boolean.TRUE : Boolean.FALSE);
  }

  public String getXMLVersion()
  {
    return "1.0"; //TODO
  }

  public void setXMLVersion(String xmlVersion)
  {
    throw new UnsupportedOperationException(); //TODO
  }

  public String getSchemaLocation()
  {
    throw new UnsupportedOperationException(); //TODO
  }

  public void setSchemaLocation(String schemaLocation)
  {
    throw new UnsupportedOperationException(); //TODO
  }

  public String getNoNamespaceSchemaLocation()
  {
    throw new UnsupportedOperationException(); //TODO
  }

  public void setNoNamespaceSchemaLocation(String schemaLocation)
  {
    throw new UnsupportedOperationException(); //TODO
  }
}