Java Code Examples for javax.xml.bind.Unmarshaller#unmarshal()

The following examples show how to use javax.xml.bind.Unmarshaller#unmarshal() . 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: JaxbSerialization.java    From joyrpc with Apache License 2.0 6 votes vote down vote up
/**
 * 反序列化
 *
 * @param reader
 * @param type
 * @param <T>
 * @return
 * @throws SerializerException
 */
public <T> T deserialize(final Reader reader, final Type type) throws SerializerException {
    if (type == null || !(type instanceof Class)) {
        return null;
    }
    Class clazz = (Class) type;
    Annotation annotation = clazz.getAnnotation(XmlRootElement.class);
    if (annotation == null) {
        return null;
    }
    try {
        JAXBContext context = getJaxbContext(clazz);
        Unmarshaller marshaller = context.createUnmarshaller();
        return (T) marshaller.unmarshal(reader);
    } catch (JAXBException e) {
        throw new SerializerException(String.format("Error occurs while deserializing %s", type), e);
    }
}
 
Example 2
Source File: UCFPackage.java    From incubator-taverna-language with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected void parseContainerXML() throws IOException {
	createdContainerXml = false;
	InputStream containerStream = getResourceAsInputStream(CONTAINER_XML);
	if (containerStream == null) {
		// Make an empty containerXml
		Container container = containerFactory.createContainer();
		containerXml = containerFactory.createContainer(container);
		createdContainerXml = true;
		return;
	}
	try {
		Unmarshaller unMarshaller = createUnMarshaller();
		containerXml = (JAXBElement<Container>) unMarshaller
				.unmarshal(containerStream);
	} catch (JAXBException e) {
		throw new IOException("Could not parse " + CONTAINER_XML, e);
	}
}
 
Example 3
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 4
Source File: JAXBSerializer.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
@Override
public T deserialize(final InputStream input) throws SerializationException {
    if (input == null) {
        throw new IllegalArgumentException("InputStream cannot be null");
    }

    try {
        // Consume the header bytes.
        readDataModelVersion(input);
        final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        return (T) unmarshaller.unmarshal(input);
    } catch (JAXBException e) {
        throw new SerializationException("Unable to deserialize object", e);
    }
}
 
Example 5
Source File: DataLoader.java    From aion-germany with GNU General Public License v3.0 5 votes vote down vote up
public DataLoader(String fileName, Object object) throws JAXBException {
	this.data = object;
	File file = new File(fileName);
       JAXBContext jaxbContext = JAXBContext.newInstance(data.getClass());
       Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
       this.data = jaxbUnmarshaller.unmarshal(file);
}
 
Example 6
Source File: CFDv2.java    From factura-electronica with Apache License 2.0 5 votes vote down vote up
private static Comprobante load(InputStream in, String... contexts) throws Exception {
    JAXBContext context = getContext(contexts);
    try {
        Unmarshaller u = context.createUnmarshaller();
        return (Comprobante) u.unmarshal(in);
    } finally {
        in.close();
    }
}
 
Example 7
Source File: AbstractMessageImpl.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
@Override
public <T> T readPayloadAsJAXB(Unmarshaller unmarshaller) throws JAXBException {
    if(hasAttachments())
        unmarshaller.setAttachmentUnmarshaller(new AttachmentUnmarshallerImpl(getAttachments()));
    try {
        return (T) unmarshaller.unmarshal(readPayloadAsSource());
    } finally{
        unmarshaller.setAttachmentUnmarshaller(null);
    }
}
 
Example 8
Source File: XmlDSigUtilsTest.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void test() throws JAXBException, SAXException {

	File xmldsigFile = new File("src/test/resources/XmlAliceSig.xml");

	JAXBContext jc = xmlDSigUtils.getJAXBContext();
	assertNotNull(jc);

	Schema schema = xmlDSigUtils.getSchema();
	assertNotNull(schema);

	Unmarshaller unmarshaller = jc.createUnmarshaller();
	unmarshaller.setSchema(schema);

	JAXBElement<SignatureType> unmarshalled = (JAXBElement<SignatureType>) unmarshaller.unmarshal(xmldsigFile);
	assertNotNull(unmarshalled);

	Marshaller marshaller = jc.createMarshaller();
	marshaller.setSchema(schema);

	StringWriter sw = new StringWriter();
	marshaller.marshal(unmarshalled, sw);

	String xmldsigString = sw.toString();

	JAXBElement<SignatureType> unmarshalled2 = (JAXBElement<SignatureType>) unmarshaller.unmarshal(new StringReader(xmldsigString));
	assertNotNull(unmarshalled2);
}
 
Example 9
Source File: SoapMessageUtils.java    From spring-ws-security-soap-example with MIT License 5 votes vote down vote up
/**
 * Creates an {@code Entity} from the received {@code SOAPMessage}.
 * <p>
 * The message should be valid and contain a {@code GetEntityResponse}.
 *
 * @param message
 *            the SOAP message
 * @return an {@code Entity} parsed from the {@code SOAPMessage}
 * @throws JAXBException
 *             if there is any problem when unmarshalling the data
 * @throws SOAPException
 *             if there is any problem when reading the SOAP message
 */
public static final Entity getEntity(final SOAPMessage message)
        throws JAXBException, SOAPException {
    final JAXBContext jc; // Context for unmarshalling
    final Unmarshaller um; // Unmarshaller for the SOAP message
    final GetEntityResponse response; // Unmarshalled response

    jc = JAXBContext.newInstance(GetEntityResponse.class);
    um = jc.createUnmarshaller();
    response = (GetEntityResponse) um
            .unmarshal(message.getSOAPBody().extractContentAsDocument());

    return response.getEntity();
}
 
Example 10
Source File: DataConverter.java    From mcg-helper with Apache License 2.0 5 votes vote down vote up
public static McgGlobal xmlToMcgGlobal(String mcgGlobalXml) {
	McgGlobal mcgGlobal = null;
	if(mcgGlobalXml != null && !"".equals(mcgGlobalXml)) {
        try {  
            JAXBContext context = JAXBContext.newInstance(McgGlobal.class);  
            Unmarshaller unmarshaller = context.createUnmarshaller();  
            mcgGlobal = (McgGlobal)unmarshaller.unmarshal(new StringReader(mcgGlobalXml));  
        } catch (JAXBException e) {  
            logger.error("xml数据转换McgGlobal出错,xml数据:{},异常信息:{}", mcgGlobalXml, e.getMessage());
        }		
	}
	
	return mcgGlobal;
}
 
Example 11
Source File: OpenLabelerController.java    From OpenLabeler with Apache License 2.0 5 votes vote down vote up
private ObjectModel fromClipboard() {
    Clipboard clipboard = Clipboard.getSystemClipboard();
    if (clipboard.getContentTypes().contains(DATA_FORMAT_JAXB)) {
        try {
            String content = (String)clipboard.getContent(DATA_FORMAT_JAXB);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            return (ObjectModel) unmarshaller.unmarshal(new StringReader(content));
        }
        catch (Exception ex) {
            LOG.log(Level.SEVERE, "Unable to get content from clipboard", ex);
        }
    }
    return null;
}
 
Example 12
Source File: SFAPIClient.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> T unmarshal(Class<T> clazz, HttpResponse response) throws JAXBException, IOException {
       if (response != null) {
		Unmarshaller unmarshaller = getUnmarshaller(clazz);
           StreamSource streamSource = new StreamSource(response.getEntity().getContent());
           JAXBElement<T> unmarshalledElement = unmarshaller.unmarshal(streamSource, clazz);
           return unmarshalledElement.getValue();
	}
	return null;
}
 
Example 13
Source File: LogicalMessageImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public Object getPayload(JAXBContext context) {
    try {
        Source payloadSrc = getPayload();
        if (payloadSrc == null)
            return null;
        Unmarshaller unmarshaller = context.createUnmarshaller();
        return unmarshaller.unmarshal(payloadSrc);
    } catch (JAXBException e) {
        throw new WebServiceException(e);
    }

}
 
Example 14
Source File: MmiHandler.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void handle(String target, Request baseRequest,
        HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    LOGGER.info("request from " + request.getRemoteAddr());
    response.setContentType("text/html;charset=utf-8");
    final Reader reader = request.getReader();
    try {
        JAXBContext ctx = JAXBContext.newInstance(Mmi.class);
        final Unmarshaller unmarshaller = ctx.createUnmarshaller();
        final Object o = unmarshaller.unmarshal(reader);
        if (o instanceof Mmi) {
            final Mmi mmi = (Mmi) o;
            LOGGER.info("received MMI event: " + mmi);
            final String protocol = request.getProtocol();
            final DecoratedMMIEvent event = new DecoratedMMIEvent(this, mmi);
            final Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    notifyMMIEvent(protocol, event);
                }
            };
            final Thread thread = new Thread(runnable);
            thread.start();
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            LOGGER.warn("received unknown MMI object: " + o);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
    } catch (JAXBException e) {
        LOGGER.error("unable to read input", e);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
    baseRequest.setHandled(true);
}
 
Example 15
Source File: HeartbeatPayload.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
public static HeartbeatPayload unmarshal(final InputStream is) throws ProtocolException {
    try {
        final Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
        return (HeartbeatPayload) unmarshaller.unmarshal(is);
    } catch (final JAXBException je) {
        throw new ProtocolException(je);
    }
}
 
Example 16
Source File: TestSHCMessage.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * common setup
 *
 * @throws Exception
 */
@Before
public void setUp() throws Exception {
    File file = new File("src/main/resources/packet_layout.xml");
    JAXBContext jaxbContext = JAXBContext.newInstance(Packet.class);

    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    packet = (Packet) jaxbUnmarshaller.unmarshal(file);
}
 
Example 17
Source File: NeuralNetwork.java    From libreveris with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Unmarshal the provided XML stream to allocate the corresponding
 * NeuralNetwork.
 *
 * @param in the input stream that contains the network definition in XML
 *           format. The stream is not closed by this method
 *
 * @return the allocated network.
 * @exception JAXBException raised when unmarshalling goes wrong
 */
public static NeuralNetwork unmarshal (InputStream in)
        throws JAXBException
{
    Unmarshaller um = getJaxbContext()
            .createUnmarshaller();
    NeuralNetwork nn = (NeuralNetwork) um.unmarshal(in);
    logger.debug("Network unmarshalled");

    return nn;
}
 
Example 18
Source File: ReadXMLFileUtils.java    From opencps-v2 with GNU Affero General Public License v3.0 5 votes vote down vote up
private static StepConfigList convertXMLToStepConfig(String xmlString) throws JAXBException {
	JAXBContext jaxbContext = null;

		jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
		Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
		StringReader reader = new StringReader(xmlString);
		StepConfigList objectElement = (StepConfigList) jaxbUnmarshaller.unmarshal(reader);
		return objectElement;
}
 
Example 19
Source File: TraceFileReader.java    From sonar-esql-plugin with Apache License 2.0 4 votes vote down vote up
protected UserTraceLog parseTraceXml() throws JAXBException {
	JAXBContext jc = JAXBContext.newInstance(UserTraceLog.class);

	Unmarshaller unmarshaller = jc.createUnmarshaller();
	return (UserTraceLog) unmarshaller.unmarshal(traceFile);
}
 
Example 20
Source File: SonosService.java    From airsonic with GNU General Public License v3.0 4 votes vote down vote up
private String getUsername() {
    MessageContext messageContext = context.getMessageContext();
    if (messageContext == null || !(messageContext instanceof WrappedMessageContext)) {
        LOG.error("Message context is null or not an instance of WrappedMessageContext.");
        return null;
    }

    Message message = ((WrappedMessageContext) messageContext).getWrappedMessage();
    List<Header> headers = CastUtils.cast((List<?>) message.get(Header.HEADER_LIST));
    if (headers != null) {
        for (Header h : headers) {
            Object o = h.getObject();
            // Unwrap the node using JAXB
            if (o instanceof Node) {
                JAXBContext jaxbContext;
                try {
                    // TODO: Check performance
                    jaxbContext = new JAXBDataBinding(Credentials.class).getContext();
                    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
                    o = unmarshaller.unmarshal((Node) o);
                } catch (JAXBException e) {
                    // failed to get the credentials object from the headers
                    LOG.error("JAXB error trying to unwrap credentials", e);
                }
            }
            if (o instanceof Credentials) {
                Credentials c = (Credentials) o;

                // Note: We're using the username as session ID.
                String username = c.getSessionId();
                if (username == null) {
                    LOG.debug("No session id in credentials object, get from login");
                    username = c.getLogin().getUsername();
                }
                return username;
            } else {
                LOG.error("No credentials object");
            }
        }
    } else {
        LOG.error("No headers found");
    }
    return null;
}