Example usage for org.xml.sax XMLReader setContentHandler

List of usage examples for org.xml.sax XMLReader setContentHandler

Introduction

In this page you can find the example usage for org.xml.sax XMLReader setContentHandler.

Prototype

public void setContentHandler(ContentHandler handler);

Source Link

Document

Allow an application to register a content event handler.

Usage

From source file:cm.aptoide.pt.RemoteInTab.java

private void xmlPass(String srv, boolean type) {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {//  w w  w . j  ava 2s .com
        File xml_file = null;
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        if (type) {
            RssHandler handler = new RssHandler(this, srv);
            xr.setContentHandler(handler);
            xml_file = new File(XML_PATH);
        } else {
            ExtrasRssHandler handler = new ExtrasRssHandler(this, srv);
            xr.setContentHandler(handler);
            xml_file = new File(EXTRAS_XML_PATH);
        }

        InputStreamReader isr = new FileReader(xml_file);
        InputSource is = new InputSource(isr);
        xr.parse(is);
        xml_file.delete();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
}

From source file:ee.ria.xroad.proxy.serverproxy.MetadataServiceHandlerImpl.java

/**
 * reads a WSDL from input stream, modifies it and returns input stream to the result
 * @param wsdl/*from   w  w w  .j  a v a2s.  c o  m*/
 * @return
 */
private InputStream modifyWsdl(InputStream wsdl) {
    try {
        TransformerHandler serializer = TRANSFORMER_FACTORY.newTransformerHandler();
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        serializer.setResult(result);

        OverwriteAttributeFilter filter = getModifyWsdlFilter();
        filter.setContentHandler(serializer);

        XMLReader xmlreader = XMLReaderFactory.createXMLReader();
        xmlreader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
        xmlreader.setProperty("http://xml.org/sax/properties/lexical-handler", new CommentsHandler(serializer));
        xmlreader.setContentHandler(filter);

        // parse XML, filter it, put end result to a String
        xmlreader.parse(new InputSource(wsdl));
        String resultString = writer.toString();
        log.debug("result of WSDL cleanup: {}", resultString);

        // offer InputStream into processed String
        return new ByteArrayInputStream(resultString.getBytes(StandardCharsets.UTF_8));
    } catch (IOException | SAXException | TransformerConfigurationException e) {
        throw new RuntimeException(e);
    }
}

From source file:cm.aptoide.pt.ManageRepo.java

private Vector<String> getRemoteServLst(String file) {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    Vector<String> out = new Vector<String>();
    try {// ww w  .  ja v  a 2 s.  co m
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        NewServerRssHandler handler = new NewServerRssHandler(this);
        xr.setContentHandler(handler);

        InputStreamReader isr = new FileReader(new File(file));
        InputSource is = new InputSource(isr);
        xr.parse(is);
        File xml_file = new File(file);
        xml_file.delete();
        out = handler.getNewSrvs();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    return out;
}

From source file:com.sonicle.webtop.core.io.input.ExcelFileReader.java

public HashMap<String, String> listXlsxColumnNames(File file) throws IOException, FileReaderException {
    OPCPackage opc = null;//from ww  w  .j av  a 2  s. c  om

    try {
        opc = OPCPackage.open(file, PackageAccess.READ);
        XSSFReader reader = new XSSFReader(opc);
        ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(opc);
        StylesTable styles = reader.getStylesTable();

        XlsxColumnsHandler columnsHandler = null;
        XSSFReader.SheetIterator sit = (XSSFReader.SheetIterator) reader.getSheetsData();
        while (sit.hasNext()) {
            InputStream is = null;
            try {
                is = sit.next();
                if (StringUtils.equals(sit.getSheetName(), sheet)) {
                    XMLReader xmlReader = SAXHelper.newXMLReader();
                    columnsHandler = new XlsxColumnsHandler(is, headersRow, firstDataRow, lastDataRow);
                    ContentHandler handler = new XSSFSheetXMLHandler(styles, null, strings, columnsHandler, fmt,
                            false);
                    xmlReader.setContentHandler(handler);
                    xmlReader.parse(new InputSource(is));
                }
            } catch (SAXException | ParserConfigurationException ex) {
                throw new FileReaderException(ex, "Error processing file content");
            } catch (NullPointerException ex) {
                // Thrown when stream is forcibly closed. Simply ignore this!
            } finally {
                IOUtils.closeQuietly(is);
            }
            if (columnsHandler != null)
                break;
        }
        return columnsHandler.columnNames;

    } catch (OpenXML4JException | SAXException ex) {
        throw new FileReaderException(ex, "Error opening file");
    } finally {
        IOUtils.closeQuietly(opc);
    }
}

From source file:com.sonicle.webtop.core.io.input.ExcelFileReader.java

public HashMap<String, Integer> listXlsxColumnIndexes(File file) throws IOException, FileReaderException {
    OPCPackage opc = null;//from  w  w w . j a v a2s  . c  om

    try {
        opc = OPCPackage.open(file, PackageAccess.READ);
        XSSFReader reader = new XSSFReader(opc);
        ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(opc);
        StylesTable styles = reader.getStylesTable();

        XlsxColumnsHandler columnsHandler = null;
        XSSFReader.SheetIterator sit = (XSSFReader.SheetIterator) reader.getSheetsData();
        while (sit.hasNext()) {
            InputStream is = null;
            try {
                is = sit.next();
                if (StringUtils.equals(sit.getSheetName(), sheet)) {
                    XMLReader xmlReader = SAXHelper.newXMLReader();
                    columnsHandler = new XlsxColumnsHandler(is, headersRow, firstDataRow, lastDataRow);
                    ContentHandler handler = new XSSFSheetXMLHandler(styles, null, strings, columnsHandler, fmt,
                            false);
                    xmlReader.setContentHandler(handler);
                    xmlReader.parse(new InputSource(is));
                }
            } catch (SAXException | ParserConfigurationException ex) {
                throw new FileReaderException(ex, "Error processing file content");
            } catch (NullPointerException ex) {
                // Thrown when stream is forcibly closed. Simply ignore this!
            } finally {
                IOUtils.closeQuietly(is);
            }
            if (columnsHandler != null)
                break;
        }
        return columnsHandler.columnIndexes;

    } catch (OpenXML4JException | SAXException ex) {
        throw new FileReaderException(ex, "Error opening file");
    } finally {
        IOUtils.closeQuietly(opc);
    }
}

From source file:org.semantictools.frame.api.OntologyManager.java

private void loadXsd(File file) throws SchemaParseException {
    try {/* www .j  av a  2  s  .c o m*/
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        XMLReader reader = parser.getXMLReader();
        reader.setFeature("http://xml.org/sax/features/namespaces", true);
        NamespaceReader handler = new NamespaceReader();
        reader.setContentHandler(handler);

        parser.parse(file, handler);

        String namespace = handler.getTargetNamespace();
        if (namespace == null) {
            logger.warn("Ignoring schema since targetNamespace is not declared: " + file.getPath());
        } else {
            OntologyEntity entity = new OntologyEntity(XML_FORMAT, file, namespace);
            uri2OntologyEntity.put(namespace, entity);
        }
    } catch (Throwable oops) {
        throw new SchemaParseException(oops);
    }

}

From source file:com.mirth.connect.plugins.datatypes.edi.EDISerializer.java

@Override
public String fromXML(String source) throws MessageSerializerException {
    XMLReader xr;
    try {/*from  w w  w  . j  av a  2s .  c o  m*/
        xr = XMLReaderFactory.createXMLReader();
    } catch (SAXException e) {
        throw new MessageSerializerException("Error converting XML to EDI", e, ErrorMessageBuilder
                .buildErrorMessage(this.getClass().getSimpleName(), "Error converting XML to EDI", e));
    }
    EDIXMLHandler handler = new EDIXMLHandler();
    xr.setContentHandler(handler);
    xr.setErrorHandler(handler);
    try {
        //Parse, but first replace all spaces between brackets. This fixes pretty-printed XML we might receive
        xr.parse(new InputSource(new StringReader(
                prettyPattern2.matcher(prettyPattern1.matcher(source).replaceAll("<$1>")).replaceAll("<$1>"))));
    } catch (Exception e) {
        throw new MessageSerializerException("Error converting XML to EDI", e, ErrorMessageBuilder
                .buildErrorMessage(this.getClass().getSimpleName(), "Error converting XML to EDI", e));
    }
    return handler.getOutput().toString();
}

From source file:com.frostwire.gui.updates.UpdateMessageReader.java

public void readUpdateFile() {
    HttpURLConnection connection = null;
    InputSource src = null;/*from w w w  .  j  a  va 2 s .c om*/

    try {
        String userAgent = "FrostWire/" + OSUtils.getOS() + "-" + OSUtils.getArchitecture() + "/"
                + FrostWireUtils.getFrostWireVersion();
        connection = (HttpURLConnection) (new URL(getUpdateURL())).openConnection();
        String url = getUpdateURL();
        System.out.println("Reading update file from " + url);
        connection.setRequestProperty("User-Agent", userAgent);
        connection.setRequestProperty("Connection", "close");
        connection.setReadTimeout(10000); // 10 secs timeout

        if (connection.getResponseCode() >= 400) {
            // invalid URL for sure
            connection.disconnect();
            return;
        }

        src = new InputSource(connection.getInputStream());

        XMLReader rdr = XMLReaderFactory
                .createXMLReader("com.sun.org.apache.xerces.internal.parsers.SAXParser");
        rdr.setContentHandler(this);

        rdr.parse(src);
        connection.getInputStream().close();
        connection.disconnect();
    } catch (java.net.SocketTimeoutException e3) {
        System.out.println("UpdateMessageReadre.readUpdateFile() Socket Timeout Exeception " + e3.toString());
    } catch (IOException e) {
        System.out.println("UpdateMessageReader.readUpdateFile() IO exception " + e.toString());
    } catch (SAXException e2) {
        System.out.println("UpdateMessageReader.readUpdateFile() SAX exception " + e2.toString());
    }
}

From source file:net.vivekiyer.GAL.ActiveSyncManager.java

/**
 * @param xml The XML to parse //from  www .  java  2 s  .  com
 * @param nodeName The Node to search for in the XML 
 * @return List of strings found in the specified node
 * @throws Exception
 * 
 * This method parses the an XML string and returns all values that were found
 * in the node specified in the request 
 */
private String[] parseXML(String xml, String nodeName) throws Exception {
    // Our parser does not handle ampersands too well. Replace with &amp;
    xml = xml.replaceAll("&", "&amp;");

    // Parse the XML
    ByteArrayInputStream xmlParseInputStream = new ByteArrayInputStream(xml.toString().getBytes());
    XMLReader xr = XMLReaderFactory.createXMLReader();
    XMLParser parser = new XMLParser(nodeName);
    xr.setContentHandler(parser);
    xr.parse(new InputSource(xmlParseInputStream));
    return parser.getOutput();
}

From source file:se.lu.nateko.edca.svc.GetCapabilities.java

/**
 * Parses an XML response from a GetCapabilities request and stores available Layers
 * and options in the local SQLite database.
 * @param xmlResponse A reader wrapped around an InputStream containing the XML response from a GetCapabilities request.
 */// w w w  . j a  v a  2 s  .  c  om
protected boolean parseXMLResponse(BufferedReader xmlResponse) {
    Log.d(TAG, "parseXMLResponse(Reader) called.");

    try {
        SAXParserFactory spfactory = SAXParserFactory.newInstance(); // Make a SAXParser factory.
        spfactory.setValidating(false); // Tell the factory not to make validating parsers.
        SAXParser saxParser = spfactory.newSAXParser(); // Use the factory to make a SAXParser.
        XMLReader xmlReader = saxParser.getXMLReader(); // Get an XML reader from the parser, which will send event calls to its specified event handler.
        XMLEventHandler xmlEventHandler = new XMLEventHandler();
        xmlReader.setContentHandler(xmlEventHandler); // Set which event handler to use.
        xmlReader.setErrorHandler(xmlEventHandler); // Also set where to send error calls.
        InputSource source = new InputSource(xmlResponse); // Make an InputSource from the XML input to give to the reader.
        xmlReader.parse(source); // Start parsing the XML.
    } catch (Exception e) {
        Log.e(TAG, "XML parsing error: " + e.toString() + " - " + e.getMessage());
        return false;
    }
    return true;
}