*/
package mircoders.localizer.basic;
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.OutputStreamWriter;
-import java.io.PrintWriter;
+import java.io.*;
import mir.generator.WriterEngine;
+import mir.log.LoggerWrapper;
+import mir.config.MirPropertiesConfiguration;
+import mir.util.FileFunctions;
import mircoders.localizer.MirLocalizerFailure;
public class MirBasicWriterEngine implements WriterEngine {
private String defaultEncoding;
+ protected static LoggerWrapper logger = new LoggerWrapper("Localizer.AdminInterface");
+ protected MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();
+
+ /**
+ * Directory to store temp files into
+ */
+ private File tempDirectory;
+
public MirBasicWriterEngine(String aDefaultEncoding) {
defaultEncoding = aDefaultEncoding;
+ tempDirectory = configuration.getFile("TempDir");
}
+ /**
+ * {@inheritDoc}
+ */
public Object openWriter(String anIdentifier, String anEncoding) throws MirLocalizerFailure {
String encoding;
File file;
File dir;
- if (anEncoding != null && !anEncoding.equals(""))
+ if (anEncoding != null && !anEncoding.equals("")) {
encoding = anEncoding;
- else
+ }
+ else {
encoding = defaultEncoding;
+ }
try {
file = new File(anIdentifier);
}
return new PrintWriter(
- new BufferedWriter(
- new OutputStreamWriter(
- new FileOutputStream(file), encoding
- ), 8192)
+ new TempWriter(file, encoding)
);
}
- catch (Throwable t) {
- throw new MirLocalizerFailure("Failure while opening a PrintWriter: " + t.getMessage(), t);
+ catch (IOException t) {
+ throw new MirLocalizerFailure("Failure while opening a writer", t);
}
- };
+ }
public void closeWriter(Object aWriter) {
((PrintWriter) aWriter).close();
- };
+ }
+
+ private class TempWriter extends Writer {
+ TempWriter(File aDestination, String anEncoding) throws IOException {
+ destinationFile = aDestination;
+ slaveFile = File.createTempFile("Mir", ".generated", tempDirectory);
+ slaveWriter = new BufferedWriter(
+ new OutputStreamWriter(
+ new FileOutputStream(slaveFile), anEncoding
+ ), 8192);
+ }
+
+ public void close() throws IOException {
+ slaveWriter.close();
+ FileFunctions.move(slaveFile, destinationFile);
+ }
+
+ public void flush() throws IOException {
+ slaveWriter.flush();
+ }
+
+ public void write(char cbuf[], int off, int len) throws IOException {
+ slaveWriter.write(cbuf, off, len);
+ }
+
+ private Writer slaveWriter;
+ private File slaveFile;
+ private File destinationFile;
+ }
+
}
\ No newline at end of file