Example usage for javax.xml.stream XMLOutputFactory newInstance

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

Introduction

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

Prototype

public static XMLOutputFactory newInstance() throws FactoryConfigurationError 

Source Link

Document

Creates a new instance of the factory in exactly the same manner as the #newFactory() method.

Usage

From source file:net.landora.video.info.file.FileInfoManager.java

private synchronized void writeCacheFile(File file, Map<String, FileInfo> infoMap) {
    OutputStream os = null;/*from www  .j a  va 2  s.com*/
    try {
        os = new BufferedOutputStream(new FileOutputStream(file));
        if (COMPRESS_INFO_FILE) {
            os = new GZIPOutputStream(os);
        }

        XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(os);
        writer.writeStartDocument();

        writer.writeStartElement("files");
        writer.writeCharacters("\n");

        for (Map.Entry<String, FileInfo> entry : infoMap.entrySet()) {
            FileInfo info = entry.getValue();

            writer.writeStartElement("file");
            writer.writeAttribute("filename", entry.getKey());

            writer.writeAttribute("ed2k", info.getE2dkHash());
            writer.writeAttribute("length", String.valueOf(info.getFileSize()));
            writer.writeAttribute("lastmodified", String.valueOf(info.getLastModified()));

            if (info.getMetadataSource() != null) {
                writer.writeAttribute("metadatasource", info.getMetadataSource());
            }
            if (info.getMetadataId() != null) {
                writer.writeAttribute("metadataid", info.getMetadataId());
            }
            if (info.getVideoId() != null) {
                writer.writeAttribute("videoid", info.getVideoId());
            }

            writer.writeEndElement();
            writer.writeCharacters("\n");
        }

        writer.writeEndElement();
        writer.writeEndDocument();
        writer.close();

    } catch (Exception e) {
        log.error("Error writing file cache.", e);
    } finally {
        if (os != null) {
            IOUtils.closeQuietly(os);
        }
    }
}

From source file:com.marklogic.client.impl.CombinedQueryBuilderImpl.java

private XMLStreamWriter makeXMLSerializer(OutputStream out) {
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    factory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);

    try {//from  w  ww  . j a v  a  2  s. c o  m
        XMLStreamWriter serializer = factory.createXMLStreamWriter(out, "UTF-8");

        serializer.setDefaultNamespace("http://marklogic.com/appservices/search");
        serializer.setPrefix("xs", XMLConstants.W3C_XML_SCHEMA_NS_URI);

        return serializer;
    } catch (Exception e) {
        throw new MarkLogicIOException(e);
    }
}

From source file:edu.jhu.cvrg.waveform.utility.WebServiceUtility.java

/** Generic function for calling web services with parameters which are more than one level deep.<BR>
 * Directly returns the webservice results if callback is null.
 * /*from  w  w w . java2s  .c o m*/
 * @param parameterMap - name, value pairs map for all the parameters(OMEChild) to be sent to the service, if a value is another LinkedHashMap, then it is assumed to contain subnodes of that parameter's key node.
 * @param serviceMethod - name of the specific method of the service to be called.  e.g. "copyDataFilesToAnalysis"
 * @param serviceName - name of the web service to invoke, e.g. "dataTransferService"
 * @param serviceURL - URL of machine the web service runs from. e.g. "http://icmv058.icm.jhu.edu:8080/axis2/services/"
 * @param callback - function to which the service will return result XML to. Calls service without callback if null.
 * @param filesMap - name, value pairs map for all the files(OMEChild) to be sent to the service.
 * @return
 */
public static OMElement callWebServiceComplexParam(Map<String, ?> parameterMap, String serviceMethod,
        String serviceName, String serviceURL, SvcAxisCallback callback, Map<String, FSFile> filesMap) {
    log.info("waveform-utilities.WebServiceUtility.callWebServiceComplexParam()");

    String serviceTarget = "";

    if (serviceName != null) {
        if (!serviceName.equals("")) {
            serviceTarget = serviceName; // + "/" + serviceMethod;
        } else {
            serviceTarget = serviceMethod;
        }
    }

    EndpointReference targetEPR = new EndpointReference(serviceURL + "/" + serviceTarget);

    OMFactory omFactory = OMAbstractFactory.getOMFactory();

    OMNamespace omNamespace = omFactory.createOMNamespace(serviceURL + "/" + serviceName, serviceName);
    OMElement omWebService = omFactory.createOMElement(serviceMethod, omNamespace);

    extractParameter(parameterMap, omFactory, omNamespace, omWebService);

    addFiles(filesMap, omWebService, omFactory, omNamespace);

    ServiceClient sender = getSender(targetEPR, serviceMethod);

    OMElement result = null;
    try {
        if (callback == null) {
            log.info("Service/method, no callback:" + serviceName + "/" + serviceMethod);
            //  Directly invoke an anonymous operation with an In-Out message exchange pattern.
            result = sender.sendReceive(omWebService);
            StringWriter writer = new StringWriter();
            result.serialize(XMLOutputFactory.newInstance().createXMLStreamWriter(writer));
            writer.flush();
        } else {
            log.info("Service/method, WITH callback:" + serviceName + "/" + serviceMethod);
            // Directly invoke an anonymous operation with an In-Out message exchange pattern without waiting for a response.
            sender.sendReceiveNonBlocking(omWebService, callback);
        }
    } catch (AxisFault e) {
        e.printStackTrace();
    } catch (XMLStreamException e) {
        e.printStackTrace();
    } catch (FactoryConfigurationError e) {
        e.printStackTrace();
    }

    return result;
}

From source file:org.castor.jaxb.CastorMarshallerTest.java

/**
 * Tests the {@link CastorMarshaller#marshal(Object, XMLStreamWriter)} method when jaxbElement is null. </p> {@link
 * IllegalArgumentException} is expected.
 *
 * @throws Exception if any error occurs during test
 *///from   www.j  av a 2 s .c o m
@Test(expected = IllegalArgumentException.class)
public void testMarshallXMLStreamWriterNull1() throws Exception {

    StringWriter writer = new StringWriter();
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    marshaller.marshal(null, outputFactory.createXMLStreamWriter(writer));
}

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

@SuppressWarnings("deprecation")
@Override/*  www .j  av  a  2  s. co  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:com.github.lindenb.jvarkit.tools.bam2xml.Bam2Xml.java

private int run(SamReader samReader) {
    OutputStream fout = null;//from  www  .  j  a va 2 s  .co m
    SAMRecordIterator iter = null;
    XMLStreamWriter w = null;
    try {
        XMLOutputFactory xmlfactory = XMLOutputFactory.newInstance();

        if (getOutputFile() != null) {
            fout = IOUtils.openFileForWriting(getOutputFile());
            w = xmlfactory.createXMLStreamWriter(fout, "UTF-8");
        } else {
            w = xmlfactory.createXMLStreamWriter(stdout(), "UTF-8");
        }
        w.writeStartDocument("UTF-8", "1.0");
        final SAMFileHeader header = samReader.getFileHeader();
        final SAMXMLWriter xw = new SAMXMLWriter(w, header);
        final SAMSequenceDictionaryProgress progress = new SAMSequenceDictionaryProgress(header);
        iter = samReader.iterator();
        while (iter.hasNext()) {
            xw.addAlignment(progress.watch(iter.next()));
        }
        xw.close();
        w.writeEndDocument();
        if (fout != null)
            fout.flush();
    } catch (Exception e) {
        e.printStackTrace();
        LOG.error(e);
        return -1;
    } finally {
        CloserUtil.close(w);
        CloserUtil.close(iter);
        CloserUtil.close(fout);
    }
    return 0;
}

From source file:de.uni_koblenz.jgralab.utilities.rsa2tg.SchemaGraph2XMI.java

/**
 * This method creates the XMI file. Created content is:<br/>
 * <code>&lt;?xml version="{@link XMIConstants4SchemaGraph2XMI#XML_VERSION}" encoding="{@link XMIConstants4SchemaGraph2XMI#XML_ENCODING}"?&gt;<br/>
 * &lt;!-- content created by {@link SchemaGraph2XMI#createRootElement(XMLStreamWriter, SchemaGraph)} --&gt;
 * </code>/* www. j  av  a2  s  . c o m*/
 * 
 * @param xmiName
 *            {@link String} the path of the XMI file
 * @param schemaGraph
 *            {@link SchemaGraph} to be converted into an XMI
 * @throws XMLStreamException
 * @throws IOException
 */
private void createXMI(String xmiName, SchemaGraph schemaGraph) throws XMLStreamException, IOException {
    Writer out = null;
    XMLStreamWriter writer = null;
    try {
        // create the XMLStreamWriter which creates the current xmi-file.
        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(xmiName), "UTF-8"));
        XMLOutputFactory factory = XMLOutputFactory.newInstance();
        factory.setProperty("javax.xml.stream.isRepairingNamespaces", Boolean.TRUE);
        writer = factory.createXMLStreamWriter(out);

        // write the first line
        writer.writeStartDocument(XMIConstants4SchemaGraph2XMI.XML_ENCODING,
                XMIConstants4SchemaGraph2XMI.XML_VERSION);
        createRootElement(writer, schemaGraph);
        // write the end of the document
        writer.writeEndDocument();

        // close the XMLStreamWriter
        writer.flush();
        out.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // no handling of exceptions, because they are throw as mentioned in
        // the declaration.
        if (writer != null) {
            writer.close();
        }
        if (out != null) {
            out.close();
        }
    }
}

From source file:DDTReporter.java

/**
 * Report Generator logic/*from  w  ww  .ja v  a2s  . co m*/
 * @param description
 * @param emailBody
 */
public void generateDefaultReport(String description, String emailBody) {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        writer.writeEndDocument();

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

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

        reportGenerated = true;

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

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

    reset();
}

From source file:jp.co.atware.solr.geta.GETAssocComponent.java

/**
 * GETAssoc??????/*from  w  ww . j a v  a 2s  .com*/
 * 
 * @param params
 * @param queryValue
 * @param queryType
 * @return
 * @throws FactoryConfigurationError
 * @throws IOException
 */
protected String convertRequest(SolrParams params, String queryValue, QueryType queryType)
        throws FactoryConfigurationError, IOException {

    String req;
    try {
        CharArrayWriter output = new CharArrayWriter();
        XMLStreamWriter xml = XMLOutputFactory.newInstance().createXMLStreamWriter(output);
        xml.writeStartDocument();
        xml.writeStartElement("gss");
        if (config.settings.gss3version != null) {
            xml.writeAttribute("version", config.settings.gss3version);
        }
        xml.writeStartElement("assoc");
        String target = params.get(PARAM_TARGET, config.defaults.target);
        if (target != null) {
            xml.writeAttribute("target", target);
        }
        convertRequestWriteStage1Param(xml, params);
        convertRequestWriteStage2Param(xml, params);

        convReqWriteQuery(xml, params, queryValue, queryType);

        xml.writeEndElement();
        xml.writeEndElement();
        xml.writeEndDocument();
        xml.close();
        req = output.toString();
    } catch (XMLStreamException e) {
        throw new IOException(e);
    }
    LOG.debug(req);
    return req;
}

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//from w  w  w . j  a  v a  2  s. co  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();
}