File: Command.java

package info (click to toggle)
emma-coverage 2.0.5312%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, stretch, wheezy
  • size: 2,000 kB
  • ctags: 3,667
  • sloc: java: 23,109; xml: 414; makefile: 22
file content (326 lines) | stat: -rw-r--r-- 11,152 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
/* Copyright (C) 2003 Vladimir Roubtsov. All rights reserved.
 * 
 * This program and the accompanying materials are made available under
 * the terms of the Common Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/cpl-v10.html
 * 
 * $Id: Command.java,v 1.1.1.1.2.1 2004/07/16 23:32:03 vlad_r Exp $
 */
package com.vladium.emma;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

import com.vladium.logging.ILogLevels;
import com.vladium.util.IConstants;
import com.vladium.util.Property;
import com.vladium.util.Strings;
import com.vladium.util.XProperties;
import com.vladium.util.args.IOptsParser;
import com.vladium.emma.data.mergeCommand;
import com.vladium.emma.instr.instrCommand;
import com.vladium.emma.report.reportCommand;

// ----------------------------------------------------------------------------
/**
 * @author Vlad Roubtsov, (C) 2003
 */
public
abstract class Command
{
    // public: ................................................................
    
    
    public static Command create (final String name, final String usageName, final String [] args)
    {
        final Command tool;
        
        // TODO: dynamic load here?
        
        if ("run".equals (name))
            tool = new runCommand (usageName, args);
        else if ("instr".equals (name))
            tool = new instrCommand (usageName, args);
        else if ("report".equals (name))
            tool = new reportCommand (usageName, args);
        else if ("merge".equals (name))
            tool = new mergeCommand (usageName, args);
        else
            throw new IllegalArgumentException ("unknown command: [" + name + "]");    
            
        tool.initialize ();
        
        return tool;
    }
    
    public abstract void run ();
    
    // protected: .............................................................

    
    protected Command (final String usageToolName, final String [] args)
    {
        m_usageToolName = usageToolName;
        m_args = args != null ? (String []) args.clone () : IConstants.EMPTY_STRING_ARRAY;  
    }
    
    protected abstract String usageArgsMsg ();

    // TODO: is this useful (separate from <init>)?
    protected void initialize ()
    {
        m_exit = false;
        
        if (m_out != null) try { m_out.flush (); } catch (Throwable ignore) {}
        m_out = new PrintWriter (System.out, true);
    }   
    
    protected final String getToolName ()
    {
        // TODO: embed build number etc
        final String clsName = getClass ().getName ();
        
        return clsName.substring (0, clsName.length () - 7);
    }
    
    protected final IOptsParser getOptParser (final ClassLoader loader)
    {
        return IOptsParser.Factory.create (usageResName (getToolName ()), loader,
            usageMsgPrefix (m_usageToolName), USAGE_OPT_NAMES);
    } 
    
    protected final boolean processOpt (final IOptsParser.IOpt opt)
    {
        final String on = opt.getCanonicalName ();
        
        if ("exit".equals (on)) // 'exit' should always be first in this else-if chain
        {
            m_exit = getOptionalBooleanOptValue (opt);
            return true;
        }
        else if ("p".equals (on))
        {
            m_propertyFile = new File (opt.getFirstValue ());
            return true;
        }
        else if ("verbose".equals (on))
        {
            setPropertyOverride (AppLoggers.PROPERTY_VERBOSITY_LEVEL, ILogLevels.VERBOSE_STRING);
            return true;
        }
        else if ("quiet".equals (on))
        {
            setPropertyOverride (AppLoggers.PROPERTY_VERBOSITY_LEVEL, ILogLevels.WARNING_STRING);
            return true;
        }
        else if ("silent".equals (on))
        {
            setPropertyOverride (AppLoggers.PROPERTY_VERBOSITY_LEVEL, ILogLevels.SEVERE_STRING);
            return true;
        }
        else if ("debug".equals (on))
        {
            if (opt.getValueCount () == 0)
                setPropertyOverride (AppLoggers.PROPERTY_VERBOSITY_LEVEL, ILogLevels.TRACE1_STRING);
            else
                setPropertyOverride (AppLoggers.PROPERTY_VERBOSITY_LEVEL, opt.getFirstValue ());
            
            return true;
        }
        else if ("debugcls".equals (on))
        {
            setPropertyOverride (AppLoggers.PROPERTY_VERBOSITY_FILTER, Strings.toListForm (Strings.merge (opt.getValues (), COMMA_DELIMITERS, true), ',')); 
            return true;
        }
        
        return false;
    }
    
    protected final void processCmdPropertyOverrides (final IOptsParser.IOpts parsedopts)
    {
        final IOptsParser.IOpt [] popts = parsedopts.getOpts (EMMAProperties.GENERIC_PROPERTY_OVERRIDE_PREFIX);
        if ((popts != null) && (popts.length != 0))
        {
            final Properties cmdOverrides = new XProperties ();
            
            for (int o = 0; o < popts.length; ++ o)
            {
                final IOptsParser.IOpt opt = popts [o];
                final String on = opt.getName ().substring (opt.getPatternPrefix ().length ());
                
                // TODO: support mergeable prefixed opts?
                
                cmdOverrides.setProperty (on, opt.getFirstValue ());
            }
            
            // command line user overrides are have highest precedence:
            m_propertyOverrides = Property.combine (cmdOverrides, m_propertyOverrides);
        }
    }
    
    protected final boolean processFilePropertyOverrides ()
    {
        if (m_propertyFile != null)
        {
            final Properties fileOverrides;
            
            try
            {
                fileOverrides = Property.getPropertiesFromFile (m_propertyFile);
            }
            catch (IOException ioe)
            {
                exit (true, "property override file [" + m_propertyFile.getAbsolutePath () + "] could not be read", ioe, RC_USAGE);
                return false;
            }
            
            // props file overrides have second highest precendence:
            m_propertyOverrides = Property.combine (m_propertyOverrides, fileOverrides); 
        }
        
        return true;
    }
    
    protected final void usageexit (final IOptsParser parser, final int level, final String msg)
    {
        if (msg != null)
        {
            m_out.print (usageMsgPrefix (m_usageToolName));
            m_out.println (msg);
        }
        
        if (parser != null)
        {
            m_out.println ();
            m_out.print (usageMsgPrefix (m_usageToolName));
            m_out.println (toolNameToCommandName (m_usageToolName) + " " + usageArgsMsg () + ",");
            m_out.println ("  where options include:");
            m_out.println ();
            parser.usage (m_out, level, STDOUT_WIDTH);            
        }
        
        m_out.println ();
        exit (true, null, null, RC_USAGE);
    }
    
    protected final void exit (final boolean showBuildID, final String msg, final Throwable t, final int rc)
        throws EMMARuntimeException
    {
        if (showBuildID)
        {
            m_out.println (IAppConstants.APP_USAGE_BUILD_ID);
        }
        
        if (msg != null)
        {
            m_out.print (toolNameToCommandName (m_usageToolName) + ": "); m_out.println (msg);
        }

        if (rc != RC_OK)
        {
            // error exit:
            
            //if ((showBuildID) || (msg != null)) m_out.println ();
            
            if (m_exit)
            {
                if (t != null) t.printStackTrace (m_out);
                System.exit (rc);
            }
            else
            {
                if (t instanceof EMMARuntimeException)
                    throw (EMMARuntimeException) t;
                else if (t != null)
                    throw msg != null ? new EMMARuntimeException (msg, t) : new EMMARuntimeException ("unexpected failure: ", t);
            }
        }
        else
        {
            // normal exit: 't' is ignored
            
            if (m_exit)
            {
                System.exit (0);
            }
        }
    }

    protected static boolean getOptionalBooleanOptValue (final IOptsParser.IOpt opt)
    {
        if (opt.getValueCount () == 0)
            return true;
        else
        {
            final String v = opt.getFirstValue ().toLowerCase ();
         
            return Property.toBoolean (v);
        }
    }
    
    protected static String [] getListOptValue (final IOptsParser.IOpt opt, final String delimiters, final boolean processAtFiles)
        throws IOException
    {
        return Strings.mergeAT (opt.getValues (), delimiters, processAtFiles);
    }
    
    protected static String usageMsgPrefix (final String toolName)
    {
        return toolNameToCommandName (toolName).concat (" usage: ");
    }
    
    protected static String usageResName (final String toolName)
    {
        return toolName.replace ('.', '/').concat ("_usage.res");
    }
    
    protected static String toolNameToCommandName (final String toolName)
    {
        final int lastDot = toolName.lastIndexOf ('.');
        
        return lastDot > 0 ? toolName.substring (lastDot + 1) : toolName;
    }
    

    protected final String m_usageToolName;
    protected final String [] m_args;
    
    protected File m_propertyFile;
    protected Properties m_propertyOverrides;
    protected boolean m_exit;
    protected PrintWriter m_out; // this is set independently from Logger by design
    
    protected static final String COMMA_DELIMITERS    = "," + Strings.WHITE_SPACE;
    protected static final String PATH_DELIMITERS     = ",".concat (File.pathSeparator);

    protected static final String [] USAGE_OPT_NAMES = new String [] {"h", "help"};
    protected static final int STDOUT_WIDTH = 80;    
    
    // return codes used with System.exit():
    protected static final int RC_OK          = 0;
    protected static final int RC_USAGE       = 1;
    protected static final int RC_UNEXPECTED  = 2;

    // package: ...............................................................
    
    // private: ...............................................................
    

    /*
     * Lazily instantiates m_propertyOverrides if necessary.
     */
    private void setPropertyOverride (final String key, final String value)
    {
        Properties propertyOverrides = m_propertyOverrides;
        if (propertyOverrides == null)
        {
            m_propertyOverrides = propertyOverrides = new XProperties ();
        }
        
        propertyOverrides.setProperty (key, value);
    }

} // end of class
// ----------------------------------------------------------------------------