下面列出了怎么用javax.xml.bind.Unmarshaller的API类实例代码及写法,或者点击链接到github查看源代码。
public static <T> T encryptFolder(T request, String hubIdPropKey, String hubAppIdPropKey) throws TechnicalConnectorException {
if (LOG.isDebugEnabled()) {
MarshallerHelper<T, T> helper = new MarshallerHelper(request.getClass(), request.getClass());
LOG.debug("Pre-encrypted request:\n" + helper.toString(request));
}
try {
Marshaller marshaller = JAXBContext.newInstance(request.getClass()).createMarshaller();
DOMResult res = new DOMResult();
marshaller.marshal(request, res);
Document doc = FolderEncryptor.encryptFolder((Document)res.getNode(), SessionUtil.getEncryptionCrypto(), hubIdPropKey, hubAppIdPropKey);
Unmarshaller unmarshaller = JAXBContext.newInstance(request.getClass()).createUnmarshaller();
return unmarshaller.unmarshal(doc.getFirstChild());
} catch (JAXBException var7) {
LOG.error("JAXBException when (un)marchalling the request", var7);
return request;
}
}
@Override
public boolean readFile( InputStream inputStream )
{
try
{
JAXBContext jc = JAXBContext.newInstance( ObjectFactory.class );
Unmarshaller u = jc.createUnmarshaller();
JAXBElement<?> rootElement = (JAXBElement<?>) u.unmarshal( inputStream );
xRoot = (XFramiumRoot) rootElement.getValue();
for ( XProperty currentProp : xRoot.getDriver().getProperty() )
{
configProperties.put( currentProp.getName(), currentProp.getValue() );
}
return true;
}
catch ( Exception e )
{
log.fatal( "Error reading CSV Element File", e );
return false;
}
}
private void validateMalformedConfig(File malformedConfig) {
try {
JAXBContext ctx = JAXBContext.newInstance(AppManagementConfig.class);
Unmarshaller um = ctx.createUnmarshaller();
um.setSchema(this.getSchema());
um.unmarshal(malformedConfig);
Assert.assertTrue(false);
} catch (JAXBException e) {
Throwable linkedException = e.getLinkedException();
if (!(linkedException instanceof SAXParseException)) {
log.error("Unexpected error occurred while unmarshalling app management config", e);
Assert.assertTrue(false);
}
log.error("JAXB parser occurred while unmarsharlling app management config", e);
Assert.assertTrue(true);
}
}
/**
* Unmarshals XML to request object.
*
* @param xml
* @param messageType
* @return Object
*/
public static Object fromXml(Source xml, MessageType messageType) {
LOGGER.debug("Unmarshalling XML to domain object.");
Object response = null;
try {
Unmarshaller jaxbUnmarshaller = JAXB_CONTEXT_MAP.get(messageType).createUnmarshaller();
response = jaxbUnmarshaller.unmarshal(xml);
} catch (JAXBException ex) {
LOGGER.error("Error unmarshalling from XML", ex);
throw new RealexException("Error unmarshalling from XML", ex);
}
return response;
}
public Object readPayloadAsJAXB(Unmarshaller unmarshaller) throws JAXBException {
if(!hasPayload())
return null;
assert unconsumed();
// TODO: How can the unmarshaller process this as a fragment?
if(hasAttachments())
unmarshaller.setAttachmentUnmarshaller(new AttachmentUnmarshallerImpl(getAttachments()));
try {
return unmarshaller.unmarshal(reader);
} finally{
unmarshaller.setAttachmentUnmarshaller(null);
XMLStreamReaderUtil.readRest(reader);
XMLStreamReaderUtil.close(reader);
XMLStreamReaderFactory.recycle(reader);
}
}
/**
* Unmarshal a RunTable from a file.
*
* @param path path to file
* @return unmarshalled run table
*/
public static RunTable unmarshal (Path path)
{
logger.debug("RunTable unmarshalling {}", path);
try (InputStream is = Files.newInputStream(path, StandardOpenOption.READ)) {
Unmarshaller um = getJaxbContext().createUnmarshaller();
RunTable runTable = (RunTable) um.unmarshal(is);
logger.debug("Unmarshalled {}", runTable);
return runTable;
} catch (IOException |
JAXBException ex) {
logger.warn("RunTable. Error unmarshalling " + path + " " + ex, ex);
return null;
}
}
public static Unmarshaller getUnmarshaller() throws JAXBException {
// This is supposed to work based on this link:
// https://jaxb.java.net/2.2.11/docs/ch03.html#compiling-xml-schema-adding-behaviors
// Override the unmarshal to use the XXXEvaluator classes
// This doesn't work exactly how it's described in the link above, but this is functional
if (context == null)
{
context = JAXBContext.newInstance(ObjectFactory.class);
}
if (unmarshaller == null) {
unmarshaller = context.createUnmarshaller();
try {
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=406032
//https://javaee.github.io/jaxb-v2/doc/user-guide/ch03.html#compiling-xml-schema-adding-behaviors
// for jre environment
unmarshaller.setProperty("com.sun.xml.bind.ObjectFactory", new ObjectFactoryEx());
} catch (javax.xml.bind.PropertyException e) {
// for jdk environment
unmarshaller.setProperty("com.sun.xml.internal.bind.ObjectFactory", new ObjectFactoryEx());
}
}
return unmarshaller;
}
/**
* Creates and returns a new instance of MapSettings with default values
* loaded from the given input stream.
*
* @param is
* the input stream that contains an XML representation of the
* map settings
* @return a MapSettings with the values from XML
*/
public static MapSettings getInstance(final InputStream is) {
MapSettings ms = null;
try {
JAXBContext jc = JAXBContext.newInstance(MapSettings.class);
Unmarshaller um = jc.createUnmarshaller();
ms = (MapSettings) um.unmarshal(MegaMekXmlUtil.createSafeXmlSource(is));
} catch (JAXBException | SAXException | ParserConfigurationException ex) {
System.err.println("Error loading XML for map settings: " + ex.getMessage()); //$NON-NLS-1$
ex.printStackTrace();
}
return ms;
}
/**
* Loads script contexes from descriptor
*
* @param scriptDescriptor
* xml file that describes contexes
* @throws Exception
* if can't load file
*/
public synchronized void load(File scriptDescriptor) throws Exception {
FileInputStream fin = new FileInputStream(scriptDescriptor);
JAXBContext c = JAXBContext.newInstance(ScriptInfo.class, ScriptList.class);
Unmarshaller u = c.createUnmarshaller();
ScriptList list = null;
try {
list = (ScriptList) u.unmarshal(fin);
} catch (Exception e) {
throw e;
} finally {
fin.close();
}
for (ScriptInfo si : list.getScriptInfos()) {
ScriptContext context = createContext(si, null);
if (context != null) {
contexts.add(context);
context.init();
}
}
}
private Unmarshaller getUnmarshaller() throws JAXBException {
JAXBContext jctx = JAXBContext.newInstance(WorkflowDefinition.class);
Unmarshaller unmarshaller = jctx.createUnmarshaller();
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
URL schemaUrl = WorkflowDefinition.class.getResource("workflow.xsd");
Schema schema = null;
try {
schema = sf.newSchema(new StreamSource(schemaUrl.toExternalForm()));
} catch (SAXException ex) {
throw new JAXBException("Missing schema workflow.xsd!", ex);
}
unmarshaller.setSchema(schema);
ValidationEventCollector errors = new ValidationEventCollector() {
@Override
public boolean handleEvent(ValidationEvent event) {
super.handleEvent(event);
return true;
}
};
unmarshaller.setEventHandler(errors);
return unmarshaller;
}
/**
* Convert from EndpointReference to CXF internal 2005/08 EndpointReferenceType
*
* @param external the javax.xml.ws.EndpointReference
* @return CXF internal 2005/08 EndpointReferenceType
*/
public static EndpointReferenceType convertToInternal(EndpointReference external) {
if (external instanceof W3CEndpointReference) {
Unmarshaller um = null;
try {
DocumentFragment frag = DOMUtils.getEmptyDocument().createDocumentFragment();
DOMResult result = new DOMResult(frag);
external.writeTo(result);
W3CDOMStreamReader reader = new W3CDOMStreamReader(frag);
// CXF internal 2005/08 EndpointReferenceType should be
// compatible with W3CEndpointReference
//jaxContext = ContextUtils.getJAXBContext();
JAXBContext context = JAXBContext
.newInstance(new Class[] {org.apache.cxf.ws.addressing.ObjectFactory.class});
um = context.createUnmarshaller();
return um.unmarshal(reader, EndpointReferenceType.class).getValue();
} catch (JAXBException e) {
throw new IllegalArgumentException("Could not unmarshal EndpointReference", e);
} finally {
JAXBUtils.closeUnmarshaller(um);
}
}
return null;
}
public void assertXmlMarshaling(Object referenceObjectBinding, String expectedXml)
throws Exception
{
JAXBContext jc = JAXBContext.newInstance(ReferenceObjectBinding.class);
Marshaller marshaller = jc.createMarshaller();
StringWriter stringWriter = new StringWriter();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// marshaller.setProperty("com.sun.xml.internal.bind.namespacePrefixMapper", new CustomNamespacePrefixMapper());
marshaller.marshal(referenceObjectBinding, stringWriter);
String xml = stringWriter.toString();
// System.out.println(xml); // run test, paste xml output into XML, comment out this line.
Unmarshaller unmarshaller = jc.createUnmarshaller();
Object actual = unmarshaller.unmarshal(new StringReader(xml));
Object expected = unmarshaller.unmarshal(new StringReader(expectedXml));
Assert.assertEquals(expected, actual);
}
private States loadStateMachine(String filename)
throws StateMachineException {
logger.debug("filename: " + filename);
ClassLoader loader = Thread.currentThread().getContextClassLoader();
try (InputStream stream = loader.getResourceAsStream("statemachines/"
+ filename);) {
JAXBContext jaxbContext = JAXBContext.newInstance(States.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
return (States) jaxbUnmarshaller.unmarshal(stream);
} catch (Exception e) {
throw new StateMachineException(
"Failed to load state machine definition file: " + filename,
e);
}
}
void afterUnmarshal(Unmarshaller u, Object parent) {
for (MailTemplate template : templates) {
String caseName = template.getName().toLowerCase();
List<MailTemplate> sysTemplates = mailCaseTemplates.get(caseName);
if (sysTemplates == null) {
sysTemplates = new ArrayList<MailTemplate>();
mailCaseTemplates.put(caseName, sysTemplates);
}
sysTemplates.add(template);
}
templates.clear();
templates = null;
}
@SuppressWarnings("unchecked")
public <T> T unmarshal(Class<T> tclass, File xmlFile) throws JAXBException {
Unmarshaller unmarshaller;
try {
unmarshaller = getContext(tclass).createUnmarshaller();
} catch (Exception e) {
throw new EPSCommonException("An unmarshaller instance could not be created for class " + tclass.getCanonicalName(),e);
}
return (T)unmarshaller.unmarshal(xmlFile);
}
public void testUnmarshall() throws JAXBException {
final Unmarshaller unmarshaller = context.createUnmarshaller();
final Object object = unmarshaller.unmarshal(new File(
"src/test/samples/po.xml"));
@SuppressWarnings("unchecked")
final PurchaseOrderType purchaseOrder = ((JAXBElement<PurchaseOrderType>) object)
.getValue();
assertEquals("Wrong city", "Mill Valley", purchaseOrder.getShipTo()
.getCity());
}
@Nullable
public Options parse(InputStream inputStream, @NotNull Map<String, String> errors) {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Options.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
return unmarshaller.unmarshal(new StreamSource(inputStream), Options.class).getValue();
} catch (JAXBException e) {
errors.put("Failed to parse Xml format", e.toString());
}
return null;
}
/**
* This operation loads an ICE Component from an XML String.
*
* @param <T>
*
* @param file
* The IFile that should be loaded as an Item from XML.
* @return the Item
*/
@SuppressWarnings("unchecked")
private <T> T loadComponent(String xmlForm) {
T comp = null;
// Make an array to store the class list of registered Items
ArrayList<Class> classList = new ArrayList<Class>();
Class[] classArray = {};
classList.addAll(new ICEJAXBClassProvider().getClasses());
// Create new JAXB class context and unmarshaller
JAXBContext context = null;
try {
context = JAXBContext.newInstance(classList.toArray(classArray));
} catch (JAXBException e1) {
actionError("Remote File Upload could not get JAXBContext.", e1);
}
try {
// Create the unmarshaller and load the item
Unmarshaller unmarshaller = context.createUnmarshaller();
comp = (T) unmarshaller
.unmarshal(new ByteArrayInputStream(xmlForm.getBytes()));
} catch (JAXBException e) {
// Complain
actionError("Remote File Upload error in unmarshalling XML data.",
e);
// Null out the Item so that it can't be returned uninitialized
comp = null;
}
return comp;
}
private SchemaInfo fromXml(String schemaInfo) {
try (StringReader sr = new StringReader(schemaInfo)) {
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
return (SchemaInfo) unmarshaller.unmarshal(sr);
}
catch (JAXBException e) {
e.printStackTrace();
}
return null;
}
public static DataService readDataServiceFile(File dsFile) throws IOException {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(DataService.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
return (DataService) jaxbUnmarshaller.unmarshal(dsFile);
} catch (JAXBException e) {
throw new IOException("Error occurred while mapping the DataService", e);
}
}
@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);
}
}
@Override
public Object getPayload(JAXBContext context) {
// if(context == ctxt) {
// return o;
// }
try {
Source payloadSrc = getPayload();
if (payloadSrc == null)
return null;
Unmarshaller unmarshaller = context.createUnmarshaller();
return unmarshaller.unmarshal(payloadSrc);
} catch (JAXBException e) {
throw new WebServiceException(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;
}
@Test
public void unmarshalUnexpectedNsTest() throws Exception {
JAXBContext context;
Unmarshaller unm;
// Create JAXB context from testTypes package
context = JAXBContext.newInstance("testTypes");
// Create unmarshaller from JAXB context
unm = context.createUnmarshaller();
// Unmarshall xml document with unqualified dtime element
Root r = (Root) unm.unmarshal(new InputSource(new StringReader(DOC)));
// Print dtime value and check if it is null
System.out.println("dtime is:"+r.getWhen().getDtime());
assertNull(r.getWhen().getDtime());
}
@Test
public void testGetOneXml() throws Exception {
final Item origItem = getItemService().getItem(0);
String out = fluentTemplate().to("undertow:http://localhost:" + port1 + "/items/0/xml")
.withHeader(Exchange.HTTP_METHOD, "GET")
.request(String.class);
JAXBContext jaxbContext = JAXBContext.newInstance(Item.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Item itemOut = (Item) jaxbUnmarshaller.unmarshal(new StringReader(out));
assertEquals(origItem, itemOut);
}
public Unmarshaller getUnmarshaller(Class<?> clazz) throws GFDDPPException {
try {
return this.getContext(clazz).createUnmarshaller();
} catch (JAXBException var4) {
LOG.error("", var4);
String message = this.processJAXBException(var4);
throw new GFDDPPException(StatusCode.COMMON_ERROR_UNMARSHALLER, new String[]{message, clazz.getName()});
}
}
private Object unmarshall(Unmarshaller unmarshaller, File sourceFile) {
try {
return unmarshaller.unmarshal(sourceFile);
} catch (JAXBException e) {
Assert.fail(String.format("Could not unmarshall [%s]. [%s]", sourceFile, e));
}
return null;
}
void afterUnmarshal(Unmarshaller u, Object parent)
{
for (SpawnMap map : spawnmaps)
{
if (!mapsByWorldId.containsKey(map.worldId))
mapsByWorldId.put(map.worldId, map);
}
}
public void testWrapping() throws Exception {
JAXBContext ctx = JAXBContext.newInstance(Job.class, Node.class, UserTask.class, AutoTask.class);
InputStream is = TestWrapping.class.getResourceAsStream("test.xml");
Unmarshaller unmarshaller = ctx.createUnmarshaller();
Job job = (Job)unmarshaller.unmarshal(is);
Collection<Node> nodes = job.getNodes();
assertNotNull("Nodes are null!", nodes);
assertTrue("There are no nodes!", nodes.size()>0);
for(Node n : nodes) {
System.out.println("Name: " + n.getName());
}
}
public static <T> JAXBElement<T> unmarshallNode(Node node, Class<T> jaxbClassName) throws InternalBusinessException {
Objects.requireNonNull(node);
JAXBElement<T> jaxbElement = null;
try {
JAXBContext jaxbContext = JAXBContext.newInstance(jaxbClassName);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
jaxbElement = unmarshaller.unmarshal(new DOMSource(node), jaxbClassName);
} catch (Exception exception) {
throw new InternalBusinessException("Problem beim Unmarshalling der Node in das JAXBElement: " + exception.getMessage(), exception);
}
return jaxbElement;
}