Example usage for javax.xml.stream XMLEventWriter add

List of usage examples for javax.xml.stream XMLEventWriter add

Introduction

In this page you can find the example usage for javax.xml.stream XMLEventWriter add.

Prototype


public void add(XMLEventReader reader) throws XMLStreamException;

Source Link

Document

Adds an entire stream to an output stream, calls next() on the inputStream argument until hasNext() returns false This should be treated as a convenience method that will perform the following loop over all the events in an event reader and call add on each event.

Usage

From source file:org.springframework.batch.item.xml.StaxEventItemWriterTests.java

/**
 * Resource is deleted when items have not been written and shouldDeleteIfEmpty flag is set.
 *//*from  w  w w .  j  a  va 2s. c  o m*/
@Test
public void testDeleteIfEmptyNoRecordsWrittenHeaderAndFooter() throws Exception {
    writer.setShouldDeleteIfEmpty(true);
    writer.setHeaderCallback(new StaxWriterCallback() {

        @Override
        public void write(XMLEventWriter writer) throws IOException {
            XMLEventFactory factory = XMLEventFactory.newInstance();
            try {
                writer.add(factory.createStartElement("", "", "header"));
                writer.add(factory.createEndElement("", "", "header"));
            } catch (XMLStreamException e) {
                throw new RuntimeException(e);
            }

        }

    });
    writer.setFooterCallback(new StaxWriterCallback() {

        @Override
        public void write(XMLEventWriter writer) throws IOException {
            XMLEventFactory factory = XMLEventFactory.newInstance();
            try {
                writer.add(factory.createStartElement("", "", "footer"));
                writer.add(factory.createEndElement("", "", "footer"));
            } catch (XMLStreamException e) {
                throw new RuntimeException(e);
            }

        }

    });
    writer.open(executionContext);
    writer.close();
    assertFalse("file should be deleted" + resource, resource.getFile().exists());
}

From source file:org.springframework.batch.item.xml.StaxEventItemWriterTests.java

/**
 * Resource is not deleted when items have been written and shouldDeleteIfEmpty flag is set (restart after delete).
 *///from w  w  w .j  av a 2s. co m
@Test
public void testDeleteIfEmptyNoRecordsWrittenHeaderAndFooterRestartAfterDelete() throws Exception {
    writer.setShouldDeleteIfEmpty(true);
    writer.setHeaderCallback(new StaxWriterCallback() {

        @Override
        public void write(XMLEventWriter writer) throws IOException {
            XMLEventFactory factory = XMLEventFactory.newInstance();
            try {
                writer.add(factory.createStartElement("", "", "header"));
                writer.add(factory.createEndElement("", "", "header"));
            } catch (XMLStreamException e) {
                throw new RuntimeException(e);
            }

        }

    });
    writer.setFooterCallback(new StaxWriterCallback() {

        @Override
        public void write(XMLEventWriter writer) throws IOException {
            XMLEventFactory factory = XMLEventFactory.newInstance();
            try {
                writer.add(factory.createStartElement("", "", "footer"));
                writer.add(factory.createEndElement("", "", "footer"));
            } catch (XMLStreamException e) {
                throw new RuntimeException(e);
            }

        }

    });
    writer.open(executionContext);
    writer.update(executionContext);
    writer.close();
    assertFalse("file should be deleted" + resource, resource.getFile().exists());
    writer.open(executionContext);
    writer.write(items);
    writer.update(executionContext);
    writer.close();
    String content = getOutputFileContent();
    assertTrue("Wrong content: " + content, content.contains(TEST_STRING));
}

From source file:org.springframework.batch.item.xml.StaxEventItemWriterTests.java

private void initWriterForSimpleCallbackTests() throws Exception {
    writer = createItemWriter();/* w w  w.j a  v a2 s.  c om*/
    writer.setHeaderCallback(new StaxWriterCallback() {

        @Override
        public void write(XMLEventWriter writer) throws IOException {
            XMLEventFactory factory = XMLEventFactory.newInstance();
            try {
                writer.add(factory.createStartElement("ns", "http://www.springframework.org/test", "group"));
            } catch (XMLStreamException e) {
                throw new RuntimeException(e);
            }
        }

    });
    writer.setFooterCallback(new StaxWriterCallback() {

        @Override
        public void write(XMLEventWriter writer) throws IOException {
            XMLEventFactory factory = XMLEventFactory.newInstance();
            try {
                writer.add(factory.createEndElement("ns", "http://www.springframework.org/test", "group"));
            } catch (XMLStreamException e) {
                throw new RuntimeException(e);
            }

        }

    });
    writer.setRootTagName("{http://www.springframework.org/test}ns:testroot");
    writer.afterPropertiesSet();
}

From source file:org.springframework.batch.item.xml.StaxEventItemWriterTests.java

private void initWriterForComplexCallbackTests() throws Exception {
    writer = createItemWriter();//  www  . j  a  v  a 2  s .  c  om
    writer.setHeaderCallback(new StaxWriterCallback() {

        @Override
        public void write(XMLEventWriter writer) throws IOException {
            XMLEventFactory factory = XMLEventFactory.newInstance();
            try {
                writer.add(factory.createStartElement("", "", "preHeader"));
                writer.add(factory.createCharacters("PRE-HEADER"));
                writer.add(factory.createEndElement("", "", "preHeader"));
                writer.add(factory.createStartElement("ns", "http://www.springframework.org/test", "group"));
                writer.add(factory.createStartElement("", "", "subGroup"));
                writer.add(factory.createStartElement("", "", "postHeader"));
                writer.add(factory.createCharacters("POST-HEADER"));
                writer.add(factory.createEndElement("", "", "postHeader"));
            } catch (XMLStreamException e) {
                throw new RuntimeException(e);
            }
        }

    });
    writer.setFooterCallback(new StaxWriterCallback() {

        @Override
        public void write(XMLEventWriter writer) throws IOException {
            XMLEventFactory factory = XMLEventFactory.newInstance();
            try {
                writer.add(factory.createStartElement("", "", "preFooter"));
                writer.add(factory.createCharacters("PRE-FOOTER"));
                writer.add(factory.createEndElement("", "", "preFooter"));
                writer.add(factory.createEndElement("", "", "subGroup"));
                writer.add(factory.createEndElement("ns", "http://www.springframework.org/test", "group"));
                writer.add(factory.createStartElement("", "", "postFooter"));
                writer.add(factory.createCharacters("POST-FOOTER"));
                writer.add(factory.createEndElement("", "", "postFooter"));
            } catch (XMLStreamException e) {
                throw new RuntimeException(e);
            }

        }

    });
    writer.setRootTagName("{http://www.springframework.org/test}ns:testroot");
    writer.afterPropertiesSet();
}

From source file:org.springframework.batch.item.xml.TransactionalStaxEventItemWriterTests.java

/**
 * Item is written to the output file only after flush.
 *///from w  w  w .  j av a 2  s . com
@Test
public void testWriteWithHeaderAfterRollback() throws Exception {
    writer.setHeaderCallback(new StaxWriterCallback() {

        @Override
        public void write(XMLEventWriter writer) throws IOException {
            XMLEventFactory factory = XMLEventFactory.newInstance();
            try {
                writer.add(factory.createStartElement("", "", "header"));
                writer.add(factory.createEndElement("", "", "header"));
            } catch (XMLStreamException e) {
                throw new RuntimeException(e);
            }

        }

    });
    writer.open(executionContext);
    try {
        new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() {
            @Override
            public Void doInTransaction(TransactionStatus status) {
                try {
                    writer.write(items);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                throw new RuntimeException("Planned");
            }
        });
        fail("Expected RuntimeException");
    } catch (RuntimeException e) {
        // expected
    }
    writer.close();
    writer.open(executionContext);
    new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() {
        @Override
        public Void doInTransaction(TransactionStatus status) {
            try {
                writer.write(items);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return null;
        }
    });
    writer.close();
    String content = outputFileContent();
    assertEquals("Wrong content: " + content, 1, StringUtils.countOccurrencesOf(content, ("<header/>")));
    assertEquals("Wrong content: " + content, 1, StringUtils.countOccurrencesOf(content, TEST_STRING));
}

From source file:org.springframework.batch.item.xml.TransactionalStaxEventItemWriterTests.java

/**
 * Item is written to the output file only after flush.
 */// www .j a va2  s . c  o m
@Test
public void testWriteWithHeaderAfterFlushAndRollback() throws Exception {
    writer.setHeaderCallback(new StaxWriterCallback() {

        @Override
        public void write(XMLEventWriter writer) throws IOException {
            XMLEventFactory factory = XMLEventFactory.newInstance();
            try {
                writer.add(factory.createStartElement("", "", "header"));
                writer.add(factory.createEndElement("", "", "header"));
            } catch (XMLStreamException e) {
                throw new RuntimeException(e);
            }

        }

    });
    writer.open(executionContext);
    new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() {
        @Override
        public Void doInTransaction(TransactionStatus status) {
            try {
                writer.write(items);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return null;
        }
    });
    writer.update(executionContext);
    writer.close();
    writer.open(executionContext);
    try {
        new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() {
            @Override
            public Void doInTransaction(TransactionStatus status) {
                try {
                    writer.write(items);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                throw new RuntimeException("Planned");
            }
        });
        fail("Expected RuntimeException");
    } catch (RuntimeException e) {
        // expected
    }
    writer.close();
    String content = outputFileContent();
    assertEquals("Wrong content: " + content, 1, StringUtils.countOccurrencesOf(content, ("<header/>")));
    assertEquals("Wrong content: " + content, 1, StringUtils.countOccurrencesOf(content, TEST_STRING));
}

From source file:org.talend.repository.json.util.ConvertJSONString.java

public static void main(String[] args) {
    ConvertJSONString convertJSON = new ConvertJSONString();
    de.odysseus.staxon.json.JsonXMLConfig jsonConfig = new de.odysseus.staxon.json.JsonXMLConfigBuilder()
            .multiplePI(false).build();/* w w w.j  ava 2s  . com*/
    de.odysseus.staxon.json.JsonXMLInputFactory jsonXMLInputFactory = new de.odysseus.staxon.json.JsonXMLInputFactory(
            jsonConfig);
    javax.xml.stream.XMLOutputFactory xmlOutputFactory = javax.xml.stream.XMLOutputFactory.newInstance();

    // org.dom4j.io.SAXReader reader_tExtractJSONFields_1 = new org.dom4j.io.SAXReader();
    // org.dom4j.Document doc_tExtractJSONFields_1 = null;
    // java.util.HashMap xmlNameSpaceMap_tExtractJSONFields_1 = new java.util.HashMap<String, String>();
    // org.dom4j.XPath x_tExtractJSONFields_1 = null;
    // java.util.List<org.dom4j.tree.AbstractNode> nodeList_tExtractJSONFields_1 = null;
    // boolean isStructError = true;
    java.io.ByteArrayOutputStream outStream = new java.io.ByteArrayOutputStream();
    java.io.ByteArrayInputStream inStream = null;
    File file = new File("E:/builds/source_file.json");
    try {
        FileInputStream input = new FileInputStream(file);
        String jsonStr = IOUtils.toString(input);

        // String loopQuery_tExtractJSONFields_1 = "/rcp.authorized_plug-ins";
        // String oraginalJsonStr_tExtractJSONFields_1 = jsonStr_tExtractJSONFields_1;
        convertJSON.setJsonString(jsonStr);
        // cjs_tExtractJSONFields_1.setLoopString(loopQuery_tExtractJSONFields_1);

        convertJSON.generate();
        jsonStr = convertJSON.getJsonString4XML();
        // loopQuery_tExtractJSONFields_1 = cjs_tExtractJSONFields_1.getLoopString4XML();
        inStream = new ByteArrayInputStream(jsonStr.getBytes());
        javax.xml.stream.XMLEventReader xmlEventReader = jsonXMLInputFactory.createXMLEventReader(inStream);
        javax.xml.stream.XMLEventWriter xmLEventWriter = xmlOutputFactory.createXMLEventWriter(outStream);
        xmLEventWriter.add(xmlEventReader);
        // convert json string to xml
        String xmlStr = outStream.toString();
        // System.out.println(xmlStr_tExtractJSONFields_1);

        FileWriter writer = new FileWriter("D:/CLOUD1.xml");
        writer.write(xmlStr);
        writer.flush();
        writer.close();
        // xmlStr_tExtractJSONFields_1 =
        // "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root><rcp.authorized_plug-ins><s1>4</s1><upk>false</upk><psn>org.eclipse.jface.databinging.n1_de</psn><v>3.6.0.v20100814043401</v><pa>MDM1,TIS,DI</pa><sd>false</sd></rcp.authorized_plug-ins><rcp.authorized_plug-ins><s1>1</s1><upk>false</upk><psn>org.eclipse.jface.databinging.n1_de</psn><v>3.6.0.v20100814043401</v><pa>TDQ,Test</pa><sd>false</sd></rcp.authorized_plug-ins></root>";
        xmLEventWriter.close();
        xmlEventReader.close();

        // doc_tExtractJSONFields_1 = reader_tExtractJSONFields_1.read(new
        // java.io.StringReader(xmlStr_tExtractJSONFields_1));
        // x_tExtractJSONFields_1 = doc_tExtractJSONFields_1.createXPath(loopQuery_tExtractJSONFields_1);
        // x_tExtractJSONFields_1.setNamespaceURIs(xmlNameSpaceMap_tExtractJSONFields_1);
        // nodeList_tExtractJSONFields_1 = (java.util.List<org.dom4j.tree.AbstractNode>) x_tExtractJSONFields_1
        // .selectNodes(doc_tExtractJSONFields_1);
        // isStructError = false;
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (java.lang.Exception ex_tExtractJSONFields_1) {
        ex_tExtractJSONFields_1.printStackTrace();
    } finally {
        try {
            outStream.close();
            if (inStream != null) {
                inStream.close();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

From source file:org.talend.repository.json.util.JSONUtil.java

public static String changeJsonToXml(String jsonPath) {
    Project project = ProjectManager.getInstance().getCurrentProject();
    IProject fsProject = null;/*from   w  ww.  j  a  va 2  s  . c  o  m*/
    try {
        fsProject = ResourceUtils.getProject(project);
    } catch (PersistenceException e2) {
        ExceptionHandler.process(e2);
    }
    if (fsProject == null) {
        return jsonPath;
    }
    String temPath = fsProject.getLocationURI().getPath() + File.separator + "temp" + File.separator
            + "jsonwizard" + File.separator;

    ConvertJSONString convertJSON = new ConvertJSONString();
    de.odysseus.staxon.json.JsonXMLConfig jsonConfig = new de.odysseus.staxon.json.JsonXMLConfigBuilder()
            .multiplePI(false).build();
    de.odysseus.staxon.json.JsonXMLInputFactory jsonXMLInputFactory = new de.odysseus.staxon.json.JsonXMLInputFactory(
            jsonConfig);
    javax.xml.stream.XMLOutputFactory xmlOutputFactory = javax.xml.stream.XMLOutputFactory.newInstance();

    java.io.ByteArrayOutputStream outStream = new java.io.ByteArrayOutputStream();
    InputStream inStream = null;
    File file = new File(jsonPath);

    // String filename = file.getName().replaceAll("\\.", "_");
    // filename = "tempTest";
    boolean isFromUrl = false;
    boolean illegalURL = false;
    InputStream input = null;

    if (file.exists()) {
        if (file.isDirectory()) {
            return "";
        }
        try {
            input = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            ExceptionHandler.process(e);
        }
    } else {
        isFromUrl = true;
        try {
            input = new URL(jsonPath).openStream();
        } catch (MalformedURLException e) {
            illegalURL = true;
        } catch (IOException e) {
            illegalURL = true;
        }
        if (illegalURL) {
            return "";
        }
    }

    try {
        String jsonStr = IOUtils.toString(input);

        convertJSON.setJsonString(jsonStr);

        convertJSON.generate();
        jsonStr = convertJSON.getJsonString4XML();
        inStream = new ByteArrayInputStream(jsonStr.getBytes());
        javax.xml.stream.XMLEventReader xmlEventReader = jsonXMLInputFactory.createXMLEventReader(inStream);
        javax.xml.stream.XMLEventWriter xmLEventWriter = xmlOutputFactory.createXMLEventWriter(outStream);
        xmLEventWriter.add(xmlEventReader);
        String xmlStr = outStream.toString();

        File xmlFolder = new File(temPath);
        if (!xmlFolder.exists()) {
            xmlFolder.mkdirs();
        }
        temPath = temPath + TMP_JSON_FILE;
        FileWriter writer = new FileWriter(temPath);
        writer.write(xmlStr);
        writer.flush();
        writer.close();

        xmLEventWriter.close();
        xmlEventReader.close();
        if (isFromUrl) {
            tempJSONXsdPath = temPath;
        }
    } catch (java.lang.Exception e) {
        ExceptionHandler.process(e);
    } finally {
        try {
            outStream.close();
            if (inStream != null) {
                inStream.close();
            }
        } catch (IOException e) {
            ExceptionHandler.process(e);
        }

    }
    return temPath;
}

From source file:org.xmlsh.commands.internal.xml2json.java

private byte[] serializeAsXML(XMLEventReader reader) throws XMLStreamException {

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    XMLOutputFactory fact = new OutputFactory();

    XMLEventWriter writer = fact.createXMLEventWriter(bos, kENCODING_UTF_8);
    while (reader.hasNext()) {
        XMLEvent event = reader.nextEvent();

        if (event.isEndElement() && event.asEndElement().getName().equals(kELEM_STRING))
            break;
        writer.add(event);
    }//  w w w .  ja va  2 s . c om

    writer.flush();
    writer.close();
    return bos.toByteArray();

}

From source file:ru.codeinside.gws.crypto.cryptopro.CryptoProvider.java

private String saxFilter(Node node) {
    try {//w ww.  ja  v a 2 s .c  o  m
        final Transformer transformer = TransformerFactory.newInstance().newTransformer();
        final StringWriter w1 = new StringWriter();
        transformer.transform(new DOMSource(node), new StreamResult(w1));
        XMLInputFactory xif = XMLInputFactory.newInstance();
        XMLEventReader eventReader = xif
                .createXMLEventReader(new StreamSource(new StringReader(w1.toString())));
        XMLEventReader filteredReader = xif.createFilteredReader(eventReader, new EventFilter() {
            @Override
            public boolean accept(XMLEvent event) {
                int type = event.getEventType();
                if (type == XMLStreamConstants.START_DOCUMENT || type == XMLStreamConstants.END_DOCUMENT) {
                    return false;
                }
                if (event.isStartElement()) {
                    StartElement startElement = (StartElement) event;
                    QName name = startElement.getName();
                    if ("".equals(name.getNamespaceURI()) && "root".equals(name.getLocalPart())) {
                        return false;
                    }
                }
                if (event.isEndElement()) {
                    EndElement endElement = (EndElement) event;
                    QName name = endElement.getName();
                    if ("".equals(name.getNamespaceURI()) && "root".equals(name.getLocalPart())) {
                        return false;
                    }
                }
                return true;
            }
        });
        StringWriter sw = new StringWriter();
        XMLOutputFactory xof = XMLOutputFactory.newInstance();
        XMLEventWriter writer = xof.createXMLEventWriter(sw);
        while (filteredReader.hasNext()) {
            writer.add(filteredReader.nextEvent());
        }
        return sw.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}