Example usage for javax.xml.stream XMLStreamWriter writeStartElement

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

Introduction

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

Prototype

public void writeStartElement(String localName) throws XMLStreamException;

Source Link

Document

Writes a start tag to the output.

Usage

From source file:com.ibm.bi.dml.runtime.controlprogram.parfor.opt.PerfTestTool.java

/**
 * StAX for efficient streaming XML writing.
 * /*w  ww .  j a  v a2  s .  co  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:com.moviejukebox.writer.MovieJukeboxHTMLWriter.java

/**
 * Generate a simple jukebox index file from scratch
 *
 * @param jukebox/*from w  w  w .  j  av a2s . co m*/
 * @param library
 */
private static void generateDefaultIndexHTML(Jukebox jukebox, Library library) {
    @SuppressWarnings("resource")
    OutputStream fos = null;
    XMLStreamWriter writer = null;

    try {
        File htmlFile = new File(jukebox.getJukeboxTempLocation(),
                PropertiesUtil.getProperty("mjb.indexFile", "index.htm"));
        FileTools.makeDirsForFile(htmlFile);

        fos = FileTools.createFileOutputStream(htmlFile);
        XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
        writer = outputFactory.createXMLStreamWriter(fos, "UTF-8");

        String homePage = PropertiesUtil.getProperty("mjb.homePage", "");
        if (homePage.length() == 0) {
            String defCat = library.getDefaultCategory();
            if (defCat != null) {
                homePage = FileTools.createPrefix("Other",
                        HTMLTools.encodeUrl(FileTools.makeSafeFilename(defCat))) + "1";
            } else {
                // figure out something better to do here
                LOG.info("No categories were found, so you should specify mjb.homePage in the config file.");
            }
        }

        writer.writeStartDocument();
        writer.writeStartElement("html");
        writer.writeStartElement("head");

        writer.writeStartElement("meta");
        writer.writeAttribute("name", "YAMJ");
        writer.writeAttribute("content", "MovieJukebox");
        writer.writeEndElement();

        writer.writeStartElement("meta");
        writer.writeAttribute("HTTP-EQUIV", "Content-Type");
        writer.writeAttribute("content", "text/html; charset=UTF-8");
        writer.writeEndElement();

        writer.writeStartElement("meta");
        writer.writeAttribute("HTTP-EQUIV", "REFRESH");
        writer.writeAttribute("content", "0; url=" + jukebox.getDetailsDirName() + '/' + homePage + EXT_HTML);
        writer.writeEndElement();

        writer.writeEndElement();
        writer.writeEndElement();
    } catch (XMLStreamException | IOException ex) {
        LOG.error("Failed generating HTML library index: {}", ex.getMessage());
        LOG.error(SystemTools.getStackTrace(ex));
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (Exception ex) {
                LOG.trace("Failed to close XMLStreamWriter");
            }
        }

        if (fos != null) {
            try {
                fos.close();
            } catch (Exception ex) {
                LOG.trace("Failed to close FileOutputStream");
            }
        }
    }
}

From source file:com.microsoft.windowsazure.storage.table.TableParser.java

/**
 * Reserved for internal use. Writes an entity to the stream as an AtomPub Entry Resource, leaving the stream open
 * for additional writing.//w  w  w.j  a  v  a2  s  . c om
 * 
 * @param entity
 *            The instance implementing {@link TableEntity} to write to the output stream.
 * @param isTableEntry
 *            A flag indicating the entity is a reference to a table at the top level of the storage service when
 *            <code>true<code> and a reference to an entity within a table when <code>false</code>.
 * @param xmlw
 *            The <code>XMLStreamWriter</code> to write the entity to.
 * @param opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * 
 * @throws XMLStreamException
 *             if an error occurs accessing the stream.
 * @throws StorageException
 *             if a Storage service error occurs.
 */
private static void writeAtomEntity(final TableEntity entity, final boolean isTableEntry,
        final XMLStreamWriter xmlw, final OperationContext opContext)
        throws XMLStreamException, StorageException {
    HashMap<String, EntityProperty> properties = entity.writeEntity(opContext);
    if (properties == null) {
        properties = new HashMap<String, EntityProperty>();
    }

    if (!isTableEntry) {
        Utility.assertNotNull(TableConstants.PARTITION_KEY, entity.getPartitionKey());
        Utility.assertNotNull(TableConstants.ROW_KEY, entity.getRowKey());
        Utility.assertNotNull(TableConstants.TIMESTAMP, entity.getTimestamp());
    }

    // Begin entry
    xmlw.writeStartElement("entry");
    xmlw.writeNamespace("d", ODataConstants.DATA_SERVICES_NS);
    xmlw.writeNamespace("m", ODataConstants.DATA_SERVICES_METADATA_NS);

    // default namespace
    xmlw.writeNamespace(null, ODataConstants.ATOM_NS);

    // Content
    xmlw.writeStartElement(ODataConstants.CONTENT);
    xmlw.writeAttribute(ODataConstants.TYPE, ODataConstants.ODATA_CONTENT_TYPE);

    // m:properties
    xmlw.writeStartElement("m", ODataConstants.PROPERTIES, ODataConstants.DATA_SERVICES_METADATA_NS);

    if (!isTableEntry) {
        // d:PartitionKey
        xmlw.writeStartElement("d", TableConstants.PARTITION_KEY, ODataConstants.DATA_SERVICES_NS);
        xmlw.writeAttribute("xml", "xml", "space", "preserve");
        xmlw.writeCharacters(entity.getPartitionKey());
        xmlw.writeEndElement();

        // d:RowKey
        xmlw.writeStartElement("d", TableConstants.ROW_KEY, ODataConstants.DATA_SERVICES_NS);
        xmlw.writeAttribute("xml", "xml", "space", "preserve");
        xmlw.writeCharacters(entity.getRowKey());
        xmlw.writeEndElement();

        // d:Timestamp
        if (entity.getTimestamp() == null) {
            entity.setTimestamp(new Date());
        }

        xmlw.writeStartElement("d", TableConstants.TIMESTAMP, ODataConstants.DATA_SERVICES_NS);
        xmlw.writeAttribute("m", ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.TYPE,
                EdmType.DATE_TIME.toString());
        xmlw.writeCharacters(Utility.getTimeByZoneAndFormat(entity.getTimestamp(), Utility.UTC_ZONE,
                Utility.ISO8061_LONG_PATTERN));
        xmlw.writeEndElement();
    }

    for (final Entry<String, EntityProperty> ent : properties.entrySet()) {
        if (ent.getKey().equals(TableConstants.PARTITION_KEY) || ent.getKey().equals(TableConstants.ROW_KEY)
                || ent.getKey().equals(TableConstants.TIMESTAMP) || ent.getKey().equals("Etag")) {
            continue;
        }

        EntityProperty currProp = ent.getValue();

        // d:PropName
        xmlw.writeStartElement("d", ent.getKey(), ODataConstants.DATA_SERVICES_NS);

        if (currProp.getEdmType() == EdmType.STRING) {
            xmlw.writeAttribute("xml", "xml", "space", "preserve");
        } else if (currProp.getEdmType().toString().length() != 0) {
            String edmTypeString = currProp.getEdmType().toString();
            if (edmTypeString.length() != 0) {
                xmlw.writeAttribute("m", ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.TYPE,
                        edmTypeString);
            }
        }

        if (currProp.getIsNull()) {
            xmlw.writeAttribute("m", ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.NULL,
                    Constants.TRUE);
        }

        // Write Value
        xmlw.writeCharacters(currProp.getValueAsString());
        // End d:PropName
        xmlw.writeEndElement();
    }

    // End m:properties
    xmlw.writeEndElement();

    // End content
    xmlw.writeEndElement();

    // End entry
    xmlw.writeEndElement();
}

From source file:com.norconex.collector.http.client.impl.GenericHttpClientFactory.java

private void writeStringElement(XMLStreamWriter writer, String name, String value) throws XMLStreamException {
    writer.writeStartElement(name);
    writer.writeCharacters(value);// w  ww . j  a v  a2s  .  c om
    writer.writeEndElement();
}

From source file:com.norconex.collector.http.client.impl.GenericHttpClientFactory.java

@Override
public void saveToXML(Writer out) throws IOException {
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    try {/*w w  w .  j  av a2s.c  o  m*/
        XMLStreamWriter writer = factory.createXMLStreamWriter(out);
        writer.writeStartElement("httpClientFactory");
        writer.writeAttribute("class", getClass().getCanonicalName());

        writeBoolElement(writer, "cookiesDisabled", cookiesDisabled);
        writeStringElement(writer, "authMethod", authMethod);
        writeStringElement(writer, "authUsername", authUsername);
        writeStringElement(writer, "authPassword", authPassword);
        writeStringElement(writer, "authUsernameField", authUsernameField);
        writeStringElement(writer, "authPasswordField", authPasswordField);
        writeStringElement(writer, "authURL", authURL);
        writeStringElement(writer, "authHostname", authHostname);
        writeIntElement(writer, "authPort", authPort);
        writeStringElement(writer, "authFormCharset", authFormCharset);
        writeStringElement(writer, "authWorkstation", authWorkstation);
        writeStringElement(writer, "authDomain", authDomain);
        writeStringElement(writer, "authRealm", authRealm);
        writeStringElement(writer, "proxyHost", proxyHost);
        writeIntElement(writer, "proxyPort", proxyPort);
        writeStringElement(writer, "proxyScheme", proxyScheme);
        writeStringElement(writer, "proxyUsername", proxyUsername);
        writeStringElement(writer, "proxyPassword", proxyPassword);
        writeStringElement(writer, "proxyRealm", proxyRealm);
        writer.writeEndElement();
        writeIntElement(writer, "connectionTimeout", connectionTimeout);
        writeIntElement(writer, "socketTimeout", socketTimeout);
        writeIntElement(writer, "connectionRequestTimeout", connectionRequestTimeout);
        writeStringElement(writer, "connectionCharset", connectionCharset);
        writeBoolElement(writer, "expectContinueEnabled", expectContinueEnabled);
        writeIntElement(writer, "maxRedirects", maxRedirects);
        writeStringElement(writer, "localAddress", localAddress);
        writeBoolElement(writer, "staleConnectionCheckDisabled", staleConnectionCheckDisabled);
        writeIntElement(writer, "maxConnections", maxConnections);

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

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

private ResponseEntity<String> errorResponse(String message, HttpStatus status) throws XMLStreamException {
    StringWriter sw = new StringWriter();
    XMLStreamWriter w = xmlOutputFactory.createXMLStreamWriter(sw);
    w.writeStartDocument("UTF-8", "1.0");
    w.writeStartElement("Opus");
    w.writeStartElement("Error");
    w.writeAttribute("message", message);
    w.writeEndElement();//from  w  w w. j a  va2 s. c  o m
    w.writeEndElement();
    w.writeEndDocument();
    w.flush();
    return new ResponseEntity<>(sw.toString(), status);
}

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

private String getDocumentUpdatedResponse() throws XMLStreamException {
    StringWriter sw = new StringWriter();
    XMLStreamWriter w = xmlOutputFactory.createXMLStreamWriter(sw);
    w.writeStartDocument("UTF-8", "1.0");
    w.writeStartElement("Opus");
    w.writeStartElement("Opus_Document_Info");
    w.writeCharacters("Update was successful.");
    w.writeEndElement();//www. java 2  s.  c om
    w.writeEndElement();
    w.writeEndDocument();
    w.flush();
    return sw.toString();
}

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

private String getDocumentCreatedResponse(String id) throws XMLStreamException {
    StringWriter sw = new StringWriter();
    XMLStreamWriter w = xmlOutputFactory.createXMLStreamWriter(sw);
    w.writeStartDocument("UTF-8", "1.0");
    w.writeStartElement("Opus");
    w.writeStartElement("Opus_Document");
    w.writeNamespace(XLINK_NAMESPACE_PREFIX, XLINK_NAMESPACE);
    w.writeAttribute(XLINK_NAMESPACE, "href", getHrefLink(id));
    w.writeAttribute("id", id);
    w.writeEndElement();/* www. ja  v a 2  s .  co m*/
    w.writeEndElement();
    w.writeEndDocument();
    w.flush();
    return sw.toString();
}

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

@RequestMapping(value = "/document", method = RequestMethod.GET)
public ResponseEntity<String> listAll() throws IOException, FedoraClientException, XMLStreamException {
    List<String> pids = fedoraRepository.getPIDsByPattern("^qucosa:");

    StringWriter sw = new StringWriter();
    XMLStreamWriter w = xmlOutputFactory.createXMLStreamWriter(sw);
    w.writeStartDocument("UTF-8", "1.0");
    w.writeStartElement("Opus");
    w.writeAttribute("version", "2.0");
    w.writeStartElement("DocumentList");
    w.writeNamespace("xlink", "http://www.w3.org/1999/xlink");
    for (String pid : pids) {
        String nr = pid.substring(pid.lastIndexOf(':') + 1);
        String href = getHrefLink(nr);
        w.writeEmptyElement("Document");
        w.writeAttribute("xlink:href", href);
        w.writeAttribute("xlink:nr", nr);
        w.writeAttribute("xlink:type", "simple");
    }/*from   w w w  .j  a v a2 s .c o  m*/
    w.writeEndElement();
    w.writeEndElement();
    w.writeEndDocument();
    w.flush();

    return new ResponseEntity<>(sw.toString(), HttpStatus.OK);
}

From source file:com.fiorano.openesb.application.application.Route.java

protected void toJXMLString(XMLStreamWriter writer, boolean writeCDataSections)
        throws XMLStreamException, FioranoException {
    writer.writeStartElement(ELEM_ROUTE);
    {//from w w w . jav  a 2 s  .  co m
        writer.writeAttribute(ATTR_NAME, name);
        if (ignoreAbsenceOfTransformation) {//write only if true
            writer.writeAttribute(ATTR_IGNORE_ABSENCE_TRANSFORMATION,
                    String.valueOf(ignoreAbsenceOfTransformation));
        }
        writer.writeStartElement(ELEM_SOURCE);
        {
            writer.writeAttribute(ATTR_SOURCE_SERVICE_INSTANCE, sourceServiceInstance);
            writer.writeAttribute(ATTR_SOURCE_PORT_INSTANCE, sourcePortInstance);
        }
        writer.writeEndElement();

        writer.writeStartElement(ELEM_TARGET);
        {
            writer.writeAttribute(ATTR_TARGET_SERVICE_INSTANCE, targetServiceInstance);
            writer.writeAttribute(ATTR_TARGET_PORT_INSTANCE, targetPortInstance);
        }
        writer.writeEndElement();

        writeElement(writer, ELEM_SHORT_DESCRIPTION, shortDescription);
        writeElement(writer, ELEM_LONG_DESCRIPTION, longDescription);

        if (messagingConfigName != null) {
            writer.writeStartElement(ELEM_MESSAGING_CONFIG_NAME);
            {
                writer.writeAttribute(ATTR_NAME, messagingConfigName);
            }
            writer.writeEndElement();
        } else {
            writer.writeStartElement(ELEM_MESSAGES);
            {
                if (compressed)
                    writer.writeAttribute(ATTR_COMPRESS, String.valueOf(true));
                if (durable)
                    writer.writeAttribute(ATTR_DURABLE, String.valueOf(true));
                if (encrypted)
                    writer.writeAttribute(ATTR_ENCRYPT, String.valueOf(true));
                writer.writeAttribute(ATTR_ROUTE_DURABLE_PRIORITY, String.valueOf(durabilitySource));
            }
            writer.writeEndElement();
        }

        if (messageTransformation != null)
            messageTransformation.toJXMLString(writer, writeCDataSections);

        if (selectorConfigName != null) {
            writer.writeStartElement(ELEM_SELECTOR_CONFIG_NAME);
            {
                writer.writeAttribute(ATTR_NAME, selectorConfigName);
            }
            writer.writeEndElement();
        } else if (selectors.size() > 0) {
            writer.writeStartElement(ELEM_SELECTORS);
            {
                Iterator iter = selectors.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    writer.writeStartElement(ELEM_SELECTOR);
                    {
                        writer.writeAttribute(ATTR_TYPE, (String) entry.getKey());
                        if (entry.getValue() instanceof XPathSelector)
                            ((XPathSelector) entry.getValue()).toJXMLString(writer);
                        else
                            writer.writeCharacters((String) entry.getValue());
                    }
                    writer.writeEndElement();
                }
            }
            writer.writeEndElement();
        }

        if (logManager != null)
            logManager.toJXMLString(writer);
        writeCollection(writer, logModules, ELEM_LOGMODULES);
    }
    writer.writeEndElement();
}