Example usage for javax.xml XMLConstants W3C_XML_SCHEMA_NS_URI

List of usage examples for javax.xml XMLConstants W3C_XML_SCHEMA_NS_URI

Introduction

In this page you can find the example usage for javax.xml XMLConstants W3C_XML_SCHEMA_NS_URI.

Prototype

String W3C_XML_SCHEMA_NS_URI

To view the source code for javax.xml XMLConstants W3C_XML_SCHEMA_NS_URI.

Click Source Link

Document

W3C XML Schema Namespace URI.

Usage

From source file:no.met.jtimeseries.service.TimeSeriesService.java

private Schema getLocationForecastSchema() throws SAXException {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL locationForecastSchemaUrl = getLocationForecastSchemaUrl();
    Schema schema = sf.newSchema(locationForecastSchemaUrl);
    return schema;

}

From source file:cz.cas.lib.proarc.common.export.mets.MetsUtils.java

/**
 *
 * Validates given XML file against an XSD schema
 *
 * @param file/*  w ww .j a  v a 2  s .  c  om*/
 * @param xsd
 * @return
 */
public static List<String> validateAgainstXSD(File file, InputStream xsd) throws Exception {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    factory.setResourceResolver(MetsLSResolver.getInstance());
    Schema schema = factory.newSchema(new StreamSource(xsd));
    DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
    dbfactory.setValidating(false);
    dbfactory.setNamespaceAware(true);
    dbfactory.setSchema(schema);
    DocumentBuilder documentBuilder = dbfactory.newDocumentBuilder();
    ValidationErrorHandler errorHandler = new ValidationErrorHandler();
    documentBuilder.setErrorHandler(errorHandler);
    documentBuilder.parse(file);
    return errorHandler.getValidationErrors();
}

From source file:hydrograph.ui.propertywindow.widgets.customwidgets.schema.ELTSchemaGridWidget.java

private boolean validateXML(InputStream xml, InputStream xsd) {
    try {/*from  w ww  . ja  v a 2 s .c o  m*/
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        javax.xml.validation.Schema schema = factory.newSchema(new StreamSource(xsd));
        Validator validator = schema.newValidator();

        validator.validate(new StreamSource(xml));
        return true;
    } catch (SAXException | IOException ex) {
        //MessageDialog.openError(Display.getCurrent().getActiveShell(), "Error", Messages.IMPORT_XML_FORMAT_ERROR + "-\n" + ex.getMessage());
        MessageBox dialog = new MessageBox(Display.getCurrent().getActiveShell(), SWT.ICON_ERROR | SWT.OK);
        dialog.setText(Messages.ERROR);
        dialog.setMessage(Messages.IMPORT_XML_FORMAT_ERROR + "-\n" + ex.getMessage());
        logger.error(Messages.IMPORT_XML_FORMAT_ERROR);
        return false;
    }
}

From source file:org.castor.jaxb.CastorMarshallerTest.java

/**
 * Loads the schema for the {@link Entity} class.
 *
 * @param schemaFile the path to the schema file
 *
 * @return the loaded schema/*from  w w  w . j a va 2  s .  c om*/
 *
 * @throws SAXException if any error occurs during loading the schema
 */
private Schema loadSchema(String schemaFile) throws SAXException {

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

    return schemaFactory.newSchema(getClass().getResource(schemaFile));
}

From source file:com.evolveum.midpoint.prism.schema.DomToSchemaProcessor.java

/**
 * Create PropertyContainer (and possibly also Property) definition from the top-level elements in XSD.
 * Each top-level element will be interpreted as a potential PropertyContainer. The element name will be set as
 * name of the PropertyContainer, element type will become type (indirectly through ComplexTypeDefinition).
 * /*  ww  w.jav  a2 s .co  m*/
 * No need to recurse here. All the work was already done while creating ComplexTypeDefinitions.
 * 
 * @param set XS Schema Set
 * @throws SchemaException
 */
private void createDefinitionsFromElements(XSSchemaSet set) throws SchemaException {
    Iterator<XSElementDecl> iterator = set.iterateElementDecls();
    while (iterator.hasNext()) {
        XSElementDecl xsElementDecl = iterator.next();
        if (isDeprecated(xsElementDecl)) {
            // Safe to ignore. We want it in the XSD schema only. The real definition will be
            // parsed from the non-deprecated variant
        }

        if (xsElementDecl.getTargetNamespace().equals(schema.getNamespace())) {

            QName elementName = new QName(xsElementDecl.getTargetNamespace(), xsElementDecl.getName());
            XSType xsType = xsElementDecl.getType();
            if (xsType == null) {
                throw new SchemaException("Found element " + elementName + " without type definition");
            }
            QName typeQName = determineType(xsElementDecl);
            if (typeQName == null) {
                // No type defined, safe to skip
                continue;
                //throw new SchemaException("Found element "+elementName+" with incomplete type name: {"+xsType.getTargetNamespace()+"}"+xsType.getName());
            }
            XSAnnotation annotation = xsElementDecl.getAnnotation();

            if (isPropertyContainer(xsElementDecl) || isObjectDefinition(xsType)) {

                ComplexTypeDefinition complexTypeDefinition = schema.findComplexTypeDefinition(typeQName);
                PrismContainerDefinition<?> propertyContainerDefinition = createPropertyContainerDefinition(
                        xsType, xsElementDecl, complexTypeDefinition, annotation, null, true);
                schema.getDefinitions().add(propertyContainerDefinition);

            } else if (isObjectReference(xsElementDecl, xsType)) {

                PrismReferenceDefinition refDef = processObjectReferenceDefinition(xsType, elementName,
                        annotation, null, null, false);

                schema.getDefinitions().add(refDef);

            } else {

                // Create a top-level property definition (even if this is a XSD complex type)
                PrismPropertyDefinition propDef = createPropertyDefinition(xsType, elementName, typeQName, null,
                        xsElementDecl.getAnnotation(), null);
                schema.getDefinitions().add(propDef);
            }

        } else if (xsElementDecl.getTargetNamespace().equals(XMLConstants.W3C_XML_SCHEMA_NS_URI)) {
            // This is OK to ignore. These are imported elements from other schemas
            //            } else {
            //               throw new SchemaException("Found element "+xsElementDecl.getName()+" with wrong namespace "+xsElementDecl.getTargetNamespace()+" while expecting "+schema.getNamespace());
        }
    }
}

From source file:edu.stanford.epad.common.util.EPADFileUtils.java

public static String validateXml(File f, String xsdSchema) throws Exception {
    try {/* ww  w  .j av a  2  s .c o m*/
        FileInputStream xml = new FileInputStream(f);
        InputStream xsd = null;
        try {
            xsd = new FileInputStream(xsdSchema);
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = factory.newSchema(new StreamSource(xsd));
            Validator validator = schema.newValidator();
            validator.validate(new StreamSource(xml));
            return "";
        } catch (SAXException ex) {
            log.info("Error: validating template/annotation " + ex.getMessage());
            return ex.getMessage();
        } catch (IOException e) {
            log.info("Error: validating template/annotation " + e.getMessage());
            throw e;
        }
    } catch (IOException e) {
        log.info("Exception validating a file: " + f.getName());
        throw e;
    }
}

From source file:eu.europa.ec.fisheries.uvms.rules.service.bean.RulesMessageServiceBean.java

private Schema getSchemaForXsd(String xsdLocation) throws SAXException {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL resource = getClass().getClassLoader().getResource(xsdLocation);
    return sf.newSchema(resource);
}

From source file:edu.stanford.epad.common.util.EPADFileUtils.java

public static boolean isValidXmlUsingClassPathSchema(File f, String xsdSchema) {
    try {//  ww  w .  j ava  2s. c  o  m
        log.debug("xml:" + f.getName() + " xsd:" + xsdSchema);
        FileInputStream xml = new FileInputStream(f);
        InputStream xsd = null;
        try {
            xsd = EPADFileUtils.class.getClassLoader().getResourceAsStream(xsdSchema);
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = factory.newSchema(new StreamSource(xsd));
            Validator validator = schema.newValidator();
            validator.validate(new StreamSource(xml));
            return true;
        } catch (SAXException ex) {
            log.info("Error: validating template/annotation " + ex.getMessage());
        } catch (IOException e) {
            log.info("Error: validating template/annotation " + e.getMessage());
        }
    } catch (IOException e) {
        log.info("Exception validating a file: " + f.getName());
    }
    return false;
}

From source file:integration.AbstractTest.java

/**
 * Parses the specified file and returns the document.
 * //from   w  ww.  ja va  2s.  c  o  m
 * @param file The file to parse.
 * @param schemaStreamArray The schema as array of stream sources used to validate the specified file.
 * @return
 * @throws Exception Thrown if an error occurred.
 */
protected Document parseFileWithStreamArray(File file, StreamSource[] schemaStreamArray) throws Exception {
    if (file == null)
        throw new IllegalArgumentException("No file to parse.");

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true); // This must be set to avoid error : cvc-elt.1: Cannot find the declaration of element 'OME'.
    SchemaFactory sFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    SchemaResolver theTestClassResolver = new SchemaResolver();
    sFactory.setResourceResolver(theTestClassResolver);

    Schema theSchema = sFactory.newSchema(schemaStreamArray);

    /*
    // Version - one step parse and validate (print error to stdErr)
    dbf.setSchema(theSchema);
    DocumentBuilder builder = dbf.newDocumentBuilder();
    Document theDoc = builder.parse(file);
    */

    // Version - two step parse then validate (throws error as exception)
    DocumentBuilder builder = dbf.newDocumentBuilder();
    Document theDoc = builder.parse(file);
    Validator validator = theSchema.newValidator();
    validator.validate(new DOMSource(theDoc));
    return theDoc;
}

From source file:com.maxl.java.aips2xml.Aips2Xml.java

static List<MedicalInformations.MedicalInformation> readAipsFile() {
    List<MedicalInformations.MedicalInformation> med_list = null;
    try {//ww  w . j  a v a 2s  .  com
        JAXBContext context = JAXBContext.newInstance(MedicalInformations.class);

        // Validation
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(new File(FILE_MEDICAL_INFOS_XSD));
        Validator validator = schema.newValidator();
        validator.setErrorHandler(new MyErrorHandler());

        // Marshaller
        /*
        Marshaller ma = context.createMarshaller();
        ma.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        MedicalInformations medi_infos = new MedicalInformations();
        ma.marshal(medi_infos, System.out);
        */
        // Unmarshaller   
        long startTime = System.currentTimeMillis();
        if (SHOW_LOGS)
            System.out.print("- Unmarshalling Swissmedic xml ... ");

        FileInputStream fis = new FileInputStream(new File(FILE_MEDICAL_INFOS_XML));
        Unmarshaller um = context.createUnmarshaller();
        MedicalInformations med_infos = (MedicalInformations) um.unmarshal(fis);
        med_list = med_infos.getMedicalInformation();

        long stopTime = System.currentTimeMillis();
        if (SHOW_LOGS)
            System.out.println(med_list.size() + " medis in " + (stopTime - startTime) / 1000.0f + " sec");
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JAXBException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }

    return med_list;
}