Example usage for org.xml.sax XMLReader parse

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

Introduction

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

Prototype

public void parse(String systemId) throws IOException, SAXException;

Source Link

Document

Parse an XML document from a system identifier (URI).

Usage

From source file:org.apache.oozie.util.GraphGenerator.java

/**
 * Stream the PNG file to client/*from   w w  w . j a v  a2  s.c o m*/
 * @param out
 * @throws Exception
 */
public void write(OutputStream out) throws Exception {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setFeature("http://xml.org/sax/features/external-general-entities", false);
    spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
    spf.setNamespaceAware(true);
    SAXParser saxParser = spf.newSAXParser();
    XMLReader xmlReader = saxParser.getXMLReader();
    xmlReader.setContentHandler(new XMLParser(out));
    xmlReader.parse(new InputSource(new StringReader(xml)));
}

From source file:org.apache.openmeetings.db.dao.label.LabelDao.java

private static List<StringLabel> getLabels(InputStream is) throws Exception {
    final List<StringLabel> labels = new ArrayList<StringLabel>();
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);/*from   www .  j av  a 2s .  c om*/
    try {
        SAXParser parser = spf.newSAXParser();
        XMLReader xr = parser.getXMLReader();
        xr.setContentHandler(new ContentHandler() {
            StringLabel label = null;

            @Override
            public void startPrefixMapping(String prefix, String uri) throws SAXException {
            }

            @Override
            public void startElement(String uri, String localName, String qName, Attributes atts)
                    throws SAXException {
                if (ENTRY_ELEMENT.equals(localName)) {
                    label = new StringLabel(atts.getValue(KEY_ATTR), "");
                }
            }

            @Override
            public void startDocument() throws SAXException {
            }

            @Override
            public void skippedEntity(String name) throws SAXException {
            }

            @Override
            public void setDocumentLocator(Locator locator) {
            }

            @Override
            public void processingInstruction(String target, String data) throws SAXException {
            }

            @Override
            public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
            }

            @Override
            public void endPrefixMapping(String prefix) throws SAXException {
            }

            @Override
            public void endElement(String uri, String localName, String qName) throws SAXException {
                if (ENTRY_ELEMENT.equals(localName)) {
                    labels.add(label);
                }
            }

            @Override
            public void endDocument() throws SAXException {
            }

            @Override
            public void characters(char[] ch, int start, int length) throws SAXException {
                StringBuilder sb = new StringBuilder(label.getValue());
                sb.append(ch, start, length);
                label.setValue(sb.toString());
            }
        });
        xr.parse(new InputSource(is));
    } catch (Exception e) {
        throw e;
    }
    return labels;
}

From source file:org.apache.poi.xssf.eventusermodel.XLSX2CSV.java

/**
 * Parses and shows the content of one sheet
 * using the specified styles and shared-strings tables.
 *
 * @param styles//from w  ww.j  a  va2s.  com
 * @param strings
 * @param sheetInputStream
 */
public void processSheet(StylesTable styles, ReadOnlySharedStringsTable strings, InputStream sheetInputStream)
        throws IOException, ParserConfigurationException, SAXException {

    InputSource sheetSource = new InputSource(sheetInputStream);
    SAXParserFactory saxFactory = SAXParserFactory.newInstance();
    SAXParser saxParser = saxFactory.newSAXParser();
    XMLReader sheetParser = saxParser.getXMLReader();
    ContentHandler handler = new MyXSSFSheetHandler(styles, strings, this.minColumns, this.output);
    sheetParser.setContentHandler(handler);
    sheetParser.parse(sheetSource);
}

From source file:org.apache.synapse.mediators.transform.PayloadFactoryMediator.java

private boolean isWellFormedXML(String value) {
    try {// w  w  w .  j  a  v  a 2  s.c  o  m
        XMLReader parser = XMLReaderFactory.createXMLReader();
        parser.setErrorHandler(null);
        InputSource source = new InputSource(new ByteArrayInputStream(value.getBytes()));
        parser.parse(source);
    } catch (SAXException e) {
        return false;
    } catch (IOException e) {
        return false;
    }
    return true;
}

From source file:org.apache.tika.parser.microsoft.ooxml.xwpf.XWPFEventBasedWordExtractor.java

private void handlePart(PackagePart packagePart, XWPFListManager xwpfListManager, StringBuilder buffer)
        throws IOException, SAXException {

    Map<String, String> hyperlinks = loadHyperlinkRelationships(packagePart);
    try (InputStream stream = packagePart.getInputStream()) {
        XMLReader reader = SAXHelper.newXMLReader();
        reader.setContentHandler(/*w w  w  . ja  v  a2 s.com*/
                new OOXMLWordAndPowerPointTextHandler(new XWPFToTextContentHandler(buffer), hyperlinks));
        reader.parse(new InputSource(new CloseShieldInputStream(stream)));

    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }

}

From source file:org.apache.xmlrpc.client.XmlRpcStreamTransport.java

/**
 * This method was modified, because the xml-parser fails with certain 
 * invalid XML-characters like the unicode-characters: cx0, 0x8, etc.
 * *///  w w  w .  ja v  a 2s. c o  m
protected Object readResponse(XmlRpcStreamRequestConfig pConfig, InputStream pStream) throws XmlRpcException {
    InputSource isource = new InputSource(pStream);
    XMLReader xr = newXMLReader();
    XmlRpcResponseParser xp;
    try {
        xp = new XmlRpcResponseParser(pConfig, getClient().getTypeFactory());
        xr.setContentHandler(xp);
        // Remove the invalid characters before parsing
        String pStreamAsStr = convertInputStreamIntoString(pStream);
        String pStreamAsStrWithValidChars = stripNonValidXMLCharacters(pStreamAsStr);
        InputStream is = IOUtils.toInputStream(pStreamAsStrWithValidChars, "UTF-8");
        isource = new InputSource(is);

        xr.parse(isource);
    } catch (SAXException e) {
        throw new XmlRpcClientException("Failed to parse server's response: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new XmlRpcClientException("Failed to read server's response: " + e.getMessage(), e);
    }
    if (xp.isSuccess()) {
        return xp.getResult();
    }
    Throwable t = xp.getErrorCause();
    if (t == null) {
        throw new XmlRpcException(xp.getErrorCode(), xp.getErrorMessage());
    }
    if (t instanceof XmlRpcException) {
        throw (XmlRpcException) t;
    }
    if (t instanceof RuntimeException) {
        throw (RuntimeException) t;
    }
    throw new XmlRpcException(xp.getErrorCode(), xp.getErrorMessage(), t);
}

From source file:org.apache.xmlrpc.server.XmlRpcStreamServer.java

protected XmlRpcRequest getRequest(final XmlRpcStreamRequestConfig pConfig, InputStream pStream)
        throws XmlRpcException {
    final XmlRpcRequestParser parser = new XmlRpcRequestParser(pConfig, getTypeFactory());
    final XMLReader xr = SAXParsers.newXMLReader();
    xr.setContentHandler(parser);//  ww w .  j a v a2 s .  com
    try {
        xr.parse(new InputSource(pStream));
    } catch (SAXException e) {
        Exception ex = e.getException();
        if (ex != null && ex instanceof XmlRpcException) {
            throw (XmlRpcException) ex;
        }
        throw new XmlRpcException("Failed to parse XML-RPC request: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new XmlRpcException("Failed to read XML-RPC request: " + e.getMessage(), e);
    }
    final List params = parser.getParams();
    return new XmlRpcRequest() {
        public XmlRpcRequestConfig getConfig() {
            return pConfig;
        }

        public String getMethodName() {
            return parser.getMethodName();
        }

        public int getParameterCount() {
            return params == null ? 0 : params.size();
        }

        public Object getParameter(int pIndex) {
            return params.get(pIndex);
        }
    };
}

From source file:org.apereo.portal.groups.GroupServiceConfiguration.java

protected void parseXml() throws Exception {
    InputSource xmlSource = new InputSource(
            ResourceLoader.getResourceAsStream(GroupServiceConfiguration.class, SERVICES_XML));

    if (xmlSource != null) {
        XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
        reader.setContentHandler(serviceHandler);
        reader.parse(xmlSource);
    }//w w w . jav  a  2 s.c  om
}

From source file:org.archive.crawler.settings.XMLSettingsHandler.java

/** Read the CrawlerSettings object from a specific file.
 *
 * @param settings the settings object to be updated with data from the
 *                 persistent storage./* w ww  . j  a va  2  s  .  c  om*/
 * @param f the file to read from.
 * @return the updated settings object or null if there was no data for this
 *         in the persistent storage.
 */
protected final CrawlerSettings readSettingsObject(CrawlerSettings settings, File f) {
    CrawlerSettings result = null;
    try {
        InputStream is = null;
        if (!f.exists()) {
            // Perhaps the file we're looking for is on the CLASSPATH.
            // DON'T look on the CLASSPATH for 'settings.xml' files.  The
            // look for 'settings.xml' files happens frequently. Not looking
            // on classpath for 'settings.xml' is an optimization based on
            // ASSUMPTION that there will never be a 'settings.xml' saved
            // on classpath.
            if (!f.getName().startsWith(settingsFilename)) {
                is = XMLSettingsHandler.class.getResourceAsStream(toResourcePath(f));
            }
        } else {
            is = new FileInputStream(f);
        }
        if (is != null) {
            XMLReader parser = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
            InputStream file = new BufferedInputStream(is);
            parser.setContentHandler(new CrawlSettingsSAXHandler(settings));
            InputSource source = new InputSource(file);
            source.setSystemId(f.toURL().toExternalForm());
            parser.parse(source);
            result = settings;
        }
    } catch (SAXParseException e) {
        logger.warning(e.getMessage() + " in '" + e.getSystemId() + "', line: " + e.getLineNumber()
                + ", column: " + e.getColumnNumber());
    } catch (SAXException e) {
        logger.warning(e.getMessage() + ": " + e.getException().getMessage());
    } catch (ParserConfigurationException e) {
        logger.warning(e.getMessage() + ": " + e.getCause().getMessage());
    } catch (FactoryConfigurationError e) {
        logger.warning(e.getMessage() + ": " + e.getException().getMessage());
    } catch (IOException e) {
        logger.warning("Could not access file '" + f.getAbsolutePath() + "': " + e.getMessage());
    }
    return result;
}

From source file:org.atombeat.xquery.functions.util.RequestGetData.java

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    RequestModule myModule = (RequestModule) context.getModule(RequestModule.NAMESPACE_URI);

    // request object is read from global variable $request
    Variable var = myModule.resolveVariable(RequestModule.REQUEST_VAR);

    if (var == null || var.getValue() == null)
        throw new XPathException(this, "No request object found in the current XQuery context.");

    if (var.getValue().getItemType() != Type.JAVA_OBJECT)
        throw new XPathException(this, "Variable $request is not bound to an Java object.");

    JavaObjectValue value = (JavaObjectValue) var.getValue().itemAt(0);

    if (value.getObject() instanceof RequestWrapper) {
        RequestWrapper request = (RequestWrapper) value.getObject();

        //if the content length is unknown, return
        if (request.getContentLength() == -1) {
            return Sequence.EMPTY_SEQUENCE;
        }// ww  w.j  a  va2  s .  c o m

        //first, get the content of the request
        byte[] bufRequestData = null;
        try {
            InputStream is = request.getInputStream();
            ByteArrayOutputStream bos = new ByteArrayOutputStream(request.getContentLength());
            byte[] buf = new byte[256];
            int l = 0;
            while ((l = is.read(buf)) > -1) {
                bos.write(buf, 0, l);
            }
            bufRequestData = bos.toByteArray();
        } catch (IOException ioe) {
            throw new XPathException(this, "An IO exception ocurred: " + ioe.getMessage(), ioe);
        }

        //was there any POST content
        if (bufRequestData != null) {
            //determine if exists mime database considers this binary data
            String contentType = request.getContentType();
            if (contentType != null) {
                //strip off any charset encoding info
                if (contentType.indexOf(";") > -1)
                    contentType = contentType.substring(0, contentType.indexOf(";"));

                MimeType mimeType = MimeTable.getInstance().getContentType(contentType);
                //<atombeat>
                // this code will only encode the request data if the mimeType
                // is present in the mime table, and the mimeType is stated
                // as binary...

                //               if(mimeType != null)
                //               {
                //                  if(!mimeType.isXMLType())
                //                  {
                //                     //binary data
                //                     return new Base64Binary(bufRequestData);
                //                  }
                //               }

                // this code takes a more conservative position and assumes that
                // if the mime type is not present in the table, the request
                // data should be treated as binary, and should be encoded as 
                // base 64...

                if (mimeType == null || !mimeType.isXMLType()) {
                    return new Base64Binary(bufRequestData);
                }
                //</atombeat>               
            }

            //try and parse as an XML documemnt, otherwise fallback to returning the data as a string
            context.pushDocumentContext();
            try {
                //try and construct xml document from input stream, we use eXist's in-memory DOM implementation
                SAXParserFactory factory = SAXParserFactory.newInstance();
                factory.setNamespaceAware(true);
                //TODO : we should be able to cope with context.getBaseURI()            
                InputSource src = new InputSource(new ByteArrayInputStream(bufRequestData));
                SAXParser parser = factory.newSAXParser();
                XMLReader reader = parser.getXMLReader();
                MemTreeBuilder builder = context.getDocumentBuilder();
                DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(builder, true);
                reader.setContentHandler(receiver);
                reader.parse(src);
                Document doc = receiver.getDocument();
                return (NodeValue) doc.getDocumentElement();
            } catch (ParserConfigurationException e) {
                //do nothing, we will default to trying to return a string below
            } catch (SAXException e) {
                //do nothing, we will default to trying to return a string below
            } catch (IOException e) {
                //do nothing, we will default to trying to return a string below
            } finally {
                context.popDocumentContext();
            }

            //not a valid XML document, return a string representation of the document
            String encoding = request.getCharacterEncoding();
            if (encoding == null) {
                encoding = "UTF-8";
            }
            try {
                String s = new String(bufRequestData, encoding);
                return new StringValue(s);
            } catch (IOException e) {
                throw new XPathException(this, "An IO exception ocurred: " + e.getMessage(), e);
            }
        } else {
            //no post data
            return Sequence.EMPTY_SEQUENCE;
        }
    } else {
        throw new XPathException(this, "Variable $request is not bound to a Request object.");
    }
}