1 package net.sf.jpkgmk;
2
3 import java.io.BufferedWriter;
4 import java.io.File;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7 import java.io.OutputStream;
8 import java.io.OutputStreamWriter;
9
10 import net.sf.jpkgmk.util.StreamUtil;
11 import net.sf.jpkgmk.util.StringUtil;
12
13 import org.apache.commons.logging.Log;
14 import org.apache.commons.logging.LogFactory;
15
16
17
18
19
20
21
22
23 public class DefaultFileHandler implements FileHandler
24 {
25 private File file;
26 private Log log = LogFactory.getLog(DefaultFileHandler.class);
27
28
29
30
31
32
33
34 public DefaultFileHandler(File basedir, String filename)
35 {
36 initialize(basedir, filename);
37 }
38
39 private void initialize(File basedir, String filename)
40 {
41 if(basedir == null) {
42 throw new NullPointerException("The parameter 'basedir' must not be null");
43 }
44 if(!basedir.isDirectory()) {
45 throw new IllegalArgumentException("The basedir '" + basedir + "' must be a directory");
46 }
47 if(StringUtil.isNullOrEmpty(filename)) {
48 throw new NullPointerException("The parameter 'filename' must not be null");
49 }
50
51 File targetFile = new File(basedir, filename);
52 this.file = targetFile;
53 }
54
55
56 public File getBasedir() {
57 return file.getParentFile();
58 }
59
60
61 public File getFile() {
62 return file;
63 }
64
65 public void create(ContentWriter contentWriter) throws IOException
66 {
67 File targetFile = this.getFile();
68
69 if(targetFile.exists()) {
70 String message = "The file '" + targetFile.getAbsolutePath() + "' already exists. Will not overwrite it.";
71 throw new PackageException(message);
72 }
73
74 OutputStream outputStream = new FileOutputStream(targetFile);
75 try {
76 BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
77 contentWriter.writeContent(writer);
78 writer.flush();
79 }
80 finally {
81 StreamUtil.tryCloseStream(outputStream);
82 }
83 log.info("Wrote file '" + targetFile.getAbsolutePath() + "'");
84 }
85
86
87
88
89 public void clean() {
90 File file = getFile();
91
92 deleteFile(file);
93 }
94
95
96
97
98
99
100 private void deleteFile(File file) {
101 log.info("Deleting file " + file);
102 if(!file.exists()) {
103
104 log.debug("File '" + file.getAbsolutePath() + "' does not exist. Nothing to delete");
105 return;
106 }
107
108 boolean success = file.delete();
109 if(!success) {
110 throw new PackageException("Could not delete file '" + file + "'.");
111 }
112 }
113
114 @Override
115 public String toString()
116 {
117 return getClass().getName() + "[" +
118 "file=" + this.file + "]";
119 }
120
121
122 }