List of usage examples for javax.xml.parsers SAXParser getXMLReader
public abstract org.xml.sax.XMLReader getXMLReader() throws SAXException;
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) */// w w w.jav a 2s . c om @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 a v a2 s . com*/ // 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.hw.parlance.ParlanceActivity.java
/** * Method to parse XML response from Yahoo URL and add markers of restaurants on the map *///from w w w .jav a2s . co m private synchronized void xmlParsing(String XMLResponse) { try { URLConnection conn = new URL(XMLResponse).openConnection(); conn.setConnectTimeout(50000); conn.setReadTimeout(50000); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); ItemHandler itemHandler = new ItemHandler(); xr.setContentHandler(itemHandler); xr.parse(new InputSource(conn.getInputStream())); _itemAdapter.arr = itemHandler.getList(); for (int index = 0; index < _itemAdapter.arr.size(); index++) { Marker temp_marker = mMap.addMarker(new MarkerOptions() .position(new LatLng(Double.parseDouble(_itemAdapter.arr.get(index).getLat()), Double.parseDouble(_itemAdapter.arr.get(index).getLon()))) .title(_itemAdapter.arr.get(index).getName()) .icon(BitmapDescriptorFactory.fromResource(numMarkerIcon[index]))); this._markList.add(temp_marker); } _itemAdapter.notifyDataSetChanged(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.intalio.tempo.workflow.wds.core.xforms.XFormsProcessor.java
/** * Process an XForms document.// w ww . j a v a 2 s . c o m * <ul> * <li>If the model schema is specified as a relative URI, it is changed to comply to the form URI, * e.g. if a form is stored at (oxf:/)my/uri/form1.xform and it specified "form1.xsd" * as its model schema, then the value of the "schema" attribute of the "xforms:model" * element will be rewritten as: "oxf:/my/uri/form1.xsd"</li> * <li>The XForms document is reformatted in a "pretty-print" way.</li> * </ul> */ @SuppressWarnings("deprecation") public static Item processXForm(final String itemUri, InputStream inputStream) throws IOException, ParserConfigurationException, SAXException { if (LOG.isDebugEnabled()) LOG.debug("Processing " + itemUri); StringWriter out = new StringWriter(); SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); OutputFormat format = new OutputFormat(); format.setEncoding(CharEncoding.UTF_8); format.setOmitXMLDeclaration(false); format.setOmitComments(false); format.setPreserveSpace(true); SchemaURLRewriter ser = new SchemaURLRewriter(out, format, itemUri); XMLReader reader = parser.getXMLReader(); reader.setContentHandler(ser); reader.parse(new InputSource(inputStream)); return new Item(itemUri, XFORMS_CONTENT_TYPE, out.toString().getBytes(CharEncoding.UTF_8)); }
From source file:org.jbpm.jpdl.internal.convert.Jpdl3ConverterParser.java
public static XMLReader createXmlReader() throws Exception { SAXParser saxParser = saxParserFactory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); try {// w w w.ja v a 2 s. c o m saxParser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); } catch (SAXException e) { log.warn("couldn't set schema language property", e); } try { saxParser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", getSchemaSource()); } catch (SAXException e) { log.warn("couldn't set schema source property", e); } try { xmlReader.setFeature("http://apache.org/xml/features/validation/dynamic", true); } catch (SAXException e) { log.warn("couldn't set dynamic validation feature", e); } return xmlReader; }
From source file:org.jbpm.jpdl.xml.JpdlParser.java
public static XMLReader createXmlReader() throws Exception { SAXParser saxParser = saxParserFactory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); try {/* w w w. ja v a2 s . c o m*/ saxParser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); } catch (SAXException e) { log.warn( "couldn't set xml parser property 'http://java.sun.com/xml/jaxp/properties/schemaLanguage' to 'http://www.w3.org/2001/XMLSchema'", e); } try { saxParser.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation", "http://jbpm.org/3/jpdl http://jbpm.org/jpdl-3.0.xsd " + "urn:jbpm.org:jpdl-3.0 http://jbpm.org/jpdl-3.0.xsd " + "urn:jbpm.org:jpdl-3.1 http://jbpm.org/jpdl-3.1.xsd " + "urn:jbpm.org:jpdl-3.2 http://jbpm.org/jpdl-3.2.xsd"); } catch (SAXException e) { log.warn( "couldn't set xml parser property 'http://apache.org/xml/properties/schema/external-schemaLocation'", e); } try { xmlReader.setFeature("http://apache.org/xml/features/validation/dynamic", true); } catch (SAXException e) { log.warn("couldn't set xml parser feature 'http://apache.org/xml/features/validation/dynamic'", e); } return xmlReader; }
From source file:org.jlibrary.core.search.extraction.XMLExtractor.java
public XMLExtractor() throws ExtractionException { try {/*from w ww . j a v a 2s. c o m*/ SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setValidating(false); SAXParser saxParser = saxParserFactory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setFeature("http://xml.org/sax/features/validation", false); xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); parser = new XMLParser(xmlReader); } catch (Exception e) { throw new ExtractionException(e); } }
From source file:org.kalypso.gml.test.GmlParsingTester.java
protected GMLWorkspace parseGml(final InputStream is, final URL context) throws ParserConfigurationException, SAXException, IOException, GMLException { final SAXParser saxParser = m_saxFactory.newSAXParser(); // make namespace-prefxes visible to content handler // used to allow necessary schemas from gml document // saxParser.setProperty( "http://xml.org/sax/features/namespace-prefixes", Boolean.TRUE ); final XMLReader reader = saxParser.getXMLReader(); // TODO: also set an error handler here // TODO: use progress-monitors to show progress and let the user cancel parsing final GMLorExceptionContentHandler exceptionHandler = new GMLorExceptionContentHandler(reader, null, context, null);// w w w . java 2 s . c o m reader.setContentHandler(exceptionHandler); final InputSource inputSource = new InputSource(is); reader.parse(inputSource); return exceptionHandler.getWorkspace(); }
From source file:org.kalypso.gmlschema.types.AbstractOldFormatMarshallingTypeHandlerAdapter.java
/** * @see org.kalypso.gmlschema.types.IMarshallingTypeHandler#marshal(java.lang.Object, org.xml.sax.ContentHandler, * org.xml.sax.ext.LexicalHandler, java.net.URL) *//*from www . j av a 2 s. co m*/ @Override public void marshal(final Object value, final XMLReader reader, final URL context, final String gmlVersion) throws SAXException { try { final Document document = m_builder.newDocument(); final Node node = marshall(value, document, context); // value is encoded in xml in document object final StringWriter writer = new StringWriter(); // REMARK: we do not write the dom formatted here (argument false), because later the // content handler will probably do the formatting (IndentContentHandler). If we format here, we will get empty // lines later. XMLHelper.writeDOM(node, "UTF-8", writer, false); //$NON-NLS-1$ IOUtils.closeQuietly(writer); // value is encoded in string final String xmlString = writer.toString(); final String xmlStringNoHeader = XMLUtilities.removeXMLHeader(xmlString); final InputSource input = new InputSource(new StringReader(xmlStringNoHeader)); SAX_FACTORY.setNamespaceAware(true); final SAXParser saxParser = SAX_FACTORY.newSAXParser(); final XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setContentHandler(reader.getContentHandler()); xmlReader.parse(input); } catch (final SAXException e) { throw e; } catch (final Exception e) { throw new SAXException(e); } }
From source file:org.kalypso.gmlschema.types.SimpleDOMTypeHandler.java
@Override public void marshal(final Object value, final XMLReader reader, final URL context, final String gmlVersion) throws SAXException { try {/*from w w w . ja va 2 s. c om*/ final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document = builder.newDocument(); final Node node = internalMarshall(value, document, context); // value is encoded in xml in document object final StringWriter writer = new StringWriter(); XMLHelper.writeDOM(node, "UTF-8", writer); //$NON-NLS-1$ IOUtils.closeQuietly(writer); // value is encoded in string final String xmlString = writer.toString(); final InputSource input = new InputSource(new StringReader(xmlString)); final SAXParserFactory saxFac = SAXParserFactory.newInstance(); saxFac.setNamespaceAware(true); final SAXParser saxParser = saxFac.newSAXParser(); final XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setContentHandler(reader.getContentHandler()); xmlReader.parse(input); } catch (final SAXException saxe) { throw saxe; } catch (final Exception e) { throw new SAXException(e); } }