Esempio n. 1
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);
    }
  }
 private XmlGenerator(final Writer writer) throws XMLStreamException {
   final XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
   if (prettyPrint) {
     xmlWriter = new IndentingXmlWriter(xmlOutputFactory.createXMLStreamWriter(writer));
   } else {
     xmlWriter = xmlOutputFactory.createXMLStreamWriter(writer);
   }
 }
  /**
   * Execute the task - write the template tracks as XML.
   *
   * @throws BuildException if there is a problem while writing to the file or reading the template
   *     tracks.
   */
  public void execute() {
    if (fileName == null) {
      throw new BuildException("fileName parameter not set");
    }

    FileWriter fw = null;
    try {
      fw = new FileWriter(fileName);
    } catch (IOException e) {
      throw new BuildException("failed to open output file: " + fileName, e);
    }

    try {
      ObjectStoreWriter userProfileOS =
          ObjectStoreWriterFactory.getObjectStoreWriter(userProfileAlias);

      XMLOutputFactory factory = XMLOutputFactory.newInstance();
      XMLStreamWriter writer = factory.createXMLStreamWriter(fw);
      TemplateTrackBinding.marshal(userProfileOS, writer);
    } catch (Exception e) {
      throw new BuildException(e);
    } finally {
      try {
        fw.close();
      } catch (IOException e) {
        throw new BuildException("failed to close output file: " + fileName, e);
      }
    }
  }
  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();
    }
  }
Esempio n. 5
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");
  }
Esempio n. 6
0
  protected XMLStreamWriter getStreamWriter(Object obj, OutputStream os, MediaType mt) {
    XMLStreamWriter writer = null;
    MessageContext mc = getContext();
    if (mc != null) {
      writer = mc.getContent(XMLStreamWriter.class);
      if (writer == null) {
        XMLOutputFactory factory = (XMLOutputFactory) mc.get(XMLOutputFactory.class.getName());
        if (factory != null) {
          try {
            writer = factory.createXMLStreamWriter(os);
          } catch (XMLStreamException e) {
            throw ExceptionUtils.toInternalServerErrorException(
                new RuntimeException("Cant' create XMLStreamWriter", e), null);
          }
        }
      }
      if (writer == null && getEnableStreaming()) {
        writer = StaxUtils.createXMLStreamWriter(os);
      }
    }

    if (writer == null && os == null) {
      writer = getStreamHandlerFromCurrentMessage(XMLStreamWriter.class);
    }
    return createTransformWriterIfNeeded(writer, os, true);
  }
  /**
   * 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();
    }
  }
Esempio n. 8
0
  private static void streamWriter2(OutputStream out) throws IOException, XMLStreamException {
    File xsdFile = new File(Const.XSD_BOOK);
    XMLValidationSchemaFactory xsdFactory =
        XMLValidationSchemaFactory.newInstance(XMLValidationSchema.SCHEMA_ID_W3C_SCHEMA);
    XMLValidationSchema schema = xsdFactory.createSchema(xsdFile);

    XMLOutputFactory factory = XMLOutputFactory2.newInstance();
    // factory.setProperty(name, value);

    XMLStreamWriter2 writer = (XMLStreamWriter2) factory.createXMLStreamWriter(out);

    writer.writeStartDocument("UTF-8", "1.0");

    writer.writeStartElement("bk", "books", Const.NSURI_BOOK);
    writer.writeNamespace("bk", Const.NSURI_BOOK);

    for (int i = 0; i < Const.NODE_COUNTS_L; ++i) {
      writer.writeStartElement("bk", "book", Const.NSURI_BOOK);
      writer.writeAttribute("id", String.valueOf(i + 1));

      writer.writeStartElement("bk", "name", Const.NSURI_BOOK);
      writer.writeCharacters("Name" + (i + 1));
      writer.writeEndElement();

      writer.writeStartElement("bk", "author", Const.NSURI_BOOK);
      writer.writeCharacters("author" + (i + 1));
      writer.writeEndElement();

      writer.writeEndElement();
    }
    writer.writeEndElement();
    writer.writeEndDocument();
    writer.close();
  }
  /**
   * 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();
  }
  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);
  }
  /**
   * 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);
    }
  }
 public static XMLStreamWriter create(OutputStream os) throws XmlSerializerException {
   try {
     XMLOutputFactory xof = XMLOutputFactory.newInstance();
     xof.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
     return xof.createXMLStreamWriter(os);
   } catch (XMLStreamException e) {
     throw new XmlSerializerException("Problem Creating a pull parser", e);
   }
 }
Esempio n. 13
0
 @Converter
 public XMLStreamWriter createXMLStreamWriter(Writer writer) throws XMLStreamException {
   XMLOutputFactory factory = getOutputFactory();
   try {
     return factory.createXMLStreamWriter(IOHelper.buffered(writer));
   } finally {
     returnXMLOutputFactory(factory);
   }
 }
Esempio 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();
 }
Esempio n. 15
0
 public static void build(Writer writer, XmlElementHandler rootBuilder) throws Exception {
   XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
   XMLStreamWriter xmlStreamWriter = outputFactory.createXMLStreamWriter(writer);
   xmlStreamWriter.writeStartElement(rootBuilder.getTagName());
   StaxXmlWriter xmlWriter = new StaxXmlWriter(xmlStreamWriter);
   XmlElementHandler[] xmlHandlers = rootBuilder.handleNext(xmlWriter);
   write(xmlWriter, xmlHandlers);
   xmlStreamWriter.writeEndElement();
 }
Esempio n. 16
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);
   }
 }
Esempio n. 17
0
  public byte[] convertToXML(BpmnModel model) {
    try {

      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

      XMLOutputFactory xof = XMLOutputFactory.newInstance();
      OutputStreamWriter out = new OutputStreamWriter(outputStream, "UTF-8");

      XMLStreamWriter writer = xof.createXMLStreamWriter(out);
      XMLStreamWriter xtw = new IndentingXMLStreamWriter(writer);

      DefinitionsRootExport.writeRootElement(model, xtw);
      SignalAndMessageDefinitionExport.writeSignalsAndMessages(model, xtw);
      PoolExport.writePools(model, xtw);

      for (Process process : model.getProcesses()) {

        if (process.getFlowElements().size() == 0 && process.getLanes().size() == 0) {
          // empty process, ignore it
          continue;
        }

        ProcessExport.writeProcess(process, xtw);

        for (FlowElement flowElement : process.getFlowElements()) {
          createXML(flowElement, model, xtw);
        }

        for (Artifact artifact : process.getArtifacts()) {
          createXML(artifact, model, xtw);
        }

        // end process element
        xtw.writeEndElement();
      }

      BPMNDIExport.writeBPMNDI(model, xtw);

      // end definitions root element
      xtw.writeEndElement();
      xtw.writeEndDocument();

      xtw.flush();

      outputStream.close();

      xtw.close();

      return outputStream.toByteArray();

    } catch (Exception e) {
      LOGGER.error("Error writing BPMN XML", e);
      throw new XMLException("Error writing BPMN XML", e);
    }
  }
 public static StaxXmlRepresentation getInstance(String projectRoot, String filename)
     throws FileNotFoundException, XMLStreamException {
   StaxXmlRepresentation representation = new StaxXmlRepresentation();
   XMLOutputFactory factory = XMLOutputFactory.newInstance();
   File f = new File(filename);
   FileOutputStream stream = new FileOutputStream(f);
   representation.writer = factory.createXMLStreamWriter(stream, "UTF-8");
   File root = new File(projectRoot);
   representation.projectRoot = root.getAbsolutePath();
   return representation;
 }
  @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);
        }
      }
    }
  }
Esempio n. 20
0
 @Converter
 public XMLStreamWriter createXMLStreamWriter(OutputStream outputStream, Exchange exchange)
     throws XMLStreamException {
   XMLOutputFactory factory = getOutputFactory();
   try {
     return factory.createXMLStreamWriter(
         IOHelper.buffered(outputStream), IOHelper.getCharsetName(exchange));
   } finally {
     returnXMLOutputFactory(factory);
   }
 }
  /**
   * Copies the current node and its children to the <code>sink</code>.
   *
   * @param sink the output sink
   */
  public void copyNode(OutputStream sink) throws XMLStreamException {
    Assertion.notNull(sink);

    outputFactory.setProperty("javax.xml.stream.isRepairingNamespaces", isNsRepairing);
    final XMLStreamWriter writer = outputFactory.createXMLStreamWriter(sink);

    final DcsStreamSupport dcsStream = new DcsStreamSupport();
    dcsStream.copyNode(in, writer);
    writer.flush();
    writer.close();
  }
 protected XMLStreamWriter initWriter(OutputStream out) throws Exception {
   // BufferedWriter buf = new BufferedWriter(new OutputStreamWriter(out));
   XMLStreamWriter writer = null;
   try {
     XMLOutputFactory factory = XMLOutputFactory.newInstance();
     writer = new IndentingXMLStreamWriter(factory.createXMLStreamWriter(out, "UTF-8"));
     return writer;
   } catch (Exception x) {
     throw x;
   } finally {
   }
 }
Esempio n. 23
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);
      }
    }
  }
Esempio n. 24
0
 @Override
 public String toString() {
   try {
     XMLOutputFactory factory = XMLOutputFactory.newInstance();
     StringWriter sw = new StringWriter();
     XMLStreamWriter xmlWriter = factory.createXMLStreamWriter(sw);
     // xmlWriter = new IndentingXMLStreamWriter(xmlWriter);
     writeTo(xmlWriter);
     return sw.toString();
   } catch (XMLStreamException e) {
     throw new AssertionError(e);
   }
 }
Esempio n. 25
0
  /**
   * Convert a TemplateQuery to XML
   *
   * @param query the SavedQuery
   * @param version the version number of the XML format, an attribute of the ProfileManager
   * @return the corresponding XML String
   */
  public static String marshal(SavedQuery query, int version) {
    StringWriter sw = new StringWriter();
    XMLOutputFactory factory = XMLOutputFactory.newInstance();

    try {
      XMLStreamWriter writer = factory.createXMLStreamWriter(sw);
      marshal(query, writer, version);
    } catch (XMLStreamException e) {
      throw new RuntimeException(e);
    }

    return sw.toString();
  }
 protected byte[] object2WbXml(
     Object o,
     WbXmlDefinition def,
     WbXmlVersion version,
     WbXmlEncoder.StrtblType encoderType,
     boolean skipSpaces,
     boolean event)
     throws Exception {
   XMLStreamWriter xmlStreamWriter = null;
   XMLEventWriter xmlEventWriter = null;
   ByteArrayOutputStream out = null;
   try {
     out = new ByteArrayOutputStream();
     outFact.setProperty(WbXmlOutputFactory.ENCODING_TYPE_PROPERTY, encoderType);
     outFact.setProperty(WbXmlOutputFactory.SKIP_SPACES_PROPERTY, skipSpaces);
     outFact.setProperty(WbXmlOutputFactory.VERSION_PROPERTY, version);
     outFact.setProperty(WbXmlOutputFactory.DEFINITION_PROPERTY, def);
     if (event) {
       xmlEventWriter = outFact.createXMLEventWriter(out);
     } else {
       xmlStreamWriter = outFact.createXMLStreamWriter(out);
     }
     JAXBContext jc = JAXBContext.newInstance(o.getClass());
     Marshaller marshaller = jc.createMarshaller();
     if (event) {
       marshaller.marshal(o, xmlEventWriter);
     } else {
       marshaller.marshal(o, xmlStreamWriter);
     }
     return out.toByteArray();
   } finally {
     if (out != null) {
       try {
         out.close();
       } catch (Exception e) {
       }
     }
     if (xmlStreamWriter != null) {
       try {
         xmlStreamWriter.close();
       } catch (Exception e) {
       }
     }
     if (xmlEventWriter != null) {
       try {
         xmlEventWriter.close();
       } catch (Exception e) {
       }
     }
   }
 }
Esempio n. 27
0
  /**
   * Render the given Item as XML
   *
   * @param item the Item to render
   * @return an XML representation of the Item
   */
  public static String render(Item item) {
    StringWriter sw = new StringWriter();
    XMLOutputFactory factory = XMLOutputFactory.newInstance();

    XMLStreamWriter writer;
    try {
      writer = factory.createXMLStreamWriter(sw);
      renderImpl(writer, item);
    } catch (XMLStreamException e) {
      throw new RuntimeException("unexpected failure while creating Item XML", e);
    }

    return sw.toString();
  }
  public void testXMLStreamWriter() throws Exception {
    FlushRoot control = getControlObject();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    XMLOutputFactory xof = XMLOutputFactory.newFactory();
    XMLStreamWriter xsw = xof.createXMLStreamWriter(baos);
    marshaller.marshal(control, xsw);

    XMLInputFactory xif = XMLInputFactory.newFactory();
    XMLStreamReader xsr = xif.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
    Object test = unmarshaller.unmarshal(xsr);

    assertEquals(control, test);
  }
Esempio n. 29
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());
   }
 }
 protected byte[] doc2WbXml(
     Document doc,
     WbXmlDefinition def,
     WbXmlVersion version,
     WbXmlEncoder.StrtblType encoderType,
     boolean skipSpaces,
     boolean event)
     throws Exception {
   XMLStreamWriter xmlStreamWriter = null;
   XMLEventWriter xmlEventWriter = null;
   ByteArrayOutputStream out = null;
   try {
     out = new ByteArrayOutputStream();
     outFact.setProperty(WbXmlOutputFactory.ENCODING_TYPE_PROPERTY, encoderType);
     outFact.setProperty(WbXmlOutputFactory.SKIP_SPACES_PROPERTY, skipSpaces);
     outFact.setProperty(WbXmlOutputFactory.VERSION_PROPERTY, version);
     outFact.setProperty(WbXmlOutputFactory.DEFINITION_PROPERTY, def);
     if (event) {
       xmlEventWriter = outFact.createXMLEventWriter(out);
     } else {
       xmlStreamWriter = outFact.createXMLStreamWriter(out);
     }
     Transformer xformer = TransformerFactory.newInstance().newTransformer();
     Source domSource = new DOMSource(doc);
     StAXResult staxResult =
         (event) ? new StAXResult(xmlEventWriter) : new StAXResult(xmlStreamWriter);
     xformer.transform(domSource, staxResult);
     return out.toByteArray();
   } finally {
     if (out != null) {
       try {
         out.close();
       } catch (Exception e) {
       }
     }
     if (xmlStreamWriter != null) {
       try {
         xmlStreamWriter.close();
       } catch (Exception e) {
       }
     }
     if (xmlEventWriter != null) {
       try {
         xmlEventWriter.close();
       } catch (Exception e) {
       }
     }
   }
 }