001: /*
002: * ChainBuilder ESB
003: * Visual Enterprise Integration
004: *
005: * Copyright (C) 2006 Bostech Corporation
006: *
007: * This program is free software; you can redistribute it and/or modify it
008: * under the terms of the GNU General Public License as published by the
009: * Free Software Foundation; either version 2 of the License, or (at your option)
010: * any later version.
011: *
012: * This program is distributed in the hope that it will be useful,
013: * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
014: * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
015: * for more details.
016: *
017: * You should have received a copy of the GNU General Public License along with
018: * this program; if not, write to the Free Software Foundation, Inc.,
019: * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
020: *
021: *
022: * $Id:$
023: *
024: */
025: package com.bostechcorp.cbesb.common.util;
026:
027: import java.io.BufferedOutputStream;
028: import java.io.BufferedReader;
029: import java.io.ByteArrayOutputStream;
030: import java.io.File;
031: import java.io.FileInputStream;
032: import java.io.FileNotFoundException;
033: import java.io.FileOutputStream;
034: import java.io.IOException;
035: import java.io.InputStreamReader;
036: import java.io.OutputStream;
037: import java.io.PrintStream;
038: import java.util.HashMap;
039: import java.util.Iterator;
040: import java.util.Map;
041:
042: import org.apache.commons.logging.Log;
043: import org.apache.commons.logging.LogFactory;
044:
045: /**
046: * This is the main class witch will process templates. This class will replace all placeholders with
047: * specified values. Placeholders ,in template file, are marked between "#" chars. (ie #placeholder#).
048: * @author LPS
049: *
050: */
051: public class TemplateProcessorIO {
052: protected final transient Log logger = LogFactory
053: .getLog(getClass());
054:
055: private boolean translateOnce = false;
056: /**
057: * input template file name
058: */
059: private String fileIn = "Default FileName";
060:
061: /**
062: * output source file name
063: */
064: private String fileOut = "Default FileName";
065:
066: /**
067: * the string holders to be replaced in template file.
068: * A holder is a string marked between "#" chars in *.template file.
069: */
070: private HashMap holders;
071:
072: /**
073: * this is the Input/output and Filtering class. It reads changes, if
074: * necessary and writes content to files
075: *
076: * @param fileIn
077: * @param fileOut
078: * @param packageName
079: * @param className
080: * @param methodName
081: */
082: public TemplateProcessorIO(String fileIn, String fileOut, HashMap h) {
083: setFileIn(fileIn);
084: setFileOut(fileOut);
085: setHolders(h);
086: }
087:
088: /**
089: * after Holders, fileIn and FileOut are set, call
090: * this metod to execute the process.
091: *
092: * This method reads content of the input file, Filter/change it and write
093: * the (changed) content to output file
094: *
095: * @return nothing
096: */
097: public void filterFile() throws Exception {
098: FileInputStream fistream = null;
099: FileOutputStream fostream = null;
100:
101: // Checking if the paths exist,and creating the patch if necessary
102: String onlyPath = getFileOut();
103: if (getFileOut().endsWith(File.separator)) {
104: onlyPath = onlyPath.substring(0, onlyPath.length() - 1);
105: }
106: onlyPath = onlyPath.substring(0, onlyPath.length()
107: - getFileName(onlyPath).length());
108:
109: if (!exist(onlyPath))
110: createPathToFile(getFileOut());
111: //
112: // opening input file
113: try {
114: fistream = new FileInputStream(getFileIn());
115: } catch (FileNotFoundException e) {
116:
117: throw new IOException("Error opening file: "
118: + e.getMessage());
119: }
120:
121: // opening output file
122: try {
123: fostream = new FileOutputStream(getFileOut());
124: } catch (FileNotFoundException e) {
125: throw new IOException("Error opening file: "
126: + e.getMessage());
127: }
128: try {
129: // the cherry from the cake
130: process(fistream, fostream);
131: } catch (Exception ex) {
132: throw ex;
133: }
134: // closing all
135: finally {
136: if (fistream != null)
137: fistream.close();
138: fostream.close();
139:
140: }
141: }
142:
143: /**
144: * Will process the imput stream, by replacing all placeholders, and sending the result to
145: * output stream. ReadLine is used to read the imput stream.
146: *
147: * @param fistream - input stream
148: * @param outStream - output stream
149: * @throws Exception - just in case something goes wrong
150: */
151: private void process(FileInputStream fistream,
152: OutputStream outStream) throws Exception {
153:
154: BufferedReader distream = new BufferedReader(
155: new InputStreamReader(fistream)); //
156:
157: PrintStream pstream = new PrintStream(outStream);
158:
159: // process
160:
161: try {
162: String line = null;
163: do {
164: line = distream.readLine();
165: if (line != null) {
166: // iterating over the dictionary and replacing found text
167: for (Iterator iter = getHolders().entrySet()
168: .iterator(); iter.hasNext();) {
169: Map.Entry entry = (Map.Entry) iter.next();
170: String key = (String) entry.getKey();
171: String value = (String) entry.getValue();
172: //System.out.println("KxV="+key+" X " + value);
173:
174: if (key != null && key.length() != 0) //validating key
175: {
176: if (translateOnce()) {
177: if (line.contains(key)) {
178: line = line
179: .replaceFirst(key, value);
180: getHolders().remove(entry);
181: }
182: } else {
183: line = line.replaceAll(key, value);
184: }
185: }
186:
187: }
188:
189: pstream.println(line);
190: }
191: } while (line != null);
192:
193: } catch (IOException e) {
194: logger.error("Exception in reading/writing file: "
195: + e.getMessage());
196: if (logger.isDebugEnabled()) {
197: logger.debug("Exception in reading/writing file:", e);
198: }
199: throw e;
200: } finally {
201: if (distream != null)
202: distream.close();
203: if (pstream != null)
204: pstream.close();
205: }
206: }
207:
208: public boolean exist(String fileName) {
209: return (new File(fileName)).exists();
210: }
211:
212: public String getFileName(String fileName) {
213: return (new File(fileName)).getName();
214: }
215:
216: public boolean createPathToFile(String fileName) {
217: // java.lang.SecurityManager.checkRead(java.lang.String)
218: // java.lang.SecurityManager.checkWrite(java.lang.String)
219: boolean result = false;
220: try {
221: String onlyPath = fileName;
222: if (fileName.endsWith(File.separator)) {
223: onlyPath = onlyPath.substring(0, onlyPath.length() - 1);
224: }
225: onlyPath = onlyPath.substring(0, onlyPath.length()
226: - getFileName(onlyPath).length());
227: result = (new File(onlyPath)).mkdirs();
228: } catch (SecurityException e) {
229:
230: logger
231: .error("Directory creation faild. Check R/W permissions: "
232: + e.getMessage());
233: if (logger.isDebugEnabled()) {
234: logger
235: .debug(
236: "Directory creation faild. Check R/W permissions:",
237: e);
238: }
239:
240: }
241: return result;
242: }
243:
244: /**
245: * @return the fileIn
246: */
247: public String getFileIn() {
248: return fileIn;
249: }
250:
251: /**
252: * @param fileIn
253: * the fileIn to set
254: */
255: public void setFileIn(String fileIn) {
256: this .fileIn = fileIn;
257: }
258:
259: /**
260: * @return the fileOut
261: */
262: public String getFileOut() {
263: return fileOut;
264: }
265:
266: /**
267: * @param fileOut
268: * the fileOut to set
269: */
270: public void setFileOut(String fileOut) {
271: this .fileOut = fileOut;
272: }
273:
274: /**
275: * If translate once is true then after first
276: * translation the placeholder will be removed. And future
277: * occurences will not be processed.
278: *
279: * @return the translateOnce ()
280: */
281: public boolean translateOnce() {
282: return translateOnce;
283: }
284:
285: /**
286: * If translate once is true then after first
287: * translation the placeholder will be removed. And future
288: * occurences will not be processed.
289: *
290: * @param translateOnce the translateOnce to set
291: */
292: public void setTranslateOnce(boolean translateOnce) {
293: this .translateOnce = translateOnce;
294: }
295:
296: /**
297: *
298: * Dictionary like structure, with holder as HashMap key and value to be
299: * replaced as HashMap value.
300: *
301: * @return the holders
302: */
303: public HashMap getHolders() {
304: if (holders == null)
305: return new HashMap<String, String>();
306: return holders;
307: }
308:
309: /**
310: * @param holders
311: * the holders to set
312: */
313: public void setHolders(HashMap holders) {
314: this .holders = holders;
315: }
316:
317: @SuppressWarnings("unchecked")
318: public void addHolder(String holder, String value) {
319: getHolders().put(holder, value);
320: }
321:
322: }
|