Example usage for javax.xml.stream XMLStreamWriter writeStartElement

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

Introduction

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

Prototype

public void writeStartElement(String localName) throws XMLStreamException;

Source Link

Document

Writes a start tag to the output.

Usage

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

private void encodeUndeclaredExtensions(IBaseResource theResource, XMLStreamWriter theEventWriter,
        List<? extends IBaseExtension<?, ?>> theExtensions, String tagName, boolean theIncludedResource)
        throws XMLStreamException, DataFormatException {
    for (IBaseExtension<?, ?> next : theExtensions) {
        if (next == null || (ElementUtil.isEmpty(next.getValue()) && next.getExtension().isEmpty())) {
            continue;
        }//from   w w  w.ja v  a2 s .co  m

        writeCommentsPre(theEventWriter, next);

        theEventWriter.writeStartElement(tagName);

        String elementId = getCompositeElementId(next);
        if (isNotBlank(elementId)) {
            theEventWriter.writeAttribute("id", elementId);
        }

        String url = next.getUrl();
        theEventWriter.writeAttribute("url", url);

        if (next.getValue() != null) {
            IBaseDatatype value = next.getValue();
            RuntimeChildUndeclaredExtensionDefinition extDef = myContext
                    .getRuntimeChildUndeclaredExtensionDefinition();
            String childName = extDef.getChildNameByDatatype(value.getClass());
            BaseRuntimeElementDefinition<?> childDef;
            if (childName == null) {
                childDef = myContext.getElementDefinition(value.getClass());
                if (childDef == null) {
                    throw new ConfigurationException(
                            "Unable to encode extension, unrecognized child element type: "
                                    + value.getClass().getCanonicalName());
                } else {
                    childName = RuntimeChildUndeclaredExtensionDefinition.createExtensionChildName(childDef);
                }
            } else {
                childDef = extDef.getChildElementDefinitionByDatatype(value.getClass());
                if (childDef == null) {
                    throw new ConfigurationException(
                            "Unable to encode extension, unrecognized child element type: "
                                    + value.getClass().getCanonicalName());
                }
            }
            encodeChildElementToStreamWriter(theResource, theEventWriter, value, childName, childDef, null,
                    theIncludedResource, null);
        }

        // child extensions
        encodeExtensionsIfPresent(theResource, theEventWriter, next, theIncludedResource);

        theEventWriter.writeEndElement();

        writeCommentsPost(theEventWriter, next);

    }
}

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

private void encodeResourceToXmlStreamWriter(IBaseResource theResource, XMLStreamWriter theEventWriter,
        boolean theContainedResource, IIdType theResourceId) throws XMLStreamException {
    if (!theContainedResource) {
        super.containResourcesForEncoding(theResource);
    }/* w w  w  .j  a  va 2  s  .  c  o  m*/

    RuntimeResourceDefinition resDef = myContext.getResourceDefinition(theResource);
    if (resDef == null) {
        throw new ConfigurationException("Unknown resource type: " + theResource.getClass());
    }

    theEventWriter.writeStartElement(resDef.getName());
    theEventWriter.writeDefaultNamespace(FHIR_NS);

    if (theResource instanceof IAnyResource) {

        // HL7.org Structures
        if (theResourceId != null) {
            writeCommentsPre(theEventWriter, theResourceId);
            writeOptionalTagWithValue(theEventWriter, "id", theResourceId.getIdPart());
            writeCommentsPost(theEventWriter, theResourceId);
        }

        encodeCompositeElementToStreamWriter(theResource, theResource, theEventWriter, theContainedResource,
                new CompositeChildElement(resDef));

    } else {

        if (myContext.getVersion().getVersion().isNewerThan(FhirVersionEnum.DSTU1)) {

            // DSTU2+

            IResource resource = (IResource) theResource;
            if (theResourceId != null) {
                writeCommentsPre(theEventWriter, theResourceId);
                writeOptionalTagWithValue(theEventWriter, "id", theResourceId.getIdPart());
                writeCommentsPost(theEventWriter, theResourceId);
            }

            InstantDt updated = (InstantDt) resource.getResourceMetadata().get(ResourceMetadataKeyEnum.UPDATED);
            IdDt resourceId = resource.getId();
            String versionIdPart = resourceId.getVersionIdPart();
            if (isBlank(versionIdPart)) {
                versionIdPart = ResourceMetadataKeyEnum.VERSION.get(resource);
            }
            List<BaseCodingDt> securityLabels = extractMetadataListNotNull(resource,
                    ResourceMetadataKeyEnum.SECURITY_LABELS);
            List<? extends IIdType> profiles = extractMetadataListNotNull(resource,
                    ResourceMetadataKeyEnum.PROFILES);
            profiles = super.getProfileTagsForEncoding(resource, profiles);

            TagList tags = getMetaTagsForEncoding((resource));

            if (super.shouldEncodeResourceMeta(resource)
                    && ElementUtil.isEmpty(versionIdPart, updated, securityLabels, tags, profiles) == false) {
                theEventWriter.writeStartElement("meta");
                writeOptionalTagWithValue(theEventWriter, "versionId", versionIdPart);
                if (updated != null) {
                    writeOptionalTagWithValue(theEventWriter, "lastUpdated", updated.getValueAsString());
                }

                for (IIdType profile : profiles) {
                    theEventWriter.writeStartElement("profile");
                    theEventWriter.writeAttribute("value", profile.getValue());
                    theEventWriter.writeEndElement();
                }
                for (BaseCodingDt securityLabel : securityLabels) {
                    theEventWriter.writeStartElement("security");
                    encodeCompositeElementToStreamWriter(resource, securityLabel, theEventWriter,
                            theContainedResource, null);
                    theEventWriter.writeEndElement();
                }
                if (tags != null) {
                    for (Tag tag : tags) {
                        if (tag.isEmpty()) {
                            continue;
                        }
                        theEventWriter.writeStartElement("tag");
                        writeOptionalTagWithValue(theEventWriter, "system", tag.getScheme());
                        writeOptionalTagWithValue(theEventWriter, "code", tag.getTerm());
                        writeOptionalTagWithValue(theEventWriter, "display", tag.getLabel());
                        theEventWriter.writeEndElement();
                    }
                }
                theEventWriter.writeEndElement();
            }

            if (theResource instanceof IBaseBinary) {
                IBaseBinary bin = (IBaseBinary) theResource;
                writeOptionalTagWithValue(theEventWriter, "contentType", bin.getContentType());
                writeOptionalTagWithValue(theEventWriter, "content", bin.getContentAsBase64());
            } else {
                encodeCompositeElementToStreamWriter(theResource, theResource, theEventWriter,
                        theContainedResource, new CompositeChildElement(resDef));
            }

        } else {

            // DSTU1
            if (theResourceId != null && theContainedResource && theResourceId.hasIdPart()) {
                theEventWriter.writeAttribute("id", theResourceId.getIdPart());
            }

            if (theResource instanceof IBaseBinary) {
                IBaseBinary bin = (IBaseBinary) theResource;
                if (bin.getContentType() != null) {
                    theEventWriter.writeAttribute("contentType", bin.getContentType());
                }
                theEventWriter.writeCharacters(bin.getContentAsBase64());
            } else {
                encodeCompositeElementToStreamWriter(theResource, theResource, theEventWriter,
                        theContainedResource, new CompositeChildElement(resDef));
            }

        }

    }

    theEventWriter.writeEndElement();
}

From source file:de.uni_koblenz.jgralab.utilities.rsa2tg.SchemaGraph2XMI.java

/**
 * Creates the default values./*  ww  w . jav  a  2s . co  m*/
 * 
 * @param writer
 *            {@link XMLStreamWriter} of the current XMI file
 * @param defaultValue
 *            {@link String} the default value of the current
 *            {@link Attribute}
 * @param id
 *            {@link String} the id of the current {@link Attribute}
 * @param domain
 *            {@link Domain} the type of the current {@link Attribute}
 * @throws XMLStreamException
 */
private void createDefaultValue(XMLStreamWriter writer, String defaultValue, String id, Domain domain)
        throws XMLStreamException {
    // start defaultValue
    if (domain instanceof LongDomain || domain instanceof EnumDomain) {
        writer.writeEmptyElement(XMIConstants4SchemaGraph2XMI.TAG_DEFAULTVALUE);
    } else {
        writer.writeStartElement(XMIConstants4SchemaGraph2XMI.TAG_DEFAULTVALUE);
    }
    if (domain instanceof BooleanDomain) {
        writer.writeAttribute(XMIConstants4SchemaGraph2XMI.NAMESPACE_XMI,
                XMIConstants4SchemaGraph2XMI.XMI_ATTRIBUTE_TYPE,
                XMIConstants4SchemaGraph2XMI.TYPE_VALUE_LITERALBOOLEAN);
    } else if (domain instanceof IntegerDomain || domain instanceof LongDomain) {
        writer.writeAttribute(XMIConstants4SchemaGraph2XMI.NAMESPACE_XMI,
                XMIConstants4SchemaGraph2XMI.XMI_ATTRIBUTE_TYPE,
                XMIConstants4SchemaGraph2XMI.TYPE_VALUE_LITERALINTEGER);
    } else if (domain instanceof EnumDomain) {
        writer.writeAttribute(XMIConstants4SchemaGraph2XMI.NAMESPACE_XMI,
                XMIConstants4SchemaGraph2XMI.XMI_ATTRIBUTE_TYPE,
                XMIConstants4SchemaGraph2XMI.TYPE_VALUE_INSTANCEVALUE);
    } else {
        writer.writeAttribute(XMIConstants4SchemaGraph2XMI.NAMESPACE_XMI,
                XMIConstants4SchemaGraph2XMI.XMI_ATTRIBUTE_TYPE,
                XMIConstants4SchemaGraph2XMI.TYPE_VALUE_OPAQUEEXPRESSION);
    }
    writer.writeAttribute(XMIConstants4SchemaGraph2XMI.NAMESPACE_XMI,
            XMIConstants4SchemaGraph2XMI.XMI_ATTRIBUTE_ID, id + "_defaultValue");
    if (domain instanceof BooleanDomain || domain instanceof IntegerDomain || domain instanceof LongDomain
            || domain instanceof EnumDomain) {
        if (domain instanceof BooleanDomain) {
            writer.writeAttribute(XMIConstants4SchemaGraph2XMI.ATTRIBUTE_VALUE,
                    defaultValue.equals("t") ? "true" : "false");
        } else if (domain instanceof EnumDomain) {
            writer.writeAttribute(XMIConstants4SchemaGraph2XMI.ATTRIBUTE_NAME, defaultValue);
            writer.writeAttribute(XMIConstants4SchemaGraph2XMI.XMI_ATTRIBUTE_TYPE, domain.get_qualifiedName());
            writer.writeAttribute(XMIConstants4SchemaGraph2XMI.DEFAULTVALUE_ATTRIBUTE_INSTANCE,
                    domain.get_qualifiedName() + "_" + defaultValue);
        } else {
            writer.writeAttribute(XMIConstants4SchemaGraph2XMI.ATTRIBUTE_VALUE, defaultValue);
        }

        // create type
        if (domain instanceof BooleanDomain || domain instanceof IntegerDomain) {
            createType(writer, domain);
        }
    } else {
        if (domain instanceof StringDomain) {
            // create type
            createType(writer, domain);
        } else {
            // there has to be created an entry for the current domain in
            // the package primitiveTypes
            writer.writeAttribute(XMIConstants4SchemaGraph2XMI.XMI_ATTRIBUTE_TYPE,
                    domain.get_qualifiedName().replaceAll("\\s", "").replaceAll("<", "_").replaceAll(">", "_"));
        }

        // start body
        writer.writeStartElement(XMIConstants4SchemaGraph2XMI.TAG_BODY);
        writer.writeCharacters(defaultValue);
        // end body
        writer.writeEndElement();
    }

    if (!(domain instanceof LongDomain || domain instanceof EnumDomain)) {
        // end defaultValue
        writer.writeEndElement();
    }
}

From source file:de.uni_koblenz.jgralab.utilities.rsa2tg.SchemaGraph2XMI.java

/**
 * Creates the representation of the {@link IncidenceClass} which contains
 * the information for the {@link VertexClass} which is specified by
 * <code>qualifiedNameOfVertexClass</code> e.g. <code>otherIncidence</code>.<br/>
 * The relevant information are: <ui> <li>the rolename,</li> <li>the min
 * value,</li> <li>the max value and</li> <li>composition or shared
 * information.</li> </ui> The default rolename for associations is
 * <code>qualifiedNameOfVertexClass_edgeClass.getQualifiedName()</code> and
 * <code>""</code> for associationClasses.
 * /*from   www  .j  a  v  a 2  s.  c om*/
 * @param writer
 *            {@link XMLStreamWriter} of the current XMI file
 * @param otherIncidence
 *            {@link IncidenceClass} which contains the information for the
 *            incidence corresponding to the {@link VertexClass} of
 *            <code>qualifiedNameOfVertexClass</code> in the xmi file.
 * @param connectedVertexClass
 *            {@link VertexClass} at the other end of <code>edgeClass</code>
 * @param incidence
 *            {@link IncidenceClass} connected to the {@link VertexClass}
 *            specified by <code>qualifiedNameOfVertexClass</code>
 * @param edgeClass
 *            {@link EdgeClass} which connects the {@link VertexClass}
 *            specified by <code>qualifiedNameOfVertexClass</code> with
 *            <code>connectedVertexClass</code>
 * @param qualifiedNameOfVertexClass
 *            {@link String} the qualified name of the {@link VertexClass}
 *            to which <code>incidence</code> is connected to.
 * @param createOwnedEnd
 *            boolean if set to <code>true</code>, the tag ownedEnd is used
 *            instead of ownedAttribute (ownedEnd has to be created, if you
 *            create an incidence at an association.)
 * @throws XMLStreamException
 */
private void createIncidence(XMLStreamWriter writer, IncidenceClass otherIncidence, EdgeClass edgeClass,
        IncidenceClass incidence, VertexClass connectedVertexClass, String qualifiedNameOfVertexClass,
        boolean createOwnedEnd) throws XMLStreamException {

    String incidenceId = qualifiedNameOfVertexClass + "_incidence_" + edgeClass.get_qualifiedName()
            + (incidence.getFirstComesFromIncidence() != null ? "_from" : "_to");

    // start ownedattribute
    writer.writeStartElement(createOwnedEnd ? XMIConstants4SchemaGraph2XMI.TAG_OWNEDEND
            : XMIConstants4SchemaGraph2XMI.TAG_OWNEDATTRIBUTE);
    writer.writeAttribute(XMIConstants4SchemaGraph2XMI.NAMESPACE_XMI,
            XMIConstants4SchemaGraph2XMI.XMI_ATTRIBUTE_TYPE,
            XMIConstants4SchemaGraph2XMI.OWNEDATTRIBUTE_TYPE_VALUE);
    writer.writeAttribute(XMIConstants4SchemaGraph2XMI.NAMESPACE_XMI,
            XMIConstants4SchemaGraph2XMI.XMI_ATTRIBUTE_ID, incidenceId);
    // set rolenames
    if (otherIncidence.get_roleName() != null && !otherIncidence.get_roleName().isEmpty()) {
        writer.writeAttribute(XMIConstants4SchemaGraph2XMI.ATTRIBUTE_NAME, otherIncidence.get_roleName());
    } else if (isRoleNameNecessary(edgeClass, connectedVertexClass.get_qualifiedName())) {
        String newRoleName = createNewUniqueRoleName(connectedVertexClass);
        writer.writeAttribute(XMIConstants4SchemaGraph2XMI.ATTRIBUTE_NAME, newRoleName);
        // to find already used rolenames set the newly created rolename
        otherIncidence.set_roleName(newRoleName);
    }
    writer.writeAttribute(XMIConstants4SchemaGraph2XMI.OWNEDATTRIBUTE_ATTRIBUTE_VISIBILITY,
            XMIConstants4SchemaGraph2XMI.OWNEDATTRIBUTE_VISIBILITY_VALUE_PRIVATE);
    writer.writeAttribute(XMIConstants4SchemaGraph2XMI.PACKAGEDELEMENT_ATTRIBUTE_TYPE,
            connectedVertexClass.get_qualifiedName());
    // set composite or shared
    if (otherIncidence.get_aggregation() == AggregationKind.SHARED) {
        writer.writeAttribute(XMIConstants4SchemaGraph2XMI.OWNEDATTRIBUTE_ATTRIBUTE_AGGREGATION,
                XMIConstants4SchemaGraph2XMI.OWNEDATTRIBUTE_ATTRIBUTE_AGGREGATION_VALUE_SHARED);
    } else if (otherIncidence.get_aggregation() == AggregationKind.COMPOSITE) {
        writer.writeAttribute(XMIConstants4SchemaGraph2XMI.OWNEDATTRIBUTE_ATTRIBUTE_AGGREGATION,
                XMIConstants4SchemaGraph2XMI.OWNEDATTRIBUTE_ATTRIBUTE_AGGREGATION_VALUE_COMPOSITE);
    }
    writer.writeAttribute(XMIConstants4SchemaGraph2XMI.PACKAGEDELEMENT_ATTRIBUTE_ASSOCIATION,
            edgeClass.get_qualifiedName());

    // create upperValue
    writer.writeEmptyElement(XMIConstants4SchemaGraph2XMI.TAG_UPPERVALUE);
    writer.writeAttribute(XMIConstants4SchemaGraph2XMI.NAMESPACE_XMI,
            XMIConstants4SchemaGraph2XMI.XMI_ATTRIBUTE_TYPE,
            XMIConstants4SchemaGraph2XMI.TYPE_VALUE_LITERALUNLIMITEDNATURAL);
    writer.writeAttribute(XMIConstants4SchemaGraph2XMI.NAMESPACE_XMI,
            XMIConstants4SchemaGraph2XMI.XMI_ATTRIBUTE_ID, incidenceId + "_uppervalue");
    writer.writeAttribute(XMIConstants4SchemaGraph2XMI.ATTRIBUTE_VALUE,
            otherIncidence.get_max() == Integer.MAX_VALUE ? "*" : Integer.toString(otherIncidence.get_max()));

    // create lowerValue
    writer.writeEmptyElement(XMIConstants4SchemaGraph2XMI.TAG_LOWERVALUE);
    writer.writeAttribute(XMIConstants4SchemaGraph2XMI.NAMESPACE_XMI,
            XMIConstants4SchemaGraph2XMI.XMI_ATTRIBUTE_TYPE,
            XMIConstants4SchemaGraph2XMI.TYPE_VALUE_LITERALINTEGER);
    writer.writeAttribute(XMIConstants4SchemaGraph2XMI.NAMESPACE_XMI,
            XMIConstants4SchemaGraph2XMI.XMI_ATTRIBUTE_ID, incidenceId + "_lowervalue");
    writer.writeAttribute(XMIConstants4SchemaGraph2XMI.ATTRIBUTE_VALUE,
            incidence.get_min() == Integer.MAX_VALUE ? "*" : Integer.toString(otherIncidence.get_min()));

    // close ownedattribute
    writer.writeEndElement();
}

From source file:de.uni_koblenz.jgralab.utilities.rsa2tg.SchemaGraph2XMI.java

/**
 * Creates the representation of an {@link Attribute}. The represented
 * information are the name, the default value and the type. <br/>
 * If the {@link Attribute} is of type LongDomain, a DoubleDomain, a
 * CollectionDomain or a MapDomain the type is stored in
 * {@link SchemaGraph2XMI#typesToBeDeclaredAtTheEnd} because there has to be
 * created a representation in the primitive types package.
 * // w w w .j  a  v  a 2 s  .com
 * @param writer
 *            {@link XMLStreamWriter} of the current XMI file
 * @param attributeName
 *            {@link String} the name of the current {@link Attribute}
 * @param defaultValue
 *            {@link String} the default value of the current
 *            {@link Attribute}
 * @param domain
 *            {@link Domain} of the current {@link Attribute}
 * @param id
 *            {@link String} the id of the tag which represents the current
 *            {@link Attribute}
 * @throws XMLStreamException
 */
private void createAttribute(XMLStreamWriter writer, String attributeName, String defaultValue, Domain domain,
        String id) throws XMLStreamException {

    boolean hasDefaultValue = defaultValue != null && !defaultValue.isEmpty();

    // start ownedAttribute
    if (!hasDefaultValue && !(domain instanceof BooleanDomain || domain instanceof IntegerDomain
            || domain instanceof StringDomain)) {
        writer.writeEmptyElement(XMIConstants4SchemaGraph2XMI.TAG_OWNEDATTRIBUTE);
    } else {
        writer.writeStartElement(XMIConstants4SchemaGraph2XMI.TAG_OWNEDATTRIBUTE);
    }
    writer.writeAttribute(XMIConstants4SchemaGraph2XMI.NAMESPACE_XMI,
            XMIConstants4SchemaGraph2XMI.XMI_ATTRIBUTE_TYPE,
            XMIConstants4SchemaGraph2XMI.OWNEDATTRIBUTE_TYPE_VALUE);
    writer.writeAttribute(XMIConstants4SchemaGraph2XMI.NAMESPACE_XMI,
            XMIConstants4SchemaGraph2XMI.XMI_ATTRIBUTE_ID, id);
    writer.writeAttribute(XMIConstants4SchemaGraph2XMI.ATTRIBUTE_NAME, attributeName);
    writer.writeAttribute(XMIConstants4SchemaGraph2XMI.OWNEDATTRIBUTE_ATTRIBUTE_VISIBILITY,
            XMIConstants4SchemaGraph2XMI.OWNEDATTRIBUTE_VISIBILITY_VALUE_PRIVATE);

    // create type
    if (domain instanceof BooleanDomain || domain instanceof IntegerDomain || domain instanceof StringDomain) {
        createType(writer, domain);
    } else {
        writer.writeAttribute(XMIConstants4SchemaGraph2XMI.XMI_ATTRIBUTE_TYPE,
                domain.get_qualifiedName().replaceAll("\\s", "").replaceAll("<", "_").replaceAll(">", "_"));
    }

    // create default value
    if (hasDefaultValue) {
        createDefaultValue(writer, defaultValue, id, domain);
    }

    if (hasDefaultValue || domain instanceof BooleanDomain || domain instanceof IntegerDomain
            || domain instanceof StringDomain) {
        // end ownedAttribute
        writer.writeEndElement();
    }

    // if domain is a LongDomain, a DoubleDomain, a CollectionDomain or a
    // MapDomain there has to be created an entry in the package
    // PrimitiveTypes
    if (domain instanceof LongDomain || domain instanceof DoubleDomain || domain instanceof CollectionDomain
            || domain instanceof MapDomain) {
        typesToBeDeclaredAtTheEnd.add(domain);
    }
}

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 {//www .  jav a 2  s .  co 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);//  www . j a v a2  s. c  om
    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.smartbear.jenkins.plugins.testcomplete.TcLogParser.java

private void convertToXML(ZipFile logArchive, TcLogInfo logInfo, XMLStreamWriter writer)
        throws ParsingException, XMLStreamException {
    writer.writeStartDocument("utf-8", "1.0");

    Node descriptionTopLevelNode = NodeUtils.getRootDocumentNodeFromArchive(logArchive, DESCRIPTION_ENTRY_NAME);
    if (descriptionTopLevelNode == null) {
        throw new ParsingException("Unable to obtain description top-level node.");
    }//  w w w . j a va 2  s. co m

    Node topLevelNode = NodeUtils.getRootDocumentNodeFromArchive(logArchive,
            NodeUtils.getTextProperty(descriptionTopLevelNode, "root file name"));

    if (topLevelNode == null) {
        throw new ParsingException("Unable to obtain root top-level node.");
    }

    NodeList rootNodes = topLevelNode.getChildNodes();
    Node rootOwnerNode = NodeUtils.findRootOwnerNode(rootNodes);

    if (rootOwnerNode == null) {
        throw new ParsingException("Unable to obtain root owner node.");
    }

    boolean isSuite = "{00000000-0000-0000-0000-000000000000}"
            .equals(NodeUtils.getTextProperty(rootOwnerNode, "projectkey"));

    Node rootOwnerNodeInfo = NodeUtils.getRootDocumentNodeFromArchive(logArchive,
            NodeUtils.getTextProperty(rootOwnerNode, "filename"));

    if (rootOwnerNodeInfo == null) {
        throw new ParsingException("Unable to obtain root owner node info.");
    }

    Node rootOwnerNodeInfoSummary = NodeUtils.findNamedNode(rootOwnerNodeInfo.getChildNodes(), "summary");
    boolean isSuiteOrProject = rootOwnerNodeInfoSummary != null;

    writer.writeStartElement("testsuites");

    if (isSuite) {
        List<Node> projects = NodeUtils.findChildNodes(rootOwnerNode,
                rootOwnerNode.getParentNode().getChildNodes());
        for (Node projectNode : projects) {
            Node projectNodeInfo = NodeUtils.getRootDocumentNodeFromArchive(logArchive,
                    NodeUtils.getTextProperty(projectNode, "filename"));
            Node projectNodeInfoSummary = NodeUtils.findNamedNode(projectNodeInfo, "summary");
            processProject(logArchive, projectNode, projectNodeInfoSummary, writer);
        }
    } else if (isSuiteOrProject) {
        processProject(logArchive, rootOwnerNode, rootOwnerNodeInfoSummary, writer);
    } else {
        String testCaseName = NodeUtils.getTextProperty(rootOwnerNode, "name");
        String testCaseDuration = Double.toString(logInfo.getTestDuration() / 1000f);

        writer.writeStartElement("testsuite");
        writer.writeAttribute("name", project);
        writer.writeAttribute("time", testCaseDuration);

        writer.writeStartElement("testcase");
        writer.writeAttribute("name", fixTestCaseName(testCaseName));
        writer.writeAttribute("classname", suite + "." + project);
        writer.writeAttribute("time", testCaseDuration);
        if (checkFail(NodeUtils.getTextProperty(rootOwnerNode, "status"))) {
            writer.writeStartElement("failure");

            List<String> messages = NodeUtils.getErrorMessages(rootOwnerNodeInfo);
            if (errorOnWarnings) {
                messages.addAll(NodeUtils.getWarningMessages(rootOwnerNodeInfo));
            }

            writer.writeAttribute("message", StringUtils.join(messages, "\n\n"));
            writer.writeEndElement(); //failure
        }
        writer.writeEndElement(); //testcase

        writer.writeEndElement(); //testsuite
    }

    writer.writeEndElement(); //testsuites
    writer.writeEndDocument();
}

From source file:de.uni_koblenz.jgralab.utilities.rsa2tg.SchemaGraph2XMI.java

/**
 * This method creates the representation of:
 * <ul>//w w  w  . ja  va 2 s.  c o m
 * <li>the {@link Package} <code>pack</code>, if it is not the
 * defaultPackage,</li>
 * <li>{@link Comment}s which are attached to <code>pack</code>,</li>
 * <li>{@link EnumDomain}s,</li>
 * <li>{@link RecordDomain}s,</li>
 * <li>{@link GraphElementClass}es and</li>
 * <li>{@link Package}s</li>
 * </ul>
 * contained in <code>pack</code>. The creation of other {@link Domain}s
 * except {@link EnumDomain}s and {@link RecordDomain}s are explained at
 * {@link SchemaGraph2XMI#createAttribute(XMLStreamWriter, String, String, Domain, String)}
 * .
 * 
 * @param writer
 *            {@link XMLStreamWriter} of the current XMI file
 * @param pack
 *            {@link Package} the current {@link Package}
 * @throws XMLStreamException
 */
private void createPackage(XMLStreamWriter writer, Package pack) throws XMLStreamException {
    boolean packageTagHasToBeClosed = false;

    if (!isPackageEmpty(pack)) {

        if (!pack.get_qualifiedName().equals(de.uni_koblenz.jgralab.schema.Package.DEFAULTPACKAGE_NAME)) {
            // for the default package there is not created a package tag
            packageTagHasToBeClosed = pack.getFirstAnnotatesIncidence() != null
                    || pack.getFirstContainsDomainIncidence() != null
                    || pack.getFirstContainsGraphElementClassIncidence() != null
                    || pack.getFirstContainsSubPackageIncidence(EdgeDirection.OUT) != null;
            if (packageTagHasToBeClosed) {
                // start package
                writer.writeStartElement(XMIConstants4SchemaGraph2XMI.TAG_PACKAGEDELEMENT);
            } else {
                // create empty package
                writer.writeEmptyElement(XMIConstants4SchemaGraph2XMI.TAG_PACKAGEDELEMENT);
            }
            writer.writeAttribute(XMIConstants4SchemaGraph2XMI.NAMESPACE_XMI,
                    XMIConstants4SchemaGraph2XMI.XMI_ATTRIBUTE_TYPE,
                    XMIConstants4SchemaGraph2XMI.PACKAGEDELEMENT_TYPE_VALUE_PACKAGE);
            writer.writeAttribute(XMIConstants4SchemaGraph2XMI.NAMESPACE_XMI,
                    XMIConstants4SchemaGraph2XMI.XMI_ATTRIBUTE_ID, pack.get_qualifiedName());
            writer.writeAttribute(XMIConstants4SchemaGraph2XMI.ATTRIBUTE_NAME,
                    extractSimpleName(pack.get_qualifiedName()));
        }

        // create comments
        createComments(writer, pack);

        // create domains
        for (ContainsDomain cd : pack.getContainsDomainIncidences()) {
            Domain domain = (Domain) cd.getThat();
            if (!domain.get_qualifiedName()
                    .equals(de.uni_koblenz.jgralab.schema.BooleanDomain.BOOLEANDOMAIN_NAME)
                    && !domain.get_qualifiedName()
                            .equals(de.uni_koblenz.jgralab.schema.DoubleDomain.DOUBLEDOMAIN_NAME)
                    && !domain.get_qualifiedName()
                            .equals(de.uni_koblenz.jgralab.schema.IntegerDomain.INTDOMAIN_NAME)
                    && !domain.get_qualifiedName()
                            .equals(de.uni_koblenz.jgralab.schema.LongDomain.LONGDOMAIN_NAME)
                    && !domain.get_qualifiedName()
                            .equals(de.uni_koblenz.jgralab.schema.StringDomain.STRINGDOMAIN_NAME)) {
                // skip basic domains
                if (domain instanceof EnumDomain) {
                    createEnum(writer, (EnumDomain) domain);
                } else if (domain instanceof RecordDomain) {
                    createRecordDomain(writer, (RecordDomain) domain);
                }
            }
        }

        // create GraphElementClasses
        for (ContainsGraphElementClass cgec : pack.getContainsGraphElementClassIncidences()) {
            GraphElementClass gec = (GraphElementClass) cgec.getThat();
            createAttributedElementClass(writer, gec);
        }

        // create subpackages
        for (ContainsSubPackage csp : pack.getContainsSubPackageIncidences(EdgeDirection.OUT)) {
            // create subpackages
            createPackage(writer, (Package) csp.getThat());
        }

        if (packageTagHasToBeClosed) {
            // close packagedElement
            writer.writeEndElement();
        }
    }
}

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);/*from  w w  w.  ja  v a 2s.  co  m*/

    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;
}