List of usage examples for javax.xml.stream XMLStreamWriter writeStartDocument
public void writeStartDocument(String encoding, String version) throws XMLStreamException;
From source file:org.sfs.nodes.compute.container.GetContainer.java
@Override public void handle(final SfsRequest httpServerRequest) { VertxContext<Server> vertxContext = httpServerRequest.vertxContext(); aVoid().flatMap(new Authenticate(httpServerRequest)) .flatMap(new ValidateActionAuthenticated(httpServerRequest)) .map(aVoid -> fromSfsRequest(httpServerRequest)).map(new ValidateContainerPath()) .flatMap(new LoadAccountAndContainer(vertxContext)) .flatMap(new ValidateActionContainerListObjects(httpServerRequest)).flatMap(persistentContainer -> { HttpServerResponse httpServerResponse = httpServerRequest.response(); MultiMap queryParams = httpServerRequest.params(); MultiMap headerParams = httpServerRequest.headers(); String format = queryParams.get(FORMAT); String accept = headerParams.get(ACCEPT); MediaType parsedAccept = null; if (equalsIgnoreCase("xml", format)) { parsedAccept = APPLICATION_XML_UTF_8; } else if (equalsIgnoreCase("json", format)) { parsedAccept = JSON_UTF_8; }/*from w ww . j ava2s .c om*/ if (parsedAccept == null) { if (!isNullOrEmpty(accept)) { parsedAccept = parse(accept); } } if (parsedAccept == null || (!PLAIN_TEXT_UTF_8.is(parsedAccept) && !APPLICATION_XML_UTF_8.is(parsedAccept) && !JSON_UTF_8.equals(parsedAccept))) { parsedAccept = PLAIN_TEXT_UTF_8; } Observable<Optional<ContainerStats>> oContainerStats; boolean hasPrefix = !Strings.isNullOrEmpty(queryParams.get(SfsHttpQueryParams.PREFIX)); if (hasPrefix) { oContainerStats = just(persistentContainer) .flatMap(new LoadContainerStats(httpServerRequest.vertxContext())) .map(Optional::of); } else { oContainerStats = Defer.just(Optional.<ContainerStats>absent()); } Observable<ObjectList> oObjectListing = just(persistentContainer) .flatMap(new ListObjects(httpServerRequest)); MediaType finalParsedAccept = parsedAccept; return combineSinglesDelayError(oContainerStats, oObjectListing, (containerStats, objectList) -> { if (containerStats.isPresent()) { Metadata metadata = persistentContainer.getMetadata(); for (String key : metadata.keySet()) { SortedSet<String> values = metadata.get(key); if (values != null && !values.isEmpty()) { httpServerResponse.putHeader( format("%s%s", X_ADD_CONTAINER_META_PREFIX, key), values); } } httpServerResponse.putHeader(X_CONTAINER_OBJECT_COUNT, valueOf(containerStats.get().getObjectCount())); httpServerResponse.putHeader(X_CONTAINER_BYTES_USED, BigDecimal.valueOf(containerStats.get().getBytesUsed()) .setScale(0, ROUND_HALF_UP).toString()); } BufferOutputStream bufferOutputStream = new BufferOutputStream(); if (JSON_UTF_8.is(finalParsedAccept)) { try { JsonFactory jsonFactory = vertxContext.verticle().jsonFactory(); JsonGenerator jg = jsonFactory.createGenerator(bufferOutputStream, UTF8); jg.writeStartArray(); for (ListedObject listedObject : ordered(objectList.getObjects())) { jg.writeStartObject(); jg.writeStringField("hash", base16().lowerCase().encode(listedObject.getEtag())); jg.writeStringField("last_modified", toDateTimeString(listedObject.getLastModified())); jg.writeNumberField("bytes", listedObject.getLength()); jg.writeStringField("content_type", listedObject.getContentType()); jg.writeStringField("name", listedObject.getName()); jg.writeEndObject(); } jg.writeEndArray(); jg.close(); } catch (IOException e) { throw new RuntimeException(e); } } else if (APPLICATION_XML_UTF_8.is(finalParsedAccept)) { String charset = UTF_8.toString(); XMLStreamWriter writer = null; try { writer = newFactory().createXMLStreamWriter(bufferOutputStream, charset); writer.writeStartDocument(charset, "1.0"); writer.writeStartElement("container"); writer.writeAttribute("name", fromPaths(persistentContainer.getId()).containerName().get()); for (ListedObject listedObject : ordered(objectList.getObjects())) { writer.writeStartElement("object"); writer.writeStartElement("name"); writer.writeCharacters(listedObject.getName()); writer.writeEndElement(); writer.writeStartElement("hash"); writer.writeCharacters( base16().lowerCase().encode(listedObject.getEtag())); writer.writeEndElement(); writer.writeStartElement("bytes"); writer.writeCharacters(valueOf(listedObject.getLength())); writer.writeEndElement(); writer.writeStartElement("content_type"); writer.writeCharacters(listedObject.getContentType()); writer.writeEndElement(); writer.writeStartElement("last_modified"); writer.writeCharacters( toDateTimeString(listedObject.getLastModified())); writer.writeEndElement(); writer.writeEndElement(); } writer.writeEndElement(); writer.writeEndDocument(); } catch (XMLStreamException e) { throw new RuntimeException(e); } finally { try { if (writer != null) { writer.close(); } } catch (XMLStreamException e) { LOGGER.warn(e.getLocalizedMessage(), e); } } } else { String charset = UTF_8.toString(); try (OutputStreamWriter outputStreamWriter = new OutputStreamWriter( bufferOutputStream, charset)) { for (ListedObject listedObject : ordered(objectList.getObjects())) { outputStreamWriter.write(listedObject.getName()); outputStreamWriter.write("\n"); } } catch (IOException e) { throw new RuntimeException(e); } } objectList.clear(); return bufferOutputStream; }).flatMap(bufferOutputStream -> { Buffer buffer = bufferOutputStream.toBuffer(); httpServerResponse.putHeader(HttpHeaders.CONTENT_TYPE, finalParsedAccept.toString()) .putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(buffer.length())); return AsyncIO.append(buffer, httpServerRequest.response()); }); }).single().subscribe(new ConnectionCloseTerminus<Void>(httpServerRequest) { @Override public void onNext(Void aVoid) { } } ); }
From source file:com.github.lindenb.jvarkit.tools.bam2xml.Bam2Xml.java
private int run(SamReader samReader) { OutputStream fout = null;//from w ww. j a va2 s .c o m SAMRecordIterator iter = null; XMLStreamWriter w = null; try { XMLOutputFactory xmlfactory = XMLOutputFactory.newInstance(); if (getOutputFile() != null) { fout = IOUtils.openFileForWriting(getOutputFile()); w = xmlfactory.createXMLStreamWriter(fout, "UTF-8"); } else { w = xmlfactory.createXMLStreamWriter(stdout(), "UTF-8"); } w.writeStartDocument("UTF-8", "1.0"); final SAMFileHeader header = samReader.getFileHeader(); final SAMXMLWriter xw = new SAMXMLWriter(w, header); final SAMSequenceDictionaryProgress progress = new SAMSequenceDictionaryProgress(header); iter = samReader.iterator(); while (iter.hasNext()) { xw.addAlignment(progress.watch(iter.next())); } xw.close(); w.writeEndDocument(); if (fout != null) fout.flush(); } catch (Exception e) { e.printStackTrace(); LOG.error(e); return -1; } finally { CloserUtil.close(w); CloserUtil.close(iter); CloserUtil.close(fout); } return 0; }
From source file:com.smartbear.jenkins.plugins.testcomplete.TcLogParser.java
private void convertToXML(ZipFile logArchive, TcLogInfo logInfo, XMLStreamWriter writer) throws ParsingException, XMLStreamException { writer.writeStartDocument("utf-8", "1.0"); Node descriptionTopLevelNode = NodeUtils.getRootDocumentNodeFromArchive(logArchive, DESCRIPTION_ENTRY_NAME); if (descriptionTopLevelNode == null) { throw new ParsingException("Unable to obtain description top-level node."); }/* w w w . j a v a2 s. co m*/ Node topLevelNode = NodeUtils.getRootDocumentNodeFromArchive(logArchive, NodeUtils.getTextProperty(descriptionTopLevelNode, "root file name")); if (topLevelNode == null) { throw new ParsingException("Unable to obtain root top-level node."); } NodeList rootNodes = topLevelNode.getChildNodes(); Node rootOwnerNode = NodeUtils.findRootOwnerNode(rootNodes); if (rootOwnerNode == null) { throw new ParsingException("Unable to obtain root owner node."); } boolean isSuite = "{00000000-0000-0000-0000-000000000000}" .equals(NodeUtils.getTextProperty(rootOwnerNode, "projectkey")); Node rootOwnerNodeInfo = NodeUtils.getRootDocumentNodeFromArchive(logArchive, NodeUtils.getTextProperty(rootOwnerNode, "filename")); if (rootOwnerNodeInfo == null) { throw new ParsingException("Unable to obtain root owner node info."); } Node rootOwnerNodeInfoSummary = NodeUtils.findNamedNode(rootOwnerNodeInfo.getChildNodes(), "summary"); boolean isSuiteOrProject = rootOwnerNodeInfoSummary != null; writer.writeStartElement("testsuites"); if (isSuite) { List<Node> projects = NodeUtils.findChildNodes(rootOwnerNode, rootOwnerNode.getParentNode().getChildNodes()); for (Node projectNode : projects) { Node projectNodeInfo = NodeUtils.getRootDocumentNodeFromArchive(logArchive, NodeUtils.getTextProperty(projectNode, "filename")); Node projectNodeInfoSummary = NodeUtils.findNamedNode(projectNodeInfo, "summary"); processProject(logArchive, projectNode, projectNodeInfoSummary, writer); } } else if (isSuiteOrProject) { processProject(logArchive, rootOwnerNode, rootOwnerNodeInfoSummary, writer); } else { String testCaseName = NodeUtils.getTextProperty(rootOwnerNode, "name"); String testCaseDuration = Double.toString(logInfo.getTestDuration() / 1000f); writer.writeStartElement("testsuite"); writer.writeAttribute("name", project); writer.writeAttribute("time", testCaseDuration); writer.writeStartElement("testcase"); writer.writeAttribute("name", fixTestCaseName(testCaseName)); writer.writeAttribute("classname", suite + "." + project); writer.writeAttribute("time", testCaseDuration); if (checkFail(NodeUtils.getTextProperty(rootOwnerNode, "status"))) { writer.writeStartElement("failure"); List<String> messages = NodeUtils.getErrorMessages(rootOwnerNodeInfo); if (errorOnWarnings) { messages.addAll(NodeUtils.getWarningMessages(rootOwnerNodeInfo)); } writer.writeAttribute("message", StringUtils.join(messages, "\n\n")); writer.writeEndElement(); //failure } writer.writeEndElement(); //testcase writer.writeEndElement(); //testsuite } writer.writeEndElement(); //testsuites writer.writeEndDocument(); }
From source file:de.uzk.hki.da.cb.CreatePremisAction.java
/** * Start new document.//w w w. j ava2s . c o m * * @param filePath the file path * @return the xML stream writer */ private XMLStreamWriter startNewDocument(String filePath) { XMLStreamWriter newWriter; XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); try { outputStream = new FileOutputStream(filePath); } catch (FileNotFoundException e) { throw new RuntimeException("Failed to create FileOutputStream", e); } try { newWriter = outputFactory.createXMLStreamWriter(outputStream); newWriter.writeStartDocument("UTF-8", "1.0"); newWriter.setPrefix("xsi", XSI_NS); } catch (Exception e) { throw new RuntimeException("Failed to create XMLStreamWriter", e); } return newWriter; }
From source file:de.qucosa.webapi.v1.DocumentResource.java
private ResponseEntity<String> errorResponse(String message, HttpStatus status) throws XMLStreamException { StringWriter sw = new StringWriter(); XMLStreamWriter w = xmlOutputFactory.createXMLStreamWriter(sw); w.writeStartDocument("UTF-8", "1.0"); w.writeStartElement("Opus"); w.writeStartElement("Error"); w.writeAttribute("message", message); w.writeEndElement();/*from w w w. j a v a2 s .co m*/ w.writeEndElement(); w.writeEndDocument(); w.flush(); return new ResponseEntity<>(sw.toString(), status); }
From source file:de.qucosa.webapi.v1.DocumentResource.java
private String getDocumentUpdatedResponse() throws XMLStreamException { StringWriter sw = new StringWriter(); XMLStreamWriter w = xmlOutputFactory.createXMLStreamWriter(sw); w.writeStartDocument("UTF-8", "1.0"); w.writeStartElement("Opus"); w.writeStartElement("Opus_Document_Info"); w.writeCharacters("Update was successful."); w.writeEndElement();//from ww w. j a v a 2 s.c o m w.writeEndElement(); w.writeEndDocument(); w.flush(); return sw.toString(); }
From source file:de.qucosa.webapi.v1.DocumentResource.java
private String getDocumentCreatedResponse(String id) throws XMLStreamException { StringWriter sw = new StringWriter(); XMLStreamWriter w = xmlOutputFactory.createXMLStreamWriter(sw); w.writeStartDocument("UTF-8", "1.0"); w.writeStartElement("Opus"); w.writeStartElement("Opus_Document"); w.writeNamespace(XLINK_NAMESPACE_PREFIX, XLINK_NAMESPACE); w.writeAttribute(XLINK_NAMESPACE, "href", getHrefLink(id)); w.writeAttribute("id", id); w.writeEndElement();//from ww w.j av a 2 s . c o m w.writeEndElement(); w.writeEndDocument(); w.flush(); return sw.toString(); }
From source file:de.qucosa.webapi.v1.DocumentResource.java
@RequestMapping(value = "/document", method = RequestMethod.GET) public ResponseEntity<String> listAll() throws IOException, FedoraClientException, XMLStreamException { List<String> pids = fedoraRepository.getPIDsByPattern("^qucosa:"); StringWriter sw = new StringWriter(); XMLStreamWriter w = xmlOutputFactory.createXMLStreamWriter(sw); w.writeStartDocument("UTF-8", "1.0"); w.writeStartElement("Opus"); w.writeAttribute("version", "2.0"); w.writeStartElement("DocumentList"); w.writeNamespace("xlink", "http://www.w3.org/1999/xlink"); for (String pid : pids) { String nr = pid.substring(pid.lastIndexOf(':') + 1); String href = getHrefLink(nr); w.writeEmptyElement("Document"); w.writeAttribute("xlink:href", href); w.writeAttribute("xlink:nr", nr); w.writeAttribute("xlink:type", "simple"); }/*w ww .j a v a2s .c o m*/ w.writeEndElement(); w.writeEndElement(); w.writeEndDocument(); w.flush(); return new ResponseEntity<>(sw.toString(), HttpStatus.OK); }
From source file:eionet.cr.util.odp.ODPDatasetsPacker.java
/** * @param writer/*from w ww . j a v a 2 s. c o m*/ * @throws XMLStreamException */ private void writeManifestHeader(XMLStreamWriter writer) throws XMLStreamException { // Start the XML document writer.writeStartDocument(ENCODING, "1.0"); // Register all relevant namespaces. registerNamespaces(MANIFEST_FILE_NAMESPACES, writer); // Write root element start tag (i.e. <ecodp:manifest>) writer.writeStartElement(Namespace.ECODP.getUri(), "manifest"); // Write namespace prefixes in the root element start tag. for (Namespace namespace : MANIFEST_FILE_NAMESPACES) { writer.writeNamespace(namespace.getPrefix(), namespace.getUri()); } // It's ok to instantiate SimpleDateFormat every time here, since this method gets called once per package generation. String packageId = PACKAGE_ID_PREFIX + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String generationDateTime = Util.virtuosoDateToString(new Date()); writer.writeAttribute(Namespace.ECODP.getUri(), "creation-date-time", generationDateTime); writer.writeAttribute(Namespace.ECODP.getUri(), "package-id", packageId); writer.writeAttribute(Namespace.ECODP.getUri(), "priority", "normal"); writer.writeAttribute(Namespace.ECODP.getUri(), "publisher", "http://publications.europa.eu/resource/authority/corporate-body/CNECT"); writer.writeAttribute(Namespace.ECODP.getUri(), "version", "1.0"); writer.writeAttribute(Namespace.XSI.getUri(), "schemaLocation", "http://open-data.europa.eu/ontologies/protocol-v1.0/odp-protocol.xsd"); }
From source file:de.codesourcery.eve.skills.dao.impl.FileShoppingListDAO.java
protected void writeToFile() { XMLStreamWriter writer = null; try {/*from w ww . j a v a 2s . c o m*/ if (!dataFile.exists()) { final File parent = dataFile.getParentFile(); if (parent != null && !parent.exists()) { if (!parent.mkdirs()) { log.error("writeToFile(): Failed to create parent directory " + parent.getAbsolutePath()); } else { log.info("writeToFile(): Created parent directory " + parent.getAbsolutePath()); } } } final XMLOutputFactory factory = XMLOutputFactory.newInstance(); log.info("writeToFile(): Writing to " + dataFile.getAbsolutePath()); final FileOutputStream outStream = new FileOutputStream(dataFile); writer = factory.createXMLStreamWriter(outStream, OUTPUT_ENCODING); writer.writeStartDocument(OUTPUT_ENCODING, "1.0"); writer.writeStartElement("shoppinglists"); // <shoppinglists> synchronized (this.entries) { for (ShoppingList list : this.entries) { writer.writeStartElement("shoppinglist"); writer.writeAttribute("title", list.getTitle()); if (!StringUtils.isBlank(list.getDescription())) { writer.writeStartElement("description"); writer.writeCharacters(list.getDescription()); writer.writeEndElement(); // </description> } writer.writeStartElement("entries"); for (ShoppingListEntry entry : list.getEntries()) { writer.writeStartElement("entry"); writer.writeAttribute("itemId", Long.toString(entry.getType().getId())); writer.writeAttribute("totalQuantity", Long.toString(entry.getQuantity())); writer.writeAttribute("purchasedQuantity", Long.toString(entry.getPurchasedQuantity())); writer.writeEndElement(); // </entry> } writer.writeEndElement(); // </entries> writer.writeEndElement(); // </shoppinglist> } } writer.writeEndElement(); // </shoppinglists> writer.writeEndDocument(); writer.flush(); writer.close(); } catch (FileNotFoundException e) { log.error("writeToFile(): Caught ", e); throw new RuntimeException("Unable to save shopping list to " + dataFile, e); } catch (XMLStreamException e) { log.error("writeToFile(): Caught ", e); throw new RuntimeException("Unable to save shopping list to " + dataFile, e); } finally { if (writer != null) { try { writer.close(); } catch (XMLStreamException e) { log.error("writeToFile(): Caught ", e); } } } }