Example usage for javax.xml.stream XMLStreamWriter writeEndDocument

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

Introduction

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

Prototype

public void writeEndDocument() throws XMLStreamException;

Source Link

Document

Closes any start tags and writes corresponding end tags.

Usage

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

/**
 * Writes manageable properties file with the specified label
 * @param applicationFolderName event process folder
 * @param label environment label/*from  w  ww .  java 2  s. c o m*/
 * @throws FioranoException FioranoException
 * @throws XMLStreamException XMLStreamException
 */
public void writeManageableProperties(File applicationFolderName, Label label)
        throws FioranoException, XMLStreamException {
    File manageablePropertiesFile = getManageablePropertiesFile(applicationFolderName, label);
    if (!manageablePropertiesFile.exists())
        manageablePropertiesFile.getParentFile().mkdirs();

    XMLOutputFactory outputFactory = XMLUtils.getStaxOutputFactory();
    //        System.out.println(".....:"+outputFactory);
    //outputFactory.setProperty(XMLOutputFactory.INDENTATION, "/t");
    XMLStreamWriter writer = null;
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(manageablePropertiesFile);
        writer = outputFactory.createXMLStreamWriter(fos);
        writer.writeStartDocument();
        {

            writer.writeStartElement(ELEM_TARGET, ELEM_TARGET, Namespaces.URI_TARGET);
            writer.writeAttribute(XMLNS_TARGET, Namespaces.URI_TARGET);
            writer.writeAttribute(XMLNS_XSI, Namespaces.URI_XSI);
            writer.writeAttribute(XSI_LOCATION, Namespaces.URI_ENV_XSD);
            {
                for (ServiceInstance instance : getServiceInstances()) {
                    instance.writeManageableProperties(writer);
                }

            }
            writer.writeEndElement();
        }

        writer.writeEndDocument();

        writer.flush();
    } catch (XMLStreamException e) {
        throw new FioranoException(e);
    } catch (IOException e) {
        throw new FioranoException(e);
    } finally {
        try {
            if (writer != null)
                writer.close();
        } catch (XMLStreamException e) {
            // Ignore
        }

        try {
            if (fos != null)
                fos.close();
        } catch (IOException e) {
            // Ignore
        }
    }

}

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");
    }/*  ww w . j  a  va  2  s. c  o  m*/
    w.writeEndElement();
    w.writeEndElement();
    w.writeEndDocument();
    w.flush();

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

From source file:com.microsoft.tfs.core.ws.runtime.types.StaxAnyContentType.java

@Override
public void readFromElement(final XMLStreamReader reader) throws XMLStreamException {
    FastTempOutputStream ftos = null;//from   w  w  w .  j  av a 2 s.  c  o  m
    XMLStreamWriter writer = null;

    /*
     * When this method is called, the writer is positioned at the element
     * that contains the "any" content. Process the child elements until the
     * container is done.
     */

    /*
     * Advance one event to get the first child.
     */
    int event = reader.next();

    do {
        if (event == XMLStreamConstants.START_ELEMENT) {
            /*
             * Parse the child element into its own temp file. The copier
             * will read the child's end element.
             */
            try {
                /*
                 * Get a new fast temp output stream.
                 */
                ftos = new FastTempOutputStream(heapStorageLimitBytes, initialHeapStorageSizeBytes);

                tempOutputStreams.add(ftos);

                /*
                 * Create a writer.
                 */
                writer = StaxFactoryProvider.getXMLOutputFactory().createXMLStreamWriter(ftos,
                        SOAPRequestEntity.SOAP_ENCODING);
                writer.writeStartDocument();

                StaxUtils.copyCurrentElement(reader, writer);

                /*
                 * Make sure to finish off the document.
                 */
                writer.writeEndDocument();
            } finally {
                if (writer != null) {
                    writer.close();
                }

                /*
                 * Closing writers does not close the underlying stream, so
                 * close that manually. This is required so the temp stream
                 * can be read from.
                 */
                if (ftos != null) {
                    try {
                        ftos.close();
                    } catch (final IOException e) {
                        log.error(e);
                    }
                }

            }
        }
    } while ((event = reader.next()) != XMLStreamConstants.END_ELEMENT);
}

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

private synchronized void writeCacheFile(File file, Map<String, FileInfo> infoMap) {
    OutputStream os = null;//  w w w .j a v  a2s .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:de.qucosa.webapi.v1.SearchResource.java

private ResponseEntity<String> scrollAndBuildResultList(SearchResponse searchResponse)
        throws XMLStreamException, ParseException {
    StringWriter sw = new StringWriter();
    XMLStreamWriter w = xmlOutputFactory.createXMLStreamWriter(sw);

    SearchHits searchHits = searchResponse.getHits();

    w.writeStartDocument("UTF-8", "1.0");
    w.writeStartElement("Opus");
    {//from  w  ww  . j a  v  a2  s.co m
        w.writeStartElement("SearchResult");
        {
            w.writeStartElement("Search");
            w.writeAttribute("hits", String.valueOf(searchHits.getTotalHits()));
            w.writeEndElement();
            w.writeStartElement("ResultList");
            w.writeNamespace(XLINK_NAMESPACE_PREFIX, XLINK_NAMESPACE);

            SearchResponse scrollResponse = searchResponse;
            int hitcount = 0;
            while (true) {
                hitcount = writeResultElements(w, searchHits, hitcount);
                scrollResponse = elasticSearchClient.prepareSearchScroll(scrollResponse.getScrollId())
                        .setScroll(new TimeValue(60, TimeUnit.SECONDS)).execute().actionGet();
                searchHits = scrollResponse.getHits();
                if (searchHits.getHits().length == 0) {
                    log.debug("Stop scrolling at hitcount: {}", hitcount);
                    break;
                }
            }

            w.writeEndElement();
        }
        w.writeEndElement();
    }
    w.writeEndElement();
    w.writeEndDocument();
    w.flush();

    log.debug(sw.toString());

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

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

/** Extract as many as <code>limit</code> questions from the <code>reader</code>
 *  provided, writing them to <code>writer</code>.
 * @param reader/*  w w  w. java 2  s  . co  m*/
 * @param writer
 * @param limit
 * @return
 * @throws XMLStreamException
 */
protected int extractXMLData(XMLStreamReader reader, XMLStreamWriter writer, int limit)
        throws XMLStreamException {

    int questionCount = 0;
    int attrCount;
    boolean copyElement = false;

    writer.writeStartDocument();
    writer.writeStartElement("posts");
    writer.writeCharacters("\n");
    while (reader.hasNext() && questionCount < limit) {
        switch (reader.next()) {
        case XMLEvent.START_ELEMENT:
            if (reader.getLocalName().equals("row")) {
                attrCount = reader.getAttributeCount();
                for (int i = 0; i < attrCount; i++) {
                    // copy only the questions.
                    if (reader.getAttributeName(i).getLocalPart().equals("PostTypeId")
                            && reader.getAttributeValue(i).equals("1")) {
                        copyElement = true;
                        break;
                    }
                }

                if (copyElement) {
                    writer.writeCharacters("  ");
                    writer.writeStartElement("row");
                    for (int i = 0; i < attrCount; i++) {
                        writer.writeAttribute(reader.getAttributeName(i).getLocalPart(),
                                reader.getAttributeValue(i));
                    }
                    writer.writeEndElement();
                    writer.writeCharacters("\n");
                    copyElement = false;
                    questionCount++;
                }
            }
            break;
        }
    }
    writer.writeEndElement();
    writer.writeEndDocument();
    writer.flush();
    writer.close();

    return questionCount;
}

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

@Override
protected HttpUriRequest createRequest() {
    final URI uri = URIUtils.createURI(repository, resource);
    final DavTemplateRequest request = new DavTemplateRequest("PROPPATCH", uri);

    if (lockToken != null) {
        request.addHeader("If", "<" + uri + "> (<" + lockToken + ">)");
    }/*  w  w w  .j a  v a2  s.  c o m*/

    final Writer body = new StringBuilderWriter();
    try {
        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.setPrefix(XmlConstants.SUBVERSION_CUSTOM_PREFIX, XmlConstants.SUBVERSION_CUSTOM_NAMESPACE);
        writer.writeNamespace(XmlConstants.SUBVERSION_CUSTOM_PREFIX, XmlConstants.SUBVERSION_CUSTOM_NAMESPACE);
        writer.setPrefix(XmlConstants.SUBVERSION_DAV_PREFIX, XmlConstants.SUBVERSION_DAV_NAMESPACE);
        writer.writeNamespace(XmlConstants.SUBVERSION_DAV_PREFIX, XmlConstants.SUBVERSION_DAV_NAMESPACE);
        writer.setPrefix(XmlConstants.SUBVERSION_SVN_PREFIX, XmlConstants.SUBVERSION_SVN_NAMESPACE);
        writer.writeNamespace(XmlConstants.SUBVERSION_SVN_PREFIX, XmlConstants.SUBVERSION_SVN_NAMESPACE);
        writer.writeStartElement(type.action);
        writer.writeStartElement("prop");
        for (final ResourceProperty property : properties) {
            final String prefix = property.getType().getPrefix();
            if (type == Type.SET) {
                writer.writeStartElement(prefix, ResourcePropertyUtils.escapedKeyNameXml(property.getName()));
                writer.writeCharacters(property.getValue());
                writer.writeEndElement();
            } else {
                writer.writeEmptyElement(prefix, property.getName());
            }
        }
        writer.writeEndElement(); // prop
        writer.writeEndElement(); // set || delete
        writer.writeEndElement(); // propertyupdate
        writer.writeEndDocument();
        writer.close();
    } catch (final XMLStreamException e) {
        throw new SubversionException("could not create request body", e);
    }

    final String bodyWithMakers = body.toString();
    final String bodyWithoutMakers = ResourcePropertyUtils.filterMarker(bodyWithMakers);
    request.setEntity(new StringEntity(bodyWithoutMakers, CONTENT_TYPE_XML));
    return request;
}

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

private String makeXMLCombinedQuery(CombinedQueryDefinitionImpl qdef) {
    try {//from w  w  w  .  java2s  .  c  om
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        String qtext = qdef.qtext;
        StructuredQueryDefinition structuredQuery = qdef.structuredQuery;
        RawQueryDefinition rawQuery = qdef.rawQuery;
        QueryOptionsWriteHandle options = qdef.options;
        String sparql = qdef.sparql;
        if (rawQuery != null && rawQuery instanceof RawCombinedQueryDefinition) {
            CombinedQueryDefinitionImpl combinedQdef = parseCombinedQuery(
                    (RawCombinedQueryDefinition) rawQuery);
            rawQuery = combinedQdef.rawQuery;
            if (qtext == null)
                qtext = combinedQdef.qtext;
            if (options == null)
                options = combinedQdef.options;
            if (sparql == null)
                sparql = combinedQdef.sparql;
        }

        XMLStreamWriter serializer = makeXMLSerializer(out);

        serializer.writeStartDocument();
        serializer.writeStartElement("search");
        if (qtext != null) {
            serializer.writeStartElement("qtext");
            serializer.writeCharacters(qtext);
            serializer.writeEndElement();
        } else {
            serializer.writeCharacters("");
        }
        if (sparql != null) {
            serializer.writeStartElement("sparql");
            serializer.writeCharacters(sparql);
            serializer.writeEndElement();
        }
        serializer.flush();
        String structure = "";
        if (structuredQuery != null)
            structure = structuredQuery.serialize();
        if (rawQuery != null)
            structure = HandleAccessor.contentAsString(rawQuery.getHandle());
        out.write(structure.getBytes("UTF-8"));
        out.flush();
        if (options != null) {
            HandleImplementation handleBase = HandleAccessor.as(options);
            Object value = handleBase.sendContent();
            if (value instanceof OutputStreamSender) {
                ((OutputStreamSender) value).write(out);
            } else {
                out.write(HandleAccessor.contentAsString(options).getBytes("UTF-8"));
            }
            out.flush();
        }

        serializer.writeEndElement();
        serializer.writeEndDocument();
        serializer.flush();
        serializer.close();
        return out.toString("UTF-8");
    } catch (Exception e) {
        throw new MarkLogicIOException(e);
    }
}

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

@Override
protected HttpUriRequest createRequest() {
    final URI uri = URIUtils.createURI(repository, resource);
    final DavTemplateRequest request = new DavTemplateRequest("PROPFIND", uri);
    request.addHeader("Depth", depth.value);

    final Writer body = new StringBuilderWriter();
    try {/*from w  w w.j a v a2  s .c om*/
        final XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(body);
        writer.writeStartDocument(XmlConstants.ENCODING, XmlConstants.VERSION_1_0);
        writer.writeStartElement("propfind");
        writer.writeDefaultNamespace(XmlConstants.DAV_NAMESPACE);
        if (requestedProperties == null) {
            writer.writeEmptyElement("prop");
        } else {
            if (requestedProperties.length == 0) {
                writer.writeEmptyElement("allprop");
            } else {
                writer.writeStartElement("prop");
                if (contains(XmlConstants.SUBVERSION_DAV_NAMESPACE)) {
                    writer.writeNamespace(XmlConstants.SUBVERSION_DAV_PREFIX,
                            XmlConstants.SUBVERSION_DAV_NAMESPACE);
                    writer.setPrefix(XmlConstants.SUBVERSION_DAV_PREFIX, XmlConstants.SUBVERSION_DAV_NAMESPACE);
                }
                if (contains(XmlConstants.SUBVERSION_SVN_NAMESPACE)) {
                    writer.writeNamespace(XmlConstants.SUBVERSION_SVN_PREFIX,
                            XmlConstants.SUBVERSION_SVN_NAMESPACE);
                    writer.setPrefix(XmlConstants.SUBVERSION_SVN_PREFIX, XmlConstants.SUBVERSION_SVN_NAMESPACE);
                }
                for (final ResourceProperty.Key requestedProperty : requestedProperties) {
                    writer.writeEmptyElement(requestedProperty.getType().getPrefix(),
                            requestedProperty.getName());
                }
                writer.writeEndElement(); // prop
            }
        }
        writer.writeEndElement(); // propfind
        writer.writeEndDocument();
        writer.close();
    } catch (final XMLStreamException e) {
        throw new SubversionException("could not create request body", e);
    }

    request.setEntity(new StringEntity(body.toString(), CONTENT_TYPE_XML));
    return request;
}

From source file:com.flexive.shared.media.impl.FxMediaImageMagickEngine.java

/**
 * Parse an identify stdOut result (from in) and convert it to an XML content
 *
 * @param in identify response/*  w  ww.  ja  v  a  2  s . c om*/
 * @return XML content
 * @throws XMLStreamException on errors
 * @throws IOException        on errors
 */
public static String parse(InputStream in) throws XMLStreamException, IOException {
    StringWriter sw = new StringWriter(2000);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(sw);
    writer.writeStartDocument();

    int lastLevel = 0, level, lastNonValueLevel = 1;
    boolean valueEntry;
    String curr = null;
    String[] entry;
    try {
        while ((curr = br.readLine()) != null) {
            level = getLevel(curr);
            if (level == 0 && curr.startsWith("Image:")) {
                writer.writeStartElement("Image");
                entry = curr.split(": ");
                if (entry.length >= 2)
                    writer.writeAttribute("source", entry[1]);
                lastLevel = level;
                continue;
            }
            if (!(valueEntry = pNumeric.matcher(curr).matches())) {
                while (level < lastLevel--)
                    writer.writeEndElement();
                lastNonValueLevel = level;
            } else
                level = lastNonValueLevel + 1;
            if (curr.endsWith(":")) {
                writer.writeStartElement(
                        curr.substring(0, curr.lastIndexOf(':')).trim().replaceAll("[ :]", "-"));
                lastLevel = level + 1;
                continue;
            } else if (pColormap.matcher(curr).matches()) {
                writer.writeStartElement(
                        curr.substring(0, curr.lastIndexOf(':')).trim().replaceAll("[ :]", "-"));
                writer.writeAttribute("colors", curr.split(": ")[1].trim());
                lastLevel = level + 1;
                continue;
            }
            entry = curr.split(": ");
            if (entry.length == 2) {
                if (!valueEntry) {
                    writer.writeStartElement(entry[0].trim().replaceAll("[ :]", "-"));
                    writer.writeCharacters(entry[1]);
                    writer.writeEndElement();
                } else {
                    writer.writeEmptyElement("value");
                    writer.writeAttribute("key", entry[0].trim().replaceAll("[ :]", "-"));
                    writer.writeAttribute("data", entry[1]);
                    //                        writer.writeEndElement();
                }
            } else {
                //                    System.out.println("unknown line: "+curr);
            }
            lastLevel = level;
        }
    } catch (Exception e) {
        LOG.error("Error at [" + curr + "]:" + e.getMessage(), e);
    }
    writer.writeEndDocument();
    writer.flush();
    writer.close();
    return sw.getBuffer().toString();
}