Example usage for javax.xml.parsers SAXParserFactory setValidating

List of usage examples for javax.xml.parsers SAXParserFactory setValidating

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParserFactory setValidating.

Prototype


public void setValidating(boolean validating) 

Source Link

Document

Specifies that the parser produced by this code will validate documents as they are parsed.

Usage

From source file:org.easyxml.parser.EasySAXParser.java

/**
 * //from w  w  w .  j a v a  2  s  . co  m
 * Parse XML as an InputSource. If external schema is referred, then it
 * would fail to locate the DTD file.
 * 
 * @param is
 *            - InputSource to be parsed.
 * 
 * @return org.easyxml.xml.Document instance if it is parsed successfully,
 *         otherwise null.
 */
public static Document parse(InputSource is) {

    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    try {
        saxParserFactory.setValidating(true);
        saxParserFactory.setFeature("http://apache.org/xml/features/validation/schema", true);
        SAXParser saxParser = saxParserFactory.newSAXParser();
        EasySAXParser handler = new EasySAXParser();
        saxParser.parse(is, handler);
        return handler.getDocument();
    } catch (SAXException | IOException | ParserConfigurationException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:org.eclim.plugin.core.util.XmlUtils.java

/**
 * Validate the supplied xml file./*from   w ww. j  av  a2s .  co  m*/
 *
 * @param project The project name.
 * @param filename The file path to the xml file.
 * @param schema True to use schema validation relying on the
 * xsi:schemaLocation attribute of the document.
 * @param handler The content handler to use while parsing the file.
 * @return A possibly empty list of errors.
 */
public static List<Error> validateXml(String project, String filename, boolean schema, DefaultHandler handler)
        throws Exception {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(true);
    if (schema) {
        factory.setFeature("http://apache.org/xml/features/validation/schema", true);
        factory.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
    }

    SAXParser parser = factory.newSAXParser();

    filename = ProjectUtils.getFilePath(project, filename);
    filename = filename.replace('\\', '/');

    ErrorAggregator errorHandler = new ErrorAggregator(filename);
    EntityResolver entityResolver = new EntityResolver(FileUtils.getFullPath(filename));
    try {
        parser.parse(new File(filename), getHandler(handler, errorHandler, entityResolver));
    } catch (SAXParseException spe) {
        ArrayList<Error> errors = new ArrayList<Error>();
        errors.add(new Error(spe.getMessage(), filename, spe.getLineNumber(), spe.getColumnNumber(), false));
        return errors;
    }

    return errorHandler.getErrors();
}

From source file:org.eclim.plugin.core.util.XmlUtils.java

/**
 * Validate the supplied xml file against the specified xsd.
 *
 * @param project The project name./*from  ww  w .  j av a  2  s. c  o  m*/
 * @param filename The file path to the xml file.
 * @param schema The file path to the xsd.
 * @return A possibly empty array of errors.
 */
public static List<Error> validateXml(String project, String filename, String schema) throws Exception {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(true);
    factory.setFeature("http://apache.org/xml/features/validation/schema", true);
    factory.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);

    SAXParser parser = factory.newSAXParser();
    parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            "http://www.w3.org/2001/XMLSchema");
    if (!schema.startsWith("file:")) {
        schema = "file://" + schema;
    }
    parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", schema);
    parser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
            schema.replace('\\', '/'));

    filename = ProjectUtils.getFilePath(project, filename);
    filename = filename.replace('\\', '/');

    ErrorAggregator errorHandler = new ErrorAggregator(filename);
    EntityResolver entityResolver = new EntityResolver(FileUtils.getFullPath(filename));
    try {
        parser.parse(new File(filename), getHandler(null, errorHandler, entityResolver));
    } catch (SAXParseException spe) {
        ArrayList<Error> errors = new ArrayList<Error>();
        errors.add(new Error(spe.getMessage(), filename, spe.getLineNumber(), spe.getColumnNumber(), false));
        return errors;
    }

    return errorHandler.getErrors();
}

From source file:org.eclipse.emf.teneo.annotations.xml.XmlPersistenceMapper.java

/**
 * Applies the XML persistence mapping to a PAnnotatedModel.
 * /*from  ww w . j  av  a2  s  .c  om*/
 * @throws IllegalStateException
 *             if the XML mapping was not configured.
 * @throws RuntimeException
 *             If there was an error reading or parsing the XML file.
 */
public void applyPersistenceMapping(PAnnotatedModel pAnnotatedModel) {
    if (xmlMapping == null) {
        throw new IllegalStateException("XML mapping not configured.");
    }

    SAXParser saxParser;
    try {
        final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        saxParserFactory.setNamespaceAware(true);
        saxParserFactory.setValidating(true);

        saxParser = saxParserFactory.newSAXParser();
    } catch (ParserConfigurationException e) {
        throw new ParseXMLAnnotationsException(e);
    } catch (SAXException e) {
        throw new ParseXMLAnnotationsException(e);
    }

    try {
        try {
            saxParser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                    "http://www.w3.org/2001/XMLSchema");
            saxParser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource",
                    this.getClass().getResourceAsStream("persistence-mapping.xsd"));
        } catch (SAXNotRecognizedException s) {
            log.warn("Properties schemaSource and/or schemaLanguage are not supported, setvalidating=false. "
                    + "Probably running 1.4 with an old crimson sax parser. Ignoring this and continuing with "
                    + "a non-validating and name-space-aware sax parser");
            final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
            saxParserFactory.setNamespaceAware(true);
            saxParserFactory.setValidating(false);
            saxParser = saxParserFactory.newSAXParser();
        }

        final XmlPersistenceContentHandler xmlContentHandler = extensionManager
                .getExtension(XmlPersistenceContentHandler.class);
        xmlContentHandler.setPAnnotatedModel(pAnnotatedModel);
        xmlContentHandler.setPrefix(getPrefix());
        xmlContentHandler.setSchema(this.getClass().getResourceAsStream("persistence-mapping.xsd"));
        saxParser.parse(xmlMapping, xmlContentHandler);
    } catch (SAXException e) {
        throw new ParseXMLAnnotationsException(e);
    } catch (IOException e) {
        throw new ParseXMLAnnotationsException(e);
    } catch (ParserConfigurationException e) {
        throw new ParseXMLAnnotationsException(e);
    } finally {
        try {
            xmlMapping.close();
        } catch (IOException e) {
            // ignoring io exception
        }
    }
}

From source file:org.eclipse.wst.ws.internal.parser.wsil.WebServicesParser.java

private void parseURL(int parseOption) throws MalformedURLException, IOException, ParserConfigurationException,
        SAXException, WWWAuthenticationException {
    WebServiceEntity wsEntity = new WebServiceEntity();

    // This variable makes this object a little more thread safe than it was
    // before, although this object is not completely thread safe.  The scenario
    // that we are trying to avoid is where one call to this method gets blocked
    // at the getInputStreamAsByteArray call.  Then a second call to the method
    // is made that changes the uri_ global variable.  When the first call
    // completes it would use uri_ value from the second invocation instead
    // of the value from the first.  Storing the uri_ into this variable helps 
    // avoid this bad scenario.
    String theUri = uri_;/* w ww.ja  v a 2s .  co  m*/

    wsEntity.setURI(theUri);
    byte[] b = getInputStreamAsByteArray(theUri);
    wsEntity.setBytes(b);
    setHTTPSettings(wsEntity);
    uriToEntityTable_.put(theUri, wsEntity);
    // parse uri_ as a HTML document
    HTMLHeadHandler headHandler = new HTMLHeadHandler(theUri);
    byte[] head = headHandler.harvestHeadTags(b);
    String byteEncoding = headHandler.getByteEncoding();
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(false);
    factory.setValidating(false);
    SAXParser parser = factory.newSAXParser();
    try {
        ByteArrayInputStream bais = new ByteArrayInputStream(head);
        InputStreamReader isr = new InputStreamReader(bais, byteEncoding);
        InputSource is = new InputSource(isr);
        parser.parse(is, headHandler);
    } catch (Exception t) {
    }
    String[] wsilURIs = headHandler.getWsils();
    String[] discoURIs = headHandler.getDiscos();
    // true if uri_ is a HTML document
    if (wsilURIs.length > 0 || discoURIs.length > 0) {
        wsEntity.setType(WebServiceEntity.TYPE_HTML);
        for (int i = 0; i < wsilURIs.length; i++) {
            String absoluteURI = convertToAbsoluteURI(theUri, wsilURIs[i]);
            WebServiceEntity wsilEntity = new WebServiceEntity();
            wsilEntity.setType(WebServiceEntity.TYPE_WSIL);
            wsilEntity.setURI(absoluteURI);
            associate(wsEntity, wsilEntity);
            uriToEntityTable_.put(absoluteURI, wsilEntity);
            if ((parseOption | PARSE_WSIL) == parseOption) {
                try {
                    parseWSIL(absoluteURI, parseOption, byteEncoding);
                } catch (Exception t) {
                }
            }
        }
        for (int i = 0; i < discoURIs.length; i++) {
            WebServiceEntity discoEntity = new WebServiceEntity();
            discoEntity.setType(WebServiceEntity.TYPE_DISCO);
            discoEntity.setURI(discoURIs[i]);
            associate(wsEntity, discoEntity);
            uriToEntityTable_.put(discoURIs[i], discoEntity);
            if ((parseOption | PARSE_DISCO) == parseOption) {
                try {
                    parseDISCO(discoURIs[i], parseOption);
                } catch (Exception t) {
                }
            }
        }
    }
    // false if uri_ is not a HTML document
    // then parse uri_ as a WSIL document
    else {
        try {
            parseWSIL(theUri, parseOption, byteEncoding);
            // no exception thrown if uri_ is a WSIL document
            wsEntity.setType(WebServiceEntity.TYPE_WSIL);
        } catch (Exception t) {
            // exception thrown if uri_ is not a WSIL document
            // then parse uri_ as a DISCO document.
            try {
                parseDISCO(theUri, parseOption);
                // no exception thrown if uri_ is a DISCO document
                wsEntity.setType(WebServiceEntity.TYPE_DISCO);
            } catch (Exception t2) {
                // exception thrown if uri_ is not a DISCO document
                // then parse uri_ as a WSDL document
                try {
                    parseWSDL(theUri);
                    // no exception thrown if uri_ is a WSDL document
                    wsEntity.setType(WebServiceEntity.TYPE_WSDL);
                } catch (Exception t3) {
                    // exception thrown if uri_ is not a WSDL document
                    // then do nothing
                }
            }
        }
    }
}

From source file:org.exist.util.XMLReaderObjectFactory.java

/**
 * Create Xmlreader and setup validation
 *//* w  w  w  .j  av  a2 s. c o  m*/
public static XMLReader createXmlReader(VALIDATION_SETTING validation, GrammarPool grammarPool,
        eXistXMLCatalogResolver resolver) throws ParserConfigurationException, SAXException {

    // Create a xmlreader
    final SAXParserFactory saxFactory = ExistSAXParserFactory.getSAXParserFactory();

    if (validation == VALIDATION_SETTING.AUTO || validation == VALIDATION_SETTING.ENABLED) {
        saxFactory.setValidating(true);
    } else {
        saxFactory.setValidating(false);
    }
    saxFactory.setNamespaceAware(true);

    final SAXParser saxParser = saxFactory.newSAXParser();
    final XMLReader xmlReader = saxParser.getXMLReader();

    // Setup grammar cache
    if (grammarPool != null) {
        setReaderProperty(xmlReader, APACHE_PROPERTIES_INTERNAL_GRAMMARPOOL, grammarPool);
    }

    // Setup xml catalog resolver
    if (resolver != null) {
        setReaderProperty(xmlReader, APACHE_PROPERTIES_ENTITYRESOLVER, resolver);
    }

    return xmlReader;
}

From source file:org.formix.dsx.XmlElement.java

private static SAXParser createSaxParser()
        throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException, SAXException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(false);//from ww  w.  j a va 2  s.  c  o m

    factory.setValidating(false);
    factory.setFeature("http://xml.org/sax/features/namespaces", false);
    factory.setFeature("http://xml.org/sax/features/validation", false);
    factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

    SAXParser parser = factory.newSAXParser();
    return parser;
}

From source file:org.gcaldaemon.core.sendmail.SendMail.java

private final void sendXML(String email, String content, GmailEntry entry) throws Exception {
    log.debug("Parsing XML file...");
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(false);
    factory.setNamespaceAware(false);/* w w w. j ava  2 s  .c  om*/
    SAXParser parser = factory.newSAXParser();
    InputSource source = new InputSource(new StringReader(content));
    MailParser mailParser = new MailParser(username);
    parser.parse(source, mailParser);

    // Submit mail
    String toList = "";
    String ccList = "";
    String bccList = "";

    Iterator i = mailParser.getTo().iterator();
    while (i.hasNext()) {
        toList += (String) i.next() + ",";
    }
    i = mailParser.getCc().iterator();
    while (i.hasNext()) {
        ccList += (String) i.next() + ",";
    }
    i = mailParser.getBcc().iterator();
    while (i.hasNext()) {
        bccList += (String) i.next() + ",";
    }
    if (toList.length() == 0) {
        toList = username;
    }

    String msg = mailParser.getBody();
    boolean isHTML = msg.indexOf("/>") != -1 || msg.indexOf("</") != -1;
    if (isHTML) {
        msg = cropBody(msg);
    }
    if (isHTML) {
        log.debug("Sending HTML mail...");
    } else {
        log.debug("Sending plain-text mail...");
    }
    entry.send(toList, ccList, bccList, mailParser.getSubject(), msg, isHTML);
    log.debug("Mail submission finished.");
}

From source file:org.infoscoop.request.filter.ical.ICalendarUtil.java

public static Reader convertRdf2Ics(InputStream is) throws SAXException, IOException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(false);
    factory.setNamespaceAware(true);//from   ww  w.j  a  v a  2s  .  c o m
    XMLReader reader = null;
    try {
        reader = factory.newSAXParser().getXMLReader();
        reader.setEntityResolver(NoOpEntityResolver.getInstance());
    } catch (ParserConfigurationException e) {
        log.error("", e);
    }

    Rdf2IcsHandler xmlHandler = new Rdf2IcsHandler();

    reader.setContentHandler(xmlHandler);
    reader.parse(new InputSource(is));
    return new StringReader(xmlHandler.getResult());
}

From source file:org.iterx.miru.bean.factory.XmlBeanParser.java

public void parse(StreamSource source) throws IOException {
    try {//from  w  w w .  j  a va  2  s . c  om
        SAXParserFactory factory;
        SAXParser parser;

        factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(true);

        parser = factory.newSAXParser();
        parser.parse(source.getInputStream(), this);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    } catch (SAXException e) {
        if (LOGGER.isErrorEnabled())
            LOGGER.error(e, e);
        throw new IOException("Invalid xml stream [" + source + "]. " + e.getMessage());
    }
}