Example usage for javax.xml.stream XMLStreamWriter writeAttribute

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

Introduction

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

Prototype

public void writeAttribute(String localName, String value) throws XMLStreamException;

Source Link

Document

Writes an attribute to the output stream without a prefix.

Usage

From source file:ca.uhn.fhir.parser.XmlParser.java

private void encodeChildElementToStreamWriter(IBaseResource theResource, XMLStreamWriter theEventWriter,
        IBase theElement, String childName, BaseRuntimeElementDefinition<?> childDef, String theExtensionUrl,
        boolean theIncludedResource, CompositeChildElement theParent)
        throws XMLStreamException, DataFormatException {
    if (theElement == null || theElement.isEmpty()) {
        if (isChildContained(childDef, theIncludedResource)) {
            // We still want to go in..
        } else {/*from  ww w.  j a  v  a2s.c o  m*/
            return;
        }
    }

    writeCommentsPre(theEventWriter, theElement);

    switch (childDef.getChildType()) {
    case ID_DATATYPE: {
        IIdType value = (IIdType) theElement;
        String encodedValue = "id".equals(childName) ? value.getIdPart() : value.getValue();
        if (value != null) {
            theEventWriter.writeStartElement(childName);
            theEventWriter.writeAttribute("value", encodedValue);
            encodeExtensionsIfPresent(theResource, theEventWriter, theElement, theIncludedResource);
            theEventWriter.writeEndElement();
        }
        break;
    }
    case PRIMITIVE_DATATYPE: {
        IPrimitiveType<?> pd = (IPrimitiveType<?>) theElement;
        String value = pd.getValueAsString();
        if (value != null || super.hasExtensions(pd)) {
            theEventWriter.writeStartElement(childName);
            String elementId = getCompositeElementId(theElement);
            if (isNotBlank(elementId)) {
                theEventWriter.writeAttribute("id", elementId);
            }
            if (value != null) {
                theEventWriter.writeAttribute("value", value);
            }
            encodeExtensionsIfPresent(theResource, theEventWriter, theElement, theIncludedResource);
            theEventWriter.writeEndElement();
        }
        break;
    }
    case RESOURCE_BLOCK:
    case COMPOSITE_DATATYPE: {
        theEventWriter.writeStartElement(childName);
        String elementId = getCompositeElementId(theElement);
        if (isNotBlank(elementId)) {
            theEventWriter.writeAttribute("id", elementId);
        }
        if (isNotBlank(theExtensionUrl)) {
            theEventWriter.writeAttribute("url", theExtensionUrl);
        }
        encodeCompositeElementToStreamWriter(theResource, theElement, theEventWriter, theIncludedResource,
                theParent);
        theEventWriter.writeEndElement();
        break;
    }
    case CONTAINED_RESOURCE_LIST:
    case CONTAINED_RESOURCES: {
        /*
         * Disable per #103 for (IResource next : value.getContainedResources()) { if (getContainedResources().getResourceId(next) != null) { continue; }
         * theEventWriter.writeStartElement("contained"); encodeResourceToXmlStreamWriter(next, theEventWriter, true, fixContainedResourceId(next.getId().getValue()));
         * theEventWriter.writeEndElement(); }
         */
        for (IBaseResource next : getContainedResources().getContainedResources()) {
            IIdType resourceId = getContainedResources().getResourceId(next);
            theEventWriter.writeStartElement("contained");
            encodeResourceToXmlStreamWriter(next, theEventWriter, true,
                    fixContainedResourceId(resourceId.getValue()));
            theEventWriter.writeEndElement();
        }
        break;
    }
    case RESOURCE: {
        theEventWriter.writeStartElement(childName);
        IBaseResource resource = (IBaseResource) theElement;
        encodeResourceToXmlStreamWriter(resource, theEventWriter, false, true);
        theEventWriter.writeEndElement();
        break;
    }
    case PRIMITIVE_XHTML: {
        XhtmlDt dt = (XhtmlDt) theElement;
        if (dt.hasContent()) {
            encodeXhtml(dt, theEventWriter);
        }
        break;
    }
    case PRIMITIVE_XHTML_HL7ORG: {
        IBaseXhtml dt = (IBaseXhtml) theElement;
        if (dt.isEmpty()) {
            break;
        } else {
            // TODO: this is probably not as efficient as it could be
            XhtmlDt hdt = new XhtmlDt();
            hdt.setValueAsString(dt.getValueAsString());
            encodeXhtml(hdt, theEventWriter);
            break;
        }
    }
    case EXTENSION_DECLARED:
    case UNDECL_EXT: {
        throw new IllegalStateException("state should not happen: " + childDef.getName());
    }
    }

    writeCommentsPost(theEventWriter, theElement);

}

From source file:com.smartbear.jenkins.plugins.testcomplete.TcLogParser.java

private void processProject(ZipFile logArchive, Node rootOwnerNode, Node rootOwnerNodeInfoSummary,
        XMLStreamWriter writer) throws ParsingException, XMLStreamException {

    String totalTests = NodeUtils.getTextProperty(
            NodeUtils.findNamedNode(rootOwnerNodeInfoSummary.getChildNodes(), "total"), "total (sum)");
    String failedTests = NodeUtils.getTextProperty(
            NodeUtils.findNamedNode(rootOwnerNodeInfoSummary.getChildNodes(), "failed"), "total (sum)");
    long startDate = Utils.safeConvertDate(NodeUtils.getTextProperty(rootOwnerNodeInfoSummary, "start date"));
    long stopDate = Utils.safeConvertDate(NodeUtils.getTextProperty(rootOwnerNodeInfoSummary, "stop date"));
    long projectDuration = stopDate - startDate > 0 ? stopDate - startDate : 0;
    String projectName = NodeUtils.getTextProperty(rootOwnerNodeInfoSummary, "test");
    Calendar cal = new GregorianCalendar();
    cal.setTimeInMillis(startDate);/*from  w  w  w  . ja v a2 s .  c  o m*/
    String timestamp = DatatypeConverter.printDateTime(cal);

    String rootOwnerNodeFileName = NodeUtils.getTextProperty(rootOwnerNode, "filename");
    if (rootOwnerNodeFileName == null || rootOwnerNodeFileName.isEmpty()) {
        throw new ParsingException("Unable to obtain filename for project node.");
    }

    List<Pair<String, Node>> items = null;

    try {
        items = NodeUtils.findChildNodesRecursively(logArchive, rootOwnerNode,
                rootOwnerNode.getParentNode().getChildNodes(), "");
    } catch (Exception e) {
        items = new ArrayList<Pair<String, Node>>();
    }

    writer.writeStartElement("testsuite");
    writer.writeAttribute("name", projectName);
    writer.writeAttribute("failures", failedTests);
    writer.writeAttribute("tests", totalTests);
    writer.writeAttribute("time", Double.toString(projectDuration / 1000f));
    writer.writeAttribute("timestamp", timestamp);

    for (Pair<String, Node> pair : items) {
        processItem(logArchive, pair.getValue(), projectName, writer, pair.getKey());
    }

    writer.writeEndElement(); //testcase
}

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

public String updateLocalization(String xml, String key, String value, String requestedLanguageId,
        String defaultLanguageId, boolean cdata, boolean localized) {

    xml = _sanitizeXML(xml);/*  w w w  .  j a v  a 2s.  com*/

    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;

        // Read root node

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

            availableLocales = xmlStreamReader.getAttributeValue(null, _AVAILABLE_LOCALES);

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

            if (availableLocales.indexOf(requestedLanguageId) == -1) {
                availableLocales = StringUtil.add(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.writeStartElement(key);

        if (localized) {
            xmlStreamWriter.writeAttribute(_LANGUAGE_ID, requestedLanguageId);
        }

        if (cdata) {
            xmlStreamWriter.writeCData(value);
        } else {
            xmlStreamWriter.writeCharacters(value);
        }

        xmlStreamWriter.writeEndElement();
        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;
}

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

/**
 * XML ??//from  w ww  .j  a  v a 2 s .  co  m
 * 
 * @param name "area" / "corp"
 * @param suffix "" / "c"
 */
void storeXml(String name, String suffix) {

    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    Collection<City> cities = getCities();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    ZipEntry entry = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_" + name + "_utf8.xml");
    entry.setTime(timestamp);
    int cnt = 0;

    try {

        zos.putNextEntry(entry);

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

        xwriter.writeStartDocument("UTF-8", "1.0");
        xwriter.writeStartElement("zips");
        xwriter.writeAttribute("type", name);

        for (City city : cities) {

            ParentChild pc = getParentChildDao().get(city.getCode() + suffix);

            if (pc == null) {
                continue;
            }

            for (String json : pc.getChildren()) {

                Zip zip = Zip.fromJson(json);

                xwriter.writeStartElement("zip");
                xwriter.writeAttribute("zip", zip.getCode());
                xwriter.writeAttribute("x0402", zip.getX0402());
                xwriter.writeAttribute("add1", zip.getAdd1());
                xwriter.writeAttribute("add2", zip.getAdd2());
                xwriter.writeAttribute("corp", zip.getCorp());
                xwriter.writeAttribute("add1Yomi", zip.getAdd1Yomi());
                xwriter.writeAttribute("add2Yomi", zip.getAdd2Yomi());
                xwriter.writeAttribute("corpYomi", zip.getCorpYomi());
                xwriter.writeAttribute("note", zip.getNote());
                xwriter.writeEndElement();
                ++cnt;
            }
        }

        xwriter.writeEndElement();
        xwriter.writeEndDocument();
        xwriter.flush();
        zos.closeEntry();
        zos.finish();
        getRawDao().store(baos.toByteArray(), name + "_utf8_xml.zip");
        log.info("count: " + cnt);

    } 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;
    }/* w ww.  j  a  v  a 2  s.  c o  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;
}

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);//from   w  ww .j  ava 2s . 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:jp.zippyzip.impl.GeneratorServiceImpl.java

public void storeX0402Zip() {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    ZipOutputStream out = new ZipOutputStream(baos);
    Collection<City> cities = getCities();
    ZipEntry tsv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_utf8.txt");
    ZipEntry csv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_sjis.csv");
    ZipEntry json = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_utf8.json");
    ZipEntry xml = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_utf8.xml");

    tsv.setTime(timestamp);/* w  ww. j a  v a2  s  . c  o m*/
    csv.setTime(timestamp);
    json.setTime(timestamp);
    xml.setTime(timestamp);

    try {

        out.putNextEntry(tsv);

        for (City city : cities) {

            out.write(new String(city.getCode() + "\t" + city.getName() + "\t" + city.getYomi() + "\t"
                    + ((city.getExpiration().getTime() < new Date().getTime()) ? "" : "") + CRLF)
                            .getBytes("UTF-8"));
        }

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

        for (City city : cities) {

            out.write(new String(city.getCode() + "," + city.getName() + "," + city.getYomi() + ","
                    + ((city.getExpiration().getTime() < new Date().getTime()) ? "" : "") + CRLF)
                            .getBytes("MS932"));
        }

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

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

        jwriter.array();

        for (City city : cities) {

            jwriter.object().key("code").value(city.getCode()).key("name").value(city.getName()).key("yomi")
                    .value(city.getYomi()).key("expired")
                    .value((city.getExpiration().getTime() < new Date().getTime()) ? "true" : "false")
                    .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("x0402s");

        for (City city : cities) {

            xwriter.writeStartElement("x0402");
            xwriter.writeAttribute("code", city.getCode());
            xwriter.writeAttribute("name", city.getName());
            xwriter.writeAttribute("yomi", city.getYomi());
            xwriter.writeAttribute("expired",
                    (city.getExpiration().getTime() < new Date().getTime()) ? "true" : "false");
            xwriter.writeEndElement();
        }

        xwriter.writeEndElement();
        xwriter.writeEndDocument();
        xwriter.flush();
        out.closeEntry();
        out.finish();
        baos.flush();
        getRawDao().store(baos.toByteArray(), "x0402.zip");
        log.info("cities: " + cities.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:net.solarnetwork.util.JavaBeanXmlSerializer.java

private void writeElement(String name, Map<?, ?> props, XMLStreamWriter out, boolean close)
        throws XMLStreamException {
    out.writeStartElement(name);//w w w .jav  a2s.  c o m
    Map<String, Object> nested = null;
    if (props != null) {
        for (Map.Entry<?, ?> me : props.entrySet()) {
            String key = me.getKey().toString();
            Object val = me.getValue();
            if (propertySerializerRegistrar != null) {
                val = propertySerializerRegistrar.serializeProperty(name, val.getClass(), props, val);
            }
            if (val instanceof Date) {
                SimpleDateFormat sdf = SDF.get();
                // SimpleDateFormat has no way to create xs:dateTime with tz,
                // so use trick here to insert required colon for non GMT dates
                Date date = (Date) val;
                StringBuilder buf = new StringBuilder(sdf.format(date));
                if (buf.charAt(buf.length() - 1) != 'Z') {
                    buf.insert(buf.length() - 2, ':');
                }
                val = buf.toString();
            } else if (val instanceof Collection) {
                if (nested == null) {
                    nested = new LinkedHashMap<String, Object>(5);
                }
                nested.put(key, val);
                val = null;
            } else if (val instanceof Map<?, ?>) {
                if (nested == null) {
                    nested = new LinkedHashMap<String, Object>(5);
                }
                nested.put(key, val);
                val = null;
            } else if (classNamesAllowedForNesting != null && !(val instanceof Enum<?>)) {
                for (String prefix : classNamesAllowedForNesting) {
                    if (val.getClass().getName().startsWith(prefix)) {
                        if (nested == null) {
                            nested = new LinkedHashMap<String, Object>(5);
                        }
                        nested.put(key, val);
                        val = null;
                        break;
                    }
                }
            }

            if (val != null) {
                String attVal = val.toString();
                out.writeAttribute(key, attVal);
            }
        }
    }
    if (nested != null) {
        for (Map.Entry<String, Object> me : nested.entrySet()) {
            outputObject(me.getValue(), me.getKey(), out);
        }
        if (close) {
            out.writeEndElement();
        }
    }
}

From source file:com.fiorano.openesb.application.aps.ServiceInstance.java

public void toJXMLString(XMLStreamWriter writer) throws XMLStreamException, FioranoException {

    //Start ServiceInstance
    writer.writeStartElement("ServiceInstance");

    //Write Attributes
    writer.writeAttribute("isManualLaunch", "" + m_isManualLaunch);
    writer.writeAttribute("isStateful", "" + m_isStateful);
    writer.writeAttribute("isDelayedLaunch", "" + m_isDelayedLaunch);
    writer.writeAttribute("delayedPort", "" + m_delayedPortName);
    writer.writeAttribute("maxRetries", "" + m_maxRetries);
    writer.writeAttribute("isTransacted", "" + m_isTransacted);
    writer.writeAttribute("isErrorHandlingEnabled", "" + m_isErrorHandlingEnabled);
    writer.writeAttribute("isInMemoryLaunch", "" + m_isInMemoryLaunch);
    writer.writeAttribute("isEndOfWorkflow", "" + m_isEndOfWorkflow);
    writer.writeAttribute("preferLaunchOnHigherLevelNode", "" + m_bPreferLaunchOnHigherLevelNode);
    writer.writeAttribute("killPrimaryOnSecondaryLaunch", "" + m_bKillPrimaryOnSecondaryLaunch);
    writer.writeAttribute("isDebugMode", "" + m_bIsDebugMode);
    writer.writeAttribute("debugPort", "" + m_iDebugPort);
    writer.writeAttribute("isTransportLPC", "" + m_isTransportLPC);
    writer.writeAttribute("profile", "" + m_profile);

    FioranoStackSerializer.writeElement("ServiceInstanceName", m_servInstName, writer);
    FioranoStackSerializer.writeElement("ServiceGUID", m_servGUID, writer);
    FioranoStackSerializer.writeElement("BufferSizePerPort", m_dBufferSizePerPort + "", writer);

    if (m_version != null) {
        writer.writeStartElement("Version");
        writer.writeAttribute("isLocked", "" + m_isVersionLocked);
        writer.writeCharacters(m_version);
        writer.writeEndElement();//from w ww . j a  v  a  2 s.  c o  m
    }
    if (m_nodes != null && m_nodes.size() > 0) {
        Enumeration nodeNameEnum = m_nodes.keys();
        Enumeration nodeLevelEnum = m_nodes.elements();

        while (nodeNameEnum.hasMoreElements()) {
            String nodeName = (String) nodeNameEnum.nextElement();
            String nodeLevel = (String) nodeLevelEnum.nextElement();
            writer.writeStartElement("Node");
            writer.writeAttribute("level", nodeLevel);
            writer.writeCharacters(nodeName);
            writer.writeEndElement();
        }
    }
    if (m_eventHandler > 0) {
        writer.writeStartElement("EventHandler");
        writer.writeAttribute("deliveryMode", "" + m_eventDeliveryMode);
        writer.writeAttribute("expiryTime", "" + m_eventExpiryTime);
        writer.writeCharacters("" + m_eventHandler);
        writer.writeEndElement();
    }
    if (m_runtimeDependencies != null && m_runtimeDependencies.size() > 0) {
        Enumeration enums = m_runtimeDependencies.elements();

        while (enums.hasMoreElements()) {
            RuntimeDependency runtimeDependency = (RuntimeDependency) enums.nextElement();
            runtimeDependency.toJXMLString(writer);
        }
    }
    if (m_runtimeArgs != null) {
        m_runtimeArgs.toJXMLString(writer);
    }
    if (m_portInstDescriptor != null) {
        m_portInstDescriptor.toJXMLString(writer);
    }

    if (!StringUtils.isEmpty(m_longDescription)) {
        FioranoStackSerializer.writeElement("LongDescription", m_longDescription, writer);

    }
    if (!StringUtils.isEmpty(m_shortDescription)) {
        FioranoStackSerializer.writeElement("ShortDescription", m_shortDescription, writer);

    }
    //LogManager
    if (m_logManager != null) {
        //Start LogMangaer
        writer.writeStartElement("LogManager");

        FioranoStackSerializer.writeElement("Name", m_logManager, writer);

        if (m_logParams != null && m_logParams.size() > 0) {
            Enumeration enums = m_logParams.elements();
            while (enums.hasMoreElements()) {
                Param param = (Param) enums.nextElement();
                if (!StringUtils.isEmpty(param.getParamName()) && !StringUtils.isEmpty(param.getParamValue())) {
                    param.toJXMLString(writer);
                }
            }
        }
        //End LogManager
        writer.writeEndElement();
    }
    if (m_params != null && m_params.size() > 0) {
        Enumeration enums = m_params.elements();

        while (enums.hasMoreElements()) {
            Param param = (Param) enums.nextElement();
            if (!StringUtils.isEmpty(param.getParamName()) && !StringUtils.isEmpty(param.getParamValue()))
                param.toJXMLString(writer);
        }
    }
    if (m_statusTracking != null) {
        m_statusTracking.toJXMLString(writer);
    }
    if (m_vecEndStates != null) {
        for (int i = 0; i < m_vecEndStates.size(); i++) {
            EndState endState = (EndState) m_vecEndStates.get(i);
            endState.toJXMLString(writer);

        }
    }
    if (m_monitor != null) {
        m_monitor.toJXMLString(writer);
    }
    if (m_logModules != null) {
        m_logModules.toJXMLString(writer);

    }

    //End ServiceInstance
    writer.writeEndElement();

}

From source file:org.gaul.s3proxy.S3ProxyHandler.java

private void handleGetContainerAcl(HttpServletResponse response, BlobStore blobStore, String containerName)
        throws IOException {
    ContainerAccess access = blobStore.getContainerAccess(containerName);

    try (Writer writer = response.getWriter()) {
        XMLStreamWriter xml = xmlOutputFactory.createXMLStreamWriter(writer);
        xml.writeStartDocument();//from   w ww. java  2  s  .c  om
        xml.writeStartElement("AccessControlPolicy");
        xml.writeDefaultNamespace(AWS_XMLNS);

        writeOwnerStanza(xml);

        xml.writeStartElement("AccessControlList");

        xml.writeStartElement("Grant");

        xml.writeStartElement("Grantee");
        xml.writeNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        xml.writeAttribute("xsi:type", "CanonicalUser");

        writeSimpleElement(xml, "ID", FAKE_OWNER_ID);
        writeSimpleElement(xml, "DisplayName", FAKE_OWNER_DISPLAY_NAME);

        xml.writeEndElement();

        writeSimpleElement(xml, "Permission", "FULL_CONTROL");

        xml.writeEndElement();

        if (access == ContainerAccess.PUBLIC_READ) {
            xml.writeStartElement("Grant");

            xml.writeStartElement("Grantee");
            xml.writeNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
            xml.writeAttribute("xsi:type", "Group");

            writeSimpleElement(xml, "URI", "http://acs.amazonaws.com/groups/global/AllUsers");

            xml.writeEndElement();

            writeSimpleElement(xml, "Permission", "READ");

            xml.writeEndElement();
        }

        xml.writeEndElement();

        xml.writeEndElement();
        xml.flush();
    } catch (XMLStreamException xse) {
        throw new IOException(xse);
    }
}