Java Code Examples for javax.xml.stream.XMLStreamWriter#writeAttribute()

The following examples show how to use javax.xml.stream.XMLStreamWriter#writeAttribute() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MetadataDocumentXmlSerializer.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private void appendOperationParameters(final XMLStreamWriter writer, final EdmOperation operation)
    throws XMLStreamException {
  for (String parameterName : operation.getParameterNames()) {
    EdmParameter parameter = operation.getParameter(parameterName);
    writer.writeStartElement(XML_PARAMETER);
    writer.writeAttribute(XML_NAME, parameterName);
    String typeFqnString;
    if (EdmTypeKind.PRIMITIVE.equals(parameter.getType().getKind())) {
      typeFqnString = getFullQualifiedName(parameter.getType(), parameter.isCollection());
    } else {
      typeFqnString = getAliasedFullQualifiedName(parameter.getType(), parameter.isCollection());
    }
    writer.writeAttribute(XML_TYPE, typeFqnString);

    appendParameterFacets(writer, parameter);

    appendAnnotations(writer, parameter);
    writer.writeEndElement();
  }
}
 
Example 2
Source File: WadlWriter.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
private static final void writeRepresentation(final Representation representation, final XMLStreamWriter xsw)
        throws XMLStreamException {
    xsw.writeStartElement(WADL_PREFIX, WadlElementName.REPRESENTATION.getLocalName(), WadlSyntax.NAMESPACE);
    try {
        xsw.writeAttribute(WadlAttributeName.MEDIA_TYPE.getLocalName(), representation.getMediaType());
        if (representation.getId() != null) {
            xsw.writeAttribute(WadlAttributeName.ID.getLocalName(), representation.getId());
        }
        final QName element = representation.getElementName();
        if (element != null) {
            xsw.writeAttribute(WadlAttributeName.ELEMENT.getLocalName(), toLexicalForm(element, xsw));
        }
        writeDocumentation(representation, xsw);
    } finally {
        xsw.writeEndElement();
    }
}
 
Example 3
Source File: ODataXmlSerializer.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private void writeLink(final XMLStreamWriter writer, final Link link, final boolean close)
    throws XMLStreamException {
  writer.writeStartElement(ATOM, Constants.ATOM_ELEM_LINK, NS_ATOM);
  writer.writeAttribute(Constants.ATTR_REL, link.getRel());
  if (link.getType() != null) {
    writer.writeAttribute(Constants.ATTR_TYPE, link.getType());
  }
  if (link.getTitle() != null) {
    writer.writeAttribute(Constants.ATTR_TITLE, link.getTitle());
  }
  if (link.getHref() != null) {
    writer.writeAttribute(Constants.ATTR_HREF, link.getHref());
  }
  if (close) {
    writer.writeEndElement();
  }
}
 
Example 4
Source File: AtomEntryEntitySerializer.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
private void appendAtomNavigationLink(final XMLStreamWriter writer, final String target,
    final String navigationPropertyName, final boolean isFeed) 
        throws EntityProviderException, EdmException, URISyntaxException { //NOSONAR
  try {
    writer.writeStartElement(FormatXml.ATOM_LINK);
    writer.writeAttribute(FormatXml.ATOM_HREF, target);
    writer.writeAttribute(FormatXml.ATOM_REL, Edm.NAMESPACE_REL_2007_08 + navigationPropertyName);
    writer.writeAttribute(FormatXml.ATOM_TITLE, navigationPropertyName);
    if (isFeed) {
      writer.writeAttribute(FormatXml.ATOM_TYPE, ContentType.APPLICATION_ATOM_XML_FEED.toString());
    } else {
      writer.writeAttribute(FormatXml.ATOM_TYPE, ContentType.APPLICATION_ATOM_XML_ENTRY.toString());
    }
  } catch (XMLStreamException e) {
    throw new EntityProviderProducerException(EntityProviderException.COMMON, e);
  }
}
 
Example 5
Source File: HtmlDocumentationWriter.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Writes the head portion of the HTML documentation.
 *
 * @param configurableComponent the component to describe
 * @param xmlStreamWriter the stream to write to
 * @throws XMLStreamException thrown if there was a problem writing to the
 * stream
 */
protected void writeHead(final ConfigurableComponent configurableComponent,
        final XMLStreamWriter xmlStreamWriter) throws XMLStreamException {
    xmlStreamWriter.writeStartElement("head");
    xmlStreamWriter.writeStartElement("meta");
    xmlStreamWriter.writeAttribute("charset", "utf-8");
    xmlStreamWriter.writeEndElement();
    writeSimpleElement(xmlStreamWriter, "title", getTitle(configurableComponent));

    xmlStreamWriter.writeStartElement("link");
    xmlStreamWriter.writeAttribute("rel", "stylesheet");
    xmlStreamWriter.writeAttribute("href", "../../css/component-usage.css");
    xmlStreamWriter.writeAttribute("type", "text/css");
    xmlStreamWriter.writeEndElement();

    xmlStreamWriter.writeEndElement();
}
 
Example 6
Source File: TableauMessageBodyGenerator.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private void writeRelation(XMLStreamWriter xmlStreamWriter, DatasetConfig datasetConfig) throws XMLStreamException {
  DatasetPath dataset = new DatasetPath(datasetConfig.getFullPathList());

  final String name = dataset.getLeaf().getName();
  // If dataset schema contains a dot '.' in one of its component
  // Tableau won't be able to open it
  final String schema = Joiner.on('.').join(dataset.toParentPathList());

  xmlStreamWriter.writeStartElement("relation");
  xmlStreamWriter.writeAttribute("name", name);
  xmlStreamWriter.writeAttribute("type", "table");
  xmlStreamWriter.writeAttribute("table", format("[%s].[%s]", tableauEncode(schema), tableauEncode(name)));
  xmlStreamWriter.writeEndElement();
}
 
Example 7
Source File: XhtmlCollectionFormat.java    From cosmo with Apache License 2.0 5 votes vote down vote up
public String format(CollectionItem collection) {
    try {
        StringWriter sw = new StringWriter();
        XMLStreamWriter writer = createXmlWriter(sw);

        writer.writeStartElement("div");
        writer.writeAttribute("class", "collection");

        writer.writeCharacters("Collection: ");

        if (collection.getDisplayName() != null) {
            writer.writeStartElement("span");
            writer.writeAttribute("class", "name");
            writer.writeCharacters(collection.getDisplayName());
            writer.writeEndElement();
        }

        if (collection.getUid() != null) {
            writer.writeCharacters(" (uuid ");
            writer.writeStartElement("span");
            writer.writeAttribute("class", "uuid");
            writer.writeCharacters(collection.getUid());
            writer.writeEndElement();
            writer.writeCharacters(")");
        }

        writer.writeEndElement();
        writer.close();

        return sw.toString();
    } catch (XMLStreamException e) {
        throw new CosmoXMLStreamException("Error formatting XML", e);
    }
}
 
Example 8
Source File: AtomEntryEntityProducer.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
private void appendAtomContentPart(final XMLStreamWriter writer, final EntityInfoAggregator eia,
    final Map<String, Object> data, final String selfLink) throws EntityProviderException, EdmException {
  try {

    EdmMapping entityTypeMapping = eia.getEntityType().getMapping();
    String self = null;
    String mediaResourceMimeType = null;

    if (entityTypeMapping != null) {
      String mediaResourceSourceKey = entityTypeMapping.getMediaResourceSourceKey();
      if (mediaResourceSourceKey != null) {
        self = (String) data.get(mediaResourceSourceKey);
      }
      if (self == null) {
        self = selfLink + "/$value";
      }
      String mediaResourceMimeTypeKey = entityTypeMapping.getMediaResourceMimeTypeKey();
      if (mediaResourceMimeTypeKey != null) {
        mediaResourceMimeType = (String) data.get(mediaResourceMimeTypeKey);
      }
      if (mediaResourceMimeType == null) {
        mediaResourceMimeType = ContentType.APPLICATION_OCTET_STREAM.toString();
      }
    } else {
      self = selfLink + "/$value";
      mediaResourceMimeType = ContentType.APPLICATION_OCTET_STREAM.toString();
    }

    writer.writeEmptyElement(FormatXml.ATOM_CONTENT);
    writer.writeAttribute(FormatXml.ATOM_TYPE, mediaResourceMimeType);
    writer.writeAttribute(FormatXml.ATOM_SRC, self);
  } catch (XMLStreamException e) {
    throw new EntityProviderProducerException(EntityProviderException.COMMON, e);
  }
}
 
Example 9
Source File: HtmlDocumentationWriter.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private void writeValidValueDescription(XMLStreamWriter xmlStreamWriter, String description)
        throws XMLStreamException {
    xmlStreamWriter.writeCharacters(" ");
    xmlStreamWriter.writeStartElement("img");
    xmlStreamWriter.writeAttribute("src", "../../html/images/iconInfo.png");
    xmlStreamWriter.writeAttribute("alt", description);
    xmlStreamWriter.writeAttribute("title", description);
    xmlStreamWriter.writeEndElement();

}
 
Example 10
Source File: AtomSerializer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void reference(final Writer outWriter, final ResWrap<URI> container) throws XMLStreamException {
  final XMLStreamWriter writer = FACTORY.createXMLStreamWriter(outWriter);

  writer.writeStartDocument();

  writer.writeStartElement(Constants.ATTR_METADATA, Constants.ATTR_REF, Constants.NS_METADATA);
  writer.writeNamespace(Constants.ATTR_METADATA, Constants.NS_METADATA);
  writer.writeAttribute(Constants.ATTR_METADATA, Constants.NS_METADATA, Constants.CONTEXT, 
      container.getContextURL().toASCIIString());
  writer.writeAttribute(Constants.ATOM_ATTR_ID, container.getPayload().toASCIIString());
  writer.writeEndElement();

  writer.writeEndDocument();
}
 
Example 11
Source File: HtmlDocumentationWriter.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Write the description of the Restricted annotation if provided in this component.
 *
 * @param configurableComponent the component to describe
 * @param xmlStreamWriter the stream writer to use
 * @throws XMLStreamException thrown if there was a problem writing the XML
 */
private void writeRestrictedInfo(ConfigurableComponent configurableComponent, XMLStreamWriter xmlStreamWriter)
        throws XMLStreamException {
    final Restricted restricted = configurableComponent.getClass().getAnnotation(Restricted.class);

    writeSimpleElement(xmlStreamWriter, "h3", "Restricted: ");

    if(restricted != null) {
        final String value = restricted.value();

        if (!StringUtils.isBlank(value)) {
            xmlStreamWriter.writeCharacters(restricted.value());
        }

        final Restriction[] restrictions = restricted.restrictions();
        if (restrictions != null && restrictions.length > 0) {
            xmlStreamWriter.writeStartElement("table");
            xmlStreamWriter.writeAttribute("id", "restrictions");
            xmlStreamWriter.writeStartElement("tr");
            writeSimpleElement(xmlStreamWriter, "th", "Required Permission");
            writeSimpleElement(xmlStreamWriter, "th", "Explanation");
            xmlStreamWriter.writeEndElement();

            for (Restriction restriction : restrictions) {
                xmlStreamWriter.writeStartElement("tr");
                writeSimpleElement(xmlStreamWriter, "td", restriction.requiredPermission().getPermissionLabel());
                writeSimpleElement(xmlStreamWriter, "td", restriction.explanation());
                xmlStreamWriter.writeEndElement();
            }

            xmlStreamWriter.writeEndElement();
        } else {
            xmlStreamWriter.writeCharacters("This component requires access to restricted components regardless of restriction.");
        }
    } else {
        xmlStreamWriter.writeCharacters("This component is not restricted.");
    }
}
 
Example 12
Source File: XmlMetadataProducer.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
private static void writeAssociationSetEnd(final AssociationSetEnd end,
    final Map<String, String> predefinedNamespaces, final XMLStreamWriter xmlStreamWriter) throws XMLStreamException {
  xmlStreamWriter.writeStartElement(XmlMetadataConstants.EDM_ASSOCIATION_END);
  xmlStreamWriter.writeAttribute(XmlMetadataConstants.EDM_ENTITY_SET, end.getEntitySet().toString());
  if (end.getRole() != null) {
    xmlStreamWriter.writeAttribute(XmlMetadataConstants.EDM_ROLE, end.getRole());
  }
  writeAnnotationAttributes(end.getAnnotationAttributes(), predefinedNamespaces, null, xmlStreamWriter);
  writeDocumentation(end.getDocumentation(), predefinedNamespaces, xmlStreamWriter);
  writeAnnotationElements(end.getAnnotationElements(), predefinedNamespaces, xmlStreamWriter);
  xmlStreamWriter.writeEndElement();
}
 
Example 13
Source File: ScanTibcoSolutionPipe.java    From iaf with Apache License 2.0 4 votes vote down vote up
public void process(XMLStreamWriter xmlStreamWriter, String cUrl, int cLevel) throws XMLStreamException, DomBuilderException, XPathExpressionException {
	String html;
	try {
		html = getHtml(cUrl);
	} catch (Exception e) {
		error(xmlStreamWriter, "error occured during getting html", e, true);
		html = null;
	}
	if (html != null) {
		Collection<String> c = XmlUtils.evaluateXPathNodeSet(html,
				"html/body/ul/li/a/@href");
		if (c != null) {
			for (Iterator<String> it = c.iterator(); it.hasNext();) {
				String token = it.next();
				if (token.equals("../")) {
					// skip reference to parent directory
				} else if (cLevel == 0 && !token.equals("BW/")
						&& !token.equals("SOA/")) {
					skipDir(xmlStreamWriter, token);
					// } else if (cLevel == 1 &&
					// !token.startsWith("Customer")) {
					// skipDir(xmlStreamWriter, token);
				} else if (cLevel == 2
						&& (token.equals("branches/") || token
								.equals("tags/")) && c.contains("trunk/")) {
					skipDir(xmlStreamWriter, token);
				} else if (cLevel == 3 && !token.equals("src/")
						&& c.contains("src/") && !token.equals("release/")) {
					skipDir(xmlStreamWriter, token);
					// } else if (cLevel == 5 && token.endsWith("/")) {
					// skipDir(xmlStreamWriter, token);
				} else {
					String newUrl = cUrl + token;
					boolean dir = false;
					if (token.endsWith("/")) {
						dir = true;
					}
					if (dir) {
						xmlStreamWriter.writeStartElement("dir");
						xmlStreamWriter.writeAttribute("name",
								skipLastCharacter(token));
						// xmlStreamWriter.writeAttribute("level",
						// String.valueOf(cLevel + 1));
						if (cLevel == 1 || cLevel == 4) {
							addCommit(xmlStreamWriter, newUrl);
						}
						process(xmlStreamWriter, newUrl, cLevel + 1);
					} else {
						xmlStreamWriter.writeStartElement("file");
						xmlStreamWriter.writeAttribute("name", token);
						if (cLevel > 5) {
							if (token.endsWith(".jmsDest")) {
								addFileContent(xmlStreamWriter, newUrl,
										"jmsDest");
							}
							if (token.endsWith(".jmsDestConf")) {
								addFileContent(xmlStreamWriter, newUrl,
										"jmsDestConf");
							}
							if (token.endsWith(".composite")) {
								addFileContent(xmlStreamWriter, newUrl,
										"composite");
							}
							if (token.endsWith(".process")) {
								addFileContent(xmlStreamWriter, newUrl,
										"process");
							}
							if (token.equals("defaultVars.substvar")) {
								addFileContent(xmlStreamWriter, newUrl,
										"substVar");
							}
						}
					}
					xmlStreamWriter.writeEndElement();
				}
			}
		}
	}
}
 
Example 14
Source File: BaseBpmnXMLConverter.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
protected boolean writeFormProperties(FlowElement flowElement, boolean didWriteExtensionStartElement, XMLStreamWriter xtw) throws Exception {

    List<FormProperty> propertyList = null;
    if (flowElement instanceof UserTask) {
      propertyList = ((UserTask) flowElement).getFormProperties();
    } else if (flowElement instanceof StartEvent) {
      propertyList = ((StartEvent) flowElement).getFormProperties();
    }

    if (propertyList != null) {

      for (FormProperty property : propertyList) {

        if (StringUtils.isNotEmpty(property.getId())) {

          if (didWriteExtensionStartElement == false) {
            xtw.writeStartElement(ELEMENT_EXTENSIONS);
            didWriteExtensionStartElement = true;
          }

          xtw.writeStartElement(ACTIVITI_EXTENSIONS_PREFIX, ELEMENT_FORMPROPERTY, ACTIVITI_EXTENSIONS_NAMESPACE);
          writeDefaultAttribute(ATTRIBUTE_FORM_ID, property.getId(), xtw);

          writeDefaultAttribute(ATTRIBUTE_FORM_NAME, property.getName(), xtw);
          writeDefaultAttribute(ATTRIBUTE_FORM_TYPE, property.getType(), xtw);
          writeDefaultAttribute(ATTRIBUTE_FORM_EXPRESSION, property.getExpression(), xtw);
          writeDefaultAttribute(ATTRIBUTE_FORM_VARIABLE, property.getVariable(), xtw);
          writeDefaultAttribute(ATTRIBUTE_FORM_DEFAULT, property.getDefaultExpression(), xtw);
          writeDefaultAttribute(ATTRIBUTE_FORM_DATEPATTERN, property.getDatePattern(), xtw);
          if (property.isReadable() == false) {
            writeDefaultAttribute(ATTRIBUTE_FORM_READABLE, ATTRIBUTE_VALUE_FALSE, xtw);
          }
          if (property.isWriteable() == false) {
            writeDefaultAttribute(ATTRIBUTE_FORM_WRITABLE, ATTRIBUTE_VALUE_FALSE, xtw);
          }
          if (property.isRequired()) {
            writeDefaultAttribute(ATTRIBUTE_FORM_REQUIRED, ATTRIBUTE_VALUE_TRUE, xtw);
          }

          for (FormValue formValue : property.getFormValues()) {
            if (StringUtils.isNotEmpty(formValue.getId())) {
              xtw.writeStartElement(ACTIVITI_EXTENSIONS_PREFIX, ELEMENT_VALUE, ACTIVITI_EXTENSIONS_NAMESPACE);
              xtw.writeAttribute(ATTRIBUTE_ID, formValue.getId());
              xtw.writeAttribute(ATTRIBUTE_NAME, formValue.getName());
              xtw.writeEndElement();
            }
          }

          xtw.writeEndElement();
        }
      }
    }

    return didWriteExtensionStartElement;
  }
 
Example 15
Source File: MetadataWriter.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private void writeSAMLMetadata(
    XMLStreamWriter writer,
    HttpServletRequest request,
    FedizContext config,
    String serviceURL
) throws Exception {

    SAMLProtocol protocol = (SAMLProtocol)config.getProtocol();

    writer.writeStartElement("md", "SPSSODescriptor", SAML2_METADATA_NS);
    writer.writeAttribute("AuthnRequestsSigned", Boolean.toString(protocol.isSignRequest()));
    writer.writeAttribute("WantAssertionsSigned", "true");
    writer.writeAttribute("protocolSupportEnumeration", "urn:oasis:names:tc:SAML:2.0:protocol");

    if (config.getLogoutURL() != null) {
        writer.writeStartElement("md", "SingleLogoutService", SAML2_METADATA_NS);

        String logoutURL = config.getLogoutURL();
        if (logoutURL.startsWith("/")) {
            logoutURL = extractFullContextPath(request).concat(logoutURL.substring(1));
        } else {
            logoutURL = extractFullContextPath(request).concat(logoutURL);
        }
        writer.writeAttribute("Location", logoutURL);

        writer.writeAttribute("Binding", "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
        writer.writeEndElement(); // SingleLogoutService
    }

    writer.writeStartElement("md", "AssertionConsumerService", SAML2_METADATA_NS);
    writer.writeAttribute("Location", serviceURL);
    writer.writeAttribute("index", "0");
    writer.writeAttribute("isDefault", "true");
    writer.writeAttribute("Binding", "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
    writer.writeEndElement(); // AssertionConsumerService

    if (protocol.getClaimTypesRequested() != null && !protocol.getClaimTypesRequested().isEmpty()) {
        writer.writeStartElement("md", "AttributeConsumingService", SAML2_METADATA_NS);
        writer.writeAttribute("index", "0");

        writer.writeStartElement("md", "ServiceName", SAML2_METADATA_NS);
        writer.writeAttribute("xml:lang", "en");
        writer.writeCharacters(config.getName());
        writer.writeEndElement(); // ServiceName

        for (Claim claim : protocol.getClaimTypesRequested()) {
            writer.writeStartElement("md", "RequestedAttribute", SAML2_METADATA_NS);
            writer.writeAttribute("isRequired", Boolean.toString(claim.isOptional()));
            writer.writeAttribute("Name", claim.getType());
            writer.writeAttribute("NameFormat",
                                  "urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified");
            writer.writeEndElement(); // RequestedAttribute
        }

        writer.writeEndElement(); // AttributeConsumingService
    }

    boolean hasSigningKey = false;
    try {
        if (config.getSigningKey().getCrypto() != null) {
            hasSigningKey = true;
        }
    } catch (Exception ex) {
        LOG.info("No signingKey element found in config: " + ex.getMessage());
    }
    if (protocol.isSignRequest() && hasSigningKey) {
        writer.writeStartElement("md", "KeyDescriptor", SAML2_METADATA_NS);
        writer.writeAttribute("use", "signing");

        writer.writeStartElement("ds", "KeyInfo", "http://www.w3.org/2000/09/xmldsig#");
        writer.writeNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
        writer.writeStartElement("ds", "X509Data", "http://www.w3.org/2000/09/xmldsig#");
        writer.writeStartElement("ds", "X509Certificate", "http://www.w3.org/2000/09/xmldsig#");

        // Write the Base-64 encoded certificate
        String keyAlias = config.getSigningKey().getKeyAlias();
        if (keyAlias == null || "".equals(keyAlias)) {
            keyAlias = config.getSigningKey().getCrypto().getDefaultX509Identifier();
        }
        X509Certificate cert =
            CertsUtils.getX509CertificateFromCrypto(config.getSigningKey().getCrypto(), keyAlias);
        if (cert == null) {
            throw new ProcessingException(
                "No signing certs were found to insert into the metadata using name: "
                    + keyAlias);
        }
        byte[] data = cert.getEncoded();
        String encodedCertificate = Base64.getEncoder().encodeToString(data);
        writer.writeCharacters(encodedCertificate);

        writer.writeEndElement(); // X509Certificate
        writer.writeEndElement(); // X509Data
        writer.writeEndElement(); // KeyInfo
        writer.writeEndElement(); // KeyDescriptor
    }

    writer.writeEndElement(); // SPSSODescriptor
}
 
Example 16
Source File: DsParser.java    From ironjacamar with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Store a pool
 * @param pool The pool
 * @param writer The writer
 * @exception Exception Thrown if an error occurs
 */
protected void storePool(DsPool pool, XMLStreamWriter writer) throws Exception
{
   writer.writeStartElement(XML.ELEMENT_POOL);

   if (pool.getMinPoolSize() != null && (pool.hasExpression(XML.ELEMENT_MIN_POOL_SIZE) ||
                                         !Defaults.MIN_POOL_SIZE.equals(pool.getMinPoolSize())))
   {
      writer.writeStartElement(XML.ELEMENT_MIN_POOL_SIZE);
      writer.writeCharacters(pool.getValue(XML.ELEMENT_MIN_POOL_SIZE, pool.getMinPoolSize().toString()));
      writer.writeEndElement();
   }

   if (pool.getInitialPoolSize() != null)
   {
      writer.writeStartElement(XML.ELEMENT_INITIAL_POOL_SIZE);
      writer.writeCharacters(pool.getValue(XML.ELEMENT_INITIAL_POOL_SIZE, pool.getInitialPoolSize().toString()));
      writer.writeEndElement();
   }

   if (pool.getMaxPoolSize() != null && (pool.hasExpression(XML.ELEMENT_MAX_POOL_SIZE) ||
                                         !Defaults.MAX_POOL_SIZE.equals(pool.getMaxPoolSize())))
   {
      writer.writeStartElement(XML.ELEMENT_MAX_POOL_SIZE);
      writer.writeCharacters(pool.getValue(XML.ELEMENT_MAX_POOL_SIZE, pool.getMaxPoolSize().toString()));
      writer.writeEndElement();
   }

   if (pool.isPrefill() != null && (pool.hasExpression(XML.ELEMENT_PREFILL) ||
                                    !Defaults.PREFILL.equals(pool.isPrefill())))
   {
      writer.writeStartElement(XML.ELEMENT_PREFILL);
      writer.writeCharacters(pool.getValue(XML.ELEMENT_PREFILL, pool.isPrefill().toString()));
      writer.writeEndElement();
   }

   if (pool.getFlushStrategy() != null && (pool.hasExpression(XML.ELEMENT_FLUSH_STRATEGY) ||
                                           !Defaults.FLUSH_STRATEGY.equals(pool.getFlushStrategy())))
   {
      writer.writeStartElement(XML.ELEMENT_FLUSH_STRATEGY);
      writer.writeCharacters(pool.getValue(XML.ELEMENT_FLUSH_STRATEGY, pool.getFlushStrategy().toString()));
      writer.writeEndElement();
   }

   if (pool.getCapacity() != null)
      storeCapacity(pool.getCapacity(), writer);

   if (pool.getConnectionListener() != null)
   {
      writer.writeStartElement(XML.ELEMENT_CONNECTION_LISTENER);
      writer.writeAttribute(XML.ATTRIBUTE_CLASS_NAME,
                            pool.getConnectionListener().getValue(XML.ATTRIBUTE_CLASS_NAME,
                                                                  pool.getConnectionListener().getClassName()));

      if (!pool.getConnectionListener().getConfigPropertiesMap().isEmpty())
      {
         Iterator<Map.Entry<String, String>> it =
            pool.getConnectionListener().getConfigPropertiesMap().entrySet().iterator();
         
         while (it.hasNext())
         {
            Map.Entry<String, String> entry = it.next();

            writer.writeStartElement(XML.ELEMENT_CONFIG_PROPERTY);
            writer.writeAttribute(XML.ATTRIBUTE_NAME, entry.getKey());
            writer.writeCharacters(pool.getConnectionListener().getValue(XML.ELEMENT_CONFIG_PROPERTY,
                                                                         entry.getKey(), entry.getValue()));
            writer.writeEndElement();
         }
      }

      writer.writeEndElement();
   }

   writer.writeEndElement();
}
 
Example 17
Source File: TtmlWriter.java    From subtitle with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void writeStyles(TtmlObject ttmlObject, XMLStreamWriter xsw) throws XMLStreamException {
    // Start layout that contains all regions
    xsw.writeStartElement("styling");

    for (Map.Entry<String, SubtitleStyle> entry: ttmlObject.getStyles().entrySet()) {
        SubtitleStyle style = entry.getValue();
        String styleId = entry.getKey();

        // Writer style
        xsw.writeStartElement("style");
        xsw.writeAttribute(NS_XML, "id", styleId);


        if (style.getColor() != null) {
            xsw.writeAttribute(NS_TTS, "color", style.getColor());
        }

        // Text align
        if (style.getTextAlign() != null) {
            String textAlign = "center";

            if (style.getTextAlign() == SubtitleStyle.TextAlign.LEFT) {
                textAlign = "left";
            } else if (style.getTextAlign() == SubtitleStyle.TextAlign.RIGHT) {
                textAlign = "right";
            }

            xsw.writeAttribute(NS_TTS, "textAlign", textAlign);
        }

        // Text direction
        if (style.getDirection() != null) {
            String direction = "ltr";

            if (style.getDirection() == SubtitleStyle.Direction.RTL) {
                direction = "rtl";
            }

            xsw.writeAttribute(NS_TTS, "direction", direction);
        }

        xsw.writeEndElement();
    }

    // End of layout
    xsw.writeEndElement();
}
 
Example 18
Source File: SecureConversationToken.java    From steady with Apache License 2.0 4 votes vote down vote up
public void serialize(XMLStreamWriter writer) throws XMLStreamException {

        String localname = getRealName().getLocalPart();
        String namespaceURI = getRealName().getNamespaceURI();
        String prefix;

        String writerPrefix = writer.getPrefix(namespaceURI);

        if (writerPrefix == null) {
            prefix = getRealName().getPrefix();
            writer.setPrefix(prefix, namespaceURI);
        } else {
            prefix = writerPrefix;
        }

        // <sp:SecureConversationToken>
        writer.writeStartElement(prefix, localname, namespaceURI);

        if (writerPrefix == null) {
            // xmlns:sp=".."
            writer.writeNamespace(prefix, namespaceURI);
        }

        String inclusion;

        inclusion = constants.getAttributeValueFromInclusion(getInclusion());

        if (inclusion != null) {
            writer.writeAttribute(prefix, namespaceURI, SPConstants.ATTR_INCLUDE_TOKEN, inclusion);
        }

        if (issuerEpr != null) {
            // <sp:Issuer>
            writer.writeStartElement(prefix, SPConstants.ISSUER, namespaceURI);

            StaxUtils.copy(issuerEpr, writer);

            writer.writeEndElement();
        }

        if (isDerivedKeys() || isRequireExternalUriRef() || isSc10SecurityContextToken()
            || isSc13SecurityContextToken() || bootstrapPolicy != null) {

            String wspNamespaceURI = SPConstants.POLICY.getNamespaceURI();

            String wspPrefix;

            String wspWriterPrefix = writer.getPrefix(wspNamespaceURI);

            if (wspWriterPrefix == null) {
                wspPrefix = SPConstants.POLICY.getPrefix();
                writer.setPrefix(wspPrefix, wspNamespaceURI);

            } else {
                wspPrefix = wspWriterPrefix;
            }

            // <wsp:Policy>
            writer.writeStartElement(wspPrefix, SPConstants.POLICY.getLocalPart(), wspNamespaceURI);

            if (wspWriterPrefix == null) {
                // xmlns:wsp=".."
                writer.writeNamespace(wspPrefix, wspNamespaceURI);
            }

            if (isDerivedKeys()) {
                // <sp:RequireDerivedKeys />
                writer.writeEmptyElement(prefix, SPConstants.REQUIRE_DERIVED_KEYS, namespaceURI);
            }

            if (isRequireExternalUriRef()) {
                // <sp:RequireExternalUriReference />
                writer.writeEmptyElement(prefix, SPConstants.REQUIRE_EXTERNAL_URI_REFERENCE, namespaceURI);
            }

            if (isSc10SecurityContextToken()) {
                // <sp:SC10SecurityContextToken />
                writer.writeEmptyElement(prefix, SPConstants.SC10_SECURITY_CONTEXT_TOKEN, namespaceURI);
            }
            
            if (isSc13SecurityContextToken()) {
                // <sp:SC13SecurityContextToken />
                writer.writeEmptyElement(prefix, SPConstants.SC13_SECURITY_CONTEXT_TOKEN, namespaceURI);
            }

            if (bootstrapPolicy != null) {
                // <sp:BootstrapPolicy ..>
                writer.writeStartElement(prefix, SPConstants.BOOTSTRAP_POLICY, namespaceURI);
                bootstrapPolicy.serialize(writer);
                writer.writeEndElement();
            }

            // </wsp:Policy>
            writer.writeEndElement();
        }

        // </sp:SecureConversationToken>
        writer.writeEndElement();
    }
 
Example 19
Source File: MetadataDocumentXmlSerializer.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
private void appendEntityContainer(final XMLStreamWriter writer, final EdmEntityContainer container)
    throws XMLStreamException {
  if (container != null) {
    writer.writeStartElement(XML_ENTITY_CONTAINER);

    writer.writeAttribute(XML_NAME, container.getName());
    FullQualifiedName parentContainerName = container.getParentContainerName();
    if (parentContainerName != null) {
      String parentContainerNameString;
      if (namespaceToAlias.get(parentContainerName.getNamespace()) != null) {
        parentContainerNameString =
            namespaceToAlias.get(parentContainerName.getNamespace()) + "." + parentContainerName.getName();
      } else {
        parentContainerNameString = parentContainerName.getFullQualifiedNameAsString();
      }
      writer.writeAttribute(XML_EXTENDS, parentContainerNameString);
    }

    // EntitySets
    appendEntitySets(writer, container.getEntitySets());

    // ActionImports
    appendActionImports(writer, container.getActionImports());

    // FunctionImports
    String containerNamespace;
    if (namespaceToAlias.get(container.getNamespace()) != null) {
      containerNamespace = namespaceToAlias.get(container.getNamespace());
    } else {
      containerNamespace = container.getNamespace();
    }
    appendFunctionImports(writer, container.getFunctionImports(), containerNamespace);

    // Singletons
    appendSingletons(writer, container.getSingletons());

    // Annotations
    appendAnnotations(writer, container);

    writer.writeEndElement();
  }
}
 
Example 20
Source File: DocumentStaxUtils.java    From gate-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Write a feature map to the given XMLStreamWriter. The map is output
 * as a sequence of "Feature" elements, each having "Name" and "Value"
 * children. Note that there is no enclosing element - the caller must
 * write the enclosing "GateDocumentFeatures" or "Annotation" element.
 * Characters in feature values that are illegal in XML are replaced
 * by {@link #INVALID_CHARACTER_REPLACEMENT} (a space). Feature
 * <i>names</i> are not modified - an illegal character in a feature
 * name will cause the serialization to fail.
 * 
 * @param features
 * @param xsw
 * @param namespaceURI
 * @throws XMLStreamException
 */
public static void writeFeatures(FeatureMap features, XMLStreamWriter xsw,
        String namespaceURI) throws XMLStreamException {
  if(features == null) {
    return;
  }

  Set<Object> keySet = features.keySet();
  Iterator<Object> keySetIterator = keySet.iterator();
  //FEATURES:
  while(keySetIterator.hasNext()) {
    Object key = keySetIterator.next();
    Object value = features.get(key);
    if(key != null && value != null) {
      String keyClassName = null;
      //String keyItemClassName = null;
      String valueClassName = null;
      //String valueItemClassName = null;
      String key2String = key.toString();
      String value2String = value.toString();
      //Object item = null;
      // Test key if it is String, Number
      if(key instanceof java.lang.String || 
         key instanceof java.lang.Number) {
        keyClassName = key.getClass().getName();
      } else {
        keyClassName = ObjectWrapper.class.getName();
        key2String = new ObjectWrapper(key).toString();
      }
        
      // Test value if it is String, Number
      if(value instanceof java.lang.String
              || value instanceof java.lang.Number
              || value instanceof java.lang.Boolean){
        valueClassName = value.getClass().getName();
      } else {
        valueClassName = ObjectWrapper.class.getName();
        value2String = new ObjectWrapper(value).toString();
      }
        
      // Features and values that are not Strings, Numbers, Booleans or
      // collections
      // will be discarded.
      //if(keyClassName == null || valueClassName == null) continue;

      xsw.writeStartElement(namespaceURI, "Feature");
      xsw.writeCharacters("\n  ");

      // write the Name
      xsw.writeStartElement(namespaceURI, "Name");
      if(keyClassName != null) {
        xsw.writeAttribute("className", keyClassName);
      }
      //if(keyItemClassName != null) {
      //  xsw.writeAttribute("itemClassName", keyItemClassName);
      //}
      xsw.writeCharacters(key2String);
      xsw.writeEndElement();
      xsw.writeCharacters("\n  ");

      // write the Value
      xsw.writeStartElement(namespaceURI, "Value");
      if(valueClassName != null) {
        xsw.writeAttribute("className", valueClassName);
      }
      //if(valueItemClassName != null) {
      //  xsw.writeAttribute("itemClassName", valueItemClassName);
      //}
      writeCharactersOrCDATA(xsw,
              replaceXMLIllegalCharactersInString(value2String));
      xsw.writeEndElement();
      newLine(xsw);

      // close the Feature element
      xsw.writeEndElement();
      newLine(xsw);
    }
  }
}