List of usage examples for javax.xml.stream XMLStreamWriter writeAttribute
public void writeAttribute(String localName, String value) throws XMLStreamException;
From source file:com.basistech.bbhmp.RosapiBundleCollectorMojo.java
private void writeMetadata(Map<Integer, List<BundleSpec>> bundlesByLevel) throws MojoExecutionException { OutputStream os = null;/* ww w .j a v a2s. c o m*/ File md = new File(outputDirectory, "bundles.xml"); try { os = new FileOutputStream(md); XMLStreamWriter writer = XMLOutputFactory.newFactory().createXMLStreamWriter(os); writer = new IndentingXMLStreamWriter(writer); writer.writeStartDocument("utf-8", "1.0"); writer.writeStartElement("bundles"); for (Integer level : bundlesByLevel.keySet()) { writer.writeStartElement("level"); writer.writeAttribute("level", Integer.toString(level)); for (BundleSpec spec : bundlesByLevel.get(level)) { writer.writeStartElement("bundle"); writer.writeAttribute("start", Boolean.toString(spec.start)); writer.writeCharacters(spec.filename); writer.writeEndElement(); } writer.writeEndElement(); } writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); } catch (IOException | XMLStreamException e) { throw new MojoExecutionException("Failed to write metadata file " + md.toString(), e); } finally { IOUtils.closeQuietly(os); } }
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; }/*ww w .java 2 s.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.vcfcmp.VcfCompareCallers.java
private void watch(XMLStreamWriter out, VariantContext ctx0, VariantContext ctx1, Genotype g0, Genotype g1, String sampleName, Counter<Category> count, Category cat) throws XMLStreamException { long n = count.incr(cat); if (out == null || n > super.numberOfExampleVariants) return;/*from w ww.ja v a2 s . co m*/ VariantContext variants[] = new VariantContext[] { ctx0, ctx1 }; Genotype gts[] = new Genotype[] { g0, g1 }; out.writeStartElement("diff"); out.writeAttribute("type", cat.name()); out.writeAttribute("sample", sampleName); for (int i = 0; i < 2; ++i) { if (variants[i] == null) continue; out.writeStartElement("variant"); out.writeAttribute("file", String.valueOf(i + 1)); out.writeAttribute("type", String.valueOf(variants[i].getType())); out.writeStartElement("chrom"); out.writeCharacters(variants[i].getContig()); out.writeEndElement(); out.writeStartElement("pos"); out.writeCharacters(String.valueOf(variants[i].getStart())); out.writeEndElement(); out.writeStartElement("id"); out.writeCharacters(variants[i].hasID() ? variants[i].getID() : "."); out.writeEndElement(); out.writeStartElement("ref"); out.writeCharacters(String.valueOf(variants[i].getReference())); out.writeEndElement(); out.writeStartElement("alts"); out.writeCharacters(String.valueOf(variants[i].getAlternateAlleles())); out.writeEndElement(); if (gts[i] != null) { out.writeStartElement("genotype"); out.writeAttribute("type", String.valueOf(gts[i].getType())); for (Allele a : gts[i].getAlleles()) { out.writeStartElement("allele"); out.writeCharacters(a.toString()); out.writeEndElement(); } if (gts[i].hasDP()) { out.writeStartElement("dp"); out.writeCharacters(String.valueOf(gts[i].getDP())); out.writeEndElement(); } out.writeEndElement(); } out.writeEndElement(); } out.writeEndElement(); out.writeCharacters("\n"); }
From source file:edu.stanford.cfuller.imageanalysistools.fitting.ImageObject.java
public void writeToXML(XMLStreamWriter xsw) { try {//from ww w . j a va2 s .c o m xsw.writeStartElement(OBJECT_ELEMENT); xsw.writeAttribute(LABEL_ATTR, Integer.toString(this.label)); xsw.writeAttribute(IMAGE_ATTR, this.imageID); xsw.writeCharacters("\n"); for (int i = 0; i < this.numberOfChannels; i++) { xsw.writeStartElement(CHANNEL_ELEMENT); xsw.writeAttribute(CH_ID_ATTR, Integer.toString(i)); xsw.writeCharacters("\n"); xsw.writeStartElement(FIT_ELEMENT); xsw.writeAttribute(R2_ATTR, Double.toString(this.getFitR2ByChannel().get(i))); xsw.writeAttribute(ERROR_ATTR, Double.toString(this.getFitErrorByChannel().get(i))); xsw.writeAttribute(N_PHOTONS_ATTR, Double.toString(this.getNPhotonsByChannel().get(i))); xsw.writeCharacters("\n"); xsw.writeStartElement(PARAMETERS_ELEMENT); xsw.writeCharacters(this.getFitParametersByChannel().get(i).toString().replace(";", ",") .replace("}", "").replace("{", "")); xsw.writeEndElement(); //parameters xsw.writeCharacters("\n"); xsw.writeStartElement(POSITION_ELEMENT); xsw.writeCharacters(this.getPositionForChannel(i).toString().replace(";", ",").replace("}", "") .replace("{", "")); xsw.writeEndElement(); //position xsw.writeCharacters("\n"); xsw.writeEndElement(); //fit xsw.writeCharacters("\n"); xsw.writeEndElement(); //channel xsw.writeCharacters("\n"); } xsw.writeStartElement(SERIAL_ELEMENT); xsw.writeAttribute(ENCODING_ATTR, ENCODING_NAME); ByteArrayOutputStream bytesOutput = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(bytesOutput); oos.writeObject(this); } catch (java.io.IOException e) { LoggingUtilities.getLogger() .severe("Exception encountered while serializing ImageObject: " + e.getMessage()); } Base64BinaryAdapter adapter = new Base64BinaryAdapter(); xsw.writeCharacters(adapter.marshal(bytesOutput.toByteArray())); xsw.writeEndElement(); //serial xsw.writeCharacters("\n"); xsw.writeEndElement(); //object xsw.writeCharacters("\n"); } catch (XMLStreamException e) { LoggingUtilities.getLogger() .severe("Exception encountered while writing XML correction output: " + e.getMessage()); } }
From source file:com.microsoft.tfs.core.memento.XMLMemento.java
/** * Saves this {@link Memento} as an XML Element in the given writer * * @param writer//ww w. ja va 2 s . c o m * the writer (must not be <code>null</code>) */ private void writeAsElement(final XMLStreamWriter writer) throws XMLStreamException { writer.writeStartElement(name); /* * Write all attributes as XML attributes. */ for (final Iterator iterator = attributes.entrySet().iterator(); iterator.hasNext();) { final Entry entry = (Entry) iterator.next(); writer.writeAttribute((String) entry.getKey(), (String) entry.getValue()); } /* * Write the text node if there is one. */ if (textData != null) { writer.writeCharacters(textData); } /* * Write all children as elements. */ for (final Iterator iterator = children.iterator(); iterator.hasNext();) { final XMLMemento child = (XMLMemento) iterator.next(); child.writeAsElement(writer); } /* * Done with the element. */ writer.writeEndElement(); }
From source file:edu.stanford.cfuller.colocalization3d.correction.Correction.java
protected String writeToXML() { StringWriter sw = new StringWriter(); try {/*from w ww . j ava 2s.c o m*/ XMLStreamWriter xsw = XMLOutputFactory.newFactory().createXMLStreamWriter(sw); xsw.writeStartDocument(); xsw.writeCharacters("\n"); xsw.writeStartElement("root"); xsw.writeCharacters("\n"); xsw.writeStartElement(CORRECTION_ELEMENT); xsw.writeAttribute(N_POINTS_ATTR, Integer.toString(this.distanceCutoffs.getDimension())); xsw.writeAttribute(REF_CHANNEL_ATTR, Integer.toString(this.referenceChannel)); xsw.writeAttribute(CORR_CHANNEL_ATTR, Integer.toString(this.correctionChannel)); xsw.writeCharacters("\n"); for (int i = 0; i < this.distanceCutoffs.getDimension(); i++) { xsw.writeStartElement(CORRECTION_POINT_ELEMENT); xsw.writeAttribute(X_POS_ATTR, Double.toString(this.positionsForCorrection.getEntry(i, 0))); xsw.writeAttribute(Y_POS_ATTR, Double.toString(this.positionsForCorrection.getEntry(i, 1))); xsw.writeAttribute(Z_POS_ATTR, Double.toString(this.positionsForCorrection.getEntry(i, 2))); xsw.writeCharacters("\n"); String x_param_string = ""; String y_param_string = ""; String z_param_string = ""; for (int j = 0; j < this.correctionX.getColumnDimension(); j++) { String commaString = ""; if (j != 0) commaString = ", "; x_param_string += commaString + this.correctionX.getEntry(i, j); y_param_string += commaString + this.correctionY.getEntry(i, j); z_param_string += commaString + this.correctionZ.getEntry(i, j); } x_param_string = x_param_string.trim() + "\n"; y_param_string = y_param_string.trim() + "\n"; z_param_string = z_param_string.trim() + "\n"; xsw.writeStartElement(X_PARAM_ELEMENT); xsw.writeCharacters(x_param_string); xsw.writeEndElement(); xsw.writeCharacters("\n"); xsw.writeStartElement(Y_PARAM_ELEMENT); xsw.writeCharacters(y_param_string); xsw.writeEndElement(); xsw.writeCharacters("\n"); xsw.writeStartElement(Z_PARAM_ELEMENT); xsw.writeCharacters(z_param_string); xsw.writeEndElement(); xsw.writeCharacters("\n"); xsw.writeEndElement(); xsw.writeCharacters("\n"); } xsw.writeStartElement(BINARY_DATA_ELEMENT); xsw.writeAttribute(ENCODING_ATTR, ENCODING_NAME); ByteArrayOutputStream bytesOutput = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(bytesOutput); oos.writeObject(this); } catch (java.io.IOException e) { java.util.logging.Logger.getLogger(LOG_NAME) .severe("Exception encountered while serializing correction: " + e.getMessage()); } HexBinaryAdapter adapter = new HexBinaryAdapter(); xsw.writeCharacters(adapter.marshal(bytesOutput.toByteArray())); xsw.writeEndElement(); xsw.writeCharacters("\n"); xsw.writeEndElement(); xsw.writeCharacters("\n"); xsw.writeEndElement(); xsw.writeCharacters("\n"); xsw.writeEndDocument(); } catch (XMLStreamException e) { java.util.logging.Logger.getLogger(LOG_NAME) .severe("Exception encountered while writing XML correction output: " + e.getMessage()); } return sw.toString(); }
From source file:jp.co.atware.solr.geta.GETAssocComponent.java
/** * /*from ww w. j a v a 2 s. c o m*/ * @param xml * @param params * @param queryValue * @param queryType * @throws XMLStreamException */ protected void convReqWriteQuery(XMLStreamWriter xml, SolrParams params, String queryValue, QueryType queryType) throws XMLStreamException { if (queryType == QueryType.fulltext) { // freetext xml.writeStartElement("freetext"); String stemmer = params.get(PARAM_STEMMER, config.defaults.stemmer); if (stemmer != null) { xml.writeAttribute("stemmer", stemmer); } String freetext_cutoff_df = params.get(PARAM_FREETEXT_CUTOFF_DF, config.defaults.freetext_cutoff_df); if (config.defaults.source != null) { xml.writeAttribute("cutoff-df", freetext_cutoff_df); } xml.writeCData(queryValue); xml.writeEndElement(); } else { // article xml.writeStartElement("article"); if (queryType == QueryType.vector) { xml.writeAttribute("vec", queryValue); } else { xml.writeAttribute("name", queryValue); } String source = params.get(PARAM_SOURCE, config.defaults.source); if (source != null) { xml.writeAttribute("source", source); } String article_cutoff_df = params.get(PARAM_ARTICLE_CUTOFF_DF, config.defaults.article_cutoff_df); if (source != null) { xml.writeAttribute("cutoff-df", article_cutoff_df); } xml.writeEndElement(); } }
From source file:com.ibm.bi.dml.runtime.controlprogram.parfor.opt.PerfTestTool.java
/** * StAX for efficient streaming XML writing. * /*from w w w. j a v a 2 s. c o m*/ * @throws IOException * @throws XMLStreamException */ private static void writeProfile(String dname, String fname) throws IOException, XMLStreamException { //create initial directory and file File dir = new File(dname); if (!dir.exists()) dir.mkdir(); File f = new File(fname); f.createNewFile(); FileOutputStream fos = new FileOutputStream(f); try { //create document XMLOutputFactory xof = XMLOutputFactory.newInstance(); XMLStreamWriter xsw = xof.createXMLStreamWriter(fos); //TODO use an alternative way for intentation //xsw = new IndentingXMLStreamWriter( xsw ); //remove this line if no indenting required //write document content xsw.writeStartDocument(); xsw.writeStartElement(XML_PROFILE); xsw.writeAttribute(XML_DATE, String.valueOf(new Date())); //foreach instruction (boundle of cost functions) for (Entry<Integer, HashMap<Integer, CostFunction>> inst : _profile.entrySet()) { int instID = inst.getKey(); String instName = _regInst_IDNames.get(instID); xsw.writeStartElement(XML_INSTRUCTION); xsw.writeAttribute(XML_ID, String.valueOf(instID)); xsw.writeAttribute(XML_NAME, instName.replaceAll(Lop.OPERAND_DELIMITOR, " ")); //foreach testdef cost function for (Entry<Integer, CostFunction> cfun : inst.getValue().entrySet()) { int tdefID = cfun.getKey(); PerfTestDef def = _regTestDef.get(tdefID); CostFunction cf = cfun.getValue(); xsw.writeStartElement(XML_COSTFUNCTION); xsw.writeAttribute(XML_ID, String.valueOf(tdefID)); xsw.writeAttribute(XML_MEASURE, def.getMeasure().toString()); xsw.writeAttribute(XML_VARIABLE, def.getVariable().toString()); xsw.writeAttribute(XML_INTERNAL_VARIABLES, serializeTestVariables(def.getInternalVariables())); xsw.writeAttribute(XML_DATAFORMAT, def.getDataformat().toString()); xsw.writeCharacters(serializeParams(cf.getParams())); xsw.writeEndElement();// XML_COSTFUNCTION } xsw.writeEndElement(); //XML_INSTRUCTION } xsw.writeEndElement();//XML_PROFILE xsw.writeEndDocument(); xsw.close(); } finally { IOUtilFunctions.closeSilently(fos); } }
From source file:org.maodian.flyingcat.xmpp.state.StreamState.java
private void doHandle(XmppContext context, XMLStreamReader xmlsr, XMLStreamWriter xmlsw) throws XMLStreamException { xmlsr.nextTag();/*w ww. j av a 2s . com*/ QName qname = new QName(XmppNamespace.STREAM, "stream"); if (!xmlsr.getName().equals(qname)) { throw new XmppException(StreamError.INVALID_NAMESPACE).set("QName", xmlsr.getName()); } // throw exception if client version > 1.0 BigDecimal version = new BigDecimal(xmlsr.getAttributeValue("", "version")); if (version.compareTo(SUPPORTED_VERSION) > 0) { throw new XmppException(StreamError.UNSUPPORTED_VERSION); } xmlsw.writeStartDocument(); xmlsw.writeStartElement("stream", "stream", XmppNamespace.STREAM); xmlsw.writeNamespace("stream", XmppNamespace.STREAM); xmlsw.writeDefaultNamespace(XmppNamespace.CLIENT_CONTENT); xmlsw.writeAttribute("id", RandomStringUtils.randomAlphabetic(32)); xmlsw.writeAttribute("version", "1.0"); xmlsw.writeAttribute("from", "localhost"); xmlsw.writeAttribute(XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI, "lang", "en"); String from = xmlsr.getAttributeValue(null, "from"); if (from != null) { xmlsw.writeAttribute("to", from); } // features xmlsw.writeStartElement(XmppNamespace.STREAM, "features"); writeFeatures(xmlsw); xmlsw.writeEndElement(); }
From source file:com.moviejukebox.writer.MovieJukeboxHTMLWriter.java
/** * Generate a simple jukebox index file from scratch * * @param jukebox/*from ww w . ja v a 2 s . c o m*/ * @param library */ private static void generateDefaultIndexHTML(Jukebox jukebox, Library library) { @SuppressWarnings("resource") OutputStream fos = null; XMLStreamWriter writer = null; try { File htmlFile = new File(jukebox.getJukeboxTempLocation(), PropertiesUtil.getProperty("mjb.indexFile", "index.htm")); FileTools.makeDirsForFile(htmlFile); fos = FileTools.createFileOutputStream(htmlFile); XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); writer = outputFactory.createXMLStreamWriter(fos, "UTF-8"); String homePage = PropertiesUtil.getProperty("mjb.homePage", ""); if (homePage.length() == 0) { String defCat = library.getDefaultCategory(); if (defCat != null) { homePage = FileTools.createPrefix("Other", HTMLTools.encodeUrl(FileTools.makeSafeFilename(defCat))) + "1"; } else { // figure out something better to do here LOG.info("No categories were found, so you should specify mjb.homePage in the config file."); } } writer.writeStartDocument(); writer.writeStartElement("html"); writer.writeStartElement("head"); writer.writeStartElement("meta"); writer.writeAttribute("name", "YAMJ"); writer.writeAttribute("content", "MovieJukebox"); writer.writeEndElement(); writer.writeStartElement("meta"); writer.writeAttribute("HTTP-EQUIV", "Content-Type"); writer.writeAttribute("content", "text/html; charset=UTF-8"); writer.writeEndElement(); writer.writeStartElement("meta"); writer.writeAttribute("HTTP-EQUIV", "REFRESH"); writer.writeAttribute("content", "0; url=" + jukebox.getDetailsDirName() + '/' + homePage + EXT_HTML); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndElement(); } catch (XMLStreamException | IOException ex) { LOG.error("Failed generating HTML library index: {}", ex.getMessage()); LOG.error(SystemTools.getStackTrace(ex)); } finally { if (writer != null) { try { writer.close(); } catch (Exception ex) { LOG.trace("Failed to close XMLStreamWriter"); } } if (fos != null) { try { fos.close(); } catch (Exception ex) { LOG.trace("Failed to close FileOutputStream"); } } } }