Example #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;
  }
  /**
   * 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();
    }
  }
Example #3
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);
  }
Example #4
0
  public XmlWriter(File output) throws FileNotFoundException, WriterException {
    this.xmlFile = output;
    System.out.println("setting up xml");
    if (output.exists()) {
      System.out.println("deleting existing file: " + output);
      output.delete();
    }

    try {
      FileOutputStream fos = new FileOutputStream(output);
      XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
      eventWriter = outputFactory.createXMLEventWriter(fos);

      eventFactory = XMLEventFactory.newInstance();

      end = eventFactory.createDTD("\n");

      // Create and write Start Tag
      StartDocument startDocument = eventFactory.createStartDocument();
      eventWriter.add(startDocument);

      StartElement configStartElement = eventFactory.createStartElement("", "", DOC_ELEMENT_NAME);
      eventWriter.add(configStartElement);
      eventWriter.add(end);
    } catch (XMLStreamException e) {
      throw new WriterException("unable to instantiate writer to file: " + output, e);
    }
  }
Example #5
0
  private static void eventWriter(OutputStream out) throws XMLStreamException {
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    // factory.setProperty(name, value);

    XMLEventWriter writer = factory.createXMLEventWriter(out);
    XMLEventFactory ef = XMLEventFactory2.newInstance();

    StartDocument startDocument = ef.createStartDocument("UTF-8", "1.0");
    writer.add(startDocument);

    StartElement booksStartElement = ef.createStartElement("bk", Const.NSURI_BOOK, "books");
    writer.add(booksStartElement);
    writer.add(ef.createNamespace("bk", Const.NSURI_BOOK));

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

      writer.add(ef.createStartElement("bk", Const.NSURI_BOOK, "name"));
      writer.add(ef.createCharacters("Name" + (i + 1)));
      writer.add(ef.createEndElement("bk", Const.NSURI_BOOK, "name"));

      writer.add(ef.createStartElement("bk", Const.NSURI_BOOK, "author"));
      writer.add(ef.createCharacters("author" + (i + 1)));
      writer.add(ef.createEndElement("bk", Const.NSURI_BOOK, "author"));

      writer.add(ef.createEndElement("bk", Const.NSURI_BOOK, "book"));
    }
    writer.add(ef.createEndElement("bk", Const.NSURI_BOOK, "books"));
    writer.add(ef.createEndDocument());
    writer.close();
  }
  protected static XMLEventWriter getEventWriter(final OutputStream os) throws XMLStreamException {
    if (ofactory == null) {
      ofactory = XMLOutputFactory.newInstance();
    }

    return ofactory.createXMLEventWriter(os, "UTF-8");
  }
Example #7
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();
  }
Example #8
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");
  }
  /**
   * 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();
  }
  /**
   * @throws XMLStreamException
   * @throws FactoryConfigurationError
   * @throws IOException
   * @throws UnknownCRSException
   * @throws TransformationException
   */
  @Test
  public void testPoint2()
      throws XMLStreamException, FactoryConfigurationError, IOException, TransformationException,
          UnknownCRSException {
    XMLStreamReaderWrapper xmlReader =
        new XMLStreamReaderWrapper(this.getClass().getResource(BASE_DIR + POINT2_FILE));
    xmlReader.nextTag();
    Point point = new GML2GeometryReader().parsePoint(xmlReader, null);
    Assert.assertEquals(5.0, point.get0(), DELTA);
    Assert.assertEquals(30.0, point.get1(), DELTA);

    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    outputFactory.setProperty("javax.xml.stream.isRepairingNamespaces", new Boolean(true));
    XMLMemoryStreamWriter memoryWriter = new XMLMemoryStreamWriter();

    SchemaLocationXMLStreamWriter writer =
        new SchemaLocationXMLStreamWriter(
            memoryWriter.getXMLStreamWriter(), SCHEMA_LOCATION_ATTRIBUTE);
    GML2GeometryWriter exporter = new GML2GeometryWriter(writer, null, null, new HashSet<String>());

    writer.setPrefix("gml", "http://www.opengis.net/gml");

    exporter.export(point);
    writer.flush();

    XMLAssert.assertValidity(memoryWriter.getReader(), SCHEMA_LOCATION);
  }
  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);
  }
  /**
   * 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();
    }
  }
 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);
   }
 }
Example #15
0
  private static XMLOutputFactory getXMLOutputFactory() throws XMLStreamException {
    if (_outputFactory == null) {
      _outputFactory = XMLOutputFactory.newInstance();
      _outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
    }

    return _outputFactory;
  }
  /**
   * @throws XMLStreamException
   * @throws FactoryConfigurationError
   * @throws IOException
   * @throws UnknownCRSException
   * @throws TransformationException
   */
  @Test
  public void testPolygon()
      throws XMLStreamException, FactoryConfigurationError, IOException, UnknownCRSException,
          TransformationException {
    XMLStreamReaderWrapper xmlReader =
        new XMLStreamReaderWrapper(this.getClass().getResource(BASE_DIR + POLYGON_FILE));
    xmlReader.nextTag();

    Assert.assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.getEventType());
    Assert.assertEquals(new QName(GML21NS, "Polygon"), xmlReader.getName());

    Polygon polygon = new GML2GeometryReader().parsePolygon(xmlReader, null);
    Assert.assertEquals(XMLStreamConstants.END_ELEMENT, xmlReader.getEventType());
    Assert.assertEquals(new QName(GML21NS, "Polygon"), xmlReader.getName());

    Points points = polygon.getExteriorRing().getControlPoints();
    comparePoint(0.0, 0.0, points.get(0));
    comparePoint(100.0, 0.0, points.get(1));
    comparePoint(100.0, 100.0, points.get(2));
    comparePoint(0.0, 100.0, points.get(3));
    comparePoint(0.0, 0.0, points.get(4));

    List<Points> innerPoints = polygon.getInteriorRingsCoordinates();
    Points points1 = innerPoints.get(0);
    comparePoint(10.0, 10.0, points1.get(0));
    comparePoint(10.0, 40.0, points1.get(1));
    comparePoint(40.0, 40.0, points1.get(2));
    comparePoint(40.0, 10.0, points1.get(3));
    comparePoint(10.0, 10.0, points1.get(4));

    Points points2 = innerPoints.get(1);
    comparePoint(60.0, 60.0, points2.get(0));
    comparePoint(60.0, 90.0, points2.get(1));
    comparePoint(90.0, 90.0, points2.get(2));
    comparePoint(90.0, 60.0, points2.get(3));
    comparePoint(60.0, 60.0, points2.get(4));

    Assert.assertEquals(
        CRSRegistry.lookup("http://www.opengis.net/gml/srs/epsg.xml#4326"),
        polygon.getCoordinateSystem().getWrappedCRS());

    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    outputFactory.setProperty("javax.xml.stream.isRepairingNamespaces", new Boolean(true));
    XMLMemoryStreamWriter memoryWriter = new XMLMemoryStreamWriter();

    SchemaLocationXMLStreamWriter writer =
        new SchemaLocationXMLStreamWriter(
            memoryWriter.getXMLStreamWriter(), SCHEMA_LOCATION_ATTRIBUTE);
    GML2GeometryWriter exporter = new GML2GeometryWriter(writer, null, null, new HashSet<String>());

    writer.setPrefix("gml", "http://www.opengis.net/gml");
    writer.setPrefix("xlink", "http://www.w3.org/1999/xlink");

    exporter.export(polygon);
    writer.flush();

    XMLAssert.assertValidity(memoryWriter.getReader(), SCHEMA_LOCATION);
  }
Example #17
0
 @Converter
 public XMLEventWriter createXMLEventWriter(Writer writer) throws XMLStreamException {
   XMLOutputFactory factory = getOutputFactory();
   try {
     return factory.createXMLEventWriter(IOHelper.buffered(writer));
   } finally {
     returnXMLOutputFactory(factory);
   }
 }
Example #18
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();
 }
 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);
   }
 }
Example #20
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();
 }
Example #21
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);
        }
      }
    }
  }
Example #24
0
 @Converter
 public XMLEventWriter createXMLEventWriter(OutputStream out, Exchange exchange)
     throws XMLStreamException {
   XMLOutputFactory factory = getOutputFactory();
   try {
     return factory.createXMLEventWriter(
         IOHelper.buffered(out), IOHelper.getCharsetName(exchange));
   } finally {
     returnXMLOutputFactory(factory);
   }
 }
  private void serializeValue(final HttpServletResponse pResponse, Object value)
      throws TransformerException, IOException, FactoryConfigurationError {
    if (value instanceof Source) {
      setContentType(pResponse, "application/binary"); // Unknown content type
      Sources.writeToStream((Source) value, pResponse.getOutputStream());
    } else if (value instanceof Node) {
      pResponse.setContentType("text/xml");
      Sources.writeToStream(new DOMSource((Node) value), pResponse.getOutputStream());
    } else if (value instanceof XmlSerializable) {
      pResponse.setContentType("text/xml");
      XMLOutputFactory factory = XMLOutputFactory.newInstance();
      factory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
      try {
        XmlWriter out =
            XmlStreaming.newWriter(
                pResponse.getOutputStream(), pResponse.getCharacterEncoding(), true);
        try {
          out.startDocument(null, null, null);
          ((XmlSerializable) value).serialize(out);
          out.endDocument();
        } finally {
          out.close();
        }
      } catch (XmlException e) {
        throw new TransformerException(e);
      }
    } else if (value instanceof Collection) {
      final XmlElementWrapper annotation = getElementWrapper();
      if (annotation != null) {
        setContentType(pResponse, "text/xml");
        try (OutputStream outStream = pResponse.getOutputStream()) {

          writeCollection(
              outStream, getGenericReturnType(), (Collection<?>) value, getQName(annotation));
        }
      }
    } else if (value instanceof CharSequence) {
      setContentType(pResponse, "text/plain");
      pResponse.getWriter().append((CharSequence) value);
    } else {
      if (value != null) {
        try {
          final JAXBContext jaxbContext = JAXBContext.newInstance(getReturnType());
          setContentType(pResponse, "text/xml");

          final JAXBSource jaxbSource = new JAXBSource(jaxbContext, value);
          Sources.writeToStream(jaxbSource, pResponse.getOutputStream());

        } catch (final JAXBException e) {
          throw new MessagingException(e);
        }
      }
    }
  }
  /**
   * 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 {
   }
 }
Example #28
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);
      }
    }
  }
  /**
   * @throws XMLStreamException
   * @throws FactoryConfigurationError
   * @throws IOException
   * @throws UnknownCRSException
   * @throws TransformationException
   */
  @Test
  public void testMultiGeometry()
      throws XMLStreamException, FactoryConfigurationError, IOException, TransformationException,
          UnknownCRSException {
    XMLStreamReaderWrapper xmlReader =
        new XMLStreamReaderWrapper(this.getClass().getResource(BASE_DIR + MULTIGEOMETRY_FILE));
    xmlReader.nextTag();

    Assert.assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.getEventType());
    Assert.assertEquals(new QName(GML21NS, "MultiGeometry"), xmlReader.getName());

    MultiGeometry<?> multiGeometry = new GML2GeometryReader().parseMultiGeometry(xmlReader, null);
    assertEquals("c731", multiGeometry.getId());

    Point firstMember = (Point) multiGeometry.get(0);
    assertEquals("P6776", firstMember.getId());
    comparePoint(50.0, 50.0, firstMember);

    LineString secondMember = (LineString) multiGeometry.get(1);
    assertEquals("L21216", secondMember.getId());

    Points controlPoints = secondMember.getControlPoints();
    comparePoint(0.0, 0.0, controlPoints.get(0));
    comparePoint(0.0, 50.0, controlPoints.get(1));
    comparePoint(100.0, 50.0, controlPoints.get(2));

    Polygon thirdMember = (Polygon) multiGeometry.get(2);
    assertEquals("_877789", thirdMember.getId());

    Points points = thirdMember.getExteriorRing().getControlPoints();
    comparePoint(0.0, 0.0, points.get(0));
    comparePoint(100.0, 0.0, points.get(1));
    comparePoint(50.0, 100.0, points.get(2));
    comparePoint(0.0, 0.0, points.get(3));

    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    outputFactory.setProperty("javax.xml.stream.isRepairingNamespaces", new Boolean(true));
    XMLMemoryStreamWriter memoryWriter = new XMLMemoryStreamWriter();

    SchemaLocationXMLStreamWriter writer =
        new SchemaLocationXMLStreamWriter(
            memoryWriter.getXMLStreamWriter(), SCHEMA_LOCATION_ATTRIBUTE);
    GML2GeometryWriter exporter = new GML2GeometryWriter(writer, null, null, new HashSet<String>());

    writer.setPrefix("gml", "http://www.opengis.net/gml");
    writer.setPrefix("xlink", "http://www.w3.org/1999/xlink");

    exporter.export(multiGeometry);
    writer.flush();

    XMLAssert.assertValidity(memoryWriter.getReader(), SCHEMA_LOCATION);
  }
Example #30
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);
   }
 }