Example usage for javax.xml.stream XMLOutputFactory createXMLStreamWriter

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

Introduction

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

Prototype

public abstract XMLStreamWriter createXMLStreamWriter(Result result) throws XMLStreamException;

Source Link

Document

Create a new XMLStreamWriter that writes to a JAXP result.

Usage

From source file:com.tamingtext.tagrecommender.ExtractStackOverflowData.java

public void extract() {
    XMLInputFactory xif = XMLInputFactory.newInstance();
    XMLStreamReader reader = null;
    InputStream is = null;// w ww .ja v  a  2 s .c  o m

    XMLOutputFactory xof = XMLOutputFactory.newInstance();
    XMLStreamWriter writer = null;
    OutputStream os = null;

    try {
        log.info("Reading data from " + inputFile);

        is = new FileInputStream(inputFile);
        reader = xif.createXMLStreamReader(is);

        os = new FileOutputStream(trainingOutputFile);
        writer = xof.createXMLStreamWriter(os);
        int trainingDataCount = extractXMLData(reader, writer, trainingDataSize);
        os.close();

        os = new FileOutputStream(testOutputFile);
        writer = xof.createXMLStreamWriter(os);
        int testDataCount = extractXMLData(reader, writer, testDataSize);
        os.close();

        log.info("Extracted " + trainingDataCount + " rows of training data");
        log.info("Extracted " + testDataCount + " rows of test data");
    } catch (XMLStreamException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.norconex.committer.core.AbstractMappedCommitter.java

@SuppressWarnings("deprecation")
@Override//from  w ww .java 2 s .c om
public void saveToXML(Writer out) throws IOException {
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    try {
        XMLStreamWriter writer = factory.createXMLStreamWriter(out);
        writer.writeStartElement("committer");
        writer.writeAttribute("class", getClass().getCanonicalName());

        if (sourceReferenceField != null) {
            writer.writeStartElement("sourceReferenceField");
            writer.writeAttribute("keep", Boolean.toString(keepSourceReferenceField));
            writer.writeCharacters(sourceReferenceField);
            writer.writeEndElement();
        }
        if (targetReferenceField != null) {
            writer.writeStartElement("targetReferenceField");
            writer.writeCharacters(targetReferenceField);
            writer.writeEndElement();
        }
        if (sourceContentField != null) {
            writer.writeStartElement("sourceContentField");
            writer.writeAttribute("keep", Boolean.toString(keepSourceContentField));
            writer.writeCharacters(sourceContentField);
            writer.writeEndElement();
        }
        if (targetContentField != null) {
            writer.writeStartElement("targetContentField");
            writer.writeCharacters(targetContentField);
            writer.writeEndElement();
        }
        if (getQueueDir() != null) {
            writer.writeStartElement("queueDir");
            writer.writeCharacters(getQueueDir());
            writer.writeEndElement();
        }
        writer.writeStartElement("queueSize");
        writer.writeCharacters(ObjectUtils.toString(getQueueSize()));
        writer.writeEndElement();

        writer.writeStartElement("commitBatchSize");
        writer.writeCharacters(ObjectUtils.toString(getCommitBatchSize()));
        writer.writeEndElement();

        writer.writeStartElement("maxRetries");
        writer.writeCharacters(ObjectUtils.toString(getMaxRetries()));
        writer.writeEndElement();

        writer.writeStartElement("maxRetryWait");
        writer.writeCharacters(ObjectUtils.toString(getMaxRetryWait()));
        writer.writeEndElement();

        saveToXML(writer);

        writer.writeEndElement();
        writer.flush();
        writer.close();
    } catch (XMLStreamException e) {
        throw new IOException("Cannot save as XML.", e);
    }
}

From source file:com.esri.geoevent.test.performance.ui.OrchestratorController.java

/**
 * Saves the current fixtures file to disk.
 *
 * @param file File where to save the configuration file.
 * @throws JAXBException/* ww  w .  j a  v a2s.c o  m*/
 * @throws XMLStreamException
 * @throws IOException
 */
private void saveFile(File file) throws JAXBException, XMLStreamException, IOException {
    JAXBContext jaxbContext = JAXBContext.newInstance(Fixtures.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    FileWriter fileWriter = new FileWriter(file);
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    XMLStreamWriter xmlWritter = factory.createXMLStreamWriter(fileWriter);
    marshaller.marshal(fixtures, xmlWritter);
    fileWriter.flush();
    fileWriter.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;// www.  ja v  a2 s  .c o m
    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.ibm.bi.dml.runtime.controlprogram.parfor.opt.PerfTestTool.java

/**
 * StAX for efficient streaming XML writing.
 * //from   w w w .  j  av  a  2s .c  o  m
 * @throws IOException
 * @throws XMLStreamException 
 */
private static void writeProfile(String dname, String fname) throws IOException, XMLStreamException {
    //create initial directory and file 
    File dir = new File(dname);
    if (!dir.exists())
        dir.mkdir();
    File f = new File(fname);
    f.createNewFile();

    FileOutputStream fos = new FileOutputStream(f);

    try {
        //create document
        XMLOutputFactory xof = XMLOutputFactory.newInstance();
        XMLStreamWriter xsw = xof.createXMLStreamWriter(fos);
        //TODO use an alternative way for intentation
        //xsw = new IndentingXMLStreamWriter( xsw ); //remove this line if no indenting required

        //write document content
        xsw.writeStartDocument();
        xsw.writeStartElement(XML_PROFILE);
        xsw.writeAttribute(XML_DATE, String.valueOf(new Date()));

        //foreach instruction (boundle of cost functions)
        for (Entry<Integer, HashMap<Integer, CostFunction>> inst : _profile.entrySet()) {
            int instID = inst.getKey();
            String instName = _regInst_IDNames.get(instID);

            xsw.writeStartElement(XML_INSTRUCTION);
            xsw.writeAttribute(XML_ID, String.valueOf(instID));
            xsw.writeAttribute(XML_NAME, instName.replaceAll(Lop.OPERAND_DELIMITOR, " "));

            //foreach testdef cost function
            for (Entry<Integer, CostFunction> cfun : inst.getValue().entrySet()) {
                int tdefID = cfun.getKey();
                PerfTestDef def = _regTestDef.get(tdefID);
                CostFunction cf = cfun.getValue();

                xsw.writeStartElement(XML_COSTFUNCTION);
                xsw.writeAttribute(XML_ID, String.valueOf(tdefID));
                xsw.writeAttribute(XML_MEASURE, def.getMeasure().toString());
                xsw.writeAttribute(XML_VARIABLE, def.getVariable().toString());
                xsw.writeAttribute(XML_INTERNAL_VARIABLES, serializeTestVariables(def.getInternalVariables()));
                xsw.writeAttribute(XML_DATAFORMAT, def.getDataformat().toString());
                xsw.writeCharacters(serializeParams(cf.getParams()));
                xsw.writeEndElement();// XML_COSTFUNCTION
            }

            xsw.writeEndElement(); //XML_INSTRUCTION
        }

        xsw.writeEndElement();//XML_PROFILE
        xsw.writeEndDocument();
        xsw.close();
    } finally {
        IOUtilFunctions.closeSilently(fos);
    }
}

From source file:jodtemplate.pptx.io.xml.SlideXmlRelsWriter.java

@Override
public void write(final Resources resources, final Slide slide, final XMLOutputFactory xmlOutputFactory)
        throws XMLStreamException, IOException {
    final String slideXmlPath = FilenameUtils
            .normalize(slide.getPresentation().getFullPath() + slide.getRelationship().getTarget(), true);
    final String slideXmlRelsPath = Utils.getRelsPathNoPrefixSeparator(slideXmlPath);
    final Resource slideXmlRelsRes = resources.getResource(slideXmlRelsPath);

    try (final OutputStream os = slideXmlRelsRes.getOutputStream()) {
        os.write(//from www.j  a  v  a2s.  c  o  m
                "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n".getBytes(CharEncoding.UTF_8));
        final XMLStreamWriter writer = xmlOutputFactory.createXMLStreamWriter(os);
        writer.writeStartElement(OOXMLDocument.RELATIONSHIPS_ELEMENT);
        writer.writeNamespace("", OOXMLDocument.RELATIONSHIPS_RELS_NAMESPACE);
        for (Relationship rel : slide.getOtherRelationships()) {
            writer.writeEmptyElement(OOXMLDocument.RELATIONSHIPS_RELS_NAMESPACE,
                    OOXMLDocument.RELATIONSHIP_ELEMENT);
            writer.writeAttribute(OOXMLDocument.RELATIONSHIPS_RELS_NAMESPACE, OOXMLDocument.ID_ATTRIBUTE,
                    rel.getId());
            writer.writeAttribute(OOXMLDocument.RELATIONSHIPS_RELS_NAMESPACE, OOXMLDocument.TYPE_ATTRIBUTE,
                    rel.getType());
            writer.writeAttribute(OOXMLDocument.RELATIONSHIPS_RELS_NAMESPACE, OOXMLDocument.TARGET_ATTRIBUTE,
                    rel.getTarget());
            if (StringUtils.isNotBlank(rel.getTargetMode())) {
                writer.writeAttribute(OOXMLDocument.RELATIONSHIPS_RELS_NAMESPACE,
                        OOXMLDocument.TARGET_MODE_ATTRIBUTE, rel.getTargetMode());
            }
            writer.flush();
        }
        writer.writeEndElement();
        writer.writeEndDocument();

        writer.flush();
        writer.close();
    }
}

From source file:DDTReporter.java

/**
 * Report Generator logic//  w w w .ja v  a 2 s .  c  o m
 * @param description
 * @param emailBody
 */
public void generateDefaultReport(String description, String emailBody) {

    if (getDDTests().size() < 1) {
        System.out.println("No Test Steps to report on.  Report Generation aborted.");
        return;
    }

    String extraEmailBody = (isBlank(emailBody) ? "" : "<br>" + emailBody) + "</br>";

    // Create the values for the various top sections of the report
    // Project, Module, Mode, Summary
    String[][] environmentItems = getEnvironmentItems();

    String projectName = settings.projectName();
    if (isBlank(projectName))
        projectName = "Selenium Based Java DDT Automation Project";
    String moduleName = description;
    if (isBlank(moduleName))
        moduleName = "Selenium based Java DDT Test Results";

    projectName = Util.sq(projectName);
    moduleName = Util.sq(moduleName);

    String durationBlurb = " (Session duration: " + sessionDurationString() + ", Reported tests duration: "
            + durationString() + ")";
    // @TODO - When documentation mode becomes available, weave that in... using "Documentation" instead of "Results"
    String mode = "Test Results as of " + new SimpleDateFormat("HH:mm:ss - yyyy, MMMM dd").format(new Date())
            + durationBlurb;
    String osInfo = environmentItems[0][1];
    String envInfo = environmentItems[1][1];
    String javaInfo = environmentItems[2][1];
    String userInfo = environmentItems[3][1];

    String summary = sectionSummary() + " " + sessionSummary();

    // String summarizing the scope of this report section
    String rangeClause = " Reportable steps included in this report: " + firstReportStep() + " thru "
            + (lastReportStep());
    if (lastReportStep() != firstReportStep() || isNotBlank(settings.dontReportActions())) {
        rangeClause += " - Actions excluded from reporting: " + settings.dontReportActions().replace(",", ", ");
    }

    String underscore = "<br>==================<br>"; // Assuming html contents of email message

    String emailSubject = "Test Results for Project: " + projectName + ", Section: " + moduleName;
    summary += rangeClause;

    summary += " - Item status included: " + settings.statusToReport().replace(",", ", ")
            + " (un-reported action steps not counted.)";

    String fileName = new SimpleDateFormat("yyyyMMdd-HHmmss.SSS").format(new Date()) + ".xml";
    String folder = settings.reportsFolder() + Util.asSafePathString(description);

    // Ensure the folder exists - if no exception is thrown, it does!
    File tmp = Util.setupReportFolder(DDTSettings.asValidOSPath(folder, true));
    String fileSpecs = folder + File.separator + DDTSettings.asValidOSPath(fileName, true);

    String extraBlurb = "";
    int nReportableSteps = 0;
    XMLOutputFactory factory = XMLOutputFactory.newInstance();

    try {
        XMLStreamWriter writer = factory.createXMLStreamWriter(new FileWriter(fileSpecs));

        writer.writeStartDocument();
        writer.writeCharacters("\n");

        // build the xml hierarchy - the innermost portion of it are the steps (see below)
        writeStartElement(writer, "Project", new String[] { "name" }, new String[] { projectName });
        writeStartElement(writer, "Module", new String[] { "name" }, new String[] { moduleName });
        writeStartElement(writer, "Mode", new String[] { "name" }, new String[] { mode });
        writeStartElement(writer, "OperatingSystem", new String[] { "name" }, new String[] { osInfo });
        writeStartElement(writer, "Environment", new String[] { "name" }, new String[] { envInfo });
        writeStartElement(writer, "Java", new String[] { "name" }, new String[] { javaInfo });
        writeStartElement(writer, "User", new String[] { "name" }, new String[] { userInfo });
        writeStartElement(writer, "Summary", new String[] { "name" }, new String[] { summary });
        writeStartElement(writer, "Steps");

        // Failures will be added to the mailed message body - we construct it here.
        int nFailures = 0;

        for (DDTReportItem t : getDDTests()) {
            // Only report the statuses indicated for reporting in the settings.
            if (!(settings.statusToReport().contains(t.getStatus())))
                continue;
            String[] attributes = new String[] { "Id", "Name", "Status", "ErrDesc" };
            String[] values = new String[] { t.paddedReportedStepNumber(), t.getUserReport(), t.getStatus(),
                    t.getErrors() };
            writeStartElement(writer, "Step", attributes, values);

            // If step failed, add its description to the failedTestsSummary.
            if (t.hasErrors()) {
                nFailures++;
                String failureBlurb = underscore + "Failure " + nFailures + " - Step: "
                        + t.paddedReportedStepNumber() + underscore;
                failedTestsSummary
                        .add(failureBlurb + t.toString() + "<p>Errors:</p>" + t.errorsAsHtml() + "<br>");
            }

            // If step has any events to report - list those
            if (t.hasEventsToReport()) {
                String eventsToReport = settings.eventsToReport();
                writeStartElement(writer, "Events");
                for (TestEvent e : t.getEvents()) {
                    if (eventsToReport.contains(e.getType().toString())) {
                        writeStartElement(writer, "Event", new String[] { "name" },
                                new String[] { e.toString() });
                        writeEndElement(writer);
                    }
                }
                writeEndElement(writer); // step's events
            }

            writeEndElement(writer); // step
            nReportableSteps++;
        }

        // If no reportable steps recorded, write a step element to indicate so...
        if (nReportableSteps < 1) {
            extraBlurb = "*** No Reportable Steps encountered ***";
            String[] attributes = new String[] { "Id", "Name", "Status", "ErrDesc" };
            String[] values = new String[] { "------", extraBlurb, "", "" };

            writeStartElement(writer, "Step", attributes, values);
            writeEndElement(writer); // step
        }

        // close each of the xml hierarchy elements in reverse order
        writeEndElement(writer); // steps
        writeEndElement(writer); // summary
        writeEndElement(writer); // user
        writeEndElement(writer); // java
        writeEndElement(writer); // environment
        writeEndElement(writer); // operating system
        writeEndElement(writer); // mode
        writeEndElement(writer); // module
        writeEndElement(writer); // project

        writer.writeEndDocument();

        writer.flush();
        writer.close();

        try {
            transformXmlFileToHtml(fileSpecs, folder);
        } catch (Exception e) {
            System.out.println("Error encountered while transofrming xml file to html.\nReport not generated.");
            e.printStackTrace();
            return;
        }

        reportGenerated = true;

    } catch (XMLStreamException e) {
        System.out.println(
                "XML Stream Exception Encountered while transforming xml file to html.\nReport not generated.");
        e.printStackTrace();
        return;
    } catch (IOException e) {
        System.out.println(
                "IO Exception Encountered while transforming xml file to html.\nReport not generated.");
        e.printStackTrace();
        return;
    }

    if (isBlank(settings.emailRecipients())) {
        System.out.println("Empty Email Recipients List - Test Results not emailed. Report Generated");
    } else {
        String messageBody = "Attached is a summary of test results run titled " + Util.dq(description) + "<br>"
                + (isBlank(extraBlurb) ? "" : "<br>" + extraBlurb) + extraEmailBody;
        try {
            Email.sendMail(emailSubject, messageBody, fileSpecs.replace(".xml", ".html"), failedTestsSummary);
            System.out.println("Report Generated.  Report Results Emailed to: " + settings.emailRecipients());
        } catch (MessagingException e) {
            System.out.println(
                    "Messaging Exception Encountered while emailing test results.\nResults not sent, Report generated.");
            e.printStackTrace();
        }
    }

    reset();
}

From source file:com.norconex.committer.idol.IdolCommitter.java

/**
 * Commits the addition operations.// ww w. j av  a 2  s.  c o  m
 * @param addOperations additions
 */
public void dreAddData(List<IAddOperation> addOperations) {
    if (addOperations.isEmpty()) {
        return;
    }
    if (LOG.isInfoEnabled()) {
        LOG.info("Sending " + addOperations.size() + " documents for addition to " + createURL());
    }

    StringBuilder b = new StringBuilder();
    b.append(createURL());

    if (isCFS()) {
        b.append("action=ingest&adds=");
        StringWriter xml = new StringWriter();
        XMLOutputFactory factory = XMLOutputFactory.newInstance();
        try {
            XMLStreamWriter writer = factory.createXMLStreamWriter(xml);
            writer.writeStartElement("adds");
            buildCfsXmlBatchContent(writer, addOperations);
            writer.writeEndElement();
            writer.flush();
            writer.close();
            b.append(URLEncoder.encode(xml.toString(), CharEncoding.UTF_8));
        } catch (Exception e) {
            throw new CommitterException("Cannot create XML.", e);
        }
        postToIDOL(b.toString(), StringUtils.EMPTY);
    } else {
        b.append("DREADDDATA?");
        QueryString qs = new QueryString();
        for (String key : dreAddDataParams.keySet()) {
            qs.addString(key, dreAddDataParams.get(key));
        }
        String addURL = qs.applyOnURL(b.toString());
        String idxBatch = buildIdxBatchContent(addOperations);
        postToIDOL(addURL, idxBatch);
    }
    if (LOG.isInfoEnabled()) {
        LOG.debug("Done sending additions to " + createURL());
    }
}

From source file:de.uzk.hki.da.cb.CreatePremisAction.java

/**
 * Start new document./*  w  w w.j  ava  2s . com*/
 *
 * @param filePath the file path
 * @return the xML stream writer
 */
private XMLStreamWriter startNewDocument(String filePath) {

    XMLStreamWriter newWriter;

    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    try {
        outputStream = new FileOutputStream(filePath);
    } catch (FileNotFoundException e) {
        throw new RuntimeException("Failed to create FileOutputStream", e);
    }

    try {
        newWriter = outputFactory.createXMLStreamWriter(outputStream);

        newWriter.writeStartDocument("UTF-8", "1.0");
        newWriter.setPrefix("xsi", XSI_NS);
    } catch (Exception e) {
        throw new RuntimeException("Failed to create XMLStreamWriter", e);
    }

    return newWriter;
}

From source file:ca.uhn.fhir.util.XmlUtil.java

public static XMLStreamWriter createXmlStreamWriter(Writer theWriter)
        throws FactoryConfigurationError, XMLStreamException {
    throwUnitTestExceptionIfConfiguredToDoSo();

    XMLOutputFactory outputFactory = getOrCreateOutputFactory();
    XMLStreamWriter retVal = outputFactory.createXMLStreamWriter(theWriter);
    return retVal;
}