source: trunk/t3q/src/org/etsi/t3q/T3QMT.java @ 7

Last change on this file since 7 was 7, checked in by phdmakk, 14 years ago
  • Property svn:mime-type set to text/plain
File size: 16.8 KB
Line 
1package org.etsi.t3q;
2
3import java.io.File;
4import java.io.FileFilter;
5import java.text.DecimalFormat;
6import java.util.ArrayList;
7import java.util.HashMap;
8import java.util.LinkedList;
9import java.util.List;
10import java.util.Stack;
11
12import org.etsi.t3q.config.T3QConfig;
13import org.etsi.t3q.exceptions.TTCN3BehaviorException;
14import org.etsi.t3q.exceptions.TTCN3ParserException;
15import org.etsi.t3q.visitor.T3QVisitor;
16import org.etsi.common.MiscTools;
17import org.etsi.common.configuration.ConfigTools;
18import org.etsi.common.configuration.ConfigurationProfile;
19import org.etsi.common.configuration.ToolConfiguration;
20
21import antlr.MismatchedTokenException;
22import antlr.RecognitionException;
23import antlr.TokenStreamException;
24import de.ugoe.cs.swe.trex.core.analyzer.rfparser.LocationAST;
25import de.ugoe.cs.swe.trex.core.analyzer.rfparser.TTCN3Analyzer;
26import de.ugoe.cs.swe.trex.core.analyzer.rfparser.TTCN3AnalyzerFlyweightFactory;
27import de.ugoe.cs.swe.trex.core.analyzer.rfparser.TTCN3FormatterTreeParser;
28import de.ugoe.cs.swe.trex.core.analyzer.rfparser.TTCN3Parser;
29import de.ugoe.cs.swe.trex.core.formatter.TTCN3Formatter;
30import de.ugoe.cs.swe.trex.core.formatter.TTCN3FormatterParameters;
31
32public class T3QMT {
33
34        //TODO: a largely deprecated multithreaded version of T3Q.
35        //TODO: transfer the relevant concepts to the current version of T3Q
36       
37        private static String versionNumber = "v0.1.1";
38        public static ToolConfiguration config = null;
39        public static ConfigurationProfile activeProfile = null;
40        private HashMap<String, String> argsMap = new HashMap<String, String>();
41        private String targetPath = null;
42        private HashMap<String, Integer> linesOfCodeMap = new HashMap<String, Integer>();
43        private int totalLoc = 0;
44
45        //private String outputPathArg = null;
46
47        public T3QMT() {
48        }
49
50        // --------------------------------------------------------------------------
51
52        public void showHelp() {
53                System.out.println("Help:");
54                System.out.println("  t3q[.cmd/.sh] [options] path");
55                System.out.println("");
56                System.out.println("  Options (specify in any order): ");
57                System.out.println("    --help ");
58                System.out.println("    --profile [profilename] ");
59                //System.out.println("    --output [path] ");
60                System.out.println("");
61        }
62
63        // --------------------------------------------------------------------------
64
65        public void run(String[] args) {
66                Runtime runtime = Runtime.getRuntime();
67                int maxThreads = runtime.availableProcessors();
68                System.out.println("T3Q " + versionNumber);
69                System.out.println("  TTCN-3 version supported: " + TTCN3Parser.getSupportedVersion());
70                System.out.println("  Number of processors: " + maxThreads);
71                System.out.println("==========================================");
72        System.out.println();
73
74               
75                if (handleCommandLineArguments(args) == false)
76                        return;
77
78                if (argsMap.get("profile") != null) {
79                        loadConfig(argsMap.get("profile"));
80                } else {
81                        loadConfig(null);
82                }
83
84                File path = new File(targetPath);
85                if (!path.isDirectory()) {
86                        System.out
87                                        .println("Error: specified argument is *not* a directory!");
88                        return;
89                }
90               
91                if (T3QMT.activeProfile.isSettingRecursiveProcessing()){
92                        System.out.println("Collecting ttcn3 files recursively in \""
93                                        + targetPath + "\" ...");
94                } else {
95                        System.out.println("Collecting ttcn3 files non-recursively in \""
96                                        + targetPath + "\" ...");
97                }
98                List<String> ttcn3Resources = findTTCN3Resources(targetPath);
99
100                long startTime = System.currentTimeMillis();
101
102                try {
103                        System.out.println("Parsing files...");
104                        TTCN3AnalyzerFlyweightFactory
105                        .getInstance();
106                        final Stack<Thread> threadStack = new Stack<Thread>();
107                       
108                        for (int j = 0; j < ttcn3Resources.size(); j++) {
109                                final int i = j;
110                                final String resourcePath = ttcn3Resources.get(i);
111                                                               
112                                Thread analysisThread = new Thread(new Runnable() {
113
114                                        @Override
115                                        public void run() {
116                                                TTCN3AnalyzerFlyweightFactory analyzerFactory = TTCN3AnalyzerFlyweightFactory
117                                                .getInstance();
118
119                                                analyzeFile(resourcePath);
120                                                TTCN3Analyzer analyzer = analyzerFactory.getTTCN3Analyzer(resourcePath);
121
122                                                if (analyzer.getExceptions().size() > 0){
123                                                       
124                                                        try {
125                                                                throw new TTCN3ParserException("Error while parsing file "
126                                                                                + analyzer.getFilename());
127                                                        } catch (TTCN3ParserException e) {
128                                                                System.err.println(e.getLocalizedMessage());
129                                                                for (int i1 = 0; i1 < analyzer.getExceptions().size(); i1++) {
130                                                                        System.err.println("Line "
131                                                                                        + analyzer.getExceptions().get(i1).getLine() + ": "
132                                                                                        + analyzer.getExceptions().get(i1).getMessage());
133                                                                }
134                                                        }
135                                                }
136                                        }
137                                });
138                                threadStack.push(analysisThread);
139                        }
140                        TTCN3Analyzer analyzer = null;
141
142                        Runnable parserRunnable = new Runnable() {
143                                        @Override
144                                        public void run() {
145                                                while (!threadStack.isEmpty()) {
146                                                        Thread analysisThread = threadStack.pop();
147                                                        analysisThread.start();
148                                                        try {
149                                                                analysisThread.join();
150                                                        } catch (InterruptedException e) {
151                                                                e.printStackTrace();
152                                                        }
153                                                }
154                                        }
155                        };
156                       
157                        ArrayList<Thread> parserThreadList = new ArrayList<Thread>();
158                        for (int i=0; i < maxThreads; i++) {
159                                Thread parserThread = new Thread(parserRunnable);
160                                parserThreadList.add(parserThread);
161                                parserThread.start();
162                        }
163
164                        for (int i=0; i < maxThreads; i++) {
165                                try {
166                                        parserThreadList.get(i).join();
167                                } catch (InterruptedException e) {
168                                        e.printStackTrace();
169                                }
170                        }                       
171                       
172                        long endTime = System.currentTimeMillis();
173                        long elapsed = endTime - startTime;
174                        double elapsedMinutes = ((double) elapsed) / 1000.0 / 60.0;
175                        System.out.println("done parsing in " + elapsed + "ms ("
176                                        + doubleToString2(elapsedMinutes) + " minutes).");
177                       
178                        if (T3QMT.activeProfile.isStatShowLOC()){
179                                System.out.println("Total lines of code parsed: " + totalLoc);
180                        }
181                       
182                        TTCN3AnalyzerFlyweightFactory analyzerFactory = TTCN3AnalyzerFlyweightFactory
183                                        .getInstance();
184
185                        System.out.println("Postprocessing...");
186                        startTime = System.currentTimeMillis();
187                        analyzerFactory.postProcess();
188                        endTime = System.currentTimeMillis();
189                        elapsed = endTime - startTime;
190                        elapsedMinutes = ((double) elapsed) / 1000.0 / 60.0;
191                        System.out.println("Done processing in " + elapsed + "ms ("
192                                        + doubleToString2(elapsedMinutes) + " minutes).");
193                        startTime = System.currentTimeMillis();
194                       
195                        System.out.println("==========================================");
196                        for (int i = 0; i < ttcn3Resources.size(); i++) {
197                                analyzer = analyzerFactory.getTTCN3Analyzer(ttcn3Resources
198                                                .get(i));
199                               
200                                T3QVisitor visitor = new T3QVisitor();
201                                System.out.println("Analyzing: " + analyzer.getFilename());
202                                visitor.setFilename(analyzer.getFilename());
203                                visitor.acceptDFS((LocationAST) analyzer.getParser().getAST());
204
205                        }
206                        endTime = System.currentTimeMillis();
207                        elapsed = endTime - startTime;
208                        elapsedMinutes = ((double) elapsed) / 1000.0 / 60.0;
209                        System.out.println("Quality checks finished in " + elapsed + "ms ("
210                                        + doubleToString2(elapsedMinutes) + " minutes).");
211
212                        analyzer = handleFormatter(ttcn3Resources, analyzer,
213                                        analyzerFactory);
214                        if (T3QMT.activeProfile.isStatShowLOC()){
215                                System.out.println("Total lines of code processed: " + totalLoc);
216                        }
217
218                } catch (TTCN3BehaviorException e) {
219                        System.err.println(e.getLocalizedMessage());
220                }
221//              } catch (TTCN3ParserException e) {
222//                      //Default setting where processing is terminated in the event of a parsing error
223//                      System.err.println(e.getLocalizedMessage());
224//                      for (int i = 0; i < analyzer.getExceptions().size(); i++) {
225//                              System.err.println("Line "
226//                                              + analyzer.getExceptions().get(i).getLine() + ": "
227//                                              + analyzer.getExceptions().get(i).getMessage());
228//                      }
229//                      //TODO: Isolate different steps and implement a recovery mechanism:
230//
231//              }
232
233        }
234
235        private TTCN3Analyzer handleFormatter(List<String> ttcn3Resources,
236                        TTCN3Analyzer analyzer,
237                        TTCN3AnalyzerFlyweightFactory analyzerFactory) {
238                long startTime;
239                long endTime;
240                long elapsed;
241                double elapsedMinutes;
242                if (false) {
243                        //TODO: consider ways to avoid reparsing (performing the comment collection during the first parse)
244                        System.out
245                                        .println("==========================================");
246                        System.out.println("Formatting Code...");
247                        startTime = System.currentTimeMillis();
248
249                        TTCN3Formatter formatter = new TTCN3Formatter();
250
251                        for (int i = 0; i < ttcn3Resources.size(); i++) {
252                                analyzer = analyzerFactory.getTTCN3Analyzer(ttcn3Resources
253                                                .get(i));
254                                System.out.println("  Formatting file: "
255                                                + analyzer.getFilename());
256//                              try {
257
258                                        String resourcePath = ttcn3Resources.get(i);
259                                       
260                                        String source = MiscTools.readFile(resourcePath);
261                                       
262//                                      String formatted = formatter.formatTTCN3Source(source, T3QMT.activeProfile
263//                                                      .getFormattingParameters());
264                                       
265                                        //TODO: consider a separate output handler
266                                        //calculate the target path for the current resource
267                                        String inputPath = new File(targetPath).getPath(); //strips the slash at the end
268                                        String subPath = resourcePath.substring(inputPath.length());
269//                                      String outputPathArg = T3QMT.activeProfile.getPathFormattedOutputPath();
270//                                      String outputPath = outputPathArg + subPath;
271                                       
272//                                      System.out.println("****************************");
273//                                      System.out.println("InputPath: "+inputPath);
274//                                      System.out.println("ResourcePath: "+resourcePath);
275//                                      System.out.println("SubPath: "+subPath);
276//                                      System.out.println("OutputPath: "+outputPath);
277//                                      System.out.println("****************************");
278                                       
279//                                      MiscTools.writeFile(outputPath, formatted);
280
281//                              } catch (RecognitionException e1) {
282//                                      System.err.println("Recognition exception:");
283//                                      System.err.println(e1.getLocalizedMessage());
284//                              } catch (TokenStreamException e) {
285//                                      System.err.println("Token stream exception:");
286//                                      e.printStackTrace();
287//                              } catch (Exception e) {
288//                                      System.err.println("Exception:");
289//                                      e.printStackTrace();
290//                              }
291
292                        }
293                        endTime = System.currentTimeMillis();
294                        elapsed = endTime - startTime;
295                        elapsedMinutes = ((double) elapsed) / 1000.0 / 60.0;
296                        System.out.println("Code formatting finished in " + elapsed
297                                        + "ms (" + doubleToString2(elapsedMinutes)
298                                        + " minutes).");
299
300                }
301                return analyzer;
302        }
303
304        private boolean handleCommandLineArguments(String[] args) {
305                if (args.length < 1) {
306                        System.out.println("Error: too few command line arguments...");
307                        System.out.println("");
308                        showHelp();
309                        return false;
310                }
311                parseCommandLineArguments(args);
312                if (argsMap.get("help") != null) {
313                        showHelp();
314                        return false;
315                }
316
317                return true;
318        }
319
320        // --------------------------------------------------------------------------
321
322        private void parseCommandLineArguments(String[] args) {
323                String key = "";
324                String value = "";
325                targetPath = "";
326
327                boolean lastKey = false;
328                for (int i = 0; i < args.length; i++) {
329                        if (args[i].startsWith("--")) {
330                                key = args[i].replaceAll("--", "").toLowerCase();
331
332                                if (lastKey) {
333                                        argsMap.put(key, "true");
334                                        key = null;
335                                        value = null;
336                                        lastKey = false;
337                                }
338
339                                lastKey = true;
340                        } else {
341                                value = args[i];
342                                if ((key != null) && (argsMap.get(key) == null)
343                                                && (key.length() > 0)) {
344                                        argsMap.put(key, value);
345                                        key = null;
346                                        value = null;
347                                } else {
348                                        targetPath += value + " ";
349                                }
350                                lastKey = false;
351                        }
352                }
353
354                if (key != null) {
355                        if ((argsMap.get(key) == null) && (key.length() > 0)) {
356                                argsMap.put(key, "true");
357                        }
358                }
359                targetPath = targetPath.trim();
360        }
361
362        // --------------------------------------------------------------------------
363
364        private void loadConfig(String specifiedProfile) {
365                boolean newConfiguration = false;
366                System.out.println("Loading configuration ...");
367                String configFile = null;
368//              String configFile = ConfigTools.findConfig();
369                if (configFile != null) {
370                        System.out.println("  Loading XML Configuration: " + configFile);
371//                      config = ConfigTools.readConfig(configFile);
372                } else {
373//                      System.out
374//                                      .println("  No existing configuration. Creating new default configuration: "
375//                                                      + ConfigTools.getDefaultConfigurationFilePath());
376                        config = new T3QConfig();
377//                      ConfigurationProfile qcProfile = new ConfigurationProfile();
378//                      qcProfile.setProfileName("exampleProfile");
379//                      config.setDefaultConfigurationProfile("all");
380//                      if (config.getConfigurationProfiles() == null) {
381//                              ArrayList<ConfigurationProfile> qcProfiles = new ArrayList<ConfigurationProfile>();
382//                              config.setConfigurationProfiles(qcProfiles);
383//                      }
384//                      config.getConfigurationProfiles().add(qcProfile);
385////                    ConfigTools.writeConfig(config, ConfigTools
386////                                    .getDefaultConfigurationFilePath());
387//                      newConfiguration = true;
388                }
389//              ConfigurationProfile allEnabledProfile = new ConfigurationProfile();
390//              allEnabledProfile.setProfileName("all");
391//              config.getConfigurationProfiles().add(allEnabledProfile);
392
393                if (newConfiguration) {
394                        System.out.println("  Auto-selecting 'all' profile.");
395//                      activeProfile = allEnabledProfile;
396                } else {
397                        if (specifiedProfile != null)
398                                activateProfile(specifiedProfile);
399                        if (activeProfile == null) {
400                                if (specifiedProfile != null) {
401                                        System.out
402                                                        .println("  Profile '"
403                                                                        + specifiedProfile
404                                                                        + "' not found in configuration. Trying default profile '"
405                                                                        + config.getDefaultConfigurationProfile()
406                                                                        + "'.");
407                                } else {
408                                        System.out
409                                                        .println("  No Profile specified. Trying default profile '"
410                                                                        + config.getDefaultConfigurationProfile()
411                                                                        + "'.");
412                                }
413                                specifiedProfile = config.getDefaultConfigurationProfile();
414                                activateProfile(specifiedProfile);
415
416                        }
417                        if (activeProfile == null) {
418                                System.out
419                                                .println("  Profile '"
420                                                                + specifiedProfile
421                                                                + "' not found in configuration. Auto-selecting 'all' profile.");
422//                              activeProfile = allEnabledProfile;
423                        }
424                }
425        }
426
427        // --------------------------------------------------------------------------
428
429        private void activateProfile(String specifiedProfile) {
430                for (int i = 0; i < config.getConfigurationProfiles().size(); i++) {
431                        ConfigurationProfile qualityProfile = config
432                                        .getConfigurationProfiles().get(i);
433                        if (qualityProfile.getProfileName().toLowerCase().equals(
434                                        specifiedProfile.toLowerCase())) {
435                                System.out.println("  Selecting '" + specifiedProfile
436                                                + "' profile.");
437                                activeProfile = qualityProfile;
438                        }
439                }
440        }
441
442        // --------------------------------------------------------------------------
443
444        List<String> findTTCN3Resources(String directory) {
445                List<String> files = new LinkedList<String>();
446
447                File f = new File(directory);
448
449                File[] fileNames = f.listFiles(new FileFilter() {
450                        public boolean accept(File pathname) {
451                                if (pathname.getPath().endsWith(".ttcn3")
452                                                || pathname.getPath().endsWith(".ttcn")
453                                                || pathname.getPath().endsWith(".3mp"))
454                                        return true;
455                                return false;
456                        }
457                });
458
459                for (int i = 0; i < fileNames.length; i++) {
460                        files.add(fileNames[i].getPath());
461                }
462
463                File[] directories = f.listFiles(new FileFilter() {
464                        public boolean accept(File pathname) {
465                                if (pathname.isDirectory())
466                                        return true;
467                                return false;
468                        }
469                });
470
471                if (T3QMT.activeProfile.isSettingRecursiveProcessing()){
472                        for (int i = 0; i < directories.length; i++) {
473                                files.addAll(findTTCN3Resources(directories[i].getPath()));
474                        }
475                }
476
477                return files;
478        }
479
480        // --------------------------------------------------------------------------
481
482        private TTCN3Analyzer analyzeFile(String filename) {
483                TTCN3AnalyzerFlyweightFactory analyzerFactory = TTCN3AnalyzerFlyweightFactory
484                                .getInstance();
485                analyzerFactory.setStandaloneUsage(true);
486                String code = MiscTools.readFile(filename);
487
488                int index = 0;
489                int loc = 0;
490                while (index != -1) {
491                        if (index == 0)
492                                index = code.indexOf("\n", index);
493                        else
494                                index = code.indexOf("\n", index+1);
495                        loc++;
496                }
497                linesOfCodeMap.put(filename, loc);
498                totalLoc += loc;               
499
500                System.out.println("  Parsing file: " + filename + " (LOC: " + linesOfCodeMap.get(filename) + ") ...");
501                long startTime = System.currentTimeMillis();
502               
503                TTCN3Analyzer analyzer = analyzerFactory.getTTCN3Analyzer(filename,
504                                code);
505                try {
506                        analyzer.analyze();
507                } catch (MismatchedTokenException e) {
508                        e.printStackTrace();
509                } catch (RecognitionException e) {
510                        e.printStackTrace();
511                } catch (TokenStreamException e) {
512                        e.printStackTrace();
513                } catch (Exception e) {
514                        e.printStackTrace();
515                }
516                long endTime = System.currentTimeMillis();
517                long elapsed = endTime-startTime;
518                double elapsedMinutes = ((double) elapsed) / 1000.0 / 60.0;
519               
520                System.out.println("    ...done " + filename + " in " + elapsed + "ms (" + doubleToString2(elapsedMinutes) + " minutes).");
521               
522                return analyzer;
523        }
524
525        // --------------------------------------------------------------------------
526        public static String doubleToString2(double d) {
527                DecimalFormat fmt = new DecimalFormat("0.00");
528                String string = fmt.format(d);
529                return string;
530        }
531
532        // --------------------------------------------------------------------------
533
534        public static void main(String[] args) {
535                T3QMT tool = new T3QMT();
536                tool.run(args);
537        }
538
539}
Note: See TracBrowser for help on using the repository browser.