Example usage for javax.xml.stream XMLOutputFactory newFactory

List of usage examples for javax.xml.stream XMLOutputFactory newFactory

Introduction

In this page you can find the example usage for javax.xml.stream XMLOutputFactory newFactory.

Prototype

public static XMLOutputFactory newFactory() throws FactoryConfigurationError 

Source Link

Document

Create a new instance of the factory.

Usage

From source file:com.github.lindenb.jvarkit.tools.blast.BlastFilterJS.java

@Override
protected Collection<Throwable> call(String inputName) throws Exception {

    final CompiledScript compiledScript;
    Unmarshaller unmarshaller;// w  ww . j  ava2s  . c o m
    Marshaller marshaller;
    try {
        compiledScript = super.compileJavascript();

        JAXBContext jc = JAXBContext.newInstance("gov.nih.nlm.ncbi.blast");

        unmarshaller = jc.createUnmarshaller();
        marshaller = jc.createMarshaller();

        XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
        xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        PrintWriter pw = openFileOrStdoutAsPrintWriter();
        XMLOutputFactory xof = XMLOutputFactory.newFactory();
        xof.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.FALSE);
        XMLEventWriter w = xof.createXMLEventWriter(pw);

        StreamSource src = null;
        if (inputName == null) {
            LOG.info("Reading stdin");
            src = new StreamSource(stdin());
        } else {
            LOG.info("Reading file " + inputName);
            src = new StreamSource(new File(inputName));
        }

        XMLEventReader r = xmlInputFactory.createXMLEventReader(src);

        XMLEventFactory eventFactory = XMLEventFactory.newFactory();

        SimpleBindings bindings = new SimpleBindings();
        while (r.hasNext()) {
            XMLEvent evt = r.peek();
            switch (evt.getEventType()) {
            case XMLEvent.START_ELEMENT: {
                StartElement sE = evt.asStartElement();
                Hit hit = null;
                JAXBElement<Hit> jaxbElement = null;
                if (sE.getName().getLocalPart().equals("Hit")) {
                    jaxbElement = unmarshaller.unmarshal(r, Hit.class);
                    hit = jaxbElement.getValue();
                } else {
                    w.add(r.nextEvent());
                    break;
                }

                if (hit != null) {

                    bindings.put("hit", hit);

                    boolean accept = super.evalJavaScriptBoolean(compiledScript, bindings);

                    if (accept) {
                        marshaller.marshal(jaxbElement, w);
                        w.add(eventFactory.createCharacters("\n"));
                    }
                }

                break;
            }
            case XMLEvent.SPACE:
                break;
            default: {
                w.add(r.nextEvent());
                break;
            }
            }
            r.close();
        }
        w.flush();
        w.close();
        pw.flush();
        pw.close();
        return RETURN_OK;
    } catch (Exception err) {
        return wrapException(err);
    } finally {

    }
}

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  www  .  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:com.mpobjects.rtcalltree.report.xml.XmlReporter.java

protected XMLStreamWriter createStreamWriter(Writer aWriter) {
    XMLOutputFactory factory = XMLOutputFactory.newFactory();
    XMLStreamWriter writer;/*  w  w  w  . j  a v  a2s.  co m*/
    try {
        writer = factory.createXMLStreamWriter(aWriter);
    } catch (XMLStreamException e) {
        LOG.error("Failed to create XMLStreamWriter. " + e.getMessage(), e);
        return null;
    }
    return writer;
}

From source file:net.solarnetwork.util.JavaBeanXmlSerializer.java

private XMLStreamWriter startXml(OutputStream out) {
    XMLStreamWriter writer = null;
    try {/*from  w  w  w . j  a v  a 2  s .  c  om*/
        writer = XMLOutputFactory.newFactory().createXMLStreamWriter(out);
    } catch (XMLStreamException e) {
        throw new RuntimeException(e);
    } catch (FactoryConfigurationError e) {
        throw new RuntimeException(e);
    }
    return writer;
}

From source file:de.qucosa.webapi.v1.SearchResource.java

@Autowired
public SearchResource(Client elasticSearchClient) {
    this.elasticSearchClient = elasticSearchClient;
    xmlOutputFactory = XMLOutputFactory.newFactory();
}

From source file:de.qucosa.webapi.v1.DocumentResource.java

@Autowired
public DocumentResource(FedoraRepository fedoraRepository, URNConfiguration urnConfiguration,
        FileHandlingService fileHandlingService)
        throws ParserConfigurationException, TransformerConfigurationException {
    this.fedoraRepository = fedoraRepository;
    this.urnConfiguration = urnConfiguration;
    this.fileHandlingService = fileHandlingService;

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilder = documentBuilderFactory.newDocumentBuilder();

    transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

    xmlOutputFactory = XMLOutputFactory.newFactory();
}

From source file:com.github.fritaly.graphml4j.GraphMLWriter.java

/**
 * Creates a new instance of {@link GraphMLWriter} using the given writer to
 * generate the GraphML markup language.
 *
 * @param writer//from  w  ww .  ja  v a 2s  .  c  om
 *            a {@link Writer} where the GraphML markup language will be
 *            written. Can't be null.
 * @throws GraphMLException
 *             if an error occurs when initializing the writer.
 */
public GraphMLWriter(Writer writer) throws GraphMLException {
    Validate.notNull(writer, "The given writer is null");

    try {
        this.writer = writer;

        // Indent the XML generated
        this.streamWriter = new IndentingXMLStreamWriter(
                XMLOutputFactory.newFactory().createXMLStreamWriter(writer));
    } catch (XMLStreamException e) {
        throw new GraphMLException(e);
    } catch (FactoryConfigurationError e) {
        throw new GraphMLException(e);
    }
}

From source file:edu.stanford.cfuller.colocalization3d.correction.Correction.java

protected String writeToXML() {

    StringWriter sw = new StringWriter();

    try {//from  ww w  .  j a v  a 2  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.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;// w  w  w.  j  a 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);
    }

}

From source file:com.adobe.acs.commons.wcm.impl.SiteMapServlet.java

@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType(request.getResponseContentType());
    if (StringUtils.isNotEmpty(this.characterEncoding)) {
        response.setCharacterEncoding(characterEncoding);
    }//w  w w. j a va 2s  .  c om
    ResourceResolver resourceResolver = request.getResourceResolver();
    PageManager pageManager = resourceResolver.adaptTo(PageManager.class);
    Page page = pageManager.getContainingPage(request.getResource());

    XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();
    try {
        XMLStreamWriter stream = outputFactory.createXMLStreamWriter(response.getWriter());
        stream.writeStartDocument("1.0");

        stream.writeStartElement("", "urlset", NS);
        stream.writeNamespace("", NS);

        // first do the current page
        write(page, stream, resourceResolver);

        for (Iterator<Page> children = page.listChildren(new PageFilter(false, true), true); children
                .hasNext();) {
            write(children.next(), stream, resourceResolver);
        }

        if (damAssetTypes.size() > 0 && damAssetProperty.length() > 0) {
            for (Resource assetFolder : getAssetFolders(page, resourceResolver)) {
                writeAssets(stream, assetFolder, resourceResolver);
            }
        }

        stream.writeEndElement();

        stream.writeEndDocument();
    } catch (XMLStreamException e) {
        throw new IOException(e);
    }
}