Example usage for javax.xml.parsers SAXParserFactory setNamespaceAware

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

Introduction

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

Prototype


public void setNamespaceAware(boolean awareness) 

Source Link

Document

Specifies that the parser produced by this code will provide support for XML namespaces.

Usage

From source file:kmlvalidator.KmlValidatorServlet.java

/**
 * Handles POST requests for the servlet.
 */// ww w  .  j ava 2 s.co m
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // Our response is always JSON.
    response.setContentType("application/json");

    // Create the JSON response objects to be filled in later.
    JSONObject responseObj = new JSONObject();
    JSONArray responseErrors = new JSONArray();

    try {
        // Load XSD files here. Note that the Java runtime should be caching
        // these files.
        Object[] schemas = {
                new URL("http://schemas.opengis.net/kml/2.2.0/atom-author-link.xsd").openConnection()
                        .getInputStream(),
                new URL("http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd").openConnection().getInputStream(),
                new URL("http://code.google.com/apis/kml/schema/kml22gx.xsd").openConnection()
                        .getInputStream() };

        // Create a SAX parser factory (not a DOM parser, we don't need the
        // overhead) and set it to validate and be namespace aware, for
        // we want to validate against multiple XSDs.
        SAXParserFactory parserFactory = SAXParserFactory.newInstance();
        parserFactory.setValidating(true);
        parserFactory.setNamespaceAware(true);

        // Create a SAX parser and prepare for XSD validation.
        SAXParser parser = parserFactory.newSAXParser();
        parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
        parser.setProperty(JAXP_SCHEMA_SOURCE, schemas);

        // Create a parser handler to trap errors during parse.
        KmlValidatorParserHandler parserHandler = new KmlValidatorParserHandler();

        // Parse the KML and send all errors to our handler.
        parser.parse(request.getInputStream(), parserHandler);

        // Check our handler for validation results.
        if (parserHandler.getErrors().size() > 0) {
            // There were errors, enumerate through them and create JSON objects
            // for each one.
            for (KmlValidationError e : parserHandler.getErrors()) {
                JSONObject error = new JSONObject();

                switch (e.getType()) {
                case KmlValidationError.VALIDATION_WARNING:
                    error.put("type", "warning");
                    break;

                case KmlValidationError.VALIDATION_ERROR:
                    error.put("type", "error");
                    break;

                case KmlValidationError.VALIDATION_FATAL_ERROR:
                    error.put("type", "fatal_error");
                    break;

                default:
                    error.put("type", "fatal_error");
                }

                // fill in parse exception details
                SAXParseException innerException = e.getInnerException();
                error.put("message", innerException.getMessage());

                if (innerException.getLineNumber() >= 0)
                    error.put("line", innerException.getLineNumber());

                if (innerException.getColumnNumber() >= 0)
                    error.put("column", innerException.getColumnNumber());

                // add this error to the list
                responseErrors.add(error);
            }

            // The KML wasn't valid.
            responseObj.put("status", "invalid");
        } else {
            // The KML is valid against the XSDs.
            responseObj.put("status", "valid");
        }
    } catch (SAXException e) {
        // We should never get here due to regular parse errors. This error
        // must've been thrown by the schema factory.
        responseObj.put("status", "internal_error");

        JSONObject error = new JSONObject();
        error.put("type", "fatal_error");
        error.put("message", "Internal error: " + e.getMessage());
        responseErrors.add(error);

    } catch (ParserConfigurationException e) {
        // Internal error at this point.
        responseObj.put("status", "internal_error");

        JSONObject error = new JSONObject();
        error.put("type", "fatal_error");
        error.put("message", "Internal parse error.");
        responseErrors.add(error);
    }

    // If there were errors, add them to the final response JSON object.
    if (responseErrors.size() > 0) {
        responseObj.put("errors", responseErrors);
    }

    // output the JSON object as the HTTP response and append a newline for
    // prettiness
    response.getWriter().print(responseObj);
    response.getWriter().println();
}

From source file:com.typhoon.newsreader.engine.ChannelRefresh.java

public List<FeedsListItem> parser(String link) {
    if (link.contains("www.24h.com.vn")) {
        try {/*from  w  w  w . j a v  a  2s .com*/
            URL url = new URL(link);
            URLConnection connection = url.openConnection();
            connection.addRequestProperty("http.agent", USER_AGENT);
            InputSource input = new InputSource(url.openStream());
            SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            factory.setValidating(false);
            SAXParser parser = factory.newSAXParser();
            XMLReader reader = parser.getXMLReader();

            reader.setContentHandler(this);
            reader.parse(input);

            return getFeedsList();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    } else {
        try {
            // URL url= new URL(link);
            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(link);
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            factory.setValidating(false);
            SAXParser parser = factory.newSAXParser();
            XMLReader reader = parser.getXMLReader();
            reader.setContentHandler(this);
            InputSource inStream = new InputSource();
            inStream.setCharacterStream(new StringReader(EntityUtils.toString(entity)));
            reader.parse(inStream);
            return getFeedsList();
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
            return null;
        } catch (SAXException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

From source file:com.dgwave.osrs.OsrsClient.java

private void initJaxb() throws OsrsException {
    if (jc != null && oj != null)
        return;/*from w ww. jav a2  s .  c o m*/
    try {
        this.jc = JAXBContext.newInstance("com.dgwave.osrs.jaxb");
        this.oj = new ObjectFactory();
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        spf.setNamespaceAware(true);
        spf.setValidating(false);
        xmlReader = spf.newSAXParser().getXMLReader();
        xmlReader.setEntityResolver(new EntityResolver() {
            @Override
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                logger.debug("Ignoring DTD");
                return new InputSource(new StringReader(""));
            }
        });
    } catch (Exception e) {
        throw new OsrsException("JAXB Error", e);
    }
}

From source file:com.esri.geoportal.commons.csw.client.impl.Client.java

/**
 * Reads capabilities from the stream./*from w  ww .  jav  a  2s. c  o  m*/
 *
 * @param stream input stream with capabilities response
 * @return capabilities
 * @throws ParserConfigurationException if unable to create XML parser
 * @throws SAXException if invalid XML response
 * @throws IOException if unable to read response
 */
private Capabilities readCapabilities(InputStream stream)
        throws ParserConfigurationException, SAXException, IOException {
    Capabilities capabilities = new Capabilities();
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    CapabilitiesParse cParse = new CapabilitiesParse(capabilities);
    factory.newSAXParser().parse(new InputSource(stream), cParse);
    return capabilities;
}

From source file:com.prowidesoftware.swift.io.parser.MxParser.java

/**
 * Non-namespace aware parse.<br />
 * Parses the complete message content into an {@link MxNode} tree structure.
 * The parser should be initialized with a valid source.
 *
 * @since 7.7/*from www .j av a  2s.  com*/
 */
public MxNode parse() {
    Validate.notNull(buffer, "the source must be initialized");
    try {
        final javax.xml.parsers.SAXParserFactory spf = javax.xml.parsers.SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        final javax.xml.parsers.SAXParser saxParser = spf.newSAXParser();
        final MxNodeContentHandler contentHandler = new MxNodeContentHandler();
        final org.xml.sax.XMLReader xmlReader = saxParser.getXMLReader();
        xmlReader.setContentHandler(contentHandler);
        xmlReader.parse(new org.xml.sax.InputSource(new StringReader(this.buffer)));
        return contentHandler.getRootNode();
    } catch (final Exception e) {
        log.log(Level.SEVERE, "Error parsing: ", e);
    }
    return null;
}

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

/**
 * Executes the message 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 response object containing the UPNP parsed response
 * @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   w  ww .j  ava  2  s  .co  m*/
public ActionResponse service() throws IOException, UPNPResponseException {
    ActionResponse 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:").append(serviceAction.getName()).append(" xmlns:u=\"").append(service.getServiceType())
            .append("\">");

    if (serviceAction.getInputActionArguments() != null) {
        // this action requires params so we just set them...
        for (Iterator itr = inputParameters.iterator(); itr.hasNext();) {
            InputParamContainer container = (InputParamContainer) itr.next();
            body.append("<").append(container.name).append(">").append(container.value);
            body.append("</").append(container.name).append(">");
        }
    }
    body.append("</u:").append(serviceAction.getName()).append(">");
    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("CONTENT-TYPE", "text/xml; charset=\"utf-8\"");
    conn.setRequestProperty("CONTENT-LENGTH", Integer.toString(body.length()));
    conn.setRequestProperty("SOAPACTION",
            "\"" + service.getServiceType() + "#" + serviceAction.getName() + "\"");
    OutputStream out = conn.getOutputStream();
    out.write(body.toString().getBytes());
    out.flush();
    out.close();
    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);
        ActionMessageResponseParser msgParser = new ActionMessageResponseParser(serviceAction);
        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) {
                // ignore
            }
        }
        if (upnpEx == null) {
            if (response == HttpURLConnection.HTTP_OK) {
                rtrVal = msgParser.getActionResponse();
            } 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;
}

From source file:eionet.gdem.conversion.spreadsheet.DDXMLConverter.java

/**
 * Converts XML file/*from w w  w. j ava2s.  c o m*/
 * @param xmlSchema XML schema
 * @param outStream OutputStream
 * @throws Exception If an error occurs.
 */
protected void doConversion(String xmlSchema, OutputStream outStream) throws Exception {
    String instanceUrl = DataDictUtil.getInstanceUrl(xmlSchema);

    DD_XMLInstance instance = new DD_XMLInstance(instanceUrl);
    DD_XMLInstanceHandler handler = new DD_XMLInstanceHandler(instance);

    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();
    XMLReader reader = parser.getXMLReader();

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

    reader.setContentHandler(handler);
    reader.parse(instanceUrl);

    if (Utils.isNullStr(instance.getEncoding())) {
        String enc_url = Utils.getEncodingFromStream(instanceUrl);
        if (!Utils.isNullStr(enc_url)) {
            instance.setEncoding(enc_url);
        }
    }
    importSheetSchemas(sourcefile, instance, xmlSchema);
    instance.startWritingXml(outStream);
    sourcefile.writeContentToInstance(instance);
    instance.flushXml();
}

From source file:net.sf.firemox.xml.XmlParser.java

/**
 * Constructor.//from   w  w w  . j  a  v  a  2 s .  c  om
 * 
 * @param validation
 *          validation flag.
 * @throws SAXException
 */
public XmlParser(boolean validation) throws SAXException {
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(validation);
        parser = factory.newSAXParser();
        if (validation) {
            parser.setProperty(JAXP_SCHEMA_LANGUAGE, XMLConstants.W3C_XML_SCHEMA_NS_URI);
            parser.setProperty(JAXP_SCHEMA_SOURCE, MToolKit.getFile(MP_XML_SCHEMA));
        }
    } catch (Exception e) {
        throw new SAXException(e.toString());
    }
}

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

/**
 * Tests the {@link CastorUnmarshaller#getUnmarshallerHandler()} method.
 *
 * @throws Exception if any error occurs during test
 *//*w ww. j ava 2s  .  co m*/
@Test
public void testGetUnmarshallHandler() throws Exception {
    UnmarshallerHandler unmarshallerHandler = unmarshaller.getUnmarshallerHandler();

    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);

    XMLReader xmlReader = spf.newSAXParser().getXMLReader();
    xmlReader.setContentHandler(unmarshallerHandler);
    xmlReader.parse(new InputSource(new StringReader(INPUT_XML)));

    Entity entity = (Entity) unmarshallerHandler.getResult();
    testEntity(entity);
}

From source file:nl.armatiek.xslweb.configuration.WebApp.java

public XsltExecutable tryTemplatesCache(String transformationPath, ErrorListener errorListener)
        throws Exception {
    String key = FilenameUtils.normalize(transformationPath);
    XsltExecutable templates = templatesCache.get(key);
    if (templates == null) {
        logger.info("Compiling and caching stylesheet \"" + transformationPath + "\" ...");
        try {//ww  w  .j a  va 2s.  c om
            SAXParserFactory spf = SAXParserFactory.newInstance();
            spf.setNamespaceAware(true);
            spf.setXIncludeAware(true);
            spf.setValidating(false);
            SAXParser parser = spf.newSAXParser();
            XMLReader reader = parser.getXMLReader();
            Source source = new SAXSource(reader, new InputSource(transformationPath));
            XsltCompiler comp = processor.newXsltCompiler();
            comp.setErrorListener(errorListener);
            templates = comp.compile(source);
        } catch (Exception e) {
            logger.error("Could not compile stylesheet \"" + transformationPath + "\"", e);
            throw e;
        }
        if (!developmentMode) {
            templatesCache.put(key, templates);
        }
    }
    return templates;
}