Search code examples
javaxmldatasetdbunitin-memory-database

FlatXmlDataSetBuilder throw "java.net.MalformedURLException" when using a StringBuffer


I'm trying to create a parser which can parse an XML database extract into a FlatXMLDataSet.

I am using a StringBuffer to write my FlatXML and then convert it into FlatXmlDataSet but it throw me a "java.net.MalformedURLException : No protocol".

So I tried to create a file from my StringBuffer and parse it into a FlatXMLDataSet. And it works ! But I really need to use the StringBuffer instead as everything must be used in memory.

Here is a sample of my FlatXML :

<?xml version='1.0' encoding='UTF-8'?>
<dataset>
    <TABLENAME COL1="1"
    COL2="35"
    />
</dataset>

And here is a sample of the code I use :

// Write the buffer into a file.
writeBuffer(buffer, "D:\\test.xml");
// Parse the file into a DataSet.
IDataSet test = createDataSet("D:\\test.xml");

// Cast the StringBuffer into an InputSource and give it to
// a FlatXMLDataSetBuider.
InputSource xmlInputStream = new InputSource(buffer.toString());

FlatXmlDataSetBuilder flatXmlBuilder = new FlatXmlDataSetBuilder();
flatXmlBuilder.setColumnSensing(true); // We do not have a dtd to give.
IDataSet dataSet = flatXmlBuilder.build(xmlInputStream); // Error is thrown here

private static void writeBuffer(StringBuffer buffer, String path)
{
    try
    {
        String content = buffer.toString();

        File file = new File(path);

        // if file doesnt exists, then create it
        if (!file.exists())
        {
            file.createNewFile();
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(content);
        bw.close();
    }
    catch (Exception e)
    {

    }
}

private static IDataSet createDataSet(String filePath)
{
    IDataSet dataSet = null;
    try
    {
        InputStream is = new FileInputStream(filePath);
        InputSource xmlInputStream = new InputSource(is);

        FlatXmlDataSetBuilder builder = new FlatXmlDataSetBuilder();
        builder.setColumnSensing(true);
        dataSet = builder.build(xmlInputStream);
    }
    catch (Exception e)
    {

    }
    return dataSet;
}

What am I doing wrong ? I mean, why is my file from my StringBuffer works and not my StringBuffer itself ?


Solution

  • After hours of test I have finally found what's going on : my StringBuffer did not specify any protocol nor my InputSource, so my FlatXmlDataSetBuilder could not know what to do with my string.

    So I change my InputSource decalaration and it worked :

    InputSource xmlInputStream = new InputSource(new ByteArrayInputStream(buffer.toString().getBytes("utf-8")));