Example usage for javax.xml.stream XMLStreamWriter writeEndElement

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

Introduction

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

Prototype

public void writeEndElement() throws XMLStreamException;

Source Link

Document

Writes an end tag to the output relying on the internal state of the writer to determine the prefix and local name of the event.

Usage

From source file:com.moviejukebox.writer.MovieJukeboxHTMLWriter.java

/**
 * Generate a simple jukebox index file from scratch
 *
 * @param jukebox/* ww w  . j av a  2 s.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:net.solarnetwork.util.JavaBeanXmlSerializer.java

private void outputMap(Map<?, ?> map, String name, XMLStreamWriter out) throws XMLStreamException {
    writeElement(name, null, out, false);

    // for each entry, write an <entry> element
    for (Map.Entry<?, ?> me : map.entrySet()) {
        String entryName = me.getKey().toString();
        out.writeStartElement("entry");
        out.writeAttribute("key", entryName);

        Object value = me.getValue();
        if (value instanceof Collection) {
            // special collection case, we don't add nested element
            for (Object o : (Collection<?>) value) {
                outputObject(o, "value", out);
            }/*  www  . j  a v a 2s. co  m*/
        } else {
            outputObject(value, null, out);
        }
        out.writeEndElement();
    }

    out.writeEndElement();
}

From source file:com.basistech.bbhmp.RosapiBundleCollectorMojo.java

private void writeMetadata(Map<Integer, List<BundleSpec>> bundlesByLevel) throws MojoExecutionException {
    OutputStream os = null;/*from w  w  w  .jav a2 s .  c om*/
    File md = new File(outputDirectory, "bundles.xml");

    try {
        os = new FileOutputStream(md);
        XMLStreamWriter writer = XMLOutputFactory.newFactory().createXMLStreamWriter(os);
        writer = new IndentingXMLStreamWriter(writer);
        writer.writeStartDocument("utf-8", "1.0");
        writer.writeStartElement("bundles");
        for (Integer level : bundlesByLevel.keySet()) {
            writer.writeStartElement("level");
            writer.writeAttribute("level", Integer.toString(level));
            for (BundleSpec spec : bundlesByLevel.get(level)) {
                writer.writeStartElement("bundle");
                writer.writeAttribute("start", Boolean.toString(spec.start));
                writer.writeCharacters(spec.filename);
                writer.writeEndElement();
            }
            writer.writeEndElement();
        }
        writer.writeEndElement();
        writer.writeEndDocument();
        writer.flush();

    } catch (IOException | XMLStreamException e) {
        throw new MojoExecutionException("Failed to write metadata file " + md.toString(), e);
    } finally {
        IOUtils.closeQuietly(os);
    }
}

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();
    w.writeEndElement();/* www .j ava 2  s.  c  o m*/
    w.writeEndDocument();
    w.flush();
    return new ResponseEntity<>(sw.toString(), status);
}

From source file:com.microsoft.windowsazure.services.table.client.AtomPubParser.java

/**
 * Reserved for internal use. Writes an entity to the stream as an AtomPub Entry Resource, leaving the stream open
 * for additional writing./*from  w  w w .  j a v a 2s .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.
 */
protected static void writeEntityToStream(final TableEntity entity, final boolean isTableEntry,
        final XMLStreamWriter xmlw, final OperationContext opContext)
        throws XMLStreamException, StorageException {
    final HashMap<String, EntityProperty> properties = entity.writeEntity(opContext);
    if (properties == null) {
        throw new IllegalArgumentException("Entity did not produce properties to serialize");
    }

    if (!isTableEntry) {
        Utility.assertNotNullOrEmpty(TableConstants.PARTITION_KEY, entity.getPartitionKey());
        Utility.assertNotNullOrEmpty(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.adobe.acs.commons.wcm.impl.SiteMapServlet.java

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

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

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

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

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

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

        stream.writeEndElement();

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

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();
    w.writeEndElement();//from   w w  w .  j a  va  2s. c  o  m
    w.writeEndDocument();
    w.flush();
    return sw.toString();
}

From source file:babel.content.pages.PageVersion.java

/**
 * To be called by ObjectWriter only.// w w  w  . ja v a2s .co m
 * @throws XMLStreamException 
 */
public void persist(XMLStreamWriter writer) throws XMLStreamException {
    writer.writeStartElement(XML_TAG_PAGEVERSION);

    if (m_verProps.numKeys() > 0) {
        m_verProps.persist(writer);
    }

    if (m_parseMeta.numKeys() > 0) {
        m_parseMeta.persist(writer);
    }

    if (m_contentMeta.numKeys() > 0) {
        m_contentMeta.persist(writer);
    }

    if (m_outLinks != null) {
        String anchor;

        writer.writeStartElement(XML_TAG_OUT_LINKS);

        for (Outlink outlink : m_outLinks) {
            writer.writeStartElement(XML_TAG_LINK);
            anchor = outlink.getAnchor();

            if ((anchor != null) && (anchor.length() != 0)) {
                writer.writeAttribute(XML_ATTRIB_ANCHOR, anchor);
            }

            writer.writeCharacters(outlink.getToUrl());
            writer.writeEndElement();
        }

        writer.writeEndElement();
    }

    if (m_content.length() > 0) {
        writer.writeStartElement(XML_TAG_CONTENT);
        writer.writeCharacters(new String(Base64.encodeBase64(m_content.getBytes())));
        //writer.writeCharacters(m_content);
        writer.writeEndElement();
    }

    writer.writeEndElement();
}

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

protected void buildCfsXmlDocument(XMLStreamWriter writer, InputStream is, Properties properties)
        throws XMLStreamException, IOException {
    try {//from   w  ww  .  j  a va2s  .c om
        writer.writeStartElement("add");
        writer.writeStartElement("document");

        // Create a database key for the idol XML document
        String targetIdField = getTargetReferenceField();
        if (DEFAULT_IDOL_REFERENCE_FIELD.equalsIgnoreCase(targetIdField)) {
            writer.writeStartElement("reference");
            writer.writeCharacters(properties.getString(targetIdField));
            writer.writeEndElement();
        } else {
            writer.writeStartElement("metadata");
            writer.writeAttribute("name", targetIdField);
            writer.writeAttribute("value", properties.getString(targetIdField));
            writer.writeEndElement();
        }

        // Loop thru the list of properties and create XML fields
        // accordingly.
        for (Entry<String, List<String>> entry : properties.entrySet()) {
            if (!EqualsUtil.equalsAny(entry.getKey(), getTargetReferenceField(), getTargetContentField())) {
                for (String value : entry.getValue()) {
                    writer.writeStartElement("metadata");
                    writer.writeAttribute("name", entry.getKey());
                    writer.writeAttribute("value", value);
                    writer.writeEndElement();
                }
            }
        }

        // Store content at specified location
        String targetCtntField = getTargetContentField();
        String targetCtntValue = properties.getString(targetCtntField);

        writer.writeEndElement();

        writer.writeStartElement("source");
        writer.writeAttribute("content",
                Base64.encodeBase64String(targetCtntValue.getBytes(CharEncoding.UTF_8)));
        writer.writeEndElement();

        writer.writeEndElement();
    } finally {
        IOUtils.closeQuietly(is);
    }
}

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

/**
 * //from   w ww .j  a  va 2 s  .c o  m
 * @param xml
 * @param params
 * @param queryValue
 * @param queryType
 * @throws XMLStreamException
 */
protected void convReqWriteQuery(XMLStreamWriter xml, SolrParams params, String queryValue, QueryType queryType)
        throws XMLStreamException {

    if (queryType == QueryType.fulltext) {
        // freetext
        xml.writeStartElement("freetext");
        String stemmer = params.get(PARAM_STEMMER, config.defaults.stemmer);
        if (stemmer != null) {
            xml.writeAttribute("stemmer", stemmer);
        }
        String freetext_cutoff_df = params.get(PARAM_FREETEXT_CUTOFF_DF, config.defaults.freetext_cutoff_df);
        if (config.defaults.source != null) {
            xml.writeAttribute("cutoff-df", freetext_cutoff_df);
        }
        xml.writeCData(queryValue);
        xml.writeEndElement();
    } else {
        // article
        xml.writeStartElement("article");
        if (queryType == QueryType.vector) {
            xml.writeAttribute("vec", queryValue);
        } else {
            xml.writeAttribute("name", queryValue);
        }
        String source = params.get(PARAM_SOURCE, config.defaults.source);
        if (source != null) {
            xml.writeAttribute("source", source);
        }
        String article_cutoff_df = params.get(PARAM_ARTICLE_CUTOFF_DF, config.defaults.article_cutoff_df);
        if (source != null) {
            xml.writeAttribute("cutoff-df", article_cutoff_df);
        }
        xml.writeEndElement();
    }
}