private XMLStreamWriter getXmlStreamWriter(String fileName) { try { // to avoid filename with forbidden symbols fileName = Util.deleteForbiddenSymbols(fileName); // if for some XMLStreamWriter was run writeStartDocument, // run writeEndDocument and close it if (last != null) { last.writeEndDocument(); last.close(); } // if..., create XMLStreamWriter to out if (fileName == null) { last = XMLOutputFactory.newInstance().createXMLStreamWriter(System.out); // else, create XMLStreamWriter to file } else { last = XMLOutputFactory.newInstance().createXMLStreamWriter(new FileOutputStream(fileName)); } last.writeStartDocument(); } catch (XMLStreamException | FileNotFoundException e) { Util.handleException(e); } return last; }
private void increaseSearchIndexStartTimeDelay() throws Exception { FileOutputStream fileOutputStream = null; XMLStreamWriter writer = null; OMElement documentElement = getRegistryXmlOmElement(); try { AXIOMXPath xpathExpression = new AXIOMXPath("/wso2registry/indexingConfiguration/startingDelayInSeconds"); OMElement indexConfigNode = (OMElement) xpathExpression.selectSingleNode(documentElement); indexConfigNode.setText("2"); AXIOMXPath xpathExpression1 = new AXIOMXPath("/wso2registry/indexingConfiguration/indexingFrequencyInSeconds"); OMElement indexConfigNode1 = (OMElement) xpathExpression1.selectSingleNode(documentElement); indexConfigNode1.setText("1"); fileOutputStream = new FileOutputStream(getRegistryXMLPath()); writer = XMLOutputFactory.newInstance().createXMLStreamWriter(fileOutputStream); documentElement.serialize(writer); documentElement.build(); Thread.sleep(2000); } catch (Exception e) { log.error("registry.xml edit fails" + e.getMessage()); throw new Exception("registry.xml edit fails" + e.getMessage()); } finally { assert fileOutputStream != null; fileOutputStream.close(); assert writer != null; writer.flush(); } }
/** Use Staxon to convert JSON to an XML string */ @Override protected Object doTransform(Object src, String enc) throws TransformerException { XMLInputFactory inputFactory = new JsonXMLInputFactory(); inputFactory.setProperty(JsonXMLInputFactory.PROP_MULTIPLE_PI, false); TransformerInputs inputs = new TransformerInputs(this, src); Source source; try { if (inputs.getInputStream() != null) { source = new StAXSource( inputFactory.createXMLStreamReader( inputs.getInputStream(), enc == null ? "UTF-8" : enc)); } else { source = new StAXSource(inputFactory.createXMLStreamReader(inputs.getReader())); } XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); return convert(source, outputFactory); } catch (Exception ex) { throw new TransformerException(this, ex); } finally { IOUtils.closeQuietly(inputs.getInputStream()); IOUtils.closeQuietly(inputs.getReader()); } }
@Override public ISORecord inspect(ISORecord record, Connection conn, SQLDialect dialect) throws MetadataInspectorException { ISORecord result = record; try { // create temporary sink for normalized XML ByteArrayOutputStream bos = new ByteArrayOutputStream(); XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(bos); writer = new NamespaceNormalizingXMLStreamWriter(writer, nsBindings); // create normalized copy XMLStreamReader reader = record.getAsXMLStream(); XMLAdapter.writeElement(writer, reader); reader.close(); writer.close(); InputStream is = new ByteArrayInputStream(bos.toByteArray()); XMLStreamReader xmlStream = XMLInputFactory.newInstance().createXMLStreamReader(is); result = new ISORecord(xmlStream); } catch (Throwable t) { LOG.error( "Namespace normalization failed. Proceeding with unnormalized record. Error: " + t.getMessage()); } return result; }
protected static XMLEventWriter getEventWriter(final OutputStream os) throws XMLStreamException { if (ofactory == null) { ofactory = XMLOutputFactory.newInstance(); } return ofactory.createXMLEventWriter(os, "UTF-8"); }
public XmlWriter(File output) throws FileNotFoundException, WriterException { this.xmlFile = output; System.out.println("setting up xml"); if (output.exists()) { System.out.println("deleting existing file: " + output); output.delete(); } try { FileOutputStream fos = new FileOutputStream(output); XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); eventWriter = outputFactory.createXMLEventWriter(fos); eventFactory = XMLEventFactory.newInstance(); end = eventFactory.createDTD("\n"); // Create and write Start Tag StartDocument startDocument = eventFactory.createStartDocument(); eventWriter.add(startDocument); StartElement configStartElement = eventFactory.createStartElement("", "", DOC_ELEMENT_NAME); eventWriter.add(configStartElement); eventWriter.add(end); } catch (XMLStreamException e) { throw new WriterException("unable to instantiate writer to file: " + output, e); } }
/** * @throws XMLStreamException * @throws FactoryConfigurationError * @throws IOException * @throws UnknownCRSException * @throws TransformationException */ @Test public void testPoint2() throws XMLStreamException, FactoryConfigurationError, IOException, TransformationException, UnknownCRSException { XMLStreamReaderWrapper xmlReader = new XMLStreamReaderWrapper(this.getClass().getResource(BASE_DIR + POINT2_FILE)); xmlReader.nextTag(); Point point = new GML2GeometryReader().parsePoint(xmlReader, null); Assert.assertEquals(5.0, point.get0(), DELTA); Assert.assertEquals(30.0, point.get1(), DELTA); XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); outputFactory.setProperty("javax.xml.stream.isRepairingNamespaces", new Boolean(true)); XMLMemoryStreamWriter memoryWriter = new XMLMemoryStreamWriter(); SchemaLocationXMLStreamWriter writer = new SchemaLocationXMLStreamWriter( memoryWriter.getXMLStreamWriter(), SCHEMA_LOCATION_ATTRIBUTE); GML2GeometryWriter exporter = new GML2GeometryWriter(writer, null, null, new HashSet<String>()); writer.setPrefix("gml", "http://www.opengis.net/gml"); exporter.export(point); writer.flush(); XMLAssert.assertValidity(memoryWriter.getReader(), SCHEMA_LOCATION); }
public static void doXmlOutput(boolean useRepairing) throws XMLStreamException { StringWriter buffer = new StringWriter(); XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); if (useRepairing) { outputFactory.setProperty("javax.xml.stream.isRepairingNamespaces", Boolean.TRUE); } XMLStreamWriter out = outputFactory.createXMLStreamWriter(buffer); out.writeStartDocument(); out.writeStartElement("env", "Envelope", SOAP12); out.writeNamespace("env", SOAP12); out.writeNamespace("test", "http://someTestUri"); out.writeStartElement("env", "Body", SOAP12); out.writeStartElement("test"); out.writeAttribute("foo", "bar"); out.writeEndElement(); out.writeStartElement("test"); out.writeAttribute("foo", "bar"); out.writeCharacters(""); out.writeEndElement(); out.writeStartElement("test"); out.writeAttribute("foo", "bar"); out.writeCharacters(" "); out.writeEndElement(); out.writeEndElement(); out.writeEndElement(); out.writeEndDocument(); out.close(); System.out.println("Created " + (useRepairing ? "" : "not") + " using repairing :-"); System.out.println(buffer); }
private void initialiseProjectFiles( IProject project, IContainer container, IProgressMonitor monitor) throws CoreException { // create a config Dir IFolder configFolder = project.getFolder("config"); configFolder.create(false, true, null); File configDir = configFolder.getLocation().toFile(); monitor.beginTask("Creating config file ", 1); XMLOutputFactory factory = XMLOutputFactory.newInstance(); try { XMLStreamWriter writer = factory.createXMLStreamWriter( new FileWriter(configDir.getAbsolutePath() + "\\config.xml")); writer.writeStartDocument(); writer.writeStartElement("document"); writer.writeStartElement("data"); writer.writeAttribute("name", "value"); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); writer.close(); } catch (XMLStreamException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
@Override public SerializerResult metadataDocument(final ServiceMetadata serviceMetadata) throws SerializerException { CircleStreamBuffer buffer; XMLStreamWriter xmlStreamWriter = null; try { buffer = new CircleStreamBuffer(); xmlStreamWriter = XMLOutputFactory.newInstance() .createXMLStreamWriter(buffer.getOutputStream(), DEFAULT_CHARSET); MetadataDocumentXmlSerializer serializer = new MetadataDocumentXmlSerializer(serviceMetadata); serializer.writeMetadataDocument(xmlStreamWriter); xmlStreamWriter.flush(); xmlStreamWriter.close(); return SerializerResultImpl.with().content(buffer.getInputStream()).build(); } catch (final XMLStreamException e) { log.error(e.getMessage(), e); throw new SerializerException( "An I/O exception occurred.", e, SerializerException.MessageKeys.IO_EXCEPTION); } finally { if (xmlStreamWriter != null) { try { xmlStreamWriter.close(); } catch (XMLStreamException e) { throw new SerializerException( "An I/O exception occurred.", e, SerializerException.MessageKeys.IO_EXCEPTION); } } } }
public void export(File f, ConceptMap cmap) { this.cmap = cmap; try (OutputStream outputStream = new FileOutputStream(f)) { out = XMLOutputFactory.newInstance() .createXMLStreamWriter(new OutputStreamWriter(outputStream, "utf-8")); out.writeStartElement("cmap"); out.writeStartElement("map"); writeConceptList(); writeLinkList(); writeConnections(); out.writeEndElement(); out.writeEndElement(); out.writeEndDocument(); out.flush(); } catch (Exception e) { LOG.error(ERROR_MESSAGE, e); } }
/** * Generiert zu einem Scratch-Programm eine XML-Repräsentation und liefert diese als String * * @param program * @return */ public static String toXML(ScratchProgram program) { XMLStreamWriter writer = null; StringWriter strWriter = new StringWriter(); try { XMLOutputFactory factory = XMLOutputFactory.newInstance(); writer = factory.createXMLStreamWriter(strWriter); writer.writeStartDocument(); writer.writeStartElement(ScratchHamsterFile.SCRATCH_TAG); StorageController controller = program.getProgram(); if (controller != null) { program.getProgram().toXML(writer); } writer.writeEndElement(); writer.writeEndDocument(); } catch (Throwable exc) { exc.printStackTrace(); } finally { try { if (writer != null) { writer.close(); } } catch (Throwable exc) { exc.printStackTrace(); } } return strWriter.toString(); }
/** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { try { String fileName = null; try { if (args[0].equals("-f")) { fileName = args[1]; } else { printUsage(); return; } } catch (Exception ex) { printUsage(); return; } XMLOutputFactory xof = XMLOutputFactory.newInstance(); XMLStreamWriter xtw = null; xtw = xof.createXMLStreamWriter(new FileOutputStream(fileName), "utf-8"); xtw.writeStartDocument("utf-8", "1.0"); xtw.writeComment("StAX Sample: writer.HelloWorld"); xtw.writeStartElement("hello"); xtw.writeDefaultNamespace("http://samples"); xtw.writeCharacters("this crazy"); xtw.writeEmptyElement("world"); xtw.writeEndElement(); xtw.writeEndDocument(); xtw.flush(); xtw.close(); } catch (Exception ex) { ex.printStackTrace(); System.err.println("Exception occurred while running Hello World samples"); } System.out.println("Done"); }
private static void eventWriter(OutputStream out) throws XMLStreamException { XMLOutputFactory factory = XMLOutputFactory.newInstance(); // factory.setProperty(name, value); XMLEventWriter writer = factory.createXMLEventWriter(out); XMLEventFactory ef = XMLEventFactory2.newInstance(); StartDocument startDocument = ef.createStartDocument("UTF-8", "1.0"); writer.add(startDocument); StartElement booksStartElement = ef.createStartElement("bk", Const.NSURI_BOOK, "books"); writer.add(booksStartElement); writer.add(ef.createNamespace("bk", Const.NSURI_BOOK)); for (int i = 0; i < Const.NODE_COUNTS_L; ++i) { writer.add(ef.createStartElement("bk", Const.NSURI_BOOK, "book")); writer.add(ef.createAttribute("id", String.valueOf(i + 1))); writer.add(ef.createStartElement("bk", Const.NSURI_BOOK, "name")); writer.add(ef.createCharacters("Name" + (i + 1))); writer.add(ef.createEndElement("bk", Const.NSURI_BOOK, "name")); writer.add(ef.createStartElement("bk", Const.NSURI_BOOK, "author")); writer.add(ef.createCharacters("author" + (i + 1))); writer.add(ef.createEndElement("bk", Const.NSURI_BOOK, "author")); writer.add(ef.createEndElement("bk", Const.NSURI_BOOK, "book")); } writer.add(ef.createEndElement("bk", Const.NSURI_BOOK, "books")); writer.add(ef.createEndDocument()); writer.close(); }
private static XMLStreamWriter createXMLStreamWriter(final Writer writer) { try { return XMLOutputFactory.newInstance().createXMLStreamWriter(writer); } catch (XMLStreamException e) { throw wrapException("create", e); } }
private XMLOutputFactory getXMLOutputFactory() { XMLOutputFactory f = OUTPUT_FACTORY_POOL.poll(); if (f == null) { f = XMLOutputFactory.newInstance(); } return f; }
/** * Execute the task - write the template tracks as XML. * * @throws BuildException if there is a problem while writing to the file or reading the template * tracks. */ public void execute() { if (fileName == null) { throw new BuildException("fileName parameter not set"); } FileWriter fw = null; try { fw = new FileWriter(fileName); } catch (IOException e) { throw new BuildException("failed to open output file: " + fileName, e); } try { ObjectStoreWriter userProfileOS = ObjectStoreWriterFactory.getObjectStoreWriter(userProfileAlias); XMLOutputFactory factory = XMLOutputFactory.newInstance(); XMLStreamWriter writer = factory.createXMLStreamWriter(fw); TemplateTrackBinding.marshal(userProfileOS, writer); } catch (Exception e) { throw new BuildException(e); } finally { try { fw.close(); } catch (IOException e) { throw new BuildException("failed to close output file: " + fileName, e); } } }
/** * makes a {@link Document} out of a {@link XMLStreamReader} * * @param xmlStreamReader the xmlStreamRader to convert * @return the xmlStreamRader as {@link Document} * @throws FactoryConfigurationError * @throws XMLStreamException * @throws ParserConfigurationException * @throws IOException * @throws SAXException */ public static Document getAsDocument(XMLStreamReader xmlStreamReader) throws XMLStreamException, FactoryConfigurationError, ParserConfigurationException, SAXException, IOException { StreamBufferStore store = new StreamBufferStore(); XMLStreamWriter xmlWriter = null; try { xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(store); xmlWriter.writeStartDocument(); XMLAdapter.writeElement(xmlWriter, xmlStreamReader); } finally { if (xmlWriter != null) { try { xmlWriter.close(); } catch (XMLStreamException e) { LOG.error("Unable to close xmlwriter."); } } } store.flush(); DOMParser parser = new DOMParser(); parser.parse(new InputSource(store.getInputStream())); Document doc = parser.getDocument(); store.close(); return doc; }
/** * Creates the <a href="http://wiki.mindmakers.org/projects:BML:main">Behavior Markup Language</a> * string for Avatar. * * @param utterance the utterance to speak <code>null</code> * @param ssml SSML with BML annotations * @return created XML string * @throws XMLStreamException if the stream could not be created. */ private String createBML(final String utterance, final SsmlDocument ssml) throws XMLStreamException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final XMLOutputFactory factory = XMLOutputFactory.newInstance(); final XMLStreamWriter writer = factory.createXMLStreamWriter(out, ENCODING); writer.writeStartDocument(ENCODING, "1.0"); writer.writeStartElement("bml"); writer.writeAttribute("id", "bml1"); writer.writeNamespace("ns1", BML_NAMESPACE_URI); if (ssml != null) { final Speak speak = ssml.getSpeak(); final NodeList children = speak.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { final Node child = children.item(i); final String namespace = child.getNamespaceURI(); if (namespace != null) { writeBMLNode(writer, child, utterance); } } } writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); // lastGestureEndTime = 0; writer.close(); try { String output = out.toString(ENCODING); return output; } catch (UnsupportedEncodingException e) { LOGGER.warn(e.getMessage(), e); return out.toString(); } }
private XmlGenerator(final Writer writer) throws XMLStreamException { final XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance(); if (prettyPrint) { xmlWriter = new IndentingXmlWriter(xmlOutputFactory.createXMLStreamWriter(writer)); } else { xmlWriter = xmlOutputFactory.createXMLStreamWriter(writer); } }
private static XMLOutputFactory getXMLOutputFactory() throws XMLStreamException { if (_outputFactory == null) { _outputFactory = XMLOutputFactory.newInstance(); _outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE); } return _outputFactory; }
/** * @throws XMLStreamException * @throws FactoryConfigurationError * @throws IOException * @throws UnknownCRSException * @throws TransformationException */ @Test public void testPolygon() throws XMLStreamException, FactoryConfigurationError, IOException, UnknownCRSException, TransformationException { XMLStreamReaderWrapper xmlReader = new XMLStreamReaderWrapper(this.getClass().getResource(BASE_DIR + POLYGON_FILE)); xmlReader.nextTag(); Assert.assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.getEventType()); Assert.assertEquals(new QName(GML21NS, "Polygon"), xmlReader.getName()); Polygon polygon = new GML2GeometryReader().parsePolygon(xmlReader, null); Assert.assertEquals(XMLStreamConstants.END_ELEMENT, xmlReader.getEventType()); Assert.assertEquals(new QName(GML21NS, "Polygon"), xmlReader.getName()); Points points = polygon.getExteriorRing().getControlPoints(); comparePoint(0.0, 0.0, points.get(0)); comparePoint(100.0, 0.0, points.get(1)); comparePoint(100.0, 100.0, points.get(2)); comparePoint(0.0, 100.0, points.get(3)); comparePoint(0.0, 0.0, points.get(4)); List<Points> innerPoints = polygon.getInteriorRingsCoordinates(); Points points1 = innerPoints.get(0); comparePoint(10.0, 10.0, points1.get(0)); comparePoint(10.0, 40.0, points1.get(1)); comparePoint(40.0, 40.0, points1.get(2)); comparePoint(40.0, 10.0, points1.get(3)); comparePoint(10.0, 10.0, points1.get(4)); Points points2 = innerPoints.get(1); comparePoint(60.0, 60.0, points2.get(0)); comparePoint(60.0, 90.0, points2.get(1)); comparePoint(90.0, 90.0, points2.get(2)); comparePoint(90.0, 60.0, points2.get(3)); comparePoint(60.0, 60.0, points2.get(4)); Assert.assertEquals( CRSRegistry.lookup("http://www.opengis.net/gml/srs/epsg.xml#4326"), polygon.getCoordinateSystem().getWrappedCRS()); XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); outputFactory.setProperty("javax.xml.stream.isRepairingNamespaces", new Boolean(true)); XMLMemoryStreamWriter memoryWriter = new XMLMemoryStreamWriter(); SchemaLocationXMLStreamWriter writer = new SchemaLocationXMLStreamWriter( memoryWriter.getXMLStreamWriter(), SCHEMA_LOCATION_ATTRIBUTE); GML2GeometryWriter exporter = new GML2GeometryWriter(writer, null, null, new HashSet<String>()); writer.setPrefix("gml", "http://www.opengis.net/gml"); writer.setPrefix("xlink", "http://www.w3.org/1999/xlink"); exporter.export(polygon); writer.flush(); XMLAssert.assertValidity(memoryWriter.getReader(), SCHEMA_LOCATION); }
public void marshall(Writer wrt, Object value) throws Exception { assert wrt != null && value != null; // get an XMl factory for use.. XMLOutputFactory xmlFactory = XMLOutputFactory.newInstance(); XMLStreamWriter xwrt = xmlFactory.createXMLStreamWriter(wrt); xwrt.writeStartDocument(); marshall(xwrt, (Boolean) value); xwrt.writeEndDocument(); }
public static XMLStreamWriter create(OutputStream os) throws XmlSerializerException { try { XMLOutputFactory xof = XMLOutputFactory.newInstance(); xof.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true); return xof.createXMLStreamWriter(os); } catch (XMLStreamException e) { throw new XmlSerializerException("Problem Creating a pull parser", e); } }
private XMLStreamWriter getXMLStreamWriter() { pushcontentDocumentFragment = pushDocument.createDocumentFragment(); try { return XMLOutputFactory.newInstance() .createXMLStreamWriter(new DOMResult(pushcontentDocumentFragment)); } catch (final XMLStreamException | FactoryConfigurationError e) { throw new RuntimeException(e); } }
public static void build(Writer writer, XmlElementHandler rootBuilder) throws Exception { XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); XMLStreamWriter xmlStreamWriter = outputFactory.createXMLStreamWriter(writer); xmlStreamWriter.writeStartElement(rootBuilder.getTagName()); StaxXmlWriter xmlWriter = new StaxXmlWriter(xmlStreamWriter); XmlElementHandler[] xmlHandlers = rootBuilder.handleNext(xmlWriter); write(xmlWriter, xmlHandlers); xmlStreamWriter.writeEndElement(); }
public byte[] convertToXML(BpmnModel model) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); XMLOutputFactory xof = XMLOutputFactory.newInstance(); OutputStreamWriter out = new OutputStreamWriter(outputStream, "UTF-8"); XMLStreamWriter writer = xof.createXMLStreamWriter(out); XMLStreamWriter xtw = new IndentingXMLStreamWriter(writer); DefinitionsRootExport.writeRootElement(model, xtw); SignalAndMessageDefinitionExport.writeSignalsAndMessages(model, xtw); PoolExport.writePools(model, xtw); for (Process process : model.getProcesses()) { if (process.getFlowElements().size() == 0 && process.getLanes().size() == 0) { // empty process, ignore it continue; } ProcessExport.writeProcess(process, xtw); for (FlowElement flowElement : process.getFlowElements()) { createXML(flowElement, model, xtw); } for (Artifact artifact : process.getArtifacts()) { createXML(artifact, model, xtw); } // end process element xtw.writeEndElement(); } BPMNDIExport.writeBPMNDI(model, xtw); // end definitions root element xtw.writeEndElement(); xtw.writeEndDocument(); xtw.flush(); outputStream.close(); xtw.close(); return outputStream.toByteArray(); } catch (Exception e) { LOGGER.error("Error writing BPMN XML", e); throw new XMLException("Error writing BPMN XML", e); } }
private void serializeValue(final HttpServletResponse pResponse, Object value) throws TransformerException, IOException, FactoryConfigurationError { if (value instanceof Source) { setContentType(pResponse, "application/binary"); // Unknown content type Sources.writeToStream((Source) value, pResponse.getOutputStream()); } else if (value instanceof Node) { pResponse.setContentType("text/xml"); Sources.writeToStream(new DOMSource((Node) value), pResponse.getOutputStream()); } else if (value instanceof XmlSerializable) { pResponse.setContentType("text/xml"); XMLOutputFactory factory = XMLOutputFactory.newInstance(); factory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE); try { XmlWriter out = XmlStreaming.newWriter( pResponse.getOutputStream(), pResponse.getCharacterEncoding(), true); try { out.startDocument(null, null, null); ((XmlSerializable) value).serialize(out); out.endDocument(); } finally { out.close(); } } catch (XmlException e) { throw new TransformerException(e); } } else if (value instanceof Collection) { final XmlElementWrapper annotation = getElementWrapper(); if (annotation != null) { setContentType(pResponse, "text/xml"); try (OutputStream outStream = pResponse.getOutputStream()) { writeCollection( outStream, getGenericReturnType(), (Collection<?>) value, getQName(annotation)); } } } else if (value instanceof CharSequence) { setContentType(pResponse, "text/plain"); pResponse.getWriter().append((CharSequence) value); } else { if (value != null) { try { final JAXBContext jaxbContext = JAXBContext.newInstance(getReturnType()); setContentType(pResponse, "text/xml"); final JAXBSource jaxbSource = new JAXBSource(jaxbContext, value); Sources.writeToStream(jaxbSource, pResponse.getOutputStream()); } catch (final JAXBException e) { throw new MessagingException(e); } } } }
@Override public void writeTo( DocBase doc, Class<?> genericType, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream out) throws IOException, WebApplicationException { XMLStreamWriter xmlStreamWriter = null; try { OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8"); XMLOutputFactory factory = XMLOutputFactory.newInstance(); xmlStreamWriter = factory.createXMLStreamWriter(osw); xmlStreamWriter.writeStartDocument("UTF-8", "1.0"); xmlStreamWriter.writeStartElement("document"); xmlStreamWriter.writeAttribute("id", Long.toString(doc.getId())); xmlStreamWriter.writeAttribute("mediaType", doc.getMediaType()); if (doc.getSchemaURI() != null) { xmlStreamWriter.writeAttribute("schema", doc.getSchemaURI()); } if (doc.getStatus() != null) { xmlStreamWriter.writeAttribute("status", doc.getStatus()); } xmlStreamWriter.writeAttribute("authorId", Long.toString(doc.getAuthor().getId())); xmlStreamWriter.writeAttribute( "signatureRequired", doc.isSignatureRequired() ? "true" : "false"); xmlStreamWriter.writeStartElement("attachments"); List<DocAttachment> attachments = getDocBean().findAttachments(doc); for (DocAttachment attachment : attachments) { xmlStreamWriter.writeStartElement("attachment"); xmlStreamWriter.writeAttribute("id", Long.toString(attachment.getId())); xmlStreamWriter.writeAttribute("description", attachment.getDescription()); xmlStreamWriter.writeAttribute( "documentId", Long.toString(attachment.getAttachedDocument().getId())); xmlStreamWriter.writeEndElement(); } xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndDocument(); } catch (Exception e) { throw new RuntimeException("Exception writing user account list", e); } finally { if (xmlStreamWriter != null) { try { xmlStreamWriter.close(); } catch (XMLStreamException e) { throw new RuntimeException("Error closing XML Stream writing UserAccounts", e); } } } }
public static StaxXmlRepresentation getInstance(String projectRoot, String filename) throws FileNotFoundException, XMLStreamException { StaxXmlRepresentation representation = new StaxXmlRepresentation(); XMLOutputFactory factory = XMLOutputFactory.newInstance(); File f = new File(filename); FileOutputStream stream = new FileOutputStream(f); representation.writer = factory.createXMLStreamWriter(stream, "UTF-8"); File root = new File(projectRoot); representation.projectRoot = root.getAbsolutePath(); return representation; }