File: BackgroundProcess.java

package info (click to toggle)
libgroboutils-java 5-3
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 9,396 kB
  • ctags: 11,186
  • sloc: java: 59,748; xml: 12,762; sh: 377; perl: 104; makefile: 20
file content (411 lines) | stat: -rw-r--r-- 10,792 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
/*
 * @(#)BackgroundProcess.java    1.0.0 11/17/2000 - 13:41:07
 *
 * Copyright (C) 2000,,2003 2002 Matt Albrecht
 * groboclown@users.sourceforge.net
 * http://groboutils.sourceforge.net
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a
 *  copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the 
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software. 
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL 
 *  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 *  DEALINGS IN THE SOFTWARE.
 */

package net.sourceforge.groboutils.util.thread.v1;


import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

import java.lang.reflect.Method;


/**
 * Creates and executes the given process.  Ensures that all the output
 * is properly read without overflowing or dead-locking the process.
 * Outside of the streaming, this class has an identical API to that
 * of {@link java.lang.Process}.
 * <P>
 * Creation of a background process begins at the creation of this object.
 * <P>
 * <H3>Changes for 0.9.1d</H3>
 * <UL>
 *      <LI>Each IOThreadRunner which handles the background process's
 *          IO have been changed such that they now close the streams when
 *          an EOL is encountered, and have no delay between reads.
 * </UL>
 *
 * @author   Matt Albrecht <a href="mailto:groboclown@users.sourceforge.net">groboclown@users.sourceforge.net</a>
 * @since    June 4, 2000 (0.9.1d Alpha)
 * @version  $Date: 2003/02/10 22:52:48 $
 */
public class BackgroundProcess
{
    private Process proc;
    private OutputStream stdIn;
    private PipedInputStream outReader;
    private PipedOutputStream outWriter;
    private PipedInputStream errReader;
    private PipedOutputStream errWriter;
    
    private IOThreadRunner outThread;
    private IOThreadRunner errThread;
    
    
    /**
     * 
     *
     * @see java.lang.Runtime#exec( String )
     */
    public BackgroundProcess( String command )
        throws IOException
    {
        setupProcess( exec( command, null, null ) );
    }
    
    
    /**
     * @see java.lang.Runtime#exec( String[] )
     */
    public BackgroundProcess( String[] cmdarray )
        throws IOException
    {
        setupProcess( exec( cmdarray, null, null ) );
    }
    
    
    /**
     * @see java.lang.Runtime#exec( String[], String[], File )
     */
    public BackgroundProcess( String[] cmdarray, String[] envp, File dir )
        throws IOException
    {
        setupProcess( exec( cmdarray, envp, dir ) );
    }
    
    
    /**
     * @see java.lang.Runtime#exec( String, String[], File )
     */
    public BackgroundProcess( String command, String[] envp, File dir )
        throws IOException
    {
        setupProcess( exec( command, envp, dir ) );
    }
    
    
    /**
     * @see java.lang.Runtime#exec( String[], String[] )
     */
    public BackgroundProcess( String[] cmdarray, String[] envp )
        throws IOException
    {
        setupProcess( exec( cmdarray, envp, null ) );
    }
    
    
    /**
     * @see java.lang.Runtime#exec( String, String[] )
     */
    public BackgroundProcess( String command, String[] envp )
        throws IOException
    {
        setupProcess( exec( command, envp, null ) );
    }
    
    
    /**
     * Initializes the background process with an existing process.
     */
    public BackgroundProcess( Process p )
        throws IOException
    {
        if (p == null)
        {
            throw new IllegalArgumentException("no null args");
        }
        setupProcess( p );
    }
    
    
    /**
     * Get the OutputStream that is sent to the StdIn of the process.
     */
    public OutputStream getStdIn()
    {
        return this.stdIn;
    }
    
    
    /**
     * Get the InputStream that retrieves the data from the StdOut of the
     * process.
     */
    public InputStream getStdOut()
    {
        return this.outReader;
    }
    
    
    /**
     * Get the InputStream that retrieves the data from the StdErr of the
     * process.
     */
    public InputStream getStdErr()
    {
        return this.errReader;
    }
    
    
    /**
     * @see java.lang.Process#destroy()
     */
    public void destroy()
    {
        this.proc.destroy();
    }
    
    
    /**
     * @see java.lang.Process#exitValue()
     */
    public int exitValue()
    {
        return this.proc.exitValue();
    }
    

    /**
     * @see java.lang.Process#waitFor()
     */
    public int waitFor()
            throws InterruptedException
    {
        return this.proc.waitFor();
    }
    
    
    //-------------------------------------------------
    // Protected methods
    
    
    /**
     * Initalize the process for internal use.
     */
    protected void setupProcess( Process p )
            throws IOException
    {
        this.proc = p;
        
        this.stdIn = p.getOutputStream();
        
        this.outReader = new PipedInputStream();
        this.outWriter = new PipedOutputStream( this.outReader );
        
        this.errReader = new PipedInputStream();
        this.errWriter = new PipedOutputStream( this.errReader );
        
        this.outThread =
            new IOThreadRunner( p.getInputStream(), this.outWriter );
        this.outThread.setCloseInputOnStop( true );
        this.outThread.setCloseOutputOnStop( true );
        this.outThread.getThread().setSleepTime( 0 );

        this.errThread =
            new IOThreadRunner( p.getErrorStream(), this.errWriter );
        this.errThread.setCloseInputOnStop( true );
        this.errThread.setCloseOutputOnStop( true );
        this.errThread.getThread().setSleepTime( 0 );
        
        
        this.outThread.start();
        this.errThread.start();
    }
    
    
    
    /**
     * Invoke the correct Exec method for the given parameters.
     */
    protected Process exec( String cmd, String[] env, File dir )
            throws IOException
    {
        Runtime r = Runtime.getRuntime();
        Process p;
        if (dir == null)
        {
            if (env == null)
            {
                p = r.exec( cmd );
            }
            else
            {
                p = r.exec( cmd, env );
            }
        }
        else
        {
            p = reflectExec( cmd, env, dir );
            if (p == null)
            {
                p = r.exec( cmd, setPWD( env, dir ) );
            }
        }
        return p;
    }
    
    
    /**
     * 
     */
    protected static Process exec( String[] cmd, String[] env, File dir )
            throws IOException
    {
        Runtime r = Runtime.getRuntime();
        Process p;
        if (dir == null)
        {
            if (env == null)
            {
                p = r.exec( cmd );
            }
            else
            {
                p = r.exec( cmd, env );
            }
        }
        else
        {
            p = reflectExec( cmd, env, dir );
            if (p == null)
            {
                p = r.exec( cmd, setPWD( env, dir ) );
            }
        }
        return p;
    }
    
    
    /**
     * Attempts to invoke the JDK 1.3 exec method with the given dir.
     * <tt>cmd</tt> is either a String or String[] type.
     *
     * @return the generated Process.  If the process is <tt>null</tt>,
     *      then another technique must be used to execute the command.
     */
    protected static Process reflectExec( Object cmd, String[] env, File dir )
            throws IOException
    {
        try
        {
            Runtime r = Runtime.getRuntime();
            Method m = r.getClass().getMethod( "exec",
                new Class[] { cmd.getClass(), String[].class,
                    File.class }
                );
            if (m == null)
            {
                return null;
            }
            return (Process)m.invoke( r, new Object[] { cmd, env, dir } );
        }
        catch (java.lang.reflect.InvocationTargetException ite)
        {
            Throwable t = ite.getTargetException();
            if (t instanceof IOException)
            {
                throw (IOException)t;
            }
            if (t instanceof RuntimeException)
            {
                throw (RuntimeException)t;
            }
            if (t instanceof Error)
            {
                throw (Error)t;
            }
            // else swallow it
            t.printStackTrace();
        }
        catch (IllegalAccessException e)
        {
            // gulp!
        }
        catch (NoSuchMethodException e)
        {
            // gulp!
        }
        catch (IllegalArgumentException e)
        {
            // gulp!
        }
        /* allow this to be thrown - it indicates a programatic error
        catch (NullPointerException e)
        {
        }
        */
        /* allow this to be thrown
        catch (ExceptionInInitializerError e)
        {
        }
        */
        return null;
    }
    
    
    /**
     * Don't change <tt>env</tt>!
     */
    protected static String[] setPWD( String env[], File dir )
    {
        String tmp[];
        String pwd = "PWD="+dir.getAbsolutePath();
        if (env == null)
        {
            tmp = new String[] { pwd };
        }
        else
        {
            int len = env.length;
            tmp = new String[ len ];
            System.arraycopy( env, 0, tmp, 0, len );
            String s[] = new String[ len + 1 ];
            for (int i = 0; i < len; ++i)
            {
                if (tmp[i].startsWith( "PWD=" ))
                {
                    tmp[i] = pwd;
                    s = null;
                    break;
                }
                else
                {
                    s[i] = tmp[i];
                }
            }
            if (s != null)
            {
                s[ env.length ] = pwd;
                tmp = s;
            }
        }
        return tmp;
    }
}