Exemplo n.º 1
1
  private XMLStreamWriter getXmlStreamWriter(String fileName) {
    try {
      // to avoid filename with forbidden symbols
      fileName = Util.deleteForbiddenSymbols(fileName);

      // if for some XMLStreamWriter was run writeStartDocument,
      // run writeEndDocument and close it
      if (last != null) {
        last.writeEndDocument();
        last.close();
      }

      // if..., create XMLStreamWriter to out
      if (fileName == null) {
        last = XMLOutputFactory.newInstance().createXMLStreamWriter(System.out);
        // else, create XMLStreamWriter to file
      } else {
        last = XMLOutputFactory.newInstance().createXMLStreamWriter(new FileOutputStream(fileName));
      }

      last.writeStartDocument();
    } catch (XMLStreamException | FileNotFoundException e) {
      Util.handleException(e);
    }
    return last;
  }
Exemplo n.º 2
1
  /**
   * Serialize object to XML and output it to given OutputStream
   *
   * @param object objec to marshal
   * @param outputStream stream to put the resulting XML to
   */
  public void marshal(Object object, OutputStream outputStream) {
    try {
      XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
      outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
      ByteArrayOutputStream tempOutput = null;
      XMLStreamWriter writer = null;

      if (autoIndent) {
        tempOutput = new ByteArrayOutputStream();
        writer = outputFactory.createXMLStreamWriter(tempOutput);
      } else {
        writer = outputFactory.createXMLStreamWriter(outputStream);
      }

      //            if (autoIndent) {
      //                writer = new IndentingXMLStreamWriterDecorator(writer);
      //            }

      writerContext.writer = writer;

      writer.writeStartDocument();

      marshalObject(writer, object);

      writer.writeEndDocument();
      writer.close();

      if (autoIndent) {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.setOutputProperty("doctype-public", "yes");
        transformer.transform(
            new StreamSource(new ByteArrayInputStream(tempOutput.toByteArray())),
            new StreamResult(outputStream));
      }

    } catch (TransformerException ex) {
      throw new XmlizerException("Error whule indenting XML", ex);
    } catch (XMLStreamException ex) {
      throw new XmlizerException("Error occured while writting", ex);
    } catch (IllegalAccessException ex) {
      throw new XmlizerException("Error while trying to read a property", ex);
    } catch (IllegalArgumentException ex) {
      throw new XmlizerException("Error while trying to read a property", ex);
    } catch (InvocationTargetException ex) {
      throw new XmlizerException("Error while trying to read a property", ex);
    }
  }
    public void run() {
      try {
        FileOutputStream fos = new FileOutputStream("" + no);
        XMLStreamWriter w = getWriter(fos);
        // System.out.println("Writer="+w+" Thread="+Thread.currentThread());
        w.writeStartDocument();
        w.writeStartElement("hello");
        for (int j = 0; j < 50; j++) {
          w.writeStartElement("a" + j);
          w.writeEndElement();
        }
        w.writeEndElement();
        w.writeEndDocument();
        w.close();
        fos.close();

        FileInputStream fis = new FileInputStream("" + no);
        XMLStreamReader r = getReader(fis);
        while (r.hasNext()) {
          r.next();
        }
        r.close();
        fis.close();
      } catch (Exception e) {
        Assert.fail(e.getMessage());
      }
    }
Exemplo n.º 4
0
 public void startDocument() {
   try {
     out.writeStartDocument();
   } catch (XMLStreamException e) {
     throw new TxwException(e);
   }
 }
Exemplo n.º 5
0
  /**
   * Creates the <a href="http://wiki.mindmakers.org/projects:BML:main">Behavior Markup Language</a>
   * string for Avatar.
   *
   * @param utterance the utterance to speak <code>null</code>
   * @param ssml SSML with BML annotations
   * @return created XML string
   * @throws XMLStreamException if the stream could not be created.
   */
  private String createBML(final String utterance, final SsmlDocument ssml)
      throws XMLStreamException {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final XMLOutputFactory factory = XMLOutputFactory.newInstance();
    final XMLStreamWriter writer = factory.createXMLStreamWriter(out, ENCODING);
    writer.writeStartDocument(ENCODING, "1.0");
    writer.writeStartElement("bml");
    writer.writeAttribute("id", "bml1");
    writer.writeNamespace("ns1", BML_NAMESPACE_URI);
    if (ssml != null) {
      final Speak speak = ssml.getSpeak();
      final NodeList children = speak.getChildNodes();
      for (int i = 0; i < children.getLength(); i++) {
        final Node child = children.item(i);
        final String namespace = child.getNamespaceURI();
        if (namespace != null) {
          writeBMLNode(writer, child, utterance);
        }
      }
    }

    writer.writeEndElement();
    writer.writeEndDocument();
    writer.flush();
    // lastGestureEndTime = 0;
    writer.close();
    try {
      String output = out.toString(ENCODING);
      return output;
    } catch (UnsupportedEncodingException e) {
      LOGGER.warn(e.getMessage(), e);
      return out.toString();
    }
  }
  public static void doXmlOutput(boolean useRepairing) throws XMLStreamException {
    StringWriter buffer = new StringWriter();
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    if (useRepairing) {
      outputFactory.setProperty("javax.xml.stream.isRepairingNamespaces", Boolean.TRUE);
    }
    XMLStreamWriter out = outputFactory.createXMLStreamWriter(buffer);
    out.writeStartDocument();
    out.writeStartElement("env", "Envelope", SOAP12);
    out.writeNamespace("env", SOAP12);
    out.writeNamespace("test", "http://someTestUri");
    out.writeStartElement("env", "Body", SOAP12);

    out.writeStartElement("test");
    out.writeAttribute("foo", "bar");
    out.writeEndElement();

    out.writeStartElement("test");
    out.writeAttribute("foo", "bar");
    out.writeCharacters("");
    out.writeEndElement();

    out.writeStartElement("test");
    out.writeAttribute("foo", "bar");
    out.writeCharacters(" ");
    out.writeEndElement();

    out.writeEndElement();
    out.writeEndElement();

    out.writeEndDocument();
    out.close();
    System.out.println("Created " + (useRepairing ? "" : "not") + " using repairing :-");
    System.out.println(buffer);
  }
Exemplo n.º 7
0
  /**
   * @param args
   * @throws Exception
   */
  public static void main(String[] args) throws Exception {
    try {
      String fileName = null;
      try {
        if (args[0].equals("-f")) {
          fileName = args[1];
        } else {
          printUsage();
          return;
        }
      } catch (Exception ex) {
        printUsage();
        return;
      }

      XMLOutputFactory xof = XMLOutputFactory.newInstance();
      XMLStreamWriter xtw = null;
      xtw = xof.createXMLStreamWriter(new FileOutputStream(fileName), "utf-8");
      xtw.writeStartDocument("utf-8", "1.0");
      xtw.writeComment("StAX Sample: writer.HelloWorld");
      xtw.writeStartElement("hello");
      xtw.writeDefaultNamespace("http://samples");
      xtw.writeCharacters("this crazy");
      xtw.writeEmptyElement("world");
      xtw.writeEndElement();
      xtw.writeEndDocument();
      xtw.flush();
      xtw.close();
    } catch (Exception ex) {
      ex.printStackTrace();
      System.err.println("Exception occurred while running Hello World samples");
    }
    System.out.println("Done");
  }
  private void initialiseProjectFiles(
      IProject project, IContainer container, IProgressMonitor monitor) throws CoreException {

    // create a config Dir
    IFolder configFolder = project.getFolder("config");
    configFolder.create(false, true, null);
    File configDir = configFolder.getLocation().toFile();

    monitor.beginTask("Creating config file ", 1);

    XMLOutputFactory factory = XMLOutputFactory.newInstance();

    try {
      XMLStreamWriter writer =
          factory.createXMLStreamWriter(
              new FileWriter(configDir.getAbsolutePath() + "\\config.xml"));

      writer.writeStartDocument();
      writer.writeStartElement("document");
      writer.writeStartElement("data");
      writer.writeAttribute("name", "value");
      writer.writeEndElement();
      writer.writeEndElement();
      writer.writeEndDocument();

      writer.flush();
      writer.close();

    } catch (XMLStreamException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 9
0
  /**
   * Generiert zu einem Scratch-Programm eine XML-Repräsentation und liefert diese als String
   *
   * @param program
   * @return
   */
  public static String toXML(ScratchProgram program) {
    XMLStreamWriter writer = null;
    StringWriter strWriter = new StringWriter();

    try {
      XMLOutputFactory factory = XMLOutputFactory.newInstance();
      writer = factory.createXMLStreamWriter(strWriter);
      writer.writeStartDocument();
      writer.writeStartElement(ScratchHamsterFile.SCRATCH_TAG);

      StorageController controller = program.getProgram();
      if (controller != null) {
        program.getProgram().toXML(writer);
      }

      writer.writeEndElement();
      writer.writeEndDocument();
    } catch (Throwable exc) {
      exc.printStackTrace();
    } finally {
      try {
        if (writer != null) {
          writer.close();
        }
      } catch (Throwable exc) {
        exc.printStackTrace();
      }
    }
    return strWriter.toString();
  }
  /**
   * Serialize the given event data as a standalone XML document
   *
   * @param includeProlog if true, include an XML prolog; if not, just render a document fragment
   * @return the XML serialization, or null if <code>data</code> is null.
   */
  public String serialize(EventDataElement data, boolean includeProlog) {
    if (data == null || data.isNull()) return null;

    try {
      // serialize the DOM to our string buffer.
      XMLStreamWriter writer = factory.createXMLStreamWriter(buffer);
      try {
        if (includeProlog) writer.writeStartDocument();
        serializeElement(writer, data);
        writer.writeEndDocument();
        writer.flush();
      } finally {
        writer.close();
      }

      // return buffer contents.
      return buffer.toString();

    } catch (XMLStreamException ioe) {
      // this shouldn't happen, since the target output stream is a StringWriter, but
      // the compiler demands that we handle it.
      throw new RuntimeException("Error serializing XML data", ioe);
    } finally {

      // reset the internal buffer for next run.
      buffer.getBuffer().setLength(0);
    }
  }
Exemplo n.º 11
0
  /**
   * makes a {@link Document} out of a {@link XMLStreamReader}
   *
   * @param xmlStreamReader the xmlStreamRader to convert
   * @return the xmlStreamRader as {@link Document}
   * @throws FactoryConfigurationError
   * @throws XMLStreamException
   * @throws ParserConfigurationException
   * @throws IOException
   * @throws SAXException
   */
  public static Document getAsDocument(XMLStreamReader xmlStreamReader)
      throws XMLStreamException, FactoryConfigurationError, ParserConfigurationException,
          SAXException, IOException {
    StreamBufferStore store = new StreamBufferStore();
    XMLStreamWriter xmlWriter = null;
    try {
      xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(store);
      xmlWriter.writeStartDocument();
      XMLAdapter.writeElement(xmlWriter, xmlStreamReader);
    } finally {
      if (xmlWriter != null) {
        try {
          xmlWriter.close();
        } catch (XMLStreamException e) {
          LOG.error("Unable to close xmlwriter.");
        }
      }
    }

    store.flush();
    DOMParser parser = new DOMParser();
    parser.parse(new InputSource(store.getInputStream()));
    Document doc = parser.getDocument();
    store.close();
    return doc;
  }
Exemplo n.º 12
0
  public static void marshell(VDBMetaData vdb, OutputStream out)
      throws XMLStreamException, IOException {
    XMLStreamWriter writer = XMLOutputFactory.newFactory().createXMLStreamWriter(out);

    writer.writeStartDocument();
    writer.writeStartElement(Element.VDB.getLocalName());
    writeAttribute(writer, Element.NAME.getLocalName(), vdb.getName());
    writeAttribute(writer, Element.VERSION.getLocalName(), String.valueOf(vdb.getVersion()));

    if (vdb.getDescription() != null) {
      writeElement(writer, Element.DESCRIPTION, vdb.getDescription());
    }
    writeProperties(writer, vdb.getProperties());

    for (VDBImport vdbImport : vdb.getVDBImports()) {
      writer.writeStartElement(Element.IMPORT_VDB.getLocalName());
      writeAttribute(writer, Element.NAME.getLocalName(), vdbImport.getName());
      writeAttribute(
          writer, Element.VERSION.getLocalName(), String.valueOf(vdbImport.getVersion()));
      writeAttribute(
          writer,
          Element.IMPORT_POLICIES.getLocalName(),
          String.valueOf(vdbImport.isImportDataPolicies()));
      writer.writeEndElement();
    }

    // models
    Collection<ModelMetaData> models = vdb.getModelMetaDatas().values();
    for (ModelMetaData model : models) {
      writeModel(writer, model);
    }

    // override translators
    for (Translator translator : vdb.getOverrideTranslators()) {
      writeTranslator(writer, translator);
    }

    // data-roles
    for (DataPolicy dp : vdb.getDataPolicies()) {
      writeDataPolicy(writer, dp);
    }

    // entry
    // designer only
    for (EntryMetaData em : vdb.getEntries()) {
      writer.writeStartElement(Element.ENTRY.getLocalName());
      writeAttribute(writer, Element.PATH.getLocalName(), em.getPath());
      if (em.getDescription() != null) {
        writeElement(writer, Element.DESCRIPTION, em.getDescription());
      }
      writeProperties(writer, em.getProperties());
      writer.writeEndElement();
    }

    writer.writeEndElement();
    writer.writeEndDocument();
    writer.close();
    out.close();
  }
Exemplo n.º 13
0
  public void testEncodingXmlStreamReader() throws Exception {
    TEST_XML_WITH_XML_HEADER_ISO_8859_1_AS_BYTE_ARRAY_STREAM.reset();

    XMLStreamReader reader = null;
    XMLStreamWriter writer = null;
    ByteArrayOutputStream output = null;
    try {
      // enter text encoded with Latin1
      reader =
          context
              .getTypeConverter()
              .mandatoryConvertTo(
                  XMLStreamReader.class, TEST_XML_WITH_XML_HEADER_ISO_8859_1_AS_BYTE_ARRAY_STREAM);

      output = new ByteArrayOutputStream();
      // ensure UTF-8 encoding
      Exchange exchange = new DefaultExchange(context);
      exchange.setProperty(Exchange.CHARSET_NAME, UTF_8.name());
      writer =
          context.getTypeConverter().mandatoryConvertTo(XMLStreamWriter.class, exchange, output);
      // copy to writer
      while (reader.hasNext()) {
        reader.next();
        switch (reader.getEventType()) {
          case XMLEvent.START_DOCUMENT:
            writer.writeStartDocument();
            break;
          case XMLEvent.END_DOCUMENT:
            writer.writeEndDocument();
            break;
          case XMLEvent.START_ELEMENT:
            writer.writeStartElement(reader.getName().getLocalPart());
            break;
          case XMLEvent.CHARACTERS:
            writer.writeCharacters(reader.getText());
            break;
          case XMLEvent.END_ELEMENT:
            writer.writeEndElement();
            break;
          default:
            break;
        }
      }
    } finally {
      if (reader != null) {
        reader.close();
      }
      if (writer != null) {
        writer.close();
      }
    }
    assertNotNull(output);

    String result = new String(output.toByteArray(), UTF_8.name());

    assertEquals(TEST_XML, result);
  }
Exemplo n.º 14
0
 public void marshall(Writer wrt, Object value) throws Exception {
   assert wrt != null && value != null;
   // get an XMl factory for use..
   XMLOutputFactory xmlFactory = XMLOutputFactory.newInstance();
   XMLStreamWriter xwrt = xmlFactory.createXMLStreamWriter(wrt);
   xwrt.writeStartDocument();
   marshall(xwrt, (Boolean) value);
   xwrt.writeEndDocument();
 }
Exemplo n.º 15
0
 public XMLExporter(OutputStream outputStream) {
   try {
     out = new OutputStreamWriter(new GZIPOutputStream(outputStream), "UTF-8");
     writer = factory.createXMLStreamWriter(out);
     writer.writeStartDocument("utf-8", "1.0");
     writer.writeStartElement("add");
   } catch (IOException | XMLStreamException e) {
     throw new RuntimeException("cannot create solr xml file", e);
   }
 }
Exemplo n.º 16
0
  @Override
  public void writeTo(
      T obj,
      Class<?> type,
      Type genericType,
      Annotation[] anns,
      MediaType m,
      MultivaluedMap<String, Object> headers,
      OutputStream os)
      throws IOException {
    if (type == null) {
      type = obj.getClass();
    }
    if (genericType == null) {
      genericType = type;
    }
    AegisContext context = getAegisContext(type, genericType);
    AegisType aegisType = context.getTypeMapping().getType(genericType);
    AegisWriter<XMLStreamWriter> aegisWriter = context.createXMLStreamWriter();
    try {
      W3CDOMStreamWriter w3cStreamWriter = new W3CDOMStreamWriter();
      XMLStreamWriter spyingWriter =
          new PrefixCollectingXMLStreamWriter(w3cStreamWriter, namespaceMap);
      spyingWriter.writeStartDocument();
      // use type qname as element qname?
      aegisWriter.write(obj, aegisType.getSchemaType(), false, spyingWriter, aegisType);
      spyingWriter.writeEndDocument();
      spyingWriter.close();
      Document dom = w3cStreamWriter.getDocument();
      // ok, now the namespace map has all the prefixes.

      XMLStreamWriter xmlStreamWriter = createStreamWriter(aegisType.getSchemaType(), os);
      xmlStreamWriter.writeStartDocument();
      StaxUtils.copy(dom, xmlStreamWriter);
      // Jettison needs, and StaxUtils.copy doesn't do it.
      xmlStreamWriter.writeEndDocument();
      xmlStreamWriter.flush();
      xmlStreamWriter.close();
    } catch (Exception e) {
      throw new WebApplicationException(e);
    }
  }
Exemplo n.º 17
0
  @Override
  public void writeTo(
      DocBase doc,
      Class<?> genericType,
      Type type,
      Annotation[] annotations,
      MediaType mediaType,
      MultivaluedMap<String, Object> httpHeaders,
      OutputStream out)
      throws IOException, WebApplicationException {
    XMLStreamWriter xmlStreamWriter = null;
    try {
      OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
      XMLOutputFactory factory = XMLOutputFactory.newInstance();
      xmlStreamWriter = factory.createXMLStreamWriter(osw);
      xmlStreamWriter.writeStartDocument("UTF-8", "1.0");
      xmlStreamWriter.writeStartElement("document");
      xmlStreamWriter.writeAttribute("id", Long.toString(doc.getId()));
      xmlStreamWriter.writeAttribute("mediaType", doc.getMediaType());
      if (doc.getSchemaURI() != null) {
        xmlStreamWriter.writeAttribute("schema", doc.getSchemaURI());
      }
      if (doc.getStatus() != null) {
        xmlStreamWriter.writeAttribute("status", doc.getStatus());
      }
      xmlStreamWriter.writeAttribute("authorId", Long.toString(doc.getAuthor().getId()));
      xmlStreamWriter.writeAttribute(
          "signatureRequired", doc.isSignatureRequired() ? "true" : "false");
      xmlStreamWriter.writeStartElement("attachments");
      List<DocAttachment> attachments = getDocBean().findAttachments(doc);
      for (DocAttachment attachment : attachments) {
        xmlStreamWriter.writeStartElement("attachment");
        xmlStreamWriter.writeAttribute("id", Long.toString(attachment.getId()));
        xmlStreamWriter.writeAttribute("description", attachment.getDescription());
        xmlStreamWriter.writeAttribute(
            "documentId", Long.toString(attachment.getAttachedDocument().getId()));
        xmlStreamWriter.writeEndElement();
      }
      xmlStreamWriter.writeEndElement();
      xmlStreamWriter.writeEndElement();
      xmlStreamWriter.writeEndDocument();

    } catch (Exception e) {
      throw new RuntimeException("Exception writing user account list", e);
    } finally {
      if (xmlStreamWriter != null) {
        try {
          xmlStreamWriter.close();
        } catch (XMLStreamException e) {
          throw new RuntimeException("Error closing XML Stream writing UserAccounts", e);
        }
      }
    }
  }
 public void startDocument() {
   try {
     writer.writeStartDocument();
     this.writer.writeCharacters(NEW_LINE);
     this.writer.writeCharacters(NEW_LINE);
     writer.writeStartElement("project");
     this.offset++;
   } catch (XMLStreamException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Exemplo n.º 19
0
  public static void main(String[] args) {
    // TODO Auto-generated method stub

    if (args.length != 1) {
      System.out.println();
    } else {
      XMLOutputFactory factory = XMLOutputFactory.newFactory();
      try (FileOutputStream fos = new FileOutputStream(args[0])) {
        XMLStreamWriter writer = factory.createXMLStreamWriter(fos, "UTF-8");
        writer.writeStartDocument();
        writer.writeCharacters("\n");
        writer.writeStartElement("clientes");
        writer.writeCharacters("\n");

        Cliente c1 =
            new Cliente("Diego", "Torres", "andalucia", "*****@*****.**", "333333333", 12341234);
        Cliente c2 =
            new Cliente(
                "Pedro", "Martinez", "calle martos", "*****@*****.**", "333332233", 53441234);

        List<Cliente> listaClientes = new ArrayList<>();
        listaClientes.add(c1);
        listaClientes.add(c2);

        for (Cliente cliente : listaClientes) {
          writer.writeStartElement("cliente");
          writer.writeAttribute("dni", cliente.getNombre());
          writer.writeStartElement("nombre");
          writer.writeCharacters(cliente.getNombre());
          writer.writeEndElement();
          writer.writeStartElement("apellidos");
          writer.writeCharacters(cliente.getApellidos());
          writer.writeEndElement();
          writer.writeStartElement("direccion");
          writer.writeCharacters(cliente.getDireccion());
          writer.writeEndElement();
          writer.writeStartElement("email");
          writer.writeCharacters(cliente.getEmail());
          writer.writeEndElement();
          writer.writeStartElement("telefono");
          writer.writeCharacters(cliente.getTelefono());
          writer.writeEndElement();
        }

        writer.writeEndElement();
        writer.writeEndDocument();
        writer.close();
      } catch (IOException | XMLStreamException e) {
        // TODO Auto-generated catch block
        Logger.getLogger(GestionXML.class.getName()).log(Level.SEVERE, null, e);
      }
    }
  }
Exemplo n.º 20
0
  protected String createXMLParameter(
      String ID,
      String checksum,
      String domain,
      String projectName,
      String entryType,
      String dataTime,
      String experimentId)
      throws XMLStreamException, FactoryConfigurationError {
    String messageParameter = "";

    StringWriter res = new StringWriter();
    XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(res);
    writer.writeStartDocument();

    writer.writeStartElement(propertiesXML.getProperty("root.element"));

    writer.writeStartElement(propertiesXML.getProperty("child.experiment.id"));
    writer.writeCharacters(String.valueOf(experimentId));
    writer.writeEndElement();

    writer.writeStartElement(propertiesXML.getProperty("child.id"));
    writer.writeCharacters(String.valueOf(ID));
    writer.writeEndElement();

    writer.writeStartElement(propertiesXML.getProperty("child.checksum"));
    writer.writeCharacters(String.valueOf(checksum));
    writer.writeEndElement();

    writer.writeStartElement(propertiesXML.getProperty("child.domain"));
    writer.writeCharacters(String.valueOf(domain));
    writer.writeEndElement();

    writer.writeStartElement(propertiesXML.getProperty("child.project"));
    writer.writeCharacters(String.valueOf(projectName));
    writer.writeEndElement();

    writer.writeStartElement(propertiesXML.getProperty("child.entry.type"));
    writer.writeCharacters(String.valueOf(entryType));
    writer.writeEndElement();

    writer.writeStartElement(propertiesXML.getProperty("child.date.time"));
    writer.writeCharacters(String.valueOf(dataTime));
    writer.writeEndElement();

    writer.writeEndElement();
    writer.writeEndDocument();

    messageParameter = res.toString();

    return messageParameter;
  }
  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();
  }
Exemplo n.º 22
0
 // @Override
 public void load(Access access) throws MappableException, UserException {
   try {
     content = new Binary();
     OutputStream ob = content.getOutputStream();
     XMLOutputFactory xof = XMLOutputFactory.newInstance();
     OutputStreamWriter out = new OutputStreamWriter(ob, "UTF8");
     xtw = xof.createXMLStreamWriter(out);
     xtw.writeStartDocument("UTF-8", "1.0");
     xtw.setPrefix("", docSpecUrl);
     xtw.writeCharacters("\n");
   } catch (Exception e) {
     throw new UserException(450, e.getMessage());
   }
 }
Exemplo n.º 23
0
  public static void main(String[] args) {
    try {
      // FLUJO DE ESCRITURA
      XMLStreamWriter sw =
          XMLOutputFactory.newInstance().createXMLStreamWriter(new FileOutputStream("autores.xml"));

      // ESCRITURA
      sw.writeStartDocument("1.0");
      sw.writeStartElement("autores");
      sw.writeStartElement("autor");
      sw.writeAttribute("codigo", "a1");
      sw.writeStartElement("nome");
      sw.writeCharacters("Alexandre Dumas");
      sw.writeEndElement();
      sw.writeStartElement("titulo");
      sw.writeCharacters("El conde de montecristo");
      sw.writeEndElement();
      sw.writeStartElement("titulo");
      sw.writeCharacters("Los miserables");
      sw.writeEndElement();
      sw.writeEndElement();
      sw.writeStartElement("autor");
      sw.writeAttribute("codigo", "a2");
      sw.writeStartElement("nome");
      sw.writeCharacters("Fiodor Dostoyevski");
      sw.writeEndElement();
      sw.writeStartElement("titulo");
      sw.writeCharacters(" El idiota");
      sw.writeEndElement();
      sw.writeStartElement("titulo");
      sw.writeCharacters("Noches blancas");
      sw.writeEndDocument();
      sw.flush();
      sw.close();

      // FLUJO DE LECTURA
      XMLEventReader er =
          XMLInputFactory.newInstance()
              .createXMLEventReader("autores.xml", new FileInputStream("autores.xml"));

      // LECTURA
      while (er.hasNext()) {
        System.out.println(er.nextEvent().toString());
      }
      er.close();

    } catch (XMLStreamException | FileNotFoundException ex) {
      Logger.getLogger(XMLprueba0.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
Exemplo n.º 24
0
 @Override
 public void writeStart(final Optional<String> title) throws IOException {
   try {
     xmlWriter.writeStartDocument();
     xmlWriter.setDefaultNamespace(NAMESPACE);
     xmlWriter.writeStartElement("report");
     xmlWriter.writeNamespace(null, NAMESPACE);
     if (title.isPresent()) {
       xmlWriter.writeAttribute("title", title.get());
     }
   } catch (XMLStreamException e) {
     throw new IOException(e);
   }
 }
Exemplo n.º 25
0
  private String pullNextXmlChunkFromTopElementOnStack(XMLChunkerState data)
      throws KettleException {
    Stack<String> elementStack = data.getElementStack();
    XMLStreamReader xmlStreamReader = data.getXmlStreamReader();

    int elementStackDepthOnEntry = elementStack.size();
    StringWriter stringWriter = new StringWriter();

    try {
      XMLStreamWriter xmlStreamWriter =
          data.getXmlOutputFactory().createXMLStreamWriter(stringWriter);

      xmlStreamWriter.writeStartDocument(CharEncoding.UTF_8, "1.0");

      // put the current element on because presumably it's the open element for the one
      // that is being looked for.

      XmlReaderToWriter.write(xmlStreamReader, xmlStreamWriter);

      while (xmlStreamReader.hasNext() & elementStack.size() >= elementStackDepthOnEntry) {

        switch (xmlStreamReader.next()) {
          case XMLStreamConstants.END_DOCUMENT:
            break; // handled below explicitly.

          case XMLStreamConstants.END_ELEMENT:
            elementStack.pop();
            XmlReaderToWriter.write(xmlStreamReader, xmlStreamWriter);
            break;

          case XMLStreamConstants.START_ELEMENT:
            elementStack.push(xmlStreamReader.getLocalName());
            XmlReaderToWriter.write(xmlStreamReader, xmlStreamWriter);
            break;

          default:
            XmlReaderToWriter.write(xmlStreamReader, xmlStreamWriter);
            break;
        }
      }

      xmlStreamWriter.writeEndDocument();
      xmlStreamWriter.close();
    } catch (Exception e) {
      throw new KettleException("unable to process a chunk of the xero xml stream", e);
    }

    return stringWriter.toString();
  }
Exemplo n.º 26
0
  public static String getEndpointDescriptionXML(EndpointDescription endpoint)
      throws XMLStreamException {
    Map<String, Object> properties = endpoint.getProperties();
    StringWriter writer = new StringWriter();
    XMLStreamWriter xml = XMLOutputFactory.newInstance().createXMLStreamWriter(writer);

    xml.writeStartDocument();
    xml.setDefaultNamespace(REMOTE_SERVICES_ADMIN_NS);
    xml.writeStartElement(REMOTE_SERVICES_ADMIN_NS, ENDPOINT_DESCRIPTIONS);
    xml.writeNamespace("", REMOTE_SERVICES_ADMIN_NS);
    xml.writeStartElement(REMOTE_SERVICES_ADMIN_NS, ENDPOINT_DESCRIPTION);

    for (Map.Entry<String, Object> entry : properties.entrySet()) {
      String key = entry.getKey();
      Object val = entry.getValue();
      xml.writeStartElement(REMOTE_SERVICES_ADMIN_NS, PROPERTY);
      xml.writeAttribute(NAME, key);
      if (val.getClass().isArray()) {
        setValueType(xml, val.getClass().getComponentType().getName());
        xml.writeStartElement(REMOTE_SERVICES_ADMIN_NS, ARRAY);
        for (int i = 0, l = Array.getLength(val); i < l; i++) {
          xml.writeStartElement(REMOTE_SERVICES_ADMIN_NS, VALUE);
          xml.writeCharacters(Array.get(val, i).toString());
          xml.writeEndElement();
        }
        xml.writeEndElement();
      } else if (val instanceof List) {
        xml.writeStartElement(REMOTE_SERVICES_ADMIN_NS, LIST);
        handleCollectionValue(xml, (Collection) val);
        xml.writeEndElement();
      } else if (val instanceof Set) {
        xml.writeStartElement(REMOTE_SERVICES_ADMIN_NS, SET);
        handleCollectionValue(xml, (Collection) val);
        xml.writeEndElement();
      } else {
        xml.writeAttribute(VALUE, val.toString());
        setValueType(xml, val.getClass().getName());
      }
      xml.writeEndElement();
    }

    xml.writeEndElement();
    xml.writeEndElement();
    xml.writeEndDocument();
    xml.close();

    return writer.toString();
  }
Exemplo n.º 27
0
  @Override
  public void write(final String filename) throws DITAOTException {
    OutputStream out = null;
    XMLStreamWriter serializer = null;
    try {
      out = new FileOutputStream(filename);
      // boolean for processing indexsee the new markup (Eclipse 3.6 feature).
      boolean indexsee = false;

      // RFE 2987769 Eclipse index-see
      if (this.getPipelineHashIO() != null) {
        indexsee = Boolean.valueOf(this.getPipelineHashIO().getAttribute("eclipse.indexsee"));
        targetExt = this.getPipelineHashIO().getAttribute(ANT_INVOKER_EXT_PARAM_TARGETEXT);
      }

      serializer = XMLOutputFactory.newInstance().createXMLStreamWriter(out);

      serializer.writeStartDocument();
      serializer.writeStartElement("index");
      // Clone the list of indexterms so we can look for see references
      termCloneList = cloneIndextermList(termList);
      final int termNum = termList.size();
      for (int i = 0; i < termNum; i++) {
        final IndexTerm term = termList.get(i);
        outputIndexTerm(term, serializer, indexsee);
      }
      serializer.writeEndElement(); // index
      serializer.writeEndDocument();
    } catch (final Exception e) {
      throw new DITAOTException(e);
    } finally {
      if (serializer != null) {
        try {
          serializer.close();
        } catch (final XMLStreamException e) {
          logger.logError(e.getMessage(), e);
        }
      }
      if (out != null) {
        try {
          out.close();
        } catch (final IOException e) {
          logger.logError(e.getMessage(), e);
        }
      }
    }
  }
 public byte[] serialize(MediaContent content) throws Exception {
   ByteArrayOutputStream baos = new ByteArrayOutputStream(expectedSize);
   XMLStreamWriter writer = outFactory.createXMLStreamWriter(baos, "UTF-8");
   writer.writeStartDocument("UTF-8", "1.0");
   writer.writeStartElement("mc");
   writeMedia(writer, content.getMedia());
   for (int i = 0, len = content.imageCount(); i < len; ++i) {
     writeImage(writer, content.getImage(i));
   }
   writer.writeEndElement();
   writer.writeEndDocument();
   writer.flush();
   writer.close();
   byte[] array = baos.toByteArray();
   expectedSize = array.length;
   return array;
 }
Exemplo n.º 29
0
  @Override
  public int writeData(OutputStream out, DbData data) throws Exception {
    XMLStreamWriter sw = _staxOutFactory.createXMLStreamWriter(out, "UTF-8");
    sw.writeStartDocument();
    sw.writeStartElement(FIELD_TABLE);
    Iterator<DbRow> it = data.rows();
    while (it.hasNext()) {
      DbRow row = it.next();
      sw.writeStartElement(FIELD_ROW); // <row>

      sw.writeStartElement(DbRow.Field.id.name());
      sw.writeCharacters(String.valueOf(row.getId()));
      sw.writeEndElement();

      sw.writeStartElement(DbRow.Field.firstname.name());
      sw.writeCharacters(row.getFirstname());
      sw.writeEndElement();

      sw.writeStartElement(DbRow.Field.lastname.name());
      sw.writeCharacters(row.getLastname());
      sw.writeEndElement();

      sw.writeStartElement(DbRow.Field.zip.name());
      sw.writeCharacters(String.valueOf(row.getZip()));
      sw.writeEndElement();

      sw.writeStartElement(DbRow.Field.street.name());
      sw.writeCharacters(row.getStreet());
      sw.writeEndElement();

      sw.writeStartElement(DbRow.Field.city.name());
      sw.writeCharacters(row.getCity());
      sw.writeEndElement();

      sw.writeStartElement(DbRow.Field.state.name());
      sw.writeCharacters(row.getState());
      sw.writeEndElement();

      sw.writeEndElement(); // </row>
    }
    sw.writeEndElement();
    sw.writeEndDocument();
    sw.close();
    return -1;
  }
  /**
   * This method should be called when the StreamMessage is created with a payload
   *
   * @param writer
   */
  private void writeEnvelope(XMLStreamWriter writer) throws XMLStreamException {
    writer.writeStartDocument();
    envelopeTag.writeStart(writer);

    // write headers
    HeaderList hl = getHeaders();
    if (hl.size() > 0) {
      headerTag.writeStart(writer);
      for (Header h : hl) {
        h.writeTo(writer);
      }
      writer.writeEndElement();
    }
    bodyTag.writeStart(writer);
    if (hasPayload()) {
      writePayloadTo(writer);
    }
    writer.writeEndElement();
    writer.writeEndElement();
    writer.writeEndDocument();
  }