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

The following examples show how to use javax.xml.stream.XMLStreamWriter#setDefaultNamespace() . 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: DefinitionsRootExport.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
public static void writeRootElement(CmmnModel model, XMLStreamWriter xtw, String encoding) throws Exception {
    xtw.writeStartDocument(encoding, "1.0");

    // start definitions root element
    xtw.writeStartElement(ELEMENT_DEFINITIONS);
    xtw.setDefaultNamespace(CMMN_NAMESPACE);
    xtw.writeDefaultNamespace(CMMN_NAMESPACE);
    xtw.writeNamespace(XSI_PREFIX, XSI_NAMESPACE);
    xtw.writeNamespace(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE);
    xtw.writeNamespace(CMMNDI_PREFIX, CMMNDI_NAMESPACE);
    xtw.writeNamespace(OMGDC_PREFIX, OMGDC_NAMESPACE);
    xtw.writeNamespace(OMGDI_PREFIX, OMGDI_NAMESPACE);
    for (String prefix : model.getNamespaces().keySet()) {
        if (!defaultNamespaces.contains(prefix) && StringUtils.isNotEmpty(prefix))
            xtw.writeNamespace(prefix, model.getNamespaces().get(prefix));
    }
    if (StringUtils.isNotEmpty(model.getTargetNamespace())) {
        xtw.writeAttribute(ATTRIBUTE_TARGET_NAMESPACE, model.getTargetNamespace());
    } else {
        xtw.writeAttribute(ATTRIBUTE_TARGET_NAMESPACE, CASE_NAMESPACE);
    }
}
 
Example 2
Source File: AtomSerializer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void startDocument(final XMLStreamWriter writer, final String rootElement) throws XMLStreamException {
  writer.writeStartDocument();
  writer.setDefaultNamespace(Constants.NS_ATOM);
  writer.writeStartElement(rootElement);

  namespaces(writer);
}
 
Example 3
Source File: GraphMlTest.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testSreaming() throws Exception {
  OutputStream out = new ByteArrayOutputStream();
  XMLOutputFactory xof = XMLOutputFactory.newFactory();
  XMLStreamWriter xsw = new IndentingXMLStreamWriter(xof.createXMLStreamWriter(out, StandardCharsets.UTF_8.name()));
  xsw.setDefaultNamespace("http://graphml.graphdrawing.org/xmlns");

  xsw.writeStartDocument("UTF-8", "1.0");
  xsw.writeStartElement("http://graphml.graphdrawing.org/xmlns","graphml");
  xsw.writeDefaultNamespace("http://graphml.graphdrawing.org/xmlns");

  GraphMlContext graphMlContext = new GraphMlContext();
  Marshaller jaxbMarshaller = graphMlContext.createMarshaller();
  //jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
  jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);

  for (int i = 0; i < 5; i++) {
    JAXBElement<Key> je = new Key("d" + i).withAttrName("r").withAttrType("int").withFor("edge").asJaxbElement();
    jaxbMarshaller.marshal(je, xsw);
  }

  xsw.writeStartElement("http://graphml.graphdrawing.org/xmlns","graph");
  xsw.writeAttribute("edgedefault", "directed");

  for (int h = 0; h < 3; h++) {

    Node node = new Node("n" + h);
    for (int i = 0; i < 5; i++) {
      node.addData(new Data().withKey("d" + i).withValue("42"));
    }
    jaxbMarshaller.marshal(node.asJaxbElement(), xsw);
  }

  xsw.writeEndElement();
  xsw.writeEndElement();

  xsw.writeEndDocument();
  xsw.close();
  //System.out.println(out.toString());
}
 
Example 4
Source File: DataSources20TestCase.java    From ironjacamar with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Write
 * @throws Exception In case of an error
 */
@Test
public void testWrite() throws Exception
{
   DsParser parser = new DsParser();

   InputStream is = DataSources20TestCase.class.getClassLoader().
      getResourceAsStream("../../resources/test/ds/dashds-2.0.xml");
   assertNotNull(is);

   XMLStreamReader xsr = XMLInputFactory.newInstance().createXMLStreamReader(is);

   DataSources ds = parser.parse(xsr);
   assertNotNull(ds);

   is.close();

   StringWriter sw = new StringWriter();
   XMLStreamWriter xsw = XMLOutputFactory.newInstance().createXMLStreamWriter(sw);
   xsw.setDefaultNamespace("");

   xsw.writeStartDocument("UTF-8", "1.0");
   parser.store(ds, xsw);
   xsw.writeEndDocument();

   xsw.flush();
   xsw.close();

   assertEquals(ds.toString(), sw.toString());
}
 
Example 5
Source File: DefinitionsRootExport.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static void writeRootElement(BpmnModel model, XMLStreamWriter xtw, String encoding) throws Exception {
  xtw.writeStartDocument(encoding, "1.0");

  // start definitions root element
  xtw.writeStartElement(ELEMENT_DEFINITIONS);
  xtw.setDefaultNamespace(BPMN2_NAMESPACE);
  xtw.writeDefaultNamespace(BPMN2_NAMESPACE);
  xtw.writeNamespace(XSI_PREFIX, XSI_NAMESPACE);
  xtw.writeNamespace(XSD_PREFIX, SCHEMA_NAMESPACE);
  xtw.writeNamespace(ACTIVITI_EXTENSIONS_PREFIX, ACTIVITI_EXTENSIONS_NAMESPACE);
  xtw.writeNamespace(BPMNDI_PREFIX, BPMNDI_NAMESPACE);
  xtw.writeNamespace(OMGDC_PREFIX, OMGDC_NAMESPACE);
  xtw.writeNamespace(OMGDI_PREFIX, OMGDI_NAMESPACE);
  for (String prefix : model.getNamespaces().keySet()) {
    if (!defaultNamespaces.contains(prefix) && StringUtils.isNotEmpty(prefix))
      xtw.writeNamespace(prefix, model.getNamespaces().get(prefix));
  }
  xtw.writeAttribute(TYPE_LANGUAGE_ATTRIBUTE, SCHEMA_NAMESPACE);
  xtw.writeAttribute(EXPRESSION_LANGUAGE_ATTRIBUTE, XPATH_NAMESPACE);
  if (StringUtils.isNotEmpty(model.getTargetNamespace())) {
    xtw.writeAttribute(TARGET_NAMESPACE_ATTRIBUTE, model.getTargetNamespace());
  } else {
    xtw.writeAttribute(TARGET_NAMESPACE_ATTRIBUTE, PROCESS_NAMESPACE);
  }

  BpmnXMLUtil.writeCustomAttributes(model.getDefinitionsAttributes().values(), xtw, model.getNamespaces(), defaultAttributes);
}
 
Example 6
Source File: MetadataDocumentXmlSerializer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public void writeMetadataDocument(final XMLStreamWriter writer) throws XMLStreamException {
  writer.writeStartDocument(ODataSerializer.DEFAULT_CHARSET, "1.0");
  writer.setPrefix(PREFIX_EDMX, NS_EDMX);
  writer.setDefaultNamespace(NS_EDMX);
  writer.writeStartElement(PREFIX_EDMX, EDMX, NS_EDMX);
  writer.writeAttribute("Version", "4.0");
  writer.writeNamespace(PREFIX_EDMX, NS_EDMX);

  appendReference(writer);
  appendDataServices(writer);

  writer.writeEndDocument();
}
 
Example 7
Source File: CombinedQueryBuilderTest.java    From java-client-api with Apache License 2.0 5 votes vote down vote up
public XMLStreamWriter makeXMLStreamWriter(OutputStream out) throws XMLStreamException {
  XMLOutputFactory factory = XmlFactories.getOutputFactory();

  XMLStreamWriter writer = factory.createXMLStreamWriter(out, "UTF-8");
  writer.setDefaultNamespace("http://marklogic.com/appservices/search");
  return writer;
}
 
Example 8
Source File: CombinedQueryBuilderImpl.java    From java-client-api with Apache License 2.0 5 votes vote down vote up
private XMLStreamWriter makeXMLSerializer(OutputStream out) {
  XMLOutputFactory factory = XmlFactories.getOutputFactory();

  try {
    XMLStreamWriter serializer = factory.createXMLStreamWriter(out, "UTF-8");

    serializer.setDefaultNamespace("http://marklogic.com/appservices/search");
    serializer.setPrefix("xs",  XMLConstants.W3C_XML_SCHEMA_NS_URI);

    return serializer;
  } catch (Exception e) {
    throw new MarkLogicIOException(e);
  }
}
 
Example 9
Source File: StructuredQueryBuilder.java    From java-client-api with Apache License 2.0 5 votes vote down vote up
static private XMLStreamWriter makeSerializer(OutputStream out) {
  XMLOutputFactory factory = XmlFactories.getOutputFactory();

  try {
    XMLStreamWriter serializer = factory.createXMLStreamWriter(out, "UTF-8");

    serializer.setDefaultNamespace(SEARCH_API_NS);
    serializer.setPrefix("xs",  XMLConstants.W3C_XML_SCHEMA_NS_URI);

    return serializer;
  } catch (Exception e) {
    throw new MarkLogicIOException(e);
  }
}
 
Example 10
Source File: XMLWriterHelper.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public void startWrapperElement(XMLStreamWriter xmlWriter, String namespace,
		String name, int resultType) throws XMLStreamException {
       if (xmlWriter == null) {
           return;
       }
	String nsPrefix;
	boolean writeNS;
	switch (resultType) {
	case DBConstants.ResultTypes.XML:
		if (name != null) {
		    /* start result wrapper */
		    xmlWriter.writeStartElement(name);
		    /* write default namespace */
		    nsPrefix = xmlWriter.getNamespaceContext().getPrefix(this.getNamespace());
			writeNS = nsPrefix == null || !"".equals(nsPrefix);				
		    if (writeNS) {
		    	xmlWriter.setDefaultNamespace(namespace);
		        xmlWriter.writeDefaultNamespace(namespace);
		    }
		}
		break;
	case DBConstants.ResultTypes.RDF:
		xmlWriter.setDefaultNamespace(namespace);
		xmlWriter.writeStartElement(DBConstants.DEFAULT_RDF_PREFIX,
				DBConstants.DBSFields.RDF, DBConstants.RDF_NAMESPACE);
		xmlWriter.writeNamespace(DBConstants.DEFAULT_RDF_PREFIX, DBConstants.RDF_NAMESPACE);
		xmlWriter.writeDefaultNamespace(namespace);
		break;
	}
}
 
Example 11
Source File: DefaultNSWriter.java    From softwarecave with GNU General Public License v3.0 5 votes vote down vote up
private void writeBooksElem(XMLStreamWriter writer, List<Book> books) throws XMLStreamException {
    writer.writeStartDocument("utf-8", "1.0");
    writer.writeComment("Describes list of books");
    
    writer.setDefaultNamespace(NS);
    writer.writeStartElement(NS, "books");
    writer.writeDefaultNamespace(NS);
    for (Book book : books)
        writeBookElem(writer, book);
    writer.writeEndElement();

    writer.writeEndDocument();
}
 
Example 12
Source File: DomWriter.java    From cosmo with Apache License 2.0 5 votes vote down vote up
private static void writeElement(Element e, XMLStreamWriter writer) throws XMLStreamException {
    
    String local = e.getLocalName();
    if (local == null) {
        local = e.getNodeName();
    }

    String ns = e.getNamespaceURI();
    if (ns != null) {
        String prefix = e.getPrefix();
        if (prefix != null) {
            writer.writeStartElement(prefix, local, ns);
            writer.writeNamespace(prefix, ns);
        } else {
            writer.setDefaultNamespace(ns);
            writer.writeStartElement(ns, local);
            writer.writeDefaultNamespace(ns);
        }
    } else {
        writer.writeStartElement(local);
    }

    NamedNodeMap attributes = e.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        writeAttribute((Attr) attributes.item(i), writer);
    }

    NodeList children = e.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        writeNode(children.item(i), writer);
    }

    writer.writeEndElement();
}
 
Example 13
Source File: ExpressionTestCase.java    From ironjacamar with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Write
 * @throws Exception In case of an error
 */
@Ignore
public void testWrite() throws Exception
{
   DsParser parser = new DsParser();

   InputStream is = ExpressionTestCase.class.getClassLoader().
      getResourceAsStream("../../resources/test/ds/expression.xml");
   assertNotNull(is);

   StringBuilder sb = new StringBuilder();
   BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
   String line = br.readLine();
   while (line != null)
   {
      String data = line.trim();
      sb.append(data);
      if (!data.equals("") && !data.endsWith(">"))
         sb.append(" ");
      line = br.readLine();
   }

   is.close();

   is = ExpressionTestCase.class.getClassLoader().
      getResourceAsStream("../../resources/test/ds/expression.xml");
   assertNotNull(is);
   
   XMLStreamReader xsr = XMLInputFactory.newInstance().createXMLStreamReader(is);

   DataSources ds = parser.parse(xsr);
   assertNotNull(ds);

   is.close();

   StringWriter sw = new StringWriter();
   XMLStreamWriter xsw = XMLOutputFactory.newInstance().createXMLStreamWriter(sw);
   xsw.setDefaultNamespace("");

   xsw.writeStartDocument("UTF-8", "1.0");
   parser.store(ds, xsw);
   xsw.writeEndDocument();

   xsw.flush();
   xsw.close();

   assertEquals(sb.toString(), sw.toString());
}
 
Example 14
Source File: JpaProcessor.java    From karaf-boot with Apache License 2.0 4 votes vote down vote up
public void process(Writer writer, Map<PersistentUnit, List<? extends AnnotationMirror>> units) throws Exception {
    Set<String> puNames = new HashSet<String>();
    XMLOutputFactory xof =  XMLOutputFactory.newInstance();
    XMLStreamWriter w = new IndentingXMLStreamWriter(xof.createXMLStreamWriter(writer));
    w.setDefaultNamespace("http://java.sun.com/xml/ns/persistence");
    w.writeStartDocument();
    w.writeStartElement("persistence");
    w.writeAttribute("verson", "2.0");
    
    //w.println("<persistence version=\"2.0\" xmlns=\"http://java.sun.com/xml/ns/persistence\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\">");
    for (PersistentUnit pu : units.keySet()) {
        if (pu.name() == null || pu.name().isEmpty()) {
            throw new IOException("Missing persistent unit name");
        }
        if (!puNames.add(pu.name())) {
            throw new IOException("Duplicate persistent unit name: " + pu.name());
        }
        w.writeStartElement("persistence-unit");
        w.writeAttribute("name", pu.name());
        w.writeAttribute("transaction-type", pu.transactionType().toString());
        writeElement(w, "description", pu.description());
        String providerName = getProvider(pu);
        writeElement(w, "provider", providerName);
        writeElement(w, "jta-data-source", pu.jtaDataSource());
        writeElement(w, "non-jta-data-source", pu.nonJtaDataSource());
        Map<String, String> props = new HashMap<>();
        addProperties(pu, props);
        addAnnProperties(units.get(pu), props);
        if (props.size() > 0) {
            w.writeStartElement("properties");
            for (String key : props.keySet()) {
                w.writeEmptyElement("property");
                w.writeAttribute("name", key);
                w.writeAttribute("value", props.get(key));
            }
            w.writeEndElement();
        }
        w.writeEndElement();
    }
    w.writeEndElement();
    w.writeEndDocument();
    w.flush();
    w.close();
}
 
Example 15
Source File: StaxUtils.java    From cxf with Apache License 2.0 4 votes vote down vote up
public static void writeEvent(XMLEvent event, XMLStreamWriter writer)
    throws XMLStreamException {

    switch (event.getEventType()) {
    case XMLStreamConstants.START_ELEMENT:
        writeStartElementEvent(event, writer);
        break;
    case XMLStreamConstants.END_ELEMENT:
        writer.writeEndElement();
        break;
    case XMLStreamConstants.ATTRIBUTE:
        writeAttributeEvent(event, writer);
        break;
    case XMLStreamConstants.ENTITY_REFERENCE:
        writer.writeEntityRef(((javax.xml.stream.events.EntityReference)event).getName());
        break;
    case XMLStreamConstants.DTD:
        writer.writeDTD(((DTD)event).getDocumentTypeDeclaration());
        break;
    case XMLStreamConstants.PROCESSING_INSTRUCTION:
        if (((javax.xml.stream.events.ProcessingInstruction)event).getData() != null) {
            writer.writeProcessingInstruction(
                ((javax.xml.stream.events.ProcessingInstruction)event).getTarget(),
                ((javax.xml.stream.events.ProcessingInstruction)event).getData());
        } else {
            writer.writeProcessingInstruction(
                ((javax.xml.stream.events.ProcessingInstruction)event).getTarget());
        }
        break;
    case XMLStreamConstants.NAMESPACE:
        if (((Namespace)event).isDefaultNamespaceDeclaration()) {
            writer.writeDefaultNamespace(((Namespace)event).getNamespaceURI());
            writer.setDefaultNamespace(((Namespace)event).getNamespaceURI());
        } else {
            writer.writeNamespace(((Namespace)event).getPrefix(),
                                  ((Namespace)event).getNamespaceURI());
            writer.setPrefix(((Namespace)event).getPrefix(),
                             ((Namespace)event).getNamespaceURI());
        }
        break;
    case XMLStreamConstants.COMMENT:
        writer.writeComment(((javax.xml.stream.events.Comment)event).getText());
        break;
    case XMLStreamConstants.CHARACTERS:
    case XMLStreamConstants.SPACE:
        writer.writeCharacters(event.asCharacters().getData());
        break;
    case XMLStreamConstants.CDATA:
        writer.writeCData(event.asCharacters().getData());
        break;
    case XMLStreamConstants.START_DOCUMENT:
        if (((StartDocument)event).encodingSet()) {
            writer.writeStartDocument(((StartDocument)event).getCharacterEncodingScheme(),
                                      ((StartDocument)event).getVersion());

        } else {
            writer.writeStartDocument(((StartDocument)event).getVersion());
        }
        break;
    case XMLStreamConstants.END_DOCUMENT:
        writer.writeEndDocument();
        break;
    default:
        //shouldn't get here
    }
}
 
Example 16
Source File: ExpressionTestCase.java    From ironjacamar with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Write
 * @throws Exception In case of an error
 */
@Ignore
public void testWrite() throws Exception
{
   IronJacamarParser parser = new IronJacamarParser();

   InputStream is = ExpressionTestCase.class.getClassLoader().
      getResourceAsStream("../../resources/test/ironjacamar/expression.xml");
   assertNotNull(is);

   StringBuilder sb = new StringBuilder();
   BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
   String line = br.readLine();
   while (line != null)
   {
      String data = line.trim();
      sb.append(data);
      if (!data.equals("") && !data.endsWith(">"))
         sb.append(" ");
      line = br.readLine();
   }

   is.close();

   is = ExpressionTestCase.class.getClassLoader().
      getResourceAsStream("../../resources/test/ironjacamar/expression.xml");
   assertNotNull(is);
   
   XMLStreamReader xsr = XMLInputFactory.newInstance().createXMLStreamReader(is);

   Activation a = parser.parse(xsr);
   assertNotNull(a);

   is.close();

   StringWriter sw = new StringWriter();
   XMLStreamWriter xsw = XMLOutputFactory.newInstance().createXMLStreamWriter(sw);
   xsw.setDefaultNamespace("");

   xsw.writeStartDocument("UTF-8", "1.0");
   parser.store(a, xsw);
   xsw.writeEndDocument();

   xsw.flush();
   xsw.close();

   assertEquals(sb.toString(), sw.toString());
}
 
Example 17
Source File: DocumentStaxUtils.java    From gate-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Save annotations to the given XMLStreamWriter in XCES format. The
 * writer is <i>not</i> closed by this method, that is left to the
 * caller. This method writes just the cesAna element - the XML
 * declaration must be filled in by the caller if required. 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, nor are annotation types - an illegal character
 * in one of these will cause the serialization to fail.
 * 
 * @param annotations the annotations to save, typically an
 *          AnnotationSet
 * @param xsw the XMLStreamWriter to write to
 * @param includeId should we include the annotation IDs (as the "n"
 *          attribute on each <code>struct</code>)?
 * @throws XMLStreamException
 */
public static void writeXcesAnnotations(Collection<Annotation> annotations,
        XMLStreamWriter xsw, boolean includeId) throws XMLStreamException {
  List<Annotation> annotsToDump = new ArrayList<Annotation>(annotations);
  Collections.sort(annotsToDump, LONGEST_FIRST_OFFSET_COMPARATOR);

  xsw.setDefaultNamespace(XCES_NAMESPACE);
  xsw.writeStartElement(XCES_NAMESPACE, "cesAna");
  xsw.writeDefaultNamespace(XCES_NAMESPACE);
  xsw.writeAttribute("version", XCES_VERSION);
  newLine(xsw);

  String indent = "   ";
  String indentMore = indent + indent;

  for(Annotation a : annotsToDump) {
    long start = a.getStartNode().getOffset().longValue();
    long end = a.getEndNode().getOffset().longValue();
    FeatureMap fm = a.getFeatures();
    xsw.writeCharacters(indent);
    if(fm == null || fm.size() == 0) {
      xsw.writeEmptyElement(XCES_NAMESPACE, "struct");
    }
    else {
      xsw.writeStartElement(XCES_NAMESPACE, "struct");
    }
    xsw.writeAttribute("type", a.getType());
    xsw.writeAttribute("from", String.valueOf(start));
    xsw.writeAttribute("to", String.valueOf(end));
    // include the annotation ID as the "n" attribute if requested
    if(includeId) {
      xsw.writeAttribute("n", String.valueOf(a.getId()));
    }
    newLine(xsw);

    if(fm != null && fm.size() != 0) {
      for(Map.Entry<Object,Object> att : fm.entrySet()) {
        if(!"isEmptyAndSpan".equals(att.getKey())) {
          xsw.writeCharacters(indentMore);
          xsw.writeEmptyElement(XCES_NAMESPACE, "feat");
          xsw.writeAttribute("name", String.valueOf(att.getKey()));
          xsw.writeAttribute("value",
                  replaceXMLIllegalCharactersInString(String.valueOf(att
                          .getValue())));
          newLine(xsw);
        }
      }
      xsw.writeCharacters(indent);
      xsw.writeEndElement();
      newLine(xsw);
    }
  }

  xsw.writeEndElement();
  newLine(xsw);
}
 
Example 18
Source File: DocumentStaxUtils.java    From gate-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Write the specified GATE Document to an XMLStreamWriter. This
 * method writes just the GateDocument element - the XML declaration
 * must be filled in by the caller if required.
 * 
 * @param doc the Document to write
 * @param annotationSets the annotations to include. If the map
 *          contains an entry for the key <code>null</code>, this
 *          will be treated as the default set. All other entries are
 *          treated as named annotation sets.
 * @param xsw the StAX XMLStreamWriter to use for output
 * @throws XMLStreamException if an error occurs during writing
 */
public static void writeDocument(Document doc,
        Map<String, Collection<Annotation>> annotationSets,
        XMLStreamWriter xsw, String namespaceURI) throws XMLStreamException {
  xsw.setDefaultNamespace(namespaceURI);
  xsw.writeStartElement(namespaceURI, "GateDocument");
  xsw.writeAttribute("version", GATE_XML_VERSION);
  if(namespaceURI.length() > 0) {
    xsw.writeDefaultNamespace(namespaceURI);
  }
  newLine(xsw);
  // features
  xsw.writeComment(" The document's features");
  newLine(xsw);
  newLine(xsw);
  xsw.writeStartElement(namespaceURI, "GateDocumentFeatures");
  newLine(xsw);
  writeFeatures(doc.getFeatures(), xsw, namespaceURI);
  xsw.writeEndElement(); // GateDocumentFeatures
  newLine(xsw);
  // text with nodes
  xsw.writeComment(" The document content area with serialized nodes ");
  newLine(xsw);
  newLine(xsw);
  writeTextWithNodes(doc, annotationSets.values(), xsw, namespaceURI);
  newLine(xsw);
  // Serialize as XML all document's annotation sets
  // Serialize the default AnnotationSet
  StatusListener sListener = (StatusListener)gate.Gate
          .getListeners().get("gate.event.StatusListener");
  if(annotationSets.containsKey(null)) {
    if(sListener != null)
      sListener.statusChanged("Saving the default annotation set ");
    xsw.writeComment(" The default annotation set ");
    newLine(xsw);
    newLine(xsw);
    writeAnnotationSet(annotationSets.get(null), null, xsw, namespaceURI);
    newLine(xsw);
  }

  // Serialize all others AnnotationSets
  // namedAnnotSets is a Map containing all other named Annotation
  // Sets.
  //Iterator<String> iter = annotationSets.keySet().iterator();
  //while(iter.hasNext()) {
  for (Map.Entry<String,Collection<Annotation>> entry : annotationSets.entrySet()) {
    String annotationSetName = entry.getKey();//iter.next();
    // ignore the null entry, if present - we've already handled that
    // above
    if(annotationSetName != null) {
      Collection<Annotation> annots = entry.getValue();//annotationSets.get(annotationSetName);
      xsw.writeComment(" Named annotation set ");
      newLine(xsw);
      newLine(xsw);
      // Serialize it as XML
      if(sListener != null)
        sListener.statusChanged("Saving " + annotationSetName
                + " annotation set ");
      writeAnnotationSet(annots, annotationSetName, xsw, namespaceURI);
      newLine(xsw);
    }// End if
  }// End while
  
  Iterator<String> iter = annotationSets.keySet().iterator();
  while(iter.hasNext()) {
    
    writeRelationSet(doc.getAnnotations(iter.next()).getRelations(), xsw,
            namespaceURI);
  }

  // close the GateDocument element
  xsw.writeEndElement();
  newLine(xsw);
}
 
Example 19
Source File: ExpressionTestCase.java    From ironjacamar with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Write
 * @throws Exception In case of an error
 */
@Ignore
public void testWrite() throws Exception
{
   ResourceAdapterParser parser = new ResourceAdapterParser();

   InputStream is = ExpressionTestCase.class.getClassLoader().
      getResourceAsStream("../../resources/test/resourceadapter/expression.xml");
   assertNotNull(is);

   StringBuilder sb = new StringBuilder();
   BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
   String line = br.readLine();
   while (line != null)
   {
      String data = line.trim();
      sb.append(data);
      if (!data.equals("") && !data.endsWith(">"))
         sb.append(" ");
      line = br.readLine();
   }

   is.close();

   is = ExpressionTestCase.class.getClassLoader().
      getResourceAsStream("../../resources/test/resourceadapter/expression.xml");
   assertNotNull(is);
   
   XMLStreamReader xsr = XMLInputFactory.newInstance().createXMLStreamReader(is);

   Activations a = parser.parse(xsr);
   assertNotNull(a);

   is.close();

   StringWriter sw = new StringWriter();
   XMLStreamWriter xsw = XMLOutputFactory.newInstance().createXMLStreamWriter(sw);
   xsw.setDefaultNamespace("");

   xsw.writeStartDocument("UTF-8", "1.0");
   parser.store(a, xsw);
   xsw.writeEndDocument();

   xsw.flush();
   xsw.close();

   assertEquals(sb.toString(), sw.toString());
}
 
Example 20
Source File: XMLWriterHelper.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
public void writeResultElement(XMLStreamWriter xmlWriter, String name, ParamValue value,
		QName xsdType, int categoryType, int resultType, ExternalParamCollection params)
		throws XMLStreamException {
       if (xmlWriter == null) {
           return;
       }
	String nsPrefix;
	boolean writeNS;
	switch (resultType) {
	case DBConstants.ResultTypes.XML:			
		xmlWriter.writeStartElement(name);
		/* write default namespace */
	    nsPrefix = xmlWriter.getNamespaceContext().getPrefix(this.getNamespace());
		writeNS = nsPrefix == null || !"".equals(nsPrefix);				
	    if (writeNS) {
	    	xmlWriter.setDefaultNamespace(namespace);
	        xmlWriter.writeDefaultNamespace(namespace);
	    }
           if (value != null) {
		    this.writeElementValue(xmlWriter, value);
           }
		xmlWriter.writeEndElement();
		break;
	case DBConstants.ResultTypes.RDF:
		switch (categoryType) {
		case DBConstants.DataCategory.VALUE:
			/* <productCode rdf:datatype="http://www.w3.org/2001/XMLSchema#string">S10_1678</productCode> */
			xmlWriter.writeStartElement(this.getNamespace(), name);
			String dataTypeString = xsdType.getNamespaceURI() + "#" + xsdType.getLocalPart();
			xmlWriter.writeAttribute(DBConstants.RDF_NAMESPACE, 
					DBConstants.DBSFields.RDF_DATATYPE, dataTypeString);
			this.writeElementValue(xmlWriter, value);
			xmlWriter.writeEndElement();
			break;
		case DBConstants.DataCategory.REFERENCE:
			/* <productLine rdf:resource="http://productLines.com/Motorcycles/"/> */
			try {
				xmlWriter.writeStartElement(this.getNamespace(), name);
				String evalValue = DBUtils.evaluateString(value.toString(), params);
				xmlWriter.writeAttribute(DBConstants.RDF_NAMESPACE,
						DBConstants.DBSFields.RDF_RESOURCE, evalValue);
				xmlWriter.writeEndElement();
			} catch (DataServiceFault e) {
				throw new XMLStreamException("Error in writing result element using RDF", e);
			}
			break;
		}
	}		
}