List of usage examples for javax.xml.stream XMLStreamWriter writeEndDocument
public void writeEndDocument() throws XMLStreamException;
From source file:jp.zippyzip.impl.GeneratorServiceImpl.java
public void storeX0402Zip() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime(); ZipOutputStream out = new ZipOutputStream(baos); Collection<City> cities = getCities(); ZipEntry tsv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_utf8.txt"); ZipEntry csv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_sjis.csv"); ZipEntry json = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_utf8.json"); ZipEntry xml = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_utf8.xml"); tsv.setTime(timestamp);//ww w . j av a 2 s . co m csv.setTime(timestamp); json.setTime(timestamp); xml.setTime(timestamp); try { out.putNextEntry(tsv); for (City city : cities) { out.write(new String(city.getCode() + "\t" + city.getName() + "\t" + city.getYomi() + "\t" + ((city.getExpiration().getTime() < new Date().getTime()) ? "" : "") + CRLF) .getBytes("UTF-8")); } out.closeEntry(); out.putNextEntry(csv); for (City city : cities) { out.write(new String(city.getCode() + "," + city.getName() + "," + city.getYomi() + "," + ((city.getExpiration().getTime() < new Date().getTime()) ? "" : "") + CRLF) .getBytes("MS932")); } out.closeEntry(); out.putNextEntry(json); OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8"); JSONWriter jwriter = new JSONWriter(writer); jwriter.array(); for (City city : cities) { jwriter.object().key("code").value(city.getCode()).key("name").value(city.getName()).key("yomi") .value(city.getYomi()).key("expired") .value((city.getExpiration().getTime() < new Date().getTime()) ? "true" : "false") .endObject(); } jwriter.endArray(); writer.flush(); out.closeEntry(); out.putNextEntry(xml); XMLStreamWriter xwriter = XMLOutputFactory.newInstance() .createXMLStreamWriter(new OutputStreamWriter(out, "UTF-8")); xwriter.writeStartDocument("UTF-8", "1.0"); xwriter.writeStartElement("x0402s"); for (City city : cities) { xwriter.writeStartElement("x0402"); xwriter.writeAttribute("code", city.getCode()); xwriter.writeAttribute("name", city.getName()); xwriter.writeAttribute("yomi", city.getYomi()); xwriter.writeAttribute("expired", (city.getExpiration().getTime() < new Date().getTime()) ? "true" : "false"); xwriter.writeEndElement(); } xwriter.writeEndElement(); xwriter.writeEndDocument(); xwriter.flush(); out.closeEntry(); out.finish(); baos.flush(); getRawDao().store(baos.toByteArray(), "x0402.zip"); log.info("cities: " + cities.size()); } catch (JSONException e) { log.log(Level.WARNING, "", e); } catch (XMLStreamException e) { log.log(Level.WARNING, "", e); } catch (FactoryConfigurationError e) { log.log(Level.WARNING, "", e); } catch (IOException e) { log.log(Level.WARNING, "", e); } }
From source file:com.liferay.portal.util.LocalizationImpl.java
public String updateLocalization(String xml, String key, String value, String requestedLanguageId, String defaultLanguageId, boolean cdata, boolean localized) { xml = _sanitizeXML(xml);//from ww w . j a v a2s .c o m XMLStreamReader xmlStreamReader = null; XMLStreamWriter xmlStreamWriter = null; ClassLoader portalClassLoader = PortalClassLoaderUtil.getClassLoader(); Thread currentThread = Thread.currentThread(); ClassLoader contextClassLoader = currentThread.getContextClassLoader(); try { if (contextClassLoader != portalClassLoader) { currentThread.setContextClassLoader(portalClassLoader); } XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); xmlStreamReader = xmlInputFactory.createXMLStreamReader(new UnsyncStringReader(xml)); String availableLocales = StringPool.BLANK; // Read root node if (xmlStreamReader.hasNext()) { xmlStreamReader.nextTag(); availableLocales = xmlStreamReader.getAttributeValue(null, _AVAILABLE_LOCALES); if (Validator.isNull(availableLocales)) { availableLocales = defaultLanguageId; } if (availableLocales.indexOf(requestedLanguageId) == -1) { availableLocales = StringUtil.add(availableLocales, requestedLanguageId, StringPool.COMMA); } } UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter(); XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance(); xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(unsyncStringWriter); xmlStreamWriter.writeStartDocument(); xmlStreamWriter.writeStartElement(_ROOT); if (localized) { xmlStreamWriter.writeAttribute(_AVAILABLE_LOCALES, availableLocales); xmlStreamWriter.writeAttribute(_DEFAULT_LOCALE, defaultLanguageId); } _copyNonExempt(xmlStreamReader, xmlStreamWriter, requestedLanguageId, defaultLanguageId, cdata); xmlStreamWriter.writeStartElement(key); if (localized) { xmlStreamWriter.writeAttribute(_LANGUAGE_ID, requestedLanguageId); } if (cdata) { xmlStreamWriter.writeCData(value); } else { xmlStreamWriter.writeCharacters(value); } xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndDocument(); xmlStreamWriter.close(); xmlStreamWriter = null; xml = unsyncStringWriter.toString(); } catch (Exception e) { if (_log.isWarnEnabled()) { _log.warn(e, e); } } finally { if (contextClassLoader != portalClassLoader) { currentThread.setContextClassLoader(contextClassLoader); } if (xmlStreamReader != null) { try { xmlStreamReader.close(); } catch (Exception e) { } } if (xmlStreamWriter != null) { try { xmlStreamWriter.close(); } catch (Exception e) { } } } return xml; }
From source file:jp.zippyzip.impl.GeneratorServiceImpl.java
/** * XML ??//from w w w . j a v a2s .c om * * @param name "area" / "corp" * @param suffix "" / "c" */ void storeXml(String name, String suffix) { long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime(); Collection<City> cities = getCities(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos); ZipEntry entry = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_" + name + "_utf8.xml"); entry.setTime(timestamp); int cnt = 0; try { zos.putNextEntry(entry); OutputStreamWriter writer = new OutputStreamWriter(zos, "UTF-8"); XMLStreamWriter xwriter = XMLOutputFactory.newInstance().createXMLStreamWriter(writer); xwriter.writeStartDocument("UTF-8", "1.0"); xwriter.writeStartElement("zips"); xwriter.writeAttribute("type", name); for (City city : cities) { ParentChild pc = getParentChildDao().get(city.getCode() + suffix); if (pc == null) { continue; } for (String json : pc.getChildren()) { Zip zip = Zip.fromJson(json); xwriter.writeStartElement("zip"); xwriter.writeAttribute("zip", zip.getCode()); xwriter.writeAttribute("x0402", zip.getX0402()); xwriter.writeAttribute("add1", zip.getAdd1()); xwriter.writeAttribute("add2", zip.getAdd2()); xwriter.writeAttribute("corp", zip.getCorp()); xwriter.writeAttribute("add1Yomi", zip.getAdd1Yomi()); xwriter.writeAttribute("add2Yomi", zip.getAdd2Yomi()); xwriter.writeAttribute("corpYomi", zip.getCorpYomi()); xwriter.writeAttribute("note", zip.getNote()); xwriter.writeEndElement(); ++cnt; } } xwriter.writeEndElement(); xwriter.writeEndDocument(); xwriter.flush(); zos.closeEntry(); zos.finish(); getRawDao().store(baos.toByteArray(), name + "_utf8_xml.zip"); log.info("count: " + cnt); } catch (XMLStreamException e) { log.log(Level.WARNING, "", e); } catch (FactoryConfigurationError e) { log.log(Level.WARNING, "", e); } catch (IOException e) { log.log(Level.WARNING, "", e); } }
From source file:edu.stanford.cfuller.colocalization3d.correction.Correction.java
protected String writeToXML() { StringWriter sw = new StringWriter(); try {/* w w w. j ava2 s . 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: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."); }//from ww w. j av a2 s .c om 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:org.elasticsearch.discovery.ec2.Ec2DiscoveryClusterFormationTests.java
/** * Creates mock EC2 endpoint providing the list of started nodes to the DescribeInstances API call *//*ww w. j a v a 2s . c o m*/ @BeforeClass public static void startHttpd() throws Exception { logDir = createTempDir(); httpServer = MockHttpServer .createHttp(new InetSocketAddress(InetAddress.getLoopbackAddress().getHostAddress(), 0), 0); httpServer.createContext("/", (s) -> { Headers headers = s.getResponseHeaders(); headers.add("Content-Type", "text/xml; charset=UTF-8"); String action = null; for (NameValuePair parse : URLEncodedUtils.parse(IOUtils.toString(s.getRequestBody()), StandardCharsets.UTF_8)) { if ("Action".equals(parse.getName())) { action = parse.getValue(); break; } } assertThat(action, equalTo("DescribeInstances")); XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory(); xmlOutputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true); StringWriter out = new StringWriter(); XMLStreamWriter sw; try { sw = xmlOutputFactory.createXMLStreamWriter(out); sw.writeStartDocument(); String namespace = "http://ec2.amazonaws.com/doc/2013-02-01/"; sw.setDefaultNamespace(namespace); sw.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX, "DescribeInstancesResponse", namespace); { sw.writeStartElement("requestId"); sw.writeCharacters(UUID.randomUUID().toString()); sw.writeEndElement(); sw.writeStartElement("reservationSet"); { Path[] files = FileSystemUtils.files(logDir); for (int i = 0; i < files.length; i++) { Path resolve = files[i].resolve("transport.ports"); if (Files.exists(resolve)) { List<String> addresses = Files.readAllLines(resolve); Collections.shuffle(addresses, random()); sw.writeStartElement("item"); { sw.writeStartElement("reservationId"); sw.writeCharacters(UUID.randomUUID().toString()); sw.writeEndElement(); sw.writeStartElement("instancesSet"); { sw.writeStartElement("item"); { sw.writeStartElement("instanceId"); sw.writeCharacters(UUID.randomUUID().toString()); sw.writeEndElement(); sw.writeStartElement("imageId"); sw.writeCharacters(UUID.randomUUID().toString()); sw.writeEndElement(); sw.writeStartElement("instanceState"); { sw.writeStartElement("code"); sw.writeCharacters("16"); sw.writeEndElement(); sw.writeStartElement("name"); sw.writeCharacters("running"); sw.writeEndElement(); } sw.writeEndElement(); sw.writeStartElement("privateDnsName"); sw.writeCharacters(addresses.get(0)); sw.writeEndElement(); sw.writeStartElement("dnsName"); sw.writeCharacters(addresses.get(0)); sw.writeEndElement(); sw.writeStartElement("instanceType"); sw.writeCharacters("m1.medium"); sw.writeEndElement(); sw.writeStartElement("placement"); { sw.writeStartElement("availabilityZone"); sw.writeCharacters("use-east-1e"); sw.writeEndElement(); sw.writeEmptyElement("groupName"); sw.writeStartElement("tenancy"); sw.writeCharacters("default"); sw.writeEndElement(); } sw.writeEndElement(); sw.writeStartElement("privateIpAddress"); sw.writeCharacters(addresses.get(0)); sw.writeEndElement(); sw.writeStartElement("ipAddress"); sw.writeCharacters(addresses.get(0)); sw.writeEndElement(); } sw.writeEndElement(); } sw.writeEndElement(); } sw.writeEndElement(); } } } sw.writeEndElement(); } sw.writeEndElement(); sw.writeEndDocument(); sw.flush(); final byte[] responseAsBytes = out.toString().getBytes(StandardCharsets.UTF_8); s.sendResponseHeaders(200, responseAsBytes.length); OutputStream responseBody = s.getResponseBody(); responseBody.write(responseAsBytes); responseBody.close(); } catch (XMLStreamException e) { Loggers.getLogger(Ec2DiscoveryClusterFormationTests.class).error("Failed serializing XML", e); throw new RuntimeException(e); } }); httpServer.start(); }
From source file:org.elasticsearch.discovery.ec2.AmazonEC2Fixture.java
/** * Generates a XML response that describe the EC2 instances *///from w ww.j a v a2s. c o m private byte[] generateDescribeInstancesResponse() { final XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory(); xmlOutputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true); final StringWriter out = new StringWriter(); XMLStreamWriter sw; try { sw = xmlOutputFactory.createXMLStreamWriter(out); sw.writeStartDocument(); String namespace = "http://ec2.amazonaws.com/doc/2013-02-01/"; sw.setDefaultNamespace(namespace); sw.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX, "DescribeInstancesResponse", namespace); { sw.writeStartElement("requestId"); sw.writeCharacters(UUID.randomUUID().toString()); sw.writeEndElement(); sw.writeStartElement("reservationSet"); { if (Files.exists(nodes)) { for (String address : Files.readAllLines(nodes)) { sw.writeStartElement("item"); { sw.writeStartElement("reservationId"); sw.writeCharacters(UUID.randomUUID().toString()); sw.writeEndElement(); sw.writeStartElement("instancesSet"); { sw.writeStartElement("item"); { sw.writeStartElement("instanceId"); sw.writeCharacters(UUID.randomUUID().toString()); sw.writeEndElement(); sw.writeStartElement("imageId"); sw.writeCharacters(UUID.randomUUID().toString()); sw.writeEndElement(); sw.writeStartElement("instanceState"); { sw.writeStartElement("code"); sw.writeCharacters("16"); sw.writeEndElement(); sw.writeStartElement("name"); sw.writeCharacters("running"); sw.writeEndElement(); } sw.writeEndElement(); sw.writeStartElement("privateDnsName"); sw.writeCharacters(address); sw.writeEndElement(); sw.writeStartElement("dnsName"); sw.writeCharacters(address); sw.writeEndElement(); sw.writeStartElement("instanceType"); sw.writeCharacters("m1.medium"); sw.writeEndElement(); sw.writeStartElement("placement"); { sw.writeStartElement("availabilityZone"); sw.writeCharacters("use-east-1e"); sw.writeEndElement(); sw.writeEmptyElement("groupName"); sw.writeStartElement("tenancy"); sw.writeCharacters("default"); sw.writeEndElement(); } sw.writeEndElement(); sw.writeStartElement("privateIpAddress"); sw.writeCharacters(address); sw.writeEndElement(); sw.writeStartElement("ipAddress"); sw.writeCharacters(address); sw.writeEndElement(); } sw.writeEndElement(); } sw.writeEndElement(); } sw.writeEndElement(); } } sw.writeEndElement(); } sw.writeEndElement(); sw.writeEndDocument(); sw.flush(); } } catch (Exception e) { throw new RuntimeException(e); } return out.toString().getBytes(UTF_8); }
From source file:DDTReporter.java
/** * Report Generator logic/* w ww .j a v a2s .com*/ * @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:edu.ucsd.library.dams.api.DAMSAPIServlet.java
private void sparqlQuery(String sparql, TripleStore ts, Map<String, String[]> params, String pathInfo, HttpServletResponse res) throws Exception { if (sparql == null) { Map err = error(SC_BAD_REQUEST, "No query specified.", null); output(err, params, pathInfo, res); return;//from ww w . j a v a 2s .c o m } else { log.info("sparql: " + sparql); } // sparql query BindingIterator objs = ts.sparqlSelect(sparql); // start output String sparqlNS = "http://www.w3.org/2005/sparql-results#"; res.setContentType("application/sparql-results+xml"); OutputStream out = res.getOutputStream(); XMLOutputFactory factory = XMLOutputFactory.newInstance(); XMLStreamWriter stream = factory.createXMLStreamWriter(out); stream.setDefaultNamespace(sparqlNS); stream.writeStartDocument(); stream.writeStartElement("sparql"); // output bindings boolean headerWritten = false; while (objs.hasNext()) { Map<String, String> binding = objs.nextBinding(); // write header on first binding if (!headerWritten) { Iterator<String> it = binding.keySet().iterator(); stream.writeStartElement("head"); while (it.hasNext()) { String k = it.next(); stream.writeStartElement("variable"); stream.writeAttribute("name", k); stream.writeEndElement(); } stream.writeEndElement(); stream.writeStartElement("results"); // ordered='false' distinct='false' headerWritten = true; } stream.writeStartElement("result"); Iterator<String> it = binding.keySet().iterator(); while (it.hasNext()) { String k = it.next(); String v = binding.get(k); stream.writeStartElement("binding"); stream.writeAttribute("name", k); String type = null; if (v.startsWith("\"") && v.endsWith("\"")) { type = "literal"; v = v.substring(1, v.length() - 1); } else if (v.startsWith("_:")) { type = "bnode"; v = v.substring(2); } else { type = "uri"; } stream.writeStartElement(type); stream.writeCharacters(v); stream.writeEndElement(); stream.writeEndElement(); } stream.writeEndElement(); } // finish output stream.writeEndElement(); stream.writeEndDocument(); stream.flush(); stream.close(); }
From source file:com.github.lindenb.jvarkit.tools.vcfcmp.VcfCompareCallers.java
@Override public Collection<Throwable> call() throws Exception { htsjdk.samtools.util.IntervalTreeMap<Boolean> capture = null; PrintWriter exampleWriter = null; XMLStreamWriter exampleOut = null; PrintStream pw = null;/*from ww w .ja va 2 s .c om*/ VcfIterator vcfInputs[] = new VcfIterator[] { null, null }; VCFHeader headers[] = new VCFHeader[] { null, null }; final List<String> args = getInputFiles(); try { if (args.size() == 1) { LOG.info("Reading from stdin and " + args.get(0)); vcfInputs[0] = VCFUtils.createVcfIteratorStdin(); vcfInputs[1] = VCFUtils.createVcfIterator(args.get(0)); } else if (args.size() == 2) { LOG.info("Reading from stdin and " + args.get(0) + " and " + args.get(1)); vcfInputs[0] = VCFUtils.createVcfIterator(args.get(0)); vcfInputs[1] = VCFUtils.createVcfIterator(args.get(1)); } else { return wrapException(getMessageBundle("illegal.number.of.arguments")); } if (super.captureFile != null) { LOG.info("Reading " + super.captureFile); capture = super.readBedFileAsBooleanIntervalTreeMap(super.captureFile); } for (int i = 0; i < vcfInputs.length; ++i) { headers[i] = vcfInputs[i].getHeader(); } /* dicts */ final SAMSequenceDictionary dict0 = headers[0].getSequenceDictionary(); final SAMSequenceDictionary dict1 = headers[1].getSequenceDictionary(); final Comparator<VariantContext> ctxComparator; if (dict0 == null && dict1 == null) { ctxComparator = VCFUtils.createChromPosRefComparator(); } else if (dict0 != null && dict1 != null) { if (!SequenceUtil.areSequenceDictionariesEqual(dict0, dict1)) { return wrapException(getMessageBundle("not.the.same.sequence.dictionaries")); } ctxComparator = VCFUtils.createTidPosRefComparator(dict0); } else { return wrapException(getMessageBundle("not.the.same.sequence.dictionaries")); } /* samples */ Set<String> samples0 = new HashSet<>(headers[0].getSampleNamesInOrder()); Set<String> samples1 = new HashSet<>(headers[1].getSampleNamesInOrder()); Set<String> samples = new TreeSet<>(samples0); samples.retainAll(samples1); if (samples.size() != samples0.size() || samples.size() != samples1.size()) { LOG.warn("Warning: Not the same samples set. Using intersection of both lists."); } if (samples.isEmpty()) { return wrapException("No common samples"); } Map<String, Counter<Category>> sample2info = new HashMap<String, Counter<Category>>(samples.size()); for (String sampleName : samples) { sample2info.put(sampleName, new Counter<Category>()); } if (super.exampleFile != null) { exampleWriter = new PrintWriter(exampleFile, "UTF-8"); XMLOutputFactory xof = XMLOutputFactory.newFactory(); exampleOut = xof.createXMLStreamWriter(exampleWriter); exampleOut.writeStartDocument("UTF-8", "1.0"); exampleOut.writeStartElement("compare-callers"); } SAMSequenceDictionaryProgress progress = new SAMSequenceDictionaryProgress(dict0); VariantContext buffer[] = new VariantContext[vcfInputs.length]; VariantContext prev[] = new VariantContext[vcfInputs.length]; for (;;) { VariantContext smallest = null; //refill buffer for (int i = 0; i < vcfInputs.length; ++i) { if (buffer[i] == null && vcfInputs[i] != null) { if (vcfInputs[i].hasNext()) { buffer[i] = vcfInputs[i].peek(); /* check data are sorted */ if (prev[i] != null && ctxComparator.compare(prev[i], buffer[i]) > 0) { return wrapException("Input " + (i + 1) + "/2 is not sorted" + (((i == 0 && dict0 == null) || (i == 1 && dict1 == null)) ? "on chrom/pos/ref" : "on sequence dictionary") + ". got\n" + buffer[i] + "\nafter\n" + prev[i]); } } else { vcfInputs[i].close(); vcfInputs[i] = null; } } if (buffer[i] != null) { if (smallest == null || ctxComparator.compare(buffer[i], smallest) < 0) { smallest = buffer[i]; } } } if (smallest == null) break; VariantContext ctx0 = null; VariantContext ctx1 = null; Interval interval = null; if (buffer[0] != null && ctxComparator.compare(buffer[0], smallest) == 0) { prev[0] = progress.watch(vcfInputs[0].next()); ctx0 = prev[0]; buffer[0] = null; interval = new Interval(ctx0.getContig(), ctx0.getStart(), ctx0.getEnd()); } if (buffer[1] != null && ctxComparator.compare(buffer[1], smallest) == 0) { prev[1] = progress.watch(vcfInputs[1].next()); ctx1 = prev[1]; buffer[1] = null; interval = new Interval(ctx1.getContig(), ctx1.getStart(), ctx1.getEnd()); } boolean in_capture = true; if (capture != null && interval != null) { in_capture = capture.containsOverlapping(interval); } for (final String sampleName : sample2info.keySet()) { final Counter<Category> sampleInfo = sample2info.get(sampleName); Genotype g0 = (ctx0 == null ? null : ctx0.getGenotype(sampleName)); Genotype g1 = (ctx1 == null ? null : ctx1.getGenotype(sampleName)); if (g0 != null && (g0.isNoCall() || !g0.isAvailable())) g0 = null; if (g1 != null && (g1.isNoCall() || !g1.isAvailable())) g1 = null; if (g0 == null && g1 == null) { watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.both_missing); continue; } else if (g0 != null && g1 == null) { if (!in_capture) { watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.off_target_only_1); continue; } watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.unique_to_file_1); if (ctx0.isIndel()) { watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.unique_to_file_1_indel); } else if (ctx0.isSNP()) { watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.unique_to_file_1_snp); } continue; } else if (g0 == null && g1 != null) { if (!in_capture) { watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.off_target_only_2); continue; } watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.unique_to_file_2); if (ctx1.isIndel()) { watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.unique_to_file_2_indel); } else if (ctx1.isSNP()) { watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.unique_to_file_2_snp); } continue; } else { if (!in_capture) { watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.off_target_both); continue; } watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.common_context); if (ctx0.isIndel() && ctx1.isIndel()) { watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.common_context_indel); } else if (ctx0.isSNP() && ctx1.isSNP()) { watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.common_context_snp); } if ((ctx0.hasID() && !ctx1.hasID()) || (!ctx0.hasID() && ctx1.hasID()) || (ctx0.hasID() && ctx1.hasID() && !ctx0.getID().equals(ctx1.getID()))) { watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.common_context_discordant_id); } if (g0.sameGenotype(g1)) { watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.called_and_same); if (g0.isHomRef()) { watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.called_and_same_hom_ref); } if (g0.isHomVar()) { watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.called_and_same_hom_var); } else if (g0.isHet()) { watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.called_and_same_het); } } else { watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.called_but_discordant); if (g0.isHom() && g1.isHet()) { watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.called_but_discordant_hom1_het2); } else if (g0.isHet() && g1.isHom()) { watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.called_but_discordant_het1_hom2); } else if (g0.isHom() && g1.isHom()) { watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.called_but_discordant_hom1_hom2); } else if (g0.isHet() && g1.isHet()) { watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.called_but_discordant_het1_het2); } else { watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.called_but_discordant_others); } } } } } progress.finish(); pw = openFileOrStdoutAsPrintStream(); pw.print("#Sample"); for (Category c : Category.values()) { pw.print('\t'); pw.print(c.name()); } pw.println(); for (String sample : sample2info.keySet()) { Counter<Category> count = sample2info.get(sample); pw.print(sample); for (Category c : Category.values()) { pw.print('\t'); pw.print(count.count(c)); } pw.println(); if (pw.checkError()) break; } pw.flush(); if (exampleOut != null) { exampleOut.writeEndElement(); exampleOut.writeEndDocument(); exampleOut.flush(); exampleOut.close(); } return RETURN_OK; } catch (Exception err) { return wrapException(err); } finally { if (getOutputFile() != null) CloserUtil.close(pw); CloserUtil.close(exampleWriter); } }