Example usage for javax.xml.stream XMLStreamWriter close

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

Introduction

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

Prototype

public void close() throws XMLStreamException;

Source Link

Document

Close this writer and free any resources associated with the writer.

Usage

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//  ww  w.j  a  va 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: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.  j  ava 2  s  .  c  om
 * @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.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  a 2  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.marklogic.client.impl.CombinedQueryBuilderImpl.java

private String makeXMLCombinedQuery(CombinedQueryDefinitionImpl qdef) {
    try {/*from  w  ww  .j av a2 s . co  m*/
        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.codesourcery.eve.skills.util.XMLMapper.java

public void write(Collection<?> beans, IFieldConverters converters, OutputStream outstream)
        throws XMLStreamException, IntrospectionException, IllegalArgumentException, IllegalAccessException {

    final XMLOutputFactory factory = XMLOutputFactory.newInstance();
    final XMLStreamWriter writer = factory.createXMLStreamWriter(outstream, OUTPUT_ENCODING);
    try {/* w  ww. ja  v a  2s .  c  o  m*/
        writer.writeStartDocument(OUTPUT_ENCODING, "1.0");
        writer.writeStartElement("rows");

        if (beans.isEmpty()) {
            writer.writeEndDocument();
            return;
        }

        final Class<?> beanClass = beans.iterator().next().getClass();

        final BeanDescription desc = createBeanDescription(beanClass);

        final Collection<Field> fields = desc.getFields();
        if (fields.isEmpty()) {
            writer.writeEndDocument();
            return;
        }

        for (Object bean : beans) {
            writer.writeStartElement("row");
            for (Field f : fields) {
                final Object fieldValue = f.get(bean);
                final String[] values = converters.getConverter(f).toString(fieldValue);

                final String attrName = this.propertyNameMappings.get(f.getName());
                if (values == null) {
                    writer.writeAttribute(f.getName(), NIL);
                } else if (attrName == null) {
                    writer.writeAttribute(f.getName(), toAttributeValue(values));
                } else {
                    writer.writeAttribute(attrName, toAttributeValue(values));
                }
            }
            writer.writeEndElement();
        }
        writer.writeEndDocument();
    } finally {
        writer.close();
    }
}

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

/**
 * Generate a simple jukebox index file from scratch
 *
 * @param jukebox/*w  w  w. jav a 2s .c  om*/
 * @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:ca.uhn.fhir.parser.XmlParser.java

@Override
public void encodeTagListToWriter(TagList theTagList, Writer theWriter) throws IOException {
    try {/* w w  w . j  a v a2  s  .  c o  m*/
        XMLStreamWriter eventWriter = createXmlWriter(theWriter);

        eventWriter.writeStartElement(TagList.ELEMENT_NAME_LC);
        eventWriter.writeDefaultNamespace(FHIR_NS);

        for (Tag next : theTagList) {
            eventWriter.writeStartElement(TagList.ATTR_CATEGORY);

            if (isNotBlank(next.getTerm())) {
                eventWriter.writeAttribute(Tag.ATTR_TERM, next.getTerm());
            }
            if (isNotBlank(next.getLabel())) {
                eventWriter.writeAttribute(Tag.ATTR_LABEL, next.getLabel());
            }
            if (isNotBlank(next.getScheme())) {
                eventWriter.writeAttribute(Tag.ATTR_SCHEME, next.getScheme());
            }

            eventWriter.writeEndElement();
        }

        eventWriter.writeEndElement();
        eventWriter.close();
    } catch (XMLStreamException e) {
        throw new ConfigurationException("Failed to initialize STaX event factory", e);
    }
}

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/*from  ww  w  . ja va  2s.co m*/
 * @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();
}

From source file:com.flexive.core.IMParser.java

/**
 * Parse an identify stdOut result (from in) and convert it to an XML content
 *
 * @param in identify response/*from www.  ja  va  2  s. com*/
 * @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) {
            if (curr.indexOf(':') == -1 || curr.trim().length() == 0) {
                System.out.println("skipping: [" + curr + "]");
                continue; //ignore lines without ':'
            }
            level = getLevel(curr);
            curr = curr.trim();
            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(cleanElement(curr.substring(0, curr.lastIndexOf(':'))));
                lastLevel = level + 1;
                continue;
            } else if (pColormap.matcher(curr).matches()) {
                writer.writeStartElement(cleanElement(curr.substring(0, curr.lastIndexOf(':'))));
                writer.writeAttribute("colors", curr.split(": ")[1].trim());
                lastLevel = level + 1;
                continue;
            }
            entry = curr.split(": ");
            if (entry.length == 2) {
                if (!valueEntry) {
                    writer.writeStartElement(cleanElement(entry[0]));
                    writer.writeCharacters(entry[1]);
                    writer.writeEndElement();
                } else {
                    writer.writeEmptyElement("value");
                    writer.writeAttribute("key", cleanElement(entry[0]));
                    writer.writeAttribute("data", entry[1]);
                    //                        writer.writeEndElement();
                }
            } else {
                //                    System.out.println("unknown line: "+curr);
            }
            lastLevel = level;
        }
    } catch (Exception e) {
        System.err.println("Error at [" + curr + "]:" + e.getMessage());
        e.printStackTrace();
    }

    writer.writeEndDocument();
    writer.flush();
    writer.close();
    return sw.getBuffer().toString();
}

From source file:com.cloud.bridge.service.EC2RestServlet.java

/**
* Serialize Axis beans to XML output. //  w  ww.java2s . c o m
 */
private void serializeResponse(HttpServletResponse response, ADBBean EC2Response)
        throws ADBException, XMLStreamException, IOException {
    OutputStream os = response.getOutputStream();
    response.setStatus(200);
    response.setContentType("text/xml; charset=UTF-8");
    XMLStreamWriter xmlWriter = xmlOutFactory.createXMLStreamWriter(os);
    MTOMAwareXMLSerializer MTOMWriter = new MTOMAwareXMLSerializer(xmlWriter);
    MTOMWriter.setDefaultNamespace("http://ec2.amazonaws.com/doc/" + wsdlVersion + "/");
    EC2Response.serialize(null, factory, MTOMWriter);
    xmlWriter.flush();
    xmlWriter.close();
    os.close();
}