Java Code Examples for org.apache.cxf.staxutils.StaxUtils#close()

The following examples show how to use org.apache.cxf.staxutils.StaxUtils#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Stax2DOM.java    From cxf with Apache License 2.0 6 votes vote down vote up
public Document getDocument(URL url) throws ToolException {
    XMLStreamReader reader = null;
    try (InputStream input = url.openStream()) {
        StreamSource src = new StreamSource(input, url.toExternalForm());
        reader = StaxUtils.createXMLStreamReader(src);
        return StaxUtils.read(reader, true);
    } catch (Exception e) {
        throw new ToolException(e);
    } finally {
        try {
            StaxUtils.close(reader);
        } catch (XMLStreamException e1) {
            throw new ToolException(e1);
        }
    }
}
 
Example 2
Source File: JAXBElementProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected Object unmarshalFromInputStream(Unmarshaller unmarshaller, InputStream is,
                                          Annotation[] anns, MediaType mt)
    throws JAXBException {
    // Try to create the read before unmarshalling the stream
    XMLStreamReader xmlReader = null;
    try {
        if (is == null) {
            Reader reader = getStreamHandlerFromCurrentMessage(Reader.class);
            if (reader == null) {
                LOG.severe("No InputStream, Reader, or XMLStreamReader is available");
                throw ExceptionUtils.toInternalServerErrorException(null, null);
            }
            xmlReader = StaxUtils.createXMLStreamReader(reader);
        } else {
            xmlReader = StaxUtils.createXMLStreamReader(is);
        }
        configureReaderRestrictions(xmlReader);
        return unmarshaller.unmarshal(xmlReader);
    } finally {
        try {
            StaxUtils.close(xmlReader);
        } catch (XMLStreamException e) {
            // Ignore
        }
    }
}
 
Example 3
Source File: DataBindingProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
public T readFrom(Class<T> clazz, Type genericType, Annotation[] annotations, MediaType type,
                  MultivaluedMap<String, String> headers, InputStream is)
    throws IOException {
    XMLStreamReader reader = null;
    try {
        reader = createReader(clazz, genericType, is);
        DataReader<XMLStreamReader> dataReader = binding.createReader(XMLStreamReader.class);
        Object o = dataReader.read(null, reader, clazz);
        return o == null ? null : clazz.cast(o);
    } catch (Exception ex) {
        throw ExceptionUtils.toBadRequestException(ex, null);
    } finally {
        try {
            StaxUtils.close(reader);
        } catch (XMLStreamException e) {
            // Ignore
        }
    }
}
 
Example 4
Source File: PersistenceUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public SequenceAcknowledgement deserialiseAcknowledgment(InputStream is) {
    Object obj = null;
    XMLStreamReader reader = StaxUtils.createXMLStreamReader(is);
    try {  //NOPMD
        obj = getContext().createUnmarshaller().unmarshal(reader);
        if (obj instanceof JAXBElement<?>) {
            JAXBElement<?> el = (JAXBElement<?>)obj;
            obj = el.getValue();
        }
    } catch (JAXBException ex) {
        throw new RMStoreException(ex);
    } finally {
        try {
            StaxUtils.close(reader);
            is.close();
        } catch (Throwable t) {
            // ignore, just cleaning up
        }
    }
    return (SequenceAcknowledgement)obj;
}
 
Example 5
Source File: StaxBuilder.java    From cxf with Apache License 2.0 5 votes vote down vote up
public Document build(InputStream is) throws XMLStreamException {
    isReadingMidStream = false;
    XMLStreamReader reader = null;
    try {
        reader = StaxUtils.createXMLStreamReader(is);
        return buildInternal(reader);
    } finally {
        StaxUtils.close(reader);
    }
}
 
Example 6
Source File: AbstractBeanDefinitionParser.java    From cxf with Apache License 2.0 5 votes vote down vote up
public AbstractBeanDefinition mapElementToJaxbBean(Element data,
                                                   Class<?> cls,
                                                  Class<?> factory,
                                                  Class<?> jaxbClass,
                                                  String method,
                                                  Object ... args) {
    StringWriter writer = new StringWriter();
    XMLStreamWriter xmlWriter = StaxUtils.createXMLStreamWriter(writer);
    try {
        StaxUtils.copy(data, xmlWriter);
        xmlWriter.flush();
    } catch (XMLStreamException e) {
        throw new RuntimeException(e);
    } finally {
        StaxUtils.close(xmlWriter);
    }

    BeanDefinitionBuilder jaxbbean
        = BeanDefinitionBuilder.rootBeanDefinition(cls);
    if (factory != null) {
        jaxbbean.getRawBeanDefinition().setFactoryBeanName(factory.getName());
    }
    jaxbbean.getRawBeanDefinition().setFactoryMethodName(method);
    jaxbbean.addConstructorArgValue(writer.toString());
    jaxbbean.addConstructorArgValue(getContext(jaxbClass));
    if (args != null) {
        for (Object o : args) {
            jaxbbean.addConstructorArgValue(o);
        }
    }
    return jaxbbean.getBeanDefinition();
}
 
Example 7
Source File: JAXBBeanFactory.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static <T> T createJAXBBean(JAXBContext context,
                                    String s,
                                    Class<T> c) {

    StringReader reader = new StringReader(s);
    XMLStreamReader data = StaxUtils.createXMLStreamReader(reader);
    try {

        T obj = null;
        if (c != null) {
            obj = JAXBUtils.unmarshall(context, data, c).getValue();
        } else {
            Object o = JAXBUtils.unmarshall(context, data);
            if (o instanceof JAXBElement<?>) {
                JAXBElement<?> el = (JAXBElement<?>)o;
                @SuppressWarnings("unchecked")
                T ot = (T)el.getValue();
                obj = ot;
            }
        }
        return obj;
    } catch (JAXBException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            StaxUtils.close(data);
        } catch (XMLStreamException ex) {
            throw new RuntimeException(ex);
        }
    }
}
 
Example 8
Source File: StaxOutEndingInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void handleMessage(Message message) {
    try {
        XMLStreamWriter xtw = message.getContent(XMLStreamWriter.class);
        if (xtw != null) {
            try {
                xtw.writeEndDocument();
                xtw.flush();
            } finally {
                StaxUtils.close(xtw);
            }
        }

        OutputStream os = (OutputStream)message.get(outStreamHolder);
        if (os != null) {
            message.setContent(OutputStream.class, os);
        }
        if (writerHolder != null) {
            Writer w = (Writer)message.get(writerHolder);
            if (w != null) {
                message.setContent(Writer.class, w);
            }
        }
        message.removeContent(XMLStreamWriter.class);
    } catch (XMLStreamException e) {
        throw new Fault(new org.apache.cxf.common.i18n.Message("STAX_WRITE_EXC", BUNDLE), e);
    }
}
 
Example 9
Source File: StaxInEndingInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void handleMessage(Message message) {
    XMLStreamReader xtr = message.getContent(XMLStreamReader.class);
    if (xtr != null && !MessageUtils.getContextualBoolean(message, STAX_IN_NOCLOSE, false)) {
        try {
            StaxUtils.close(xtr);
        } catch (XMLStreamException ex) {
            throw new Fault(ex);
        }
        message.removeContent(XMLStreamReader.class);
    }
}
 
Example 10
Source File: AtomPojoProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Object readFromEntry(Entry entry, Class<Object> cls)
    throws IOException {

    AtomElementReader<?, ?> reader = getAtomReader(cls);
    if (reader != null) {
        return ((AtomElementReader<Entry, Object>)reader).readFrom(entry);
    }
    String entryContent = entry.getContent();
    if (entryContent != null) {
        XMLStreamReader xreader = StaxUtils.createXMLStreamReader(new StringReader(entryContent));
        try {
            Unmarshaller um =
                jaxbProvider.getJAXBContext(cls, cls).createUnmarshaller();
            return cls.cast(um.unmarshal(xreader));
        } catch (Exception ex) {
            reportError("Object of type " + cls.getName() + " can not be deserialized from Entry", ex, 400);
        } finally {
            try {
                StaxUtils.close(xreader);
            } catch (XMLStreamException e) {
                //ignore
            }
        }
    }
    return null;
}
 
Example 11
Source File: ColocUtil.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static void convertSourceToObject(Message message) {
    List<Object> content = CastUtils.cast(message.getContent(List.class));
    if (content == null || content.isEmpty()) {
        // nothing to convert
        return;
    }
    // only supporting the wrapped style for now  (one pojo <-> one source)
    Source source = (Source)content.get(0);
    DataReader<XMLStreamReader> reader =
        message.getExchange().getService().getDataBinding().createReader(XMLStreamReader.class);
    MessagePartInfo mpi = getMessageInfo(message).getMessagePart(0);
    XMLStreamReader streamReader = null;
    Object wrappedObject = null;
    try {
        streamReader = StaxUtils.createXMLStreamReader(source);
        wrappedObject = reader.read(mpi, streamReader);
    } finally {
        try {
            StaxUtils.close(streamReader);
        } catch (XMLStreamException e) {
            // Ignore
        }
    }
    MessageContentsList parameters = new MessageContentsList();
    parameters.put(mpi, wrappedObject);

    message.setContent(List.class, parameters);
}
 
Example 12
Source File: DataBindingProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void writeTo(T o, Class<?> clazz, Type genericType, Annotation[] annotations,
                    MediaType m, MultivaluedMap<String, Object> headers, OutputStream os)
    throws IOException {
    XMLStreamWriter writer = null;
    try {
        String enc = HttpUtils.getSetEncoding(m, headers, StandardCharsets.UTF_8.name());
        writer = createWriter(clazz, genericType, enc, os);
        writeToWriter(writer, o);
    } catch (Exception ex) {
        throw ExceptionUtils.toInternalServerErrorException(ex, null);
    } finally {
        StaxUtils.close(writer);
    }
}
 
Example 13
Source File: SwAOutInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
private DataSource createDataSource(Source o, String ct) {
    DataSource ds = null;

    if (o instanceof StreamSource) {
        StreamSource src = (StreamSource)o;
        try {
            if (src.getInputStream() != null) {
                try (ByteArrayOutputStream bos = new ByteArrayOutputStream(2048)) {
                    IOUtils.copy(src.getInputStream(), bos, 1024);
                    ds = new ByteDataSource(bos.toByteArray(), ct);
                }
            } else {
                ds = new ByteDataSource(IOUtils.toString(src.getReader()).getBytes(StandardCharsets.UTF_8),
                                             ct);
            }
        } catch (IOException e) {
            throw new Fault(e);
        }
    } else {
        ByteArrayOutputStream bwriter = new ByteArrayOutputStream();
        XMLStreamWriter writer = null;
        try {
            writer = StaxUtils.createXMLStreamWriter(bwriter);
            StaxUtils.copy(o, writer);
            writer.flush();
            ds = new ByteDataSource(bwriter.toByteArray(), ct);
        } catch (XMLStreamException e1) {
            throw new Fault(e1);
        } finally {
            StaxUtils.close(writer);
        }
    }
    return ds;
}
 
Example 14
Source File: StaxBuilder.java    From cxf with Apache License 2.0 5 votes vote down vote up
public Document build(Reader reader) throws XMLStreamException {
    isReadingMidStream = false;
    XMLStreamReader streamReader = null;
    try {
        streamReader = StaxUtils.createXMLStreamReader(reader);
        return buildInternal(streamReader);
    } finally {
        StaxUtils.close(streamReader);
    }
}
 
Example 15
Source File: DispatchImpl.java    From cxf with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private QName calculateOpName(Holder<T> holder, QName opName, boolean hasOpName) throws XMLStreamException {
    boolean findDispatchOp = Boolean.TRUE.equals(getRequestContext().get("find.dispatch.operation"));

    //CXF-2836 : find the operation for the dispatched object
    // if findDispatchOp is already true, skip the addressing feature lookup.
    // if the addressing feature is enabled, set findDispatchOp to true
    if (!findDispatchOp) {
        // the feature list to be searched is the endpoint and the bus's lists
        List<Feature> endpointFeatures
            = ((JaxWsClientEndpointImpl)client.getEndpoint()).getFeatures();
        List<Feature> allFeatures;
        if (client.getBus().getFeatures() != null) {
            allFeatures = new ArrayList<>(endpointFeatures.size()
                + client.getBus().getFeatures().size());
            allFeatures.addAll(endpointFeatures);
            allFeatures.addAll(client.getBus().getFeatures());
        } else {
            allFeatures = endpointFeatures;
        }
        for (Feature feature : allFeatures) {
            if (feature instanceof WSAddressingFeature) {
                findDispatchOp = true;
            }
        }
    }
    Source createdSource = null;
    Map<String, QName> payloadOPMap = createPayloadEleOpNameMap(
            client.getEndpoint().getBinding().getBindingInfo(), hasOpName);
    if (findDispatchOp && !payloadOPMap.isEmpty()) {
        QName payloadElementName = null;
        if (holder.value instanceof javax.xml.transform.Source) {
            XMLStreamReader reader = null;
            try {
                reader = StaxUtils.createXMLStreamReader((javax.xml.transform.Source)holder.value);
                Document document = StaxUtils.read(reader);
                createdSource = new StaxSource(StaxUtils.createXMLStreamReader(document));
                payloadElementName = getPayloadElementName(document.getDocumentElement());
            } catch (Exception e) {
                // ignore, we are trying to get the operation name
            } finally {
                StaxUtils.close(reader);
            }
        }
        if (holder.value instanceof SOAPMessage) {
            payloadElementName = getPayloadElementName((SOAPMessage)holder.value);

        }

        if (this.context != null) {
            payloadElementName = getPayloadElementName(holder.value);
        }

        if (payloadElementName != null) {
            if (hasOpName) {
                // Verify the payload element against the given operation name.
                // This allows graceful handling of non-standard WSDL definitions
                // where different operations have the same payload element.
                QName expectedElementName = payloadOPMap.get(opName.toString());
                if (expectedElementName == null || !expectedElementName.toString().equals(
                        payloadElementName.toString())) {
                    // Verification of the provided operation name failed.
                    // Resolve the operation name from the payload element.
                    hasOpName = false;
                    payloadOPMap = createPayloadEleOpNameMap(
                            client.getEndpoint().getBinding().getBindingInfo(), hasOpName);
                }
            }
            QName dispatchedOpName = null;
            if (!hasOpName) {
                dispatchedOpName = payloadOPMap.get(payloadElementName.toString());
            }
            if (null != dispatchedOpName) {
                BindingOperationInfo dbop = client.getEndpoint().getBinding().getBindingInfo()
                    .getOperation(dispatchedOpName);
                if (dbop != null) {
                    opName = dispatchedOpName;
                }
            }
        }
    }
    if (createdSource != null) {
        holder.value = (T)createdSource;
    }
    return opName;
}
 
Example 16
Source File: AbstractBeanDefinitionParser.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected void mapElementToJaxbProperty(Element data,
                                        BeanDefinitionBuilder bean,
                                        String propertyName,
                                        Class<?> c) {
    try {
        XMLStreamWriter xmlWriter = null;
        Unmarshaller u = null;
        try {
            StringWriter writer = new StringWriter();
            xmlWriter = StaxUtils.createXMLStreamWriter(writer);
            StaxUtils.copy(data, xmlWriter);
            xmlWriter.flush();

            BeanDefinitionBuilder jaxbbean
                = BeanDefinitionBuilder.rootBeanDefinition(JAXBBeanFactory.class);
            jaxbbean.getRawBeanDefinition().setFactoryMethodName("createJAXBBean");
            jaxbbean.addConstructorArgValue(getContext(c));
            jaxbbean.addConstructorArgValue(writer.toString());
            jaxbbean.addConstructorArgValue(c);
            bean.addPropertyValue(propertyName, jaxbbean.getBeanDefinition());
        } catch (Exception ex) {
            u = getContext(c).createUnmarshaller();
            u.setEventHandler(null);
            Object obj;
            if (c != null) {
                obj = u.unmarshal(data, c);
            } else {
                obj = u.unmarshal(data);
            }
            if (obj instanceof JAXBElement<?>) {
                JAXBElement<?> el = (JAXBElement<?>)obj;
                obj = el.getValue();
            }
            if (obj != null) {
                bean.addPropertyValue(propertyName, obj);
            }
        } finally {
            StaxUtils.close(xmlWriter);
            JAXBUtils.closeUnmarshaller(u);
        }
    } catch (JAXBException e) {
        throw new RuntimeException("Could not parse configuration.", e);
    }
}
 
Example 17
Source File: AbstractBPBeanDefinitionParser.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected void mapElementToJaxbProperty(ParserContext ctx,
                                        MutableBeanMetadata bean,
                                        Element data,
                                        String propertyName,
                                        Class<?> c) {
    try {
        XMLStreamWriter xmlWriter = null;
        Unmarshaller u = null;
        try {
            StringWriter writer = new StringWriter();
            xmlWriter = StaxUtils.createXMLStreamWriter(writer);
            StaxUtils.copy(data, xmlWriter);
            xmlWriter.flush();


            MutableBeanMetadata factory = ctx.createMetadata(MutableBeanMetadata.class);
            factory.setClassName(c.getName());
            factory.setFactoryComponent(createPassThrough(ctx, new JAXBBeanFactory(getContext(c), c)));
            factory.setFactoryMethod("createJAXBBean");
            factory.addArgument(createValue(ctx, writer.toString()), String.class.getName(), 0);
            bean.addProperty(propertyName, factory);

        } catch (Exception ex) {
            u = getContext(c).createUnmarshaller();
            u.setEventHandler(null);
            Object obj;
            if (c != null) {
                obj = u.unmarshal(data, c);
            } else {
                obj = u.unmarshal(data);
            }
            if (obj instanceof JAXBElement<?>) {
                JAXBElement<?> el = (JAXBElement<?>)obj;
                obj = el.getValue();
            }
            if (obj != null) {
                MutablePassThroughMetadata value = ctx.createMetadata(MutablePassThroughMetadata.class);
                value.setObject(obj);
                bean.addProperty(propertyName, value);
            }
        } finally {
            StaxUtils.close(xmlWriter);
            JAXBUtils.closeUnmarshaller(u);
        }
    } catch (JAXBException e) {
        throw new RuntimeException("Could not parse configuration.", e);
    }
}