Example usage for javax.xml.stream XMLEventWriter close

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

Introduction

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

Prototype

public void close() throws XMLStreamException;

Source Link

Document

Frees any resources associated with this stream

Usage

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).
 *//*  w  w  w. ja  va  2  s .c o  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.TransactionalStaxEventItemWriterTests.java

/**
 * Item is written to the output file only after flush.
 *///from w  w  w . j a va  2s  .c om
@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.
 *//* w  w  w.j  a  v  a2s  . co  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();//from w  ww.j a v a 2 s  . c om
    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;// w  w  w  .  ja  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);/*from ww  w. j av  a2 s  .co m*/
    }

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

}