下面列出了javax.xml.bind.Unmarshaller#setSchema ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@SuppressWarnings("unchecked")
@Test
public void test() throws JAXBException, SAXException {
JAXBContext jc = samlAssertionUtils.getJAXBContext();
assertNotNull(jc);
Schema schema = samlAssertionUtils.getSchema();
assertNotNull(schema);
File file = new File("src/test/resources/sample-saml-assertion.xml");
Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.setSchema(schema);
JAXBElement<AssertionType> unmarshalled = (JAXBElement<AssertionType>) unmarshaller.unmarshal(file);
assertNotNull(unmarshalled);
}
static Mets unmarshalMets(File metsFile, boolean validate, Class<?>... nestedClassed) throws IOException, JAXBException, SAXException {
Mets mets;
// try {
Unmarshaller u = JaxbUtils.createUnmarshaller(Mets.class);
long t = System.currentTimeMillis();
if (validate) {
Schema schema = XmlFormat.METS.getOrCompileSchema();
u.setSchema(schema);
}
Object o = u.unmarshal(metsFile);
mets = (Mets) o;
logger.debug("time for unmarshalling: "+(System.currentTimeMillis()-t)+", validated: "+validate);
// mets = JaxbUtils.unmarshal(metsFile, Mets.class, nestedClassed);
// mets = JaxbUtils.unmarshal2(new FileInputStream(metsFile), Mets.class, true, false);
// } catch (Exception e) {
// throw new IOException("Could not unmarshal METS file!", e);
// }
logger.debug("unmarshalled mets file");
return mets;
}
/**
* Template method that can be overridden by concrete JAXB marshallers for custom initialization behavior.
* Gets called after creation of JAXB {@code Marshaller}, and after the respective properties have been set.
* <p>The default implementation sets the {@link #setUnmarshallerProperties(Map) defined properties}, the {@link
* #setValidationEventHandler(ValidationEventHandler) validation event handler}, the {@link #setSchemas(Resource[])
* schemas}, {@link #setUnmarshallerListener(javax.xml.bind.Unmarshaller.Listener) listener}, and
* {@link #setAdapters(XmlAdapter[]) adapters}.
*/
protected void initJaxbUnmarshaller(Unmarshaller unmarshaller) throws JAXBException {
if (this.unmarshallerProperties != null) {
for (String name : this.unmarshallerProperties.keySet()) {
unmarshaller.setProperty(name, this.unmarshallerProperties.get(name));
}
}
if (this.unmarshallerListener != null) {
unmarshaller.setListener(this.unmarshallerListener);
}
if (this.validationEventHandler != null) {
unmarshaller.setEventHandler(this.validationEventHandler);
}
if (this.adapters != null) {
for (XmlAdapter<?, ?> adapter : this.adapters) {
unmarshaller.setAdapter(adapter);
}
}
if (this.schema != null) {
unmarshaller.setSchema(this.schema);
}
}
private void validateMalformedConfig(File malformedConfig) {
try {
JAXBContext ctx = JAXBContext.newInstance(DeviceManagementConfig.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 device management config", e);
Assert.assertTrue(false);
}
log.error("JAXB parser occurred while unmarsharlling device management config", e);
Assert.assertTrue(true);
}
}
private Authorizers loadAuthorizersConfiguration() throws Exception {
final File authorizersConfigurationFile = properties.getAuthorizerConfigurationFile();
// load the authorizers from the specified file
if (authorizersConfigurationFile.exists()) {
try {
// find the schema
final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
final Schema schema = schemaFactory.newSchema(Authorizers.class.getResource(AUTHORIZERS_XSD));
// attempt to unmarshal
final Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
unmarshaller.setSchema(schema);
final JAXBElement<Authorizers> element = unmarshaller.unmarshal(new StreamSource(authorizersConfigurationFile), Authorizers.class);
return element.getValue();
} catch (SAXException | JAXBException e) {
throw new Exception("Unable to load the authorizer configuration file at: " + authorizersConfigurationFile.getAbsolutePath(), e);
}
} else {
throw new Exception("Unable to find the authorizer configuration file at " + authorizersConfigurationFile.getAbsolutePath());
}
}
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);
}
}
/**
* Unmarshall an instance of {@link QueriesBenchmarkConf} from the XML that
* is retrieved from an {@link InputStream}.
*
* @param xmlStream - The input stream holding the XML. (not null)
* @return The {@link BenchmarkQueries} instance that was read from the stream.
* @throws JAXBException There was a problem with the formatting of the XML.
* @throws ParserConfigurationException There was a problem creating the DocumentBuilder.
* @throws IOException There was a problem reading the xmlStream.
* @throws SAXException There was a problem parsing the xmlStream.
*/
public QueriesBenchmarkConf load(final InputStream xmlStream) throws JAXBException, ParserConfigurationException, SAXException, IOException {
requireNonNull(xmlStream);
// Load the schema that describes the stream.
final Schema schema = SCHEMA_SUPPLIER.get();
// Unmarshal the object from the stream.
final JAXBContext context = JAXBContext.newInstance( QueriesBenchmarkConf.class );
final Unmarshaller unmarshaller = context.createUnmarshaller();
unmarshaller.setSchema(schema);
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
XmlFactoryConfiguration.harden(dbf);
final DocumentBuilder db = dbf.newDocumentBuilder();
return (QueriesBenchmarkConf) unmarshaller.unmarshal(db.parse(xmlStream));
}
@Override
public Unmarshaller createUnmarshaller() throws JAXBException {
Unmarshaller unmarshaller = super.createUnmarshaller();
Schema schema;
try {
schema = JAXBUtil.getSchema();
} catch(Exception e){
throw new RuntimeException(e);
}
unmarshaller.setSchema(schema);
unmarshaller.setEventHandler(new SimpleValidationEventHandler());
return unmarshaller;
}
@Override
public T fromXML(String xml) {
try {
JAXBContext context = JAXBContext.newInstance(type);
Unmarshaller u = context.createUnmarshaller();
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);
u.setSchema(schema);
}
StringReader reader = new StringReader(xml);
T obj = (T) u.unmarshal(reader);
return obj;
} catch (Exception e) {
System.out.println("ERROR: "+e.toString());
return null;
}
}
private IdentityProviders loadLoginIdentityProvidersConfiguration() throws Exception {
final File loginIdentityProvidersConfigurationFile = properties.getIdentityProviderConfigurationFile();
// load the users from the specified file
if (loginIdentityProvidersConfigurationFile.exists()) {
try {
// find the schema
final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
final Schema schema = schemaFactory.newSchema(IdentityProviders.class.getResource(LOGIN_IDENTITY_PROVIDERS_XSD));
// attempt to unmarshal
XMLStreamReader xsr = XmlUtils.createSafeReader(new StreamSource(loginIdentityProvidersConfigurationFile));
final Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
unmarshaller.setSchema(schema);
final JAXBElement<IdentityProviders> element = unmarshaller.unmarshal(xsr, IdentityProviders.class);
return element.getValue();
} catch (SAXException | JAXBException e) {
throw new Exception("Unable to load the login identity provider configuration file at: " + loginIdentityProvidersConfigurationFile.getAbsolutePath());
}
} else {
throw new Exception("Unable to find the login identity provider configuration file at " + loginIdentityProvidersConfigurationFile.getAbsolutePath());
}
}
private void setSchema(Unmarshaller u, File schemaLocation) throws Exception {
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
URI schemaURI = schemaLocation.toURI();
File schemaFile = new File(schemaURI.getPath());
Schema schema = sf.newSchema(schemaFile);
u.setSchema(schema);
}
@Test
@SuppressWarnings("unchecked")
public void test() throws JAXBException, SAXException {
File xmldsigFile = new File("src/test/resources/xades-lta.xml");
JAXBContext jc = xadesUtils.getJAXBContext();
assertNotNull(jc);
Schema schema = xadesUtils.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 xadesString = sw.toString();
JAXBElement<SignatureType> unmarshalled2 = (JAXBElement<SignatureType>) unmarshaller.unmarshal(new StringReader(xadesString));
assertNotNull(unmarshalled2);
}
private Tenants unmarshallTenants() throws JAXBException {
final Unmarshaller unmarshaller = JAXB_TENANTS_CONTEXT.createUnmarshaller();
unmarshaller.setSchema(tenantsSchema);
final JAXBElement<Tenants> element = unmarshaller.unmarshal(new StreamSource(tenantsFile), Tenants.class);
return element.getValue();
}
public static Unmarshaller getValidatingUnmarshaller(String[] pkgNames, String[] schemaLocations) throws JAXBException,
SAXException, IOException {
StringBuilder builder = new StringBuilder();
int len = pkgNames.length;
if (len == 0)
throw logger.nullValueError("Packages are empty");
for (String pkg : pkgNames) {
builder.append(pkg);
builder.append(":");
}
Unmarshaller unmarshaller = getUnmarshaller(builder.toString());
SchemaFactory schemaFactory = getSchemaFactory();
// Get the sources
Source[] schemaSources = new Source[schemaLocations.length];
int i = 0;
for (String schemaLocation : schemaLocations) {
URL schemaURL = SecurityActions.loadResource(JAXBUtil.class, schemaLocation);
if (schemaURL == null)
throw logger.nullValueError("Schema URL :" + schemaLocation);
schemaSources[i++] = new StreamSource(schemaURL.openStream());
}
Schema schema = schemaFactory.newSchema(schemaSources);
unmarshaller.setSchema(schema);
return unmarshaller;
}
public <ConfigType> ConfigType unmarshallXml(T2FlowParser t2FlowParser,
String xml, Class<ConfigType> configType) throws ReaderException {
Unmarshaller unmarshaller2 = t2FlowParser.getUnmarshaller();
unmarshaller2.setSchema(null);
Source source = new StreamSource(new StringReader(xml));
try {
JAXBElement<ConfigType> configElemElem = unmarshaller2.unmarshal(
source, configType);
return configElemElem.getValue();
} catch (JAXBException|ClassCastException e) {
throw new ReaderException("Can't parse xml " + xml, e);
}
}
@Override
public Unmarshaller get() {
try {
Unmarshaller unmarshaller = context.createUnmarshaller();
unmarshaller.setSchema(schema);
return unmarshaller;
} catch (JAXBException e) {
throw new RuntimeException(e);
}
}
public Unmarshaller getUnmarshaller(boolean validate) throws JAXBException, IOException, SAXException {
Unmarshaller unmarshaller = getJAXBContext().createUnmarshaller();
if (validate) {
unmarshaller.setSchema(getSchema());
}
return unmarshaller;
}
private Tenants unmarshallTenants() throws JAXBException {
final Unmarshaller unmarshaller = JAXB_TENANTS_CONTEXT.createUnmarshaller();
unmarshaller.setSchema(tenantsSchema);
try {
final XMLStreamReader xsr = XmlUtils.createSafeReader(new StreamSource(tenantsFile));
final JAXBElement<Tenants> element = unmarshaller.unmarshal(xsr, Tenants.class);
return element.getValue();
} catch (XMLStreamException e) {
throw new JAXBException("Error unmarshalling tenants", e);
}
}
private void load(InputStream stream) throws JAXBException, SAXException, IOException {
JAXBContext jaxbContext = JAXBContext.newInstance(ActionsContingencies.class);
Unmarshaller jaxbMarshaller = jaxbContext.createUnmarshaller();
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
URL res = XmlFileContingenciesAndActionsDatabaseClient.class.getClassLoader().getResource("xsd/actions.xsd");
if (res == null) {
throw new IOException("Unable to find schema");
}
Schema schema = sf.newSchema(res);
jaxbMarshaller.setSchema(schema);
actionContingencies = (ActionsContingencies) jaxbMarshaller.unmarshal(stream);
}
@Override
public SampleObject parse(final String text) {
try {
Unmarshaller unmashaller = context.createUnmarshaller();
unmashaller.setSchema(schema);
// SampleObject object = JAXB.unmarshal(new StringReader(text), SampleObject.class);
SampleObject object = (SampleObject) unmashaller.unmarshal(new StringReader(text));
return object;
} catch(JAXBException | DataBindingException e) {
throw new TextParseException(text, SampleObject.class);
}
}