Search in sources :

Example 16 with XMLConversionManager

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

the class SDOMarshalListener method beforeMarshal.

@Override
public void beforeMarshal(Object obj) {
    if (obj instanceof SDOChangeSummary) {
        SDOChangeSummary changeSummary = ((SDOChangeSummary) obj);
        // CREATED - build a list of xpaths to write to the created attribute
        // this must be done dynamically because the xpath is relative to the marshalledObject
        // so it can't be calculated until we know what object is being marshalled
        List createdSet = changeSummary.getCreated();
        List xpaths = new ArrayList(createdSet.size());
        String rootElementName = this.marshalledObjectRootQName.getLocalPart();
        String rootNamespaceUri = this.marshalledObjectRootQName.getNamespaceURI();
        if (rootNamespaceUri != null && !rootNamespaceUri.equals(XMLConstants.EMPTY_STRING)) {
            org.eclipse.persistence.internal.oxm.NamespaceResolver resolver = getRootMarshalRecord().getNamespaceResolver();
            if (resolver != null) {
                String prefix = resolver.resolveNamespaceURI(this.marshalledObjectRootQName.getNamespaceURI());
                if (prefix != null) {
                    rootElementName = prefix + XMLConstants.COLON + rootElementName;
                }
            }
        }
        if ((createdSet != null) && (createdSet.size() > 0)) {
            Iterator anIterator = createdSet.iterator();
            SDODataObject nextCreatedDO = null;
            while (anIterator.hasNext()) {
                // get path to the changeSummaryRoot (may not be the root marshalled object - may be internal)
                nextCreatedDO = ((SDODataObject) anIterator.next());
                String nextPath = getPathFromAncestor(nextCreatedDO, (SDODataObject) marshalledObject, changeSummary);
                // Add sdoRef attribute...all modified objects written should have this
                if (nextPath == SDOConstants.EMPTY_STRING) {
                    // if this is the root, just put the root element
                    xpaths.add(SDOConstants.SDO_CHANGESUMMARY_REF_PATH_PREFIX + // 
                    SDOConstants.SDO_XPATH_SEPARATOR_FRAGMENT + rootElementName);
                } else {
                    xpaths.add(SDOConstants.SDO_CHANGESUMMARY_REF_PATH_PREFIX + // 
                    SDOConstants.SDO_XPATH_SEPARATOR_FRAGMENT + rootElementName + SDOConstants.SDO_XPATH_SEPARATOR_FRAGMENT + nextPath);
                }
            }
        }
        changeSummary.setCreatedXPaths(xpaths);
        // Build xpathToCS
        String xpathMarshalledObjToCS = getPathFromAncestor(changeSummary.getRootObject(), (SDODataObject) marshalledObject, changeSummary);
        String xpathChangeSumProp = getXPathForProperty(changeSummary.getRootObject().getType().getChangeSummaryProperty());
        String xpathToCS = SDOConstants.SDO_CHANGESUMMARY_REF_PATH_PREFIX + SDOConstants.SDO_XPATH_SEPARATOR_FRAGMENT + rootElementName;
        // check if the CS is at the local-cs-root or is in a child property
        if ((xpathMarshalledObjToCS != null) && !xpathMarshalledObjToCS.equals(SDOConstants.EMPTY_STRING)) {
            // SDO_XPATH_TO_ROOT)) {
            // CS is not on the root
            xpathToCS = xpathToCS + SDOConstants.SDO_XPATH_SEPARATOR_FRAGMENT + xpathMarshalledObjToCS;
        }
        xpathToCS = // 
        xpathToCS + SDOConstants.SDO_XPATH_SEPARATOR_FRAGMENT + xpathChangeSumProp + SDOConstants.SDO_XPATH_SEPARATOR_FRAGMENT;
        // MODIFIED && DELETED
        List deletedXPaths = new ArrayList();
        Document document = XMLPlatformFactory.getInstance().getXMLPlatform().createDocument();
        Element csNode = null;
        List modifiedItems = changeSummary.getModified();
        int modifiedSize = modifiedItems.size();
        List newNodes = new ArrayList(modifiedSize);
        SDODataObject nextModifiedDO = null;
        // Iterate through CS modified items
        for (int i = 0; i < modifiedSize; i++) {
            nextModifiedDO = (SDODataObject) modifiedItems.get(i);
            String sdoPrefix = typeHelper.getPrefix(SDOConstants.SDO_URL);
            // List unsetPropNames = new ArrayList();
            String uri = getURI(nextModifiedDO);
            String qualifiedName = getQualifiedName(nextModifiedDO);
            String sdoRefPrefix = SDOConstants.SDO_CHANGESUMMARY_REF_PATH_PREFIX + SDOConstants.SDO_XPATH_SEPARATOR_FRAGMENT;
            if (uri == null) {
                csNode = document.createElement(qualifiedName);
            } else {
                csNode = document.createElementNS(uri, qualifiedName);
            }
            String nextPath = getPathFromAncestor(nextModifiedDO, (SDODataObject) marshalledObject, changeSummary);
            // Add sdoRef attribute...all modified objects written should have this
            if (nextPath == SDOConstants.EMPTY_STRING) {
                // if this is the root, just put the root element
                csNode.setAttributeNS(SDOConstants.SDO_URL, // 
                sdoPrefix + // 
                SDOConstants.SDO_XPATH_NS_SEPARATOR_FRAGMENT + // 
                SDOConstants.CHANGESUMMARY_REF, sdoRefPrefix + rootElementName);
            } else {
                csNode.setAttributeNS(SDOConstants.SDO_URL, // 
                sdoPrefix + // 
                SDOConstants.SDO_XPATH_NS_SEPARATOR_FRAGMENT + // 
                SDOConstants.CHANGESUMMARY_REF, sdoRefPrefix + rootElementName + "/" + nextPath);
            }
            // Bug6346754 Add all namespaces if they are not yet declared above.
            Vector namespaces = nextModifiedDO.getType().getXmlDescriptor().getNonNullNamespaceResolver().getNamespaces();
            for (int j = 0; j < namespaces.size(); j++) {
                Namespace next = (Namespace) namespaces.get(j);
                if (declareNamespace(next.getNamespaceURI(), next.getPrefix(), changeSummary.getRootObject())) {
                    csNode.setAttributeNS(javax.xml.XMLConstants.XMLNS_ATTRIBUTE_NS_URI, javax.xml.XMLConstants.XMLNS_ATTRIBUTE + XMLConstants.COLON + next.getPrefix(), next.getNamespaceURI());
                }
            }
            List nextDOSettings = changeSummary.getOldValues(nextModifiedDO);
            DOMRecord row = new DOMRecord(csNode);
            Session session = ((SDOXMLHelper) typeHelper.getHelperContext().getXMLHelper()).getXmlContext().getSession();
            row.setSession((AbstractSession) session);
            // Iterate through SDOSettings for the current modified Object
            SDOSetting nextSetting = null;
            for (int j = 0; j < nextDOSettings.size(); j++) {
                nextSetting = (SDOSetting) nextDOSettings.get(j);
                if (nextSetting.isSet()) {
                    if (!nextSetting.getProperty().getType().isDataType()) {
                        if (nextSetting.getProperty().isMany()) {
                            List values = (List) nextSetting.getValue();
                            for (int k = 0; k < values.size(); k++) {
                                doMarshal(// 
                                nextSetting.getProperty(), // 
                                (DataObject) values.get(k), changeSummary, csNode, nextModifiedDO, deletedXPaths, xpathToCS, sdoPrefix, rootElementName);
                            }
                        } else {
                            doMarshal(// 
                            nextSetting.getProperty(), // 
                            (DataObject) nextSetting.getValue(), changeSummary, csNode, nextModifiedDO, deletedXPaths, xpathToCS, sdoPrefix, rootElementName);
                        }
                    } else {
                        // This writes out simple values
                        Object value = nextSetting.getValue();
                        if (value == null) {
                            // Marshal out xsi:nil=true
                            marshalNilAttribute(nextSetting.getProperty(), row);
                        } else {
                            String xPath = getXPathForProperty(nextSetting.getProperty());
                            XMLField field = new XMLField(xPath);
                            field.setNamespaceResolver(typeHelper.getNamespaceResolver());
                            row.put(field, value);
                        }
                    }
                }
            }
            List unsetPropNames = changeSummary.getUnsetProps(nextModifiedDO);
            if (!unsetPropNames.isEmpty()) {
                XMLConversionManager xmlConversionManager = ((SDOXMLHelper) typeHelper.getHelperContext().getXMLHelper()).getXmlConversionManager();
                String unsetPropsString = xmlConversionManager.convertObject(unsetPropNames, String.class);
                csNode.setAttributeNS(SDOConstants.SDO_URL, // 
                sdoPrefix + // 
                SDOConstants.SDO_XPATH_NS_SEPARATOR_FRAGMENT + SDOConstants.CHANGESUMMARY_UNSET, unsetPropsString);
            }
            newNodes.add(csNode);
        }
        changeSummary.setDeletedXPaths(deletedXPaths);
        changeSummary.setModifiedDoms(newNodes);
    }
}
Also used : XMLField(org.eclipse.persistence.oxm.XMLField) SDOSetting(org.eclipse.persistence.sdo.SDOSetting) DOMRecord(org.eclipse.persistence.oxm.record.DOMRecord) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) Document(org.w3c.dom.Document) Namespace(org.eclipse.persistence.internal.oxm.Namespace) SDOChangeSummary(org.eclipse.persistence.sdo.SDOChangeSummary) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) SDODataObject(org.eclipse.persistence.sdo.SDODataObject) DataObject(commonj.sdo.DataObject) Vector(java.util.Vector) SDODataObject(org.eclipse.persistence.sdo.SDODataObject) AbstractSession(org.eclipse.persistence.internal.sessions.AbstractSession) Session(org.eclipse.persistence.sessions.Session) XMLConversionManager(org.eclipse.persistence.internal.oxm.XMLConversionManager)

Example 17 with XMLConversionManager

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

the class SDOTypesGenerator method processSimpleComponentAnnotations.

private SDOType processSimpleComponentAnnotations(SDOType owningType, SimpleComponent simpleComponent, SDOProperty p, String targetNamespace, String defaultNamespace, SDOType sdoPropertyType) {
    // aliasName annotation
    String aliasNamesValue = simpleComponent.getAttributesMap().get(SDOConstants.SDOXML_ALIASNAME_QNAME);
    if (aliasNamesValue != null) {
        XMLConversionManager xmlConversionManager = ((SDOXMLHelper) aHelperContext.getXMLHelper()).getXmlConversionManager();
        java.util.List names = xmlConversionManager.convertObject(aliasNamesValue, java.util.List.class);
        p.setAliasNames(names);
    }
    // readOnly annotation
    String readOnlyValue = simpleComponent.getAttributesMap().get(SDOConstants.SDOXML_READONLY_QNAME);
    if (readOnlyValue != null) {
        p.setReadOnly(Boolean.parseBoolean(readOnlyValue));
    }
    // dataType annotation
    String dataTypeValue = simpleComponent.getAttributesMap().get(SDOConstants.SDOXML_DATATYPE_QNAME);
    if (dataTypeValue != null) {
        QName xsdQName = ((SDOTypeHelper) aHelperContext.getTypeHelper()).getXSDTypeFromSDOType(sdoPropertyType);
        if ((xsdQName == null) && !sdoPropertyType.isDataType()) {
            xsdQName = new QName(sdoPropertyType.getURI(), sdoPropertyType.getName());
        }
        p.setXsdType(xsdQName);
        SDOType sdoType = getSDOTypeForName(targetNamespace, defaultNamespace, dataTypeValue);
        sdoPropertyType = sdoType;
        Property xmlDataTypeProperty = aHelperContext.getTypeHelper().getOpenContentProperty(SDOConstants.SDOXML_URL, SDOConstants.SDOXML_DATATYPE);
        p.setInstanceProperty(xmlDataTypeProperty, sdoType);
    }
    // string annotation
    String stringValue = simpleComponent.getAttributesMap().get(SDOConstants.SDOXML_STRING_QNAME);
    if (stringValue != null) {
        QName xsdTypeQName = getQNameForString(defaultNamespace, simpleComponent.getType());
        p.setXsdType(xsdTypeQName);
        sdoPropertyType = SDOConstants.SDO_STRING;
    }
    // name annotation
    String nameValue = simpleComponent.getAttributesMap().get(SDOConstants.SDOXML_NAME_QNAME);
    if (nameValue != null) {
        // itemNameToSDOName.put(sdoTypeName, nameValue);
        p.setName(nameValue);
        if (p.isGlobal() && targetNamespace != null) {
            QName propertyName = new QName(targetNamespace, nameValue);
            ((SDOTypeHelper) aHelperContext.getTypeHelper()).getOpenContentProperties().put(propertyName, p);
        }
    } else {
        if (p.isGlobal() && targetNamespace != null) {
            QName propertyName = new QName(targetNamespace, p.getName());
            ((SDOTypeHelper) aHelperContext.getTypeHelper()).getOpenContentProperties().put(propertyName, p);
        }
    }
    // propertyType annotation
    String propertyTypeValue = simpleComponent.getAttributesMap().get(SDOConstants.SDOXML_PROPERTYTYPE_QNAME);
    if (propertyTypeValue != null) {
        String uri = targetNamespace;
        int colonIndex = propertyTypeValue.indexOf(':');
        if (colonIndex > -1) {
            String prefix = propertyTypeValue.substring(0, colonIndex);
            uri = getURIForPrefix(prefix);
        }
        NonContainmentReference nonContainmentReference = new NonContainmentReference();
        nonContainmentReference.setPropertyTypeName(propertyTypeValue);
        nonContainmentReference.setPropertyTypeURI(uri);
        nonContainmentReference.setOwningType(owningType);
        nonContainmentReference.setOwningProp(p);
        String oppositePropValue = simpleComponent.getAttributesMap().get(SDOConstants.SDOXML_OPPOSITEPROPERTY_QNAME);
        nonContainmentReference.setOppositePropName(oppositePropValue);
        getNonContainmentReferences().add(nonContainmentReference);
    }
    return sdoPropertyType;
}
Also used : QName(javax.xml.namespace.QName) SDOType(org.eclipse.persistence.sdo.SDOType) SDOProperty(org.eclipse.persistence.sdo.SDOProperty) Property(commonj.sdo.Property) XMLConversionManager(org.eclipse.persistence.internal.oxm.XMLConversionManager)

Example 18 with XMLConversionManager

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

the class SDOTypesGenerator method finishSimpleType.

private void finishSimpleType(String targetNamespace, String defaultNamespace, String sdoTypeName, SimpleType simpleType, SDOType currentType) {
    String value = simpleType.getAttributesMap().get(SDOConstants.SDOXML_ALIASNAME_QNAME);
    if (value != null) {
        XMLConversionManager xmlConversionManager = ((SDOXMLHelper) aHelperContext.getXMLHelper()).getXmlConversionManager();
        java.util.List names = xmlConversionManager.convertObject(value, java.util.List.class);
        currentType.setAliasNames(names);
    }
    String instanceClassValue = simpleType.getAttributesMap().get(SDOConstants.SDOJAVA_INSTANCECLASS_QNAME);
    if (instanceClassValue != null) {
        currentType.setInstanceProperty(SDOConstants.JAVA_CLASS_PROPERTY, instanceClassValue);
        currentType.setBaseTypes(null);
    }
    String extendedInstanceClassValue = simpleType.getAttributesMap().get(SDOConstants.SDOJAVA_EXTENDEDINSTANCECLASS_QNAME);
    if (extendedInstanceClassValue != null) {
        currentType.setInstanceClassName(extendedInstanceClassValue);
    }
    currentType.postInitialize();
}
Also used : XMLConversionManager(org.eclipse.persistence.internal.oxm.XMLConversionManager)

Example 19 with XMLConversionManager

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

the class QueryOperation method createSimpleXMLFormat.

@SuppressWarnings({ "unchecked" })
public Object createSimpleXMLFormat(XRServiceAdapter xrService, Object value) {
    XMLRoot xmlRoot = new XMLRoot();
    SimpleXMLFormat simpleXMLFormat = result.getSimpleXMLFormat();
    String tempSimpleXMLFormatTag = SimpleXMLFormat.DEFAULT_SIMPLE_XML_FORMAT_TAG;
    String simpleXMLFormatTag = simpleXMLFormat.getSimpleXMLFormatTag();
    if (simpleXMLFormatTag != null && !EMPTY_STR.equals(simpleXMLFormatTag)) {
        tempSimpleXMLFormatTag = simpleXMLFormatTag;
    }
    xmlRoot.setLocalName(tempSimpleXMLFormatTag);
    String tempXMLTag = DEFAULT_SIMPLE_XML_TAG;
    String xmlTag = simpleXMLFormat.getXMLTag();
    if (xmlTag != null && !EMPTY_STR.equals(xmlTag)) {
        tempXMLTag = xmlTag;
    }
    Vector<DatabaseRecord> records = null;
    if (value instanceof ArrayList) {
        // JPA query results in a list of raw values
        // Here we have raw values returned as opposed to DatabaseRecords - this means
        // we need to figure out the tag names based on the call's output parameters.
        // assumes JPAQuery
        JPAQuery jpaQuery = (JPAQuery) queryHandler.getDatabaseQuery();
        // to match field names with results, we need to gather the database fields from each of the Output parameters
        List<DatabaseField> paramFlds = new ArrayList<>();
        DatasourceCall dsCall = (DatasourceCall) jpaQuery.getDatabaseQuery().getDatasourceCall();
        for (Object obj : dsCall.getParameters()) {
            if (obj instanceof OutputParameterForCallableStatement) {
                paramFlds.add(((OutputParameterForCallableStatement) obj).getOutputField());
            } else if (obj instanceof Object[]) {
                Object[] objArray = (Object[]) obj;
                for (int i = 0; i < objArray.length; i++) {
                    Object o = objArray[i];
                    if (o instanceof OutputParameterForCallableStatement) {
                        paramFlds.add(((OutputParameterForCallableStatement) o).getOutputField());
                    }
                }
            }
        }
        // now create a record using DatabaseField/value pairs
        DatabaseRecord dr = new DatabaseRecord();
        if (paramFlds.size() > 0) {
            for (int i = 0; i < ((ArrayList<?>) value).size(); i++) {
                dr.add(paramFlds.get(i), ((ArrayList<?>) value).get(i));
            }
        } else {
            dr.add(new DatabaseField(RESULT_STR), ((ArrayList<?>) value).get(0));
        }
        records = new Vector<>();
        records.add(dr);
    } else if (value instanceof Vector) {
        Class<?> vectorContent = ((Vector<?>) value).firstElement().getClass();
        if (DatabaseRecord.class.isAssignableFrom(vectorContent)) {
            records = (Vector<DatabaseRecord>) value;
        } else {
            records = new Vector<>();
            DatabaseRecord dr = new DatabaseRecord();
            dr.add(new DatabaseField(RESULT_STR), ((Vector<?>) value).firstElement());
            records.add(dr);
        }
    } else {
        records = new Vector<>();
        DatabaseRecord dr = new DatabaseRecord();
        dr.add(new DatabaseField(RESULT_STR), value);
        records.add(dr);
    }
    SimpleXMLFormatModel simpleXMLFormatModel = new SimpleXMLFormatModel();
    XMLConversionManager conversionManager = (XMLConversionManager) xrService.getOXSession().getDatasourcePlatform().getConversionManager();
    SessionLog log = xrService.getOXSession().getSessionLog();
    for (DatabaseRecord dr : records) {
        Element rowElement = TEMP_DOC.createElement(tempXMLTag);
        for (DatabaseField field : dr.getFields()) {
            // handle complex types, i.e. ones we have a descriptor for
            if (field instanceof ObjectRelationalDatabaseField) {
                ObjectRelationalDatabaseField ordtField = (ObjectRelationalDatabaseField) field;
                if (xrService.getOXSession().getDescriptor(ordtField.getType()) != null) {
                    xrService.getXMLContext().createMarshaller().marshal(dr.get(field), rowElement);
                    continue;
                }
            }
            Object fieldValue = dr.get(field);
            if (fieldValue != null) {
                if (fieldValue instanceof Calendar) {
                    Calendar cValue = (Calendar) fieldValue;
                    fieldValue = conversionManager.convertObject(cValue, STRING, DATE_TIME_QNAME);
                }
                if (fieldValue instanceof Date) {
                    Date dValue = (Date) fieldValue;
                    fieldValue = conversionManager.convertObject(dValue, STRING, DATE_QNAME);
                } else if (fieldValue instanceof Time) {
                    Time tValue = (Time) fieldValue;
                    fieldValue = conversionManager.convertObject(tValue, STRING, TIME_QNAME);
                } else if (fieldValue instanceof Timestamp) {
                    Timestamp tsValue = (Timestamp) fieldValue;
                    fieldValue = conversionManager.convertObject(tsValue, STRING, DATE_TIME_QNAME);
                } else if (fieldValue instanceof Blob) {
                    fieldValue = conversionManager.convertObject(fieldValue, ClassConstants.APBYTE);
                } else if (SQLXML.class.isAssignableFrom(fieldValue.getClass())) {
                    // handle XMLType case where an oracle.jdbc.driver.OracleSQLXML instance was returned
                    SQLXML sqlXml = (SQLXML) fieldValue;
                    try {
                        String str = sqlXml.getString();
                        sqlXml.free();
                        // Oracle 12c appends a \n character to the xml string
                        fieldValue = str.endsWith("\n") ? str.substring(0, str.length() - 1) : str;
                    } catch (SQLException e) {
                        log.logThrowable(SessionLog.FINE, SessionLog.DBWS, e);
                    }
                } else if (fieldValue.getClass().getName().equalsIgnoreCase(ORACLEOPAQUE_STR)) {
                    // handle XMLType case where an oracle.sql.OPAQUE instance was returned
                    try {
                        Class<?> oracleOPAQUE;
                        Class<?> xmlTypeFactoryClass;
                        Constructor<?> xmlTypeFactoryConstructor;
                        Object xmlTypeFactory;
                        Method getStringMethod;
                        if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
                            oracleOPAQUE = AccessController.doPrivileged(new PrivilegedClassForName<>(IORACLEOPAQUE_STR, true, this.getClass().getClassLoader()));
                            xmlTypeFactoryClass = AccessController.doPrivileged(new PrivilegedClassForName<>(XMLTYPEFACTORY_STR, true, this.getClass().getClassLoader()));
                            xmlTypeFactoryConstructor = AccessController.doPrivileged(new PrivilegedGetConstructorFor<>(xmlTypeFactoryClass, new Class<?>[0], true));
                            xmlTypeFactory = AccessController.doPrivileged(new PrivilegedInvokeConstructor<>(xmlTypeFactoryConstructor, new Object[0]));
                            getStringMethod = AccessController.doPrivileged(new PrivilegedGetDeclaredMethod(xmlTypeFactoryClass, GETSTRING_METHOD, new Class<?>[] { oracleOPAQUE }));
                            fieldValue = AccessController.doPrivileged(new PrivilegedMethodInvoker<>(getStringMethod, xmlTypeFactory, new Object[] { fieldValue }));
                        } else {
                            oracleOPAQUE = PrivilegedAccessHelper.getClassForName(IORACLEOPAQUE_STR, false, this.getClass().getClassLoader());
                            xmlTypeFactoryClass = PrivilegedAccessHelper.getClassForName(XMLTYPEFACTORY_STR, true, this.getClass().getClassLoader());
                            xmlTypeFactoryConstructor = PrivilegedAccessHelper.getConstructorFor(xmlTypeFactoryClass, new Class<?>[0], true);
                            xmlTypeFactory = PrivilegedAccessHelper.invokeConstructor(xmlTypeFactoryConstructor, new Object[0]);
                            getStringMethod = PrivilegedAccessHelper.getDeclaredMethod(xmlTypeFactoryClass, GETSTRING_METHOD, new Class<?>[] { oracleOPAQUE });
                            fieldValue = PrivilegedAccessHelper.invokeMethod(getStringMethod, xmlTypeFactory, new Object[] { fieldValue });
                        }
                    } catch (ReflectiveOperationException | PrivilegedActionException e) {
                        // if the required resources are not available there's nothing we can do...
                        log.logThrowable(SessionLog.FINE, SessionLog.DBWS, e);
                    }
                }
                String elementName;
                if (field.getName() == null || (elementName = sqlToXmlName(field.getName())).equals(EMPTY_STR)) {
                    // return arg from stored function has no name
                    elementName = RESULT_STR;
                }
                Element columnElement = TEMP_DOC.createElement(elementName);
                rowElement.appendChild(columnElement);
                String fieldValueString = fieldValue.toString();
                // handle binary content - attachments dealt with in invoke() above
                if (result.getType().equals(BASE_64_BINARY_QNAME)) {
                    fieldValueString = Helper.buildHexStringFromBytes(Base64.base64Encode((byte[]) fieldValue));
                    columnElement.setAttributeNS(XMLNS_URL, XSD_STR, SCHEMA_URL);
                    columnElement.setAttributeNS(XMLNS_URL, XSI_STR, SCHEMA_INSTANCE_URL);
                    columnElement.setAttributeNS(SCHEMA_INSTANCE_URL, XSITYPE_STR, BASE64_BINARY_STR);
                }
                columnElement.appendChild(TEMP_DOC.createTextNode(fieldValueString));
            }
        }
        simpleXMLFormatModel.simpleXML.add(rowElement);
    }
    xmlRoot.setObject(simpleXMLFormatModel);
    return xmlRoot;
}
Also used : SQLException(java.sql.SQLException) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) Time(java.sql.Time) SimpleXMLFormat(org.eclipse.persistence.internal.xr.sxf.SimpleXMLFormat) DatasourceCall(org.eclipse.persistence.internal.databaseaccess.DatasourceCall) Timestamp(java.sql.Timestamp) PrivilegedGetDeclaredMethod(org.eclipse.persistence.internal.security.PrivilegedGetDeclaredMethod) Vector(java.util.Vector) ObjectRelationalDatabaseField(org.eclipse.persistence.mappings.structures.ObjectRelationalDatabaseField) Blob(java.sql.Blob) DatabaseRecord(org.eclipse.persistence.sessions.DatabaseRecord) XMLRoot(org.eclipse.persistence.oxm.XMLRoot) PrivilegedInvokeConstructor(org.eclipse.persistence.internal.security.PrivilegedInvokeConstructor) Constructor(java.lang.reflect.Constructor) Calendar(java.util.Calendar) Method(java.lang.reflect.Method) PrivilegedGetDeclaredMethod(org.eclipse.persistence.internal.security.PrivilegedGetDeclaredMethod) JPAQuery(org.eclipse.persistence.internal.jpa.JPAQuery) SimpleXMLFormatModel(org.eclipse.persistence.internal.xr.sxf.SimpleXMLFormatModel) Date(java.sql.Date) SessionLog(org.eclipse.persistence.logging.SessionLog) SQLXML(java.sql.SQLXML) OutputParameterForCallableStatement(org.eclipse.persistence.internal.databaseaccess.OutputParameterForCallableStatement) ObjectRelationalDatabaseField(org.eclipse.persistence.mappings.structures.ObjectRelationalDatabaseField) DatabaseField(org.eclipse.persistence.internal.helper.DatabaseField) XMLConversionManager(org.eclipse.persistence.internal.oxm.XMLConversionManager)

Example 20 with XMLConversionManager

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

the class XMLBinaryDataMapping method writeSingleValue.

@Override
public void writeSingleValue(Object attributeValue, Object parent, XMLRecord record, AbstractSession session) {
    XMLMarshaller marshaller = record.getMarshaller();
    attributeValue = convertObjectValueToDataValue(attributeValue, session, record.getMarshaller());
    XMLField field = (XMLField) getField();
    if (field.getLastXPathFragment().isAttribute()) {
        if (isSwaRef() && (marshaller.getAttachmentMarshaller() != null)) {
            // should be a DataHandler here
            try {
                String value = null;
                if (getAttributeClassification() == XMLBinaryDataHelper.getXMLBinaryDataHelper().DATA_HANDLER) {
                    value = marshaller.getAttachmentMarshaller().addSwaRefAttachment((DataHandler) attributeValue);
                } else {
                    XMLBinaryDataHelper.EncodedData data = // 
                    XMLBinaryDataHelper.getXMLBinaryDataHelper().getBytesForBinaryValue(attributeValue, marshaller, getMimeType(parent));
                    byte[] bytes = data.getData();
                    value = marshaller.getAttachmentMarshaller().addSwaRefAttachment(bytes, 0, bytes.length);
                }
                record.put(field, value);
            } catch (ClassCastException cce) {
                throw XMLMarshalException.invalidSwaRefAttribute(getAttributeClassification().getName());
            }
        } else {
            // inline case
            XMLBinaryDataHelper.EncodedData data = XMLBinaryDataHelper.getXMLBinaryDataHelper().getBytesForBinaryValue(attributeValue, record.getMarshaller(), getMimeType(parent));
            String base64Value = ((XMLConversionManager) session.getDatasourcePlatform().getConversionManager()).buildBase64StringFromBytes(data.getData());
            record.put(field, base64Value);
        }
        return;
    }
    if (record.isXOPPackage() && !isSwaRef() && !shouldInlineBinaryData()) {
        // write as attachment
        String c_id = XMLConstants.EMPTY_STRING;
        byte[] bytes = null;
        String elementName = field.getLastXPathFragment().getLocalName();
        String namespaceUri = field.getLastXPathFragment().getNamespaceURI();
        if (field.getLastXPathFragment().isSelfFragment()) {
            // If it's a self mapping, get the element from the DOM record
            DOMRecord domRecord = (DOMRecord) record;
            if (domRecord.getDOM().getNodeType() == Node.ELEMENT_NODE) {
                elementName = domRecord.getDOM().getLocalName();
                namespaceUri = domRecord.getDOM().getNamespaceURI();
            }
        }
        if ((getAttributeClassification() == ClassConstants.ABYTE) || (getAttributeClassification() == ClassConstants.APBYTE)) {
            if (getAttributeClassification() == ClassConstants.ABYTE) {
                attributeValue = session.getDatasourcePlatform().getConversionManager().convertObject(attributeValue, ClassConstants.APBYTE);
            }
            bytes = (byte[]) attributeValue;
            c_id = // 
            marshaller.getAttachmentMarshaller().addMtomAttachment(// 
            bytes, // 
            0, // 
            bytes.length, // 
            this.getMimeType(parent), // 
            elementName, // 
            namespaceUri);
        } else if (getAttributeClassification() == XMLBinaryDataHelper.getXMLBinaryDataHelper().DATA_HANDLER) {
            c_id = // 
            marshaller.getAttachmentMarshaller().addMtomAttachment((DataHandler) attributeValue, elementName, namespaceUri);
            if (c_id == null) {
                // get the bytes so we can write it out inline
                XMLBinaryDataHelper.EncodedData data = // 
                XMLBinaryDataHelper.getXMLBinaryDataHelper().getBytesForBinaryValue(attributeValue, marshaller, getMimeType(parent));
                bytes = data.getData();
            }
        } else {
            XMLBinaryDataHelper.EncodedData data = // 
            XMLBinaryDataHelper.getXMLBinaryDataHelper().getBytesForBinaryValue(attributeValue, marshaller, getMimeType(parent));
            bytes = data.getData();
            c_id = // 
            marshaller.getAttachmentMarshaller().addMtomAttachment(// 
            bytes, // 
            0, // 
            bytes.length, // 
            data.getMimeType(), // 
            elementName, namespaceUri);
        }
        if (c_id == null) {
            XMLField textField = null;
            if (field.isSelfField()) {
                textField = new XMLField(XMLConstants.TEXT);
            } else {
                textField = new XMLField(field.getXPath() + '/' + XMLConstants.TEXT);
            }
            textField.setNamespaceResolver(field.getNamespaceResolver());
            textField.setSchemaType(field.getSchemaType());
            record.put(textField, bytes);
        // write out bytes inline
        } else {
            String xpath = this.getXPath();
            String prefix = null;
            boolean prefixAlreadyDefined = false;
            // If the field's resolver is non-null and has an entry for XOP,
            // use it - otherwise, create a new resolver, set the XOP entry,
            // on it, and use it instead.
            // We do this to avoid setting the XOP namespace declaration on
            // a given field or descriptor's resolver, as it is only required
            // on the current element
            NamespaceResolver resolver = field.getNamespaceResolver();
            if (resolver != null) {
                prefix = resolver.resolveNamespaceURI(XMLConstants.XOP_URL);
            }
            if (prefix == null) {
                prefix = XMLConstants.XOP_PREFIX;
                resolver = new NamespaceResolver();
                resolver.put(prefix, XMLConstants.XOP_URL);
            } else {
                prefixAlreadyDefined = true;
            }
            String incxpath = null;
            if (field.isSelfField()) {
                incxpath = prefix + ":Include";
                xpath = (prefix + include);
            } else {
                incxpath = xpath + '/' + prefix + ":Include";
                xpath += ('/' + prefix + include);
            }
            XMLField xpathField = new XMLField(xpath);
            xpathField.setNamespaceResolver(resolver);
            record.put(xpathField, c_id);
            // Need to call setAttributeNS on the record, unless the xop prefix
            // is defined on the descriptor's resolver already
            XMLField incField = new XMLField(incxpath);
            incField.setNamespaceResolver(resolver);
            Object obj = record.getIndicatingNoEntry(incField);
            if (!prefixAlreadyDefined && obj != null && obj instanceof DOMRecord) {
                if (((DOMRecord) obj).getDOM().getNodeType() == Node.ELEMENT_NODE) {
                    ((Element) ((DOMRecord) obj).getDOM()).setAttributeNS(javax.xml.XMLConstants.XMLNS_ATTRIBUTE_NS_URI, javax.xml.XMLConstants.XMLNS_ATTRIBUTE + XMLConstants.COLON + prefix, XMLConstants.XOP_URL);
                }
            }
        }
    } else if (isSwaRef() && (marshaller.getAttachmentMarshaller() != null)) {
        // AttributeValue should be a data-handler
        try {
            String c_id = null;
            if (getAttributeClassification() == XMLBinaryDataHelper.getXMLBinaryDataHelper().DATA_HANDLER) {
                c_id = marshaller.getAttachmentMarshaller().addSwaRefAttachment((DataHandler) attributeValue);
            } else {
                XMLBinaryDataHelper.EncodedData data = // 
                XMLBinaryDataHelper.getXMLBinaryDataHelper().getBytesForBinaryValue(attributeValue, marshaller, getMimeType(parent));
                byte[] bytes = data.getData();
                c_id = marshaller.getAttachmentMarshaller().addSwaRefAttachment(bytes, 0, bytes.length);
            }
            XMLField textField = new XMLField(field.getXPath() + '/' + XMLConstants.TEXT);
            textField.setNamespaceResolver(field.getNamespaceResolver());
            textField.setSchemaType(field.getSchemaType());
            record.put(textField, c_id);
        } catch (Exception ex) {
        }
    } else {
        // inline
        XMLField textField = null;
        if (field.isSelfField()) {
            textField = new XMLField(XMLConstants.TEXT);
        } else {
            textField = new XMLField(field.getXPath() + '/' + XMLConstants.TEXT);
        }
        textField.setNamespaceResolver(field.getNamespaceResolver());
        textField.setSchemaType(field.getSchemaType());
        if ((getAttributeClassification() == ClassConstants.ABYTE) || (getAttributeClassification() == ClassConstants.APBYTE)) {
            record.put(textField, attributeValue);
        } else {
            byte[] bytes = // 
            XMLBinaryDataHelper.getXMLBinaryDataHelper().getBytesForBinaryValue(attributeValue, marshaller, getMimeType(parent)).getData();
            record.put(textField, bytes);
        }
    }
}
Also used : XMLField(org.eclipse.persistence.oxm.XMLField) XMLBinaryDataHelper(org.eclipse.persistence.internal.oxm.XMLBinaryDataHelper) XMLMarshaller(org.eclipse.persistence.oxm.XMLMarshaller) DOMRecord(org.eclipse.persistence.oxm.record.DOMRecord) Element(org.w3c.dom.Element) DataHandler(jakarta.activation.DataHandler) XMLMarshalException(org.eclipse.persistence.exceptions.XMLMarshalException) NamespaceResolver(org.eclipse.persistence.oxm.NamespaceResolver) XMLConversionManager(org.eclipse.persistence.internal.oxm.XMLConversionManager)

Aggregations

XMLConversionManager (org.eclipse.persistence.internal.oxm.XMLConversionManager)34 XMLField (org.eclipse.persistence.oxm.XMLField)12 QName (javax.xml.namespace.QName)10 NamespaceResolver (org.eclipse.persistence.oxm.NamespaceResolver)8 ArrayList (java.util.ArrayList)6 Element (org.w3c.dom.Element)6 Time (java.sql.Time)4 Timestamp (java.sql.Timestamp)4 Vector (java.util.Vector)3 XPathFragment (org.eclipse.persistence.internal.oxm.XPathFragment)3 SDOProperty (org.eclipse.persistence.sdo.SDOProperty)3 SDOType (org.eclipse.persistence.sdo.SDOType)3 DataObject (commonj.sdo.DataObject)2 Property (commonj.sdo.Property)2 Type (commonj.sdo.Type)2 DataHandler (jakarta.activation.DataHandler)2 List (java.util.List)2 XMLMarshalException (org.eclipse.persistence.exceptions.XMLMarshalException)2 XMLBinaryDataHelper (org.eclipse.persistence.internal.oxm.XMLBinaryDataHelper)2 JavaClass (org.eclipse.persistence.jaxb.javamodel.JavaClass)2