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

The following examples show how to use javax.xml.bind.Unmarshaller#setSchema() . 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: FEPLocalDocReader.java    From TranskribusCore with GNU General Public License v3.0 6 votes vote down vote up
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;
	}
 
Example 2
Source File: Jaxb2Marshaller.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example 3
Source File: DeviceManagementConfigTests.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example 4
Source File: SAMLAssertionUtilsTest.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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);
}
 
Example 5
Source File: IdentityProviderFactory.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
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());
    }
}
 
Example 6
Source File: AuthorizerFactoryBean.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
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());
    }
}
 
Example 7
Source File: AppManagementConfigurationManagerTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
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);
	}
}
 
Example 8
Source File: QueriesBenchmarkConfReader.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * 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));
}
 
Example 9
Source File: ValidationExample.java    From jpmml-model with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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;
}
 
Example 10
Source File: ConverterImpl.java    From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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;
    }
}
 
Example 11
Source File: GeneralProcessorBuilderTest.java    From super-csv-annotation with Apache License 2.0 5 votes vote down vote up
@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);
            }
        }
 
Example 12
Source File: XmlFileContingenciesAndActionsDatabaseClient.java    From ipst with Mozilla Public License 2.0 5 votes vote down vote up
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);
}
 
Example 13
Source File: FileUserGroupProvider.java    From nifi with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 14
Source File: AbstractJaxbFacade.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
public Unmarshaller getUnmarshaller(boolean validate) throws JAXBException, IOException, SAXException {
	Unmarshaller unmarshaller = getJAXBContext().createUnmarshaller();
	if (validate) {
		unmarshaller.setSchema(getSchema());
	}
	return unmarshaller;
}
 
Example 15
Source File: JaxbConverter.java    From conf4j with MIT License 5 votes vote down vote up
@Override
public Unmarshaller get() {
    try {
        Unmarshaller unmarshaller = context.createUnmarshaller();
        unmarshaller.setSchema(schema);
        return unmarshaller;
    } catch (JAXBException e) {
        throw new RuntimeException(e);
    }
}
 
Example 16
Source File: AbstractActivityParser.java    From incubator-taverna-language with Apache License 2.0 5 votes vote down vote up
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);
	}
}
 
Example 17
Source File: JAXBUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 18
Source File: FileAuthorizer.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 19
Source File: XAdESUtilsTest.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/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);
}
 
Example 20
Source File: SchemaValidator.java    From jdmn with Apache License 2.0 5 votes vote down vote up
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);
}