KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > izforge > izpack > util > os > unix > ShellScript


1 /*
2  * IzPack - Copyright 2001-2007 Julien Ponge, All Rights Reserved.
3  *
4  * http://www.izforge.com/izpack/ http://developer.berlios.de/projects/izpack/
5  *
6  * Copyright 2006 Marc Eppelmann
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software distributed under the License
14  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
15  * or implied. See the License for the specific language governing permissions and limitations under
16  * the License.
17  */

18 package com.izforge.izpack.util.os.unix;
19
20 import com.izforge.izpack.util.FileExecutor;
21
22 import java.io.BufferedWriter JavaDoc;
23 import java.io.File JavaDoc;
24 import java.io.FileWriter JavaDoc;
25 import java.io.IOException JavaDoc;
26
27 import java.util.Date JavaDoc;
28
29 /**
30  * A Generator, Wrapper and Executor for Unix ShellScripts
31  *
32  * @author marc.eppelmann@reddot.de
33  */

34 public class ShellScript
35 {
36
37     // ~ Static fields/initializers *********************************************************
38

39     // ~ Static fields/initializers *********************************************************
40
/** Author = "marc.eppelmann_at_gmx.de" */
41     private final static String JavaDoc Author = "Author: marc.eppelmann_at_gmx.de";
42
43     /** Generator = "Generator: " + ShellScript.class.getName() */
44     private final static String JavaDoc Generator = "Generator: " + ShellScript.class.getName();
45
46     /** internal SourceCode Management ( currently 'svn') ID :: 'SCM_ID = "$Id$"' */
47     private final static String JavaDoc SCM_ID = "$Id$";
48
49     /** internal Revision = "$Revision$" */
50     private final static String JavaDoc Revision = "$Revision$";
51
52     /** internal comment prefix; makes a line as comment:-) :: 'CommentPre = "# "' */
53     private final static String JavaDoc CommentPre = "# ";
54
55     /** H = CommentPre */
56     private final static String JavaDoc H = CommentPre;
57
58     /** the linefeed: lf = "\n" */
59     private final static String JavaDoc lf = "\n";
60
61     /** lh = lf + H = "\n#" */
62     private final static String JavaDoc lh = lf + H;
63
64     /** the explanation header for this generated script */
65     private final static String JavaDoc explanation = lh + "This is an automatically generated Script."
66             + lh + "Usually this can be removed if the Generator " + lh
67             + "was unable to remove the script after execution." + lf;
68
69     /** "Generated at: " + new Date().toString() */
70     private static String JavaDoc currentDateMsg = "Generated at: " + new Date JavaDoc().toString();
71
72     /** the header of this ShellScript */
73     private final static String JavaDoc header = lf + explanation + lf + H + Generator + lf + H + SCM_ID
74             + lf + H + Author + lf + H + Revision + lf + H + currentDateMsg + lf + lf;
75
76     // ~ Instance fields ********************************************************************
77

78     // ~ Instance fields ********************************************************************
79
/** Internal ContentBuffer of this ShellScript */
80     private StringBuffer JavaDoc content = new StringBuffer JavaDoc();
81
82     /** internal field: where to write via write( itsLocation ) this shellscript. */
83     private String JavaDoc itsLocation;
84
85     // ~ Constructors ***********************************************************************
86

87     // ~ Constructors ***********************************************************************
88
/**
89      * Creates and initializes the ShellScript for running on the given shell.
90      *
91      * @param aShell "sh", "bash", "ksh", "csh" and so an...
92      */

93     public ShellScript(String JavaDoc aShell)
94     {
95         content.append("#!/usr/bin/env " + aShell);
96         content.append(header);
97     }
98
99     /**
100      * Creates and initializes the ShellScript for running on the bourne shell: "sh".
101      */

102     public ShellScript()
103     {
104         this("sh");
105     }
106
107     // ~ Methods ****************************************************************************
108

109     // ~ Methods ****************************************************************************
110
/**
111      * Appends an Object or String to this ShellScript.
112      *
113      * @param anObject the Object to append
114      */

115     public void append(Object JavaDoc anObject)
116     {
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     {
127         content.append(aChar);
128     }
129
130     /**
131      * Appends an Object or String to this ShellScript with unix linefeed ("\n").
132      *
133      * @param anObject the Object to append
134      */

135     public void appendln(Object JavaDoc anObject)
136     {
137         append(anObject);
138         append(lf);
139     }
140
141     /**
142      * Appends a Char Object or String to this ShellScript with unix linefeed ("\n").
143      *
144      * @param aChar a char to append
145      */

146     public void appendln(char aChar)
147     {
148         append(aChar);
149         append(lf);
150     }
151
152     /**
153      * Appends an Object or String to this ShellScript with unix linefeed ("\n").
154      */

155     public void appendln()
156     {
157         append(lf);
158     }
159
160     /**
161      * gets the Content of this Script.
162      *
163      * @return the Content
164      */

165     public StringBuffer JavaDoc getContent()
166     {
167         return content;
168     }
169
170     /**
171      * Gets the Content of this Script as String
172      *
173      * @return the script as String
174      */

175     public String JavaDoc getContentAsString()
176     {
177         return content.toString();
178     }
179
180     /**
181      * Dumps the ShellScript Content, and Location.
182      * Use getContentAsString() to get this ShellScripts Content
183      *
184      * @return The ShellScript as Object dump.
185      */

186     public String JavaDoc toString()
187     {
188         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
189         result.append(getClass().getName());
190         result.append('\n');
191         result.append(itsLocation);
192         result.append('\n');
193         result.append(content);
194
195         return result.toString();
196     }
197
198     /**
199      * write this to the given Destination FileName
200      *
201      * @param aDestination a destination filename
202      */

203     public void write(String JavaDoc aDestination)
204     {
205         itsLocation = aDestination;
206
207         try
208         {
209             BufferedWriter JavaDoc writer = new BufferedWriter JavaDoc(new FileWriter JavaDoc(aDestination));
210             writer.write(content.toString());
211             writer.write(lh + aDestination + lf);
212             writer.flush();
213             writer.close();
214         }
215         catch (IOException JavaDoc e)
216         {
217             e.printStackTrace();
218         }
219     }
220
221     /**
222      * Executes thsi ShellScript with the given Params.<br>
223      * NOTE: the params cannot be contain whitespaces.<br>
224      * This (su -c &lt;br&gt;"cp from to"&lt;/br&gt;) would not work:<br>
225      * because the underlaying java.runtime.exec("command") does not handle balanced or unbalanced
226      * (") correctly.<br>
227      * else just whitespace separate tokens.<br>
228      * This means for the sample. runtime.exec() would ever execute such as: su "-c" "\"cp"
229      * "fromFile" "toFile\""<br>
230      * But this his hidden in Sun's native code ;-(<br>
231      * This was the reason to write thsi class to have a Workaround :-)
232      *
233      * @param itsParams
234      *
235      * @return the output from stdout of the execution.
236      */

237     public String JavaDoc exec(String JavaDoc itsParams)
238     {
239         FileExecutor.getExecOutput(new String JavaDoc[] { UnixHelper.getCustomCommand("chmod"), "+x",
240                 itsLocation});
241
242         if (itsParams != null)
243         {
244             return FileExecutor.getExecOutput(new String JavaDoc[] { itsLocation, itsParams});
245         }
246         else
247         {
248             return FileExecutor.getExecOutput(new String JavaDoc[] { itsLocation});
249         }
250     }
251
252     /**
253      * Execute this ShellScript.
254      *
255      * @return the output from stdout of the execution.
256      */

257     public String JavaDoc exec()
258     {
259         return exec(null);
260     }
261
262     /**
263      * Execs ths given lines in the creted shell stored on location.
264      *
265      * @param aShell A Shell which will be eexecute the script.
266      * @param lines The content of the script.
267      * @param aLocation The location where to store.
268      * @param itsParams Th eoptional params of the script.
269      *
270      * @return the exec result
271      */

272     public static String JavaDoc execute(String JavaDoc aShell, StringBuffer JavaDoc lines, String JavaDoc aLocation,
273             String JavaDoc itsParams)
274     {
275         ShellScript s = new ShellScript((aShell == null) ? "sh" : aShell);
276         s.append(lines);
277         s.write(aLocation);
278
279         return (itsParams == null) ? s.exec() : s.exec(itsParams);
280     }
281
282     /**
283      * Executes ths given lines in the created default shell (sh) stored on location.
284      *
285      * @param lines the lines of the script to exec.s
286      * @param aLocation where to store
287      *
288      * @return the stdout of the script.
289      */

290     public static String JavaDoc execute(StringBuffer JavaDoc lines, String JavaDoc aLocation)
291     {
292         return ShellScript.execute(null, lines, aLocation, null);
293     }
294
295     /**
296      * Executes and removes the script.<br>
297      * The Lines be also written in python or perl,<br>
298      * In this case, the Shell must be python or perl or so.
299      *
300      * @param aShell The Shell which should exec the script. Can be also be python or perl, if the
301      * shellcontent is given in this language.
302      * @param lines of the script.
303      * @param aLocation where to store.
304      * @param itsParams which should be pass to the script.
305      *
306      * @return the stdout.
307      */

308     public static String JavaDoc execAndDelete(String JavaDoc aShell, StringBuffer JavaDoc lines, String JavaDoc aLocation,
309             String JavaDoc itsParams)
310     {
311         String JavaDoc result = execute(aShell, lines, aLocation, itsParams);
312         File JavaDoc location = new File JavaDoc(aLocation);
313
314         try
315         {
316             location.delete();
317         }
318         catch (Exception JavaDoc e)
319         {
320             location.deleteOnExit();
321         }
322
323         return result;
324     }
325
326     /**
327      * Executes and removes the script.
328      *
329      * @param lines of the script.
330      * @param aLocation where to store.
331      *
332      * @return the sdtout.
333      */

334     public static String JavaDoc execAndDelete(StringBuffer JavaDoc lines, String JavaDoc aLocation)
335     {
336         return execAndDelete(null, lines, aLocation, null);
337     }
338
339     /**
340      * Test Main Method Run test with: java -cp .jar com.izforge.izpack.util.os.unix.ShellScript
341      *
342      * @param args Arguments from Commandline
343      */

344     public static void main(String JavaDoc[] args)
345     {
346         /*
347          * ShellScript s = new ShellScript( ); s.append( "ls $HOME" ); s.write( System.getProperty(
348          * "user.home", "." ) + File.separator + "test.sh" );
349          */

350
351         /*
352          * System.out.println(ShellScript.execute(new StringBuffer("ls $HOME"), System.getProperty(
353          * "user.home", ".") + File.separator + Long.toString(System.currentTimeMillis()) +
354          * "test.sh"));
355          */

356     }
357 }
358
Popular Tags