org.springframework.util.DBUnitUtils Maven / Gradle / Ivy
package org.springframework.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.ITable;
import org.dbunit.dataset.ReplacementDataSet;
import org.dbunit.dataset.excel.XlsDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.dataset.xml.XmlDataSet;
import org.springframework.core.io.Resource;
public class DBUnitUtils {
public static void write(Resource source, Resource target) throws IOException {
Assert.notNull(source, "'source' must not be null");
Assert.notNull(target, "'target' must not be null");
File file = target.getFile();
Assert.isTrue(file.getParentFile() != null && (file.getParentFile().mkdirs() || file.getParentFile().isDirectory()), "Create Directory fail..." + target);
File temp = File.createTempFile(StringUtils.getFilename(source.getFilename()), ".xml", file.getParentFile());
temp.deleteOnExit();
try (InputStream inputStream = source.getInputStream(); Writer writer = new OutputStreamWriter(new FileOutputStream(temp), StandardCharsets.UTF_8)) {
ReplacementDataSet replacementDataSet = new ReplacementDataSet(new XlsDataSet(inputStream));
replacementDataSet.addReplacementObject(ITable.NO_VALUE, null);
replacementDataSet.addReplacementObject("[null]", null);
XmlDataSet.write(replacementDataSet, writer);
}
catch (IOException | DataSetException e) {
throw new IllegalStateException(e);
}
try (InputStream inputStream = new FileInputStream(temp); Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)) {
ReplacementDataSet replacementDataSet = new ReplacementDataSet(new XmlDataSet(inputStream));
replacementDataSet.addReplacementObject(ITable.NO_VALUE, null);
replacementDataSet.addReplacementObject("[null]", null);
FlatXmlDataSet.write(replacementDataSet, writer);
}
catch (IOException | DataSetException e) {
throw new IllegalStateException(e);
}
}
}