List of usage examples for javax.xml.stream XMLStreamWriter writeStartDocument
public void writeStartDocument() throws XMLStreamException;
From source file:com.marklogic.client.impl.CombinedQueryBuilderImpl.java
private String makeXMLCombinedQuery(CombinedQueryDefinitionImpl qdef) { try {// ww w .j a v a 2s . co m ByteArrayOutputStream out = new ByteArrayOutputStream(); String qtext = qdef.qtext; StructuredQueryDefinition structuredQuery = qdef.structuredQuery; RawQueryDefinition rawQuery = qdef.rawQuery; QueryOptionsWriteHandle options = qdef.options; String sparql = qdef.sparql; if (rawQuery != null && rawQuery instanceof RawCombinedQueryDefinition) { CombinedQueryDefinitionImpl combinedQdef = parseCombinedQuery( (RawCombinedQueryDefinition) rawQuery); rawQuery = combinedQdef.rawQuery; if (qtext == null) qtext = combinedQdef.qtext; if (options == null) options = combinedQdef.options; if (sparql == null) sparql = combinedQdef.sparql; } XMLStreamWriter serializer = makeXMLSerializer(out); serializer.writeStartDocument(); serializer.writeStartElement("search"); if (qtext != null) { serializer.writeStartElement("qtext"); serializer.writeCharacters(qtext); serializer.writeEndElement(); } else { serializer.writeCharacters(""); } if (sparql != null) { serializer.writeStartElement("sparql"); serializer.writeCharacters(sparql); serializer.writeEndElement(); } serializer.flush(); String structure = ""; if (structuredQuery != null) structure = structuredQuery.serialize(); if (rawQuery != null) structure = HandleAccessor.contentAsString(rawQuery.getHandle()); out.write(structure.getBytes("UTF-8")); out.flush(); if (options != null) { HandleImplementation handleBase = HandleAccessor.as(options); Object value = handleBase.sendContent(); if (value instanceof OutputStreamSender) { ((OutputStreamSender) value).write(out); } else { out.write(HandleAccessor.contentAsString(options).getBytes("UTF-8")); } out.flush(); } serializer.writeEndElement(); serializer.writeEndDocument(); serializer.flush(); serializer.close(); return out.toString("UTF-8"); } catch (Exception e) { throw new MarkLogicIOException(e); } }
From source file:net.landora.video.info.file.FileInfoManager.java
private synchronized void writeCacheFile(File file, Map<String, FileInfo> infoMap) { OutputStream os = null;/*from w w w. j av a 2s . c o m*/ try { os = new BufferedOutputStream(new FileOutputStream(file)); if (COMPRESS_INFO_FILE) { os = new GZIPOutputStream(os); } XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(os); writer.writeStartDocument(); writer.writeStartElement("files"); writer.writeCharacters("\n"); for (Map.Entry<String, FileInfo> entry : infoMap.entrySet()) { FileInfo info = entry.getValue(); writer.writeStartElement("file"); writer.writeAttribute("filename", entry.getKey()); writer.writeAttribute("ed2k", info.getE2dkHash()); writer.writeAttribute("length", String.valueOf(info.getFileSize())); writer.writeAttribute("lastmodified", String.valueOf(info.getLastModified())); if (info.getMetadataSource() != null) { writer.writeAttribute("metadatasource", info.getMetadataSource()); } if (info.getMetadataId() != null) { writer.writeAttribute("metadataid", info.getMetadataId()); } if (info.getVideoId() != null) { writer.writeAttribute("videoid", info.getVideoId()); } writer.writeEndElement(); writer.writeCharacters("\n"); } writer.writeEndElement(); writer.writeEndDocument(); writer.close(); } catch (Exception e) { log.error("Error writing file cache.", e); } finally { if (os != null) { IOUtils.closeQuietly(os); } } }
From source file:edu.jhu.pha.vospace.node.Node.java
public String getXmlMetadata(Detail detail) { StringWriter jobWriter = new StringWriter(); try {//from www. ja v a 2 s. c o m XMLStreamWriter xsw = XMLOutputFactory.newInstance().createXMLStreamWriter(jobWriter); xsw.writeStartDocument(); xsw.setDefaultNamespace(VOS_NAMESPACE); xsw.writeStartElement("node"); xsw.writeNamespace("xsi", XSI_NAMESPACE); xsw.writeNamespace(null, VOS_NAMESPACE); xsw.writeAttribute("xsi:type", this.getType().getTypeName()); xsw.writeAttribute("uri", this.getUri().toString()); if (detail == Detail.max) { xsw.writeStartElement("properties"); Map<String, String> properties = this.getMetastore().getProperties(this.getUri()); properties.put(LENGTH_PROPERTY, Long.toString(getNodeInfo().getSize())); properties.put(DATE_PROPERTY, dropboxDateFormat.format(getNodeInfo().getMtime())); if (this.getType() == NodeType.DATA_NODE || this.getType() == NodeType.STRUCTURED_DATA_NODE || this.getType() == NodeType.UNSTRUCTURED_DATA_NODE) { properties.put(CONTENTTYPE_PROPERTY, getNodeInfo().getContentType()); } for (String propUri : properties.keySet()) { xsw.writeStartElement("property"); xsw.writeAttribute("uri", propUri); xsw.writeCharacters(properties.get(propUri)); xsw.writeEndElement(); } xsw.writeEndElement(); xsw.writeStartElement("accepts"); xsw.writeEndElement(); xsw.writeStartElement("provides"); xsw.writeEndElement(); xsw.writeStartElement("capabilities"); xsw.writeEndElement(); if (this.getType() == NodeType.CONTAINER_NODE) { NodesList childrenList = ((ContainerNode) this).getDirectChildren(false, 0, -1); List<Node> children = childrenList.getNodesList(); xsw.writeStartElement("nodes"); for (Node childNode : children) { xsw.writeStartElement("node"); xsw.writeAttribute("uri", childNode.getUri().getId().toString()); xsw.writeEndElement(); } xsw.writeEndElement(); } } xsw.writeEndElement(); xsw.writeEndDocument(); xsw.close(); } catch (XMLStreamException e) { e.printStackTrace(); throw new InternalServerErrorException(e); } return jobWriter.getBuffer().toString(); }
From source file:jp.co.atware.solr.geta.GETAssocComponent.java
/** * GETAssoc??????/* ww w. java2s.c o m*/ * * @param params * @param queryValue * @param queryType * @return * @throws FactoryConfigurationError * @throws IOException */ protected String convertRequest(SolrParams params, String queryValue, QueryType queryType) throws FactoryConfigurationError, IOException { String req; try { CharArrayWriter output = new CharArrayWriter(); XMLStreamWriter xml = XMLOutputFactory.newInstance().createXMLStreamWriter(output); xml.writeStartDocument(); xml.writeStartElement("gss"); if (config.settings.gss3version != null) { xml.writeAttribute("version", config.settings.gss3version); } xml.writeStartElement("assoc"); String target = params.get(PARAM_TARGET, config.defaults.target); if (target != null) { xml.writeAttribute("target", target); } convertRequestWriteStage1Param(xml, params); convertRequestWriteStage2Param(xml, params); convReqWriteQuery(xml, params, queryValue, queryType); xml.writeEndElement(); xml.writeEndElement(); xml.writeEndDocument(); xml.close(); req = output.toString(); } catch (XMLStreamException e) { throw new IOException(e); } LOG.debug(req); return req; }
From source file:edu.stanford.cfuller.colocalization3d.correction.Correction.java
protected String writeToXML() { StringWriter sw = new StringWriter(); try {//from www. j a v a 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:org.maodian.flyingcat.xmpp.state.StreamState.java
private void doHandle(XmppContext context, XMLStreamReader xmlsr, XMLStreamWriter xmlsw) throws XMLStreamException { xmlsr.nextTag();/*from w w w . jav a 2s . c o m*/ 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:DDTReporter.java
/** * Report Generator logic//from w w w. ja v a 2 s . c o m * @param description * @param emailBody */ public void generateDefaultReport(String description, String emailBody) { if (getDDTests().size() < 1) { System.out.println("No Test Steps to report on. Report Generation aborted."); return; } String extraEmailBody = (isBlank(emailBody) ? "" : "<br>" + emailBody) + "</br>"; // Create the values for the various top sections of the report // Project, Module, Mode, Summary String[][] environmentItems = getEnvironmentItems(); String projectName = settings.projectName(); if (isBlank(projectName)) projectName = "Selenium Based Java DDT Automation Project"; String moduleName = description; if (isBlank(moduleName)) moduleName = "Selenium based Java DDT Test Results"; projectName = Util.sq(projectName); moduleName = Util.sq(moduleName); String durationBlurb = " (Session duration: " + sessionDurationString() + ", Reported tests duration: " + durationString() + ")"; // @TODO - When documentation mode becomes available, weave that in... using "Documentation" instead of "Results" String mode = "Test Results as of " + new SimpleDateFormat("HH:mm:ss - yyyy, MMMM dd").format(new Date()) + durationBlurb; String osInfo = environmentItems[0][1]; String envInfo = environmentItems[1][1]; String javaInfo = environmentItems[2][1]; String userInfo = environmentItems[3][1]; String summary = sectionSummary() + " " + sessionSummary(); // String summarizing the scope of this report section String rangeClause = " Reportable steps included in this report: " + firstReportStep() + " thru " + (lastReportStep()); if (lastReportStep() != firstReportStep() || isNotBlank(settings.dontReportActions())) { rangeClause += " - Actions excluded from reporting: " + settings.dontReportActions().replace(",", ", "); } String underscore = "<br>==================<br>"; // Assuming html contents of email message String emailSubject = "Test Results for Project: " + projectName + ", Section: " + moduleName; summary += rangeClause; summary += " - Item status included: " + settings.statusToReport().replace(",", ", ") + " (un-reported action steps not counted.)"; String fileName = new SimpleDateFormat("yyyyMMdd-HHmmss.SSS").format(new Date()) + ".xml"; String folder = settings.reportsFolder() + Util.asSafePathString(description); // Ensure the folder exists - if no exception is thrown, it does! File tmp = Util.setupReportFolder(DDTSettings.asValidOSPath(folder, true)); String fileSpecs = folder + File.separator + DDTSettings.asValidOSPath(fileName, true); String extraBlurb = ""; int nReportableSteps = 0; XMLOutputFactory factory = XMLOutputFactory.newInstance(); try { XMLStreamWriter writer = factory.createXMLStreamWriter(new FileWriter(fileSpecs)); writer.writeStartDocument(); writer.writeCharacters("\n"); // build the xml hierarchy - the innermost portion of it are the steps (see below) writeStartElement(writer, "Project", new String[] { "name" }, new String[] { projectName }); writeStartElement(writer, "Module", new String[] { "name" }, new String[] { moduleName }); writeStartElement(writer, "Mode", new String[] { "name" }, new String[] { mode }); writeStartElement(writer, "OperatingSystem", new String[] { "name" }, new String[] { osInfo }); writeStartElement(writer, "Environment", new String[] { "name" }, new String[] { envInfo }); writeStartElement(writer, "Java", new String[] { "name" }, new String[] { javaInfo }); writeStartElement(writer, "User", new String[] { "name" }, new String[] { userInfo }); writeStartElement(writer, "Summary", new String[] { "name" }, new String[] { summary }); writeStartElement(writer, "Steps"); // Failures will be added to the mailed message body - we construct it here. int nFailures = 0; for (DDTReportItem t : getDDTests()) { // Only report the statuses indicated for reporting in the settings. if (!(settings.statusToReport().contains(t.getStatus()))) continue; String[] attributes = new String[] { "Id", "Name", "Status", "ErrDesc" }; String[] values = new String[] { t.paddedReportedStepNumber(), t.getUserReport(), t.getStatus(), t.getErrors() }; writeStartElement(writer, "Step", attributes, values); // If step failed, add its description to the failedTestsSummary. if (t.hasErrors()) { nFailures++; String failureBlurb = underscore + "Failure " + nFailures + " - Step: " + t.paddedReportedStepNumber() + underscore; failedTestsSummary .add(failureBlurb + t.toString() + "<p>Errors:</p>" + t.errorsAsHtml() + "<br>"); } // If step has any events to report - list those if (t.hasEventsToReport()) { String eventsToReport = settings.eventsToReport(); writeStartElement(writer, "Events"); for (TestEvent e : t.getEvents()) { if (eventsToReport.contains(e.getType().toString())) { writeStartElement(writer, "Event", new String[] { "name" }, new String[] { e.toString() }); writeEndElement(writer); } } writeEndElement(writer); // step's events } writeEndElement(writer); // step nReportableSteps++; } // If no reportable steps recorded, write a step element to indicate so... if (nReportableSteps < 1) { extraBlurb = "*** No Reportable Steps encountered ***"; String[] attributes = new String[] { "Id", "Name", "Status", "ErrDesc" }; String[] values = new String[] { "------", extraBlurb, "", "" }; writeStartElement(writer, "Step", attributes, values); writeEndElement(writer); // step } // close each of the xml hierarchy elements in reverse order writeEndElement(writer); // steps writeEndElement(writer); // summary writeEndElement(writer); // user writeEndElement(writer); // java writeEndElement(writer); // environment writeEndElement(writer); // operating system writeEndElement(writer); // mode writeEndElement(writer); // module writeEndElement(writer); // project writer.writeEndDocument(); writer.flush(); writer.close(); try { transformXmlFileToHtml(fileSpecs, folder); } catch (Exception e) { System.out.println("Error encountered while transofrming xml file to html.\nReport not generated."); e.printStackTrace(); return; } reportGenerated = true; } catch (XMLStreamException e) { System.out.println( "XML Stream Exception Encountered while transforming xml file to html.\nReport not generated."); e.printStackTrace(); return; } catch (IOException e) { System.out.println( "IO Exception Encountered while transforming xml file to html.\nReport not generated."); e.printStackTrace(); return; } if (isBlank(settings.emailRecipients())) { System.out.println("Empty Email Recipients List - Test Results not emailed. Report Generated"); } else { String messageBody = "Attached is a summary of test results run titled " + Util.dq(description) + "<br>" + (isBlank(extraBlurb) ? "" : "<br>" + extraBlurb) + extraEmailBody; try { Email.sendMail(emailSubject, messageBody, fileSpecs.replace(".xml", ".html"), failedTestsSummary); System.out.println("Report Generated. Report Results Emailed to: " + settings.emailRecipients()); } catch (MessagingException e) { System.out.println( "Messaging Exception Encountered while emailing test results.\nResults not sent, Report generated."); e.printStackTrace(); } } reset(); }
From source file:eu.interedition.collatex.tools.CollationServer.java
public void service(Request request, Response response) throws Exception { final Deque<String> path = path(request); if (path.isEmpty() || !"collate".equals(path.pop())) { response.sendError(404);/* w w w. j av a 2 s. c o m*/ return; } final SimpleCollation collation = JsonProcessor.read(request.getInputStream()); if (maxCollationSize > 0) { for (SimpleWitness witness : collation.getWitnesses()) { final int witnessLength = witness.getTokens().stream().filter(t -> t instanceof SimpleToken) .map(t -> (SimpleToken) t).mapToInt(t -> t.getContent().length()).sum(); if (witnessLength > maxCollationSize) { response.sendError(413, "Request Entity Too Large"); return; } } } response.suspend(60, TimeUnit.SECONDS, new EmptyCompletionHandler<>()); collationThreads.submit(() -> { try { final VariantGraph graph = new VariantGraph(); collation.collate(graph); // CORS support response.setHeader("Access-Control-Allow-Origin", Optional.ofNullable(request.getHeader("Origin")).orElse("*")); response.setHeader("Access-Control-Allow-Methods", Optional.ofNullable(request.getHeader("Access-Control-Request-Method")) .orElse("GET, POST, HEAD, OPTIONS")); response.setHeader("Access-Control-Allow-Headers", Optional.ofNullable(request.getHeader("Access-Control-Request-Headers")) .orElse("Content-Type, Accept, X-Requested-With")); response.setHeader("Access-Control-Max-Age", "86400"); response.setHeader("Access-Control-Allow-Credentials", "true"); final String clientAccepts = Optional.ofNullable(request.getHeader(Header.Accept)).orElse(""); if (clientAccepts.contains("text/plain")) { response.setContentType("text/plain"); response.setCharacterEncoding("utf-8"); try (final Writer out = response.getWriter()) { new SimpleVariantGraphSerializer(graph).toDot(out); } response.resume(); } else if (clientAccepts.contains("application/tei+xml")) { XMLStreamWriter xml = null; try { response.setContentType("application/tei+xml"); try (OutputStream responseStream = response.getOutputStream()) { xml = XMLOutputFactory.newInstance().createXMLStreamWriter(responseStream); xml.writeStartDocument(); new SimpleVariantGraphSerializer(graph).toTEI(xml); xml.writeEndDocument(); } finally { if (xml != null) { xml.close(); } } response.resume(); } catch (XMLStreamException e) { e.printStackTrace(); } } else if (clientAccepts.contains("application/graphml+xml")) { XMLStreamWriter xml = null; try { response.setContentType("application/graphml+xml"); try (OutputStream responseStream = response.getOutputStream()) { xml = XMLOutputFactory.newInstance().createXMLStreamWriter(responseStream); xml.writeStartDocument(); new SimpleVariantGraphSerializer(graph).toGraphML(xml); xml.writeEndDocument(); } finally { if (xml != null) { xml.close(); } } response.resume(); } catch (XMLStreamException e) { e.printStackTrace(); } } else if (clientAccepts.contains("image/svg+xml")) { if (dotPath == null) { response.sendError(204); response.resume(); } else { final StringWriter dot = new StringWriter(); new SimpleVariantGraphSerializer(graph).toDot(dot); final Process dotProc = new ProcessBuilder(dotPath, "-Grankdir=LR", "-Gid=VariantGraph", "-Tsvg").start(); final StringWriter errors = new StringWriter(); CompletableFuture.allOf(CompletableFuture.runAsync(() -> { final char[] buf = new char[8192]; try (final Reader errorStream = new InputStreamReader(dotProc.getErrorStream())) { int len; while ((len = errorStream.read(buf)) >= 0) { errors.write(buf, 0, len); } } catch (IOException e) { throw new CompletionException(e); } }, processThreads), CompletableFuture.runAsync(() -> { try (final Writer dotProcStream = new OutputStreamWriter(dotProc.getOutputStream(), "UTF-8")) { dotProcStream.write(dot.toString()); } catch (IOException e) { throw new CompletionException(e); } }, processThreads), CompletableFuture.runAsync(() -> { response.setContentType("image/svg+xml"); final byte[] buf = new byte[8192]; try (final InputStream in = dotProc.getInputStream(); final OutputStream out = response.getOutputStream()) { int len; while ((len = in.read(buf)) >= 0) { out.write(buf, 0, len); } } catch (IOException e) { throw new CompletionException(e); } }, processThreads), CompletableFuture.runAsync(() -> { try { if (!dotProc.waitFor(60, TimeUnit.SECONDS)) { throw new CompletionException(new RuntimeException( "dot processing took longer than 60 seconds, process was timed out.")); } if (dotProc.exitValue() != 0) { throw new CompletionException(new IllegalStateException(errors.toString())); } } catch (InterruptedException e) { throw new CompletionException(e); } }, processThreads)).exceptionally(t -> { t.printStackTrace(); return null; }).thenRunAsync(response::resume, processThreads); } } else { response.setContentType("application/json"); try (final OutputStream responseStream = response.getOutputStream()) { JsonProcessor.write(graph, responseStream); } response.resume(); } } catch (IOException e) { // FIXME: ignored } }); }
From source file:com.moviejukebox.writer.MovieJukeboxHTMLWriter.java
/** * Generate a simple jukebox index file from scratch * * @param jukebox//from w w w . j a va 2s. 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"); } } } }
From source file:com.ibm.bi.dml.runtime.controlprogram.parfor.opt.PerfTestTool.java
/** * StAX for efficient streaming XML writing. * /* w ww . java 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); } }