Example usage for javax.xml.stream XMLStreamWriter writeCharacters

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

Introduction

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

Prototype

public void writeCharacters(String text) throws XMLStreamException;

Source Link

Document

Write text to the output

Usage

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

/**
 * Generates a XML response that describe the EC2 instances
 */// w ww.  j av  a  2  s.  c  om
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:edu.stanford.cfuller.colocalization3d.correction.Correction.java

protected String writeToXML() {

    StringWriter sw = new StringWriter();

    try {//from   ww w .j a v a 2s.co 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.norconex.committer.idol.IdolCommitter.java

@Override
protected void saveToXML(XMLStreamWriter writer) throws XMLStreamException {
    writer.writeStartElement("host");
    writer.writeCharacters(getHost());
    writer.writeEndElement();/*from  w  ww  .ja v a  2  s .  c  om*/

    writer.writeStartElement("cfsPort");
    writer.writeCharacters(Integer.toString(getCfsPort()));
    writer.writeEndElement();

    writer.writeStartElement("indexPort");
    writer.writeCharacters(Integer.toString(getIndexPort()));
    writer.writeEndElement();

    writer.writeStartElement("databaseName");
    writer.writeCharacters(getDatabaseName());
    writer.writeEndElement();

    writer.writeStartElement("dreAddDataParams");
    for (String key : dreAddDataParams.keySet()) {
        writer.writeStartElement("param");
        writer.writeAttribute(key, key);
        writer.writeCharacters(dreAddDataParams.get(key));
        writer.writeEndElement();
    }
    writer.writeEndElement();

    writer.writeStartElement("dreDeleteRefParams");
    for (String key : dreDeleteRefParams.keySet()) {
        writer.writeStartElement("param");
        writer.writeAttribute(key, key);
        writer.writeCharacters(dreDeleteRefParams.get(key));
        writer.writeEndElement();
    }
    writer.writeEndElement();
}

From source file:com.norconex.collector.http.sitemap.impl.DefaultSitemapResolver.java

@Override
public void saveToXML(Writer out) throws IOException {
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    try {//from  w  ww  . j a  va2s .c  o  m
        XMLStreamWriter writer = factory.createXMLStreamWriter(out);
        writer.writeStartElement("sitemap");
        writer.writeAttribute("class", getClass().getCanonicalName());
        writer.writeAttribute("lenient", Boolean.toString(lenient));
        if (sitemapLocations != null) {
            for (String location : sitemapLocations) {
                writer.writeStartElement("location");
                writer.writeCharacters(location);
                writer.writeEndElement();
            }
        }
        writer.writeEndElement();
        writer.flush();
        writer.close();
    } catch (XMLStreamException e) {
        throw new IOException("Cannot save as XML.", e);
    }
}

From source file:de.shadowhunt.subversion.internal.CommitMessageOperation.java

@Override
protected HttpUriRequest createRequest() {
    final Writer body = new StringBuilderWriter();
    try {// w  w  w.j  a  v a2  s . c o m
        final XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(body);
        writer.writeStartDocument(XmlConstants.ENCODING, XmlConstants.VERSION_1_0);
        writer.writeStartElement("propertyupdate");
        writer.writeDefaultNamespace(XmlConstants.DAV_NAMESPACE);
        writer.writeStartElement("set");
        writer.writeStartElement("prop");
        writer.setPrefix(XmlConstants.SUBVERSION_DAV_PREFIX, XmlConstants.SUBVERSION_DAV_NAMESPACE);
        writer.writeStartElement(XmlConstants.SUBVERSION_DAV_NAMESPACE, "log");
        writer.writeNamespace(XmlConstants.SUBVERSION_DAV_PREFIX, XmlConstants.SUBVERSION_DAV_NAMESPACE);
        writer.writeCharacters(message);
        writer.writeEndElement(); // log
        writer.writeEndElement(); // prop
        writer.writeEndElement(); // set
        writer.writeEndElement(); // propertyupdate
        writer.writeEndDocument();
        writer.close();
    } catch (final XMLStreamException e) {
        throw new SubversionException("could not create request body", e);
    }

    final URI uri = URIUtils.createURI(repository, resource);
    final DavTemplateRequest request = new DavTemplateRequest("PROPPATCH", uri);
    request.setEntity(new StringEntity(body.toString(), CONTENT_TYPE_XML));
    return request;
}

From source file:DDTReporter.java

private void writeStartElement(XMLStreamWriter writer, String name, String[] attributes, String[] values)
        throws XMLStreamException {
    writer.writeStartElement(name);/*  w w  w  . ja  v  a  2  s  .c o  m*/
    for (int i = 0; i < attributes.length; i++) {
        writer.writeAttribute(attributes[i], values[i]);
    }
    writer.writeCharacters("\n");
}

From source file:DDTReporter.java

/**
 * Report Generator logic//from ww w . j  av  a2 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.fiorano.openesb.application.application.LogManager.java

protected void toJXMLString(XMLStreamWriter writer) throws XMLStreamException, FioranoException {

    writer.writeStartElement(ELEM_LOG_MANAGER);
    {// ww w. j  a  v  a2 s .c  o m
        writer.writeAttribute(ATTR_LOGGER_CLASS, loggerClass);

        Iterator iter = props.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            writer.writeStartElement(ELEM_PARAM);
            {
                writer.writeAttribute(ATTR_PROPERTY_NAME, (String) entry.getKey());
                writer.writeCharacters((String) entry.getValue());
            }
            writer.writeEndElement();
        }
    }
    writer.writeEndElement();
}

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

@SuppressWarnings("deprecation")
@Override// w  ww .java  2  s .c o  m
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:edu.harvard.hms.dbmi.bd2k.irct.ws.rs.resultconverter.XMLTabularDataConverter.java

@Override
public StreamingOutput createStream(final Result result) {
    StreamingOutput stream = new StreamingOutput() {
        @Override/*from   www  .  j  a v  a  2s.c om*/
        public void write(OutputStream outputStream) throws IOException, WebApplicationException {
            ResultSet rs = null;
            XMLStreamWriter xtw = null;
            try {
                rs = (ResultSet) result.getData();
                rs.load(result.getResultSetLocation());
                XMLOutputFactory xof = XMLOutputFactory.newInstance();
                xtw = xof.createXMLStreamWriter(new OutputStreamWriter(outputStream));
                xtw.writeStartDocument("utf-8", "1.0");
                xtw.writeStartElement("results");
                rs.beforeFirst();
                while (rs.next()) {
                    xtw.writeStartElement("result");
                    for (int i = 0; i < rs.getColumnSize(); i++) {
                        xtw.writeStartElement(rs.getColumn(i).getName().replace(" ", "_"));
                        xtw.writeCharacters(rs.getString(i));
                        xtw.writeEndElement();
                    }
                    xtw.writeEndElement();
                }
                xtw.writeEndElement();
                xtw.writeEndDocument();

                xtw.flush();

            } catch (ResultSetException | PersistableException | XMLStreamException e) {
                log.info("Error creating XML Stream: " + e.getMessage());
            } finally {
                if (xtw != null) {
                    try {
                        xtw.close();
                    } catch (XMLStreamException e) {
                        e.printStackTrace();
                    }
                }
                if (rs != null && !rs.isClosed()) {
                    try {
                        rs.close();
                    } catch (ResultSetException e) {
                        e.printStackTrace();
                    }
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            }

        }
    };
    return stream;
}