Example usage for javax.xml.validation SchemaFactory newInstance

List of usage examples for javax.xml.validation SchemaFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.validation SchemaFactory newInstance.

Prototype

public static SchemaFactory newInstance(String schemaLanguage) 

Source Link

Document

Lookup an implementation of the SchemaFactory that supports the specified schema language and return it.

Usage

From source file:cl.vmetrix.operation.persistence.XmlValidator.java

/**
 * The method validatorXMLstg determinate if the String XML is correct. 
 * @return a boolean (true or false) to indicate if the XML is correct.
 * @param xml is the String XML to validate against XSD Schema
 * @throws SAXException/* w  w  w.  ja  va 2s  .  c  o  m*/
 * @throws IOException
 */

public boolean validateXMLstg(String xml) throws SAXException, IOException {
    String rpta = "";

    boolean validation = true;
    try {

        xml = new String(xml.getBytes("UTF-8"));

        //         System.out.println("---> XML in UTF-8: "+ xml);
        // convert String into InputStream
        InputStream is = new ByteArrayInputStream(xml.getBytes());

        Source xmlFile = new StreamSource(is);//new File("C:/XML/424437.xml"));

        // XSD schema
        String schemea = getFileSchema("operationSchema.xsd");

        InputStream sch = new ByteArrayInputStream(schemea.getBytes());

        Source schemaFile = new StreamSource(sch);//new File("main/resources/Operation.xsd"));

        // Preparing the schema
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(schemaFile);

        // Validator creation
        Validator validator = schema.newValidator();

        // DException handle of validator
        final List<SAXParseException> exceptions = new LinkedList<SAXParseException>();
        validator.setErrorHandler(new ErrorHandler() {
            @Override
            public void warning(SAXParseException exception) throws SAXException {
                exceptions.add(exception);
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                exceptions.add(exception);
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                exceptions.add(exception);
            }
        });

        // XML validation
        validator.validate(xmlFile);

        // Validation result. If there are errors, detailed the exact position in the XML  and the error
        if (exceptions.size() == 0) {
            rpta = "XML IS VALID";
        } else {
            validation = false;
            StringBuffer sb = new StringBuffer();
            sb.append("XML IS INVALID");
            sb.append("\n");
            sb.append("NUMBER OF ERRORS: " + exceptions.size());
            sb.append("\n");
            for (int i = 0; i < exceptions.size(); i++) {
                i = i + 1;
                sb.append("Error # " + i + ":");
                sb.append("\n");
                i = i - 1;
                sb.append("    - Line: " + ((SAXParseException) exceptions.get(i)).getLineNumber());
                sb.append("\n");
                sb.append("    - Column: " + ((SAXParseException) exceptions.get(i)).getColumnNumber());
                sb.append("\n");
                sb.append("    - Error message: " + ((Throwable) exceptions.get(i)).getLocalizedMessage());
                sb.append("\n");
                sb.append("------------------------------");
            }
            rpta = sb.toString();
            logger.debug(rpta);

        }
    } catch (SAXException e) {
        logger.error("SAXException in XML validator: ", e);
        logger.debug(rpta);
        throw new SAXException(e);
    } catch (IOException e) {
        logger.error("IOException in XML validator: ", e);
        logger.debug(rpta);
        throw new IOException(e);
    }

    return validation;
}

From source file:com.springsource.hq.plugin.tcserver.serverconfig.ProfileMarshaller.java

public ProfileMarshaller() throws JAXBException, SAXException, IOException {
    jaxbContext = JAXBContext.newInstance(Profile.class, TomcatDataSource.class, DbcpDataSource.class,
            AjpConnector.class, HttpConnector.class);
    Resource schemaResource = new ClassPathResource("tomcatserverconfig-profile-2.0.xsd", Profile.class);
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    profileSchema = schemaFactory.newSchema(schemaResource.getURL());
}

From source file:be.fedict.eid.dss.model.bean.XmlSchemaManagerBean.java

public void add(String revision, InputStream xsdInputStream)
        throws InvalidXmlSchemaException, ExistingXmlSchemaException {
    byte[] xsd;// w w w  .j  a va2s . c  om
    try {
        xsd = IOUtils.toByteArray(xsdInputStream);
    } catch (IOException e) {
        throw new RuntimeException("IO error: " + e.getMessage(), e);
    }
    ByteArrayInputStream schemaInputStream = new ByteArrayInputStream(xsd);
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    schemaFactory.setResourceResolver(new SignatureServiceLSResourceResolver(this.entityManager));
    StreamSource schemaSource = new StreamSource(schemaInputStream);
    try {
        schemaFactory.newSchema(schemaSource);
    } catch (SAXException e) {
        LOG.error("SAX error: " + e.getMessage(), e);
        throw new InvalidXmlSchemaException("SAX error: " + e.getMessage(), e);
    } catch (RuntimeException e) {
        LOG.error("Runtime exception: " + e.getMessage(), e);
        throw new InvalidXmlSchemaException(e.getMessage(), e);
    }

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder;
    try {
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException("DOM error: " + e.getMessage(), e);
    }
    schemaInputStream = new ByteArrayInputStream(xsd);
    Document schemaDocument;
    try {
        schemaDocument = documentBuilder.parse(schemaInputStream);
    } catch (Exception e) {
        throw new RuntimeException("DOM error: " + e.getMessage(), e);
    }
    String namespace = schemaDocument.getDocumentElement().getAttribute("targetNamespace");
    LOG.debug("namespace: " + namespace);

    XmlSchemaEntity existingXmlSchemaEntity = this.entityManager.find(XmlSchemaEntity.class, namespace);
    if (null != existingXmlSchemaEntity) {
        throw new ExistingXmlSchemaException();
    }

    XmlSchemaEntity xmlSchemaEntity = new XmlSchemaEntity(namespace, revision, xsd);
    this.entityManager.persist(xmlSchemaEntity);
}

From source file:gov.nih.nci.ncicb.cadsr.bulkloader.schema.validator.SchemaValidatorImpl.java

/**
 * /*from   w  w  w.ja v  a 2s .  com*/
 * @return <code>javax.xml.validation.Schema</code>
 * @throws SchemaValidationException
 */
private Schema getSchema() throws SAXException {
    URL xsdURL = getSchemaURL();
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(xsdURL);

    return schema;
}

From source file:com.geewhiz.pacify.managers.EntityManager.java

public EntityManager(File startPath) {
    this.startPath = startPath;

    try {/*from  w w w .j  a v  a2  s. c  o m*/
        jaxbContext = JAXBContext.newInstance(ObjectFactory.class);

        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        schema = factory.newSchema(
                new StreamSource(EntityManager.class.getClassLoader().getResourceAsStream("pacify.xsd")));
    } catch (Exception e) {
        throw new RuntimeException("Couldn't instanciate jaxb.", e);
    }
}

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;/*from  www.  j a v a  2s.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();
}

From source file:eu.scape_project.tool.toolwrapper.data.tool_spec.utils.Utils.java

private static void setSchemaTo(Unmarshaller unmarshaller) throws IOException, SAXException {
    // copy XML Schema from resources to a temporary location
    File schemaFile = File.createTempFile("schema", null);
    FileUtils.copyInputStreamToFile(Utils.class.getResourceAsStream(TOOLSPEC_FILENAME_IN_RESOURCES),
            schemaFile);// www . j av a  2 s .c  o m
    Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaFile);

    // validate provided toolspec against XML Schema
    unmarshaller.setSchema(schema);
}

From source file:energy.usef.core.util.XMLUtil.java

/**
 * Converts xml to an object after optional validation against the xsd.
 *
 * @param xml xml string/*w  w w  .  ja va  2 s . com*/
 * @param validate true when the xml needs to be validated
 * @return object corresponding to this xml
 */
public static Object xmlToMessage(String xml, boolean validate) {
    try (InputStream is = IOUtils.toInputStream(xml, UTF_8)) {
        Unmarshaller unmarshaller = CONTEXT.createUnmarshaller();

        if (validate) {
            // setup xsd validation
            SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = sf.newSchema(XMLUtil.class.getClassLoader().getResource(MESSAGING_XSD_FILE));

            unmarshaller.setSchema(schema);
        }

        return unmarshaller.unmarshal(is);
    } catch (JAXBException | IOException e) {
        LOGGER.error(e.getMessage(), e);
        throw new TechnicalException("Invalid XML content: " + e.getMessage(), e);
    } catch (SAXException e) {
        LOGGER.error(e.getMessage(), e);
        throw new TechnicalException("Unable to read XSD schema", e);
    }
}

From source file:com.smartitengineering.cms.spi.impl.type.validator.XMLSchemaBasedTypeValidator.java

protected boolean isValid(Document document) throws Exception {
    // create a SchemaFactory capable of understanding WXS schemas
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final InputStream xsdStream = getClass().getClassLoader().getResourceAsStream(XSD_LOCATION);
    // load a WXS schema, represented by a Schema instance
    Source schemaFile = new StreamSource(xsdStream);
    schemaFile.setSystemId(CONTENT_TYPE_SCHEMA_URI);
    Schema schema = factory.newSchema(schemaFile);
    // create a Validator instance, which can be used to validate an instance document
    Validator validator = schema.newValidator();
    // validate the DOM tree
    try {/*from w w  w  .  j a v a  2s  .c  o  m*/
        validator.validate(new DOMSource(document));
        return true;
    } catch (SAXException e) {
        e.printStackTrace();
        return false;
    }
}