List of usage examples for javax.xml.stream XMLEventWriter add
public void add(XMLEventReader reader) throws XMLStreamException;
From source file:com.predic8.membrane.core.interceptor.rest.XML2HTTP.java
private static String slurpXMLData(XMLEventReader parser, StartElement sevent) throws XML2HTTPException, XMLStreamException { StringWriter bodyStringWriter = new StringWriter(); XMLEventWriter bodyWriter = null; int depth = 0; synchronized (xmlOutputFactory) { bodyWriter = xmlOutputFactory.createXMLEventWriter(bodyStringWriter); }//from w w w .ja v a 2s . c om while (parser.hasNext()) { XMLEvent event = parser.nextEvent(); if (event.isEndElement() && depth == 0) { bodyWriter.flush(); return bodyStringWriter.toString(); } bodyWriter.add(event); if (event.isStartElement()) depth++; else if (event.isEndElement()) depth--; } throw new XML2HTTPException("Early end of file while reading inner XML document."); }
From source file:Main.java
/** * // w ww . ja v a 2s .c om * @param elementName * @param is * @param onlyValues * @return Collection * @throws XMLStreamException * @throws UnsupportedEncodingException */ public 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:Main.java
/** * /*ww w . j a v a2 s . com*/ * @param is * @param os * @param elementNames * @throws XMLStreamException * @throws FactoryConfigurationError * @throws UnsupportedEncodingException */ public static void stripElements(final InputStream is, final OutputStream os, final Collection<String> elementNames) throws XMLStreamException, UnsupportedEncodingException, FactoryConfigurationError { final XMLEventReader xmlEventReader = XMLInputFactory.newInstance() .createXMLEventReader(new InputStreamReader(is, Charset.defaultCharset().name())); final XMLEventWriter xmlEventWriter = XMLOutputFactory.newInstance().createXMLEventWriter(os); String elementName = null; while (xmlEventReader.peek() != null) { final XMLEvent event = (XMLEvent) xmlEventReader.next(); switch (event.getEventType()) { case XMLStreamConstants.START_DOCUMENT: case XMLStreamConstants.END_DOCUMENT: { // Ignore. break; } case XMLStreamConstants.START_ELEMENT: { final StartElement startElement = event.asStartElement(); final QName name = startElement.getName(); if (elementNames.contains(name.getLocalPart())) { elementName = name.getLocalPart(); } if (elementName == null) { xmlEventWriter.add(event); } break; } case XMLStreamConstants.END_ELEMENT: { final EndElement endElement = event.asEndElement(); final QName name = endElement.getName(); if (elementName == null) { xmlEventWriter.add(event); } else if (elementName.equals(name.getLocalPart())) { elementName = null; } break; } default: { if (elementName == null) { xmlEventWriter.add(event); } } } } xmlEventWriter.flush(); }
From source file:eionet.webq.converter.JsonXMLBidirectionalConverter.java
/** * Template for conversion.// w w w . j a v a2s . c om * * @param inputFactory input factory. * @param outputFactory output factory. * @param source source to convert. * @return conversion result as byte array. */ private byte[] convert(XMLInputFactory inputFactory, XMLOutputFactory outputFactory, byte[] source) { InputStream input = new ByteArrayInputStream(source); ByteArrayOutputStream output = new ByteArrayOutputStream(); try { XMLEventReader reader = inputFactory.createXMLEventReader(input, "utf-8"); XMLEventWriter writer = outputFactory.createXMLEventWriter(output, "utf-8"); writer = new PrettyXMLEventWriter(writer); writer.add(reader); closeQuietly(reader, writer); return output.toByteArray(); } catch (XMLStreamException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } }
From source file:WpRDFFunctionLibrary.java
public static void mergeGpmltoSingleFile(String gpmlLocation) throws IOException, XMLStreamException, ParserConfigurationException, SAXException, TransformerException { // Based on: http://stackoverflow.com/questions/10759775/how-to-merge-1000-xml-files-into-one-in-java //for (int i = 1; i < 8 ; i++) { Writer outputWriter = new FileWriter("/tmp/WpGPML.xml"); XMLOutputFactory xmlOutFactory = XMLOutputFactory.newFactory(); XMLEventWriter xmlEventWriter = xmlOutFactory.createXMLEventWriter(outputWriter); XMLEventFactory xmlEventFactory = XMLEventFactory.newFactory(); xmlEventWriter.add(xmlEventFactory.createStartDocument("ISO-8859-1", "1.0")); xmlEventWriter.add(xmlEventFactory.createStartElement("", null, "PathwaySet")); xmlEventWriter.add(xmlEventFactory.createAttribute("creationData", basicCalls.now())); XMLInputFactory xmlInFactory = XMLInputFactory.newFactory(); File dir = new File(gpmlLocation); File[] rootFiles = dir.listFiles(); //the section below is only in case of analysis sets for (File rootFile : rootFiles) { String fileName = FilenameUtils.removeExtension(rootFile.getName()); System.out.println(fileName); String[] identifiers = fileName.split("_"); System.out.println(fileName); String wpIdentifier = identifiers[identifiers.length - 2]; String wpRevision = identifiers[identifiers.length - 1]; //Pattern pattern = Pattern.compile("_(WP[0-9]+)_([0-9]+).gpml"); //Matcher matcher = pattern.matcher(fileName); //System.out.println(matcher.find()); //String wpIdentifier = matcher.group(1); File tempFile = new File(constants.localAllGPMLCacheDir() + wpIdentifier + "_" + wpRevision + ".gpml"); //System.out.println(matcher.group(1)); //String wpRevision = matcher.group(2); //System.out.println(matcher.group(2)); if (!(tempFile.exists())) { System.out.println(tempFile.getName()); Document currentGPML = basicCalls.openXmlFile(rootFile.getPath()); basicCalls.saveDOMasXML(WpRDFFunctionLibrary.addWpProvenance(currentGPML, wpIdentifier, wpRevision), constants.localCurrentGPMLCache() + tempFile.getName()); }// www. j a v a 2 s . c o m } dir = new File("/tmp/GPML"); rootFiles = dir.listFiles(); for (File rootFile : rootFiles) { System.out.println(rootFile); XMLEventReader xmlEventReader = xmlInFactory.createXMLEventReader(new StreamSource(rootFile)); XMLEvent event = xmlEventReader.nextEvent(); // Skip ahead in the input to the opening document element try { while (event.getEventType() != XMLEvent.START_ELEMENT) { event = xmlEventReader.nextEvent(); } do { xmlEventWriter.add(event); event = xmlEventReader.nextEvent(); } while (event.getEventType() != XMLEvent.END_DOCUMENT); xmlEventReader.close(); } catch (Exception e) { System.out.println("Malformed gpml file"); } } xmlEventWriter.add(xmlEventFactory.createEndElement("", null, "PathwaySet")); xmlEventWriter.add(xmlEventFactory.createEndDocument()); xmlEventWriter.close(); outputWriter.close(); }
From source file:fr.gael.dhus.server.http.webapp.search.controller.SearchController.java
void xmlToJson(InputStream xmlInput, OutputStream jsonOutput) throws XMLStreamException { JsonXMLConfig config = new JsonXMLConfigBuilder().autoArray(true).autoPrimitive(false).fieldPrefix("") .contentField("content").build(); XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(xmlInput); XMLEventWriter writer = new JsonXMLOutputFactory(config).createXMLEventWriter(jsonOutput); writer.add(reader); reader.close();// www . j a v a2 s . c om writer.close(); }
From source file:eu.delving.sip.base.Harvestor.java
@Override public void run() { try {// w ww .j a v a 2 s . c om if (context.harvestPrefix() == null || context.harvestPrefix().trim().isEmpty()) { throw new IllegalArgumentException("Harvest prefix missing"); } new URL(context.harvestUrl()); // throws MalformedUrlException if it is OutputStream outputStream = new GZIPOutputStream(new FileOutputStream(dataSet.importedOutput())); XMLEventWriter out = outputFactory.createXMLEventWriter(new OutputStreamWriter(outputStream, "UTF-8")); out.add(eventFactory.createStartDocument()); out.add(eventFactory.createCharacters("\n")); progressListener.setProgress(recordCount); HttpEntity fetchedRecords = fetchFirstEntity(); String resumptionToken = saveRecords(fetchedRecords, out); while (isValidResumptionToken(resumptionToken) && recordCount > 0) { EntityUtils.consume(fetchedRecords); progressListener.setProgress(recordCount); fetchedRecords = fetchNextEntity(resumptionToken); resumptionToken = saveRecords(fetchedRecords, out); if (!isValidResumptionToken(resumptionToken) && recordCount > 0) EntityUtils.consume(fetchedRecords); } out.add(eventFactory.createEndElement("", "", ENVELOPE_TAG)); out.add(eventFactory.createCharacters("\n")); out.add(eventFactory.createEndDocument()); out.flush(); outputStream.close(); } catch (CancelException e) { progressListener.getFeedback().alert("Cancelled harvest of " + context.harvestUrl(), e); recordCount = 0; } catch (Exception e) { progressListener.getFeedback().alert(String.format("Unable to complete harvest of %s because of: %s", context.harvestUrl(), e.getMessage()), e); recordCount = 0; } finally { if (recordCount > 0) { progressListener.getFeedback().alert(String.format("Harvest of %s successfully fetched %d records", context.harvestUrl(), recordCount)); } else { FileUtils.deleteQuietly(dataSet.importedOutput()); } } }
From source file:log4JToXml.xmlToProperties.XmlToLog4jConverterImpl.java
private void addDTDDeclaration(String filename) throws XMLStreamException { XMLEventFactory eventFactory = XMLEventFactory.newInstance(); XMLEvent dtd = eventFactory/*from ww w . ja v a 2 s . c o m*/ .createDTD("<!DOCTYPE log4j:configuration SYSTEM \"" + tempDTD.getAbsolutePath() + "\">"); XMLInputFactory inFactory = XMLInputFactory.newInstance(); XMLOutputFactory outFactory = XMLOutputFactory.newInstance(); XMLEventReader reader = inFactory.createXMLEventReader(new StreamSource(filename)); reader = new DTDReplacer(reader, dtd); XMLEventWriter writer = outFactory.createXMLEventWriter(documentStream); writer.add(reader); writer.flush(); writer.close(); }
From source file:org.javelin.sws.ext.bind.SweJaxbMarshaller.java
/** * The main marshal method which converts an object into a series of {@link XMLEventWriter XML events} being added to {@link XMLEventWriter}. * /*from www . j a v a 2s . c o m*/ * @param jaxbElement * @param writer */ private void marshal0(Object jaxbElement, XMLEventWriter writer) throws JAXBException { ElementPattern<?> pattern = this.determineXmlPattern(jaxbElement); try { if (this.formatting) writer = new IndentingXMLEventWriter(writer); if (!this.fragment) writer.add(XmlEventsPattern.XML_EVENTS_FACTORY.createStartDocument(this.encoding, "1.0", true)); MarshallingContext context = new MarshallingContext(); // TODO: correctly handle internal xmlOutputFactory's IS_REPAIRING_NAMESPACES property! context.setRepairingXmlEventWriter( (Boolean) this.xmlOutputFactory.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES)); context.setMultiRefEncoding(this.multiRefEncoding); context.setSendTypes(this.sendTypes); // go! pattern.replay(jaxbElement, writer, context); if (context.isMultiRefEncoding()) context.getMultiRefSupport().outputMultiRefs(writer, context); if (!this.fragment) writer.add(XmlEventsPattern.XML_EVENTS_FACTORY.createEndDocument()); } catch (XMLStreamException e) { throw new MarshalException(e); } }
From source file:sapience.injectors.stax.inject.StringBasedStaxStreamInjector.java
/** * If the reference is a attribute (e.g. sawsdl:modelreference), we add it here (by creating * the according XMLEvent)/*from w w w . jav a 2 s . co m*/ * @param w * @param ref * @throws XMLStreamException */ private void handleAttribute(XMLEventWriter w, Reference ref) throws XMLStreamException { String target = ref.getTarget().toString(); // TODO: should also make user of the event writer String[] attributes = target.split(" "); for (String attribute : attributes) { w.add(createAttribute(attribute)); } }