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:com.opensymphony.xwork.util.DomHelper.java

/**
 * Creates a W3C Document that remembers the location of each element in
 * the source file. The location of element nodes can then be retrieved
 * using the {@link #getLocationObject(Element)} method.
 *
 * @param inputSource the inputSource to read the document from
 * @param dtdMappings a map of DTD names and public ids
 *//*from ww w.  j  a v  a  2  s. c  om*/
public static Document parse(InputSource inputSource, Map dtdMappings) {
    SAXParserFactory factory = null;
    String parserProp = System.getProperty("xwork.saxParserFactory");
    if (parserProp != null) {
        try {
            Class clazz = ObjectFactory.getObjectFactory().getClassInstance(parserProp);
            factory = (SAXParserFactory) clazz.newInstance();
        } catch (ClassNotFoundException e) {
            LOG.error("Unable to load saxParserFactory set by system property 'xwork.saxParserFactory': "
                    + parserProp, e);
        } catch (Exception e) {
            LOG.error("Unable to load saxParserFactory set by system property 'xwork.saxParserFactory': "
                    + parserProp, e);
        }
    }

    if (factory == null) {
        factory = SAXParserFactory.newInstance();
    }

    factory.setValidating((dtdMappings != null));
    factory.setNamespaceAware(true);

    SAXParser parser = null;
    try {
        parser = factory.newSAXParser();
    } catch (Exception ex) {
        throw new XworkException("Unable to create SAX parser", ex);
    }

    DOMBuilder builder = new DOMBuilder();

    // Enhance the sax stream with location information
    ContentHandler locationHandler = new LocationAttributes.Pipe(builder);

    try {
        parser.parse(inputSource, new StartHandler(locationHandler, dtdMappings));
    } catch (Exception ex) {
        throw new XworkException(ex);
    }

    return builder.getDocument();
}

From source file:ValidateXMLInput.java

void validate() throws Exception {
    // Since we're going to use a SAX feature, the transformer must support 
    // input in the form of a SAXSource.
    TransformerFactory tfactory = TransformerFactory.newInstance();
    if (tfactory.getFeature(SAXSource.FEATURE)) {
        // Standard way of creating an XMLReader in JAXP 1.1.
        SAXParserFactory pfactory = SAXParserFactory.newInstance();
        pfactory.setNamespaceAware(true); // Very important!
        // Turn on validation.
        pfactory.setValidating(true);
        // Get an XMLReader.
        XMLReader reader = pfactory.newSAXParser().getXMLReader();

        // Instantiate an error handler (see the Handler inner class below) that will report any
        // errors or warnings that occur as the XMLReader is parsing the XML input.
        Handler handler = new Handler();
        reader.setErrorHandler(handler);

        // Standard way of creating a transformer from a URL.
        Transformer t = tfactory.newTransformer(new StreamSource("birds.xsl"));

        // Specify a SAXSource that takes both an XMLReader and a URL.
        SAXSource source = new SAXSource(reader, new InputSource("birds.xml"));

        // Transform to a file.
        try {//from w  w w  . j  a  v a2 s.  c  om
            t.transform(source, new StreamResult("birds.out"));
        } catch (TransformerException te) {
            // The TransformerException wraps someting other than a SAXParseException
            // warning or error, either of which should be "caught" by the Handler.
            System.out.println("Not a SAXParseException warning or error: " + te.getMessage());
        }

        System.out.println("=====Done=====");
    } else
        System.out.println("tfactory does not support SAX features!");
}

From source file:com.sparsity.dex.etl.config.impl.XMLConfigurationProvider.java

public void load() throws DexUtilsException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);
    factory.setNamespaceAware(true);// w  ww.ja v a  2s. c om

    try {
        SAXParser parser = factory.newSAXParser();
        DexUtilsHandler handler = new DexUtilsHandler(config);
        parser.parse(xml.getAbsolutePath(), handler);
    } catch (Exception e) {
        String msg = new String("Parsing error.");
        log.error(msg, e);
        throw new DexUtilsException(msg, e);
    }
    log.info("Loaded configuration from " + xml.getAbsolutePath());
}

From source file:Validate.java

void parse(String dir, String filename)
        throws FileNotFoundException, IOException, ParserConfigurationException, SAXException {
    try {// w  w w. ja va 2s  .c  om
        File f = new File(dir, filename);
        StringBuffer errorBuff = new StringBuffer();
        InputSource input = new InputSource(new FileInputStream(f));
        // Set systemID so parser can find the dtd with a relative URL in the source document.
        input.setSystemId(f.toString());
        SAXParserFactory spfact = SAXParserFactory.newInstance();

        spfact.setValidating(true);
        spfact.setNamespaceAware(true);

        SAXParser parser = spfact.newSAXParser();
        XMLReader reader = parser.getXMLReader();

        //Instantiate inner-class error and lexical handler.
        Handler handler = new Handler(filename, errorBuff);
        reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
        parser.parse(input, handler);

        if (handler.containsDTD && !handler.errorOrWarning) // valid
        {
            buff.append("VALID " + filename + "\n");
            numValidFiles++;
        } else if (handler.containsDTD) // not valid
        {
            buff.append("NOT VALID " + filename + "\n");
            buff.append(errorBuff.toString());
            numInvalidFiles++;
        } else // no DOCTYPE to use for validation
        {
            buff.append("NO DOCTYPE DECLARATION " + filename + "\n");
            numFilesMissingDoctype++;
        }
    } catch (Exception e) // Serious problem!
    {
        buff.append("NOT WELL-FORMED " + filename + ". " + e.getMessage() + "\n");
        numMalformedFiles++;
    } finally {
        numXMLFiles++;
    }
}

From source file:eionet.gdem.conversion.excel.ExcelProcessor.java

/**
 * Converts XML string to OutputStream/*from w w  w. j  av a  2  s  .  c  o  m*/
 * @param sIn Input string
 * @param sOut OutputStream
 * @throws GDEMException In case an error occurs.
 */
public void makeExcel(String sIn, OutputStream sOut) throws GDEMException {

    if (sIn == null) {
        return;
    }
    if (sOut == null) {
        return;
    }

    try {
        ExcelConversionHandlerIF excel = ExcelUtils.getExcelConversionHandler();
        //excel.setFileName(sOut);

        ExcelXMLHandler handler = new ExcelXMLHandler(excel);
        SAXParserFactory spfact = SAXParserFactory.newInstance();
        SAXParser parser = spfact.newSAXParser();
        XMLReader reader = parser.getXMLReader();
        spfact.setValidating(true);

        reader.setContentHandler(handler);
        reader.parse(sIn);
        excel.writeToFile(sOut);
    } catch (Exception e) {
        throw new GDEMException("Error generating Excel file: " + e.toString(), e);
    }

    return;
}

From source file:es.mityc.firmaJava.libreria.utilidades.AnalizadorFicheroFirma.java

public void analizar(File fichero) {
    SAXParserFactory factoria = SAXParserFactory.newInstance();
    factoria.setNamespaceAware(true);//  www.  j  a  v a2  s.  com
    factoria.setValidating(false);
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(fichero);
        SAXParser parser = factoria.newSAXParser();
        parser.parse(fis, this);
    } catch (ParserConfigurationException e) {
        log.error(e);
    } catch (SAXException e) {
        log.error(e);
    } catch (FileNotFoundException e) {
        log.error(e);
    } catch (IOException e) {
        log.error(e);
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:no.uis.service.studinfo.commons.StudinfoValidator.java

protected List<String> validate(String studieinfoXml, StudinfoType infoType, int year, FsSemester semester,
        String language) throws Exception {

    // save xml/*from w w  w  . jav a2 s  .  com*/
    File outFile = new File("target/out", infoType.toString() + year + semester + language + ".xml");
    if (outFile.exists()) {
        outFile.delete();
    } else {
        outFile.getParentFile().mkdirs();
    }
    File outBackup = new File("target/out", infoType.toString() + year + semester + language + "_orig.xml");
    Writer backupWriter = new OutputStreamWriter(new FileOutputStream(outBackup), IOUtils.UTF8_CHARSET);
    backupWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    IOUtils.copy(new StringReader(studieinfoXml), backupWriter, IOBUFFER_SIZE);
    backupWriter.flush();
    backupWriter.close();

    TransformerFactory trFactory = TransformerFactory.newInstance();
    Source schemaSource = new StreamSource(getClass().getResourceAsStream("/fspreprocess.xsl"));
    Transformer stylesheet = trFactory.newTransformer(schemaSource);

    Source input = new StreamSource(new StringReader(studieinfoXml));

    Result result = new StreamResult(outFile);
    stylesheet.transform(input, result);

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

    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schema = schemaFactory
            .newSchema(new Source[] { new StreamSource(new File("src/main/xsd/studinfo.xsd")) });

    factory.setSchema(schema);

    SAXParser parser = factory.newSAXParser();

    XMLReader reader = parser.getXMLReader();
    ValidationErrorHandler errorHandler = new ValidationErrorHandler(infoType, year, semester, language);
    reader.setErrorHandler(errorHandler);
    reader.setContentHandler(errorHandler);
    try {
        reader.parse(
                new InputSource(new InputStreamReader(new FileInputStream(outFile), IOUtils.UTF8_CHARSET)));
    } catch (SAXException ex) {
        // do nothing. The error is handled in the error handler
    }
    return errorHandler.getMessages();
}

From source file:net.sourceforge.fenixedu.utilTests.ParseMetadata.java

public Vector<Element> parseMetadata(String metadataFile) throws ParseException {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setValidating(true);
    try {/*from  w ww  .  j a v  a2  s. c  o m*/
        SAXParser saxParser = spf.newSAXParser();
        XMLReader reader = saxParser.getXMLReader();
        reader.setContentHandler(this);
        reader.setErrorHandler(this);
        StringReader sr = new StringReader(metadataFile);
        InputSource input = new InputSource(sr);
        MetadataResolver resolver = new MetadataResolver();
        reader.setEntityResolver(resolver);
        reader.parse(input);
    } catch (Exception e) {
        throw new ParseException();
    }

    setMembers(vector);
    return vector;
}

From source file:ee.ria.xroad.common.message.SaxSoapParserImpl.java

@SneakyThrows
private static SAXParserFactory createSaxParserFactory() {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);/*from  w w  w.j av  a 2 s.co  m*/
    factory.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
    // disable external entity parsing to avoid DOS attacks
    factory.setValidating(false);
    factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
    factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
    factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    return factory;
}

From source file:net.sbbi.upnp.messages.StateVariableMessage.java

/**
 * Executes the state variable query and retuns the UPNP device response, according to the UPNP specs,
 * this method could take up to 30 secs to process ( time allowed for a device to respond to a request )
 * @return a state variable response object containing the variable value
 * @throws IOException if some IOException occurs during message send and reception process
 * @throws UPNPResponseException if an UPNP error message is returned from the server
 *         or if some parsing exception occurs ( detailErrorCode = 899, detailErrorDescription = SAXException message )
 *///from   ww w.  ja va 2 s .c o  m
public StateVariableResponse service() throws IOException, UPNPResponseException {
    StateVariableResponse rtrVal = null;
    UPNPResponseException upnpEx = null;
    IOException ioEx = null;
    StringBuffer body = new StringBuffer(256);

    body.append("<?xml version=\"1.0\"?>\r\n");
    body.append("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"");
    body.append(" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">");
    body.append("<s:Body>");
    body.append("<u:QueryStateVariable xmlns:u=\"urn:schemas-upnp-org:control-1-0\">");
    body.append("<u:varName>").append(serviceStateVar.getName()).append("</u:varName>");
    body.append("</u:QueryStateVariable>");
    body.append("</s:Body>");
    body.append("</s:Envelope>");

    if (log.isDebugEnabled())
        log.debug("POST prepared for URL " + service.getControlURL());
    URL url = new URL(service.getControlURL().toString());
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    HttpURLConnection.setFollowRedirects(false);
    //conn.setConnectTimeout( 30000 );
    conn.setRequestProperty("HOST", url.getHost() + ":" + url.getPort());
    conn.setRequestProperty("SOAPACTION", "\"urn:schemas-upnp-org:control-1-0#QueryStateVariable\"");
    conn.setRequestProperty("CONTENT-TYPE", "text/xml; charset=\"utf-8\"");
    conn.setRequestProperty("CONTENT-LENGTH", Integer.toString(body.length()));
    OutputStream out = conn.getOutputStream();
    out.write(body.toString().getBytes());
    out.flush();
    conn.connect();
    InputStream input = null;

    if (log.isDebugEnabled())
        log.debug("executing query :\n" + body);
    try {
        input = conn.getInputStream();
    } catch (IOException ex) {
        // java can throw an exception if he error code is 500 or 404 or something else than 200
        // but the device sends 500 error message with content that is required
        // this content is accessible with the getErrorStream
        input = conn.getErrorStream();
    }

    if (input != null) {
        int response = conn.getResponseCode();
        String responseBody = getResponseBody(input);
        if (log.isDebugEnabled())
            log.debug("received response :\n" + responseBody);
        SAXParserFactory saxParFact = SAXParserFactory.newInstance();
        saxParFact.setValidating(false);
        saxParFact.setNamespaceAware(true);
        StateVariableResponseParser msgParser = new StateVariableResponseParser(serviceStateVar);
        StringReader stringReader = new StringReader(responseBody);
        InputSource src = new InputSource(stringReader);
        try {
            SAXParser parser = saxParFact.newSAXParser();
            parser.parse(src, msgParser);
        } catch (ParserConfigurationException confEx) {
            // should never happen
            // we throw a runtimeException to notify the env problem
            throw new RuntimeException(
                    "ParserConfigurationException during SAX parser creation, please check your env settings:"
                            + confEx.getMessage());
        } catch (SAXException saxEx) {
            // kind of tricky but better than nothing..
            upnpEx = new UPNPResponseException(899, saxEx.getMessage());
        } finally {
            try {
                input.close();
            } catch (IOException ex) {
                // ignoring
            }
        }
        if (upnpEx == null) {
            if (response == HttpURLConnection.HTTP_OK) {
                rtrVal = msgParser.getStateVariableResponse();
            } else if (response == HttpURLConnection.HTTP_INTERNAL_ERROR) {
                upnpEx = msgParser.getUPNPResponseException();
            } else {
                ioEx = new IOException("Unexpected server HTTP response:" + response);
            }
        }
    }
    try {
        out.close();
    } catch (IOException ex) {
        // ignore
    }
    conn.disconnect();
    if (upnpEx != null) {
        throw upnpEx;
    }
    if (rtrVal == null && ioEx == null) {
        ioEx = new IOException("Unable to receive a response from the UPNP device");
    }
    if (ioEx != null) {
        throw ioEx;
    }
    return rtrVal;
}