Esempio 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;
  }
  @Override
  public SerializerResult metadataDocument(final ServiceMetadata serviceMetadata)
      throws SerializerException {
    CircleStreamBuffer buffer;
    XMLStreamWriter xmlStreamWriter = null;

    try {
      buffer = new CircleStreamBuffer();
      xmlStreamWriter =
          XMLOutputFactory.newInstance()
              .createXMLStreamWriter(buffer.getOutputStream(), DEFAULT_CHARSET);
      MetadataDocumentXmlSerializer serializer = new MetadataDocumentXmlSerializer(serviceMetadata);
      serializer.writeMetadataDocument(xmlStreamWriter);
      xmlStreamWriter.flush();
      xmlStreamWriter.close();

      return SerializerResultImpl.with().content(buffer.getInputStream()).build();
    } catch (final XMLStreamException e) {
      log.error(e.getMessage(), e);
      throw new SerializerException(
          "An I/O exception occurred.", e, SerializerException.MessageKeys.IO_EXCEPTION);
    } finally {
      if (xmlStreamWriter != null) {
        try {
          xmlStreamWriter.close();
        } catch (XMLStreamException e) {
          throw new SerializerException(
              "An I/O exception occurred.", e, SerializerException.MessageKeys.IO_EXCEPTION);
        }
      }
    }
  }
Esempio n. 3
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 doFromSoapMessage(Message message, Object sm) {
    SOAPMessage m = (SOAPMessage) sm;
    MessageContentsList list = (MessageContentsList) message.getContent(List.class);
    if (list == null) {
      list = new MessageContentsList();
      message.setContent(List.class, list);
    }
    Object o = m;

    if (StreamSource.class.isAssignableFrom(type)) {
      try {
        try (CachedOutputStream out = new CachedOutputStream()) {
          XMLStreamWriter xsw = StaxUtils.createXMLStreamWriter(out);
          StaxUtils.copy(new DOMSource(m.getSOAPPart()), xsw);
          xsw.close();
          o = new StreamSource(out.getInputStream());
        }
      } catch (Exception e) {
        throw new Fault(e);
      }
    } else if (SAXSource.class.isAssignableFrom(type)) {
      o = new StaxSource(new W3CDOMStreamReader(m.getSOAPPart()));
    } else if (Source.class.isAssignableFrom(type)) {
      o = new DOMSource(m.getSOAPPart());
    }
    list.set(0, o);
  }
    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());
      }
    }
  @Override
  public EndElement endElement(final EndElement element) throws XMLStreamException {
    final String theName = element.getLocalName();

    if ("component".equals(theName)) {
      if (this.componentId == null) {
        final Map components = (Map) outputStreams.get("components");
        components.remove(this.componentId);
      }
      this.inComponent = false;
      this.componentId = null;
    }
    if (this.inside) {
      this.insideLevel--;
      if (this.insideLevel > 0 || this.insideLevel == 0 && !"md-record".equals(theName)) {
        writer.writeEndElement();
      }

      if (this.insideLevel == 0) {
        this.inside = false;
        writer.flush();
        writer.close();
      }
    }

    return element;
  }
 public void safeClose(final XMLStreamWriter closeable) {
   if (closeable != null)
     try {
       closeable.close();
     } catch (Throwable ignore) {
     }
 }
 private static void writeNormalizedRpc(
     final ContainerNode normalized,
     final DOMResult result,
     final SchemaPath schemaPath,
     final SchemaContext baseNetconfCtx)
     throws IOException, XMLStreamException {
   final XMLStreamWriter writer =
       NetconfMessageTransformUtil.XML_FACTORY.createXMLStreamWriter(result);
   try {
     try (final NormalizedNodeStreamWriter normalizedNodeStreamWriter =
         XMLStreamNormalizedNodeStreamWriter.create(writer, baseNetconfCtx, schemaPath)) {
       try (final OrderedNormalizedNodeWriter normalizedNodeWriter =
           new OrderedNormalizedNodeWriter(
               normalizedNodeStreamWriter, baseNetconfCtx, schemaPath)) {
         Collection<DataContainerChild<?, ?>> value = normalized.getValue();
         normalizedNodeWriter.write(value);
         normalizedNodeWriter.flush();
       }
     }
   } finally {
     try {
       writer.close();
     } catch (final Exception e) {
       LOG.warn("Unable to close resource properly", e);
     }
   }
 }
Esempio n. 9
0
 @Override
 public void endElement(final String uri, final String localName, final String name)
     throws SAXException {
   if (start) {
     level--;
     try {
       pushcontentWriter.writeEndElement();
     } catch (XMLStreamException e) {
       throw new SAXException(e);
     }
   }
   if (level == 0) {
     // turn off start if we reach the end tag of staring element
     start = false;
     if (ATTR_CONACTION_VALUE_PUSHAFTER.equals(pushType)
         || ATTR_CONACTION_VALUE_PUSHREPLACE.equals(pushType)) {
       // if it is pushafter or replace, we need to record content in pushtable
       // if target == null we have already reported error in startElement;
       if (target != null) {
         if (pushcontentWriter != null) {
           try {
             pushcontentWriter.close();
           } catch (final XMLStreamException e) {
             throw new SAXException(e);
           }
         }
         addtoPushTable(target, pushcontentDocumentFragment, pushType);
         pushcontentWriter = getXMLStreamWriter();
         target = null;
         pushType = null;
       }
     }
   }
 }
  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. 11
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();
  }
Esempio n. 12
0
  public void close() {
    if (closed) {
      return;
    }
    closed = true;

    // finish off anything
    try {
      xmlw.writeEndElement(); // msRun element

      // declare the index does not exist
      xmlw.writeEmptyElement("indexOffset");
      xmlw.writeAttribute("xsi:nil", "1");

      xmlw.writeEndElement(); // mzXML element

      // close out the xml writer
      xmlw.flush();
      xmlw.close();
    } catch (XMLStreamException e) {
      throw new RuntimeException("Can't write all of XML!", e);
    } finally {
      super.close();
    }
  }
  /**
   * 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);
    }
  }
Esempio n. 14
0
  /**
   * Конвертирует XMLDOM древо в текстовое представление
   *
   * @param xmlDocument XMLDOM древо
   * @return Текстовое представление XMLDOM древа
   * @throws javax.xml.stream.XMLStreamException Если не смогло
   * @throws javax.xml.transform.TransformerConfigurationException Если не смогло
   * @throws javax.xml.transform.TransformerException Если не смогло
   * @throws java.io.IOException Если не смогло
   */
  public static String toStringWithException(Node xmlDocument)
      throws XMLStreamException, TransformerConfigurationException, TransformerException,
          IOException {
    if (xmlDocument == null) {
      throw new IllegalArgumentException("xmlDocument == null");
    }

    Transformer tr = TransformerFactory.newInstance().newTransformer();

    DOMSource domSrc = new DOMSource(xmlDocument);

    StringWriter sWiter = new StringWriter();
    XMLStreamWriter xml2format = new FormatXMLWriter(sWiter);

    StAXResult sResult = new StAXResult(xml2format);
    Result result = sResult;

    tr.transform(domSrc, result);

    //        sWiter.flush();
    xml2format.writeEndDocument();
    xml2format.flush();

    String toOutput = sWiter.toString();

    xml2format.close();
    sWiter.close();

    return toOutput;
  }
Esempio n. 15
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);
  }
  @Override
  public ISORecord inspect(ISORecord record, Connection conn, SQLDialect dialect)
      throws MetadataInspectorException {

    ISORecord result = record;

    try {
      // create temporary sink for normalized XML
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(bos);
      writer = new NamespaceNormalizingXMLStreamWriter(writer, nsBindings);

      // create normalized copy
      XMLStreamReader reader = record.getAsXMLStream();
      XMLAdapter.writeElement(writer, reader);
      reader.close();
      writer.close();

      InputStream is = new ByteArrayInputStream(bos.toByteArray());
      XMLStreamReader xmlStream = XMLInputFactory.newInstance().createXMLStreamReader(is);
      result = new ISORecord(xmlStream);
    } catch (Throwable t) {
      LOG.error(
          "Namespace normalization failed. Proceeding with unnormalized record. Error: "
              + t.getMessage());
    }

    return result;
  }
Esempio n. 18
0
  @Override
  public void encodeTagListToWriter(TagList theTagList, Writer theWriter) throws IOException {
    try {
      XMLStreamWriter eventWriter = createXmlWriter(theWriter);

      eventWriter.writeStartElement(TagList.ELEMENT_NAME_LC);
      eventWriter.writeDefaultNamespace(FHIR_NS);

      for (Tag next : theTagList) {
        eventWriter.writeStartElement(TagList.ATTR_CATEGORY);

        if (isNotBlank(next.getTerm())) {
          eventWriter.writeAttribute(Tag.ATTR_TERM, next.getTerm());
        }
        if (isNotBlank(next.getLabel())) {
          eventWriter.writeAttribute(Tag.ATTR_LABEL, next.getLabel());
        }
        if (isNotBlank(next.getScheme())) {
          eventWriter.writeAttribute(Tag.ATTR_SCHEME, next.getScheme());
        }

        eventWriter.writeEndElement();
      }

      eventWriter.writeEndElement();
      eventWriter.close();
    } catch (XMLStreamException e) {
      throw new ConfigurationException("Failed to initialize STaX event factory", e);
    }
  }
Esempio n. 19
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;
  }
Esempio n. 20
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();
  }
Esempio n. 21
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);
  }
Esempio n. 22
0
 public Binary getContent() throws UserException {
   try {
     xtw.flush();
     xtw.close();
     return content;
   } catch (Exception e) {
     throw new UserException(455, e.getMessage());
   }
 }
 @Override
 public void close() throws IOException {
   try {
     if (xmlWriter != null) xmlWriter.close();
   } catch (XMLStreamException ignore) {
   } finally {
     super.close();
   }
 }
Esempio n. 24
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);
    }
  }
  @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);
    }
  }
Esempio n. 26
0
  public static void closeQuietly(XMLStreamWriter writer) {
    if (writer == null) {
      return; // nothing to do
    }

    try {
      writer.close();
    } catch (XMLStreamException ignore) {
      /* ignore */
    }
  }
  @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);
        }
      }
    }
  }
  /**
   * 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();
  }
Esempio n. 29
0
 /**
  * Serializes the XML element (including all attributes and subnodes) from the given {@link
  * XMLStreamReader} into a {@link StreamBufferStore}.
  *
  * @param reader cursor must point at a <code>START_ELEMENT</code> event and points at the
  *     corresponding <code>END_ELEMENT</code> event afterwards
  * @return stored document, never <code>null</code>
  * @throws IOException
  * @throws FactoryConfigurationError
  * @throws XMLStreamException
  */
 public static StreamBufferStore serialize(XMLStreamReader reader)
     throws IOException, XMLStreamException, FactoryConfigurationError {
   StreamBufferStore tmpStore = new StreamBufferStore();
   XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(tmpStore);
   try {
     copy(writer, reader);
   } finally {
     writer.close();
     tmpStore.close();
   }
   return tmpStore;
 }
Esempio n. 30
0
 @Override
 public void finish() {
   try {
     writer.writeEndElement();
     writer.writeEndDocument();
     writer.flush();
     writer.close();
     out.close();
   } catch (XMLStreamException | IOException e) {
     throw new RuntimeException(e);
   }
 }