下面列出了javax.xml.bind.Unmarshaller#unmarshal ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 反序列化
*
* @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);
}
}
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
}
}
}
@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);
}
}
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;
}
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;
}
/**
* 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;
}
/**
* 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);
}
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);
}
}
@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);
}
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);
}
}
@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;
}
@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);
}
}
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;
}
/**
* 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();
}
@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);
}
@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);
}
}
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();
}
}
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);
}
protected UserTraceLog parseTraceXml() throws JAXBException {
JAXBContext jc = JAXBContext.newInstance(UserTraceLog.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
return (UserTraceLog) unmarshaller.unmarshal(traceFile);
}
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;
}