Example usage for javax.xml.parsers SAXParser parse

List of usage examples for javax.xml.parsers SAXParser parse

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParser parse.

Prototype

public void parse(InputSource is, DefaultHandler dh) throws SAXException, IOException 

Source Link

Document

Parse the content given org.xml.sax.InputSource as XML using the specified org.xml.sax.helpers.DefaultHandler .

Usage

From source file:org.exjello.mail.ExchangeConnection.java

private void findInbox() throws Exception {
    inbox = null;//from  www  .  j  a  v a2s  .c  o  m
    drafts = null;
    submissionUri = null;
    sentitems = null;
    outbox = null;
    HttpClient client = getClient();
    ExchangeMethod op = new ExchangeMethod(PROPFIND_METHOD, server + "/exchange/" + mailbox);
    op.setHeader("Content-Type", XML_CONTENT_TYPE);
    op.setHeader("Depth", "0");
    op.setHeader("Brief", "t");
    op.setRequestEntity(createFindInboxEntity());
    InputStream stream = null;
    try {
        int status = client.executeMethod(op);
        stream = op.getResponseBodyAsStream();
        if (status >= 300) {
            throw new IllegalStateException("Unable to obtain inbox.");
        }
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        SAXParser parser = spf.newSAXParser();
        parser.parse(stream, new DefaultHandler() {
            private final StringBuilder content = new StringBuilder();

            public void startElement(String uri, String localName, String qName, Attributes attributes)
                    throws SAXException {
                content.setLength(0);
            }

            public void characters(char[] ch, int start, int length) throws SAXException {
                content.append(ch, start, length);
            }

            public void endElement(String uri, String localName, String qName) throws SAXException {
                if (!HTTPMAIL_NAMESPACE.equals(uri))
                    return;
                if ("inbox".equals(localName)) {
                    ExchangeConnection.this.inbox = content.toString();
                } else if ("drafts".equals(localName)) {
                    ExchangeConnection.this.drafts = content.toString();
                } else if ("sentitems".equals(localName)) {
                    ExchangeConnection.this.sentitems = content.toString();
                } else if ("outbox".equals(localName)) {
                    ExchangeConnection.this.outbox = content.toString();
                } else if ("sendmsg".equals(localName)) {
                    ExchangeConnection.this.submissionUri = content.toString();
                }
            }
        });
        stream.close();
        stream = null;
    } finally {
        try {
            if (stream != null) {
                byte[] buf = new byte[65536];
                try {
                    if (session.getDebug()) {
                        PrintStream log = session.getDebugOut();
                        log.println("Response Body:");
                        int count;
                        while ((count = stream.read(buf, 0, 65536)) != -1) {
                            log.write(buf, 0, count);
                        }
                        log.flush();
                        log.println();
                    } else {
                        while (stream.read(buf, 0, 65536) != -1)
                            ;
                    }
                } catch (Exception ignore) {
                } finally {
                    try {
                        stream.close();
                    } catch (Exception ignore2) {
                    }
                }
            }
        } finally {
            op.releaseConnection();
        }
    }
}

From source file:org.fcrepo.utilities.XmlTransformUtility.java

public static void parseWithoutValidating(InputSource in, DefaultHandler handler)
        throws SAXException, IOException {
    SAXParser parser = null;
    try {/*from   ww  w . j a v a2  s .c  om*/
        parser = (SAXParser) SAX_PARSERS.borrowObject();
    } catch (Exception e) {
        throw new RuntimeException("Error initializing SAX parser", e);
    }

    try {
        parser.parse(in, handler);
    } finally {
        if (parser != null) {
            try {
                SAX_PARSERS.returnObject(parser);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

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

/**
 * Read XML from the given reader and fire events from the provided
 * listener.//from w  w w.j  a  va2s.  co m
 * 
 * @param reader
 *            The reader containing the XML data.
 * 
 * @param listener
 *            The XmlContentListener containing code to be notified each
 *            time an Xml content object is created.
 * 
 * @return The XmsElement created by parsing the given reader data.
 * 
 * @throws XmlException
 *             Thrown if a problem occur while reading the provided XML
 *             data.
 */
public static XmlElement readXML(Reader reader, XmlContentListener listener) throws XmlException {
    XmlHandler handler = new XmlHandler(listener);
    try {
        SAXParser parser = createSaxParser();
        parser.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
        parser.parse(new InputSource(reader), handler);
        return handler.getRootElement();
    } catch (SAXException e) {
        String message = "A parser problem occured";
        if (handler.peekTopElement() != null) {
            message += ", node = " + handler.peekTopElement().toString();
        }
        throw new XmlException(message, e);
    } catch (IOException e) {
        throw new XmlException("A reader problem occured.", e);
    } catch (ParserConfigurationException e) {
        throw new XmlException("A parser configuration has been detected.", e);
    }
}

From source file:org.gbif.dwca.io.ArchiveFactory.java

@VisibleForTesting
protected static void readMetaDescriptor(Archive archive, InputStream metaDescriptor)
        throws UnsupportedArchiveException {

    try {/*from   w  w w  .j  a v a 2s. c  om*/
        SAXParser p = SAX_FACTORY.newSAXParser();
        MetaHandler mh = new MetaHandler(archive);
        LOG.debug("Reading archive metadata file");
        p.parse(new BOMInputStream(metaDescriptor), mh);
    } catch (Exception e1) {
        LOG.warn("Exception caught", e1);
        throw new UnsupportedArchiveException(e1);
    }
}

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);/*from  w  w w. ja va 2 s.c o  m*/
    factory.setNamespaceAware(false);
    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.glimpse.server.news.sax.SaxServerNewsChannelBuilder.java

public ServerNewsChannel buildChannel(InputStream is) throws Exception {
    SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
    ChannelHandler handler = new ChannelHandler();
    try {/* ww  w  .j a  va  2  s . com*/
        parser.parse(is, handler);
    } catch (SAXParseException e) {
        // If an parse error occurs, we just log the exception
        // because we may have some data available in the channel
        logger.warn("Error while parsing channel", e);
    }

    return handler.getChannel();
}

From source file:org.gluu.oxtrust.ldap.service.Shibboleth2ConfService.java

private EntityIDHandler parseMetadata(File metadataFile) {
    if (!metadataFile.exists()) {
        log.error("Failed to get entityId from metadata file '{0}'", metadataFile.getAbsolutePath());
        return null;
    }/*from  w w  w . j  a  v a 2 s. co m*/

    InputStream is = null;
    InputStreamReader isr = null;
    EntityIDHandler handler = null;
    try {
        is = FileUtils.openInputStream(metadataFile);
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        SAXParser saxParser = saxParserFactory.newSAXParser();

        handler = new EntityIDHandler();
        is = FileUtils.openInputStream(metadataFile);
        saxParser.parse(is, handler);

    } catch (IOException ex) {
        log.error("Failed to read metadata file '{0}'", ex, metadataFile.getAbsolutePath());
    } catch (ParserConfigurationException e) {
        log.error("Failed to confugure SAX parser for file '{0}'", e, metadataFile.getAbsolutePath());
    } catch (SAXException e) {
        log.error("Failed to parse file '{0}'", e, metadataFile.getAbsolutePath());
    } finally {
        IOUtils.closeQuietly(isr);
        IOUtils.closeQuietly(is);
    }

    return handler;
}

From source file:org.gluu.saml.metadata.SAMLMetadataParser.java

public static EntityIDHandler parseMetadata(InputStream is) {
    InputStreamReader isr = null;
    EntityIDHandler handler = null;// w w  w  .ja  v a  2 s  .c om
    try {
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        SAXParser saxParser = saxParserFactory.newSAXParser();

        handler = new EntityIDHandler();
        saxParser.parse(is, handler);
    } catch (IOException ex) {
        log.error("Failed to read SAML metadata", ex);
    } catch (ParserConfigurationException e) {
        log.error("Failed to confugure SAX parser", e);
    } catch (SAXException e) {
        log.error("Failed to parse SAML metadata", e);
    } finally {
        IOUtils.closeQuietly(isr);
        IOUtils.closeQuietly(is);
    }

    return handler;
}

From source file:org.grails.plugins.CorePluginFinder.java

@SuppressWarnings("rawtypes")
private void loadCorePluginsFromResources(Resource[] resources) throws IOException {

    LOG.debug("Attempting to load [" + resources.length + "] core plugins");
    try {/*from ww  w. j a v  a  2  s. c o  m*/
        SAXParser saxParser = SpringIOUtils.newSAXParser();
        for (Resource resource : resources) {
            InputStream input = null;

            try {
                input = resource.getInputStream();
                PluginHandler ph = new PluginHandler();
                saxParser.parse(input, ph);

                for (String pluginType : ph.pluginTypes) {
                    Class<?> pluginClass = attemptCorePluginClassLoad(pluginType);
                    if (pluginClass != null) {
                        addPlugin(pluginClass);
                        binaryDescriptors.put(pluginClass,
                                new BinaryGrailsPluginDescriptor(resource, ph.pluginClasses));
                    }
                }

            } finally {
                if (input != null) {
                    input.close();
                }
            }
        }
    } catch (ParserConfigurationException e) {
        throw new GrailsConfigurationException("XML parsing error loading core plugins: " + e.getMessage(), e);
    } catch (SAXException e) {
        throw new GrailsConfigurationException("XML parsing error loading core plugins: " + e.getMessage(), e);
    }
}

From source file:org.hippoecm.hst.demo.components.NonWorkflowWikiImporterComponent.java

@Override
public void doAction(HstRequest request, HstResponse response) throws HstComponentException {
    String numberStr = request.getParameter("number");
    long start = System.currentTimeMillis();
    if (numberStr != null) {
        SAXParserFactoryImpl impl = new SAXParserFactoryImpl();
        SAXParser parser;
        int numberOfWikiDocs = 0;
        try {// ww  w  . j av  a 2  s  .c om
            numberOfWikiDocs = Integer.parseInt(numberStr);
        } catch (NumberFormatException e) {
            response.setRenderParameter("message", "number must be a number but was '" + numberStr + "'");
        }

        if (numberOfWikiDocs <= 0) {
            response.setRenderParameter("message",
                    "number must be a number larger than 0 but was '" + numberStr + "'");
        }

        String wikiContentFileSystem = request.getParameter("filesystemLocation");

        if (numberOfWikiDocs > 100 && StringUtils.isEmpty(wikiContentFileSystem)) {
            response.setRenderParameter("message",
                    "When number is larger than 100, you need to specify the filesystem location (for exmaple /home/use/Downloads/enwiki-20100622-pages-articles.xml) where wikipedia content can be found that "
                            + "has more than 100 docs. If you choose less than 100, a built in wikipedia xml is used that contains 100 items");
            return;
        }

        String offsetStr = request.getParameter("offset");
        int offset = 0;
        if (StringUtils.isNotBlank(offsetStr)) {
            try {
                offset = Integer.parseInt(offsetStr);
                if (offset < 0) {
                    offset = 0;
                }
            } catch (NumberFormatException e) {
                response.setRenderParameter("message", "offset must be a number but was '" + offsetStr + "'");
                return;
            }
        }

        String maxDocsPerFolderStr = request.getParameter("maxDocsPerFolder");
        int maxDocsPerFolder = 200;
        if (StringUtils.isNotBlank(maxDocsPerFolderStr)) {
            try {
                maxDocsPerFolder = Integer.parseInt(maxDocsPerFolderStr);
                if (maxDocsPerFolder < 0) {
                    maxDocsPerFolder = 0;
                }
            } catch (NumberFormatException e) {
                response.setRenderParameter("message",
                        "maxDocsPerFolder must be a number but was '" + maxDocsPerFolderStr + "'");
                return;
            }
        }

        String maxSubFolderStr = request.getParameter("maxSubFolder");
        int maxSubFolder = 50;
        if (StringUtils.isNotBlank(maxSubFolderStr)) {
            try {
                maxSubFolder = Integer.parseInt(maxSubFolderStr);
                if (maxSubFolder < 0) {
                    maxSubFolder = 0;
                }
            } catch (NumberFormatException e) {
                response.setRenderParameter("message",
                        "maxSubFolder must be a number but was '" + maxSubFolderStr + "'");
                return;
            }
        }

        String imageStr = request.getParameter("images");
        boolean addImages = (imageStr != null);

        try {
            parser = impl.newSAXParser();
            InputStream wikiStream = null;
            File f = null;
            if (StringUtils.isEmpty(wikiContentFileSystem)) {
                wikiStream = NonWorkflowWikiImporterComponent.class.getClassLoader()
                        .getResourceAsStream("enwiki-20081008-pages-articles.xml.100.top.xml");
            } else {
                f = new File(wikiContentFileSystem);
            }

            WikiPediaToJCRHandler handler = null;

            try {
                Session writableSession = this.getPersistableSession(request);
                Node baseNode = writableSession.getNode("/" + getSiteContentBasePath(request));

                Node wikiFolder;

                if (!baseNode.hasNode("wikipedia")) {
                    wikiFolder = baseNode.addNode("wikipedia", "hippostd:folder");
                    wikiFolder.setProperty("hippostd:foldertype",
                            new String[] { "new-translated-folder-demosite", "new-document-demosite" });
                    wikiFolder.addMixin("mix:referenceable");
                    wikiFolder.addMixin("hippotranslation:translated");
                    wikiFolder.setProperty("hippotranslation:locale", "en");
                    wikiFolder.setProperty("hippotranslation:id", UUID.randomUUID().toString());
                } else {
                    wikiFolder = baseNode.getNode("wikipedia");
                }

                handler = new WikiPediaToJCRHandler(wikiFolder, numberOfWikiDocs, offset, maxDocsPerFolder,
                        maxSubFolder, addImages);

                if (wikiStream == null) {
                    parser.parse(f, handler);
                } else {
                    parser.parse(wikiStream, handler);
                }
            } catch (ForcedStopException e) {
                // successful handler quits after numberOfWikiDocs has been achieved
            } catch (Exception e) {
                log.warn("Exception during importing wikipedia docs", e);
                response.setRenderParameter("message",
                        "An exception happened. Did not import wiki docs. " + e.toString());
                return;
            }
        } catch (ParserConfigurationException e) {
            response.setRenderParameter("message", "Did not import wiki: " + e.toString());
            return;
        }
        String relateString = request.getParameter("relate");
        if (relateString != null) {
            int numberOfRelations = 0;
            try {
                numberOfRelations = Integer.parseInt(relateString);
            } catch (NumberFormatException e) {
                response.setRenderParameter("message",
                        "number of relations must be a number but was '" + relateString + "'");
            }
            relateDocuments(request, response, getRelateNodesOperation(), numberOfRelations, "uuid");
        }

        String linkString = request.getParameter("link");
        if (linkString != null) {
            int numberOfLinks = 0;
            try {
                numberOfLinks = Integer.parseInt(linkString);
            } catch (NumberFormatException e) {
                response.setRenderParameter("message",
                        "number of links must be a number but was '" + linkString + "'");
            }
            relateDocuments(request, response, getLinkNodesOperation(), numberOfLinks, "versionHistory");
        }

        String translateString = request.getParameter("translate");
        if (translateString != null) {
            int numberOfTranslations = 0;
            try {
                numberOfTranslations = Integer.parseInt(translateString);
            } catch (NumberFormatException e) {
                response.setRenderParameter("message",
                        "number of translations must be a number but was '" + translateString + "'");
            }
            relateDocuments(request, response, getTranslateOperation(), numberOfTranslations, "uuid");
        }
    }

    response.setRenderParameter("message",
            "Successfully completed operation in " + (System.currentTimeMillis() - start) + "ms.");
}