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:org.modeldriven.fuml.bind.ValidatingUnmarshaler.java

/**
 * Creates an unmarshaler using the given factories and URL. Loads only the
 * given (subclass) schema as this is the "root" schema and it should
 * include any other schema resources it needs, and so on. Note all included
 * schemas MUST be found at the same class level as the root schema.
 * //w  w  w .  j av  a2 s.c om
 * @param url
 *            the Schema URL
 * @param context
 *            the SAXB context
 * @param handler
 *            the SAX handler
 * @param resolver
 *            the SAX resolver
 * @return the unmarshaler
 * @throws JAXBException
 * @throws SAXException
 */
private Unmarshaller createUnmarshaler(URL url, JAXBContext context, Handler handler, Resolver resolver)
        throws JAXBException, SAXException {
    Unmarshaller u = context.createUnmarshaller();
    // adds a custom object factory
    // u.setProperty("com.sun.xml.bind.ObjectFactory",new
    // ObjectFactoryEx());
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schemaGrammar = schemaFactory.newSchema(url);
    u.setSchema(schemaGrammar);
    Validator schemaValidator = schemaGrammar.newValidator();
    schemaValidator.setResourceResolver(resolver);
    schemaValidator.setErrorHandler(handler);

    return u;
}

From source file:org.modeldriven.fuml.bind.ValidatingUnmarshaler.java

private Unmarshaller createUnmarshaler(URL url, JAXBContext context) throws JAXBException, SAXException {
    Unmarshaller u = context.createUnmarshaller();
    // adds a custom object factory
    // u.setProperty("com.sun.xml.bind.ObjectFactory",new
    // ObjectFactoryEx());
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schemaGrammar = schemaFactory.newSchema(url);
    u.setSchema(schemaGrammar);/*w  ww. ja  va  2s .co  m*/

    return u;
}

From source file:org.modeldriven.fuml.bind.ValidatingUnmarshaler.java

/**
 * Creates an unmarshaler using the given factories and sream. Loads only
 * the given (subclass) schema as this is the "root" schema and it should
 * include any other schema resources it needs, and so on. Note all included
 * schemas MUST be found at the same class level as the root schema.
 * /*  w w  w .  j  a va2 s  .c o  m*/
 * @param stream
 *            the Schema stream
 * @param context
 *            the SAXB context
 * @param handler
 *            the SAX handler
 * @param resolver
 *            the SAX resolver
 * @return the unmarshaler
 * @throws JAXBException
 * @throws SAXException
 */
private Unmarshaller createUnmarshaler(InputStream stream, JAXBContext context, Handler handler,
        Resolver resolver) throws JAXBException, SAXException {
    Unmarshaller u = context.createUnmarshaller();
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schemaGrammar = schemaFactory.newSchema(new StreamSource(stream));
    u.setSchema(schemaGrammar);
    Validator schemaValidator = schemaGrammar.newValidator();
    schemaValidator.setResourceResolver(resolver);
    schemaValidator.setErrorHandler(handler);

    return u;
}

From source file:org.modeldriven.fuml.bind.ValidatingUnmarshaler.java

private Unmarshaller createUnmarshaler(InputStream stream, JAXBContext context)
        throws JAXBException, SAXException {
    Unmarshaller u = context.createUnmarshaller();
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schemaGrammar = schemaFactory.newSchema(new StreamSource(stream));
    u.setSchema(schemaGrammar);/*from  ww w.  ja  v  a2  s  . c  o m*/

    return u;
}

From source file:org.mule.config.spring.AbstractSchemaValidationTestCase.java

protected void doTest(String config) throws SAXException, IOException {
    try {//from  www  .ja  v  a  2 s .co  m
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        schemaFactory.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
        Schema schema = schemaFactory.newSchema(getSchemasAsSources());
        schema.newValidator().validate(load(config));
    } catch (SAXParseException ex) {
        System.err.println(MessageFormat.format("SAX parsing exception occurs at line {0}, column {1}",
                ex.getLineNumber(), ex.getColumnNumber()));
        throw ex;
    }
}

From source file:org.mule.module.xml.filters.SchemaValidationFilter.java

public void initialise() throws InitialisationException {
    super.initialise();

    if (getSchemaObject() == null) {
        if (schemaLocations == null) {
            throw new InitialisationException(CoreMessages.objectIsNull("schemaLocations"), this);
        }/*www  .ja  va2  s. c  o m*/

        String[] split = StringUtils.splitAndTrim(schemaLocations, ",");
        Source[] schemas = new Source[split.length];
        for (int i = 0; i < split.length; i++) {
            String loc = split[i];
            InputStream schemaStream;
            try {
                schemaStream = loadSchemaStream(loc);
            } catch (IOException e) {
                throw new InitialisationException(e, this);
            }

            if (schemaStream == null) {
                throw new InitialisationException(CoreMessages.failedToLoad(loc), this);
            }

            schemas[i] = new StreamSource(schemaStream);
        }

        SchemaFactory schemaFactory = SchemaFactory.newInstance(getSchemaLanguage());

        if (logger.isInfoEnabled()) {
            logger.info("Schema factory implementation: " + schemaFactory);
        }

        if (this.errorHandler != null) {
            schemaFactory.setErrorHandler(this.errorHandler);
        }

        if (this.resourceResolver != null) {
            schemaFactory.setResourceResolver(this.resourceResolver);
        }

        Schema schema;
        try {
            schema = schemaFactory.newSchema(schemas);
        } catch (SAXException e) {
            throw new InitialisationException(e, this);
        }

        setSchemaObject(schema);
    }

    if (getSchemaObject() == null) {
        throw new InitialisationException(CoreMessages.objectIsNull("schemaObject"), this);
    }
}

From source file:org.multicore_association.measure.mem.generate.MemCodeGen.java

/**
 * Get the data which need to make CSource from SHIM file.
 * @return Flag for success judgements/*from w  ww  .j  ava 2  s .  c o m*/
 */
private boolean getDataFromShim() {
    boolean ch = true;

    try {
        JAXBContext context = JAXBContext.newInstance(PACKAGENAME);
        Unmarshaller unmarshaller = context.createUnmarshaller();

        /* validation check setup */
        if (!shimSchemaPath.equals("")) {
            SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = sf.newSchema(new File(shimSchemaPath));
            unmarshaller.setSchema(schema);
            unmarshaller.setEventHandler(new ValidationEventHandler() {
                @Override
                public boolean handleEvent(ValidationEvent event) {
                    if ((event.getSeverity() == ValidationEvent.FATAL_ERROR)
                            || (event.getSeverity() == ValidationEvent.ERROR)) {
                        ValidationEventLocator loc = event.getLocator();
                        parseErrList.add("    Line[" + loc.getLineNumber() + "] : " + event.getMessage());
                    }
                    return true;
                }
            });
        }

        sysConf = unmarshaller.unmarshal(new StreamSource(shimf), SystemConfiguration.class).getValue();

        if (parseErrList.size() > 0) {
            System.err.println("Error: input SHIM file validation error");

            System.err.println("    Validation error location:");
            for (int i = 0; i < parseErrList.size(); i++) {
                System.err.println(parseErrList.get(i));
            }
            return false;
        }

        //         JAXBElement<SystemConfiguration> root = unmarshaller.unmarshal(new StreamSource(shimf), SystemConfiguration.class);
        //         sysConf = root.getValue();
    } catch (Exception e) {
        System.err.println("Error: failed to parse the SHIM file, please check the contents of the file");
        return false;
    }

    ch = makeCPUListFromShim();
    if (!ch) {
        return ch;
    }
    ch = makeSlaveListFromShim();
    if (!ch) {
        return ch;
    }

    ch = makeAddressSpaceListFromShim();
    if (!ch) {
        return ch;
    }

    ch = makeAccessPatternListFromShim();
    if (!ch) {
        return ch;
    }

    return ch;
}

From source file:org.multicore_association.measure.mem.writeback.SetResultToShim.java

/**
 * Set the value to read the existing SHIM file.
 * @return Flag for success judgements//from  w ww .  ja  v  a  2s  .  c o  m
 * @throws ShimFileFormatException
 * @throws ShimFileGenerateException
 */
private static boolean appendToExistingShim() {
    /*
     * append to existing llvm-shim
     */
    SystemConfiguration sysConf = null;

    try {
        JAXBContext context = JAXBContext.newInstance(SystemConfiguration.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();

        /* validation check setup */
        if (!shimSchemaPath.equals("")) {
            SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = sf.newSchema(new File(shimSchemaPath));
            unmarshaller.setSchema(schema);
            unmarshaller.setEventHandler(new ValidationEventHandler() {
                @Override
                public boolean handleEvent(ValidationEvent event) {
                    if ((event.getSeverity() == ValidationEvent.FATAL_ERROR)
                            || (event.getSeverity() == ValidationEvent.ERROR)) {
                        ValidationEventLocator loc = event.getLocator();
                        parseErrList.add("    Line[" + loc.getLineNumber() + "] : " + event.getMessage());
                    }
                    return true;
                }
            });
        }

        sysConf = unmarshaller.unmarshal(new StreamSource(shimf), SystemConfiguration.class).getValue();

        if (parseErrList.size() > 0) {
            System.err.println("Error: input SHIM file validation error");

            System.err.println("    Validation error location:");
            for (int i = 0; i < parseErrList.size(); i++) {
                System.err.println(parseErrList.get(i));
            }
            return false;
        }
    } catch (Exception e) {
        System.err.println("Error: failed to parse the SHIM file, please check the contents of the file");
        e.printStackTrace();
        return false;
    }

    AddressSpaceSet addrSpaceSet = sysConf.getAddressSpaceSet();
    if (addrSpaceSet == null) {
        System.err.println("Error: failed to parse the SHIM file, please check the contents of the file");
        return false;
    }

    List<AddressSpace> addrSpaceList = addrSpaceSet.getAddressSpace();
    if (addrSpaceList == null) {
        System.err.println("Error: failed to parse the SHIM file, please check the contents of the file");
        return false;
    }

    masterComponentMap = new HashMap<String, MasterComponent>();
    slaveComponentMap = new HashMap<String, SlaveComponent>();
    accessTypeMap = new HashMap<String, AccessType>();

    List<String> route = new ArrayList<String>();
    ComponentSet cs = sysConf.getComponentSet();
    route.add(cs.getName());

    makeRefMapFromComponentSet(cs, route);

    for (int i = 0; i < measureList.size(); i++) {
        MeasurementsCSVData data = measureList.get(i);

        route.clear();

        /*
         * search AddressSpaceName
         */
        AddressSpace addrSp = null;
        for (Iterator<AddressSpace> j = addrSpaceList.iterator(); j.hasNext();) {
            AddressSpace as = j.next();

            if (as.getName() != null && as.getName().equals(data.getAddressSpaceName())) {
                addrSp = as;
                break;
            }
        }
        if (addrSp == null) {
            System.err.println("Error: Unknown 'Address Space' name (\"" + data.getAddressSpaceName() + "\").");
            return false;
        }

        route.add(addrSp.getName());

        /*
         * search SubSpaceName
         */
        SubSpace subSp = null;
        List<SubSpace> ssList = addrSp.getSubSpace();
        for (Iterator<SubSpace> j = ssList.iterator(); j.hasNext();) {
            SubSpace ss = j.next();

            route.add(ss.getName());
            String path = createPathName(route);
            route.remove(ss.getName());
            if (path != null && path.equals(data.getSubSpaceName())) {
                subSp = ss;
                break;
            }

        }
        if (subSp == null) {
            System.err.println("Error: Unknown 'Sub Space' name (\"" + data.getSubSpaceName() + "\").");
            return false;
        }

        /*
         * search SlaveComponentRef in MasterSlaveBinding
         */
        MasterSlaveBindingSet msBindSet = null;
        msBindSet = subSp.getMasterSlaveBindingSet();
        if (msBindSet == null) {
            continue;
        }

        MasterSlaveBinding msBind = null;
        List<MasterSlaveBinding> msBindList = msBindSet.getMasterSlaveBinding();
        SlaveComponent scComp = slaveComponentMap.get(data.getSlaveComponentName());
        if (scComp == null) {
            System.err.println(
                    "Error: Unknown 'Slave Comonent' name (\"" + data.getSlaveComponentName() + "\").");
            return false;
        }
        for (Iterator<MasterSlaveBinding> j = msBindList.iterator(); j.hasNext();) {
            MasterSlaveBinding msb = j.next();
            SlaveComponent sca = (SlaveComponent) msb.getSlaveComponentRef();

            if (sca != null && sca.getId().equals(scComp.getId())) {
                msBind = msb;
                break;
            }
        }
        if (msBind == null) {
            continue;
        }

        /*
         * search MasterComponentRef in Accessor
         */
        Accessor accessor = null;
        List<Accessor> acList = msBind.getAccessor();
        MasterComponent mcComp = masterComponentMap.get(data.getMasterComponentName());
        if (mcComp == null) {
            System.err.println(
                    "Error: Unknown 'Master Comonent' name (\"" + data.getMasterComponentName() + "\").");
            return false;
        }
        for (Iterator<Accessor> j = acList.iterator(); j.hasNext();) {
            Accessor ac = j.next();
            MasterComponent mc = (MasterComponent) ac.getMasterComponentRef();

            if (mc != null && mc.getId().equals(mcComp.getId())) {
                accessor = ac;
                break;
            }
        }
        if (accessor == null) {
            continue;
        }

        /*
         * search PerformanceSet
         */
        PerformanceSet perfrmSet = null;

        if (accessor.getPerformanceSet().size() != 0) {
            perfrmSet = accessor.getPerformanceSet().get(0);
        }
        if (perfrmSet == null) {
            continue;
        }

        /*
         * search Performance
         */
        List<Performance> pfrmList = perfrmSet.getPerformance();
        AccessType atComp = accessTypeMap.get(data.getAccessTypeName());
        if (atComp == null) {
            System.err.println("Error: Unknown 'Access Type' name (\"" + data.getAccessTypeName() + "\").");
            return false;
        }
        for (Iterator<Performance> j = pfrmList.iterator(); j.hasNext();) {
            Performance pfm = j.next();
            AccessType at = (AccessType) pfm.getAccessTypeRef();

            if (at != null && at.getId().equals(atComp.getId())) {
                Latency latency = new Latency();
                Pitch pitch = new Pitch();

                latency.setBest(data.getBestLatency());
                latency.setWorst(data.getWorstLatency());
                latency.setTypical(data.getTypicalLatency());
                pitch.setBest(data.getBestPitch());
                pitch.setWorst(data.getWorstPitch());
                pitch.setTypical(data.getTypicalPitch());

                pfm.setLatency(latency);
                pfm.setPitch(pitch);
                break;
            }
        }
    }

    try {
        JAXBContext context = JAXBContext.newInstance(SystemConfiguration.class.getPackage().getName());

        Marshaller marshaller = context.createMarshaller();
        /* validation check setup */
        if (!shimSchemaPath.equals("")) {
            SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = sf.newSchema(new File(shimSchemaPath));
            marshaller.setSchema(schema);
        }
        QName qname = new QName("", "SystemConfiguration");

        JAXBElement<SystemConfiguration> elem = new JAXBElement<SystemConfiguration>(qname,
                SystemConfiguration.class, sysConf);

        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        //         marshaller.marshal(elem, new PrintStream(shimf));
        marshaller.marshal(elem, System.out);
    } catch (JAXBException e) {
        e.printStackTrace();
        System.err.println("Error: exception occurs in SHIM file generation"); //$NON-NLS-1$
        return false;
    } catch (SAXException e) {
        e.printStackTrace();
        System.err.println("Error: output SHIM file validation error"); //$NON-NLS-1$
        return false;
    }

    return true;
}

From source file:org.n52.ifgicopter.spf.xml.XMLTools.java

/**
 * @param f the xml file// w ww . ja  v  a  2  s.c o  m
 * @return the parsed {@link Document}
 */
public static Document parseDocument(File f) {
    DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = null;
    try {
        builder = fac.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        log.warn(null, e);
        return null;
    }

    //get the config as Document
    Document doc = null;
    try {
        doc = builder.parse(f);
    } catch (SAXException e) {
        log.warn(null, e);
        return null;
    } catch (IOException e) {
        log.warn(null, e);
        return null;
    }

    /*
     * do we validate?
     */
    if (!Boolean.parseBoolean(SPFRegistry.getInstance().getConfigProperty(SPFRegistry.VALIDATE_XML_PROP))) {
        return doc;
    }

    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

    Schema schema = null;
    try {
        schema = factory.newSchema();
    } catch (SAXException e) {
        log.warn(null, e);
        return null;
    }

    Validator val = schema.newValidator();
    val.setErrorHandler(new ErrorHandler() {
        @Override
        public void warning(SAXParseException exception) throws SAXException {
            log.warn(null, exception);
        }

        @Override
        public void fatalError(SAXParseException exception) throws SAXException {
            log.warn(null, exception);
        }

        @Override
        public void error(SAXParseException exception) throws SAXException {
            warning(exception);
        }
    });

    /*
     * do the validation
     */
    try {
        val.validate(new SAXSource(new InputSource(new FileInputStream(f))));
    } catch (FileNotFoundException e) {
        log.warn(null, e);
        return null;
    } catch (SAXException e) {
        log.warn(null, e);
        return null;
    } catch (IOException e) {
        log.warn(null, e);
        return null;
    }

    return doc;
}

From source file:org.ojbc.util.xml.XmlUtils.java

public static Document validateInstance(String rootXsdPath, Document docXmlToValidate,
        IEPDFullPathResourceResolver fullPathResolver, List<String> additionalSchemaRelativePaths)
        throws Exception {

    List<String> schemaPaths = new ArrayList<String>();
    schemaPaths.add(rootXsdPath);/*www . ja v  a2 s .  co m*/
    schemaPaths.addAll(additionalSchemaRelativePaths);

    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setResourceResolver(fullPathResolver);

    Source[] sources = new Source[schemaPaths.size()];
    int i = 0;
    for (String path : schemaPaths) {
        sources[i++] = new StreamSource(XmlUtils.class.getClassLoader().getResourceAsStream(path));
    }

    Schema schema = schemaFactory.newSchema(sources);

    Validator v = schema.newValidator();

    try {
        v.validate(new DOMSource(docXmlToValidate));

    } catch (Exception e) {
        try {
            e.printStackTrace();
            System.err.println("FAILED Input Doc: \n");
            XmlUtils.printNode(docXmlToValidate);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        throw e;
    }
    return docXmlToValidate;
}