Example usage for javax.xml.bind Unmarshaller setSchema

List of usage examples for javax.xml.bind Unmarshaller setSchema

Introduction

In this page you can find the example usage for javax.xml.bind Unmarshaller setSchema.

Prototype

public void setSchema(javax.xml.validation.Schema schema);

Source Link

Document

Specify the JAXP 1.3 javax.xml.validation.Schema Schema object that should be used to validate subsequent unmarshal operations against.

Usage

From source file:Main.java

@SuppressWarnings("unchecked")
public static <T> Object xmlToObject(InputStream xmlContent, Class<T> clazz) throws JAXBException {

    JAXBContext context = JAXBContext.newInstance(clazz);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    unmarshaller.setSchema(null); //note: setting schema to null will turn validator off
    Object unMarshalled = unmarshaller.unmarshal(xmlContent);
    Object xmlObject = clazz.cast(unMarshalled);

    return (T) xmlObject;
}

From source file:Main.java

@SuppressWarnings("unchecked")
public static <T> Object xmlToObject(String xmlContent, Class<T> clazz) throws JAXBException {

    ByteArrayInputStream xmlContentBytes = new ByteArrayInputStream(xmlContent.getBytes());
    JAXBContext context = JAXBContext.newInstance(clazz);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    unmarshaller.setSchema(null); //note: setting schema to null will turn validator off
    Object unmarshalledObj = unmarshaller.unmarshal(xmlContentBytes);
    Object xmlObject = clazz.cast(unmarshalledObj);

    return (T) xmlObject;
}

From source file:Main.java

public static <T> T unmarshal(Reader r, Class<T> clazz)
        throws JAXBException, XMLStreamException, FactoryConfigurationError {
    JAXBContext context = s_contexts.get(clazz);
    if (context == null) {
        context = JAXBContext.newInstance(clazz);
        s_contexts.put(clazz, context);/* w  w w  . j  a  va 2s  .c o m*/
    }

    ValidationEventCollector valEventHndlr = new ValidationEventCollector();
    XMLStreamReader xmlsr = XMLInputFactory.newFactory().createXMLStreamReader(r);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    unmarshaller.setSchema(null);
    unmarshaller.setEventHandler(valEventHndlr);

    JAXBElement<T> elem = null;
    try {
        elem = unmarshaller.unmarshal(xmlsr, clazz);
    } catch (Exception e) {
        if (e instanceof JAXBException) {
            throw (JAXBException) e;
        } else {
            throw new UnmarshalException(e.getMessage(), e);
        }
    }

    if (valEventHndlr.hasEvents()) {
        for (ValidationEvent valEvent : valEventHndlr.getEvents()) {
            if (valEvent.getSeverity() != ValidationEvent.WARNING) {
                // throw a new Unmarshall Exception if there is a parsing error
                String msg = MessageFormat.format("Line {0}, Col: {1}: {2}",
                        valEvent.getLocator().getLineNumber(), valEvent.getLocator().getColumnNumber(),
                        valEvent.getLinkedException().getMessage());
                throw new UnmarshalException(msg, valEvent.getLinkedException());
            }
        }
    }
    return elem.getValue();
}

From source file:eu.europa.esig.dss.validation.ValidationResourceManager.java

/**
 * This is the utility method that loads the data from the inputstream determined by the inputstream parameter into
 * a/*w w  w .  j a  v  a2 s. c  o  m*/
 * {@link ConstraintsParameters}.
 *
 * @param inputStream
 * @return
 */
public static ConstraintsParameters load(final InputStream inputStream) throws DSSException {
    try {
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(new StreamSource(
                ValidationResourceManager.class.getResourceAsStream(defaultPolicyXsdLocation)));

        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.setSchema(schema);

        return (ConstraintsParameters) unmarshaller.unmarshal(inputStream);
    } catch (Exception e) {
        throw new DSSException("Unable to load policy : " + e.getMessage(), e);
    }
}

From source file:Main.java

/**
 * Generic method to Validate XML file while unmarshalling against their schema.
 * /*w w  w .  j  a v  a 2s .  co  m*/
 * @param context
 * @param schemaFile
 * @param object
 * @return
 * @throws SAXException
 * @throws JAXBException
 */
public static Object validateAndUnmarshallXML(JAXBContext context, String schemaFile, InputStream fio)
        throws SAXException, JAXBException {

    if (context != null && (schemaFile != null && schemaFile.trim().length() > 0)) {
        Unmarshaller unMarshaller = context.createUnmarshaller();

        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // thread- safe 
        unMarshaller.setSchema(sf.newSchema(new File(schemaFile))); // validate jaxb context against schema 

        return unMarshaller.unmarshal(fio);

    }
    return null;
}

From source file:de.iteratec.iteraplan.businesslogic.service.SavedQueryXmlHelper.java

/**
 * Loads a query from database// w  w w  .j ava  2s  .  co  m
 * 
 * @param <T> The XML dto class the XML content reflects
 * @param clazz The XML dto class the XML content reflects
 * @param schemaName The URI of the schema that will be used to validate the XML query
 * @param savedQuery the query object
 * @return The object tree reflecting the XML query. Instance of a JAXB-marshallable class
 */
@SuppressWarnings("unchecked")
public static <T extends SerializedQuery<? extends ReportMemBean>> T loadQuery(Class<T> clazz,
        String schemaName, SavedQuery savedQuery) {
    if (!ReportType.LANDSCAPE.equals(savedQuery.getType())
            && clazz.isAssignableFrom(LandscapeDiagramXML.class)) {
        LOGGER.error("requested QueryType ('{0}') does not fit the required QueryType ('{1}')",
                ReportType.LANDSCAPE, savedQuery.getType());
        throw new IteraplanBusinessException(IteraplanErrorMessages.INVALID_REQUEST_PARAMETER,
                "savedQueryType");
    }

    try {
        String content = savedQuery.getContent();
        if (content == null || content.length() <= 0) {
            throw new IteraplanTechnicalException(IteraplanErrorMessages.LOAD_QUERY_EXCEPTION);
        }

        Reader queryDefinitionReader = null;
        try {
            Schema schema = getSchema(schemaName);
            JAXBContext context = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            unmarshaller.setSchema(schema);

            queryDefinitionReader = new StringReader(content);
            return (T) unmarshaller.unmarshal(queryDefinitionReader);
        } finally {
            IOUtils.closeQuietly(queryDefinitionReader);
        }
    } catch (SAXException e) {
        LOGGER.error("SAXException in SavedQueryServiceImpl#loadQuery " + e.getLocalizedMessage());
        throw new IteraplanTechnicalException(IteraplanErrorMessages.INTERNAL_ERROR, e);
    } catch (JAXBException e) {
        LOGGER.error("JAXBException in SavedQueryServiceImpl#loadQuery " + e.getLocalizedMessage());
        throw new IteraplanTechnicalException(IteraplanErrorMessages.INTERNAL_ERROR, e);
    }
}

From source file:com.hmsinc.epicenter.classifier.ClassifierFactory.java

/**
 * Creates the actual classifier./*from w  w  w  . j a  v a  2 s. c o m*/
 * 
 * @param resource
 * @return classificationEngine
 * @throws Exception
 */
private static ClassificationEngine instantiateClassifier(final Resource resource) throws Exception {

    final Unmarshaller u = JAXBContext.newInstance("com.hmsinc.epicenter.classifier.config")
            .createUnmarshaller();

    // Enable validation
    u.setSchema(schema);

    final InputStream is = resource.getInputStream();
    final ClassifierConfig config = (ClassifierConfig) u.unmarshal(is);
    is.close();

    Validate.notNull(config, "Configuration was null!");
    Validate.notNull(config.getImplementation(), "No implementation was specified.");

    final Class<?> implementation = Class.forName(config.getImplementation());
    Validate.isTrue(ClassificationEngine.class.isAssignableFrom(implementation),
            "Implementation must be an instance of ClassificationEngine (was: " + config.getImplementation()
                    + ")");

    final ClassificationEngine engine = (ClassificationEngine) implementation.newInstance();
    engine.init(config);

    return engine;
}

From source file:ee.ria.xroad.opmonitordaemon.QueryRequestHandler.java

private static Unmarshaller createUnmarshaller(Class<?> clazz) throws Exception {
    Unmarshaller unmarshaller = JaxbUtils.createUnmarshaller(clazz);
    unmarshaller.setEventHandler(QueryRequestHandler::validationFailed);
    unmarshaller.setSchema(OP_MONITORING_SCHEMA);

    return unmarshaller;
}

From source file:Main.java

/**
 * Unmarshal XML data from XML DOM document using XSD string and return the resulting JAXB content tree
 *
 * @param dummyJAXBObject/*from w  w  w.  j a v a 2s  .c  o m*/
 *            Dummy contect object for creating related JAXB context
 * @param doc
 *            XML DOM document
 * @param strXSD
 *            XSD
 * @return resulting JAXB content tree
 * @throws Exception
 *             in error case
 */
public static Object doUnmarshallingFromDOMDocument(Object dummyJAXBObject, Document doc, String strXSD)
        throws Exception {
    if (dummyJAXBObject == null) {
        throw new RuntimeException("No dummy context objekt (null)!");
    }
    if (doc == null) {
        throw new RuntimeException("No XML DOM document (null)!");
    }
    if (strXSD == null) {
        throw new RuntimeException("No XSD document (null)!");
    }

    Object unmarshalledObject = null;
    StringReader reader = null;

    try {
        JAXBContext jaxbCtx = JAXBContext.newInstance(dummyJAXBObject.getClass().getPackage().getName());
        Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();
        reader = new StringReader(strXSD);

        javax.xml.validation.Schema schema = javax.xml.validation.SchemaFactory
                .newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(new StreamSource(reader));
        unmarshaller.setSchema(schema);

        unmarshalledObject = unmarshaller.unmarshal(doc);
    } catch (Exception e) {
        //            Logger.XMLEval.logState("Unmarshalling failed: " + e.getMessage(), LogLevel.Error);
        throw e;
    } finally {
        if (reader != null) {
            reader.close();
            reader = null;
        }
    }

    return unmarshalledObject;
}

From source file:com.aionemu.gameserver.model.TribeRelationCheck.java

@BeforeClass
public static void init() throws Exception {
    File xml = new File("./data/static_data/tribe/tribe_relations.xml");
    Schema schema = null;/*w w w  .  j a v a  2  s .c  o m*/
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    TribeRelationsData tribeRelations = null;
    NpcData npcTemplates = null;

    try {
        schema = sf.newSchema(new File("./data/static_data/tribe/tribe_relations.xsd"));
        JAXBContext jc = JAXBContext.newInstance(TribeRelationsData.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        unmarshaller.setSchema(schema);
        tribeRelations = (TribeRelationsData) unmarshaller.unmarshal(xml);

        xml = new File("./data/static_data/npcs/npc_templates.xml");
        schema = sf.newSchema(new File("./data/static_data/npcs/npcs.xsd"));
        jc = JAXBContext.newInstance(NpcData.class);
        unmarshaller = jc.createUnmarshaller();
        unmarshaller.setSchema(schema);
        npcTemplates = (NpcData) unmarshaller.unmarshal(xml);
    } catch (SAXException e1) {
        System.out.println(e1.getMessage());
    } catch (JAXBException e2) {
        System.out.println(e2.getMessage());
    }

    // Not interesting
    DataManager.NPC_SKILL_DATA = new NpcSkillData();
    DataManager.NPC_DATA = npcTemplates;
    DataManager.TRIBE_RELATIONS_DATA = tribeRelations;
    DataManager.ZONE_DATA = new DummyZoneData();
    DataManager.WORLD_MAPS_DATA = new DummyWorldMapData();

    Config.load();
    // AIConfig.ONCREATE_DEBUG = true;
    AIConfig.EVENT_DEBUG = true;
    ThreadConfig.THREAD_POOL_SIZE = 20;
    ThreadPoolManager.getInstance();

    AI2Engine.getInstance().load(null);

    /**
     * Comment out these lines in DAOManager.registerDAO() if not using DB: <tt> 
     * if (!dao.supports(getDatabaseName(),
     *       getDatabaseMajorVersion(), getDatabaseMinorVersion())) { return; } 
     * </tt>
     */
    DAOManager.init();

    world = World.getInstance();
    asmo = DummyPlayer.createAsmodian();
    asmoPosition = World.getInstance().createPosition(DummyWorldMapData.DEFAULT_MAP, 100f, 100f, 0f, (byte) 0,
            0);

    MapRegion asmoRegion = asmoPosition.getWorldMapInstance().getRegion(100f, 100f, 0);
    asmoRegion.getObjects().put(asmo.getObjectId(), asmo);
    asmoRegion.activate();
    asmo.setPosition(asmoPosition);

    ely = DummyPlayer.createElyo();
    elyPosition = World.getInstance().createPosition(DummyWorldMapData.DEFAULT_MAP, 200f, 200f, 0f, (byte) 0,
            0);
    MapRegion elyRegion = elyPosition.getWorldMapInstance().getRegion(200f, 200f, 0);
    elyRegion.getObjects().put(ely.getObjectId(), ely);
    elyRegion.activate();
    ely.setPosition(elyPosition);

    PacketBroadcaster.getInstance();
    DuelService.getInstance();
    PlayerMoveTaskManager.getInstance();
    MoveTaskManager.getInstance();
}