Search in sources :

Example 21 with XMLContext

use of org.eclipse.persistence.oxm.XMLContext in project eclipselink by eclipse-ee4j.

the class DOMUnmarshaller method xmlToObject.

/**
 * INTERNAL: Convert the Oracle XMLDocument to the reference-class.
 */
public Object xmlToObject(DOMRecord xmlRow, Class<?> referenceClass) throws XMLMarshalException {
    try {
        // Try to get the Encoding and Version from DOM3 APIs if available
        String xmlEncoding = "UTF-8";
        String xmlVersion = "1.0";
        try {
            xmlEncoding = xmlRow.getDocument().getXmlEncoding() != null ? xmlRow.getDocument().getXmlEncoding() : xmlEncoding;
            xmlVersion = xmlRow.getDocument().getXmlVersion() != null ? xmlRow.getDocument().getXmlVersion() : xmlVersion;
        } catch (Exception ex) {
        // if the methods aren't available, then just use the default values
        }
        XMLContext xmlContext = xmlUnmarshaller.getXMLContext();
        // populate and return an XMLRoot
        if (referenceClass != null && (XMLConversionManager.getDefaultJavaTypes().get(referenceClass) != null || CoreClassConstants.XML_GREGORIAN_CALENDAR.isAssignableFrom(referenceClass) || CoreClassConstants.DURATION.isAssignableFrom(referenceClass))) {
            // we're assuming that since we're unmarshalling to a primitive
            // wrapper, the root element has a single text node
            Object nodeVal;
            try {
                Text rootTxt = (Text) xmlRow.getDOM().getFirstChild();
                nodeVal = rootTxt.getNodeValue();
            } catch (Exception ex) {
                // here, either the root element doesn't have a text node as a
                // first child, or there is no first child at all - in any case,
                // try converting null
                nodeVal = null;
            }
            Object obj = xmlContext.getSession().getDatasourcePlatform().getConversionManager().convertObject(nodeVal, referenceClass);
            Root xmlRoot = new XMLRoot();
            xmlRoot.setObject(obj);
            String lName = xmlRow.getDOM().getLocalName();
            if (lName == null) {
                lName = xmlRow.getDOM().getNodeName();
            }
            xmlRoot.setLocalName(lName);
            xmlRoot.setNamespaceURI(xmlRow.getDOM().getNamespaceURI());
            xmlRoot.setEncoding(xmlEncoding);
            xmlRoot.setVersion(xmlVersion);
            return xmlRoot;
        }
        Descriptor descriptor = null;
        CoreAbstractSession readSession = null;
        boolean shouldWrap = true;
        if (referenceClass == null) {
            QName rootQName = new QName(xmlRow.getNamespaceURI(), xmlRow.getLocalName());
            descriptor = xmlContext.getDescriptor(rootQName);
            if (null == descriptor) {
                String type = ((Element) xmlRow.getDOM()).getAttributeNS(javax.xml.XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "type");
                if (null != type) {
                    XPathFragment typeFragment = new XPathFragment(type);
                    String namespaceURI = xmlRow.resolveNamespacePrefix(typeFragment.getPrefix());
                    typeFragment.setNamespaceURI(namespaceURI);
                    descriptor = xmlContext.getDescriptorByGlobalType(typeFragment);
                }
            } else {
                if (null != descriptor.getDefaultRootElementField() && !descriptor.isResultAlwaysXMLRoot() && !xmlUnmarshaller.isResultAlwaysXMLRoot()) {
                    String descLocalName = descriptor.getDefaultRootElementField().getXPathFragment().getLocalName();
                    String localName = xmlRow.getDOM().getLocalName();
                    if (localName == null) {
                        localName = xmlRow.getDOM().getNodeName();
                    }
                    String namespaceURI = xmlRow.getDOM().getNamespaceURI();
                    if (descLocalName != null && descLocalName.equals(localName)) {
                        String descUri = descriptor.getDefaultRootElementField().getXPathFragment().getNamespaceURI();
                        if ((namespaceURI == null && descUri == null) || (namespaceURI != null && namespaceURI.length() == 0 && descUri == null) || (namespaceURI != null && namespaceURI.equals(descUri))) {
                            // found a descriptor based on root element then know we won't need to wrap in an XMLRoot
                            shouldWrap = false;
                        }
                    }
                }
            }
            if (null == descriptor) {
                throw XMLMarshalException.noDescriptorWithMatchingRootElement(rootQName.toString());
            } else {
                readSession = xmlContext.getSession(descriptor.getJavaClass());
            }
        } else {
            // for XMLObjectReferenceMappings we need a non-shared cache, so
            // try and get a Unit Of Work from the XMLContext
            readSession = xmlContext.getSession(referenceClass);
            descriptor = (Descriptor) readSession.getDescriptor(referenceClass);
            if (descriptor == null) {
                throw XMLMarshalException.descriptorNotFoundInProject(referenceClass.getName());
            }
        }
        Object object = null;
        if (null == xmlRow.getDOM().getAttributes().getNamedItemNS(javax.xml.XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, Constants.SCHEMA_NIL_ATTRIBUTE)) {
            xmlRow.setUnmarshaller(xmlUnmarshaller);
            xmlRow.setDocPresPolicy(xmlContext.getDocumentPreservationPolicy((AbstractSession) readSession));
            XMLObjectBuilder objectBuilder = (XMLObjectBuilder) descriptor.getObjectBuilder();
            ReadObjectQuery query = new ReadObjectQuery();
            query.setReferenceClass(referenceClass);
            query.setSession((AbstractSession) readSession);
            object = objectBuilder.buildObject(query, xmlRow, null);
            // resolve mapping references
            xmlRow.resolveReferences(readSession, xmlUnmarshaller.getIDResolver());
        }
        String elementNamespaceUri = xmlRow.getDOM().getNamespaceURI();
        String elementLocalName = xmlRow.getDOM().getLocalName();
        if (elementLocalName == null) {
            elementLocalName = xmlRow.getDOM().getNodeName();
        }
        String elementPrefix = xmlRow.getDOM().getPrefix();
        if (shouldWrap || descriptor.isResultAlwaysXMLRoot() || isResultAlwaysXMLRoot) {
            return descriptor.wrapObjectInXMLRoot(object, elementNamespaceUri, elementLocalName, elementPrefix, xmlEncoding, xmlVersion, this.isResultAlwaysXMLRoot, true, xmlUnmarshaller);
        } else {
            return object;
        }
    } finally {
        xmlUnmarshaller.getStringBuffer().reset();
    }
}
Also used : CoreAbstractSession(org.eclipse.persistence.internal.core.sessions.CoreAbstractSession) Root(org.eclipse.persistence.internal.oxm.Root) XMLRoot(org.eclipse.persistence.oxm.XMLRoot) ReadObjectQuery(org.eclipse.persistence.queries.ReadObjectQuery) XMLContext(org.eclipse.persistence.oxm.XMLContext) XMLRoot(org.eclipse.persistence.oxm.XMLRoot) QName(javax.xml.namespace.QName) Element(org.w3c.dom.Element) Text(org.w3c.dom.Text) XPathFragment(org.eclipse.persistence.internal.oxm.XPathFragment) XMLMarshalException(org.eclipse.persistence.exceptions.XMLMarshalException) IOException(java.io.IOException) XMLPlatformException(org.eclipse.persistence.platform.xml.XMLPlatformException) SAXException(org.xml.sax.SAXException) XMLObjectBuilder(org.eclipse.persistence.internal.oxm.XMLObjectBuilder) Descriptor(org.eclipse.persistence.internal.oxm.mappings.Descriptor) AbstractSession(org.eclipse.persistence.internal.sessions.AbstractSession) CoreAbstractSession(org.eclipse.persistence.internal.core.sessions.CoreAbstractSession)

Example 22 with XMLContext

use of org.eclipse.persistence.oxm.XMLContext in project eclipselink by eclipse-ee4j.

the class ComicsConfigTestSuite method buildComicsSession.

public static DatabaseSession buildComicsSession() {
    DynamicClassLoader dcl = new DynamicClassLoader(ComicsConfigTestSuite.class.getClassLoader());
    new DynamicTypeBuilder(dcl.createDynamicClass("model.Issue"), null);
    new DynamicTypeBuilder(dcl.createDynamicClass("model.Publisher"), null);
    new DynamicTypeBuilder(dcl.createDynamicClass("model.Title"), null);
    XMLSessionConfigLoader loader = new XMLSessionConfigLoader(COMICS_SESSION_XML) {

        @Override
        @SuppressWarnings("unchecked")
        public boolean load(SessionManager sessionManager, ClassLoader loader) {
            Document document = loadDocument(loader);
            if (getExceptionStore().isEmpty()) {
                if (document.getDocumentElement().getTagName().equals("sessions")) {
                    XMLContext context = new XMLContext(new XMLSessionConfigProject_11_1_1());
                    XMLUnmarshaller unmarshaller = context.createUnmarshaller();
                    SessionConfigs configs = (SessionConfigs) unmarshaller.unmarshal(document);
                    SessionsFactory factory = new SessionsFactory() {

                        @Override
                        protected Project loadProjectConfig(ProjectConfig projectConfig) {
                            if (projectConfig.isProjectXMLConfig()) {
                                projectConfig.setProjectString(PACKAGE_PATH + "/" + projectConfig.getProjectString());
                            }
                            return super.loadProjectConfig(projectConfig);
                        }

                        @Override
                        protected Login buildLogin(LoginConfig loginConfig) {
                            return createLogin();
                        }

                        @Override
                        protected AbstractSession buildSession(SessionConfig sessionConfig) {
                            AbstractSession s = super.buildSession(sessionConfig);
                            if (SessionLog.OFF == logLevel) {
                                s.dontLogMessages();
                            } else {
                                s.setLogLevel(logLevel);
                            }
                            return s;
                        }
                    };
                    Map<String, Session> sessions = factory.buildSessionConfigs(configs, loader);
                    for (Map.Entry<String, Session> entry : sessions.entrySet()) {
                        if (!sessionManager.getSessions().containsKey(entry.getKey())) {
                            sessionManager.addSession(entry.getKey(), entry.getValue());
                        }
                    }
                    return true;
                }
            }
            return false;
        }
    };
    loader.setClassLoader(dcl);
    loader.setSessionName(COMICS_SESSION_NAME);
    return (DatabaseSession) SessionManager.getManager().getSession(loader);
}
Also used : DynamicClassLoader(org.eclipse.persistence.dynamic.DynamicClassLoader) SessionConfigs(org.eclipse.persistence.internal.sessions.factories.model.SessionConfigs) XMLContext(org.eclipse.persistence.oxm.XMLContext) DatabaseSession(org.eclipse.persistence.sessions.DatabaseSession) SessionManager(org.eclipse.persistence.sessions.factories.SessionManager) SessionsFactory(org.eclipse.persistence.internal.sessions.factories.SessionsFactory) SessionConfig(org.eclipse.persistence.internal.sessions.factories.model.session.SessionConfig) Document(org.w3c.dom.Document) XMLSessionConfigProject_11_1_1(org.eclipse.persistence.internal.sessions.factories.XMLSessionConfigProject_11_1_1) ProjectConfig(org.eclipse.persistence.internal.sessions.factories.model.project.ProjectConfig) LoginConfig(org.eclipse.persistence.internal.sessions.factories.model.login.LoginConfig) DynamicClassLoader(org.eclipse.persistence.dynamic.DynamicClassLoader) XMLSessionConfigLoader(org.eclipse.persistence.sessions.factories.XMLSessionConfigLoader) XMLUnmarshaller(org.eclipse.persistence.oxm.XMLUnmarshaller) DynamicTypeBuilder(org.eclipse.persistence.dynamic.DynamicTypeBuilder) Map(java.util.Map) AbstractSession(org.eclipse.persistence.internal.sessions.AbstractSession) DatabaseSession(org.eclipse.persistence.sessions.DatabaseSession) AbstractSession(org.eclipse.persistence.internal.sessions.AbstractSession) Session(org.eclipse.persistence.sessions.Session)

Example 23 with XMLContext

use of org.eclipse.persistence.oxm.XMLContext in project eclipselink by eclipse-ee4j.

the class XMLCompositeCollectionMapping method getDescriptor.

protected XMLDescriptor getDescriptor(XMLRecord xmlRecord, AbstractSession session, QName rootQName) throws XMLMarshalException {
    if (rootQName == null) {
        rootQName = new QName(xmlRecord.getNamespaceURI(), xmlRecord.getLocalName());
    }
    XMLContext xmlContext = xmlRecord.getUnmarshaller().getXMLContext();
    XMLDescriptor xmlDescriptor = xmlContext.getDescriptor(rootQName);
    if (null == xmlDescriptor) {
        if (!((getKeepAsElementPolicy() == UnmarshalKeepAsElementPolicy.KEEP_UNKNOWN_AS_ELEMENT) || (getKeepAsElementPolicy() == UnmarshalKeepAsElementPolicy.KEEP_ALL_AS_ELEMENT))) {
            throw XMLMarshalException.noDescriptorWithMatchingRootElement(xmlRecord.getLocalName());
        }
    }
    return xmlDescriptor;
}
Also used : XMLDescriptor(org.eclipse.persistence.oxm.XMLDescriptor) XMLContext(org.eclipse.persistence.oxm.XMLContext) XPathQName(org.eclipse.persistence.internal.oxm.XPathQName) QName(javax.xml.namespace.QName)

Example 24 with XMLContext

use of org.eclipse.persistence.oxm.XMLContext in project eclipselink by eclipse-ee4j.

the class XMLAnyAttributeMapping method getDescriptor.

protected XMLDescriptor getDescriptor(XMLRecord xmlRecord, AbstractSession session) throws XMLMarshalException {
    XMLContext xmlContext = xmlRecord.getUnmarshaller().getXMLContext();
    QName rootQName = new QName(xmlRecord.getNamespaceURI(), xmlRecord.getLocalName());
    XMLDescriptor xmlDescriptor = xmlContext.getDescriptor(rootQName);
    if (null == xmlDescriptor) {
        throw XMLMarshalException.noDescriptorWithMatchingRootElement(xmlRecord.getLocalName());
    }
    return xmlDescriptor;
}
Also used : XMLDescriptor(org.eclipse.persistence.oxm.XMLDescriptor) XMLContext(org.eclipse.persistence.oxm.XMLContext) QName(javax.xml.namespace.QName)

Example 25 with XMLContext

use of org.eclipse.persistence.oxm.XMLContext in project eclipselink by eclipse-ee4j.

the class XMLAnyCollectionMapping method buildObjectValuesFromDOMRecord.

private Object buildObjectValuesFromDOMRecord(DOMRecord record, AbstractSession session, ObjectBuildingQuery query, JoinedAttributeManager joinManager) {
    // This DOMRecord represents the root node of the AnyType instance
    // Grab ALL children to populate the collection.
    Node root = record.getDOM();
    NodeList children = root.getChildNodes();
    ContainerPolicy cp = getContainerPolicy();
    Object container = null;
    if (reuseContainer) {
        Object currentObject = record.getCurrentObject();
        Object value = getAttributeAccessor().getAttributeValueFromObject(currentObject);
        container = value != null ? value : cp.containerInstance();
    } else {
        container = cp.containerInstance();
    }
    int length = children.getLength();
    Node next = null;
    if (length > 0) {
        next = record.getDOM().getFirstChild();
    }
    while (next != null) {
        Object objectValue = null;
        if (isUnmappedContent(next)) {
            if ((next.getNodeType() == Node.TEXT_NODE) && this.isMixedContent()) {
                if (next.getNodeValue().trim().length() > 0) {
                    objectValue = next.getNodeValue();
                    objectValue = convertDataValueToObjectValue(objectValue, session, record.getUnmarshaller());
                    cp.addInto(objectValue, container, session);
                }
            } else if (next.getNodeType() == Node.ELEMENT_NODE) {
                XMLDescriptor referenceDescriptor = null;
                // In this case it must be an element so we need to dig up the descriptor
                // make a nested record and build an object from it.
                DOMRecord nestedRecord = (DOMRecord) record.buildNestedRow((Element) next);
                if (!useXMLRoot) {
                    referenceDescriptor = getDescriptor(nestedRecord, session, null);
                    objectValue = buildObjectForNonXMLRoot(referenceDescriptor, getConverter(), query, record, nestedRecord, joinManager, session, next, container, cp);
                } else {
                    String schemaType = ((Element) next).getAttributeNS(javax.xml.XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, XMLConstants.SCHEMA_TYPE_ATTRIBUTE);
                    QName schemaTypeQName = null;
                    XPathFragment frag = new XPathFragment();
                    if ((null != schemaType) && (schemaType.length() > 0)) {
                        frag.setXPath(schemaType);
                        if (frag.hasNamespace()) {
                            String prefix = frag.getPrefix();
                            XMLPlatform xmlPlatform = XMLPlatformFactory.getInstance().getXMLPlatform();
                            String url = xmlPlatform.resolveNamespacePrefix(next, prefix);
                            frag.setNamespaceURI(url);
                            schemaTypeQName = new QName(url, frag.getLocalName());
                        }
                        XMLContext xmlContext = nestedRecord.getUnmarshaller().getXMLContext();
                        referenceDescriptor = xmlContext.getDescriptorByGlobalType(frag);
                    }
                    if (referenceDescriptor == null) {
                        try {
                            QName qname = new QName(nestedRecord.getNamespaceURI(), nestedRecord.getLocalName());
                            referenceDescriptor = getDescriptor(nestedRecord, session, qname);
                        } catch (XMLMarshalException e) {
                            referenceDescriptor = null;
                        }
                        // Check if descriptor is for a wrapper, if it is null it out and let continue
                        XMLDescriptor xmlReferenceDescriptor = referenceDescriptor;
                        if (referenceDescriptor != null && xmlReferenceDescriptor.isWrapper()) {
                            referenceDescriptor = null;
                        }
                    }
                    // is set, then we want to return either an Element or an XMLRoot wrapping an Element
                    if (getKeepAsElementPolicy() == UnmarshalKeepAsElementPolicy.KEEP_ALL_AS_ELEMENT || (referenceDescriptor == null && getKeepAsElementPolicy() == UnmarshalKeepAsElementPolicy.KEEP_UNKNOWN_AS_ELEMENT)) {
                        Object objVal = buildObjectNoReferenceDescriptor(record, getConverter(), session, next, null, null);
                        // if we know the descriptor use it to wrap the Element in an XMLRoot (if necessary)
                        if (referenceDescriptor != null) {
                            objVal = referenceDescriptor.wrapObjectInXMLRoot(objVal, next.getNamespaceURI(), next.getLocalName(), next.getPrefix(), false, record.isNamespaceAware(), record.getUnmarshaller());
                            cp.addInto(objVal, container, session);
                        } else {
                            // no descriptor, so manually build the XMLRoot
                            cp.addInto(buildXMLRoot(next, objVal), container, session);
                        }
                    } else // if we have a descriptor use it to build the object and wrap it in an XMLRoot
                    if (referenceDescriptor != null) {
                        buildObjectAndWrapInXMLRoot(referenceDescriptor, getConverter(), query, record, nestedRecord, joinManager, session, next, container, cp);
                    } else {
                        // no descriptor, but could be TEXT to wrap and return
                        XMLRoot rootValue;
                        if ((rootValue = buildXMLRootForText(next, schemaTypeQName, getConverter(), session, record)) != null) {
                            cp.addInto(rootValue, container, session);
                        }
                    }
                }
            }
        }
        next = next.getNextSibling();
    }
    return container;
}
Also used : XMLContext(org.eclipse.persistence.oxm.XMLContext) DOMRecord(org.eclipse.persistence.oxm.record.DOMRecord) QName(javax.xml.namespace.QName) XMLRoot(org.eclipse.persistence.oxm.XMLRoot) Node(org.w3c.dom.Node) NodeList(org.w3c.dom.NodeList) XPathFragment(org.eclipse.persistence.internal.oxm.XPathFragment) ContainerPolicy(org.eclipse.persistence.internal.queries.ContainerPolicy) ListContainerPolicy(org.eclipse.persistence.internal.queries.ListContainerPolicy) CollectionContainerPolicy(org.eclipse.persistence.internal.queries.CollectionContainerPolicy) XMLDescriptor(org.eclipse.persistence.oxm.XMLDescriptor) XMLPlatform(org.eclipse.persistence.platform.xml.XMLPlatform) XMLMarshalException(org.eclipse.persistence.exceptions.XMLMarshalException)

Aggregations

XMLContext (org.eclipse.persistence.oxm.XMLContext)170 Project (org.eclipse.persistence.sessions.Project)80 XMLMarshaller (org.eclipse.persistence.oxm.XMLMarshaller)68 Document (org.w3c.dom.Document)57 StringReader (java.io.StringReader)56 Test (org.junit.Test)41 ObjectPersistenceWorkbenchXMLProject (org.eclipse.persistence.internal.sessions.factories.ObjectPersistenceWorkbenchXMLProject)40 XMLUnmarshaller (org.eclipse.persistence.oxm.XMLUnmarshaller)39 PLSQLStoredProcedureCall (org.eclipse.persistence.platform.database.oracle.plsql.PLSQLStoredProcedureCall)36 InputStream (java.io.InputStream)30 NonJDBCTestHelper.buildTestProject (org.eclipse.persistence.testing.tests.nonJDBC.NonJDBCTestHelper.buildTestProject)30 NonJDBCTestHelper.buildWorkbenchXMLProject (org.eclipse.persistence.testing.tests.nonJDBC.NonJDBCTestHelper.buildWorkbenchXMLProject)30 DataModifyQuery (org.eclipse.persistence.queries.DataModifyQuery)21 SchemaModelProject (org.eclipse.persistence.internal.oxm.schema.SchemaModelProject)18 XMLDescriptor (org.eclipse.persistence.oxm.XMLDescriptor)17 XMLLogin (org.eclipse.persistence.oxm.XMLLogin)17 StringWriter (java.io.StringWriter)15 StreamSource (javax.xml.transform.stream.StreamSource)15 JAXBException (jakarta.xml.bind.JAXBException)14 Map (java.util.Map)14