Example usage for javax.xml.parsers SAXParserFactory newSAXParser

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

Introduction

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

Prototype


public abstract SAXParser newSAXParser() throws ParserConfigurationException, SAXException;

Source Link

Document

Creates a new instance of a SAXParser using the currently configured factory parameters.

Usage

From source file:org.exist.mongodb.xquery.gridfs.Get.java

/**
 * Parse an byte-array containing (compressed) XML data into an eXist-db
 * document./*from  w  w w .j a v a  2 s  .  c  o m*/
 *
 * @param data Byte array containing the XML data.
 * @return Sequence containing the XML as DocumentImpl
 *
 * @throws XPathException Something bad happened.
 */
private Sequence processXML(XQueryContext xqueryContext, InputStream is) throws XPathException {

    Sequence content = null;
    try {
        final ValidationReport validationReport = new ValidationReport();
        final SAXAdapter adapter = new SAXAdapter(xqueryContext);
        final SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(true);
        final InputSource src = new InputSource(is);
        final SAXParser parser = factory.newSAXParser();
        XMLReader xr = parser.getXMLReader();

        xr.setErrorHandler(validationReport);
        xr.setContentHandler(adapter);
        xr.setProperty(Namespaces.SAX_LEXICAL_HANDLER, adapter);

        xr.parse(src);

        // Cleanup
        IOUtils.closeQuietly(is);

        if (validationReport.isValid()) {
            content = (DocumentImpl) adapter.getDocument();
        } else {
            String txt = String.format("Received document is not valid: %s", validationReport.toString());
            LOG.debug(txt);
            throw new XPathException(txt);
        }

    } catch (SAXException | ParserConfigurationException | IOException ex) {
        LOG.error(ex.getMessage(), ex);
        throw new XPathException(ex.getMessage());

    }

    return content;
}

From source file:org.exist.util.XMLReaderObjectFactory.java

/**
 * Create Xmlreader and setup validation
 *///from w  ww  .j ava 2 s .c om
public static XMLReader createXmlReader(VALIDATION_SETTING validation, GrammarPool grammarPool,
        eXistXMLCatalogResolver resolver) throws ParserConfigurationException, SAXException {

    // Create a xmlreader
    final SAXParserFactory saxFactory = ExistSAXParserFactory.getSAXParserFactory();

    if (validation == VALIDATION_SETTING.AUTO || validation == VALIDATION_SETTING.ENABLED) {
        saxFactory.setValidating(true);
    } else {
        saxFactory.setValidating(false);
    }
    saxFactory.setNamespaceAware(true);

    final SAXParser saxParser = saxFactory.newSAXParser();
    final XMLReader xmlReader = saxParser.getXMLReader();

    // Setup grammar cache
    if (grammarPool != null) {
        setReaderProperty(xmlReader, APACHE_PROPERTIES_INTERNAL_GRAMMARPOOL, grammarPool);
    }

    // Setup xml catalog resolver
    if (resolver != null) {
        setReaderProperty(xmlReader, APACHE_PROPERTIES_ENTITYRESOLVER, resolver);
    }

    return xmlReader;
}

From source file:org.exist.xquery.modules.sql.ExecuteFunction.java

/**
 * evaluate the call to the XQuery execute() function, it is really the main entry point of this class.
 *
 * @param   args             arguments from the execute() function call
 * @param   contextSequence  the Context Sequence to operate on (not used here internally!)
 *
 * @return  A node representing the SQL result set
 *
 * @throws  XPathException  DOCUMENT ME!
 *
 * @see     org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence)
 *//*from  w  w w  . j a va 2  s.c  o m*/
@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    // was a connection and SQL statement specified?
    if (args[0].isEmpty() || args[1].isEmpty()) {
        return (Sequence.EMPTY_SEQUENCE);
    }

    // get the Connection
    long connectionUID = ((IntegerValue) args[0].itemAt(0)).getLong();
    Connection con = SQLModule.retrieveConnection(context, connectionUID);

    if (con == null) {
        return (Sequence.EMPTY_SEQUENCE);
    }

    boolean preparedStmt = false;

    //setup the SQL statement
    String sql = null;
    Statement stmt = null;
    boolean executeResult = false;
    ResultSet rs = null;

    try {
        boolean makeNodeFromColumnName = false;
        MemTreeBuilder builder = context.getDocumentBuilder();
        int iRow = 0;

        //SQL or PreparedStatement?
        if (args.length == 3) {

            // get the SQL statement
            sql = args[1].getStringValue();
            stmt = con.createStatement();
            makeNodeFromColumnName = ((BooleanValue) args[2].itemAt(0)).effectiveBooleanValue();

            //execute the statement
            executeResult = stmt.execute(sql);

        } else if (args.length == 4) {

            preparedStmt = true;

            //get the prepared statement
            long statementUID = ((IntegerValue) args[1].itemAt(0)).getLong();
            PreparedStatementWithSQL stmtWithSQL = SQLModule.retrievePreparedStatement(context, statementUID);
            sql = stmtWithSQL.getSql();
            stmt = stmtWithSQL.getStmt();
            makeNodeFromColumnName = ((BooleanValue) args[3].itemAt(0)).effectiveBooleanValue();

            if (!args[2].isEmpty()) {
                setParametersOnPreparedStatement(stmt, (Element) args[2].itemAt(0));
            }

            //execute the prepared statement
            executeResult = ((PreparedStatement) stmt).execute();
        } else {
            //TODO throw exception
        }

        // DW: stmt can be null ?

        // execute the query statement
        if (executeResult) {
            /* SQL Query returned results */

            // iterate through the result set building an XML document
            rs = stmt.getResultSet();
            ResultSetMetaData rsmd = rs.getMetaData();
            int iColumns = rsmd.getColumnCount();

            builder.startDocument();

            builder.startElement(new QName("result", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);
            builder.addAttribute(new QName("count", null, null), String.valueOf(-1));

            while (rs.next()) {
                builder.startElement(new QName("row", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);
                builder.addAttribute(new QName("index", null, null), String.valueOf(rs.getRow()));

                // get each tuple in the row
                for (int i = 0; i < iColumns; i++) {
                    String columnName = rsmd.getColumnLabel(i + 1);

                    if (columnName != null) {

                        String colElement = "field";

                        if (makeNodeFromColumnName && columnName.length() > 0) {
                            // use column names as the XML node

                            /**
                             * Spaces in column names are replaced with
                             * underscore's
                             */
                            colElement = SQLUtils.escapeXmlAttr(columnName.replace(' ', '_'));
                        }

                        builder.startElement(new QName(colElement, SQLModule.NAMESPACE_URI, SQLModule.PREFIX),
                                null);

                        if (!makeNodeFromColumnName || columnName.length() <= 0) {
                            String name;

                            if (columnName.length() > 0) {
                                name = SQLUtils.escapeXmlAttr(columnName);
                            } else {
                                name = "Column: " + String.valueOf(i + 1);
                            }

                            builder.addAttribute(new QName("name", null, null), name);
                        }

                        builder.addAttribute(
                                new QName(TYPE_ATTRIBUTE_NAME, SQLModule.NAMESPACE_URI, SQLModule.PREFIX),
                                rsmd.getColumnTypeName(i + 1));
                        builder.addAttribute(new QName(TYPE_ATTRIBUTE_NAME, Namespaces.SCHEMA_NS, "xs"),
                                Type.getTypeName(SQLUtils.sqlTypeToXMLType(rsmd.getColumnType(i + 1))));

                        //get the content
                        if (rsmd.getColumnType(i + 1) == Types.SQLXML) {
                            //parse sqlxml value
                            try {
                                final SQLXML sqlXml = rs.getSQLXML(i + 1);

                                if (rs.wasNull()) {
                                    // Add a null indicator attribute if the value was SQL Null
                                    builder.addAttribute(
                                            new QName("null", SQLModule.NAMESPACE_URI, SQLModule.PREFIX),
                                            "true");
                                } else {

                                    SAXParserFactory factory = SAXParserFactory.newInstance();
                                    factory.setNamespaceAware(true);
                                    InputSource src = new InputSource(sqlXml.getCharacterStream());
                                    SAXParser parser = factory.newSAXParser();
                                    XMLReader xr = parser.getXMLReader();

                                    SAXAdapter adapter = new AppendingSAXAdapter(builder);
                                    xr.setContentHandler(adapter);
                                    xr.setProperty(Namespaces.SAX_LEXICAL_HANDLER, adapter);
                                    xr.parse(src);
                                }
                            } catch (Exception e) {
                                throw new XPathException(
                                        "Could not parse column of type SQLXML: " + e.getMessage(), e);
                            }
                        } else {
                            //otherwise assume string value
                            final String colValue = rs.getString(i + 1);

                            if (rs.wasNull()) {
                                // Add a null indicator attribute if the value was SQL Null
                                builder.addAttribute(
                                        new QName("null", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), "true");
                            } else {
                                if (colValue != null) {
                                    builder.characters(SQLUtils.escapeXmlText(colValue));
                                }
                            }
                        }

                        builder.endElement();
                    }
                }

                builder.endElement();
                iRow++;
            }

            builder.endElement();
        } else {
            /* SQL Query performed updates */

            builder.startDocument();

            builder.startElement(new QName("result", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);
            builder.addAttribute(new QName("updateCount", null, null), String.valueOf(stmt.getUpdateCount()));
            builder.endElement();
        }

        // Change the root element count attribute to have the correct value
        NodeValue node = (NodeValue) builder.getDocument().getDocumentElement();
        Node count = node.getNode().getAttributes().getNamedItem("count");

        if (count != null) {
            count.setNodeValue(String.valueOf(iRow));
        }

        builder.endDocument();

        // return the XML result set
        return (node);

    } catch (SQLException sqle) {
        LOG.error("sql:execute() Caught SQLException \"" + sqle.getMessage() + "\" for SQL: \"" + sql + "\"",
                sqle);

        //return details about the SQLException
        MemTreeBuilder builder = context.getDocumentBuilder();

        builder.startDocument();
        builder.startElement(new QName("exception", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);

        boolean recoverable = false;

        if (sqle instanceof SQLRecoverableException) {
            recoverable = true;
        }
        builder.addAttribute(new QName("recoverable", null, null), String.valueOf(recoverable));

        builder.startElement(new QName("state", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);
        builder.characters(sqle.getSQLState());
        builder.endElement();

        builder.startElement(new QName("message", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);

        String state = sqle.getMessage();

        if (state != null) {
            builder.characters(state);
        }

        builder.endElement();

        builder.startElement(new QName("stack-trace", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);
        ByteArrayOutputStream bufStackTrace = new ByteArrayOutputStream();
        sqle.printStackTrace(new PrintStream(bufStackTrace));
        builder.characters(new String(bufStackTrace.toByteArray()));
        builder.endElement();

        builder.startElement(new QName("sql", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);
        builder.characters(SQLUtils.escapeXmlText(sql));
        builder.endElement();

        if (stmt instanceof PreparedStatement) {
            Element parametersElement = (Element) args[2].itemAt(0);

            if (parametersElement.getNamespaceURI().equals(SQLModule.NAMESPACE_URI)
                    && parametersElement.getLocalName().equals(PARAMETERS_ELEMENT_NAME)) {
                NodeList paramElements = parametersElement.getElementsByTagNameNS(SQLModule.NAMESPACE_URI,
                        PARAM_ELEMENT_NAME);

                builder.startElement(
                        new QName(PARAMETERS_ELEMENT_NAME, SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);

                for (int i = 0; i < paramElements.getLength(); i++) {
                    Element param = ((Element) paramElements.item(i));
                    String value = param.getFirstChild().getNodeValue();
                    String type = param.getAttributeNS(SQLModule.NAMESPACE_URI, TYPE_ATTRIBUTE_NAME);

                    builder.startElement(
                            new QName(PARAM_ELEMENT_NAME, SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);

                    builder.addAttribute(
                            new QName(TYPE_ATTRIBUTE_NAME, SQLModule.NAMESPACE_URI, SQLModule.PREFIX), type);
                    builder.characters(SQLUtils.escapeXmlText(value));

                    builder.endElement();
                }

                builder.endElement();
            }
        }

        builder.startElement(new QName("xquery", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);
        builder.addAttribute(new QName("line", null, null), String.valueOf(getLine()));
        builder.addAttribute(new QName("column", null, null), String.valueOf(getColumn()));
        builder.endElement();

        builder.endElement();
        builder.endDocument();

        return ((NodeValue) builder.getDocument().getDocumentElement());
    } finally {

        // close any record set or statement
        if (rs != null) {

            try {
                rs.close();
            } catch (SQLException se) {
                LOG.warn("Unable to cleanup JDBC results", se);
            }
            rs = null;
        }

        if (!preparedStmt && stmt != null) {

            try {
                stmt.close();
            } catch (SQLException se) {
                LOG.warn("Unable to cleanup JDBC results", se);
            }
            stmt = null;
        }

    }
}

From source file:org.exist.xquery.xproc.ProcessFunction.java

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

    if (args[0].isEmpty()) {
        return Sequence.EMPTY_SEQUENCE;
    }/*from   w  w  w . j  av a 2 s  . co m*/

    //        Sequence input = getArgument(0).eval(contextSequence, contextItem);

    UserArgs userArgs = new UserArgs();

    Sequence pipe = args[0];

    if (Type.subTypeOf(pipe.getItemType(), Type.NODE)) {

        if (pipe.getItemCount() != 1) {
            throw new XPathException(this, "Pipeline must have just ONE and only ONE element.");
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        OutputStreamWriter osw;
        try {
            osw = new OutputStreamWriter(baos, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new XPathException(this, "Internal error");
        }

        XMLWriter xmlWriter = new XMLWriter(osw);

        SAXSerializer sax = new SAXSerializer();

        sax.setReceiver(xmlWriter);

        try {
            pipe.itemAt(0).toSAX(context.getBroker(), sax, new Properties());
            osw.flush();
            osw.close();
        } catch (Exception e) {
            throw new XPathException(this, e);
        }

        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        userArgs.setPipeline(bais, XmldbURI.LOCAL_DB + "/");

    } else {
        userArgs.setPipeline(pipe.getStringValue());
    }

    InputStream defaultIn = null;

    //prepare primary input
    if (args.length > 2) {
        Sequence input = args[1];

        if (Type.subTypeOf(input.getItemType(), Type.NODE)) {

            if (input.getItemCount() != 1) {
                throw new XPathException(this, "Primary input must have just ONE and only ONE element.");
            }

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            OutputStreamWriter osw;
            try {
                osw = new OutputStreamWriter(baos, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new XPathException(this, "Internal error");
            }

            XMLWriter xmlWriter = new XMLWriter(osw);

            SAXSerializer sax = new SAXSerializer();

            sax.setReceiver(xmlWriter);

            try {
                input.itemAt(0).toSAX(context.getBroker(), sax, new Properties());
                osw.flush();
                osw.close();
            } catch (Exception e) {
                throw new XPathException(this, e);
            }

            defaultIn = new ByteArrayInputStream(baos.toByteArray());

        } else {
            defaultIn = new ByteArrayInputStream(input.getStringValue().getBytes());
        }
    }

    //parse options
    if (args.length > 2) {
        parseOptions(userArgs, args[2]);
    } else if (args.length > 1) {
        parseOptions(userArgs, args[1]);
    }

    String outputResult;
    try {

        //getContext().getModuleLoadPath();

        URI staticBaseURI = null;

        Object key = getContext().getSource().getKey();
        if (key instanceof XmldbURI) {

            String uri = ((XmldbURI) key).removeLastSegment().toString();

            if (!uri.endsWith("/")) {
                uri += "/";
            }

            staticBaseURI = new URI("xmldb", "", uri, null);

        } else {

            String uri = getContext().getModuleLoadPath();
            if (uri == null || uri.isEmpty()) {
                staticBaseURI = new URI(XmldbURI.LOCAL_DB + "/");

            } else {

                if (uri.startsWith(XmldbURI.EMBEDDED_SERVER_URI_PREFIX)) {
                    uri = uri.substring(XmldbURI.EMBEDDED_SERVER_URI_PREFIX.length());
                }
                if (!uri.endsWith("/")) {
                    uri += "/";
                }

                staticBaseURI = new URI("xmldb", "", uri, null);
            }
        }

        outputResult = XProcRunner.run(staticBaseURI, context.getBroker(), userArgs, defaultIn);

    } catch (Exception e) {
        e.printStackTrace();
        throw new XPathException(this, e);
    }

    if (outputResult == null || outputResult.isEmpty()) {
        return Sequence.EMPTY_SEQUENCE;
    }

    StringReader reader = new StringReader(outputResult);
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(true);
        InputSource src = new InputSource(reader);

        XMLReader xr = null;

        if (xr == null) {
            SAXParser parser = factory.newSAXParser();
            xr = parser.getXMLReader();
        }

        SAXAdapter adapter = new SAXAdapter(context);
        xr.setContentHandler(adapter);
        xr.setProperty(Namespaces.SAX_LEXICAL_HANDLER, adapter);
        xr.parse(src);

        return (DocumentImpl) adapter.getDocument();
    } catch (ParserConfigurationException e) {
        throw new XPathException(this, "Error while constructing XML parser: " + e.getMessage(), e);
    } catch (SAXException e) {
        throw new XPathException(this, "Error while parsing XML: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new XPathException(this, "Error while parsing XML: " + e.getMessage(), e);
    }
}

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

private void listFolder(DefaultHandler handler, String folder) throws Exception {
    synchronized (this) {
        if (!isConnected()) {
            throw new IllegalStateException("Not connected.");
        }//  w ww. j a  v a  2s  .co m
        HttpClient client = getClient();
        ExchangeMethod op = new ExchangeMethod(SEARCH_METHOD, folder);
        op.setHeader("Content-Type", XML_CONTENT_TYPE);
        if (limit > 0)
            op.setHeader("Range", "rows=0-" + limit);
        op.setHeader("Brief", "t");

        /* Mirco: Manage of custom query */
        if ((filterLastCheck == null || "".equals(filterLastCheck))
                && (filterFrom == null || "".equals(filterFrom))
                && (filterNotFrom == null || "".equals(filterNotFrom))
                && (filterTo == null || "".equals(filterTo))) {
            op.setRequestEntity(unfiltered ? createAllInboxEntity() : createUnreadInboxEntity());
        } else {
            op.setRequestEntity(
                    createCustomInboxEntity(unfiltered, filterLastCheck, filterFrom, filterNotFrom, filterTo));
        }
        InputStream stream = null;
        try {
            int status = client.executeMethod(op);
            stream = op.getResponseBodyAsStream();
            if (status >= 300) {
                throw new IllegalStateException("Unable to obtain " + folder + ".");
            }
            SAXParserFactory spf = SAXParserFactory.newInstance();
            spf.setNamespaceAware(true);
            SAXParser parser = spf.newSAXParser();
            parser.parse(stream, handler);
            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.exjello.mail.Exchange2003Connection.java

private void findInbox() throws Exception {
    inbox = null;/* w  w w . j  a v  a 2s.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)) {
                    Exchange2003Connection.this.inbox = content.toString();
                } else if ("drafts".equals(localName)) {
                    Exchange2003Connection.this.drafts = content.toString();
                } else if ("sentitems".equals(localName)) {
                    Exchange2003Connection.this.sentitems = content.toString();
                } else if ("outbox".equals(localName)) {
                    Exchange2003Connection.this.outbox = content.toString();
                } else if ("sendmsg".equals(localName)) {
                    Exchange2003Connection.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.exjello.mail.ExchangeConnection.java

private void findInbox() throws Exception {
    inbox = null;//from  ww w  .java  2 s . 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.formix.dsx.XmlElement.java

private static SAXParser createSaxParser()
        throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException, SAXException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(false);/*from w ww  .  j  av  a 2 s .  c  o m*/

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

    SAXParser parser = factory.newSAXParser();
    return parser;
}

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);//  ww  w. j a  v  a2s.  c  om
    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.geosdi.geoplatform.services.GPWMSServiceImpl.java

/**
 * @param serverURL/*from   www .j  ava  2s . com*/
 * @param layerName
 * @return {@link GPLayerTypeResponse}
 * @throws Exception
 */
@Override
public GPLayerTypeResponse getLayerType(String serverURL, String layerName) throws Exception {
    checkArgument((serverURL != null) && !(serverURL.trim().isEmpty()),
            "The Parameter serverURL must not be null or an empty string.");
    checkArgument((layerName != null) && !(layerName.trim().isEmpty()),
            "The Parameter layerName must not be null or an empty string.");
    logger.debug(
            "###########################TRYING TO RETRIEVE LAYER_TYPE with serverURL : {} - layerName : {]\n",
            serverURL, layerName);
    int index = serverURL.indexOf("?");
    if (index != -1) {
        serverURL = serverURL.substring(0, index);
    }
    String decribeLayerUrl = serverURL.concat("?service=WMS&request=DescribeLayer&version=1.1.1&layers=")
            .concat(layerName);
    logger.info("#########################DESCRIBE_LAYER_URL : {}\n", decribeLayerUrl);
    try {
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(decribeLayerUrl);
        httpClient.executeMethod(getMethod);
        InputStream inputStream = getMethod.getResponseBodyAsStream();
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", FALSE);
        spf.setFeature("http://xml.org/sax/features/validation", FALSE);

        XMLReader xmlReader = spf.newSAXParser().getXMLReader();
        InputSource inputSource = new InputSource(new InputStreamReader(inputStream));
        SAXSource source = new SAXSource(xmlReader, inputSource);
        JAXBContext jaxbContext = JAXBContext.newInstance(WMSDescribeLayerResponse.class);
        WMSDescribeLayerResponse describeLayerResponse = (WMSDescribeLayerResponse) jaxbContext
                .createUnmarshaller().unmarshal(source);
        return new GPLayerTypeResponse(describeLayerResponse);
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new ServerInternalFault(ex.getMessage());
    }
}