001: /*
002: * IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved.
003: *
004: * http://izpack.org/ http://izpack.codehaus.org/
005: *
006: * Copyright 2006 Marc Eppelmann
007: *
008: * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
009: * in compliance with the License. You may obtain a copy of the License at
010: *
011: * http://www.apache.org/licenses/LICENSE-2.0
012: *
013: * Unless required by applicable law or agreed to in writing, software distributed under the License
014: * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
015: * or implied. See the License for the specific language governing permissions and limitations under
016: * the License.
017: */
018: package com.izforge.izpack.util.os.unix;
019:
020: import com.izforge.izpack.util.FileExecutor;
021:
022: import java.io.BufferedWriter;
023: import java.io.File;
024: import java.io.FileWriter;
025: import java.io.IOException;
026:
027: import java.util.Date;
028:
029: /**
030: * A Generator, Wrapper and Executor for Unix ShellScripts
031: *
032: * @author marc.eppelmann@reddot.de
033: */
034: public class ShellScript {
035:
036: // ~ Static fields/initializers *********************************************************
037:
038: // ~ Static fields/initializers *********************************************************
039: /** Author = "marc.eppelmann_at_gmx.de" */
040: private final static String Author = "Author: marc.eppelmann_at_gmx.de";
041:
042: /** Generator = "Generator: " + ShellScript.class.getName() */
043: private final static String Generator = "Generator: "
044: + ShellScript.class.getName();
045:
046: /** internal SourceCode Management ( currently 'svn') ID :: 'SCM_ID = "$Id$"' */
047: private final static String SCM_ID = "$Id$";
048:
049: /** internal Revision = "$Revision$" */
050: private final static String Revision = "$Revision$";
051:
052: /** internal comment prefix; makes a line as comment:-) :: 'CommentPre = "# "' */
053: private final static String CommentPre = "# ";
054:
055: /** H = CommentPre */
056: private final static String H = CommentPre;
057:
058: /** the linefeed: lf = "\n" */
059: private final static String lf = "\n";
060:
061: /** lh = lf + H = "\n#" */
062: private final static String lh = lf + H;
063:
064: /** the explanation header for this generated script */
065: private final static String explanation = lh
066: + "This is an automatically generated Script." + lh
067: + "Usually this can be removed if the Generator " + lh
068: + "was unable to remove the script after execution." + lf;
069:
070: /** "Generated at: " + new Date().toString() */
071: private static String currentDateMsg = "Generated at: "
072: + new Date().toString();
073:
074: /** the header of this ShellScript */
075: private final static String header = lf + explanation + lf + H
076: + Generator + lf + H + SCM_ID + lf + H + Author + lf + H
077: + Revision + lf + H + currentDateMsg + lf + lf;
078:
079: // ~ Instance fields ********************************************************************
080:
081: // ~ Instance fields ********************************************************************
082: /** Internal ContentBuffer of this ShellScript */
083: private StringBuffer content = new StringBuffer();
084:
085: /** internal field: where to write via write( itsLocation ) this shellscript. */
086: private String itsLocation;
087:
088: // ~ Constructors ***********************************************************************
089:
090: // ~ Constructors ***********************************************************************
091: /**
092: * Creates and initializes the ShellScript for running on the given shell.
093: *
094: * @param aShell "sh", "bash", "ksh", "csh" and so an...
095: */
096: public ShellScript(String aShell) {
097: content.append("#!/usr/bin/env ").append(aShell);
098: content.append(header);
099: }
100:
101: /**
102: * Creates and initializes the ShellScript for running on the bourne shell: "sh".
103: */
104: public ShellScript() {
105: this ("sh");
106: }
107:
108: // ~ Methods ****************************************************************************
109:
110: // ~ Methods ****************************************************************************
111: /**
112: * Appends an Object or String to this ShellScript.
113: *
114: * @param anObject the Object to append
115: */
116: public void append(Object anObject) {
117: content.append(anObject);
118: }
119:
120: /**
121: * Appends a Char to this ShellScript.
122: *
123: * @param aChar a char to append
124: */
125: public void append(char aChar) {
126: content.append(aChar);
127: }
128:
129: /**
130: * Appends an Object or String to this ShellScript with unix linefeed ("\n").
131: *
132: * @param anObject the Object to append
133: */
134: public void appendln(Object anObject) {
135: append(anObject);
136: append(lf);
137: }
138:
139: /**
140: * Appends a Char Object or String to this ShellScript with unix linefeed ("\n").
141: *
142: * @param aChar a char to append
143: */
144: public void appendln(char aChar) {
145: append(aChar);
146: append(lf);
147: }
148:
149: /**
150: * Appends an Object or String to this ShellScript with unix linefeed ("\n").
151: */
152: public void appendln() {
153: append(lf);
154: }
155:
156: /**
157: * gets the Content of this Script.
158: *
159: * @return the Content
160: */
161: public StringBuffer getContent() {
162: return content;
163: }
164:
165: /**
166: * Gets the Content of this Script as String
167: *
168: * @return the script as String
169: */
170: public String getContentAsString() {
171: return content.toString();
172: }
173:
174: /**
175: * Dumps the ShellScript Content, and Location.
176: * Use getContentAsString() to get this ShellScripts Content
177: *
178: * @return The ShellScript as Object dump.
179: */
180: public String toString() {
181: StringBuffer result = new StringBuffer();
182: result.append(getClass().getName());
183: result.append('\n');
184: result.append(itsLocation);
185: result.append('\n');
186: result.append(content);
187:
188: return result.toString();
189: }
190:
191: /**
192: * write this to the given Destination FileName
193: *
194: * @param aDestination a destination filename
195: */
196: public void write(String aDestination) {
197: itsLocation = aDestination;
198:
199: try {
200: BufferedWriter writer = new BufferedWriter(new FileWriter(
201: aDestination));
202: writer.write(content.toString());
203: writer.write(lh + aDestination + lf);
204: writer.flush();
205: writer.close();
206: } catch (IOException e) {
207: e.printStackTrace();
208: }
209: }
210:
211: /**
212: * Executes thsi ShellScript with the given Params.<br>
213: * NOTE: the params cannot be contain whitespaces.<br>
214: * This (su -c <br>"cp from to"</br>) would not work:<br>
215: * because the underlaying java.runtime.exec("command") does not handle balanced or unbalanced
216: * (") correctly.<br>
217: * else just whitespace separate tokens.<br>
218: * This means for the sample. runtime.exec() would ever execute such as: su "-c" "\"cp"
219: * "fromFile" "toFile\""<br>
220: * But this his hidden in Sun's native code ;-(<br>
221: * This was the reason to write thsi class to have a Workaround :-)
222: *
223: * @param itsParams
224: *
225: * @return the output from stdout of the execution.
226: */
227: public String exec(String itsParams) {
228: FileExecutor
229: .getExecOutput(new String[] {
230: UnixHelper.getCustomCommand("chmod"), "+x",
231: itsLocation });
232:
233: if (itsParams != null) {
234: return FileExecutor.getExecOutput(new String[] {
235: itsLocation, itsParams });
236: } else {
237: return FileExecutor
238: .getExecOutput(new String[] { itsLocation });
239: }
240: }
241:
242: /**
243: * Execute this ShellScript.
244: *
245: * @return the output from stdout of the execution.
246: */
247: public String exec() {
248: return exec(null);
249: }
250:
251: /**
252: * Execs ths given lines in the creted shell stored on location.
253: *
254: * @param aShell A Shell which will be eexecute the script.
255: * @param lines The content of the script.
256: * @param aLocation The location where to store.
257: * @param itsParams Th eoptional params of the script.
258: *
259: * @return the exec result
260: */
261: public static String execute(String aShell, StringBuffer lines,
262: String aLocation, String itsParams) {
263: ShellScript s = new ShellScript((aShell == null) ? "sh"
264: : aShell);
265: s.append(lines);
266: s.write(aLocation);
267:
268: return (itsParams == null) ? s.exec() : s.exec(itsParams);
269: }
270:
271: /**
272: * Executes ths given lines in the created default shell (sh) stored on location.
273: *
274: * @param lines the lines of the script to exec.s
275: * @param aLocation where to store
276: *
277: * @return the stdout of the script.
278: */
279: public static String execute(StringBuffer lines, String aLocation) {
280: return ShellScript.execute(null, lines, aLocation, null);
281: }
282:
283: /**
284: * Executes and removes the script.<br>
285: * The Lines be also written in python or perl,<br>
286: * In this case, the Shell must be python or perl or so.
287: *
288: * @param aShell The Shell which should exec the script. Can be also be python or perl, if the
289: * shellcontent is given in this language.
290: * @param lines of the script.
291: * @param aLocation where to store.
292: * @param itsParams which should be pass to the script.
293: *
294: * @return the stdout.
295: */
296: public static String execAndDelete(String aShell,
297: StringBuffer lines, String aLocation, String itsParams) {
298: String result = execute(aShell, lines, aLocation, itsParams);
299: File location = new File(aLocation);
300:
301: try {
302: location.delete();
303: } catch (Exception e) {
304: location.deleteOnExit();
305: }
306:
307: return result;
308: }
309:
310: /**
311: * Executes and removes the script.
312: *
313: * @param lines of the script.
314: * @param aLocation where to store.
315: *
316: * @return the sdtout.
317: */
318: public static String execAndDelete(StringBuffer lines,
319: String aLocation) {
320: return execAndDelete(null, lines, aLocation, null);
321: }
322:
323: /**
324: * Test Main Method Run test with: java -cp .jar com.izforge.izpack.util.os.unix.ShellScript
325: *
326: * @param args Arguments from Commandline
327: */
328: public static void main(String[] args) {
329: /*
330: * ShellScript s = new ShellScript( ); s.append( "ls $HOME" ); s.write( System.getProperty(
331: * "user.home", "." ) + File.separator + "test.sh" );
332: */
333:
334: /*
335: * System.out.println(ShellScript.execute(new StringBuffer("ls $HOME"), System.getProperty(
336: * "user.home", ".") + File.separator + Long.toString(System.currentTimeMillis()) +
337: * "test.sh"));
338: */
339: }
340: }
|