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.flexive.core.IMParser.java

/**
 * Parse an identify stdOut result (from in) and convert it to an XML content
 *
 * @param in identify response/*from   w  w w  . j  a  va 2  s  . 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) {
            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: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>/*  w  ww  . java  2s.c om*/
 * 
 * @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:Main.java

/**
 * Borrowed from org.apache.xml.security.test.stax.utils.XmlReaderToWriter
 *//*from w  ww .  jav  a 2  s  .  c o m*/
public static void write(XMLStreamReader xmlr, XMLStreamWriter writer) throws XMLStreamException {
    switch (xmlr.getEventType()) {
    case XMLEvent.START_ELEMENT:
        final String localName = xmlr.getLocalName();
        final String namespaceURI = xmlr.getNamespaceURI();
        if (namespaceURI != null && namespaceURI.length() > 0) {
            final String prefix = xmlr.getPrefix();
            if (prefix != null) {
                writer.writeStartElement(prefix, localName, namespaceURI);
            } else {
                writer.writeStartElement(namespaceURI, localName);
            }
        } else {
            writer.writeStartElement(localName);
        }

        for (int i = 0, len = xmlr.getNamespaceCount(); i < len; i++) {
            String prefix = xmlr.getNamespacePrefix(i);
            if (prefix == null) {
                writer.writeDefaultNamespace(xmlr.getNamespaceURI(i));
            } else {
                writer.writeNamespace(prefix, xmlr.getNamespaceURI(i));
            }
        }

        for (int i = 0, len = xmlr.getAttributeCount(); i < len; i++) {
            final String attUri = xmlr.getAttributeNamespace(i);

            if (attUri != null && attUri.length() > 0) {
                final String prefix = xmlr.getAttributePrefix(i);
                if (prefix != null) {
                    writer.writeAttribute(prefix, attUri, xmlr.getAttributeLocalName(i),
                            xmlr.getAttributeValue(i));
                } else {
                    writer.writeAttribute(attUri, xmlr.getAttributeLocalName(i), xmlr.getAttributeValue(i));
                }
            } else {
                writer.writeAttribute(xmlr.getAttributeLocalName(i), xmlr.getAttributeValue(i));
            }

        }
        break;
    case XMLEvent.END_ELEMENT:
        writer.writeEndElement();
        break;
    case XMLEvent.SPACE:
    case XMLEvent.CHARACTERS:
        char[] text = new char[xmlr.getTextLength()];
        xmlr.getTextCharacters(0, text, 0, xmlr.getTextLength());
        writer.writeCharacters(text, 0, text.length);
        break;
    case XMLEvent.PROCESSING_INSTRUCTION:
        writer.writeProcessingInstruction(xmlr.getPITarget(), xmlr.getPIData());
        break;
    case XMLEvent.CDATA:
        writer.writeCData(xmlr.getText());
        break;
    case XMLEvent.COMMENT:
        writer.writeComment(xmlr.getText());
        break;
    case XMLEvent.ENTITY_REFERENCE:
        writer.writeEntityRef(xmlr.getLocalName());
        break;
    case XMLEvent.START_DOCUMENT:
        String encoding = xmlr.getCharacterEncodingScheme();
        String version = xmlr.getVersion();

        if (encoding != null && version != null) {
            writer.writeStartDocument(encoding, version);
        } else if (version != null) {
            writer.writeStartDocument(xmlr.getVersion());
        }
        break;
    case XMLEvent.END_DOCUMENT:
        writer.writeEndDocument();
        break;
    case XMLEvent.DTD:
        writer.writeDTD(xmlr.getText());
        break;
    }
}

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

@Override
protected HttpUriRequest createRequest() {
    final DavTemplateRequest request = new DavTemplateRequest("MERGE", repository);
    request.addHeader("X-SVN-Options", "release-locks");

    final Writer body = new StringBuilderWriter();
    try {//w w  w. ja va 2  s .c om
        final XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(body);
        writer.writeStartDocument(XmlConstants.ENCODING, XmlConstants.VERSION_1_0);
        writer.writeStartElement("merge");
        writer.writeDefaultNamespace(XmlConstants.DAV_NAMESPACE);
        writer.writeStartElement("source");
        writer.writeStartElement("href");
        writer.writeCData(repository.getPath() + resource.getValue());
        writer.writeEndElement(); // href
        writer.writeEndElement(); // source
        writer.writeEmptyElement("no-auto-merge");
        writer.writeEmptyElement("no-checkout");
        writer.writeStartElement("prop");
        writer.writeEmptyElement("checked-in");
        writer.writeEmptyElement("version-name");
        writer.writeEmptyElement("resourcetype");
        writer.writeEmptyElement("creationdate");
        writer.writeEmptyElement("creator-displayname");
        writer.writeEndElement(); // prop
        if (!infoSet.isEmpty()) {
            writer.setPrefix(XmlConstants.SVN_PREFIX, XmlConstants.SVN_NAMESPACE);
            writer.writeStartElement(XmlConstants.SVN_NAMESPACE, "lock-token-list");
            writer.writeNamespace(XmlConstants.SVN_PREFIX, XmlConstants.SVN_NAMESPACE);
            for (final Info info : infoSet) {
                final String lockToken = info.getLockToken();
                assert (lockToken != null) : "must not be null";
                final Resource infoResource = info.getResource();

                writer.writeStartElement(XmlConstants.SVN_NAMESPACE, "lock");
                writer.writeStartElement(XmlConstants.SVN_NAMESPACE, "lock-path");
                writer.writeCData(infoResource.getValueWithoutLeadingSeparator());
                writer.writeEndElement(); // lock-path
                writer.writeStartElement(XmlConstants.SVN_NAMESPACE, "lock-token");
                writer.writeCharacters(lockToken);
                writer.writeEndElement(); // lock-token
                writer.writeEndElement(); // lock
            }
            writer.writeEndElement(); // lock-token-list
        }
        writer.writeEndElement(); // merge
        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.ibm.bi.dml.runtime.controlprogram.parfor.opt.PerfTestTool.java

/**
 * StAX for efficient streaming XML writing.
 * /*from   ww  w .  j a  v a  2s.  com*/
 * @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:de.codesourcery.eve.skills.dao.impl.FileShoppingListDAO.java

protected void writeToFile() {

    XMLStreamWriter writer = null;
    try {/*from w  ww .  jav  a  2  s . c  o  m*/

        if (!dataFile.exists()) {
            final File parent = dataFile.getParentFile();
            if (parent != null && !parent.exists()) {
                if (!parent.mkdirs()) {
                    log.error("writeToFile(): Failed to create parent directory " + parent.getAbsolutePath());
                } else {
                    log.info("writeToFile(): Created parent directory " + parent.getAbsolutePath());
                }
            }
        }

        final XMLOutputFactory factory = XMLOutputFactory.newInstance();

        log.info("writeToFile(): Writing to " + dataFile.getAbsolutePath());
        final FileOutputStream outStream = new FileOutputStream(dataFile);
        writer = factory.createXMLStreamWriter(outStream, OUTPUT_ENCODING);

        writer.writeStartDocument(OUTPUT_ENCODING, "1.0");
        writer.writeStartElement("shoppinglists"); // <shoppinglists>
        synchronized (this.entries) {
            for (ShoppingList list : this.entries) {
                writer.writeStartElement("shoppinglist");
                writer.writeAttribute("title", list.getTitle());
                if (!StringUtils.isBlank(list.getDescription())) {
                    writer.writeStartElement("description");
                    writer.writeCharacters(list.getDescription());
                    writer.writeEndElement(); // </description>
                }

                writer.writeStartElement("entries");
                for (ShoppingListEntry entry : list.getEntries()) {
                    writer.writeStartElement("entry");
                    writer.writeAttribute("itemId", Long.toString(entry.getType().getId()));
                    writer.writeAttribute("totalQuantity", Long.toString(entry.getQuantity()));
                    writer.writeAttribute("purchasedQuantity", Long.toString(entry.getPurchasedQuantity()));

                    writer.writeEndElement(); // </entry>
                }
                writer.writeEndElement(); // </entries>
                writer.writeEndElement(); // </shoppinglist>
            }
        }
        writer.writeEndElement(); // </shoppinglists>
        writer.writeEndDocument();

        writer.flush();
        writer.close();
    } catch (FileNotFoundException e) {
        log.error("writeToFile(): Caught ", e);
        throw new RuntimeException("Unable to save shopping list to " + dataFile, e);
    } catch (XMLStreamException e) {
        log.error("writeToFile(): Caught ", e);
        throw new RuntimeException("Unable to save shopping list to " + dataFile, e);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (XMLStreamException e) {
                log.error("writeToFile(): Caught ", e);
            }
        }
    }
}

From source file:org.sfs.nodes.compute.container.GetContainer.java

@Override
public void handle(final SfsRequest httpServerRequest) {

    VertxContext<Server> vertxContext = httpServerRequest.vertxContext();
    aVoid().flatMap(new Authenticate(httpServerRequest))
            .flatMap(new ValidateActionAuthenticated(httpServerRequest))
            .map(aVoid -> fromSfsRequest(httpServerRequest)).map(new ValidateContainerPath())
            .flatMap(new LoadAccountAndContainer(vertxContext))
            .flatMap(new ValidateActionContainerListObjects(httpServerRequest)).flatMap(persistentContainer -> {

                HttpServerResponse httpServerResponse = httpServerRequest.response();

                MultiMap queryParams = httpServerRequest.params();
                MultiMap headerParams = httpServerRequest.headers();

                String format = queryParams.get(FORMAT);
                String accept = headerParams.get(ACCEPT);

                MediaType parsedAccept = null;

                if (equalsIgnoreCase("xml", format)) {
                    parsedAccept = APPLICATION_XML_UTF_8;
                } else if (equalsIgnoreCase("json", format)) {
                    parsedAccept = JSON_UTF_8;
                }// www .  j ava  2 s.  c  om

                if (parsedAccept == null) {
                    if (!isNullOrEmpty(accept)) {
                        parsedAccept = parse(accept);
                    }
                }

                if (parsedAccept == null || (!PLAIN_TEXT_UTF_8.is(parsedAccept)
                        && !APPLICATION_XML_UTF_8.is(parsedAccept) && !JSON_UTF_8.equals(parsedAccept))) {
                    parsedAccept = PLAIN_TEXT_UTF_8;
                }

                Observable<Optional<ContainerStats>> oContainerStats;
                boolean hasPrefix = !Strings.isNullOrEmpty(queryParams.get(SfsHttpQueryParams.PREFIX));
                if (hasPrefix) {
                    oContainerStats = just(persistentContainer)
                            .flatMap(new LoadContainerStats(httpServerRequest.vertxContext()))
                            .map(Optional::of);
                } else {
                    oContainerStats = Defer.just(Optional.<ContainerStats>absent());
                }

                Observable<ObjectList> oObjectListing = just(persistentContainer)
                        .flatMap(new ListObjects(httpServerRequest));

                MediaType finalParsedAccept = parsedAccept;
                return combineSinglesDelayError(oContainerStats, oObjectListing,
                        (containerStats, objectList) -> {

                            if (containerStats.isPresent()) {

                                Metadata metadata = persistentContainer.getMetadata();

                                for (String key : metadata.keySet()) {
                                    SortedSet<String> values = metadata.get(key);
                                    if (values != null && !values.isEmpty()) {
                                        httpServerResponse.putHeader(
                                                format("%s%s", X_ADD_CONTAINER_META_PREFIX, key), values);
                                    }
                                }

                                httpServerResponse.putHeader(X_CONTAINER_OBJECT_COUNT,
                                        valueOf(containerStats.get().getObjectCount()));
                                httpServerResponse.putHeader(X_CONTAINER_BYTES_USED,
                                        BigDecimal.valueOf(containerStats.get().getBytesUsed())
                                                .setScale(0, ROUND_HALF_UP).toString());
                            }

                            BufferOutputStream bufferOutputStream = new BufferOutputStream();

                            if (JSON_UTF_8.is(finalParsedAccept)) {

                                try {
                                    JsonFactory jsonFactory = vertxContext.verticle().jsonFactory();
                                    JsonGenerator jg = jsonFactory.createGenerator(bufferOutputStream, UTF8);
                                    jg.writeStartArray();

                                    for (ListedObject listedObject : ordered(objectList.getObjects())) {

                                        jg.writeStartObject();
                                        jg.writeStringField("hash",
                                                base16().lowerCase().encode(listedObject.getEtag()));
                                        jg.writeStringField("last_modified",
                                                toDateTimeString(listedObject.getLastModified()));
                                        jg.writeNumberField("bytes", listedObject.getLength());
                                        jg.writeStringField("content_type", listedObject.getContentType());
                                        jg.writeStringField("name", listedObject.getName());
                                        jg.writeEndObject();
                                    }

                                    jg.writeEndArray();
                                    jg.close();
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }

                            } else if (APPLICATION_XML_UTF_8.is(finalParsedAccept)) {

                                String charset = UTF_8.toString();
                                XMLStreamWriter writer = null;
                                try {
                                    writer = newFactory().createXMLStreamWriter(bufferOutputStream, charset);

                                    writer.writeStartDocument(charset, "1.0");

                                    writer.writeStartElement("container");

                                    writer.writeAttribute("name",
                                            fromPaths(persistentContainer.getId()).containerName().get());

                                    for (ListedObject listedObject : ordered(objectList.getObjects())) {

                                        writer.writeStartElement("object");

                                        writer.writeStartElement("name");
                                        writer.writeCharacters(listedObject.getName());
                                        writer.writeEndElement();

                                        writer.writeStartElement("hash");
                                        writer.writeCharacters(
                                                base16().lowerCase().encode(listedObject.getEtag()));
                                        writer.writeEndElement();

                                        writer.writeStartElement("bytes");
                                        writer.writeCharacters(valueOf(listedObject.getLength()));
                                        writer.writeEndElement();

                                        writer.writeStartElement("content_type");
                                        writer.writeCharacters(listedObject.getContentType());
                                        writer.writeEndElement();

                                        writer.writeStartElement("last_modified");
                                        writer.writeCharacters(
                                                toDateTimeString(listedObject.getLastModified()));
                                        writer.writeEndElement();

                                        writer.writeEndElement();
                                    }

                                    writer.writeEndElement();

                                    writer.writeEndDocument();

                                } catch (XMLStreamException e) {
                                    throw new RuntimeException(e);
                                } finally {
                                    try {
                                        if (writer != null) {
                                            writer.close();
                                        }
                                    } catch (XMLStreamException e) {
                                        LOGGER.warn(e.getLocalizedMessage(), e);
                                    }
                                }

                            } else {
                                String charset = UTF_8.toString();
                                try (OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                                        bufferOutputStream, charset)) {
                                    for (ListedObject listedObject : ordered(objectList.getObjects())) {
                                        outputStreamWriter.write(listedObject.getName());
                                        outputStreamWriter.write("\n");
                                    }
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                            objectList.clear();
                            return bufferOutputStream;
                        }).flatMap(bufferOutputStream -> {
                            Buffer buffer = bufferOutputStream.toBuffer();
                            httpServerResponse.putHeader(HttpHeaders.CONTENT_TYPE, finalParsedAccept.toString())
                                    .putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(buffer.length()));
                            return AsyncIO.append(buffer, httpServerRequest.response());
                        });
            }).single().subscribe(new ConnectionCloseTerminus<Void>(httpServerRequest) {
                @Override
                public void onNext(Void aVoid) {

                }
            }

    );

}

From source file:edu.jhu.pha.vospace.node.Node.java

public String getXmlMetadata(Detail detail) {

    StringWriter jobWriter = new StringWriter();
    try {/*www . j  a  va 2 s  .c  o m*/
        XMLStreamWriter xsw = XMLOutputFactory.newInstance().createXMLStreamWriter(jobWriter);
        xsw.writeStartDocument();

        xsw.setDefaultNamespace(VOS_NAMESPACE);

        xsw.writeStartElement("node");
        xsw.writeNamespace("xsi", XSI_NAMESPACE);
        xsw.writeNamespace(null, VOS_NAMESPACE);
        xsw.writeAttribute("xsi:type", this.getType().getTypeName());
        xsw.writeAttribute("uri", this.getUri().toString());

        if (detail == Detail.max) {
            xsw.writeStartElement("properties");
            Map<String, String> properties = this.getMetastore().getProperties(this.getUri());
            properties.put(LENGTH_PROPERTY, Long.toString(getNodeInfo().getSize()));
            properties.put(DATE_PROPERTY, dropboxDateFormat.format(getNodeInfo().getMtime()));
            if (this.getType() == NodeType.DATA_NODE || this.getType() == NodeType.STRUCTURED_DATA_NODE
                    || this.getType() == NodeType.UNSTRUCTURED_DATA_NODE) {
                properties.put(CONTENTTYPE_PROPERTY, getNodeInfo().getContentType());
            }

            for (String propUri : properties.keySet()) {
                xsw.writeStartElement("property");
                xsw.writeAttribute("uri", propUri);
                xsw.writeCharacters(properties.get(propUri));
                xsw.writeEndElement();
            }

            xsw.writeEndElement();

            xsw.writeStartElement("accepts");
            xsw.writeEndElement();

            xsw.writeStartElement("provides");
            xsw.writeEndElement();

            xsw.writeStartElement("capabilities");
            xsw.writeEndElement();

            if (this.getType() == NodeType.CONTAINER_NODE) {
                NodesList childrenList = ((ContainerNode) this).getDirectChildren(false, 0, -1);
                List<Node> children = childrenList.getNodesList();

                xsw.writeStartElement("nodes");
                for (Node childNode : children) {
                    xsw.writeStartElement("node");
                    xsw.writeAttribute("uri", childNode.getUri().getId().toString());
                    xsw.writeEndElement();
                }
                xsw.writeEndElement();

            }

        }

        xsw.writeEndElement();

        xsw.writeEndDocument();
        xsw.close();
    } catch (XMLStreamException e) {
        e.printStackTrace();
        throw new InternalServerErrorException(e);
    }
    return jobWriter.getBuffer().toString();
}

From source file:jp.zippyzip.impl.GeneratorServiceImpl.java

public void storeX0401Zip() {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    ZipOutputStream out = new ZipOutputStream(baos);
    Collection<Pref> prefs = getPrefs();
    ZipEntry tsv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0401_utf8.txt");
    ZipEntry csv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0401_sjis.csv");
    ZipEntry json = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0401_utf8.json");
    ZipEntry xml = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0401_utf8.xml");

    tsv.setTime(timestamp);// w  ww  . j a  v  a 2 s  .co  m
    csv.setTime(timestamp);
    json.setTime(timestamp);
    xml.setTime(timestamp);

    try {

        out.putNextEntry(tsv);

        for (Pref pref : prefs) {

            out.write(new String(pref.getCode() + "\t" + pref.getName() + "\t" + pref.getYomi() + CRLF)
                    .getBytes("UTF-8"));
        }

        out.closeEntry();
        out.putNextEntry(csv);

        for (Pref pref : prefs) {

            out.write(new String(pref.getCode() + "," + pref.getName() + "," + pref.getYomi() + CRLF)
                    .getBytes("MS932"));
        }

        out.closeEntry();
        out.putNextEntry(json);

        OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
        JSONWriter jwriter = new JSONWriter(writer);

        jwriter.array();

        for (Pref pref : prefs) {

            jwriter.object().key("code").value(pref.getCode()).key("name").value(pref.getName()).key("yomi")
                    .value(pref.getYomi()).endObject();
        }

        jwriter.endArray();
        writer.flush();
        out.closeEntry();
        out.putNextEntry(xml);

        XMLStreamWriter xwriter = XMLOutputFactory.newInstance()
                .createXMLStreamWriter(new OutputStreamWriter(out, "UTF-8"));

        xwriter.writeStartDocument("UTF-8", "1.0");
        xwriter.writeStartElement("x0401s");

        for (Pref pref : prefs) {

            xwriter.writeStartElement("x0401");
            xwriter.writeAttribute("code", pref.getCode());
            xwriter.writeAttribute("name", pref.getName());
            xwriter.writeAttribute("yomi", pref.getYomi());
            xwriter.writeEndElement();
        }

        xwriter.writeEndElement();
        xwriter.writeEndDocument();
        xwriter.flush();
        out.closeEntry();
        out.finish();
        baos.flush();
        getRawDao().store(baos.toByteArray(), "x0401.zip");
        log.info("prefs: " + prefs.size());

    } catch (JSONException e) {
        log.log(Level.WARNING, "", e);
    } catch (XMLStreamException e) {
        log.log(Level.WARNING, "", e);
    } catch (FactoryConfigurationError e) {
        log.log(Level.WARNING, "", e);
    } catch (IOException e) {
        log.log(Level.WARNING, "", e);
    }
}

From source file:com.liferay.portal.util.LocalizationImpl.java

public String removeLocalization(String xml, String key, String requestedLanguageId, boolean cdata,
        boolean localized) {

    if (Validator.isNull(xml)) {
        return StringPool.BLANK;
    }//from w  w w .  ja  v  a  2s .  co m

    xml = _sanitizeXML(xml);

    String systemDefaultLanguageId = LocaleUtil.toLanguageId(LocaleUtil.getDefault());

    XMLStreamReader xmlStreamReader = null;
    XMLStreamWriter xmlStreamWriter = null;

    ClassLoader portalClassLoader = PortalClassLoaderUtil.getClassLoader();

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    try {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(portalClassLoader);
        }

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();

        xmlStreamReader = xmlInputFactory.createXMLStreamReader(new UnsyncStringReader(xml));

        String availableLocales = StringPool.BLANK;
        String defaultLanguageId = StringPool.BLANK;

        // Read root node

        if (xmlStreamReader.hasNext()) {
            xmlStreamReader.nextTag();

            availableLocales = xmlStreamReader.getAttributeValue(null, _AVAILABLE_LOCALES);
            defaultLanguageId = xmlStreamReader.getAttributeValue(null, _DEFAULT_LOCALE);

            if (Validator.isNull(defaultLanguageId)) {
                defaultLanguageId = systemDefaultLanguageId;
            }
        }

        if ((availableLocales != null) && (availableLocales.indexOf(requestedLanguageId) != -1)) {

            availableLocales = StringUtil.remove(availableLocales, requestedLanguageId, StringPool.COMMA);

            UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter();

            XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();

            xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(unsyncStringWriter);

            xmlStreamWriter.writeStartDocument();
            xmlStreamWriter.writeStartElement(_ROOT);

            if (localized) {
                xmlStreamWriter.writeAttribute(_AVAILABLE_LOCALES, availableLocales);
                xmlStreamWriter.writeAttribute(_DEFAULT_LOCALE, defaultLanguageId);
            }

            _copyNonExempt(xmlStreamReader, xmlStreamWriter, requestedLanguageId, defaultLanguageId, cdata);

            xmlStreamWriter.writeEndElement();
            xmlStreamWriter.writeEndDocument();

            xmlStreamWriter.close();
            xmlStreamWriter = null;

            xml = unsyncStringWriter.toString();
        }
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn(e, e);
        }
    } finally {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(contextClassLoader);
        }

        if (xmlStreamReader != null) {
            try {
                xmlStreamReader.close();
            } catch (Exception e) {
            }
        }

        if (xmlStreamWriter != null) {
            try {
                xmlStreamWriter.close();
            } catch (Exception e) {
            }
        }
    }

    return xml;
}