KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sslexplorer > agent > client > util > FileReplacement


1 package com.sslexplorer.agent.client.util;
2
3 import java.io.BufferedReader JavaDoc;
4 import java.io.ByteArrayOutputStream JavaDoc;
5 import java.io.File JavaDoc;
6 import java.io.FileInputStream JavaDoc;
7 import java.io.FileOutputStream JavaDoc;
8 import java.io.IOException JavaDoc;
9 import java.io.InputStreamReader JavaDoc;
10 import java.io.PrintWriter JavaDoc;
11 import java.io.StringReader JavaDoc;
12 import java.text.MessageFormat JavaDoc;
13 import java.util.Enumeration JavaDoc;
14 import java.util.Hashtable JavaDoc;
15 import java.util.Random JavaDoc;
16
17 /**
18  * This utility will take an input file and replace any number of
19  * tokens before outputing it to an output file, which may or may
20  * not be temporary.
21  *
22  * @author Lee David Painter
23  */

24 public class FileReplacement {
25     
26     public final static String JavaDoc DOS_EOL = "dos";
27     public final static String JavaDoc UNIX_EOL = "unix";
28     public final static String JavaDoc MAC_EOL = "mac";
29     public final static String JavaDoc PLATFORM_EOL = "platform";
30     
31     // Private instance variables
32

33     private Hashtable JavaDoc tokens = new Hashtable JavaDoc();
34     private File JavaDoc templateFile;
35     private File JavaDoc outputFile;
36     private File JavaDoc cwd;
37     private String JavaDoc parameter;
38     private String JavaDoc encoding = "UTF8"; //$NON-NLS-1$
39
private String JavaDoc convertLineEndings;
40
41     /**
42      * Constructor.
43      *
44      * @param cwd working directory
45      */

46     public FileReplacement(File JavaDoc cwd) {
47         this.cwd = cwd;
48     }
49
50     /**
51      * Get the ID. This will only be available of {@link #processReplacementXML(XMLElement, AbstractApplicationLauncher)}
52      * has been called.
53      *
54      * @return id
55      */

56     public String JavaDoc getId() {
57         return parameter;
58     }
59
60     void processReplacementXML(XMLElement el, AbstractApplicationLauncher launcher) throws IOException JavaDoc {
61         if (!el.getName().equalsIgnoreCase("replacements")) { //$NON-NLS-1$
62
throw new IOException JavaDoc(Messages.getString("FileReplacement.elementIsNotReplacements")); //$NON-NLS-1$
63
}
64
65         if (el.getAttribute("templateFile") == null) { //$NON-NLS-1$
66
throw new IOException JavaDoc(Messages.getString("FileReplacement.elementRequiresTemplateFileAttribute")); //$NON-NLS-1$
67
}
68         
69         convertLineEndings = el.getStringAttribute("convertLineEndings");
70
71         templateFile = new File JavaDoc(cwd, el.getAttribute("templateFile").toString()); //$NON-NLS-1$
72

73         if (launcher.events != null)
74             launcher.events.debug(MessageFormat.format(Messages.getString("FileReplacement.templateFile"), new Object JavaDoc[] { templateFile.getAbsolutePath() } ) ); //$NON-NLS-1$
75

76         if (el.getAttribute("outputFile") != null) { //$NON-NLS-1$
77
outputFile = new File JavaDoc(cwd, el.getAttribute("outputFile").toString()); //$NON-NLS-1$
78
} else {
79             outputFile = getTempFile(cwd);
80         }
81
82         if (launcher.events != null)
83             launcher.events.debug(MessageFormat.format(Messages.getString("FileReplacement.outputFile"), new Object JavaDoc[] { outputFile.getAbsolutePath() } ) ); //$NON-NLS-1$
84

85         if (el.getAttribute("parameter") == null) { //$NON-NLS-1$
86
throw new IOException JavaDoc(Messages.getString("FileReplacement.replacementsRequiresParameterAttribute")); //$NON-NLS-1$
87
}
88
89         parameter = el.getAttribute("parameter").toString(); //$NON-NLS-1$
90
launcher.addParameter(parameter, outputFile.getAbsolutePath());
91
92         if (el.getAttribute("encoding") != null) //$NON-NLS-1$
93
encoding = el.getAttribute("encoding").toString(); //$NON-NLS-1$
94

95         if (launcher.events != null)
96             launcher.events.debug(MessageFormat.format(Messages.getString("FileReplacement.outputFileEncoding"), new Object JavaDoc[] { encoding } ) ); //$NON-NLS-1$
97

98         for (Enumeration JavaDoc e = el.getChildren().elements(); e.hasMoreElements();) {
99             XMLElement child = (XMLElement) e.nextElement();
100
101             if (!child.getName().equalsIgnoreCase("replace")) { //$NON-NLS-1$
102
throw new IOException JavaDoc(MessageFormat.format(Messages.getString("FileReplacement.notSupported"), new Object JavaDoc[] { child.getName() } ) ) ;//$NON-NLS-1$
103
}
104
105             if (child.getAttribute("token") == null || child.getAttribute("value") == null) { //$NON-NLS-1$ //$NON-NLS-2$
106
throw new IOException JavaDoc(Messages.getString("FileReplacement.replaceRequiresTokenAndValue")); //$NON-NLS-1$
107
}
108
109             tokens.put(child.getAttribute("token").toString(), child.getAttribute("value").toString()); //$NON-NLS-1$ //$NON-NLS-2$
110
}
111
112     }
113
114     void createReplacementsFile(AbstractApplicationLauncher launcher) throws IOException JavaDoc {
115
116         FileInputStream JavaDoc in = new FileInputStream JavaDoc(templateFile);
117         ByteArrayOutputStream JavaDoc tmp = new ByteArrayOutputStream JavaDoc();
118
119         byte[] buf = new byte[4096];
120         int read;
121
122         while ((read = in.read(buf)) > -1) {
123             tmp.write(buf, 0, read);
124         }
125
126         // First replace all standard parameters etc
127
String JavaDoc outputContent = launcher.replaceTokens(new String JavaDoc(tmp.toByteArray(), encoding));
128
129         for (Enumeration JavaDoc e = tokens.keys(); e.hasMoreElements();) {
130
131             String JavaDoc token = (String JavaDoc) e.nextElement();
132             String JavaDoc value = (String JavaDoc) tokens.get(token);
133
134             if (launcher.events != null)
135                 launcher.events.debug(MessageFormat.format(Messages.getString("FileReplacement.processingReplacement"), new Object JavaDoc[] { token, value } ) ); //$NON-NLS-1$ //$NON-NLS-2$
136

137             // Perform replacement in String
138
outputContent = AbstractApplicationLauncher.replaceAllTokens(outputContent, token, value);
139
140         }
141         
142         if(convertLineEndings != null && !convertLineEndings.equals(PLATFORM_EOL)) {
143             BufferedReader JavaDoc br = new BufferedReader JavaDoc(new StringReader JavaDoc(outputContent));
144             String JavaDoc line = null;
145             PrintWriter JavaDoc pw = new PrintWriter JavaDoc(new FileOutputStream JavaDoc(outputFile));
146             try {
147                 while( ( line = br.readLine() ) != null) {
148                     if(DOS_EOL.equals(convertLineEndings)) {
149                         pw.print(line + "\r\n");
150                     }
151                     else if(UNIX_EOL.equals(convertLineEndings)) {
152                         pw.print(line + "\n");
153                     }
154                     else if(MAC_EOL.equals(convertLineEndings)) {
155                         pw.print(line + "\r");
156                     }
157                     else {
158                         pw.println(line);
159                     }
160                 }
161             } finally {
162                 pw.close();
163             }
164         }
165         else {
166             FileOutputStream JavaDoc out = new FileOutputStream JavaDoc(outputFile);
167             try {
168                 out.write(outputContent.getBytes(encoding));
169             } finally {
170                 out.close();
171             }
172         }
173
174
175     }
176
177     static File JavaDoc getTempFile(File JavaDoc near) throws IOException JavaDoc {
178         String JavaDoc path = null;
179         if (near != null)
180             if (near.isFile())
181                 path = near.getParent();
182             else if (near.isDirectory())
183                 path = near.getPath();
184
185         Random JavaDoc wheel = new Random JavaDoc(); // seeded from the clock
186
File JavaDoc tempFile = null;
187         do {
188             // generate random a number 10,000,000 .. 99,999,999
189
int unique = (wheel.nextInt() & Integer.MAX_VALUE) % 90000000 + 10000000;
190             tempFile = new File JavaDoc(path, Integer.toString(unique) + ".tmp"); //$NON-NLS-1$
191
} while (tempFile.exists());
192         // We "finally" found a name not already used. Nearly always the first
193
// time.
194
// Quickly stake our claim to it by opening/closing it to create it.
195
// In theory somebody could have grabbed it in that tiny window since
196
// we checked if it exists, but that is highly unlikely.
197
new FileOutputStream JavaDoc(tempFile).close();
198
199         // debugging peek at the name generated.
200
if (false) {
201             System.out.println(tempFile.getCanonicalPath());
202         }
203         return tempFile;
204     } // end getTempFile
205
}
206
Popular Tags