List of usage examples for javax.xml.stream XMLInputFactory newInstance
public static XMLInputFactory newInstance() throws FactoryConfigurationError
From source file:org.mcisb.subliminal.SubliminalUtils.java
/** * // ww w . j av a2 s. c o m * @param elementName * @param is * @param onlyValues * @return Collection * @throws XMLStreamException * @throws UnsupportedEncodingException */ private static Collection<String> getElements(final String elementName, final InputStream is, final boolean onlyValues) throws XMLStreamException, UnsupportedEncodingException { final Collection<String> elements = new ArrayList<>(); final ByteArrayOutputStream os = new ByteArrayOutputStream(); final XMLEventReader reader = XMLInputFactory.newInstance() .createXMLEventReader(new InputStreamReader(is, Charset.defaultCharset().name())); final XMLEventWriter writer = XMLOutputFactory.newInstance() .createXMLEventWriter(new OutputStreamWriter(os, Charset.defaultCharset().name())); boolean read = false; String characters = null; while (reader.peek() != null) { final XMLEvent event = (XMLEvent) reader.next(); switch (event.getEventType()) { case XMLStreamConstants.START_DOCUMENT: case XMLStreamConstants.END_DOCUMENT: { // Ignore. break; } case XMLStreamConstants.START_ELEMENT: { read = read || elementName.equals(event.asStartElement().getName().getLocalPart()); if (read && !onlyValues) { writer.add(event); } break; } case XMLStreamConstants.ATTRIBUTE: { if (read && !onlyValues) { writer.add(event); } break; } case XMLStreamConstants.CHARACTERS: { if (read && !onlyValues) { writer.add(event); } characters = event.asCharacters().getData(); break; } case XMLStreamConstants.END_ELEMENT: { if (read && !onlyValues) { writer.add(event); } if (elementName.equals(event.asEndElement().getName().getLocalPart())) { writer.flush(); if (characters != null) { elements.add(characters); } os.reset(); read = false; } break; } default: { // Ignore break; } } } return elements; }
From source file:org.miloss.fgsms.presentation.Helper.java
public static ServicePolicy ImportServicePolicy(String pol, PolicyType pt) { try {/*w ww.j a v a2 s .co m*/ JAXBContext jc = Utility.getSerializationContext(); Unmarshaller u = jc.createUnmarshaller(); ByteArrayInputStream bss = new ByteArrayInputStream(pol.getBytes(Constants.CHARSET)); //1 = reader //2 = writer XMLInputFactory xf = XMLInputFactory.newInstance(); XMLStreamReader r = xf.createXMLStreamReader(bss); // com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl r = new com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl(bss, new com.sun.org.apache.xerces.internal.impl.PropertyManager(1)); switch (pt) { case MACHINE: JAXBElement<MachinePolicy> foo = (JAXBElement<MachinePolicy>) u.unmarshal(r, MachinePolicy.class); bss.close(); if (foo != null && foo.getValue() != null) { return foo.getValue(); } break; case PROCESS: JAXBElement<ProcessPolicy> foo2 = (JAXBElement<ProcessPolicy>) u.unmarshal(r, ProcessPolicy.class); bss.close(); if (foo2 != null && foo2.getValue() != null) { return foo2.getValue(); } break; case STATISTICAL: JAXBElement<StatisticalServicePolicy> foo3 = (JAXBElement<StatisticalServicePolicy>) u.unmarshal(r, StatisticalServicePolicy.class); bss.close(); if (foo3 != null && foo3.getValue() != null) { return foo3.getValue(); } break; case STATUS: JAXBElement<StatusServicePolicy> foo4 = (JAXBElement<StatusServicePolicy>) u.unmarshal(r, StatusServicePolicy.class); bss.close(); if (foo4 != null && foo4.getValue() != null) { return foo4.getValue(); } break; case TRANSACTIONAL: JAXBElement<TransactionalWebServicePolicy> foo5 = (JAXBElement<TransactionalWebServicePolicy>) u .unmarshal(r, TransactionalWebServicePolicy.class); bss.close(); if (foo5 != null && foo5.getValue() != null) { return foo5.getValue(); } break; } bss.close(); Logger.getLogger(Helper.class).log(Level.WARN, "ServicePolicy is unexpectedly null or empty"); return null; } catch (Exception ex) { Logger.getLogger(Helper.class).log(Level.ERROR, null, ex); } return null; }
From source file:org.modeldriven.fuml.xmi.stream.StreamReader.java
@SuppressWarnings("unchecked") public Collection read(InputStream stream) { List<Object> results = new ArrayList<Object>(); InputStream source = stream;/* w w w . j a va2 s .com*/ StreamContext context = null; try { XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setXMLResolver(new XMLResolver() { @Override public Object resolveEntity(String publicID, String systemID, String baseURI, String namespace) throws XMLStreamException { // TODO Auto-generated method stub return null; } }); /* XStream xstream = new XStream(new StaxDriver() { protected XMLStreamReader createParser(Reader xml) throws XMLStreamException { return getInputFactory().createXMLStreamReader(xml); } protected XMLStreamReader createParser(InputStream xml) throws XMLStreamException { return getInputFactory().createXMLStreamReader(xml); } }); */ //factory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES,Boolean.FALSE); //factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES,Boolean.TRUE); //set the IS_COALESCING property to true , if application desires to //get whole text data as one event. //factory.setProperty(XMLInputFactory.IS_COALESCING , Boolean.TRUE); factory.setEventAllocator(new EventAllocator()); allocator = factory.getEventAllocator(); XMLStreamReader streamReader = factory.createXMLStreamReader(stream); int eventType = streamReader.getEventType(); StreamNode node = null; StreamNode parent = null; int level = 0; int ignoredNodeLevel = -1; while (streamReader.hasNext()) { eventType = streamReader.next(); //if (log.isDebugEnabled()) // log.debug(this.getEventTypeString(eventType)); switch (eventType) { case XMLEvent.START_ELEMENT: level++; if (ignoredNodeLevel >= 0) break; XMLEvent event = allocateXMLEvent(streamReader); if (level == 1) { if (context != null) throw new XmiException("existing context unexpected"); context = new StreamContext(event); } // debugging if (event.toString().contains("plasma:PlasmaType")) { int foo = 1; foo++; } node = new StreamNode(event, context); if (node.isIgnored()) { if (log.isDebugEnabled()) { Location loc = event.getLocation(); String msg = "start ignoring elements - level: " + String.valueOf(level) + " - line:col[" + loc.getLineNumber() + ":" + loc.getColumnNumber() + "] - "; log.debug(msg); } ignoredNodeLevel = level; break; } logEventInfo(event); parent = null; if (nodes.size() > 0) { parent = nodes.peek(); parent.add(node); node.setParent(parent); if (isRootNode(node, context)) results.add(node); } else { if (isRootNode(node, context)) results.add(node); } nodes.push(node); fireStreamNodeCreated(node, parent); break; case XMLEvent.END_ELEMENT: if (ignoredNodeLevel >= 0) { if (ignoredNodeLevel == level) { if (log.isDebugEnabled()) { event = allocateXMLEvent(streamReader); Location loc = event.getLocation(); String msg = "end ignoring elements - level: " + String.valueOf(level) + " - line:col[" + loc.getLineNumber() + ":" + loc.getColumnNumber() + "] - "; log.debug(msg); } ignoredNodeLevel = -1; } level--; break; } level--; node = nodes.pop(); parent = null; if (nodes.size() > 0) parent = nodes.peek(); fireStreamNodeCompleted(node, parent); break; case XMLEvent.CHARACTERS: if (ignoredNodeLevel >= 0) break; node = nodes.peek(); event = allocateXMLEvent(streamReader); String data = event.asCharacters().getData(); if (data != null) { data = data.trim(); if (data.length() > 0) { if (log.isDebugEnabled()) log.debug("CHARACTERS: '" + data + "'"); if (data.length() > 0) { node = nodes.peek(); node.addCharactersEvent(event); } } } break; default: if (log.isDebugEnabled()) { event = allocateXMLEvent(streamReader); logEventInfo(event); } break; } } if (results.size() > 1) throw new XmiException("found multiple root nodes (" + results.size() + ")"); } catch (XMLStreamException e) { throw new XmiException(e); } finally { try { source.close(); } catch (IOException e) { } } return results; }
From source file:org.mule.module.xml.transformer.AbstractXmlTransformer.java
public AbstractXmlTransformer() { registerSourceType(DataTypeFactory.STRING); registerSourceType(DataTypeFactory.BYTE_ARRAY); registerSourceType(DataTypeFactory.create(javax.xml.transform.Source.class)); registerSourceType(DataTypeFactory.create(org.xml.sax.InputSource.class)); registerSourceType(DataTypeFactory.create(org.dom4j.Node.class)); registerSourceType(DataTypeFactory.create(org.dom4j.Document.class)); registerSourceType(DataTypeFactory.create(org.w3c.dom.Document.class)); registerSourceType(DataTypeFactory.create(org.w3c.dom.Element.class)); registerSourceType(DataTypeFactory.create(java.io.InputStream.class)); registerSourceType(DataTypeFactory.create(org.mule.api.transport.OutputHandler.class)); registerSourceType(DataTypeFactory.create(javax.xml.stream.XMLStreamReader.class)); registerSourceType(DataTypeFactory.create(org.mule.module.xml.transformer.DelayedResult.class)); setReturnDataType(DataTypeFactory.BYTE_ARRAY); xmlInputFactory = XMLInputFactory.newInstance(); xmlOutputFactory = XMLOutputFactory.newInstance(); }
From source file:org.mule.transport.sap.transformer.XmlToJcoFunctionTransformer.java
public JCoFunction transform(InputStream stream, String encoding) throws XMLStreamException { XMLStreamReader reader = null; XMLInputFactory factory = XMLInputFactory.newInstance(); String functionName = null;//from w ww.j a v a 2 s . co m String tableName = null; String structureName = null; String rowId = null; String fieldName = null; String value = null; JCoFunction function = null; try { reader = factory.createXMLStreamReader(stream); String localName = null; while (reader.hasNext()) { int eventType = reader.next(); if (eventType == XMLStreamReader.START_DOCUMENT) { // find START_DOCUMENT } else if (eventType == XMLStreamReader.START_ELEMENT) { // find START_ELEMENT localName = reader.getLocalName(); logger.debug("START ELEMENT IS FOUND"); logger.debug("start localName = " + localName); if (localName.equals(MessageConstants.JCO)) { functionName = getAttributeValue(MessageConstants.JCO_ATTR_NAME, reader); try { function = this.connector.getAdapter().getFunction(functionName); } catch (JCoException e) { throw new XMLStreamException(e); } logger.debug("function name:" + functionName); } else if (functionName != null) { if (localName.equals(MessageConstants.IMPORT)) { //recordType = IMPORT; push(function.getImportParameterList()); } else if (localName.equals(MessageConstants.EXPORT)) { //recordType = EXPORT; push(function.getExportParameterList()); } else if (localName.equals(MessageConstants.TABLES)) { //recordType = TABLES; tableName = null; push(function.getTableParameterList()); } else if (localName.equals(MessageConstants.TABLE)) { if (tableName != null) { pop(); } tableName = getAttributeValue(MessageConstants.TABLE_ATTR_NAME, reader); logger.debug("tableName = " + tableName); push(this.record.getTable(tableName)); } else if (localName.equals(MessageConstants.STRUCTURE)) { structureName = getAttributeValue(MessageConstants.STRUCTURE_ATTR_NAME, reader); push(this.record.getStructure(structureName)); } else if (localName.equals(MessageConstants.ROW)) { rowId = getAttributeValue(MessageConstants.ROW_ATTR_ID, reader); logger.debug("rowId = " + rowId); if (this.record instanceof JCoTable) { ((JCoTable) this.record).appendRow(); } } else if (localName.equals(MessageConstants.FIELD)) { fieldName = getAttributeValue(MessageConstants.STRUCTURE_ATTR_NAME, reader); value = reader.getElementText().trim(); // get an element value logger.debug("FieldName = " + fieldName); logger.debug("value = " + value); this.record.setValue(fieldName, value); } } } else if (eventType == XMLStreamReader.END_DOCUMENT) { // find END_DOCUMENT logger.debug("END DOCUMENT IS FOUND"); } else if (eventType == XMLStreamReader.END_ELEMENT) { logger.debug("END ELEMENT IS FOUND"); logger.debug("end localName = " + localName); // find END_ELEMENT if (localName.equals(MessageConstants.IMPORT) || localName.equals(MessageConstants.EXPORT) || localName.equals(MessageConstants.TABLES) || localName.equals(MessageConstants.TABLE) || localName.equals(MessageConstants.STRUCTURE)) { pop(); } } } } catch (Exception e) { logger.fatal(e); throw new TransformerException(this, e); } finally { if (reader != null) { try { reader.close(); } catch (XMLStreamException ex) { } } if (stream != null) { try { stream.close(); } catch (IOException ex) { } } logger.debug("\n" + function.getImportParameterList().toXML()); logger.debug("\n" + function.getExportParameterList().toXML()); logger.debug("\n" + function.getTableParameterList().toXML()); return function; } }
From source file:org.odata4j.format.xml.AtomFeedFormatParserExt.java
private XMLEventReader2 createXMLEventReader(Reader reader) { XMLInputFactory factory = XMLInputFactory.newInstance(); //XXE on its own can be prevented by setting IS_SUPPORT_EXTERNAL_ENTITIES to false but this will not //prevent a billion laugh attack. Setting IS_REPLACING_ENTITY_REFERENCES to false does //not force the implementation to not process internal entity references. //Safest thing to do is to set SUPPORT_DTD to false to prevent both XXE and billion laugh. factory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE); XMLEventReader2 xmlEventReader2 = new StaxXMLInputFactory2Ext(factory).createXMLEventReader(reader); return xmlEventReader2; }
From source file:org.omegat.util.TMXReader2.java
public TMXReader2() { factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false); factory.setXMLReporter(new XMLReporter() { public void report(String message, String error_type, Object info, Location location) throws XMLStreamException { Log.logWarningRB("TMXR_WARNING_WHILE_PARSING", location.getLineNumber(), location.getColumnNumber()); Log.log(message + ": " + info); warningsCount++;// w ww. j a v a 2s. c o m } }); factory.setXMLResolver(TMX_DTD_RESOLVER_2); dateFormat1 = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'", Locale.ENGLISH); dateFormat1.setTimeZone(TimeZone.getTimeZone("UTC")); dateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH); dateFormat2.setTimeZone(TimeZone.getTimeZone("UTC")); dateFormatOut = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'", Locale.ENGLISH); dateFormatOut.setTimeZone(TimeZone.getTimeZone("UTC")); }
From source file:org.openengsb.connector.promreport.internal.ProcessFileStore.java
public ProcessFileStore(File rootDirectory) { this.processDir = rootDirectory; if (!rootDirectory.exists() && !rootDirectory.mkdirs()) { throw new RuntimeException("Could not make directory " + rootDirectory.getAbsolutePath()); } else if (!rootDirectory.isDirectory()) { throw new IllegalArgumentException("Root directory '" + rootDirectory + "' is not a directory."); }/* www .j av a2 s. c o m*/ try { jaxbContext = JAXBContext.newInstance(WorkflowLog.class); xmlif = XMLInputFactory.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } try { schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI) .newSchema(new URL("http://is.tm.tue.nl/research/processmining/WorkflowLog.xsd")); } catch (Exception e) { LOGGER.warn("Error during creating of Mxml schema. Continue without schema validation.", e); } }
From source file:org.openhab.binding.denon.internal.DenonConnector.java
private <T> T getDocument(String uri, Class<T> response) { try {//from w w w.j a v a 2 s . co m String result = HttpUtil.executeUrl("GET", uri, REQUEST_TIMEOUT_MS); JAXBContext jc = JAXBContext.newInstance(response); XMLInputFactory xif = XMLInputFactory.newInstance(); XMLStreamReader xsr = xif.createXMLStreamReader(IOUtils.toInputStream(result)); xsr = new PropertyRenamerDelegate(xsr); @SuppressWarnings("unchecked") T obj = (T) jc.createUnmarshaller().unmarshal(xsr); return obj; } catch (JAXBException e) { logger.warn("Encoding error in get", e); } catch (XMLStreamException e) { logger.warn("Communication error in get", e); } return null; }
From source file:org.openhab.binding.denonmarantz.internal.connector.http.DenonMarantzHttpConnector.java
@Nullable private <T> T getDocument(String uri, Class<T> response) throws IOException { try {/* ww w. j av a 2 s. co m*/ String result = HttpUtil.executeUrl("GET", uri, REQUEST_TIMEOUT_MS); logger.trace("result of getDocument for uri '{}':\r\n{}", uri, result); if (StringUtils.isNotBlank(result)) { JAXBContext jc = JAXBContext.newInstance(response); XMLInputFactory xif = XMLInputFactory.newInstance(); XMLStreamReader xsr = xif.createXMLStreamReader(IOUtils.toInputStream(result)); xsr = new PropertyRenamerDelegate(xsr); @SuppressWarnings("unchecked") T obj = (T) jc.createUnmarshaller().unmarshal(xsr); return obj; } } catch (UnmarshalException e) { logger.debug("Failed to unmarshal xml document: {}", e.getMessage()); } catch (JAXBException e) { logger.debug("Unexpected error occurred during unmarshalling of document: {}", e.getMessage()); } catch (XMLStreamException e) { logger.debug("Communication error: {}", e.getMessage()); } return null; }