Search in sources :

Example 21 with StAXSource

use of javax.xml.transform.stax.StAXSource in project sis by apache.

the class XML method unmarshal.

/**
 * Unmarshal an object from the given stream, DOM or other sources.
 * Together with the {@linkplain #unmarshal(Source, Map) Unmarshal Global Root Element} variant,
 * this is the most flexible unmarshalling method provided in this {@code XML} class.
 * The source is specified by the {@code input} argument implementation, for example
 * {@link javax.xml.transform.stream.StreamSource} for reading from a file or input stream.
 * The optional {@code properties} map can contain any key documented in this {@code XML} class,
 * together with the keys documented in the <cite>supported properties</cite> section of the the
 * {@link Unmarshaller} class.
 *
 * @param  <T>           compile-time value of the {@code declaredType} argument.
 * @param  input         the file from which to read a XML representation.
 * @param  declaredType  the JAXB mapped class of the object to unmarshal.
 * @param  properties    an optional map of properties to give to the unmarshaller, or {@code null} if none.
 * @return the object unmarshalled from the given input, wrapped in a JAXB element.
 * @throws JAXBException if a property has an illegal value, or if an error occurred during the unmarshalling.
 *
 * @since 0.8
 */
public static <T> JAXBElement<T> unmarshal(final Source input, final Class<T> declaredType, final Map<String, ?> properties) throws JAXBException {
    ensureNonNull("input", input);
    ensureNonNull("declaredType", declaredType);
    final MarshallerPool pool = getPool();
    final Unmarshaller unmarshaller = pool.acquireUnmarshaller(properties);
    final JAXBElement<T> element;
    if (input instanceof StAXSource) {
        // Same workaround than the one documented in above method.
        @Workaround(library = "JDK", version = "1.8") final XMLStreamReader reader = ((StAXSource) input).getXMLStreamReader();
        if (reader != null) {
            element = unmarshaller.unmarshal(reader, declaredType);
        } else {
            element = unmarshaller.unmarshal(((StAXSource) input).getXMLEventReader(), declaredType);
        }
    } else {
        element = unmarshaller.unmarshal(input, declaredType);
    }
    pool.recycle(unmarshaller);
    return element;
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) StAXSource(javax.xml.transform.stax.StAXSource) Unmarshaller(javax.xml.bind.Unmarshaller) Workaround(org.apache.sis.util.Workaround)

Example 22 with StAXSource

use of javax.xml.transform.stax.StAXSource in project teiid by teiid.

the class ConnectorWorkItem method convertToRuntimeType.

static Object convertToRuntimeType(BufferManager bm, Object value, Class<?> desiredType, CommandContext context) throws TransformationException {
    if (desiredType != DataTypeManager.DefaultDataClasses.XML || !(value instanceof Source)) {
        if (value instanceof DataSource) {
            final DataSource ds = (DataSource) value;
            try {
                // Teiid uses the datasource interface in a degenerate way that
                // reuses the stream, so we test for that here
                InputStream initial = ds.getInputStream();
                InputStream other = null;
                try {
                    other = ds.getInputStream();
                } catch (IOException e) {
                // likely streaming
                }
                if (other != null && initial != other) {
                    initial.close();
                    other.close();
                    if (value instanceof InputStreamFactory) {
                        return asLob((InputStreamFactory) value, desiredType);
                    }
                    return asLob(new InputStreamFactory() {

                        @Override
                        public InputStream getInputStream() throws IOException {
                            return ds.getInputStream();
                        }
                    }, desiredType);
                }
                // $NON-NLS-1$
                FileStore fs = bm.createFileStore("bytes");
                // TODO: guess at the encoding from the content type
                FileStoreInputStreamFactory fsisf = new FileStoreInputStreamFactory(fs, Streamable.ENCODING);
                SaveOnReadInputStream is = new SaveOnReadInputStream(initial, fsisf);
                if (context != null) {
                    context.addCreatedLob(fsisf);
                }
                return asLob(is.getInputStreamFactory(), desiredType);
            } catch (IOException e) {
                throw new TransformationException(QueryPlugin.Event.TEIID30500, e, e.getMessage());
            }
        }
        if (value instanceof InputStreamFactory) {
            return asLob((InputStreamFactory) value, desiredType);
        }
        if (value instanceof GeometryInputSource) {
            GeometryInputSource gis = (GeometryInputSource) value;
            try {
                InputStream is = gis.getEwkb();
                if (is != null) {
                    return GeometryUtils.geometryFromEwkb(is, gis.getSrid());
                }
            } catch (Exception e) {
                throw new TransformationException(e);
            }
            try {
                Reader r = gis.getGml();
                if (r != null) {
                    return GeometryUtils.geometryFromGml(r, gis.getSrid());
                }
            } catch (Exception e) {
                throw new TransformationException(e);
            }
        }
    }
    if (value instanceof Source) {
        if (!(value instanceof InputStreamFactory)) {
            if (value instanceof StreamSource) {
                StreamSource ss = (StreamSource) value;
                InputStream is = ss.getInputStream();
                Reader r = ss.getReader();
                if (is == null && r != null) {
                    is = new ReaderInputStream(r, Streamable.CHARSET);
                }
                // $NON-NLS-1$
                final FileStore fs = bm.createFileStore("xml");
                final FileStoreInputStreamFactory fsisf = new FileStoreInputStreamFactory(fs, Streamable.ENCODING);
                value = new SaveOnReadInputStream(is, fsisf).getInputStreamFactory();
                if (context != null) {
                    context.addCreatedLob(fsisf);
                }
            } else if (value instanceof StAXSource) {
                // TODO: do this lazily.  if the first access to get the STaXSource, then
                // it's more efficient to let the processing happen against STaX
                StAXSource ss = (StAXSource) value;
                try {
                    // $NON-NLS-1$
                    final FileStore fs = bm.createFileStore("xml");
                    final FileStoreInputStreamFactory fsisf = new FileStoreInputStreamFactory(fs, Streamable.ENCODING);
                    value = new SaveOnReadInputStream(new XMLInputStream(ss, XMLSystemFunctions.getOutputFactory(true)), fsisf).getInputStreamFactory();
                    if (context != null) {
                        context.addCreatedLob(fsisf);
                    }
                } catch (XMLStreamException e) {
                    throw new TransformationException(e);
                }
            } else {
                // maybe dom or some other source we want to get out of memory
                StandardXMLTranslator sxt = new StandardXMLTranslator((Source) value);
                SQLXMLImpl sqlxml;
                try {
                    sqlxml = XMLSystemFunctions.saveToBufferManager(bm, sxt, context);
                } catch (TeiidComponentException e) {
                    throw new TransformationException(e);
                } catch (TeiidProcessingException e) {
                    throw new TransformationException(e);
                }
                return new XMLType(sqlxml);
            }
        }
        return new XMLType(new SQLXMLImpl((InputStreamFactory) value));
    }
    return DataTypeManager.convertToRuntimeType(value, desiredType != DataTypeManager.DefaultDataClasses.OBJECT);
}
Also used : SaveOnReadInputStream(org.teiid.dqp.internal.process.SaveOnReadInputStream) XMLInputStream(org.teiid.util.XMLInputStream) FileStoreInputStreamFactory(org.teiid.common.buffer.FileStoreInputStreamFactory) XMLInputStream(org.teiid.util.XMLInputStream) SaveOnReadInputStream(org.teiid.dqp.internal.process.SaveOnReadInputStream) ReaderInputStream(org.teiid.core.util.ReaderInputStream) InputStream(java.io.InputStream) StreamSource(javax.xml.transform.stream.StreamSource) GeometryInputSource(org.teiid.GeometryInputSource) Reader(java.io.Reader) IOException(java.io.IOException) StAXSource(javax.xml.transform.stax.StAXSource) FileStoreInputStreamFactory(org.teiid.common.buffer.FileStoreInputStreamFactory) GeometryInputSource(org.teiid.GeometryInputSource) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) StAXSource(javax.xml.transform.stax.StAXSource) DataSource(javax.activation.DataSource) CollectionTupleSource(org.teiid.query.processor.CollectionTupleSource) ResourceException(javax.resource.ResourceException) TeiidComponentException(org.teiid.core.TeiidComponentException) XMLStreamException(javax.xml.stream.XMLStreamException) TeiidProcessingException(org.teiid.core.TeiidProcessingException) TeiidException(org.teiid.core.TeiidException) IOException(java.io.IOException) DataSource(javax.activation.DataSource) TeiidProcessingException(org.teiid.core.TeiidProcessingException) FileStore(org.teiid.common.buffer.FileStore) ReaderInputStream(org.teiid.core.util.ReaderInputStream) XMLStreamException(javax.xml.stream.XMLStreamException) TeiidComponentException(org.teiid.core.TeiidComponentException)

Example 23 with StAXSource

use of javax.xml.transform.stax.StAXSource in project teiid by teiid.

the class WSProcedureExecution method getOutputParameterValues.

@Override
public List<?> getOutputParameterValues() throws TranslatorException {
    Object result = returnValue;
    if (returnValue != null && (returnValue instanceof StAXSource) && procedure.getArguments().size() > 4 && procedure.getArguments().get(4).getDirection() == Direction.IN && Boolean.TRUE.equals(procedure.getArguments().get(4).getArgumentValue().getValue())) {
        SQLXMLImpl sqlXml = new StAXSQLXML((StAXSource) returnValue);
        XMLType xml = new XMLType(sqlXml);
        xml.setType(Type.DOCUMENT);
        result = xml;
    } else if (returnValue != null && returnValue instanceof DOMSource) {
        final DOMSource xmlSource = (DOMSource) returnValue;
        SQLXMLImpl sqlXml = new SQLXMLImpl(new InputStreamFactory() {

            @Override
            public InputStream getInputStream() throws IOException {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                Result outputTarget = new StreamResult(outputStream);
                try {
                    TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget);
                } catch (Exception e) {
                    throw new IOException(e);
                }
                return new ByteArrayInputStream(outputStream.toByteArray());
            }
        });
        XMLType xml = new XMLType(sqlXml);
        xml.setType(Type.DOCUMENT);
        result = xml;
    }
    return Arrays.asList(result);
}
Also used : SQLXMLImpl(org.teiid.core.types.SQLXMLImpl) DOMSource(javax.xml.transform.dom.DOMSource) StreamResult(javax.xml.transform.stream.StreamResult) StAXSource(javax.xml.transform.stax.StAXSource) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) InputStreamFactory(org.teiid.core.types.InputStreamFactory) TransformerException(javax.xml.transform.TransformerException) SQLException(java.sql.SQLException) XMLStreamException(javax.xml.stream.XMLStreamException) TranslatorException(org.teiid.translator.TranslatorException) DataNotAvailableException(org.teiid.translator.DataNotAvailableException) IOException(java.io.IOException) WebServiceException(javax.xml.ws.WebServiceException) StreamResult(javax.xml.transform.stream.StreamResult) Result(javax.xml.transform.Result) XMLType(org.teiid.core.types.XMLType) ByteArrayInputStream(java.io.ByteArrayInputStream) StAXSQLXML(org.teiid.util.StAXSQLXML)

Example 24 with StAXSource

use of javax.xml.transform.stax.StAXSource in project teiid by teiid.

the class WSWSDLProcedureExecution method execute.

public void execute() throws TranslatorException {
    List<Argument> arguments = this.procedure.getArguments();
    XMLType docObject = (XMLType) arguments.get(0).getArgumentValue().getValue();
    StAXSource source = null;
    try {
        source = convertToSource(docObject);
        Dispatch<StAXSource> dispatch = conn.createDispatch(StAXSource.class, executionFactory.getDefaultServiceMode());
        String operation = this.procedure.getProcedureName();
        if (this.procedure.getMetadataObject() != null && this.procedure.getMetadataObject().getNameInSource() != null) {
            operation = this.procedure.getMetadataObject().getNameInSource();
        }
        QName opQName = new QName(conn.getServiceQName().getNamespaceURI(), operation);
        dispatch.getRequestContext().put(MessageContext.WSDL_OPERATION, opQName);
        if (source == null) {
            // JBoss Native DispatchImpl throws exception when the source is null
            // $NON-NLS-1$
            source = new StAXSource(XMLType.getXmlInputFactory().createXMLEventReader(new StringReader("<none/>")));
        }
        this.returnValue = dispatch.invoke(source);
    } catch (SQLException e) {
        throw new TranslatorException(e);
    } catch (WebServiceException e) {
        throw new TranslatorException(e);
    } catch (XMLStreamException e) {
        throw new TranslatorException(e);
    } catch (IOException e) {
        throw new TranslatorException(e);
    } finally {
        Util.closeSource(source);
    }
}
Also used : Argument(org.teiid.language.Argument) WebServiceException(javax.xml.ws.WebServiceException) SQLException(java.sql.SQLException) QName(javax.xml.namespace.QName) StAXSource(javax.xml.transform.stax.StAXSource) IOException(java.io.IOException) XMLType(org.teiid.core.types.XMLType) XMLStreamException(javax.xml.stream.XMLStreamException) StringReader(java.io.StringReader) TranslatorException(org.teiid.translator.TranslatorException)

Example 25 with StAXSource

use of javax.xml.transform.stax.StAXSource in project teiid by teiid.

the class TestWSTranslator method testPre81Procedure.

@Test
public void testPre81Procedure() throws Exception {
    WSExecutionFactory ef = new WSExecutionFactory();
    WSConnection mockConnection = Mockito.mock(WSConnection.class);
    MetadataFactory mf = new MetadataFactory("vdb", 1, "x", SystemMetadata.getInstance().getRuntimeTypeMap(), new Properties(), null);
    ef.getMetadata(mf, mockConnection);
    Procedure p = mf.getSchema().getProcedure(WSExecutionFactory.INVOKE_HTTP);
    assertEquals(7, p.getParameters().size());
    p.getParameters().remove(4);
    p.getParameters().remove(5);
    // designer treated the result as an out parameter
    p.getParameters().get(0).setType(Type.Out);
    p.getParameters().add(3, p.getParameters().remove(0));
    for (int i = 0; i < p.getParameters().size(); i++) {
        p.getParameters().get(i).setPosition(i + 1);
    }
    p = mf.getSchema().getProcedure("invoke");
    assertEquals(6, p.getParameters().size());
    p.getParameters().remove(5);
    // designer treated the result as an out parameter
    p.getParameters().get(0).setType(Type.Out);
    p.getParameters().add(p.getParameters().remove(0));
    for (int i = 0; i < p.getParameters().size(); i++) {
        p.getParameters().get(i).setPosition(i + 1);
    }
    TransformationMetadata tm = RealMetadataFactory.createTransformationMetadata(mf.asMetadataStore(), "vdb");
    RuntimeMetadataImpl rm = new RuntimeMetadataImpl(tm);
    Dispatch<Object> mockDispatch = mockDispatch();
    DataSource source = Mockito.mock(DataSource.class);
    Mockito.stub(mockDispatch.invoke(Mockito.any(DataSource.class))).toReturn(source);
    Mockito.stub(mockConnection.createDispatch(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(Class.class), Mockito.any(Service.Mode.class))).toReturn(mockDispatch);
    CommandBuilder cb = new CommandBuilder(tm);
    Call call = (Call) cb.getCommand("call invokeHttp('GET', null, null)");
    BinaryWSProcedureExecution pe = new BinaryWSProcedureExecution(call, rm, Mockito.mock(ExecutionContext.class), ef, mockConnection);
    pe.execute();
    pe.getOutputParameterValues();
    mockConnection = Mockito.mock(WSConnection.class);
    mockDispatch = Mockito.mock(Dispatch.class);
    StAXSource ssource = Mockito.mock(StAXSource.class);
    Mockito.stub(mockDispatch.invoke(Mockito.any(StAXSource.class))).toReturn(ssource);
    Mockito.stub(mockConnection.createDispatch(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(Class.class), Mockito.any(Service.Mode.class))).toReturn(mockDispatch);
    call = (Call) cb.getCommand("call invoke()");
    WSProcedureExecution wpe = new WSProcedureExecution(call, rm, Mockito.mock(ExecutionContext.class), ef, mockConnection);
    wpe.execute();
    wpe.getOutputParameterValues();
}
Also used : WSConnection(org.teiid.translator.WSConnection) Call(org.teiid.language.Call) TransformationMetadata(org.teiid.query.metadata.TransformationMetadata) Dispatch(javax.xml.ws.Dispatch) StAXSource(javax.xml.transform.stax.StAXSource) Properties(java.util.Properties) DataSource(javax.activation.DataSource) ExecutionContext(org.teiid.translator.ExecutionContext) RealMetadataFactory(org.teiid.query.unittest.RealMetadataFactory) MetadataFactory(org.teiid.metadata.MetadataFactory) RuntimeMetadataImpl(org.teiid.dqp.internal.datamgr.RuntimeMetadataImpl) Procedure(org.teiid.metadata.Procedure) CommandBuilder(org.teiid.cdk.CommandBuilder) Test(org.junit.Test)

Aggregations

StAXSource (javax.xml.transform.stax.StAXSource)66 XMLStreamReader (javax.xml.stream.XMLStreamReader)27 XMLStreamException (javax.xml.stream.XMLStreamException)24 StringReader (java.io.StringReader)19 XMLInputFactory (javax.xml.stream.XMLInputFactory)19 XMLEventReader (javax.xml.stream.XMLEventReader)16 StreamSource (javax.xml.transform.stream.StreamSource)15 DOMSource (javax.xml.transform.dom.DOMSource)14 Source (javax.xml.transform.Source)13 SAXSource (javax.xml.transform.sax.SAXSource)12 Test (org.junit.Test)12 StreamResult (javax.xml.transform.stream.StreamResult)10 InputStream (java.io.InputStream)9 TransformerException (javax.xml.transform.TransformerException)8 IOException (java.io.IOException)7 Transformer (javax.xml.transform.Transformer)7 Test (org.junit.jupiter.api.Test)7 Document (org.w3c.dom.Document)7 InputSource (org.xml.sax.InputSource)7 StringWriter (java.io.StringWriter)6