KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > knowgate > dataxslt > FastStreamReplacer


1 /*
2   Copyright (C) 2003 Know Gate S.L. All rights reserved.
3                       C/Oņa, 107 1š2 28050 Madrid (Spain)
4
5   Redistribution and use in source and binary forms, with or without
6   modification, are permitted provided that the following conditions
7   are met:
8
9   1. Redistributions of source code must retain the above copyright
10      notice, this list of conditions and the following disclaimer.
11
12   2. The end-user documentation included with the redistribution,
13      if any, must include the following acknowledgment:
14      "This product includes software parts from hipergate
15      (http://www.hipergate.org/)."
16      Alternately, this acknowledgment may appear in the software itself,
17      if and wherever such third-party acknowledgments normally appear.
18
19   3. The name hipergate must not be used to endorse or promote products
20      derived from this software without prior written permission.
21      Products derived from this software may not be called hipergate,
22      nor may hipergate appear in their name, without prior written
23      permission.
24
25   This library is distributed in the hope that it will be useful,
26   but WITHOUT ANY WARRANTY; without even the implied warranty of
27   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
28
29   You should have received a copy of hipergate License with this code;
30   if not, visit http://www.hipergate.org or mail to info@hipergate.org
31 */

32
33 package com.knowgate.dataxslt;
34
35 import java.io.StringBufferInputStream JavaDoc;
36 import java.io.BufferedInputStream JavaDoc;
37 import java.io.IOException JavaDoc;
38 import java.io.InputStream JavaDoc;
39 import java.io.FileInputStream JavaDoc;
40
41 import java.util.HashMap JavaDoc;
42
43 import java.util.Date JavaDoc;
44
45 import com.knowgate.debug.DebugFile;
46
47 /**
48  * Search and Replace a set of substrings with another substrings.
49  * <p>This class is a single-pass fast no wildcards replacer for a given set of substrings.</p>
50  * <p>It is primarily designed for mail merge document personalization routines, where a small
51  * number of substrings have to be replaced at a master document with data retrieved from a list
52  * or database.</p>
53  * @author Sergio Montoro Ten
54  * @version 2.1
55  */

56
57 public class FastStreamReplacer {
58   int BufferSize;
59   int iReplacements;
60   StringBuffer JavaDoc oOutStream;
61
62   // ----------------------------------------------------------
63

64   public FastStreamReplacer() {
65     BufferSize = 32767;
66     oOutStream = new StringBuffer JavaDoc(BufferSize);
67   }
68
69   // ----------------------------------------------------------
70

71   public FastStreamReplacer(int iBufferSize) {
72     BufferSize = iBufferSize;
73     oOutStream = new StringBuffer JavaDoc(BufferSize);
74   }
75
76   // ----------------------------------------------------------
77
/**
78    * Replace subtrings from a Stream.
79    * @param oInStream Input Stream containing substrings to be replaced.
80    * @param oMap Map with values to be replaced.<br>
81    * Each map key will be replaced by its value.<br>
82    * Map keys must appear in stream text as {#<i>key</i>}<br>
83    * For example: InputStream "Today is {#System.Date}" will be replaced with "Today is 2002-02-21 11:32:44"<br>
84    * No wildcards are accepted.<br>
85    * Map keys must not contain {#&nbsp;} key markers.
86    * @return String Replacements Result
87    * @throws IOException
88    */

89
90   public String JavaDoc replace(InputStream JavaDoc oFileInStream, HashMap JavaDoc oMap) throws IOException JavaDoc {
91
92     if (DebugFile.trace) {
93       DebugFile.writeln("Begin FastStreamReplacer.replace([InputStream],[HashMap])");
94       DebugFile.incIdent();
95     }
96
97     int iChr;
98     String JavaDoc sKey;
99     Object JavaDoc oValue;
100
101     Date JavaDoc dtToday = new Date JavaDoc();
102     String JavaDoc sToday = String.valueOf(dtToday.getYear()+1900) + "-" + String.valueOf(dtToday.getMonth()+1) + "-" + String.valueOf(dtToday.getDate());
103
104     oMap.put("Sistema.Fecha",sToday);
105     oMap.put("System.Date",sToday);
106
107     iReplacements = 0;
108
109     BufferedInputStream JavaDoc oInStream = new BufferedInputStream JavaDoc(oFileInStream, BufferSize);
110
111     oOutStream.setLength(0);
112
113     do {
114       iChr = oInStream.read();
115
116       if (-1==iChr)
117         break;
118
119       else {
120
121         if (123 == iChr) {
122           // Se encontro el caracter '{'
123
iChr = oInStream.read();
124           if (35 == iChr) {
125             // Se encontro el caracter '#'
126

127             iReplacements++;
128
129             sKey = "";
130
131             do {
132
133               iChr = oInStream.read();
134               if (-1==iChr || 125==iChr)
135                 break;
136               sKey += (char) iChr;
137
138             } while (true);
139
140             oValue = oMap.get(sKey);
141
142             if (null!=oValue)
143               oOutStream.append(((String JavaDoc)oValue));
144           } // fi ('#')
145

146           else {
147             oOutStream.append((char)123);
148             oOutStream.append((char)iChr);
149           }
150
151         } // fi ('{')
152

153         else
154           oOutStream.append((char)iChr);
155       } // fi (!eof)
156

157     } while (true);
158
159     oInStream.close();
160
161     if (DebugFile.trace) {
162       DebugFile.decIdent();
163       DebugFile.writeln("End FastStreamReplacer.replace() : " + String.valueOf(oOutStream.length()));
164     }
165
166     return oOutStream.toString();
167   } // replace()
168

169   // ----------------------------------------------------------
170
/**
171    * Replace subtrings from a Stream.
172    * @param oInStream Input Stream containing substrings to be replaced.
173    * @param oMap Map with values to be replaced.<br>
174    * Each map key will be replaced by its value.<br>
175    * Map keys must appear in stream text as {#<i>key</i>}<br>
176    * For example: InputStream "Today is {#System.Date}" will be replaced with "Today is 2002-02-21 11:32:44"<br>
177    * No wildcards are accepted.<br>
178    * Map keys must not contain {#&nbsp;} key markers.
179    * @return String Replacements Result
180    * @throws IOException
181    * @throws IndexOutOfBoundsException
182    */

183
184   public String JavaDoc replace(StringBuffer JavaDoc oStrBuff, HashMap JavaDoc oMap)
185     throws IOException JavaDoc, IndexOutOfBoundsException JavaDoc {
186
187     if (DebugFile.trace) {
188       DebugFile.writeln("Begin FastStreamReplacer.replace([StringBuffer],[HashMap])");
189       DebugFile.incIdent();
190     }
191
192     int iChr;
193     String JavaDoc sKey;
194     Object JavaDoc oValue;
195
196     Date JavaDoc dtToday = new Date JavaDoc();
197     String JavaDoc sToday = String.valueOf(dtToday.getYear()+1900) + "-" + String.valueOf(dtToday.getMonth()+1) + "-" + String.valueOf(dtToday.getDate());
198
199     oMap.put("Sistema.Fecha",sToday);
200     oMap.put("System.Date",sToday);
201
202     iReplacements = 0;
203
204     oOutStream.setLength(0);
205
206     int iAt = 0;
207     final int iLen = oStrBuff.length();
208
209     while (iAt<iLen) {
210       iChr = oStrBuff.charAt(iAt++);
211
212         if (123 == iChr) {
213           // Se encontro el caracter '{'
214
iChr = oStrBuff.charAt(iAt++);
215           if (35 == iChr) {
216             // Se encontro el caracter '#'
217
iReplacements++;
218
219             sKey = "";
220
221             while (iAt<iLen) {
222               iChr = oStrBuff.charAt(iAt++);
223               if (125==iChr) break;
224               sKey += (char) iChr;
225             } // wend
226

227             oValue = oMap.get(sKey);
228
229             if (null!=oValue)
230               oOutStream.append(((String JavaDoc)oValue));
231           } // fi ('#')
232

233           else {
234             oOutStream.append((char)123);
235             oOutStream.append((char)iChr);
236           }
237
238         } // fi ('{')
239

240         else
241           oOutStream.append((char)iChr);
242
243     } // wend
244

245     if (DebugFile.trace) {
246       DebugFile.decIdent();
247       DebugFile.writeln("End FastStreamReplacer.replace() : " + String.valueOf(oOutStream.length()));
248     }
249
250     return oOutStream.toString();
251   } // replace()
252

253   // ----------------------------------------------------------
254

255
256   /**
257    * Replace substrings from a Text File.
258    * @param sFilePath File containing text to be replaced.
259    * @param oMap Map with values to be replaced.<br>
260    * Each map key will be replaced by its value.<br>
261    * Map keys must appear in stream text as {#<i>key</i>}<br>
262    * For example: InputStream "Today is {#System.Date}" will be replaced with "Today is 2002-02-21 11:32:44"<br>
263    * No wildcards are accepted.<br>
264    * Map keys must not contain {#&nbsp;} key markers.
265    * @return String Replacements Result.
266    * @throws IOException
267    */

268
269   public String JavaDoc replace(String JavaDoc sFilePath, HashMap JavaDoc oMap) throws IOException JavaDoc {
270
271     FileInputStream JavaDoc oStrm = new FileInputStream JavaDoc(sFilePath);
272     String JavaDoc sRetVal = replace(oStrm, oMap);
273     oStrm.close();
274
275     return sRetVal;
276   }
277
278   // ----------------------------------------------------------
279

280   /**
281    * Number of replacements done in last call to replace() method.
282    */

283   public int lastReplacements() {
284     return iReplacements;
285   }
286
287   // ----------------------------------------------------------
288

289   /**
290    * <p>Create a HashMap for a couple of String Arrays</p>
291    * This method is just a convenient shortcut for creating input HashMap for
292    * replace methods from this class
293    * @param aKeys An array of Strings to be used as keys
294    * @param aValues An array of Strings that will be the actual values for the keys
295    * @return A HashMap with the given keys and values
296    */

297   public static HashMap JavaDoc createMap(String JavaDoc[] aKeys, String JavaDoc[] aValues) {
298
299     HashMap JavaDoc oRetVal = new HashMap JavaDoc(5+((aKeys.length*100)/60));
300
301     for (int k=0; k<aKeys.length; k++)
302       oRetVal.put(aKeys[k], aValues[k]);
303
304     return oRetVal;
305   } // createMap
306

307   // ----------------------------------------------------------
308

309 } // FastStreamReplacer
310
Popular Tags