Example usage for javax.xml.stream XMLStreamWriter flush

List of usage examples for javax.xml.stream XMLStreamWriter flush

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamWriter flush.

Prototype

public void flush() throws XMLStreamException;

Source Link

Document

Write any cached data to the underlying output mechanism.

Usage

From source file:org.gaul.s3proxy.S3ProxyHandler.java

private void handleGetContainerAcl(HttpServletResponse response, BlobStore blobStore, String containerName)
        throws IOException {
    ContainerAccess access = blobStore.getContainerAccess(containerName);

    try (Writer writer = response.getWriter()) {
        XMLStreamWriter xml = xmlOutputFactory.createXMLStreamWriter(writer);
        xml.writeStartDocument();//  ww  w . j av a 2  s  . com
        xml.writeStartElement("AccessControlPolicy");
        xml.writeDefaultNamespace(AWS_XMLNS);

        writeOwnerStanza(xml);

        xml.writeStartElement("AccessControlList");

        xml.writeStartElement("Grant");

        xml.writeStartElement("Grantee");
        xml.writeNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        xml.writeAttribute("xsi:type", "CanonicalUser");

        writeSimpleElement(xml, "ID", FAKE_OWNER_ID);
        writeSimpleElement(xml, "DisplayName", FAKE_OWNER_DISPLAY_NAME);

        xml.writeEndElement();

        writeSimpleElement(xml, "Permission", "FULL_CONTROL");

        xml.writeEndElement();

        if (access == ContainerAccess.PUBLIC_READ) {
            xml.writeStartElement("Grant");

            xml.writeStartElement("Grantee");
            xml.writeNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
            xml.writeAttribute("xsi:type", "Group");

            writeSimpleElement(xml, "URI", "http://acs.amazonaws.com/groups/global/AllUsers");

            xml.writeEndElement();

            writeSimpleElement(xml, "Permission", "READ");

            xml.writeEndElement();
        }

        xml.writeEndElement();

        xml.writeEndElement();
        xml.flush();
    } catch (XMLStreamException xse) {
        throw new IOException(xse);
    }
}

From source file:org.elasticsearch.discovery.ec2.Ec2DiscoveryClusterFormationTests.java

/**
 * Creates mock EC2 endpoint providing the list of started nodes to the DescribeInstances API call
 *//*from  w  w w .  j  a va 2 s  .com*/
@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:com.amalto.core.load.io.XMLStreamUnwrapper.java

/**
 * Moves to next record in stream and stores it in {@link #stringWriter}.
 *//*from w  w  w  .  ja  va  2s .c o m*/
private void moveToNext() {
    try {
        XMLStreamWriter writer = xmlOutputFactory.createXMLStreamWriter(stringWriter);
        boolean hasMadeChanges;
        do {
            if (!reader.hasNext()) {
                break;
            }
            hasMadeChanges = false; // Keep a state to skip line feeds
            final XMLEvent event = reader.nextEvent();
            if (event.isEndElement()) {
                level--;
            } else if (event.isStartElement()) {
                level++;
            } else if (event.isEndDocument()) {
                level--;
            }
            if (level >= RECORD_LEVEL) {
                if (event.isEndElement()) {
                    writer.writeEndElement();
                    hasMadeChanges = true;
                } else if (event.isStartElement()) {
                    final StartElement startElement = event.asStartElement();
                    final QName name = startElement.getName();
                    writer.writeStartElement(name.getNamespaceURI(), name.getLocalPart());
                    boolean isRecordRootElement = (RECORD_LEVEL == level - 1);
                    if (isRecordRootElement) {
                        for (int i = 0; i < rootNamespaceList.size(); i++) {
                            Namespace namespace = rootNamespaceList.get(i);
                            writer.writeNamespace(namespace.getPrefix(), namespace.getNamespaceURI());
                        }
                    }
                    // Declare namespaces (if any)
                    final Iterator elementNamespaces = startElement.getNamespaces();
                    while (elementNamespaces.hasNext()) {
                        Namespace elementNamespace = (Namespace) elementNamespaces.next();
                        if (isRecordRootElement) {
                            if (rootNamespaceList.size() > 0) {
                                for (int i = 0; i < rootNamespaceList.size(); i++) {
                                    Namespace namespace = rootNamespaceList.get(i);
                                    if (!namespace.getPrefix().equals(elementNamespace.getPrefix())
                                            || !namespace.getNamespaceURI()
                                                    .equals(elementNamespace.getNamespaceURI())) {
                                        writer.writeNamespace(elementNamespace.getPrefix(),
                                                elementNamespace.getNamespaceURI());
                                    }
                                }
                            } else {
                                writer.writeNamespace(elementNamespace.getPrefix(),
                                        elementNamespace.getNamespaceURI());
                            }
                        } else {
                            writer.writeNamespace(elementNamespace.getPrefix(),
                                    elementNamespace.getNamespaceURI());
                        }
                    }
                    // Write attributes
                    final Iterator attributes = startElement.getAttributes();
                    while (attributes.hasNext()) {
                        Attribute attribute = (Attribute) attributes.next();
                        QName attributeName = attribute.getName();
                        String value = attribute.getValue();
                        if (StringUtils.isEmpty(attributeName.getNamespaceURI())) {
                            writer.writeAttribute(attributeName.getLocalPart(), value);
                        } else {
                            writer.writeAttribute(attributeName.getNamespaceURI(), attributeName.getLocalPart(),
                                    value);
                        }
                    }
                    hasMadeChanges = true;
                } else if (event.isCharacters()) {
                    final String text = event.asCharacters().getData().trim();
                    if (!text.isEmpty()) {
                        writer.writeCharacters(text);
                        hasMadeChanges = true;
                    }
                }
            }
        } while (level > RECORD_LEVEL || !hasMadeChanges);
        writer.flush();
    } catch (XMLStreamException e) {
        throw new RuntimeException("Unexpected parsing exception.", e);
    }
}

From source file:org.elasticsearch.discovery.ec2.AmazonEC2Fixture.java

/**
 * Generates a XML response that describe the EC2 instances
 *//*from w  ww.  j av a  2  s. co 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 av a  2 s  .  co 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: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;//w ww.jav a 2  s.c om
    } 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 w  w  w .j  a v a  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);
    }

}

From source file:nl.nn.adapterframework.extensions.svn.ScanTibcoSolutionPipe.java

public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException {
    StringWriter stringWriter = new StringWriter();
    XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
    XMLStreamWriter xmlStreamWriter;
    try {/*from  www  .  j  a  v  a 2s .  c o m*/
        xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(stringWriter);
        xmlStreamWriter.writeStartDocument();
        xmlStreamWriter.writeStartElement("root");
        xmlStreamWriter.writeAttribute("url", getUrl());
        // xmlStreamWriter.writeAttribute("level",
        // String.valueOf(getLevel()));
        process(xmlStreamWriter, getUrl(), getLevel());
        xmlStreamWriter.writeEndDocument();
        xmlStreamWriter.flush();
        xmlStreamWriter.close();
    } catch (XMLStreamException e) {
        throw new PipeRunException(this, "XMLStreamException", e);
    } catch (DomBuilderException e) {
        throw new PipeRunException(this, "DomBuilderException", e);
    } catch (XPathExpressionException e) {
        throw new PipeRunException(this, "XPathExpressionException", e);
    }

    return new PipeRunResult(getForward(), stringWriter.getBuffer().toString());
}

From source file:nz.co.jsrsolutions.ds3.test.RetrieveTestData.java

public static void main(String[] args) {

    logger.info("Starting application [ rtd ] ...");

    try {//from  ww  w  .java  2s  . c om

        config.addConfiguration(
                new XMLConfiguration(RetrieveTestData.class.getClassLoader().getResource(CONFIG_FILENAME)));

        HierarchicalConfiguration appConfig = config.configurationAt(APPLICATION_CONFIG_ROOT);

        EodDataProvider eodDataProvider = null;

        OutputStream out = new FileOutputStream(OUTPUT_FILENAME);
        XMLOutputFactory factory = XMLOutputFactory.newInstance();
        XMLStreamWriter writer = factory.createXMLStreamWriter(out);

        eodDataProvider = EodDataProviderFactory.create(appConfig, EODDATA_PROVIDER_NAME);

        writer.writeStartDocument("utf-8", "1.0");
        writer.writeCharacters(NEWLINE);
        writer.writeComment("Test data for running DataScraper unit tests against");
        writer.writeCharacters(NEWLINE);

        writer.setPrefix(XML_PREFIX, XML_NAMESPACE_URI);

        writer.writeStartElement(XML_NAMESPACE_URI, TESTDATA_LOCALNAME);
        writer.writeNamespace(XML_PREFIX, XML_NAMESPACE_URI);
        writer.writeCharacters(NEWLINE);

        serializeExchanges(eodDataProvider, writer);
        serializeSymbols(eodDataProvider, writer);
        serializeQuotes(eodDataProvider, writer);

        writer.writeEndElement();
        writer.writeCharacters(NEWLINE);
        writer.writeEndDocument();
        writer.flush();
        writer.close();

    } catch (ConfigurationException ce) {

        logger.error(ce.toString());
        ce.printStackTrace();

    } catch (Exception e) {

        logger.error(e.toString());
        logger.error(e);

    }

    logger.info("Exiting application [ rtd ] ...");

}