List of usage examples for javax.xml.stream XMLInputFactory createXMLEventReader
public abstract XMLEventReader createXMLEventReader(java.io.InputStream stream) throws XMLStreamException;
From source file:org.apereo.portal.rendering.StaticDocumentComponent.java
@Override public PipelineEventReader<XMLEventReader, XMLEvent> getEventReader(HttpServletRequest request, HttpServletResponse response) {/*from ww w. j a v a2 s.c om*/ final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); final DocumentBuilder documentBuilder; try { documentBuilder = documentBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } final InputStream documentStream; try { documentStream = this.document.getInputStream(); } catch (IOException e) { throw new RuntimeException(e); } final Document document; try { document = documentBuilder.parse(documentStream); } catch (SAXException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(documentStream); } final XMLInputFactory inputFactory = XMLInputFactory.newFactory(); final DOMSource source = new DOMSource(document); final XMLEventReader streamReader; try { streamReader = inputFactory.createXMLEventReader(source); } catch (XMLStreamException e) { throw new RuntimeException(e); } return new PipelineEventReaderImpl<XMLEventReader, XMLEvent>(streamReader); }
From source file:org.apereo.portal.url.xml.XsltPortalUrlProviderTest.java
@Before public void setup() throws Exception { final ResourceLoaderURIResolver resolver = new ResourceLoaderURIResolver( new ClassRelativeResourceLoader(getClass())); this.tFactory = TransformerFactory.newInstance(); this.tFactory.setURIResolver(resolver); this.tFactory.setErrorListener(new SimpleTransformErrorListener(LogFactory.getLog(getClass()))); //Load the XML document so it reads the same way the rendering pipeline reads XML final XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory(); final XMLEventReader eventReader = xmlInputFactory .createXMLEventReader(this.getClass().getResourceAsStream("test.xml")); final XMLStreamReader streamReader = new FixedXMLEventStreamReader(eventReader); xmlSource = new StAXSource(streamReader); xslTemplate = tFactory.newTemplates(new StreamSource(this.getClass().getResourceAsStream("test.xsl"))); expected = IOUtils.toString(this.getClass().getResourceAsStream("result.xml")); }
From source file:org.dkpro.core.io.xces.XcesBasicXmlReader.java
@Override public void getNext(JCas aJCas) throws IOException, CollectionException { Resource res = nextFile();/*from ww w. jav a 2s . co m*/ initCas(aJCas, res); InputStream is = null; try { is = CompressionUtils.getInputStream(res.getLocation(), res.getInputStream()); XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); XMLEventReader xmlEventReaderBasic = xmlInputFactory.createXMLEventReader(is); //JAXB context for XCES body with basic type JAXBContext contextBasic = JAXBContext.newInstance(XcesBodyBasic.class); Unmarshaller unmarshallerBasic = contextBasic.createUnmarshaller(); unmarshallerBasic.setEventHandler(new ValidationEventHandler() { public boolean handleEvent(ValidationEvent event) { throw new RuntimeException(event.getMessage(), event.getLinkedException()); } }); JCasBuilder jb = new JCasBuilder(aJCas); XMLEvent eBasic = null; while ((eBasic = xmlEventReaderBasic.peek()) != null) { if (isStartElement(eBasic, "body")) { try { XcesBodyBasic parasBasic = (XcesBodyBasic) unmarshallerBasic .unmarshal(xmlEventReaderBasic, XcesBodyBasic.class).getValue(); readPara(jb, parasBasic); } catch (RuntimeException ex) { getLogger().warn("Input is not in basic xces format."); } } else { xmlEventReaderBasic.next(); } } jb.close(); } catch (XMLStreamException ex1) { throw new IOException(ex1); } catch (JAXBException e1) { throw new IOException(e1); } finally { closeQuietly(is); } }
From source file:org.dkpro.core.io.xces.XcesXmlReader.java
@Override public void getNext(JCas aJCas) throws IOException, CollectionException { Resource res = nextFile();//from w w w. j a v a2 s . c o m initCas(aJCas, res); InputStream is = null; try { is = CompressionUtils.getInputStream(res.getLocation(), res.getInputStream()); XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(is); JAXBContext context = JAXBContext.newInstance(XcesBody.class); Unmarshaller unmarshaller = context.createUnmarshaller(); unmarshaller.setEventHandler(new ValidationEventHandler() { public boolean handleEvent(ValidationEvent event) { throw new RuntimeException(event.getMessage(), event.getLinkedException()); } }); JCasBuilder jb = new JCasBuilder(aJCas); XMLEvent e = null; while ((e = xmlEventReader.peek()) != null) { if (isStartElement(e, "body")) { try { XcesBody paras = (XcesBody) unmarshaller.unmarshal(xmlEventReader, XcesBody.class) .getValue(); readPara(jb, paras); } catch (RuntimeException ex) { System.out.println("Unable to parse XCES format: " + ex); } } else { xmlEventReader.next(); } } jb.close(); } catch (XMLStreamException ex1) { throw new IOException(ex1); } catch (JAXBException e1) { throw new IOException(e1); } finally { closeQuietly(is); } }
From source file:org.jasig.portal.io.xml.AbstractIdentityImportExportTest.java
protected final <T> void testIdentityImportExport(final IDataImporter<T> dataImporter, final IDataExporter<?> dataExporter, Resource resource, Function<T, String> getName) throws Exception { final String importData = toString(resource); final XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory(); final XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(new StringReader(importData)); //Unmarshall from XML final Unmarshaller unmarshaller = dataImporter.getUnmarshaller(); final StAXSource source = new StAXSource(xmlEventReader); @SuppressWarnings("unchecked") final T dataImport = (T) unmarshaller.unmarshal(source); //Make sure the data was unmarshalled assertNotNull("Unmarshalled import data was null", dataImport); //Import the data dataImporter.importData(dataImport); //Export the data final String name = getName.apply(dataImport); final Object dataExport = transactionOperations.execute(new TransactionCallback<Object>() { /* (non-Javadoc) * @see org.springframework.transaction.support.TransactionCallback#doInTransaction(org.springframework.transaction.TransactionStatus) *//*from ww w. j ava 2 s . c o m*/ @Override public Object doInTransaction(TransactionStatus status) { return dataExporter.exportData(name); } }); //Make sure the data was exported assertNotNull("Exported data was null", dataExport); //Marshall to XML final Marshaller marshaller = dataExporter.getMarshaller(); final StringWriter result = new StringWriter(); marshaller.marshal(dataExport, new StreamResult(result)); //Compare the exported XML data with the imported XML data, they should match final String resultString = result.toString(); try { XMLUnit.setIgnoreWhitespace(true); Diff d = new Diff(new StringReader(importData), new StringReader(resultString)); assertTrue("Export result differs from import" + d, d.similar()); } catch (Exception e) { throw new XmlTestException("Failed to assert similar between import XML and export XML", resultString, e); } catch (Error e) { throw new XmlTestException("Failed to assert similar between import XML and export XML", resultString, e); } }
From source file:org.jwifisd.eyefi.Main.java
private static void getPhotoStatus(Request request, Response response, final String date) throws FactoryConfigurationError, XMLStreamException, IOException { String macaddress = null;//from w w w .j a va2 s. c o m String credential = null; String filename = null; String filesize = null; String filesignature = null; XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLEventReader eventReader = inputFactory.createXMLEventReader(request.getInputStream()); while (eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); if (event.isStartElement()) { if (event.asStartElement().getName().getLocalPart().equals("macaddress")) { event = eventReader.nextEvent(); macaddress = event.asCharacters().getData(); continue; } if (event.asStartElement().getName().getLocalPart().equals("credential")) { event = eventReader.nextEvent(); credential = event.asCharacters().getData(); continue; } if (event.asStartElement().getName().getLocalPart().equals("filename")) { event = eventReader.nextEvent(); filename = event.asCharacters().getData(); continue; } if (event.asStartElement().getName().getLocalPart().equals("filesize")) { event = eventReader.nextEvent(); filesize = event.asCharacters().getData(); continue; } if (event.asStartElement().getName().getLocalPart().equals("filesignature")) { event = eventReader.nextEvent(); filesignature = event.asCharacters().getData(); continue; } } } System.out.println("macaddress:" + macaddress); System.out.println("credential:" + credential); System.out.println("filename:" + filename); System.out.println("filesize:" + filesize); System.out.println("filesignature:" + filesignature); response.setHeader("Server", "Eye-Fi Agent/2.0.4.0"); response.setHeader("Date", date); response.setHeader("Pragma", "no-cache"); response.setHeader("Content-Type", "text/xml; charset=\"utf-8\""); String responseText = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + // "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">" + // /**/"<SOAP-ENV:Body>\n" + // /* */"<GetPhotoStatusResponse xmlns=\"http://localhost/api/soap/eyefilm\">" + // /* */"<fileid>1</fileid><offset>0</offset>" + // /* */"</GetPhotoStatusResponse>" + // /**/"</SOAP-ENV:Body>" + // "</SOAP-ENV:Envelope>"; response.setContentLength(responseText.length()); response.getWriter().write(responseText); }
From source file:org.jwifisd.eyefi.Main.java
private static void startSession(Request request, Response response, final String date) throws Exception, IOException { String macaddress = null;/*from ww w . j av a 2 s .com*/ String cnonce = null; String transfermode = null; String transfermodetimestamp = null; System.out.println("connectx"); XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLEventReader eventReader = inputFactory.createXMLEventReader(request.getInputStream()); while (eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); if (event.isStartElement()) { if (event.asStartElement().getName().getLocalPart().equals("macaddress")) { event = eventReader.nextEvent(); macaddress = event.asCharacters().getData(); continue; } if (event.asStartElement().getName().getLocalPart().equals("cnonce")) { event = eventReader.nextEvent(); cnonce = event.asCharacters().getData(); continue; } if (event.asStartElement().getName().getLocalPart().equals("transfermode")) { event = eventReader.nextEvent(); transfermode = event.asCharacters().getData(); continue; } if (event.asStartElement().getName().getLocalPart().equals("transfermodetimestamp")) { event = eventReader.nextEvent(); transfermodetimestamp = event.asCharacters().getData(); continue; } } } System.out.println("macaddress:" + macaddress); System.out.println("cnonce:" + cnonce); System.out.println("transfermode:" + transfermode); System.out.println("transfermodetimestamp:" + transfermodetimestamp); byte[] cnonceBytes = Hex.decodeHex(cnonce.toCharArray()); byte[] uploadKey = Hex.decodeHex("00000000000000000000000000000000".toCharArray()); byte[] credential = md5(Hex.decodeHex(macaddress.toCharArray()), cnonceBytes, uploadKey); String credentialStr = Hex.encodeHexString(credential); response.setHeader("Server", "Eye-Fi Agent/2.0.4.0"); response.setHeader("Date", date); response.setHeader("Pragma", "no-cache"); response.setHeader("Content-Type", "text/xml; charset=\"utf-8\""); String responseText = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + // "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">" + // /**/"<SOAP-ENV:Body>" + // /* */"<StartSessionResponse xmlns=\"http://localhost/api/soap/eyefilm\">" + // /* */"<credential>" + credentialStr + "</credential>" + // /* */"<snonce>" + cnonce + "</snonce>" + // /* */"<transfermode>2</transfermode>" + // /* */"<transfermodetimestamp>1230268824</transfermodetimestamp>" + // /* */"<upsyncallowed>false</upsyncallowed>" + // /* */"</StartSessionResponse>" + // /**/"</SOAP-ENV:Body>" + // "</SOAP-ENV:Envelope>"; System.out.println(responseText); response.setContentLength(responseText.length()); response.getWriter().write(responseText); }
From source file:org.omnaest.utils.xml.XMLIteratorFactory.java
private CachedElement<XMLEventReader> newXmlEventReaderCache(final InputStream inputStream, final ExceptionHandler exceptionHandler) { return new CachedElement<XMLEventReader>(new ValueResolver<XMLEventReader>() { @Override/*from w ww . ja va2 s . c o m*/ public XMLEventReader resolveValue() { // XMLEventReader retval = null; // try { // final XMLInputFactory xmlInputFactory = XMLIteratorFactory.this.xmlInstanceContextFactory .newXmlInputFactory(); Assert.isNotNull(xmlInputFactory, "xmlInputFactory must not be null"); // retval = xmlInputFactory.createXMLEventReader(inputStream); } catch (Exception e) { exceptionHandler.handleException(e); } // return retval; } }); }
From source file:org.omnaest.utils.xml.XMLNestedMapConverter.java
/** * Template method for {@link #newNamespaceAwareMapFromXML(CharSequence)} and {@link #newMapFromXML(CharSequence)} which allows * to convert the {@link QName} based key values to other representations. * /*from w ww .j a va 2 s . c o m*/ * @param xmlContent * @return new (nested) {@link Map} instance */ protected <K> Map<K, Object> newMapFromXML(CharSequence xmlContent, final ElementConverter<QName, K> keyElementConverter) { // final Map<K, Object> retmap = new LinkedHashMap<K, Object>(); // Assert.isNotNull(keyElementConverter, "keyElementConverter must not be null"); // final ExceptionHandler exceptionHandler = this.exceptionHandler; // try { // final XMLInputFactory xmlInputFactory = this.xmlInstanceContextFactory.newXmlInputFactory(); Assert.isNotNull(xmlInputFactory, "xmlInputFactory must not be null"); // final Reader reader = new CharSequenceReader(xmlContent); final XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(reader); // final class Helper { /* ********************************************** Variables ********************************************** */ private List<TupleTwo<QName, Object>> stackList = new ArrayList<TupleTwo<QName, Object>>(); /* ********************************************** Methods ********************************************** */ /** * Manifests a single tag node recursively * * @return * @throws XMLStreamException */ @SuppressWarnings("unchecked") public TupleTwo<QName, Object> manifest() throws XMLStreamException { // TupleTwo<QName, Object> retval = null; // while (xmlEventReader.hasNext()) { // final XMLEvent xmlEvent = xmlEventReader.nextEvent(); // if (xmlEvent.isStartElement()) { // final StartElement startElement = xmlEvent.asStartElement(); final QName name = startElement.getName(); // this.addNewStackElement().setValueFirst(name); // final Iterator<Attribute> attributeIterator = startElement.getAttributes(); if (attributeIterator.hasNext()) { // final Map<QName, Object> map = new LinkedHashMap<QName, Object>(); for (Attribute attribute : IterableUtils.valueOf(attributeIterator)) { map.put(attribute.getName(), attribute.getValue()); } // this.updateCurrentStackValue(map); } } else if (xmlEvent.isEndElement()) { // retval = this.removeStackElement(); // final Object manifestation = retval.getValueSecond(); final QName tagname = retval.getValueFirst(); // updateCurrentStackValue(manifestation, tagname); } else if (xmlEvent.isCharacters()) { // final Characters characters = xmlEvent.asCharacters(); if (!characters.isWhiteSpace()) { // final TupleTwo<QName, Object> currentStackValue = this.getCurrentStackValue(); currentStackValue.setValueSecond( ObjectUtils.defaultIfNull(currentStackValue.getValueSecond(), "") + characters.getData()); } } } // return retval; } /** * Updates the current stack value * * @param manifestation * @param tagname */ private void updateCurrentStackValue(Object manifestation, QName tagname) { // final Map<QName, Object> tagNameToManifestationMap = new LinkedHashMap<QName, Object>(); tagNameToManifestationMap.put(tagname, manifestation); this.updateCurrentStackValue(tagNameToManifestationMap); } @SuppressWarnings("unchecked") private void updateCurrentStackValue(Map<QName, Object> tagNameToManifestationMap) { // final TupleTwo<QName, Object> currentStackValue = this.getCurrentStackValue(); // if (currentStackValue != null) { // Map<K, Object> map = null; { // final Object valueSecond = currentStackValue.getValueSecond(); if (valueSecond instanceof Map) { map = (Map<K, Object>) valueSecond; } else { // map = new LinkedHashMap<K, Object>(); if (valueSecond instanceof String) { map.put(keyElementConverter.convert(new QName("")), valueSecond); } } } // for (Entry<QName, Object> tagNameToManifestationEntry : tagNameToManifestationMap .entrySet()) { // final K tagname = keyElementConverter.convert(tagNameToManifestationEntry.getKey()); final Object manifestation = tagNameToManifestationEntry.getValue(); // if (!map.containsKey(tagname)) { map.put(tagname, manifestation); } else { // final Object object = map.get(tagname); if (object instanceof List) { // final List<Object> list = (List<Object>) object; list.add(manifestation); } else { // final List<Object> list = new ArrayList<Object>(); list.add(object); list.add(manifestation); map.put(tagname, list); } } } // currentStackValue.setValueSecond(map); } } private TupleTwo<QName, Object> getCurrentStackValue() { return ListUtils.firstElement(this.stackList); } private TupleTwo<QName, Object> removeStackElement() { return ListUtils.removeFirst(this.stackList); } private TupleTwo<QName, Object> addNewStackElement() { // final TupleTwo<QName, Object> retval = new TupleTwo<QName, Object>(); this.stackList.add(0, retval); return retval; } } // try { final Helper helper = new Helper(); final TupleTwo<QName, Object> result = helper.manifest(); retmap.put(keyElementConverter.convert(result.getValueFirst()), result.getValueSecond()); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.handleException(e); } } // xmlEventReader.close(); reader.close(); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.handleException(e); } } // return retmap; }
From source file:org.openhab.binding.dwdunwetter.internal.data.DwdWarningsData.java
/** * Refreshes the Warnings Data// w w w . j ava 2s . c om */ public boolean refresh() { String rawData = dataAccessCached.getValue(); if (StringUtils.isEmpty(rawData)) { logger.debug("No Data from Endpoint"); return false; } cityData.clear(); try { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLStreamReader reader = inputFactory.createXMLStreamReader(new StringReader(rawData)); XMLEventReader eventReader = inputFactory.createXMLEventReader(reader); DwdWarningData gemeindeData = new DwdWarningData(); boolean insideGemeinde = false; while (eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); if (!insideGemeinde && event.isStartElement()) { DwdXmlTag xmlTag = DwdXmlTag.getDwdXmlTag(event.asStartElement().getName().getLocalPart()); switch (xmlTag) { case WARNUNGEN_GEMEINDEN: gemeindeData = new DwdWarningData(); insideGemeinde = true; break; default: break; } } else if (insideGemeinde && event.isStartElement()) { DwdXmlTag xmlTag = DwdXmlTag.getDwdXmlTag(event.asStartElement().getName().getLocalPart()); switch (xmlTag) { case SEVERITY: gemeindeData.setSeverity(Severity.getSeverity(getValue(eventReader))); break; case DESCRIPTION: gemeindeData.setDescription(getValue(eventReader)); break; case EFFECTIVE: gemeindeData.setEffective(getTimestampValue(eventReader)); break; case EXPIRES: gemeindeData.setExpires(getTimestampValue(eventReader)); break; case EVENT: gemeindeData.setEvent(getValue(eventReader)); break; case STATUS: gemeindeData.setStatus(getValue(eventReader)); break; case MSGTYPE: gemeindeData.setMsgType(getValue(eventReader)); break; case HEADLINE: gemeindeData.setHeadline(getValue(eventReader)); break; case ONSET: gemeindeData.setOnset(getTimestampValue(eventReader)); break; case ALTITUDE: gemeindeData.setAltitude(getBigDecimalValue(eventReader)); break; case CEILING: gemeindeData.setCeiling(getBigDecimalValue(eventReader)); break; case IDENTIFIER: gemeindeData.setId(getValue(eventReader)); break; case INSTRUCTION: gemeindeData.setInstruction(getValue(eventReader)); break; case URGENCY: gemeindeData.setUrgency(Urgency.getUrgency(getValue(eventReader))); break; default: break; } } else if (insideGemeinde && event.isEndElement()) { DwdXmlTag xmlTag = DwdXmlTag.getDwdXmlTag(event.asEndElement().getName().getLocalPart()); switch (xmlTag) { case WARNUNGEN_GEMEINDEN: if (!gemeindeData.isTest() && !gemeindeData.isCancel()) { cityData.add(gemeindeData); } insideGemeinde = false; break; default: break; } } } } catch (XMLStreamException e) { logger.debug("Exception while parsing the XML Response", e); return false; } Collections.sort(cityData, new SeverityComparator()); return true; }