下面列出了怎么用javax.xml.bind.JAXBContext的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Map a Token instance to its XML representation.
*
* @return a String with the description of this object in XML.
*/
public String toXML() {
StringWriter sw = new StringWriter();
String xml = "";
try {
JAXBContext context = JAXBContext.newInstance(this.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(this, sw);
xml = sw.toString();
} catch (Exception e) {
e.printStackTrace();
}
return xml;
}
public static String marshallToString(Object object, String thePackage) {
String rawObject = null;
try {
JAXBContext jc = getContext(thePackage);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
marshaller.marshal(object, baos);
rawObject = baos.toString();
} catch (JAXBException e) {
logger.error(e.getMessage(),e);
}
return rawObject;
}
public void assertXmlMarshaling(Object typeTypeRelation, String expectedXml)
throws Exception
{
JAXBContext jc = JAXBContext.newInstance(TypeTypeRelation.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(typeTypeRelation, 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);
}
@Override
public String toXML(T obj) {
try {
JAXBContext context = JAXBContext.newInstance(type);
Marshaller m = context.createMarshaller();
if(schemaLocation != null) {
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
StreamSource source = new StreamSource(getClass().getResourceAsStream(schemaLocation));
Schema schema = schemaFactory.newSchema(source);
m.setSchema(schema);
}
StringWriter writer = new StringWriter();
m.marshal(obj, writer);
String xml = writer.toString();
return xml;
} catch (Exception e) {
System.out.println("ERROR: "+e.toString());
return null;
}
}
@SuppressWarnings("unchecked")
public static <V> List<V> parseListElement(Element parent,
QName name,
Class<?> c,
JAXBContext context) throws JAXBException {
List<V> list = new ArrayList<>();
Node data = null;
Unmarshaller u = context.createUnmarshaller();
Node node = parent.getFirstChild();
while (node != null) {
if (node.getNodeType() == Node.ELEMENT_NODE && name.getLocalPart().equals(node.getLocalName())
&& name.getNamespaceURI().equals(node.getNamespaceURI())) {
data = node;
Object obj = unmarshal(u, data, c);
if (obj != null) {
list.add((V) obj);
}
}
node = node.getNextSibling();
}
return list;
}
/**
* The JAXB API will invoke this method via reflection
*/
public static JAXBContext createContext( String contextPath,
ClassLoader classLoader, Map properties ) throws JAXBException {
List<Class> classes = new ArrayList<Class>();
StringTokenizer tokens = new StringTokenizer(contextPath,":");
// each package should be pointing to a JAXB RI generated
// content interface package.
//
// translate them into a list of private ObjectFactories.
try {
while(tokens.hasMoreTokens()) {
String pkg = tokens.nextToken();
classes.add(classLoader.loadClass(pkg+IMPL_DOT_OBJECT_FACTORY));
}
} catch (ClassNotFoundException e) {
throw new JAXBException(e);
}
// delegate to the JAXB provider in the system
return JAXBContext.newInstance(classes.toArray(new Class[classes.size()]),properties);
}
/**
* @param <T> the type we want to convert the XML into
* @param c the class of the parameterized type
* @param xml the instance XML description
* @return a deserialization of the XML into an object of type T of class class <T>
* @throws JAXBException
*/
public static <T> T marshal(Class<T> c, String xml) throws JAXBException
{
T res;
if (c == xml.getClass())
{
res = (T) xml;
}
else
{
JAXBContext ctx = JAXBContext.newInstance(c);
Unmarshaller marshaller = ctx.createUnmarshaller();
res = (T) marshaller.unmarshal(new StringReader(xml));
}
return res;
}
/**
* Deserializes binary data representing a xml-fragment to an object of
* given class.
*
* @param data the binary data, representing a xml-fragment
* @param clazz the class of the resulting object
*
* @return the deserialized object
*/
@SuppressWarnings( "unchecked" )
@Override
public <T> T deserialize( byte[] data, Class<T> clazz )
{
try
{
JAXBContext context = JAXBContext.newInstance( clazz );
Unmarshaller m = context.createUnmarshaller();
Object o = m.unmarshal( new ByteArrayInputStream( data ) );
return ( T ) o;
}
catch ( JAXBException e )
{
LOG.warn( e.getMessage() );
}
return null;
}
@SuppressWarnings("unchecked")
public JAXBContext getJAXBContext(Class<?> type, Type genericType) throws JAXBException {
if (mc != null) {
ContextResolver<JAXBContext> resolver =
mc.getResolver(ContextResolver.class, JAXBContext.class);
if (resolver != null) {
JAXBContext customContext = resolver.getContext(type);
if (customContext != null) {
return customContext;
}
}
}
JAXBContext context = classContexts.get(type);
if (context != null) {
return context;
}
context = getPackageContext(type, genericType);
return context != null ? context : getClassContext(type, genericType);
}
/**
* @throws Exception
*/
public void testPersistenceVersion1() throws Exception {
final JAXBContext ctx = JAXBContextFactory.newInstance(Persistence.class);
final Unmarshaller unmarshaller = ctx.createUnmarshaller();
final URL resource = this.getClass().getClassLoader().getResource("persistence-example.xml");
final InputStream in = resource.openStream();
final java.lang.String expected = readContent(in);
final Persistence element = (Persistence) unmarshaller.unmarshal(new ByteArrayInputStream(expected.getBytes()));
unmarshaller.setEventHandler(new TestValidationEventHandler());
System.out.println("unmarshalled");
final Marshaller marshaller = ctx.createMarshaller();
marshaller.setProperty("jaxb.formatted.output", true);
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
marshaller.marshal(element, baos);
final String actual = new String(baos.toByteArray());
final Diff myDiff = new Diff(expected, actual);
myDiff.overrideElementQualifier(new ElementNameAndAttributeQualifier());
assertTrue("Files are similar " + myDiff, myDiff.similar());
}
void initJaxbContext(final Method method) {
Stream
.concat(of(method.getGenericReturnType()),
of(method.getParameters())
.filter(p -> of(Path.class, Query.class, Header.class, QueryParams.class, Headers.class,
HttpMethod.class, Url.class).noneMatch(p::isAnnotationPresent))
.map(Parameter::getParameterizedType))
.map(RequestParser::toClassType)
.filter(Objects::nonNull)
.filter(cType -> cType.isAnnotationPresent(XmlRootElement.class)
|| cType.isAnnotationPresent(XmlType.class))
.forEach(rootElemType -> jaxbContexts.computeIfAbsent(rootElemType, k -> {
try {
return JAXBContext.newInstance(k);
} catch (final JAXBException e) {
throw new IllegalStateException(e);
}
}));
}
public boolean ReloadCustomFuels()
{
boolean tResult = false;
_mLogger.debug("CustomFuelsHandler will now try to load it's configuration");
try
{
JAXBContext tJaxbCtx = JAXBContext.newInstance(CustomFuels.class);
File tConfigFile = new File(_mConfigFileName);
Unmarshaller jaxUnmarsh = tJaxbCtx.createUnmarshaller();
CustomFuels tNewItemCollection = (CustomFuels) jaxUnmarsh.unmarshal(tConfigFile);
_mLogger.debug("Config file has been loaded. Entering Verify state");
_mCustomFuels = tNewItemCollection;
tResult = true;
}
catch (Exception e)
{
e.printStackTrace();
}
return tResult;
}
@org.junit.Test
public void verifyConfigFederation() throws JAXBException {
final JAXBContext jaxbContext = JAXBContext
.newInstance(FedizConfig.class);
FedizConfigurator configurator = new FedizConfigurator();
FedizConfig configOut = createConfiguration(true);
StringWriter writer = new StringWriter();
jaxbContext.createMarshaller().marshal(configOut, writer);
StringReader reader = new StringReader(writer.toString());
configurator.loadConfig(reader);
ContextConfig config = configurator.getContextConfig(CONFIG_NAME);
Assert.assertNotNull(config);
AudienceUris audience = config.getAudienceUris();
Assert.assertEquals(3, audience.getAudienceItem().size());
Assert.assertTrue(config.getProtocol() instanceof FederationProtocolType);
FederationProtocolType fp = (FederationProtocolType) config
.getProtocol();
Assert.assertEquals(HOME_REALM_CLASS, fp.getHomeRealm().getValue());
}
private static WebApp parseXmlFragment() {
InputStream precompiledJspWebXml = RegisterPrecompiledJSPInitializer.class.getResourceAsStream("/precompiled-jsp-web.xml");
InputStream webXmlIS = new SequenceInputStream(
new SequenceInputStream(
IOUtils.toInputStream("<web-app>", Charset.defaultCharset()),
precompiledJspWebXml),
IOUtils.toInputStream("</web-app>", Charset.defaultCharset()));
try {
JAXBContext jaxbContext = new JAXBDataBinding(WebApp.class).getContext();
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
WebApp webapp = (WebApp) unmarshaller.unmarshal(webXmlIS);
try {
webXmlIS.close();
} catch (java.io.IOException ignored) {}
return webapp;
} catch (JAXBException e) {
throw new RuntimeException("Could not parse precompiled-jsp-web.xml", e);
}
}
@org.junit.Test
public void testClaimProcessor() throws JAXBException, IOException {
final JAXBContext jaxbContext = JAXBContext.newInstance(FedizConfig.class);
FedizConfigurator configurator = new FedizConfigurator();
FedizConfig configOut = createConfiguration(true);
StringWriter writer = new StringWriter();
jaxbContext.createMarshaller().marshal(configOut, writer);
StringReader reader = new StringReader(writer.toString());
configurator.loadConfig(reader);
FedizContext fedContext = configurator.getFedizContext(CONFIG_NAME);
List<ClaimsProcessor> claimsProcessor = fedContext.getClaimsProcessor();
Assert.assertNotNull(claimsProcessor);
Assert.assertEquals(1, claimsProcessor.size());
List<org.apache.cxf.fediz.core.Claim> inputClaims = new ArrayList<>();
org.apache.cxf.fediz.core.Claim claim = new org.apache.cxf.fediz.core.Claim();
claim.setClaimType(URI.create(CLAIM_TYPE_1));
claim.setValue("Alice");
inputClaims.add(claim);
List<org.apache.cxf.fediz.core.Claim> processedClaims = claimsProcessor.get(0).processClaims(inputClaims);
Assert.assertEquals(inputClaims, processedClaims);
}
public void reinit(IServiceSettings serviceSettings) {
TCPIPProxySettings newSettings;
if (serviceSettings instanceof TCPIPProxySettings) {
newSettings = (TCPIPProxySettings) serviceSettings;
} else {
throw new ServiceException("Incorrect class of settings has been passed to init " + serviceSettings.getClass());
}
if(newSettings.isChangeTags() && (newSettings.getRulesAlias() != null)) {
try {
JAXBContext jc = JAXBContext.newInstance(new Class[]{Rules.class});
Unmarshaller u = jc.createUnmarshaller();
InputStream rulesAliasIS = dataManager.getDataInputStream(newSettings.getRulesAlias());
JAXBElement<Rules> root = u.unmarshal(new StreamSource(rulesAliasIS),Rules.class);
this.rules = root.getValue();
} catch (Exception e) {
disconnect();
dispose();
changeStatus(ServiceStatus.ERROR, "Error while reiniting", e);
throw new EPSCommonException(e);
}
}
}
protected static JAXBContext getJaxbContext(Class clazz) {
if (clazz == null){
throw new RuntimeException("'clazz' must not be null");
}
JAXBContext jaxbContext = jaxbContexts.get(clazz);
if (jaxbContext == null) {
try {
jaxbContext = JAXBContext.newInstance(clazz, CollectionWrapper.class);
jaxbContexts.putIfAbsent(clazz, jaxbContext);
} catch (JAXBException ex) {
// throw new HttpMessageConversionException("Could not instantiate JAXBContext for class [" + clazz
// + "]: " + ex.getMessage(), ex);
throw new RuntimeException("Could not instantiate JAXBContext for class [" + clazz
+ "]: " + ex.getMessage(), ex);
}
}
return jaxbContext;
}
@Before
public void setUp() throws Exception {
try {
JAXBContext cntxt = JAXBContext.newInstance(JAXB_CONTEXT);
InputStream in = this.getClass().getClassLoader().getResourceAsStream(XML_FILE);
Unmarshaller um = cntxt.createUnmarshaller();
JAXBElement<?> jel = (JAXBElement<?>) um.unmarshal(in);
assertNotNull(jel.getValue());
assertTrue(jel.getValue() instanceof PortletAppType);
portletApp = (PortletAppType) jel.getValue();
} catch (Exception e) {
System.out.println("\nException during setup: " + e.getMessage()
+ "\n");
throw e;
}
}
/**
* Return a {@link JAXBContext} for the given class.
* @param clazz the class to return the context for
* @return the {@code JAXBContext}
* @throws HttpMessageConversionException in case of JAXB errors
*/
protected final JAXBContext getJaxbContext(Class<?> clazz) {
Assert.notNull(clazz, "Class must not be null");
JAXBContext jaxbContext = this.jaxbContexts.get(clazz);
if (jaxbContext == null) {
try {
jaxbContext = JAXBContext.newInstance(clazz);
this.jaxbContexts.putIfAbsent(clazz, jaxbContext);
}
catch (JAXBException ex) {
throw new HttpMessageConversionException(
"Could not instantiate JAXBContext for class [" + clazz + "]: " + ex.getMessage(), ex);
}
}
return jaxbContext;
}
/**
* <p>writeMigration.</p>
*
* @param dbMigration a {@link io.ebeaninternal.dbmigration.migration.Migration} object.
* @param version a {@link java.lang.String} object.
* @return a boolean.
*/
protected boolean writeMigration(Migration dbMigration, String version) {
if (migrationModel.isMigrationTableExist()) {
scriptInfo = server.find(ScriptInfo.class, version);
if (scriptInfo != null) {
return false;
}
}
scriptInfo = new ScriptInfo();
scriptInfo.setRevision(version);
try (StringWriter writer = new StringWriter()) {
JAXBContext jaxbContext = JAXBContext.newInstance(Migration.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(dbMigration, writer);
writer.flush();
scriptInfo.setModelDiff(writer.toString());
} catch (JAXBException | IOException e) {
throw new RuntimeException(e);
}
return true;
}
@Test
public void testSOAPPBindingNullMessage() throws Exception {
d.setMessageObserver(new MessageReplayObserver("/org/apache/cxf/jaxws/sayHiResponse.xml"));
URL wsdl = getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service = new SOAPService(wsdl, SERVICE_NAME);
assertNotNull(service);
JAXBContext jc = JAXBContext.newInstance("org.apache.hello_world_soap_http.types");
Dispatch<Object> disp = service.createDispatch(PORT_NAME, jc, Service.Mode.PAYLOAD);
try {
// Send a null message
disp.invoke(null);
} catch (SOAPFaultException e) {
//Passed
return;
}
fail("SOAPFaultException was not thrown");
}
public void printInterchangeStudentProgram(PrintStream ps) throws JAXBException {
JAXBContext context = JAXBContext.newInstance(InterchangeStudentProgram.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty("jaxb.formatted.output", Boolean.TRUE);
InterchangeStudentProgram interchangeStudentProgram = new InterchangeStudentProgram();
List<Object> list = interchangeStudentProgram
.getStudentProgramAssociationOrStudentSpecialEdProgramAssociationOrRestraintEvent();
// StudentProgramAssociation
// StudentSpecialEdProgramAssociation
// RestraintEvent
// StudentCTEProgramAssociation
// StudentTitleIPartAProgramAssociation
// ServiceDescriptor
marshaller.marshal(interchangeStudentProgram, ps);
}
void init() {
try {
JAXBContext context = JAXBContext.newInstance("org.zstack.core.errorcode.schema");
List<String> paths = PathUtil.scanFolderOnClassPath("errorCodes");
for (String p : paths) {
if (!p.endsWith(".xml")) {
logger.warn(String.format("ignore %s which is not ending with .xml", p));
continue;
}
File cfg = new File(p);
Unmarshaller unmarshaller = context.createUnmarshaller();
org.zstack.core.errorcode.schema.Error error =
(org.zstack.core.errorcode.schema.Error) unmarshaller.unmarshal(cfg);
createErrorCode(error, p);
}
} catch (Exception e) {
throw new CloudRuntimeException(e);
}
}
/**
* Marshal an object to a file, using provided JAXB context.
*
* @param object instance to marshal
* @param path target file
* @param jaxbContext proper context
* @throws IOException on IO error
* @throws JAXBException on JAXB error
* @throws XMLStreamException on XML error
*/
public static void marshal (Object object,
Path path,
JAXBContext jaxbContext)
throws IOException,
JAXBException,
XMLStreamException
{
try (OutputStream os = Files.newOutputStream(path, CREATE);) {
Marshaller m = jaxbContext.createMarshaller();
XMLStreamWriter writer = new IndentingXMLStreamWriter(
XMLOutputFactory.newInstance().createXMLStreamWriter(os, "UTF-8"));
m.marshal(object, writer);
os.flush();
}
}
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;
}
/**
* Marshals the given QueryResults object to its XML representations and
* returns it as a String.
*
* @param results
* The QueryResults object to marshal into XML.
* @param out
* The OutputStream to which the XML representation will be
* written to.
* @throws IOException
* If an error marshaling the QueryResults object occurred.
*/
public static String queryResultsToXml(final QueryResults results) throws IOException {
// serialize the response
try {
StringWriter writer = new StringWriter();
JAXBElement<QueryResults> item = factory.createQueryResults(results);
JAXBContext context = JAXBContext.newInstance(QueryResults.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
marshaller.marshal(item, writer);
return writer.toString();
} catch (JAXBException e) {
IOException ioe = new IOException(e.getMessage());
ioe.setStackTrace(e.getStackTrace());
throw ioe;
}
}
public ApiMessageProcessorImpl(Map<String, Object> config) {
this.unitTestOn = CoreGlobalProperty.UNIT_TEST_ON;
this.configFolders = (List <String>)config.get("serviceConfigFolders");
populateGlobalInterceptors();
try {
JAXBContext context = JAXBContext.newInstance("org.zstack.portal.apimediator.schema");
List<String> paths = new ArrayList<String>();
for (String configFolder : this.configFolders) {
paths.addAll(PathUtil.scanFolderOnClassPath(configFolder));
}
for (String p : paths) {
if (!p.endsWith(".xml")) {
logger.warn(String.format("ignore %s which is not ending with .xml", p));
continue;
}
File cfg = new File(p);
Unmarshaller unmarshaller = context.createUnmarshaller();
Service schema = (Service) unmarshaller.unmarshal(cfg);
createDescriptor(schema, cfg.getAbsolutePath());
}
if (!this.unitTestOn) {
dump();
}
} catch (JAXBException e) {
throw new CloudRuntimeException(e);
}
}
private static JAXBContext getJaxbContext ()
throws JAXBException
{
// Lazy creation
if (jaxbContext == null) {
jaxbContext = JAXBContext.newInstance(TribeList.class);
}
return jaxbContext;
}
public static <T> Object unmarshal(final Class<T> type, final InputStream in, final boolean logErrors) throws ParserConfigurationException, SAXException, JAXBException {
final InputSource inputSource = new InputSource(in);
final SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(false);
final SAXParser parser = factory.newSAXParser();
final JAXBContext ctx = getContext(type);
final Unmarshaller unmarshaller = ctx.createUnmarshaller();
unmarshaller.setEventHandler(new ValidationEventHandler() {
public boolean handleEvent(final ValidationEvent validationEvent) {
if (logErrors) {
System.out.println(validationEvent);
}
return false;
}
});
unmarshaller.setListener(new Unmarshaller.Listener() {
public void afterUnmarshal(final Object object, final Object object1) {
super.afterUnmarshal(object, object1);
}
public void beforeUnmarshal(final Object target, final Object parent) {
super.beforeUnmarshal(target, parent);
}
});
final NamespaceFilter xmlFilter = new NamespaceFilter(parser.getXMLReader());
xmlFilter.setContentHandler(unmarshaller.getUnmarshallerHandler());
final SAXSource source = new SAXSource(xmlFilter, inputSource);
return unmarshaller.unmarshal(source, type);
}
private Node createNode(JAXBElement jaxb, JAXBContext jc, String expression) throws Exception{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.newDocument();
Marshaller marshaller = jc.createMarshaller();
marshaller.marshal(jaxb, document);
XPath xpath = XPathFactory.newInstance().newXPath();
Node node = (Node) xpath.compile(expression).evaluate(document, XPathConstants.NODE);
return node;
}