Пример #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;
  }
Пример #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);
    }
  }
Пример #3
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;
  }
Пример #4
0
  public void export(File f, ConceptMap cmap) {
    this.cmap = cmap;
    try (OutputStream outputStream = new FileOutputStream(f)) {

      out =
          XMLOutputFactory.newInstance()
              .createXMLStreamWriter(new OutputStreamWriter(outputStream, "utf-8"));

      out.writeStartElement("cmap");

      out.writeStartElement("map");

      writeConceptList();
      writeLinkList();
      writeConnections();

      out.writeEndElement();

      out.writeEndElement();

      out.writeEndDocument();

      out.flush();
    } catch (Exception e) {
      LOG.error(ERROR_MESSAGE, e);
    }
  }
Пример #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");
  }
Пример #6
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);
  }
Пример #8
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);
    }
  }
    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());
      }
    }
  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();
    }
  }
Пример #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();
  }
Пример #13
0
 public void endDocument() {
   try {
     out.writeEndDocument();
     out.flush();
   } catch (XMLStreamException e) {
     throw new TxwException(e);
   }
 }
Пример #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();
 }
Пример #15
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);
  }
 @Override
 public void writeEnd() throws IOException {
   try {
     xmlWriter.writeEndElement();
     xmlWriter.writeEndDocument();
   } catch (XMLStreamException e) {
     throw new IOException(e);
   }
 }
Пример #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);
    }
  }
Пример #18
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);
    }
  }
Пример #19
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);
        }
      }
    }
  }
Пример #20
0
 @Override
 public void finish() {
   try {
     writer.writeEndElement();
     writer.writeEndDocument();
     writer.flush();
     writer.close();
     out.close();
   } catch (XMLStreamException | IOException e) {
     throw new RuntimeException(e);
   }
 }
Пример #21
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);
      }
    }
  }
Пример #22
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();
  }
 public void endDocument() {
   try {
     this.offset--;
     writeOffset();
     writer.writeEndElement();
     this.writer.writeCharacters(NEW_LINE);
     writer.writeEndDocument();
     writer.close();
   } catch (XMLStreamException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Пример #25
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);
    }
  }
  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();
  }
Пример #27
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();
  }
Пример #28
0
 //    public static void write(OutputStream stream, Element element, int hashLength) throws
 // XMLStreamException {
 //        XMLOutputFactory xof = XMLOutputFactory.newInstance();
 //        IndentingXMLStreamWriter xtw = new
 // IndentingXMLStreamWriter(xof.createXMLStreamWriter(stream));
 //        writeXMLStreamWriter(xtw, element, hashLength);
 //    }
 //
 private static void writeXMLStreamWriter(XMLStreamWriter xtw, Element element, int hashLength)
     throws XMLStreamException {
   if (hashLength > 0) {
     String hash = element.getHash(hashLength);
     Element hashElement = new Element(CRC_ELEMENT);
     hashElement.setText(hash);
     element.addChild(hashElement);
   }
   writeElement(xtw, element);
   xtw.writeEndDocument();
   xtw.flush();
   xtw.close();
   if (hashLength > 0) {
     element.removeChildren(CRC_ELEMENT);
   }
 }
Пример #29
0
 @Override
 protected Object unmarshalFromReader(
     Unmarshaller unmarshaller, XMLStreamReader reader, Annotation[] anns, MediaType mt)
     throws JAXBException {
   CachedOutputStream out = new CachedOutputStream();
   try {
     XMLStreamWriter writer = StaxUtils.createXMLStreamWriter(out);
     StaxUtils.copy(new StaxSource(reader), writer);
     writer.writeEndDocument();
     writer.flush();
     writer.close();
     return unmarshalFromInputStream(unmarshaller, out.getInputStream(), anns, mt);
   } catch (Exception ex) {
     throw ExceptionUtils.toBadRequestException(ex, null);
   }
 }
Пример #30
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);
        }
      }
    }
  }