List of usage examples for javax.xml.stream XMLInputFactory createXMLStreamReader
public abstract XMLStreamReader createXMLStreamReader(java.io.InputStream stream) throws XMLStreamException;
From source file:org.orbisgis.core.layerModel.mapcatalog.RemoteMapCatalog.java
/** * Request the workspaces synchronously. * This call may take a long time to execute. * @return A list of workspaces/* w ww. j a va 2 s.co m*/ * @throws IOException The request fail */ public List<Workspace> getWorkspaces() throws IOException { List<Workspace> workspaces = new ArrayList<Workspace>(); // Construct request URL requestWorkspacesURL = new URL(RemoteCommons.getUrlWorkspaceList(cParams)); // Establish connection HttpURLConnection connection = (HttpURLConnection) requestWorkspacesURL.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(cParams.getConnectionTimeOut()); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException(I18N.tr("HTTP Error {0} message : {1}", connection.getResponseCode(), connection.getResponseMessage())); } // Read the response content BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream(), RemoteCommons.getConnectionCharset(connection))); //"Content-Type" "text/xml; charset=utf-8" XMLInputFactory factory = XMLInputFactory.newInstance(); // Parse Data XMLStreamReader parser; try { parser = factory.createXMLStreamReader(in); // Fill workspaces parseXML(workspaces, parser); parser.close(); } catch (XMLStreamException ex) { throw new IOException(I18N.tr("Invalid XML content"), ex); } return workspaces; }
From source file:org.orbisgis.core.layerModel.mapcatalog.Workspace.java
/** * Add a mapcontext to the workspace/* w ww. j ava 2 s.c o m*/ * @param mapContext * @return The ID of the published map context * @throws IOException */ public int publishMapContext(MapContext mapContext, Integer mapContextId) throws IOException { // Construct request URL requestWorkspacesURL; if (mapContextId == null) { // Post a new map context requestWorkspacesURL = new URL(RemoteCommons.getUrlPostContext(cParams, workspaceName)); } else { // Update an existing map context requestWorkspacesURL = new URL(RemoteCommons.getUrlUpdateContext(cParams, workspaceName, mapContextId)); } // Establish connection HttpURLConnection connection = (HttpURLConnection) requestWorkspacesURL.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setConnectTimeout(cParams.getConnectionTimeOut()); connection.addRequestProperty("Content-Type", "text/xml"); OutputStream out = connection.getOutputStream(); mapContext.write(out); // Send map context out.close(); // Get response int responseCode = connection.getResponseCode(); if (!((responseCode == HttpURLConnection.HTTP_CREATED && mapContextId == null) || (responseCode == HttpURLConnection.HTTP_OK && mapContextId != null))) { throw new IOException(I18N.tr("HTTP Error {0} message : {1} with the URL {2}", connection.getResponseCode(), connection.getResponseMessage(), requestWorkspacesURL)); } if (mapContextId == null) { // Get response content BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), RemoteCommons.getConnectionCharset(connection))); XMLInputFactory factory = XMLInputFactory.newInstance(); // Parse Data XMLStreamReader parser; try { parser = factory.createXMLStreamReader(in); // Fill workspaces int resId = parsePublishResponse(parser); parser.close(); return resId; } catch (XMLStreamException ex) { throw new IOException(I18N.tr("Invalid XML content"), ex); } } else { return mapContextId; } }
From source file:org.orbisgis.core.layerModel.mapcatalog.Workspace.java
/** * Retrieve the list of MapContext linked with this workspace * This call may take a long time to execute. * @return/* ww w.j av a 2s. c o m*/ * @throws IOException Connection failure */ public List<RemoteMapContext> getMapContextList() throws IOException { List<RemoteMapContext> contextList = new ArrayList<RemoteMapContext>(); // Construct request URL requestWorkspacesURL = new URL(RemoteCommons.getUrlContextList(cParams, workspaceName)); // Establish connection HttpURLConnection connection = (HttpURLConnection) requestWorkspacesURL.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(cParams.getConnectionTimeOut()); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException(I18N.tr("HTTP Error {0} message : {1}", connection.getResponseCode(), connection.getResponseMessage())); } XMLInputFactory factory = XMLInputFactory.newInstance(); // Read the response content BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream(), RemoteCommons.getConnectionCharset(connection))); // Parse Data XMLStreamReader parser; try { parser = factory.createXMLStreamReader(in); // Fill workspaces parseXML(contextList, parser); parser.close(); } catch (XMLStreamException ex) { throw new IOException(I18N.tr("Invalid XML content"), ex); } return contextList; }
From source file:org.pentaho.di.trans.steps.excelinput.staxpoi.StaxPoiSheet.java
public StaxPoiSheet(XSSFReader reader, String sheetName, String sheetID) throws InvalidFormatException, IOException, XMLStreamException { this.sheetName = sheetName; xssfReader = reader;/*from w w w . j av a 2 s .c om*/ sheetId = sheetID; sst = reader.getSharedStringsTable(); styles = reader.getStylesTable(); sheetStream = reader.getSheet(sheetID); XMLInputFactory factory = XMLInputFactory.newInstance(); sheetReader = factory.createXMLStreamReader(sheetStream); headerRow = new ArrayList<String>(); while (sheetReader.hasNext()) { int event = sheetReader.next(); if (event == XMLStreamConstants.START_ELEMENT && sheetReader.getLocalName().equals("dimension")) { String dim = sheetReader.getAttributeValue(null, "ref"); // empty sheets have dimension with no range if (StringUtils.contains(dim, ':')) { dim = dim.split(":")[1]; numRows = StaxUtil.extractRowNumber(dim); numCols = StaxUtil.extractColumnNumber(dim); } } if (event == XMLStreamConstants.START_ELEMENT && sheetReader.getLocalName().equals("row")) { currentRow = Integer.parseInt(sheetReader.getAttributeValue(null, "r")); firstRow = currentRow; // calculate the number of columns in the header row while (sheetReader.hasNext()) { event = sheetReader.next(); if (event == XMLStreamConstants.END_ELEMENT && sheetReader.getLocalName().equals("row")) { // if the row has ended, break the inner while loop break; } if (event == XMLStreamConstants.START_ELEMENT && sheetReader.getLocalName().equals("c")) { String attributeValue = sheetReader.getAttributeValue(null, "t"); if (attributeValue != null && attributeValue.equals("s")) { // only if the type of the cell is string, we continue while (sheetReader.hasNext()) { event = sheetReader.next(); if (event == XMLStreamConstants.START_ELEMENT && sheetReader.getLocalName().equals("v")) { int idx = Integer.parseInt(sheetReader.getElementText()); String content = new XSSFRichTextString(sst.getEntryAt(idx)).toString(); headerRow.add(content); break; } } } else { break; } } } // we have parsed the header row break; } } }
From source file:org.pentaho.di.trans.steps.excelinput.staxpoi.StaxPoiSheet.java
private void resetSheetReader() throws IOException, XMLStreamException, InvalidFormatException { sheetReader.close();//w ww .j a va 2 s .c o m sheetStream.close(); sheetStream = xssfReader.getSheet(sheetId); XMLInputFactory factory = XMLInputFactory.newInstance(); sheetReader = factory.createXMLStreamReader(sheetStream); }
From source file:org.pentaho.di.trans.steps.webservices.WebService.java
private void compatibleProcessRows(InputStream anXml, Object[] rowData, RowMetaInterface rowMeta, boolean ignoreNamespacePrefix, String encoding) throws KettleException { // First we should get the complete string // The problem is that the string can contain XML or any other format such as HTML saying the service is no longer // available. // We're talking about a WEB service here. // As such, to keep the original parsing scheme, we first read the content. // Then we create an input stream from the content again. // It's elaborate, but that way we can report on the failure more correctly. ////from w w w. ja v a 2 s . co m String response = readStringFromInputStream(anXml, encoding); // Create a new reader to feed into the XML Input Factory below... // StringReader stringReader = new StringReader(response.toString()); // TODO Very empirical : see if we can do something better here try { XMLInputFactory vFactory = XMLInputFactory.newInstance(); XMLStreamReader vReader = vFactory.createXMLStreamReader(stringReader); Object[] outputRowData = RowDataUtil.allocateRowData(data.outputRowMeta.size()); int outputIndex = 0; boolean processing = false; boolean oneValueRowProcessing = false; for (int event = vReader.next(); vReader.hasNext(); event = vReader.next()) { switch (event) { case XMLStreamConstants.START_ELEMENT: // Start new code // START_ELEMENT= 1 // if (log.isRowLevel()) { logRowlevel("START_ELEMENT / " + vReader.getAttributeCount() + " / " + vReader.getNamespaceCount()); } // If we start the xml element named like the return type, // we start a new row // if (log.isRowLevel()) { logRowlevel("vReader.getLocalName = " + vReader.getLocalName()); } if (Const.isEmpty(meta.getOutFieldArgumentName())) { // getOutFieldArgumentName() == null if (oneValueRowProcessing) { WebServiceField field = meta.getFieldOutFromWsName(vReader.getLocalName(), ignoreNamespacePrefix); if (field != null) { outputRowData[outputIndex++] = getValue(vReader.getElementText(), field); putRow(data.outputRowMeta, outputRowData); oneValueRowProcessing = false; } else { if (meta.getOutFieldContainerName().equals(vReader.getLocalName())) { // meta.getOutFieldContainerName() = vReader.getLocalName() if (log.isRowLevel()) { logRowlevel("OutFieldContainerName = " + meta.getOutFieldContainerName()); } oneValueRowProcessing = true; } } } } else { // getOutFieldArgumentName() != null if (log.isRowLevel()) { logRowlevel("OutFieldArgumentName = " + meta.getOutFieldArgumentName()); } if (meta.getOutFieldArgumentName().equals(vReader.getLocalName())) { if (log.isRowLevel()) { logRowlevel("vReader.getLocalName = " + vReader.getLocalName()); } if (log.isRowLevel()) { logRowlevel("OutFieldArgumentName = "); } if (processing) { WebServiceField field = meta.getFieldOutFromWsName(vReader.getLocalName(), ignoreNamespacePrefix); if (field != null) { int index = data.outputRowMeta.indexOfValue(field.getName()); if (index >= 0) { outputRowData[index] = getValue(vReader.getElementText(), field); } } processing = false; } else { WebServiceField field = meta.getFieldOutFromWsName(vReader.getLocalName(), ignoreNamespacePrefix); if (meta.getFieldsOut().size() == 1 && field != null) { // This can be either a simple return element, or a complex type... // try { if (meta.isPassingInputData()) { for (int i = 0; i < rowMeta.getValueMetaList().size(); i++) { ValueMetaInterface valueMeta = getInputRowMeta().getValueMeta(i); outputRowData[outputIndex++] = valueMeta.cloneValueData(rowData[i]); } } outputRowData[outputIndex++] = getValue(vReader.getElementText(), field); putRow(data.outputRowMeta, outputRowData); } catch (WstxParsingException e) { throw new KettleStepException("Unable to get value for field [" + field.getName() + "]. Verify that this is not a complex data type by looking at the response XML.", e); } } else { for (WebServiceField curField : meta.getFieldsOut()) { if (!Const.isEmpty(curField.getName())) { outputRowData[outputIndex++] = getValue(vReader.getElementText(), curField); } } processing = true; } } } else { if (log.isRowLevel()) { logRowlevel("vReader.getLocalName = " + vReader.getLocalName()); } if (log.isRowLevel()) { logRowlevel("OutFieldArgumentName = " + meta.getOutFieldArgumentName()); } } } break; case XMLStreamConstants.END_ELEMENT: // END_ELEMENT= 2 if (log.isRowLevel()) { logRowlevel("END_ELEMENT"); } // If we end the xml element named as the return type, we // finish a row if ((meta.getOutFieldArgumentName() == null && meta.getOperationName().equals(vReader.getLocalName()))) { oneValueRowProcessing = false; } else if (meta.getOutFieldArgumentName() != null && meta.getOutFieldArgumentName().equals(vReader.getLocalName())) { putRow(data.outputRowMeta, outputRowData); processing = false; } break; case XMLStreamConstants.PROCESSING_INSTRUCTION: // PROCESSING_INSTRUCTION= 3 if (log.isRowLevel()) { logRowlevel("PROCESSING_INSTRUCTION"); } break; case XMLStreamConstants.CHARACTERS: // CHARACTERS= 4 if (log.isRowLevel()) { logRowlevel("CHARACTERS"); } break; case XMLStreamConstants.COMMENT: // COMMENT= 5 if (log.isRowLevel()) { logRowlevel("COMMENT"); } break; case XMLStreamConstants.SPACE: // PROCESSING_INSTRUCTION= 6 if (log.isRowLevel()) { logRowlevel("PROCESSING_INSTRUCTION"); } break; case XMLStreamConstants.START_DOCUMENT: // START_DOCUMENT= 7 if (log.isRowLevel()) { logRowlevel("START_DOCUMENT"); } if (log.isRowLevel()) { logRowlevel(vReader.getText()); } break; case XMLStreamConstants.END_DOCUMENT: // END_DOCUMENT= 8 if (log.isRowLevel()) { logRowlevel("END_DOCUMENT"); } break; case XMLStreamConstants.ENTITY_REFERENCE: // ENTITY_REFERENCE= 9 if (log.isRowLevel()) { logRowlevel("ENTITY_REFERENCE"); } break; case XMLStreamConstants.ATTRIBUTE: // ATTRIBUTE= 10 if (log.isRowLevel()) { logRowlevel("ATTRIBUTE"); } break; case XMLStreamConstants.DTD: // DTD= 11 if (log.isRowLevel()) { logRowlevel("DTD"); } break; case XMLStreamConstants.CDATA: // CDATA= 12 if (log.isRowLevel()) { logRowlevel("CDATA"); } break; case XMLStreamConstants.NAMESPACE: // NAMESPACE= 13 if (log.isRowLevel()) { logRowlevel("NAMESPACE"); } break; case XMLStreamConstants.NOTATION_DECLARATION: // NOTATION_DECLARATION= 14 if (log.isRowLevel()) { logRowlevel("NOTATION_DECLARATION"); } break; case XMLStreamConstants.ENTITY_DECLARATION: // ENTITY_DECLARATION= 15 if (log.isRowLevel()) { logRowlevel("ENTITY_DECLARATION"); } break; default: break; } } } catch (Exception e) { throw new KettleStepException( BaseMessages.getString(PKG, "WebServices.ERROR0010.OutputParsingError", response.toString()), e); } }
From source file:org.pentaho.platform.dataaccess.datasource.api.AnalysisService.java
private String getSchemaName(String encoding, InputStream inputStream) throws XMLStreamException, IOException { String domainId = null;//w w w . j a va2s .c o m XMLStreamReader reader = null; try { XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); if (StringUtils.isEmpty(encoding)) { reader = factory.createXMLStreamReader(inputStream); } else { reader = factory.createXMLStreamReader(inputStream, encoding); } while (reader.next() != XMLStreamReader.END_DOCUMENT) { if (reader.getEventType() == XMLStreamReader.START_ELEMENT && reader.getLocalName().equalsIgnoreCase("Schema")) { domainId = reader.getAttributeValue("", "name"); return domainId; } } } finally { if (reader != null) { reader.close(); } inputStream.reset(); } return domainId; }
From source file:org.restcomm.connect.interpreter.rcml.Parser.java
public Parser(final Reader reader, final String xml, final ActorRef sender) throws IOException { super();/*from w ww. j av a2 s . com*/ if (logger.isDebugEnabled()) { logger.debug("About to create new Parser for xml: " + xml); } this.xml = xml; this.sender = sender; final XMLInputFactory inputs = XMLInputFactory.newInstance(); inputs.setProperty("javax.xml.stream.isCoalescing", true); XMLStreamReader stream = null; try { stream = inputs.createXMLStreamReader(reader); document = parse(stream); if (document == null) { throw new IOException("There was an error parsing the RCML."); } iterator = document.iterator(); } catch (final XMLStreamException exception) { if (logger.isInfoEnabled()) { logger.info("There was an error parsing the RCML for xml: " + xml + " excpetion: ", exception); } sender.tell(new ParserFailed(exception, xml), null); } finally { if (stream != null) { try { stream.close(); } catch (final XMLStreamException nested) { throw new IOException(nested); } } } }
From source file:org.reusables.dbunit.autocomplete.AutoCompletionRules.java
private void parse(final URL rulesFileUrl) { InputStream input = null;/* ww w. jav a 2s . co m*/ XMLStreamReader parser = null; try { final XMLInputFactory factory = XMLInputFactory.newInstance(); input = rulesFileUrl.openStream(); parser = factory.createXMLStreamReader(input); for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) { if (event == XMLStreamConstants.START_ELEMENT && ELEM_RULES.equals(parser.getLocalName())) { parseRules(parser); } else if (event == XMLStreamConstants.START_ELEMENT && ELEM_TABLE.equals(parser.getLocalName())) { parseTable(parser); } } } catch (final XMLStreamException e) { throw new DbUnitAutoCompletionException("Error parsing xml stream.", e); } catch (final IOException e) { throw new DbUnitAutoCompletionException("Error reading stream.", e); } finally { IOUtils.closeQuietly(input); closeParser(parser); } }
From source file:org.rhq.enterprise.server.sync.test.DeployedAgentPluginsValidatorTest.java
public void testCanExportAndImportState() throws Exception { final PluginManagerLocal pluginManager = context.mock(PluginManagerLocal.class); final DeployedAgentPluginsValidator validator = new DeployedAgentPluginsValidator(pluginManager); context.checking(new Expectations() { {/*from ww w.jav a2s . c om*/ oneOf(pluginManager).getInstalledPlugins(); will(returnValue(new ArrayList<Plugin>(getDeployedPlugins()))); } }); validator.initialize(null, null); StringWriter output = new StringWriter(); try { XMLOutputFactory ofactory = XMLOutputFactory.newInstance(); XMLStreamWriter wrt = ofactory.createXMLStreamWriter(output); //wrap the exported plugins in "something" so that we produce //a valid xml wrt.writeStartDocument(); wrt.writeStartElement("root"); validator.exportState(new ExportWriter(wrt)); wrt.writeEndDocument(); wrt.close(); StringReader input = new StringReader(output.toString()); try { XMLInputFactory ifactory = XMLInputFactory.newInstance(); XMLStreamReader rdr = ifactory.createXMLStreamReader(input); //push the reader to the start of the plugin elements //this is what is expected by the validators rdr.nextTag(); validator.initializeExportedStateValidation(new ExportReader(rdr)); rdr.close(); assertEquals(validator.getPluginsToValidate(), getDeployedPlugins()); } finally { input.close(); } } catch (Exception e) { LOG.error("Test failed. Output generated so far:\n" + output, e); throw e; } finally { output.close(); } }