Some Eclipse Foundation services are deprecated, or will be soon. Please ensure you've read this important communication.
View | Details | Raw Unified | Return to bug 411377 | Differences between
and this patch

Collapse All | Expand All

(-)a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/XMLCompositeCollectionMappingNodeValue.java (-1 / +2 lines)
Lines 88-94 public class XMLCompositeCollectionMappingNodeValue extends XMLRelationshipMappi Link Here
88
        } else {
88
        } else {
89
        	return marshalRecord.emptyCollection(xPathFragment, namespaceResolver, xmlCompositeCollectionMapping.getWrapperNullPolicy() != null);
89
        	return marshalRecord.emptyCollection(xPathFragment, namespaceResolver, xmlCompositeCollectionMapping.getWrapperNullPolicy() != null);
90
        }
90
        }
91
        marshalRecord.startCollection(); 
91
        
92
        
92
        
93
        int size =marshalRecord.getCycleDetectionStack().size(); 
93
        int size =marshalRecord.getCycleDetectionStack().size(); 
94
        //when writing the collection need to see if any of the objects we are writing are in the parent collection inverse ref
94
        //when writing the collection need to see if any of the objects we are writing are in the parent collection inverse ref
Lines 98-103 public class XMLCompositeCollectionMappingNodeValue extends XMLRelationshipMappi Link Here
98
        		return false;
98
        		return false;
99
        	}
99
        	}
100
         }
100
         }
101
        marshalRecord.startCollection(); 
101
        iterator = cp.iteratorFor(collection);
102
        iterator = cp.iteratorFor(collection);
102
        while (cp.hasNext(iterator)) {
103
        while (cp.hasNext(iterator)) {
103
            Object objectValue = cp.next(iterator, session);
104
            Object objectValue = cp.next(iterator, session);
(-)a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/XMLMarshaller.java (-1 / +4 lines)
Lines 41-46 import org.eclipse.persistence.internal.core.sessions.CoreAbstractSession; Link Here
41
import org.eclipse.persistence.internal.oxm.mappings.Descriptor;
41
import org.eclipse.persistence.internal.oxm.mappings.Descriptor;
42
import org.eclipse.persistence.internal.oxm.mappings.Field;
42
import org.eclipse.persistence.internal.oxm.mappings.Field;
43
import org.eclipse.persistence.internal.oxm.record.AbstractMarshalRecord;
43
import org.eclipse.persistence.internal.oxm.record.AbstractMarshalRecord;
44
import org.eclipse.persistence.internal.oxm.record.ExtendedResult;
44
import org.eclipse.persistence.internal.oxm.record.namespaces.PrefixMapperNamespaceResolver;
45
import org.eclipse.persistence.internal.oxm.record.namespaces.PrefixMapperNamespaceResolver;
45
import org.eclipse.persistence.internal.security.PrivilegedAccessHelper;
46
import org.eclipse.persistence.internal.security.PrivilegedAccessHelper;
46
import org.eclipse.persistence.oxm.JSONWithPadding;
47
import org.eclipse.persistence.oxm.JSONWithPadding;
Lines 1009-1015 public abstract class XMLMarshaller< Link Here
1009
        } else if (result instanceof SAXResult) {
1010
        } else if (result instanceof SAXResult) {
1010
            SAXResult saxResult = (SAXResult) result;
1011
            SAXResult saxResult = (SAXResult) result;
1011
            marshal(object, saxResult.getHandler());
1012
            marshal(object, saxResult.getHandler());
1012
        } else {
1013
        } else if (result instanceof ExtendedResult){           
1014
            marshal(object, ((ExtendedResult)result).createRecord(), session, xmlDescriptor, isXMLRoot);
1015
        }else {
1013
            if (result.getClass().equals(staxResultClass)) {
1016
            if (result.getClass().equals(staxResultClass)) {
1014
                try {
1017
                try {
1015
                    Object xmlStreamWriter = PrivilegedAccessHelper.invokeMethod(staxResultGetStreamWriterMethod, result);
1018
                    Object xmlStreamWriter = PrivilegedAccessHelper.invokeMethod(staxResultGetStreamWriterMethod, result);
(-)a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/record/ExtendedResult.java (+32 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
3
 * This program and the accompanying materials are made available under the
4
 * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
5
 * which accompanies this distribution.
6
 * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
7
 * and the Eclipse Distribution License is available at
8
 * http://www.eclipse.org/org/documents/edl-v10.php.
9
 *
10
 * Contributors:
11
 *     Denise Smith - 2.6 - initial implementation
12
 ******************************************************************************/
13
package org.eclipse.persistence.internal.oxm.record;
14
15
import javax.xml.transform.Result;
16
17
public abstract class ExtendedResult implements Result {
18
19
    private String systemId;
20
21
    public abstract org.eclipse.persistence.oxm.record.MarshalRecord createRecord();
22
    
23
    @Override
24
    public void setSystemId(String systemId) {
25
        this.systemId = systemId;        
26
    }
27
28
    @Override
29
    public String getSystemId() {
30
        return systemId;
31
    }
32
}
(-)a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/record/json/JsonStructureReader.java (-116 / +2 lines)
Lines 40-109 import javax.xml.namespace.QName; Link Here
40
40
41
import org.eclipse.persistence.exceptions.XMLMarshalException;
41
import org.eclipse.persistence.exceptions.XMLMarshalException;
42
import org.eclipse.persistence.internal.oxm.CollectionGroupingElementNodeValue;
42
import org.eclipse.persistence.internal.oxm.CollectionGroupingElementNodeValue;
43
import org.eclipse.persistence.internal.oxm.ConversionManager;
44
import org.eclipse.persistence.internal.oxm.Constants;
43
import org.eclipse.persistence.internal.oxm.Constants;
45
import org.eclipse.persistence.internal.oxm.ContainerValue;
44
import org.eclipse.persistence.internal.oxm.ContainerValue;
46
import org.eclipse.persistence.internal.oxm.MappingNodeValue;
45
import org.eclipse.persistence.internal.oxm.MappingNodeValue;
47
import org.eclipse.persistence.internal.oxm.MediaType;
48
import org.eclipse.persistence.internal.oxm.NamespaceResolver;
46
import org.eclipse.persistence.internal.oxm.NamespaceResolver;
49
import org.eclipse.persistence.internal.oxm.NodeValue;
47
import org.eclipse.persistence.internal.oxm.NodeValue;
50
import org.eclipse.persistence.internal.oxm.Root;
48
import org.eclipse.persistence.internal.oxm.Root;
51
import org.eclipse.persistence.internal.oxm.Unmarshaller;
49
import org.eclipse.persistence.internal.oxm.Unmarshaller;
52
import org.eclipse.persistence.internal.oxm.XPathFragment;
50
import org.eclipse.persistence.internal.oxm.XPathFragment;
53
import org.eclipse.persistence.internal.oxm.mappings.Field;
54
import org.eclipse.persistence.internal.oxm.record.AbstractUnmarshalRecord;
55
import org.eclipse.persistence.internal.oxm.record.SAXUnmarshallerHandler;
51
import org.eclipse.persistence.internal.oxm.record.SAXUnmarshallerHandler;
56
import org.eclipse.persistence.internal.oxm.record.UnmarshalRecord;
52
import org.eclipse.persistence.internal.oxm.record.UnmarshalRecord;
57
import org.eclipse.persistence.internal.oxm.XPathNode;
53
import org.eclipse.persistence.internal.oxm.XPathNode;
58
import org.eclipse.persistence.internal.oxm.record.XMLReaderAdapter;
59
import org.eclipse.persistence.internal.oxm.record.deferred.DeferredContentHandler;
54
import org.eclipse.persistence.internal.oxm.record.deferred.DeferredContentHandler;
60
import org.eclipse.persistence.oxm.mappings.nullpolicy.AbstractNullPolicy;
61
import org.eclipse.persistence.oxm.record.XMLRootRecord;
55
import org.eclipse.persistence.oxm.record.XMLRootRecord;
62
import org.xml.sax.ErrorHandler;
63
import org.xml.sax.InputSource;
56
import org.xml.sax.InputSource;
64
import org.xml.sax.SAXException;
57
import org.xml.sax.SAXException;
65
import org.xml.sax.helpers.AttributesImpl;
58
import org.xml.sax.helpers.AttributesImpl;
66
59
67
public class JsonStructureReader extends XMLReaderAdapter {
60
public class JsonStructureReader extends JsonPReader {
68
61
69
    private static final String TRUE = "true";
70
    private static final String FALSE = "false";
71
    private String attributePrefix = null;
72
    private NamespaceResolver namespaces = null;
73
    private boolean includeRoot;
74
    private String textWrapper;
75
    private Class unmarshalClass;
76
    private boolean isInCollection;
77
    private JsonStructure jsonStructure;
62
    private JsonStructure jsonStructure;
78
    private JsonAttributes attributes = new JsonAttributes();
63
    private JsonAttributes attributes = new JsonAttributes();
79
64
80
81
    public JsonStructureReader(Unmarshaller u) {
65
    public JsonStructureReader(Unmarshaller u) {
82
        this(u, null);        
66
        this(u, null);        
83
    }
67
    }
84
    
68
    
85
    public JsonStructureReader(Unmarshaller u, Class clazz) {
69
    public JsonStructureReader(Unmarshaller u, Class clazz) {
86
        this(u.getAttributePrefix(), u.getNamespaceResolver(), u.getNamespaceResolver() != null, u.isIncludeRoot(), u.getNamespaceSeparator(), u.getErrorHandler(), u.getValueWrapper(), clazz);
70
        super(u.getAttributePrefix(), u.getNamespaceResolver(), u.getNamespaceResolver() != null, u.isIncludeRoot(), u.getNamespaceSeparator(), u.getErrorHandler(), u.getValueWrapper(), clazz);
87
    }
88
89
    private JsonStructureReader(String attrPrefix, NamespaceResolver nr,boolean namespaceAware, boolean includeRoot,Character namespaceSeparator, ErrorHandler errorHandler, String textWrapper, Class unmarshalClass) {
90
        this.attributePrefix = attrPrefix;
91
        if (attributePrefix == Constants.EMPTY_STRING) {
92
            attributePrefix = null;
93
        }
94
        namespaces = nr;
95
        this.namespaceAware = namespaceAware;
96
        if (namespaceSeparator == null) {
97
            this.namespaceSeparator = Constants.DOT;
98
        } else {
99
            this.namespaceSeparator = namespaceSeparator;
100
        }
101
        this.includeRoot = includeRoot;
102
        this.setErrorHandler(errorHandler);
103
        this.textWrapper = textWrapper;
104
        this.unmarshalClass = unmarshalClass;
105
    }
71
    }
106
    
107
72
108
    public void setJsonStructure(JsonStructure jsonStructure) {
73
    public void setJsonStructure(JsonStructure jsonStructure) {
109
        this.jsonStructure = jsonStructure;
74
        this.jsonStructure = jsonStructure;
Lines 152-168 public class JsonStructureReader extends XMLReaderAdapter { Link Here
152
        }
117
        }
153
    }
118
    }
154
119
155
    @Override
156
    public void parse(String systemId) {
157
        try {
158
            parse(new InputSource(systemId));
159
        } catch (IOException e) {
160
            throw XMLMarshalException.unmarshalException(e);
161
        } catch (SAXException e) {
162
            throw XMLMarshalException.unmarshalException(e);
163
        }
164
    }
165
166
    public void parseRoot(JsonValue jsonValue) throws SAXException {
120
    public void parseRoot(JsonValue jsonValue) throws SAXException {
167
        if (namespaces != null) {
121
        if (namespaces != null) {
168
            Map<String, String> namespacePairs = namespaces.getPrefixesToNamespaces();
122
            Map<String, String> namespacePairs = namespaces.getPrefixesToNamespaces();
Lines 453-526 public class JsonStructureReader extends XMLReaderAdapter { Link Here
453
407
454
    }
408
    }
455
409
456
    public boolean isNullRepresentedByXsiNil(AbstractNullPolicy nullPolicy) {
457
        return true;
458
    }
459
460
    private void startCollection() {
461
        isInCollection = true;
462
    }
463
464
    private void endCollection() {
465
        isInCollection = false;
466
    }
467
468
    public boolean isInCollection() {
469
        return isInCollection;
470
    }
471
472
    private boolean isTextValue(String localName) {
473
        XPathNode currentNode = ((UnmarshalRecord) contentHandler).getXPathNode();
474
        if (currentNode == null) {
475
            return textWrapper != null && textWrapper.equals(localName);
476
        }
477
478
        return ((currentNode.getNonAttributeChildrenMap() == null || currentNode.getNonAttributeChildrenMap().size() == 0 || (currentNode.getNonAttributeChildrenMap().size() == 1 && currentNode.getTextNode() != null))&& textWrapper != null && textWrapper.equals(localName));
479
    }
480
481
    @Override
482
    public Object convertValueBasedOnSchemaType(Field xmlField, Object value, ConversionManager conversionManager, AbstractUnmarshalRecord record) {
483
        if (xmlField.getSchemaType() != null) {
484
            if (Constants.QNAME_QNAME.equals(xmlField.getSchemaType())) {
485
                String stringValue = (String) value;
486
                int indexOpen = stringValue.indexOf('{');
487
                int indexClose = stringValue.indexOf('}');
488
                String uri = null;
489
                String localName = null;
490
                if (indexOpen > -1 && indexClose > -1) {
491
                    uri = stringValue.substring(indexOpen + 1, indexClose);
492
                    localName = stringValue.substring(indexClose + 1);
493
                } else {
494
                    QName obj = (QName) xmlField.convertValueBasedOnSchemaType(stringValue, conversionManager, record);
495
                    localName = obj.getLocalPart();
496
                    uri = obj.getNamespaceURI();
497
                }
498
                if (uri != null) {
499
                    return new QName(uri, localName);
500
                } else {
501
                    return new QName(localName);
502
                }
503
            } else {
504
                Class fieldType = xmlField.getType();
505
                if (fieldType == null) {
506
                    fieldType = xmlField.getJavaClass(xmlField.getSchemaType());
507
                }
508
                return conversionManager.convertObject(value, fieldType, xmlField.getSchemaType());
509
            }
510
        }
511
        return value;
512
    }
513
514
    /**
515
     * INTERNAL: The MediaType associated with this reader
516
     * 
517
     * @return
518
     */
519
    @Override
520
    public MediaType getMediaType() {
521
        return Constants.APPLICATION_JSON;
522
    }
523
524
    private static class JsonAttributes extends IndexedAttributeList {
410
    private static class JsonAttributes extends IndexedAttributeList {
525
411
526
        private JsonValue value;
412
        private JsonValue value;
(-)a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/oxm/XMLMarshaller.java (-3 / +26 lines)
Lines 12-17 Link Here
12
 ******************************************************************************/
12
 ******************************************************************************/
13
package org.eclipse.persistence.oxm;
13
package org.eclipse.persistence.oxm;
14
14
15
import java.io.IOException;
16
import java.lang.reflect.Array;
17
import java.util.Collection;
15
import java.util.Properties;
18
import java.util.Properties;
16
19
17
import javax.xml.transform.Result;
20
import javax.xml.transform.Result;
Lines 23-33 import org.eclipse.persistence.internal.oxm.Root; Link Here
23
import org.eclipse.persistence.internal.oxm.TreeObjectBuilder;
26
import org.eclipse.persistence.internal.oxm.TreeObjectBuilder;
24
import org.eclipse.persistence.internal.oxm.XMLObjectBuilder;
27
import org.eclipse.persistence.internal.oxm.XMLObjectBuilder;
25
import org.eclipse.persistence.internal.oxm.XPathEngine;
28
import org.eclipse.persistence.internal.oxm.XPathEngine;
29
import org.eclipse.persistence.internal.oxm.record.ExtendedResult;
26
import org.eclipse.persistence.internal.security.PrivilegedAccessHelper;
30
import org.eclipse.persistence.internal.security.PrivilegedAccessHelper;
27
import org.eclipse.persistence.internal.sessions.AbstractSession;
31
import org.eclipse.persistence.internal.sessions.AbstractSession;
28
import org.eclipse.persistence.oxm.documentpreservation.DocumentPreservationPolicy;
32
import org.eclipse.persistence.oxm.documentpreservation.DocumentPreservationPolicy;
29
import org.eclipse.persistence.oxm.record.MarshalRecord;
33
import org.eclipse.persistence.oxm.record.MarshalRecord;
30
import org.eclipse.persistence.oxm.record.NodeRecord;
34
import org.eclipse.persistence.oxm.record.NodeRecord;
35
import org.eclipse.persistence.oxm.record.WriterRecord;
31
import org.eclipse.persistence.oxm.record.XMLRecord;
36
import org.eclipse.persistence.oxm.record.XMLRecord;
32
import org.eclipse.persistence.platform.xml.XMLPlatformException;
37
import org.eclipse.persistence.platform.xml.XMLPlatformException;
33
import org.w3c.dom.Document;
38
import org.w3c.dom.Document;
Lines 123-129 public class XMLMarshaller extends org.eclipse.persistence.internal.oxm.XMLMarsh Link Here
123
        }
128
        }
124
        XMLDescriptor xmlDescriptor = null;
129
        XMLDescriptor xmlDescriptor = null;
125
        AbstractSession session = null;
130
        AbstractSession session = null;
126
        
131
               
127
        boolean isXMLRoot = (object instanceof Root);
132
        boolean isXMLRoot = (object instanceof Root);
128
        
133
        
129
        if(isXMLRoot){
134
        if(isXMLRoot){
Lines 139-146 public class XMLMarshaller extends org.eclipse.persistence.internal.oxm.XMLMarsh Link Here
139
            }
144
            }
140
        }else{
145
        }else{
141
            Class objectClass = object.getClass();
146
            Class objectClass = object.getClass();
142
            session = context.getSession(objectClass);
147
            if(result instanceof ExtendedResult){
143
            xmlDescriptor = getDescriptor(objectClass, session);
148
                MarshalRecord writerRecord = ((ExtendedResult)result).createRecord();
149
                if(object instanceof Collection){
150
                    writerRecord.startCollection();
151
                    for(Object o : (Collection) object) {                        
152
                        marshal(o, writerRecord);
153
                    }
154
                    writerRecord.endCollection();
155
                    return;
156
                }else{
157
                    marshal(object, writerRecord);
158
                    return;
159
                }
160
            }
161
            if(session == null || xmlDescriptor == null){
162
                session = context.getSession(objectClass);
163
                xmlDescriptor = getDescriptor(objectClass, session);
164
            }
165
            
166
            
144
        }
167
        }
145
168
146
        //if this is a simple xml root, the session and descriptor will be null
169
        //if this is a simple xml root, the session and descriptor will be null
(-)a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/oxm/json/JsonArrayBuilderResult.java (+42 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
3
 * This program and the accompanying materials are made available under the
4
 * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
5
 * which accompanies this distribution.
6
 * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
7
 * and the Eclipse Distribution License is available at
8
 * http://www.eclipse.org/org/documents/edl-v10.php.
9
 *
10
 * Contributors:
11
 *     Denise Smith - 2.6 - initial implementation
12
 ******************************************************************************/
13
package org.eclipse.persistence.oxm.json;
14
15
import javax.json.Json;
16
import javax.json.JsonArrayBuilder;
17
import org.eclipse.persistence.internal.oxm.record.ExtendedResult;
18
import org.eclipse.persistence.oxm.record.JsonObjectBuilderWriterRecord;
19
20
21
public class JsonArrayBuilderResult extends ExtendedResult{
22
23
    private JsonArrayBuilder jsonArrayBuilder;
24
        
25
    public JsonArrayBuilderResult(){
26
        this.jsonArrayBuilder = Json.createArrayBuilder();
27
    }
28
    
29
    public JsonArrayBuilderResult(JsonArrayBuilder jsonArrayBuilder){
30
        this.jsonArrayBuilder = jsonArrayBuilder;
31
    }
32
33
    @Override
34
    public org.eclipse.persistence.oxm.record.MarshalRecord createRecord() {       
35
         return new JsonObjectBuilderWriterRecord(jsonArrayBuilder);
36
    }
37
38
    public JsonArrayBuilder getJsonArrayBuilder() {
39
        return jsonArrayBuilder;
40
    }
41
42
}
(-)a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/oxm/json/JsonObjectBuilderResult.java (+43 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
3
 * This program and the accompanying materials are made available under the
4
 * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
5
 * which accompanies this distribution.
6
 * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
7
 * and the Eclipse Distribution License is available at
8
 * http://www.eclipse.org/org/documents/edl-v10.php.
9
 *
10
 * Contributors:
11
 *     Denise Smith - 2.6 - initial implementation
12
 ******************************************************************************/
13
package org.eclipse.persistence.oxm.json;
14
15
import javax.json.Json;
16
import javax.json.JsonObjectBuilder;
17
import org.eclipse.persistence.internal.oxm.record.ExtendedResult;
18
//import org.eclipse.persistence.internal.oxm.record.MarshalRecord;
19
import org.eclipse.persistence.oxm.record.JsonObjectBuilderWriterRecord;
20
21
22
public class JsonObjectBuilderResult extends ExtendedResult{
23
24
    private JsonObjectBuilder jsonObjectBuilder;
25
    
26
    public JsonObjectBuilderResult(){        
27
        this.jsonObjectBuilder = Json.createObjectBuilder();
28
    }
29
    
30
    public JsonObjectBuilderResult(JsonObjectBuilder jsonObjectBuilder){
31
        this.jsonObjectBuilder = jsonObjectBuilder;
32
    }
33
34
    @Override
35
    public org.eclipse.persistence.oxm.record.MarshalRecord createRecord() {       
36
         return new JsonObjectBuilderWriterRecord(jsonObjectBuilder);
37
    }
38
39
    public JsonObjectBuilder getJsonObjectBuilder() {
40
        return jsonObjectBuilder;
41
    }
42
43
}
(-)a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/oxm/record/JSONFormattedWriterRecord.java (-4 / +1 lines)
Lines 123-132 public class JSONFormattedWriterRecord extends JSONWriterRecord { Link Here
123
                }
123
                }
124
            }
124
            }
125
            if(xPathFragment.nameIsText()){
125
            if(xPathFragment.nameIsText()){
126
               if(position != null && position.isCollection() && position.isEmptyCollection()) {
126
               if(position != null && position.isCollection() && position.isEmptyCollection()) {            	    
127
            	    if(!charactersAllowed){
128
              		     throw JAXBException.jsonValuePropertyRequired("[");   
129
              	    }
130
                    writer.write('[');
127
                    writer.write('[');
131
                    writer.write(' ');
128
                    writer.write(' ');
132
                    position.setEmptyCollection(false);
129
                    position.setEmptyCollection(false);
(-)a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/oxm/record/JSONWriterRecord.java (-5 / +9 lines)
Lines 235-244 public class JSONWriterRecord extends MarshalRecord<XMLMarshaller> { Link Here
235
                }
235
                }
236
            }
236
            }
237
            if(xPathFragment.nameIsText()){
237
            if(xPathFragment.nameIsText()){
238
                if(position != null && position.isCollection() && position.isEmptyCollection()) {
238
                if(position != null && position.isCollection() && position.isEmptyCollection()) {                	
239
                	if(!charactersAllowed){
240
                		 throw JAXBException.jsonValuePropertyRequired("[");   
241
                	}
242
                    writer.write('[');                    
239
                    writer.write('[');                    
243
                    position.setEmptyCollection(false);
240
                    position.setEmptyCollection(false);
244
                    position.setNeedToOpenComplex(false);
241
                    position.setNeedToOpenComplex(false);
Lines 365-370 public class JSONWriterRecord extends MarshalRecord<XMLMarshaller> { Link Here
365
        } else {
362
        } else {
366
            levels.peek().setCollection(true);
363
            levels.peek().setCollection(true);
367
            levels.peek().setEmptyCollection(true);
364
            levels.peek().setEmptyCollection(true);
365
            charactersAllowed = false;
366
            isStartElementOpen = false;
368
        }
367
        }
369
    }
368
    }
370
    
369
    
Lines 408-421 public class JSONWriterRecord extends MarshalRecord<XMLMarshaller> { Link Here
408
     */
407
     */
409
     public void characters(String value, boolean isString, boolean isAttribute) {
408
     public void characters(String value, boolean isString, boolean isAttribute) {
410
    	  boolean textWrapperOpened = false;
409
    	  boolean textWrapperOpened = false;
410
    	  Level position = levels.peek();
411
          if(!charactersAllowed){    
411
          if(!charactersAllowed){    
412
        	   if(textWrapperFragment != null){
412
        	   if(textWrapperFragment != null){
413
        	       if(!isStartElementOpen && position.isFirst()){
414
        	           position.needToOpenComplex = true;
415
        	           position.needToOpenComplex = true;
416
        	       }
413
        		   openStartElement(textWrapperFragment, namespaceResolver);
417
        		   openStartElement(textWrapperFragment, namespaceResolver);
414
        		   textWrapperOpened = true;
418
        		   textWrapperOpened = true;
415
        	   }
419
        	   }
416
    	   }
420
    	   }
417
    	 
421
    	 
418
           Level position = levels.peek();
422
           position = levels.peek();
419
           position.setNeedToOpenComplex(false);
423
           position.setNeedToOpenComplex(false);
420
           try {
424
           try {
421
        	   if(isString){
425
        	   if(isString){
(-)a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/oxm/record/JsonObjectBuilderWriterRecord.java (+812 lines)
Added Link Here
1
package org.eclipse.persistence.oxm.record;
2
3
import java.io.IOException;
4
import java.io.StringWriter;
5
import java.math.BigDecimal;
6
import java.math.BigInteger;
7
import java.util.List;
8
9
import javax.json.Json;
10
import javax.json.JsonArrayBuilder;
11
import javax.json.JsonObjectBuilder;
12
import javax.xml.namespace.QName;
13
14
import org.eclipse.persistence.exceptions.XMLMarshalException;
15
import org.eclipse.persistence.internal.helper.ClassConstants;
16
import org.eclipse.persistence.internal.oxm.Constants;
17
import org.eclipse.persistence.internal.oxm.NamespaceResolver;
18
import org.eclipse.persistence.internal.oxm.ObjectBuilder;
19
import org.eclipse.persistence.internal.oxm.Root;
20
import org.eclipse.persistence.internal.oxm.XMLBinaryDataHelper;
21
import org.eclipse.persistence.internal.oxm.XMLConversionManager;
22
import org.eclipse.persistence.internal.oxm.XMLMarshaller;
23
import org.eclipse.persistence.internal.oxm.XPathFragment;
24
import org.eclipse.persistence.internal.oxm.mappings.Descriptor;
25
import org.eclipse.persistence.internal.oxm.record.ExtendedContentHandler;
26
import org.eclipse.persistence.internal.oxm.record.XMLFragmentReader;
27
import org.eclipse.persistence.oxm.CharacterEscapeHandler;
28
import org.w3c.dom.Attr;
29
import org.w3c.dom.Node;
30
import org.xml.sax.Attributes;
31
import org.xml.sax.Locator;
32
import org.xml.sax.SAXException;
33
import org.xml.sax.ext.LexicalHandler;
34
35
36
//TODO replace NULL string with addNUll
37
//TODO element method
38
public class JsonObjectBuilderWriterRecord extends MarshalRecord <XMLMarshaller> {
39
40
    private Level position;
41
    private JsonObjectBuilder rootJsonObjectBuilder;
42
    private JsonArrayBuilder rootJsonArrayBuilder;
43
    private CharacterEscapeHandler characterEscapeHandler;
44
45
    private String attributePrefix;
46
    private boolean isRootArray;
47
    private static final String NULL="null";
48
    private boolean isLastEventStart;
49
        
50
    public JsonObjectBuilderWriterRecord(){
51
        super();
52
        isLastEventStart = false;
53
    }
54
    
55
    public JsonObjectBuilderWriterRecord(JsonObjectBuilder jsonObjectBuilder){
56
        this();
57
        rootJsonObjectBuilder = jsonObjectBuilder;
58
    }
59
    
60
    public JsonObjectBuilderWriterRecord(JsonArrayBuilder jsonArrayBuilder){
61
        this();
62
        rootJsonArrayBuilder = jsonArrayBuilder;
63
    }
64
    
65
    /**
66
     * INTERNAL:
67
     */
68
    public void setMarshaller(XMLMarshaller marshaller) {
69
        super.setMarshaller(marshaller);
70
        attributePrefix = marshaller.getAttributePrefix();
71
        if (marshaller.getValueWrapper() != null) {
72
            textWrapperFragment = new XPathFragment();
73
            textWrapperFragment.setLocalName(marshaller.getValueWrapper());
74
        }
75
        characterEscapeHandler = marshaller.getCharacterEscapeHandler();
76
    }
77
    
78
    @Override
79
    public void startDocument(String encoding, String version) {      
80
        if(isRootArray){
81
            position.setEmptyCollection(false);
82
            
83
            Level newLevel = new Level(false, position);
84
            newLevel.setItemInCollection(true);
85
            position = newLevel;
86
            
87
            isLastEventStart = true;
88
        }else{
89
            Level rootLevel = new Level(false, null);
90
            position = rootLevel;
91
            if(rootJsonObjectBuilder == null){
92
                rootJsonObjectBuilder = Json.createObjectBuilder();
93
            }  
94
            
95
            rootLevel.setJsonObjectBuilder(rootJsonObjectBuilder);
96
        }
97
    }
98
99
    @Override
100
    public void endDocument() {
101
        if(position != null){
102
            if(position.isItemInCollection() && position.parentLevel != null){
103
                popAndSetInParentBuilder();
104
            }else{
105
                //this is the root level list case
106
                position = position.parentLevel;
107
            }            
108
        }
109
    }
110
    
111
    private void popAndSetInParentBuilder(){
112
        Level removedLevel = position;
113
        Level parentLevel = position.parentLevel;
114
        position = position.parentLevel;
115
        if(removedLevel.isCollection && removedLevel.isEmptyCollection() && removedLevel.keyName == null){
116
            return;
117
        }
118
      
119
        if(parentLevel != null){                  
120
            if(parentLevel.isCollection){
121
                if(removedLevel.isCollection){
122
                    parentLevel.getJsonArrayBuilder().add(removedLevel.getJsonArrayBuilder());
123
                }else{                   
124
                    parentLevel.getJsonArrayBuilder().add(removedLevel.getJsonObjectBuilder());
125
                }
126
            }else{
127
                if(removedLevel.isCollection){                    
128
                    parentLevel.getJsonObjectBuilder().add(removedLevel.getKeyName(), removedLevel.getJsonArrayBuilder());
129
                }else{
130
                    parentLevel.getJsonObjectBuilder().add(removedLevel.getKeyName(), removedLevel.getJsonObjectBuilder());
131
                }
132
            }
133
        }
134
        
135
    }    
136
    
137
    public void startCollection() {
138
        if(position == null){
139
             isRootArray = true;              
140
             Level rootLevel = new Level(true, null);
141
             if(rootJsonArrayBuilder == null){
142
                  rootJsonArrayBuilder = Json.createArrayBuilder();
143
             }
144
             rootLevel.setJsonArrayBuilder(rootJsonArrayBuilder);
145
             position = rootLevel;
146
        } else {            
147
            if(isLastEventStart){
148
                position.setComplex(true);           
149
            }            
150
            Level level = new Level(true, position);            
151
            position = level;
152
        }      
153
        isLastEventStart = false;
154
    }
155
    
156
    @Override
157
    public void endCollection() {
158
         popAndSetInParentBuilder();    
159
    }
160
    
161
    @Override    
162
    public void openStartElement(XPathFragment xPathFragment, NamespaceResolver namespaceResolver) {
163
        super.openStartElement(xPathFragment, namespaceResolver);
164
        if(position != null){
165
            Level newLevel = new Level(false, position);
166
            
167
            if(position.isCollection){
168
                newLevel.itemInCollection = true;            
169
            }            
170
          
171
            if(isLastEventStart){ 
172
                //this means 2 startevents in a row so the last this is a complex object
173
                position.setComplex(true);                                
174
            }
175
                      
176
            String keyName = getKeyName(xPathFragment);
177
           
178
            if(position.isCollection && position.isEmptyCollection() ){
179
                position.setKeyName(keyName);
180
            }else{
181
                newLevel.setKeyName(keyName);    
182
            }
183
            position = newLevel;   
184
            isLastEventStart = true;
185
        }
186
    }
187
    
188
    protected String getKeyName(XPathFragment xPathFragment){
189
        String keyName = xPathFragment.getLocalName(); 
190
       
191
        if(isNamespaceAware()){
192
            if(xPathFragment.getNamespaceURI() != null){
193
                String prefix = null;
194
                if(getNamespaceResolver() !=null){
195
                    prefix = getNamespaceResolver().resolveNamespaceURI(xPathFragment.getNamespaceURI());
196
                } else if(namespaceResolver != null){
197
                    prefix = namespaceResolver.resolveNamespaceURI(xPathFragment.getNamespaceURI());
198
                }
199
                if(prefix != null && !prefix.equals(Constants.EMPTY_STRING)){
200
                    keyName = prefix + getNamespaceSeparator() +  keyName;                           
201
                }
202
            }
203
        } 
204
        if(xPathFragment.isAttribute() && attributePrefix != null){
205
            keyName = attributePrefix + keyName;
206
        }
207
208
        return keyName;
209
    }
210
211
    public void attribute(XPathFragment xPathFragment, NamespaceResolver namespaceResolver,  Object value, QName schemaType){
212
        if(xPathFragment.getNamespaceURI() != null && xPathFragment.getNamespaceURI() == javax.xml.XMLConstants.XMLNS_ATTRIBUTE_NS_URI){
213
            return;
214
        }
215
        xPathFragment.setAttribute(true);
216
        openStartElement(xPathFragment, namespaceResolver);
217
        characters(schemaType, value, null, false, true);
218
        endElement(xPathFragment, namespaceResolver);
219
    }
220
    
221
    /**
222
     * INTERNAL:
223
     */
224
    @Override
225
    public void marshalWithoutRootElement(ObjectBuilder treeObjectBuilder, Object object, Descriptor descriptor, Root root, boolean isXMLRoot){
226
        if(treeObjectBuilder != null){
227
            addXsiTypeAndClassIndicatorIfRequired(descriptor, null, descriptor.getDefaultRootElementField(), root, object, isXMLRoot, true);
228
            treeObjectBuilder.marshalAttributes(this, object, session);
229
        }         
230
     }
231
    
232
    /**
233
     * INTERNAL:
234
     * The character used to separate the prefix and uri portions when namespaces are present 
235
     * @since 2.4
236
     */
237
    public char getNamespaceSeparator(){        
238
        return marshaller.getNamespaceSeparator();
239
    }
240
    
241
    /**
242
     * INTERNAL:
243
     * The optional fragment used to wrap the text() mappings
244
     * @since 2.4
245
     */
246
    public XPathFragment getTextWrapperFragment() {
247
        return textWrapperFragment;
248
    }
249
    
250
    @Override
251
    public boolean isWrapperAsCollectionName() {
252
        return marshaller.isWrapperAsCollectionName();
253
    }
254
    
255
    @Override
256
    public void element(XPathFragment frag) {
257
        isLastEventStart = false;
258
    }
259
    
260
    /**
261
     * Handle marshal of an empty collection.  
262
     * @param xPathFragment
263
     * @param namespaceResolver
264
     * @param openGrouping if grouping elements should be marshalled for empty collections
265
     * @return
266
     */    
267
    public boolean emptyCollection(XPathFragment xPathFragment, NamespaceResolver namespaceResolver, boolean openGrouping) {
268
269
         if(marshaller.isMarshalEmptyCollections()){
270
             super.emptyCollection(xPathFragment, namespaceResolver, true);
271
             
272
             if (null != xPathFragment) {
273
                 
274
                 if(xPathFragment.isSelfFragment() || xPathFragment.nameIsText()){
275
                     String keyName = position.getKeyName();
276
                     position.setComplex(false);
277
                     position.parentLevel.getJsonObjectBuilder().add(keyName, Json.createArrayBuilder());                     
278
                 }else{ 
279
                     if(isLastEventStart){
280
                         position.setComplex(true);                  
281
                     }                 
282
                     String keyName =  getKeyName(xPathFragment);
283
                     if(keyName != null){
284
                        position.getJsonObjectBuilder().add(keyName, Json.createArrayBuilder());
285
                     }
286
                 }
287
                 isLastEventStart = false;   
288
             }
289
                  
290
             return true;
291
         }else{
292
             return super.emptyCollection(xPathFragment, namespaceResolver, openGrouping);
293
         }
294
    }
295
296
    @Override
297
    public void attribute(XPathFragment xPathFragment,NamespaceResolver namespaceResolver, String value) {
298
        attribute(xPathFragment, namespaceResolver, value, null);
299
    }
300
301
    @Override
302
    public void attribute(String namespaceURI, String localName, String qName, String value) {
303
        XPathFragment xPathFragment = new XPathFragment();
304
        xPathFragment.setNamespaceURI(namespaceURI);
305
        xPathFragment.setAttribute(true);
306
        xPathFragment.setLocalName(localName);
307
308
        openStartElement(xPathFragment, namespaceResolver);
309
        characters(null, value, null, false, true);
310
311
        endElement(xPathFragment, namespaceResolver);
312
        
313
    }
314
315
    @Override
316
    public void closeStartElement() {}
317
318
    @Override
319
    public void endElement(XPathFragment xPathFragment,NamespaceResolver namespaceResolver) {
320
        if(position != null){
321
            if(isLastEventStart){
322
                position.setComplex(true);
323
            }
324
            if(position.isComplex){
325
                popAndSetInParentBuilder();
326
            }else{
327
                position = position.parentLevel;
328
            }            
329
            isLastEventStart = false;          
330
        }
331
    }
332
333
    @Override
334
    public void characters(String value) {
335
        writeValue(value, null, false);
336
    }
337
338
    @Override
339
    public void characters(QName schemaType, Object value, String mimeType, boolean isCDATA){          
340
        characters(schemaType, value, mimeType, isCDATA, false);
341
     }
342
    
343
    public void characters(QName schemaType, Object value, String mimeType, boolean isCDATA, boolean isAttribute){
344
        if(mimeType != null) {
345
            if(value instanceof List){
346
               value = XMLBinaryDataHelper.getXMLBinaryDataHelper().getBytesListForBinaryValues((List)value, marshaller, mimeType);
347
           }else{
348
349
            value = XMLBinaryDataHelper.getXMLBinaryDataHelper().getBytesForBinaryValue(value, marshaller, mimeType).getData();
350
           }
351
        }         
352
        if(schemaType != null && Constants.QNAME_QNAME.equals(schemaType)){
353
            String convertedValue = getStringForQName((QName)value);
354
            writeValue(convertedValue, null, isAttribute);
355
        } 
356
        else if(value.getClass() == String.class){          
357
            //if schemaType is set and it's a numeric or boolean type don't treat as a string
358
            if(schemaType != null && isNumericOrBooleanType(schemaType)){
359
                Class theClass = (Class) ((XMLConversionManager) session.getDatasourcePlatform().getConversionManager()).getDefaultXMLTypes().get(schemaType);
360
                Object convertedValue = ((XMLConversionManager) session.getDatasourcePlatform().getConversionManager()).convertObject(value, theClass, schemaType);
361
                writeValue(convertedValue, schemaType, isAttribute);
362
            }else if(isCDATA){
363
                cdata((String)value);
364
            }else{
365
                writeValue((String)value, null, isAttribute);                
366
            }
367
       }else{
368
           Class theClass = (Class) ((XMLConversionManager) session.getDatasourcePlatform().getConversionManager()).getDefaultXMLTypes().get(schemaType);          
369
370
           if(schemaType == null || theClass == null){
371
               if(value.getClass() == ClassConstants.BOOLEAN || ClassConstants.NUMBER.isAssignableFrom(value.getClass())){
372
                   writeValue(value, schemaType, isAttribute);
373
               }else{
374
                   String convertedValue = ((String) ((XMLConversionManager) session.getDatasourcePlatform().getConversionManager()).convertObject(value, ClassConstants.STRING, schemaType));
375
                   writeValue(convertedValue, schemaType, isAttribute);
376
               }
377
           }else if(schemaType != null && !isNumericOrBooleanType(schemaType)){
378
               //if schemaType exists and is not boolean or number do write quotes (convert to string)
379
               String convertedValue = ((String) ((XMLConversionManager) session.getDatasourcePlatform().getConversionManager()).convertObject(value, ClassConstants.STRING, schemaType));
380
               writeValue(convertedValue, schemaType, isAttribute);
381
           } else if(isCDATA){
382
               String convertedValue = ((String) ((XMLConversionManager) session.getDatasourcePlatform().getConversionManager()).convertObject(value, ClassConstants.STRING, schemaType));
383
               cdata(convertedValue);
384
           }else{
385
               writeValue(value, schemaType, isAttribute);           
386
           }
387
       }        
388
    }
389
    
390
    
391
    private boolean isNumericOrBooleanType(QName schemaType){
392
        if(schemaType == null){
393
            return false;
394
        }else if(schemaType.equals(Constants.BOOLEAN_QNAME)
395
                || schemaType.equals(Constants.INTEGER_QNAME)
396
                || schemaType.equals(Constants.INT_QNAME)
397
                || schemaType.equals(Constants.BYTE_QNAME)
398
                || schemaType.equals(Constants.DECIMAL_QNAME)
399
                || schemaType.equals(Constants.FLOAT_QNAME)
400
                || schemaType.equals(Constants.DOUBLE_QNAME)
401
                || schemaType.equals(Constants.SHORT_QNAME)
402
                || schemaType.equals(Constants.LONG_QNAME)
403
                || schemaType.equals(Constants.NEGATIVE_INTEGER_QNAME)
404
                || schemaType.equals(Constants.NON_NEGATIVE_INTEGER_QNAME)
405
                || schemaType.equals(Constants.NON_POSITIVE_INTEGER_QNAME)
406
                || schemaType.equals(Constants.POSITIVE_INTEGER_QNAME)
407
                || schemaType.equals(Constants.UNSIGNED_BYTE_QNAME)
408
                || schemaType.equals(Constants.UNSIGNED_INT_QNAME)
409
                || schemaType.equals(Constants.UNSIGNED_LONG_QNAME)
410
                || schemaType.equals(Constants.UNSIGNED_SHORT_QNAME)
411
        ){
412
            return true;
413
        }
414
        return false;
415
    }
416
    
417
    public void writeValue(Object value, QName schemaType, boolean isAttribute) {
418
        
419
        if (characterEscapeHandler != null && value instanceof String) {
420
            try {
421
                StringWriter stringWriter = new StringWriter();
422
                characterEscapeHandler.escape(((String)value).toCharArray(), 0, ((String)value).length(), isAttribute, stringWriter);
423
                value = stringWriter.toString();
424
            } catch (IOException e) {
425
                throw XMLMarshalException.marshalException(e);
426
            }
427
        }
428
        
429
        boolean textWrapperOpened = false;                       
430
        if(!isLastEventStart){
431
             openStartElement(textWrapperFragment, namespaceResolver);
432
             textWrapperOpened = true;
433
        }
434
      
435
        Level currentLevel = position;
436
        String keyName = position.getKeyName();
437
        if(!position.isComplex){           
438
            currentLevel = position.parentLevel;
439
            currentLevel.setComplex(true);          
440
        }
441
        if(currentLevel.isCollection()){
442
            currentLevel.setEmptyCollection(false);
443
            addValueToArrayBuilder(currentLevel.getJsonArrayBuilder(), value, schemaType);            
444
        } else {
445
            JsonObjectBuilder builder = currentLevel.getJsonObjectBuilder();                   
446
            addValueToObjectBuilder(builder, keyName, value, schemaType);          
447
        }
448
        isLastEventStart = false;
449
        if(textWrapperOpened){    
450
             endElement(textWrapperFragment, namespaceResolver);
451
        }    
452
    }
453
    
454
    private void addValueToObjectBuilder(JsonObjectBuilder jsonObjectBuilder, String keyName, Object value, QName schemaType){
455
        if(value == NULL){
456
            jsonObjectBuilder.addNull(keyName);
457
        }else if(value instanceof Integer){
458
            jsonObjectBuilder.add(keyName, (Integer)value);  
459
        }else if(value instanceof BigDecimal){
460
            jsonObjectBuilder.add(keyName, (BigDecimal)value);   
461
        }else if(value instanceof BigInteger){
462
            jsonObjectBuilder.add(keyName, (BigInteger)value);               
463
        }else if(value instanceof Boolean){
464
            jsonObjectBuilder.add(keyName, (Boolean)value);
465
        }else if(value instanceof Character){
466
            jsonObjectBuilder.add(keyName, (Character)value);  
467
        }else if(value instanceof Double){
468
            jsonObjectBuilder.add(keyName, (Double)value);
469
        }else if(value instanceof Float){
470
            jsonObjectBuilder.add(keyName, (Float)value);
471
        }else if(value instanceof Long){
472
            jsonObjectBuilder.add(keyName, (Long)value);
473
        }else if(value instanceof String){
474
            jsonObjectBuilder.add(keyName, (String)value);                
475
        }else{
476
            String convertedValue = ((String) ((XMLConversionManager) session.getDatasourcePlatform().getConversionManager()).convertObject(value, ClassConstants.STRING, schemaType));
477
            Class theClass = (Class) ((XMLConversionManager) session.getDatasourcePlatform().getConversionManager()).getDefaultXMLTypes().get(schemaType);          
478
            if((schemaType == null || theClass == null) && (ClassConstants.NUMBER.isAssignableFrom(value.getClass()))){
479
                //if it's still a number and falls through the cracks we dont want "" around the value
480
                    BigDecimal convertedNumberValue = ((BigDecimal) ((XMLConversionManager) session.getDatasourcePlatform().getConversionManager()).convertObject(value, ClassConstants.BIGDECIMAL, schemaType));
481
                    jsonObjectBuilder.add(keyName, (BigDecimal)convertedNumberValue);
482
            }else{
483
                jsonObjectBuilder.add(keyName, convertedValue);
484
            }
485
                
486
        }
487
    }
488
    
489
    private void addValueToArrayBuilder(JsonArrayBuilder jsonArrayBuilder, Object value, QName schemaType){
490
        if(value == NULL){
491
            jsonArrayBuilder.addNull();
492
        }else if(value instanceof Integer){
493
            jsonArrayBuilder.add((Integer)value);  
494
        }else if(value instanceof BigDecimal){
495
            jsonArrayBuilder.add((BigDecimal)value);   
496
        }else if(value instanceof BigInteger){
497
            jsonArrayBuilder.add((BigInteger)value);               
498
        }else if(value instanceof Boolean){                
499
            jsonArrayBuilder.add((Boolean)value);
500
        }else if(value instanceof Character){
501
            jsonArrayBuilder.add((Character)value);  
502
        }else if(value instanceof Double){
503
            jsonArrayBuilder.add((Double)value);
504
        }else if(value instanceof Float){
505
            jsonArrayBuilder.add((Float)value);
506
        }else if(value instanceof Long){
507
            jsonArrayBuilder.add((Long)value);
508
        }else if(value instanceof String){
509
            jsonArrayBuilder.add((String)value);
510
        }else{
511
            String convertedValue = ((String) ((XMLConversionManager) session.getDatasourcePlatform().getConversionManager()).convertObject(value, ClassConstants.STRING, schemaType));
512
            Class theClass = (Class) ((XMLConversionManager) session.getDatasourcePlatform().getConversionManager()).getDefaultXMLTypes().get(schemaType);          
513
            if((schemaType == null || theClass == null) && (ClassConstants.NUMBER.isAssignableFrom(value.getClass()))){
514
                //if it's still a number and falls through the cracks we dont want "" around the value
515
                    BigDecimal convertedNumberValue = ((BigDecimal) ((XMLConversionManager) session.getDatasourcePlatform().getConversionManager()).convertObject(value, ClassConstants.BIGDECIMAL, schemaType));
516
                    jsonArrayBuilder.add((BigDecimal)convertedNumberValue);
517
            }else{
518
                jsonArrayBuilder.add(convertedValue);
519
            }
520
        }
521
    }
522
    
523
    @Override
524
    public void cdata(String value) {
525
        characters(value);        
526
    }
527
528
    @Override
529
    public void node(Node node, NamespaceResolver resolver, String uri, String name) {
530
       
531
        if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
532
            Attr attr = (Attr) node;
533
            String resolverPfx = null;
534
            if (getNamespaceResolver() != null) {
535
                resolverPfx = this.getNamespaceResolver().resolveNamespaceURI(attr.getNamespaceURI());
536
            }
537
            String namespaceURI = attr.getNamespaceURI();
538
            // If the namespace resolver contains a prefix for the attribute's URI,
539
            // use it instead of what is set on the attribute
540
            if (resolverPfx != null) {
541
                attribute(attr.getNamespaceURI(), Constants.EMPTY_STRING, resolverPfx+Constants.COLON+attr.getLocalName(), attr.getNodeValue());
542
            } else {
543
                attribute(attr.getNamespaceURI(), Constants.EMPTY_STRING, attr.getName(), attr.getNodeValue());
544
                // May need to declare the URI locally
545
                if (attr.getNamespaceURI() != null) {
546
                    attribute(javax.xml.XMLConstants.XMLNS_ATTRIBUTE_NS_URI, Constants.EMPTY_STRING, javax.xml.XMLConstants.XMLNS_ATTRIBUTE + Constants.COLON + attr.getPrefix(), attr.getNamespaceURI());
547
                    this.getNamespaceResolver().put(attr.getPrefix(), attr.getNamespaceURI());
548
                }
549
            }
550
        } else if (node.getNodeType() == Node.TEXT_NODE) {
551
            writeValue(node.getNodeValue(), null, false);
552
        } else {
553
            try {
554
                JsonObjectBuilderRecordContentHandler wrcHandler = new JsonObjectBuilderRecordContentHandler();
555
                
556
                XMLFragmentReader xfragReader = new XMLFragmentReader(namespaceResolver);
557
                xfragReader.setContentHandler(wrcHandler);
558
                xfragReader.setProperty("http://xml.org/sax/properties/lexical-handler", wrcHandler);
559
                xfragReader.parse(node, uri, name);
560
            } catch (SAXException sex) {
561
                throw XMLMarshalException.marshalException(sex);
562
            }
563
        }
564
        
565
    }        
566
    
567
    protected String getStringForQName(QName qName){
568
        if(null == qName) {
569
            return null;
570
        }
571
        XMLConversionManager xmlConversionManager = (XMLConversionManager) getSession().getDatasourcePlatform().getConversionManager();
572
573
        return (String) xmlConversionManager.convertObject(qName, String.class);       
574
    }
575
576
    /**
577
     * INTERNAL:
578
     */
579
     public void namespaceDeclarations(NamespaceResolver namespaceResolver) {
580
     }
581
582
     public void namespaceDeclaration(String prefix, String namespaceURI){
583
     }
584
     
585
     public void defaultNamespaceDeclaration(String defaultNamespace){
586
     }
587
     
588
    /**
589
     * INTERNAL:
590
     */
591
     public void nilComplex(XPathFragment xPathFragment, NamespaceResolver namespaceResolver){
592
         XPathFragment groupingFragment = openStartGroupingElements(namespaceResolver);
593
         closeStartGroupingElements(groupingFragment);
594
         openStartElement(xPathFragment, namespaceResolver);
595
         characters(NULL);
596
         endElement(xPathFragment, namespaceResolver);
597
     }
598
599
    /**
600
     * INTERNAL:
601
     */
602
     public void nilSimple(NamespaceResolver namespaceResolver){
603
         XPathFragment groupingFragment = openStartGroupingElements(namespaceResolver);         
604
         characters(NULL);        
605
         closeStartGroupingElements(groupingFragment);
606
     }
607
608
     /**
609
      * Used when an empty simple value should be written
610
      * @since EclipseLink 2.4
611
      */
612
     public void emptySimple(NamespaceResolver namespaceResolver){
613
         nilSimple(namespaceResolver);
614
     }
615
     
616
     public void emptyAttribute(XPathFragment xPathFragment,NamespaceResolver namespaceResolver){
617
         XPathFragment groupingFragment = openStartGroupingElements(namespaceResolver);
618
         openStartElement(xPathFragment, namespaceResolver);
619
         characters(NULL);
620
         endElement(xPathFragment, namespaceResolver);
621
         closeStartGroupingElements(groupingFragment);
622
     }
623
624
     /**
625
      * Used when an empty complex item should be written
626
      * @since EclipseLink 2.4
627
      */
628
     public void emptyComplex(XPathFragment xPathFragment, NamespaceResolver namespaceResolver){
629
         XPathFragment groupingFragment = openStartGroupingElements(namespaceResolver);
630
         closeStartGroupingElements(groupingFragment);
631
         openStartElement(xPathFragment, namespaceResolver);
632
         endElement(xPathFragment, namespaceResolver);
633
     }
634
    
635
    
636
     
637
     /**
638
      * This class will typically be used in conjunction with an XMLFragmentReader.
639
      * The XMLFragmentReader will walk a given XMLFragment node and report events
640
      * to this class - the event's data is then written to the enclosing class'
641
      * writer.
642
      *
643
      * @see org.eclipse.persistence.internal.oxm.record.XMLFragmentReader
644
      */
645
     protected class JsonObjectBuilderRecordContentHandler implements ExtendedContentHandler, LexicalHandler {
646
647
         JsonObjectBuilderRecordContentHandler() {
648
         }
649
650
         // --------------------- CONTENTHANDLER METHODS --------------------- //
651
         public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
652
                 XPathFragment xPathFragment = new XPathFragment(localName);
653
                 xPathFragment.setNamespaceURI(namespaceURI);
654
                 openStartElement(xPathFragment, namespaceResolver);
655
                 handleAttributes(atts);
656
         }
657
658
         public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
659
             XPathFragment xPathFragment = new XPathFragment(localName);
660
             xPathFragment.setNamespaceURI(namespaceURI);
661
             
662
             JsonObjectBuilderWriterRecord.this.endElement(xPathFragment, namespaceResolver);        
663
         }
664
665
         public void startPrefixMapping(String prefix, String uri) throws SAXException {
666
         }
667
668
         public void characters(char[] ch, int start, int length) throws SAXException {
669
             String characters = new String (ch, start, length);
670
             characters(characters);
671
         }
672
673
         public void characters(CharSequence characters) throws SAXException {           
674
             JsonObjectBuilderWriterRecord.this.characters(characters.toString());      
675
         }
676
677
         // --------------------- LEXICALHANDLER METHODS --------------------- //
678
         public void comment(char[] ch, int start, int length) throws SAXException {
679
         }
680
681
         public void startCDATA() throws SAXException {
682
         }
683
684
         public void endCDATA() throws SAXException {
685
         }
686
687
         // --------------------- CONVENIENCE METHODS --------------------- //
688
            protected void handleAttributes(Attributes atts) {
689
             for (int i=0, attsLength = atts.getLength(); i<attsLength; i++) {
690
                 String qName = atts.getQName(i);
691
                 if((qName != null && (qName.startsWith(javax.xml.XMLConstants.XMLNS_ATTRIBUTE + Constants.COLON) || qName.equals(javax.xml.XMLConstants.XMLNS_ATTRIBUTE)))) {
692
                     continue;
693
                 }
694
                 attribute(atts.getURI(i), atts.getLocalName(i), qName, atts.getValue(i));
695
             }
696
         }
697
698
         protected void writeComment(char[] chars, int start, int length) {        
699
         }
700
        
701
         protected void writeCharacters(char[] chars, int start, int length) {
702
             try {
703
                 characters(chars, start, length);
704
             } catch (SAXException e) {
705
                 throw XMLMarshalException.marshalException(e);
706
             }           
707
         }
708
         // --------------- SATISFY CONTENTHANDLER INTERFACE --------------- //
709
         public void endPrefixMapping(String prefix) throws SAXException {}
710
         public void processingInstruction(String target, String data) throws SAXException {}
711
         public void setDocumentLocator(Locator locator) {}
712
         public void startDocument() throws SAXException {}
713
         public void endDocument() throws SAXException {}
714
         public void skippedEntity(String name) throws SAXException {}
715
         public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {}
716
717
         // --------------- SATISFY LEXICALHANDLER INTERFACE --------------- //
718
         public void startEntity(String name) throws SAXException {}
719
         public void endEntity(String name) throws SAXException {}
720
         public void startDTD(String name, String publicId, String systemId) throws SAXException {}
721
         public void endDTD() throws SAXException {}
722
         @Override
723
         public void setNil(boolean isNil) {}
724
725
     }
726
727
     
728
     /**
729
     * Instances of this class are used to maintain state about the current
730
     * level of the JSON message being marshalled.
731
     */
732
    protected static class Level {
733
        
734
        private boolean isCollection;
735
        private boolean emptyCollection;
736
        private String keyName;        
737
        private JsonObjectBuilder jsonObjectBuilder;
738
        private JsonArrayBuilder jsonArrayBuilder;
739
        private boolean isComplex;
740
        private boolean itemInCollection;
741
        private Level parentLevel;
742
        
743
        public Level(boolean isCollection, Level parentLevel) {
744
            setCollection(isCollection);
745
            emptyCollection = true;
746
            this.parentLevel = parentLevel;
747
        }
748
749
        public boolean isCollection() {
750
            return isCollection;
751
        }
752
753
        public void setCollection(boolean isCollection) {
754
            this.isCollection = isCollection;
755
            if(isCollection && jsonArrayBuilder == null){
756
                jsonArrayBuilder = Json.createArrayBuilder();
757
            }
758
        }
759
760
        public String getKeyName() {
761
            return keyName;
762
        }
763
764
        public void setKeyName(String keyName) {
765
            this.keyName = keyName;
766
        }
767
768
        public JsonObjectBuilder getJsonObjectBuilder() {
769
            return jsonObjectBuilder;
770
        }
771
772
        public void setJsonObjectBuilder(JsonObjectBuilder jsonObjectBuilder) {
773
            this.jsonObjectBuilder = jsonObjectBuilder;
774
        }
775
776
        public JsonArrayBuilder getJsonArrayBuilder() {
777
            return jsonArrayBuilder;
778
        }
779
780
        public void setJsonArrayBuilder(JsonArrayBuilder jsonArrayBuilder) {
781
            this.jsonArrayBuilder = jsonArrayBuilder;
782
        }
783
784
        public boolean isEmptyCollection() {
785
            return emptyCollection;
786
        }
787
788
        public void setEmptyCollection(boolean emptyCollection) {
789
            this.emptyCollection = emptyCollection;
790
        }
791
        public boolean isComplex() {
792
            return isComplex;
793
        }
794
795
        public void setComplex(boolean isComplex) {
796
            this.isComplex = isComplex;
797
            if(isComplex && jsonObjectBuilder == null){
798
                jsonObjectBuilder = Json.createObjectBuilder();
799
            }
800
        }
801
802
        public boolean isItemInCollection() {
803
            return itemInCollection;
804
        }
805
806
        public void setItemInCollection(boolean itemInCollection) {
807
            this.itemInCollection = itemInCollection;
808
        }
809
    }
810
811
812
}
(-)a/moxy/eclipselink.moxy.test/resource/org/eclipse/persistence/testing/jaxb/externalizedmetadata/mappings/anycollection/employee.json (-2 / +4 lines)
Lines 1-7 Link Here
1
{"employee":{
1
{"employee":{
2
  "things":{
2
  "things":{
3
     "junk":{
3
     "junk":{
4
       "stuff":"Some Stuff"
4
       "stuff":{
5
          "value":["Some Stuff"]
6
	}
5
    }
7
    }
6
  }
8
  }
7
}}
9
}}
(-)a/moxy/eclipselink.moxy.test/resource/org/eclipse/persistence/testing/jaxb/externalizedmetadata/mappings/anycollection/write-only-employee.json (-1 / +3 lines)
Lines 1-7 Link Here
1
{"employee":{
1
{"employee":{
2
  "things":{
2
  "things":{
3
    "write-only":{
3
    "write-only":{
4
      "stuff":"Some Stuff"
4
      "stuff":{
5
         "value":["Some Stuff"]
6
	 }
5
    }
7
    }
6
  }
8
  }
7
}}
9
}}
(-)a/moxy/eclipselink.moxy.test/resource/org/eclipse/persistence/testing/jaxb/javadoc/xmlidref/xmlidrefcontainment.json (-1 / +1 lines)
Lines 1-6 Link Here
1
{"customer-data":{
1
{"customer-data":{
2
	"customer":{
2
	"customer":{
3
	        "customerID":"Alice",
3
	        "@customerID":"Alice",
4
		"name":"Alice Jane",
4
		"name":"Alice Jane",
5
		"customerID":"Alice"
5
		"customerID":"Alice"
6
		},
6
		},
(-)a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/JAXBWithJSONTestCases.java (+57 lines)
Lines 23-30 import java.util.ArrayList; Link Here
23
import java.util.List;
23
import java.util.List;
24
24
25
import javax.json.Json;
25
import javax.json.Json;
26
import javax.json.JsonObject;
27
import javax.json.JsonObjectBuilder;
26
import javax.json.JsonReader;
28
import javax.json.JsonReader;
27
import javax.json.JsonStructure;
29
import javax.json.JsonStructure;
30
import javax.json.JsonWriter;
31
import javax.json.stream.JsonGenerator;
32
import javax.json.stream.JsonParser;
28
import javax.xml.bind.JAXBElement;
33
import javax.xml.bind.JAXBElement;
29
import javax.xml.bind.Marshaller;
34
import javax.xml.bind.Marshaller;
30
import javax.xml.bind.Unmarshaller;
35
import javax.xml.bind.Unmarshaller;
Lines 37-42 import org.eclipse.persistence.jaxb.JAXBContext; Link Here
37
import org.eclipse.persistence.jaxb.MarshallerProperties;
42
import org.eclipse.persistence.jaxb.MarshallerProperties;
38
import org.eclipse.persistence.jaxb.UnmarshallerProperties;
43
import org.eclipse.persistence.jaxb.UnmarshallerProperties;
39
import org.eclipse.persistence.oxm.MediaType;
44
import org.eclipse.persistence.oxm.MediaType;
45
import org.eclipse.persistence.oxm.json.JsonGeneratorResult;
46
import org.eclipse.persistence.oxm.json.JsonObjectBuilderResult;
47
import org.eclipse.persistence.oxm.json.JsonParserSource;
40
import org.eclipse.persistence.oxm.json.JsonStructureSource;
48
import org.eclipse.persistence.oxm.json.JsonStructureSource;
41
import org.eclipse.persistence.testing.jaxb.JAXBTestCases.MyStreamSchemaOutputResolver;
49
import org.eclipse.persistence.testing.jaxb.JAXBTestCases.MyStreamSchemaOutputResolver;
42
import org.xml.sax.InputSource;
50
import org.xml.sax.InputSource;
Lines 235-240 public abstract class JAXBWithJSONTestCases extends JAXBTestCases { Link Here
235
            jsonToObjectTest(testObject);
243
            jsonToObjectTest(testObject);
236
        }
244
        }
237
    }
245
    }
246
    
247
    //200 failures? doesn't handle attributes
248
   /* public void testJSONUnmarshalFromJsonParserSource() throws Exception {
249
        if(isUnmarshalTest()){
250
            getJSONUnmarshaller().setProperty(UnmarshallerProperties.MEDIA_TYPE, getJSONUnmarshalMediaType());
251
           InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(controlJSONLocation);    
252
           JsonParser parser = Json.createParser(inputStream);
253
           JsonParserSource source = new JsonParserSource(parser);
254
            
255
            Object testObject = null;
256
            if(getUnmarshalClass() != null){               
257
                testObject = getJSONUnmarshaller().unmarshal(source, getUnmarshalClass());
258
            }else{
259
                testObject = getJSONUnmarshaller().unmarshal(source);
260
            }
261
            jsonToObjectTest(testObject);
262
        }
263
    }
264
*/
238
       
265
       
239
    public void testJSONUnmarshalFromURL() throws Exception {
266
    public void testJSONUnmarshalFromURL() throws Exception {
240
    	if(isUnmarshalTest()){
267
    	if(isUnmarshalTest()){
Lines 290-295 public abstract class JAXBWithJSONTestCases extends JAXBTestCases { Link Here
290
        compareStringToControlFile("testJSONMarshalToStringWriter_FORMATTED", sw.toString(), getWriteControlJSONFormatted(),shouldRemoveWhitespaceFromControlDocJSON());
317
        compareStringToControlFile("testJSONMarshalToStringWriter_FORMATTED", sw.toString(), getWriteControlJSONFormatted(),shouldRemoveWhitespaceFromControlDocJSON());
291
    }
318
    }
292
319
320
  /*  public void testJSONMarshalToJsonGeneratorResult() throws Exception{
321
        getJSONMarshaller().setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
322
323
        StringWriter sw = new StringWriter();
324
        JsonGenerator generator = Json.createGenerator(sw);
325
        JsonGeneratorResult result = new JsonGeneratorResult(generator);
326
        getJSONMarshaller().marshal(getWriteControlObject(), result);
327
        generator.flush();
328
        log(sw.toString());
329
        compareStringToControlFile("**testJSONMarshalToStringWriter**", sw.toString());
330
    }
331
    */
332
    
333
    public void testJSONMarshalToBuilderResult() throws Exception{
334
        getJSONMarshaller().setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
335
336
        JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
337
        JsonObjectBuilderResult result = new JsonObjectBuilderResult(jsonObjectBuilder);
338
        getJSONMarshaller().marshal(getWriteControlObject(), result);
339
        JsonObject jsonObject = jsonObjectBuilder.build();
340
        
341
        StringWriter sw = new StringWriter();
342
        JsonWriter writer= Json.createWriter(sw);
343
        writer.writeObject(jsonObject);
344
        writer.close();
345
        
346
        log(sw.toString());
347
        compareStringToControlFile("**testJSONMarshalToStringWriter**", sw.toString());
348
    }
349
    
293
    protected void compareStringToControlFile(String test, String testString) {
350
    protected void compareStringToControlFile(String test, String testString) {
294
    	compareStringToControlFile(test, testString, getWriteControlJSON());
351
    	compareStringToControlFile(test, testString, getWriteControlJSON());
295
    }
352
    }
(-)a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/annotations/xmltransient/ObjectWithTransientListTestCases.java (+13 lines)
Lines 72-77 e.printStackTrace(); Link Here
72
        fail("An exception should have been thrown");
72
        fail("An exception should have been thrown");
73
    }
73
    }
74
    
74
    
75
    public void testJSONMarshalToBuilderResult() throws Exception{
76
        try{
77
            super.testJSONMarshalToBuilderResult();
78
        }catch(MarshalException e){
79
            Throwable linkedException = e.getLinkedException();
80
            assertTrue(linkedException instanceof XMLMarshalException);
81
            assertEquals("Wrong XMLMarshalExcpetion was thrown",XMLMarshalException.DESCRIPTOR_NOT_FOUND_IN_PROJECT ,((XMLMarshalException)linkedException).getErrorCode());
82
            return;
83
        }
84
        fail("An exception should have been thrown");
85
    } 
86
    
87
    
75
    public void testJSONMarshalToStringWriter() throws Exception{
88
    public void testJSONMarshalToStringWriter() throws Exception{
76
        try{
89
        try{
77
            super.testJSONMarshalToStringWriter();
90
            super.testJSONMarshalToStringWriter();
(-)a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/annotations/xmltransient/ObjectWithTransientTestCases.java (+14 lines)
Lines 52-57 public class ObjectWithTransientTestCases extends JAXBWithJSONTestCases{ Link Here
52
        fail("An exception should have been thrown");
52
        fail("An exception should have been thrown");
53
    }
53
    }
54
    
54
    
55
    public void testJSONMarshalToBuilderResult() throws Exception{
56
        try{
57
            super.testJSONMarshalToBuilderResult();
58
        }catch(MarshalException e){
59
            Throwable linkedException = e.getLinkedException();
60
            assertTrue(linkedException instanceof XMLMarshalException);
61
  //          Throwable actualException = ((XMLMarshalException)linkedException).getCause();
62
//            assertTrue(actualException instanceof XMLMarshalException);
63
            assertEquals("Wrong XMLMarshalExcpetion was thrown",XMLMarshalException.DESCRIPTOR_NOT_FOUND_IN_PROJECT ,((XMLMarshalException)linkedException).getErrorCode());
64
            return;
65
        }
66
        fail("An exception should have been thrown");
67
    }
68
    
55
    public void testJSONMarshalToOutputStream_FORMATTED() throws Exception{
69
    public void testJSONMarshalToOutputStream_FORMATTED() throws Exception{
56
        try{
70
        try{
57
            super.testJSONMarshalToOutputStream_FORMATTED();
71
            super.testJSONMarshalToOutputStream_FORMATTED();
(-)a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/javadoc/xmlidref/XmlIdRefContainmentTest.java (+3 lines)
Lines 14-19 package org.eclipse.persistence.testing.jaxb.javadoc.xmlidref; Link Here
14
14
15
//Example 2
15
//Example 2
16
16
17
import org.eclipse.persistence.jaxb.MarshallerProperties;
17
import org.eclipse.persistence.testing.jaxb.JAXBWithJSONTestCases;
18
import org.eclipse.persistence.testing.jaxb.JAXBWithJSONTestCases;
18
19
19
public class XmlIdRefContainmentTest extends JAXBWithJSONTestCases{
20
public class XmlIdRefContainmentTest extends JAXBWithJSONTestCases{
Lines 31-36 public class XmlIdRefContainmentTest extends JAXBWithJSONTestCases{ Link Here
31
		classes[2] = Shipping.class;
32
		classes[2] = Shipping.class;
32
		classes[3] = CustomerData.class;
33
		classes[3] = CustomerData.class;
33
		setClasses(classes);
34
		setClasses(classes);
35
		jaxbMarshaller.setProperty(MarshallerProperties.JSON_ATTRIBUTE_PREFIX, "@");
36
		jaxbUnmarshaller.setProperty(MarshallerProperties.JSON_ATTRIBUTE_PREFIX, "@");
34
	}
37
	}
35
38
36
	protected Object getControlObject() {
39
	protected Object getControlObject() {
(-)a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/json/JSONMarshalUnmarshalTestCases.java (+21 lines)
Lines 20-29 import java.net.URL; Link Here
20
import java.util.ArrayList;
20
import java.util.ArrayList;
21
import java.util.List;
21
import java.util.List;
22
22
23
import javax.json.Json;
24
import javax.json.JsonReader;
25
import javax.json.JsonStructure;
23
import javax.xml.bind.JAXBElement;
26
import javax.xml.bind.JAXBElement;
24
import javax.xml.transform.stream.StreamSource;
27
import javax.xml.transform.stream.StreamSource;
25
28
26
import org.eclipse.persistence.jaxb.JAXBContext;
29
import org.eclipse.persistence.jaxb.JAXBContext;
30
import org.eclipse.persistence.jaxb.UnmarshallerProperties;
31
import org.eclipse.persistence.oxm.json.JsonStructureSource;
27
import org.eclipse.persistence.testing.jaxb.JAXBTestCases.MyStreamSchemaOutputResolver;
32
import org.eclipse.persistence.testing.jaxb.JAXBTestCases.MyStreamSchemaOutputResolver;
28
import org.xml.sax.InputSource;
33
import org.xml.sax.InputSource;
29
34
Lines 53-58 public abstract class JSONMarshalUnmarshalTestCases extends JSONTestCases{ Link Here
53
		inputStream.close();
58
		inputStream.close();
54
		jsonToObjectTest(testObject);
59
		jsonToObjectTest(testObject);
55
	}
60
	}
61
	
62
	public void testJSONUnmarshalFromJsonStructureSource() throws Exception {
63
       
64
        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(controlJSONLocation);    
65
        JsonReader reader = Json.createReader(inputStream);
66
        JsonStructure jsonStructure = reader.read();     
67
        JsonStructureSource source = new JsonStructureSource(jsonStructure);
68
            
69
        Object testObject = null;
70
        if(getUnmarshalClass() != null){               
71
            testObject = jsonUnmarshaller.unmarshal(source, getUnmarshalClass());
72
        }else{
73
            testObject = jsonUnmarshaller.unmarshal(source);
74
        }
75
        jsonToObjectTest(testObject);        
76
    }
56
77
57
	public void testJSONUnmarshalFromInputSource() throws Exception {	
78
	public void testJSONUnmarshalFromInputSource() throws Exception {	
58
         InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(controlJSONLocation);
79
         InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(controlJSONLocation);
(-)a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/json/JSONTestCases.java (+53 lines)
Lines 13-23 Link Here
13
package org.eclipse.persistence.testing.jaxb.json;
13
package org.eclipse.persistence.testing.jaxb.json;
14
14
15
import java.io.ByteArrayOutputStream;
15
import java.io.ByteArrayOutputStream;
16
import java.io.OutputStream;
17
import java.io.OutputStreamWriter;
16
import java.io.StringWriter;
18
import java.io.StringWriter;
19
import java.nio.charset.Charset;
17
import java.util.Collection;
20
import java.util.Collection;
18
import java.util.Iterator;
21
import java.util.Iterator;
19
import java.util.Map;
22
import java.util.Map;
20
23
24
import javax.json.Json;
25
import javax.json.JsonArray;
26
import javax.json.JsonArrayBuilder;
27
import javax.json.JsonObject;
28
import javax.json.JsonObjectBuilder;
29
import javax.json.JsonWriter;
30
import javax.json.JsonWriterFactory;
21
import javax.xml.bind.JAXBContext;
31
import javax.xml.bind.JAXBContext;
22
import javax.xml.bind.JAXBElement;
32
import javax.xml.bind.JAXBElement;
23
import javax.xml.bind.Marshaller;
33
import javax.xml.bind.Marshaller;
Lines 27-32 import org.eclipse.persistence.jaxb.JAXBContextFactory; Link Here
27
import org.eclipse.persistence.jaxb.MarshallerProperties;
37
import org.eclipse.persistence.jaxb.MarshallerProperties;
28
import org.eclipse.persistence.jaxb.UnmarshallerProperties;
38
import org.eclipse.persistence.jaxb.UnmarshallerProperties;
29
import org.eclipse.persistence.oxm.XMLContext;
39
import org.eclipse.persistence.oxm.XMLContext;
40
import org.eclipse.persistence.oxm.json.JsonArrayBuilderResult;
41
import org.eclipse.persistence.oxm.json.JsonObjectBuilderResult;
30
import org.eclipse.persistence.testing.oxm.OXTestCase;
42
import org.eclipse.persistence.testing.oxm.OXTestCase;
31
43
32
public abstract class JSONTestCases extends OXTestCase{
44
public abstract class JSONTestCases extends OXTestCase{
Lines 172-178 public abstract class JSONTestCases extends OXTestCase{ Link Here
172
	        compareStringToControlFile("testJSONMarshalToOutputStream", new String(os.toByteArray()));
184
	        compareStringToControlFile("testJSONMarshalToOutputStream", new String(os.toByteArray()));
173
	        os.close();
185
	        os.close();
174
	    }
186
	    }
187
	 
188
     public void testJSONMarshalToBuilderResult() throws Exception{
189
           Object writeControlObject = getWriteControlObject();
190
           if(writeControlObject instanceof Collection || writeControlObject.getClass().isArray()){
191
               marshalToArrayBuilderResult();
192
           }else{
193
               marshalToObjectBuilderResult();
194
           }
195
     }  
196
	 
197
	   public void marshalToObjectBuilderResult() throws Exception{
198
	       
199
	        JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
200
	        JsonObjectBuilderResult result = new JsonObjectBuilderResult(jsonObjectBuilder);
201
	        jsonMarshaller.marshal(getWriteControlObject(), result);
175
202
203
	        JsonObject jsonObject = jsonObjectBuilder.build();	        
204
	        StringWriter sw = new StringWriter();
205
	        
206
	        JsonWriter writer= Json.createWriter(sw);
207
	        writer.writeObject(jsonObject);
208
	        writer.close();
209
	        log(sw.toString());
210
	        compareStringToControlFile("**testJSONMarshalToBuilderResult**", sw.toString());
211
	    }
212
213
    public void marshalToArrayBuilderResult() throws Exception{
214
           
215
           JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
216
           JsonArrayBuilderResult result = new JsonArrayBuilderResult(jsonArrayBuilder);
217
           jsonMarshaller.marshal(getWriteControlObject(), result);
218
219
           JsonArray jsonArray = jsonArrayBuilder.build();          
220
           StringWriter sw = new StringWriter();
221
           JsonWriter writer= Json.createWriter(sw);
222
           writer.writeArray(jsonArray);
223
           writer.close();
224
           
225
           log(sw.toString());
226
           compareStringToControlFile("**testJSONMarshalToBuilderResult**", sw.toString());
227
       }
228
	   
176
	 public void testJSONMarshalToOutputStream_FORMATTED() throws Exception{
229
	 public void testJSONMarshalToOutputStream_FORMATTED() throws Exception{
177
	    jsonMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
230
	    jsonMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
178
	    ByteArrayOutputStream os = new ByteArrayOutputStream();
231
	    ByteArrayOutputStream os = new ByteArrayOutputStream();
(-)a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/json/characters/UsAsciiTestCases.java (+29 lines)
Lines 12-21 Link Here
12
 ******************************************************************************/
12
 ******************************************************************************/
13
package org.eclipse.persistence.testing.jaxb.json.characters;
13
package org.eclipse.persistence.testing.jaxb.json.characters;
14
14
15
import java.io.ByteArrayOutputStream;
16
import java.io.OutputStreamWriter;
17
import java.nio.charset.Charset;
15
import java.util.Map;
18
import java.util.Map;
16
19
20
import javax.json.Json;
21
import javax.json.JsonObject;
22
import javax.json.JsonObjectBuilder;
23
import javax.json.JsonWriter;
17
import javax.xml.bind.Marshaller;
24
import javax.xml.bind.Marshaller;
18
25
26
import org.eclipse.persistence.oxm.json.JsonObjectBuilderResult;
19
import org.eclipse.persistence.testing.jaxb.json.JSONMarshalUnmarshalTestCases;
27
import org.eclipse.persistence.testing.jaxb.json.JSONMarshalUnmarshalTestCases;
20
28
21
public class UsAsciiTestCases  extends JSONMarshalUnmarshalTestCases {
29
public class UsAsciiTestCases  extends JSONMarshalUnmarshalTestCases {
Lines 43-47 public class UsAsciiTestCases extends JSONMarshalUnmarshalTestCases { Link Here
43
        control.characters.add('b');
51
        control.characters.add('b');
44
        return control;
52
        return control;
45
    }
53
    }
54
    
55
    public void marshalToObjectBuilderResult() throws Exception{
56
        
57
        JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
58
        JsonObjectBuilderResult result = new JsonObjectBuilderResult(jsonObjectBuilder);
59
        jsonMarshaller.marshal(getWriteControlObject(), result);
60
61
        JsonObject jsonObject = jsonObjectBuilder.build();                
62
        ByteArrayOutputStream out = new ByteArrayOutputStream();
63
        Charset charset = Charset.forName("US-ASCII");
64
65
        JsonWriter writer = Json.createWriterFactory(null).createWriter(out, charset);
66
        
67
        writer.writeObject(jsonObject);
68
        writer.close();
69
       
70
        String s = out.toString();
71
       
72
        log(s);
73
        compareStringToControlFile("**testJSONMarshalToBuilderResult**", s);
74
    }
46
75
47
}
76
}
(-)a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/json/padding/JAXBElementJSONPaddingTestCases.java (+4 lines)
Lines 45-48 public class JAXBElementJSONPaddingTestCases extends JAXBWithJSONTestCases{ Link Here
45
	public boolean isUnmarshalTest (){
45
	public boolean isUnmarshalTest (){
46
		return false;
46
		return false;
47
	}
47
	}
48
	
49
	public void testJSONMarshalToBuilderResult() throws Exception{     
50
    }
51
    
48
}
52
}
(-)a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/json/padding/JAXBElementListJSONPaddingTestCases.java (+3 lines)
Lines 57-60 public class JAXBElementListJSONPaddingTestCases extends JSONTestCases{ Link Here
57
	public boolean isUnmarshalTest (){
57
	public boolean isUnmarshalTest (){
58
		return false;
58
		return false;
59
	}
59
	}
60
	
61
	public void testJSONMarshalToBuilderResult() throws Exception{     
62
    }
60
}
63
}
(-)a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/json/padding/JSONWithNullNameTestCases.java (+4 lines)
Lines 42-45 public class JSONWithNullNameTestCases extends JAXBWithJSONTestCases{ Link Here
42
	public boolean isUnmarshalTest (){
42
	public boolean isUnmarshalTest (){
43
		return false;
43
		return false;
44
	}
44
	}
45
	
46
	public void testJSONMarshalToBuilderResult() throws Exception{     
47
    }
48
    
45
}
49
}
(-)a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/json/padding/JSONWithNullObjectTestCases.java (+4 lines)
Lines 196-199 public class JSONWithNullObjectTestCases extends JAXBWithJSONTestCases{ Link Here
196
		}
196
		}
197
		fail("An error should have occurred");		
197
		fail("An error should have occurred");		
198
	}
198
	}
199
	
200
	public void testJSONMarshalToBuilderResult() throws Exception{	    
201
	}
202
	
199
}
203
}
(-)a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/json/padding/JSONWithPaddingSimpleListTestCases.java (+3 lines)
Lines 55-60 public class JSONWithPaddingSimpleListTestCases extends JSONTestCases{ Link Here
55
		return false;
55
		return false;
56
	}
56
	}
57
	
57
	
58
	public void testJSONMarshalToBuilderResult() throws Exception{     
59
    }
60
	
58
//	public boolean shouldRemoveWhitespaceFromControlDocJSON(){
61
//	public boolean shouldRemoveWhitespaceFromControlDocJSON(){
59
	//	return false;
62
	//	return false;
60
	//}
63
	//}
(-)a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/json/padding/JSONWithPaddingSimpleTestCases.java (+4 lines)
Lines 48-51 public class JSONWithPaddingSimpleTestCases extends JAXBWithJSONTestCases{ Link Here
48
	public boolean isUnmarshalTest (){		
48
	public boolean isUnmarshalTest (){		
49
		return false;
49
		return false;
50
	}
50
	}
51
	
52
	public void testJSONMarshalToBuilderResult() throws Exception{     
53
    }
54
    
51
}
55
}
(-)a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/json/padding/JSONWithUnsetNameTestCases.java (+4 lines)
Lines 42-45 public class JSONWithUnsetNameTestCases extends JAXBWithJSONTestCases{ Link Here
42
	public boolean isUnmarshalTest (){
42
	public boolean isUnmarshalTest (){
43
		return false;
43
		return false;
44
	}
44
	}
45
	
46
	public void testJSONMarshalToBuilderResult() throws Exception{     
47
    }
48
    
45
}
49
}
(-)a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/xmladapter/direct/XmlAdapterDirectNullTestCases.java (+12 lines)
Lines 66-71 public class XmlAdapterDirectNullTestCases extends JAXBWithJSONTestCases { Link Here
66
        fail("An exception should have been thrown");
66
        fail("An exception should have been thrown");
67
    }
67
    }
68
    
68
    
69
    public void testJSONMarshalToBuilderResult() throws Exception{
70
        try{
71
            super.testJSONMarshalToBuilderResult();
72
        }catch(MarshalException me){
73
            Throwable nestedException = me.getLinkedException();
74
            assertTrue(nestedException instanceof ConversionException);            
75
            return;
76
        }
77
        fail("An exception should have been thrown");
78
    }
79
    
69
    public void testJSONMarshalToStringWriter() throws Exception{
80
    public void testJSONMarshalToStringWriter() throws Exception{
70
        try{
81
        try{
71
            super.testJSONMarshalToStringWriter();
82
            super.testJSONMarshalToStringWriter();
Lines 146-151 public class XmlAdapterDirectNullTestCases extends JAXBWithJSONTestCases { Link Here
146
        }
157
        }
147
        fail("An exception should have been thrown");
158
        fail("An exception should have been thrown");
148
    }
159
    }
160
        
149
    public void testObjectToXMLStreamWriter() throws Exception{
161
    public void testObjectToXMLStreamWriter() throws Exception{
150
        try{
162
        try{
151
            super.testObjectToXMLStreamWriter();
163
            super.testObjectToXMLStreamWriter();
(-)a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/xmlvariablenode/XmlVariableNodeNullValueTestCases.java (+11 lines)
Lines 86-91 public class XmlVariableNodeNullValueTestCases extends JAXBWithJSONTestCases{ Link Here
86
		fail("An XMLMarshalException should have occurred");
86
		fail("An XMLMarshalException should have occurred");
87
    }
87
    }
88
    
88
    
89
    public void testJSONMarshalToBuilderResult() throws Exception{
90
        try{
91
            super.testJSONMarshalToBuilderResult();
92
        }catch(JAXBException e){
93
            if(verifyException(e)){
94
                return;
95
            }
96
        }
97
        fail("An XMLMarshalException should have occurred");
98
    }
99
    
89
    public void testJSONMarshalToStringWriter_FORMATTED() throws Exception{
100
    public void testJSONMarshalToStringWriter_FORMATTED() throws Exception{
90
    	try{
101
    	try{
91
     		super.testJSONMarshalToStringWriter_FORMATTED();
102
     		super.testJSONMarshalToStringWriter_FORMATTED();

Return to bug 411377