package net.raymanoz.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import net.raymanoz.config.Parameteriser;
import net.raymanoz.config.ParameteriserImpl;
import net.raymanoz.config.VariableEvaluaterImpl;
import net.raymanoz.io.FileImpl;
import net.raymanoz.io.File;
public class FileUtilImpl implements FileUtil {
private StreamUtil assembler;
public FileUtilImpl(StreamUtil assembler) {
this.assembler = assembler;
}
static public String readStreamText(InputStream stream) {
StringBuilder builder = new StringBuilder();
final int BUFFER_SIZE = 1024;
byte[] buf = new byte[BUFFER_SIZE];
int len;
try {
while((len = stream.read(buf)) > 0) {
if(len < BUFFER_SIZE) {
byte[] smallerBuf = new byte[len];
for(int i=0; i<len; i++) {
smallerBuf[i] = buf[i];
}
builder.append(new String(smallerBuf));
} else {
builder.append(new String(buf));
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return builder.toString();
}
public String loadStreamIntoString(InputStream stream) {
return readStreamText(stream);
}
public void writeStringIntoStream(String string, OutputStream stream) {
PrintWriter writer = new PrintWriter(stream);
writer.write(string);
writer.close();
}
@Override
public void copyFile(File inFile, File outFile, Properties properties, String prefixFileWith) {
InputStream in = assembler.newFileInputStream(inFile);
OutputStream out = assembler.newFileOutputStream(outFile);
String source = loadStreamIntoString(in);
String result = prefixFileWith + new VariableEvaluaterImpl(properties).replaceAllVariables(source);
Parameteriser parameteriser = new ParameteriserImpl(properties);
result = parameteriser.parameterise(result);
writeStringIntoStream(result, out);
}
public void copyFile(File inFile, File outFile, Properties properties) {
copyFile(inFile, outFile, properties, "");
}
public File newFile(String fileName, DirType dirType, Long dbVersion) {
return new FileImpl(fileName, dbVersion, dirType);
}
@Override
public String loadFileIntoString(String fileName) {
java.io.File file = new java.io.File(fileName);
if (!file.exists()) return null;
try {
InputStream stream = new FileInputStream(file);
String result = readStreamText(stream);
stream.close();
return result;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}