source: trunk/t3d/src/org/etsi/t3d/T3D.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: 28.1 KB
Line 
1package org.etsi.t3d;
2
3
4import java.io.File;
5import java.io.FileNotFoundException;
6import java.io.FileOutputStream;
7import java.io.IOException;
8import java.util.ArrayList;
9import java.util.Comparator;
10import java.util.HashMap;
11import java.util.List;
12
13import javax.xml.parsers.DocumentBuilderFactory;
14import javax.xml.parsers.ParserConfigurationException;
15import javax.xml.transform.Transformer;
16import javax.xml.transform.TransformerConfigurationException;
17import javax.xml.transform.TransformerException;
18import javax.xml.transform.TransformerFactory;
19import javax.xml.transform.stream.StreamResult;
20import javax.xml.transform.stream.StreamSource;
21
22import org.apache.commons.cli.CommandLine;
23import org.apache.commons.cli.CommandLineParser;
24import org.apache.commons.cli.GnuParser;
25import org.apache.commons.cli.HelpFormatter;
26import org.apache.commons.cli.Option;
27import org.apache.commons.cli.ParseException;
28import org.etsi.t3d.config.T3DConfig;
29import org.etsi.t3d.config.DocumentationProfile;
30import org.etsi.t3d.config.T3DOptionsHandler;
31import org.etsi.t3d.exceptions.TTCN3BehaviorException;
32import org.etsi.t3d.exceptions.TTCN3ParserException;
33import org.etsi.t3d.visitor.DependencyVisitor;
34import org.etsi.t3d.visitor.ImportVisitor;
35import org.etsi.t3d.visitor.T3DVisitor;
36import org.etsi.common.InputInterface;
37import org.etsi.common.MiscTools;
38import org.etsi.common.configuration.ConfigTools;
39import org.etsi.common.exceptions.TerminationException;
40import org.etsi.common.logging.LoggingInterface;
41import org.etsi.common.logging.LoggingInterface.LogLevel;
42import org.xml.sax.SAXException;
43
44import antlr.MismatchedTokenException;
45import antlr.RecognitionException;
46import antlr.TokenStreamException;
47import de.ugoe.cs.swe.trex.core.analyzer.rfparser.LocationAST;
48import de.ugoe.cs.swe.trex.core.analyzer.rfparser.TTCN3Analyzer;
49import de.ugoe.cs.swe.trex.core.analyzer.rfparser.TTCN3AnalyzerFlyweightFactory;
50import de.ugoe.cs.swe.trex.core.analyzer.rfparser.TTCN3Parser;
51
52public class T3D {
53
54        public static String versionNumber = "v1.0.2";
55        //set during automated server builds
56        private static String buildStamp = "---BUILD_STAMP---";
57        public static DocumentationProfile activeProfile = null;
58        private String configurationClassName = T3DConfig.class.getName();
59        private String configurationProfileClassName = DocumentationProfile.class.getName();
60        private String configurationFilename;
61        private String selectedProfileName = null;
62        private static LogLevel logLevel = LogLevel.INFORMATION;
63
64        private HashMap<String, String> argsMap = new HashMap<String, String>();
65        private ArrayList<String> inputPaths = new ArrayList<String>();
66        private String destinationPath = null;
67
68        private HashMap<String, Integer> linesOfCodeMap = new HashMap<String, Integer>();
69        private int totalLoc = 0;
70
71        private boolean generateNewConfiguration = false;
72       
73        private static boolean generateMainXML = false;
74        private static boolean generateDependenciesXML = false;
75        private static boolean generateHTML = false;
76       
77        private static XMLPrinter xmlPrinter;
78        private static ImportPrinter importPrinter;
79        private static DependencyPrinter depPrinter;
80        //TODO: START HERE, remove and substitute by a method that derives the names based on the TTCN3ParserTokenTypes
81        //WHAT ABOUT EXTERNAL FUNCTIONS???
82        //public final static String elementTypes[] = {"Module", "Function", "Testcase", "Group", "Altstep", "Constant", "Module Parameter", "Template", "Type", "Signature"};
83        private static final String documentationLogFile = "log.xml";
84        private static final String documentationXmlFile = "project.xml";
85        private static final String dependencyXmlFile = "dependencies.xml";
86        private static final String importXmlFile = "imports.xml";
87        private String xsdFile = System.getenv("T3D_HOME")+"/xsd/project_schema.xsd";
88
89        //private static T3DLoggingInterface loggingInterface = new T3DLoggingInterface();
90
91        //TODO: TEMPORARY SOLUTION UNTIL MAJOR OTHER ISSUES ARE RESOLVED
92        private static LoggingInterface logger = null;
93       
94        public T3D() {
95        }
96
97//      public static void printLog(int LEVEL, String filename, int startLine, int endLine, int type, String output){
98//              loggingInterface.printLog(LEVEL, filename, startLine, endLine, type, output);
99//      }
100
101        // --------------------------------------------------------------------------
102
103        public void showHelp() {
104                System.out.println("\nHelp:");
105//              System.out.println("  t3d[.bat] [options] (path | filename)+");
106//              System.out.println("");
107//              System.out.println("  Options (specify in any order): ");
108//              System.out.println("    --help - prints this screen");
109//              System.out.println("    --profile [profilename] - allows manual profile selection, overriding the selected default profile");
110//              System.out.println("");
111                HelpFormatter formatter = new HelpFormatter();
112                formatter.setOptionComparator(new Comparator<Option>() {
113                       
114                        @Override
115                        public int compare(Option o1, Option o2) {
116                                if (o1.getId() > o2.getId()) {
117                                        return 1;
118                                } else {
119                                        return -1;
120                                }
121                        }
122                });
123                formatter.setSyntaxPrefix("  Usage: ");
124//              formatter.setWidth(74);
125                formatter.printHelp("t3d [options] ((--html | --xml-only) | --local-dependencies)+ (filename | path)+", "  Options: (in any order, config and at least one output format are required)",
126                                new T3DOptionsHandler().getOptions(), "");
127                System.out.println("");
128        }
129       
130        // --------------------------------------------------------------------------
131        private void showDebugInfo(String[] args) {
132                if (getLogLevel().equals(LogLevel.DEBUG)) {
133                        System.out.println("==================ARGS:===================");
134                        for (int a = 0; a < args.length; a++) {
135                                System.out.println("" + args[a]);
136                        }
137                        System.out.println("==================PROPERTIES:=============");
138                        for(Object key : System.getProperties().keySet()) {
139                                System.out.println("   "+key.toString() + " : "+System.getProperty(key.toString()));
140                        }
141                        System.out.println("==========================================");
142                }
143        }
144        // --------------------------------------------------------------------------
145
146        public void run(String[] args) {
147                System.out.println("T3D " + getVersionNumber());
148                System.out.println("Build " + getBuildStamp());
149                System.out.println("  TTCN-3 version supported: "
150                                + TTCN3Parser.getSupportedVersion());
151                System.out.println("==========================================");
152                try {
153                        if (handleCommandLineArguments(args) == false) {
154                                return;
155                        }
156                        showDebugInfo(args);
157                        if (selectedProfileName != null) {
158                                handleConfig(selectedProfileName);
159                        } else {
160                                handleConfig(null);
161                        }
162                } catch (TerminationException e) {
163                        // TODO: handle exception
164                        System.out.println("ERRORING OUT!");
165                }
166               
167                TTCN3Parser.disableStatementBlockCompatibilityMode();
168                TTCN3Parser.enableStatementBlockCompatibilityMode();
169               
170                List<String> ttcn3Resources = new InputInterface(T3D.activeProfile.getResourceExtensionsRegExp(), T3D.activeProfile.getProjectExtension(),
171                                T3D.activeProfile.isSettingRecursiveProcessing()).getInputFromParameterList(inputPaths);
172                ttcn3Resources = InputInterface.filterAbsoluteDuplicates(ttcn3Resources);
173
174                if (ttcn3Resources.isEmpty()) {
175                        // Terminate
176                        System.out.println("No ttcn3 files found!");
177                        showHelp();
178                        return;
179                }
180
181                long startTime = System.currentTimeMillis();
182                TTCN3Analyzer analyzer = null;
183               
184                try {
185                        System.out.println("Parsing files...");
186                        for (int i = 0; i < ttcn3Resources.size(); i++) {
187                                String resourcePath = ttcn3Resources.get(i);
188                                analyzeFile(resourcePath);
189                                TTCN3AnalyzerFlyweightFactory analyzerFactory = TTCN3AnalyzerFlyweightFactory
190                                                .getInstance();
191                                analyzer = analyzerFactory.getTTCN3Analyzer(ttcn3Resources
192                                                .get(i));
193                                if (analyzer.getExceptions().size() > 0) {
194
195                                        // TODO: in eclipse the error stream seems to be delayed
196                                        // somewhat
197                                        // -> Investigate
198                                        // -> The terminal seems to handle this properly in contrast
199                                        if (T3D.activeProfile.isSettingAbortOnError()) {
200                                                throw new TTCN3ParserException(
201                                                                "Error while parsing file "
202                                                                                + analyzer.getFilename());
203                                        } else {
204                                                try {
205                                                        throw new TTCN3ParserException(
206                                                                        "Error while parsing file "
207                                                                                        + analyzer.getFilename());
208                                                } catch (TTCN3ParserException e) {
209                                                        System.err.println(e.getLocalizedMessage());
210                                                        for (int i1 = 0; i1 < analyzer.getExceptions()
211                                                                        .size(); i1++) {
212                                                                System.err.println("Line "
213                                                                                + analyzer.getExceptions().get(i1)
214                                                                                                .getLine()
215                                                                                + ": "
216                                                                                + analyzer.getExceptions().get(i1)
217                                                                                                .getMessage());
218                                                        }
219                                                        // e.printStackTrace();
220                                                }
221                                        }
222                                }                       
223                        }
224                        long endTime = System.currentTimeMillis();
225                        long elapsed = endTime - startTime;
226                        double elapsedMinutes = ((double) elapsed) / 1000.0 / 60.0;
227                        System.out.println("Done parsing in " + elapsed + "ms ("
228                                        + MiscTools.doubleToString(elapsedMinutes) + " minutes).");
229                       
230                        if (T3D.activeProfile.isStatShowLOC()) {
231                                System.out.println("Total lines of code parsed: " + totalLoc);
232                        }
233                       
234                        TTCN3AnalyzerFlyweightFactory analyzerFactory = TTCN3AnalyzerFlyweightFactory
235                        .getInstance();
236                       
237                        System.out.println("Postprocessing...");
238                        startTime = System.currentTimeMillis();
239                        analyzerFactory.postProcess();
240                        endTime = System.currentTimeMillis();
241                        elapsed = endTime - startTime;
242                        elapsedMinutes = ((double) elapsed) / 1000.0 / 60.0;
243                        System.out.println("Done processing in " + elapsed + "ms ("
244                                        + MiscTools.doubleToString(elapsedMinutes) + " minutes).");
245                        startTime = System.currentTimeMillis();
246
247                        System.out.println("==========================================");
248                        //TODO: up to here mostly identical, make reusable
249                       
250                        //TODO: custom functionality
251                        initialize();
252                        handlePaths();
253                       
254                        //TODO: core functionality, encapsulate, split, and extract
255                        for (int i = 0; i < ttcn3Resources.size(); i++) {
256                                analyzer = analyzerFactory.getTTCN3Analyzer(ttcn3Resources
257                                                .get(i));
258                                System.out.println("Preparing documentation for "
259                                                + analyzer.getFilename());
260//TODO: review logging interface
261                                //loggingInterface.setCurrentTTCN3File(analyzer.getFilename());
262                                T3D.getLoggingInterface().setLogSourceName(analyzer.getFilename());
263                                if (isGenerateMainXML() || isGenerateHTML()) {
264                                        T3DVisitor visitor = new T3DVisitor(xmlPrinter);
265                                        visitor.setFilename(analyzer.getFilename());
266                                        ImportVisitor importVisitor = new ImportVisitor(importPrinter);
267                                        importVisitor.setFilename(analyzer.getFilename());
268//                                      xmlPrinter.setCurrentTTCN3File(analyzer.getFilename());
269                                        // visitor.setFilename(analyzer.getFilename());
270                                        visitor.acceptDFS((LocationAST) analyzer.getParser().getAST());
271                                        importVisitor.acceptDFS((LocationAST) analyzer.getParser().getAST());
272                                }
273                                if (isGenerateDependenciesXML()) {
274                                        DependencyVisitor dependencyVisitor = new DependencyVisitor(depPrinter);
275                                        depPrinter.setCurrentTTCN3File(analyzer.getFilename());
276                                        dependencyVisitor.acceptDFS((LocationAST) analyzer.getParser().getAST());
277                                }
278
279                        }
280                        endTime = System.currentTimeMillis();
281                        elapsed = endTime - startTime;
282                        elapsedMinutes = ((double) elapsed) / 1000.0 / 60.0;
283                        System.out.println("Documentation preparation finished in "
284                                        + elapsed + "ms (" + MiscTools.doubleToString(elapsedMinutes)
285                                        + " minutes).");
286
287                        if (T3D.activeProfile.isStatShowLOC()) {
288                                System.out
289                                                .println("Total lines of code processed: " + totalLoc);
290                        }
291
292                        //TODO: custom functionality
293                        handleOutput();
294
295                        //TODO: move summary here
296                        if (T3D.activeProfile.isStatShowSummary()) {
297//                              System.out.println("Brief statistics summary of occurences in message classes:");
298//                              for (MessageClass m : MessageClass.values()) {
299//                                      System.out.println("\t" + m.getDescription() + " : "
300//                                                      + m.getOccurenceCount());
301//                              }
302                        }
303                } catch (TTCN3BehaviorException e) {
304                        System.err.println(e.getLocalizedMessage());
305                } catch (TTCN3ParserException e) {
306                        // Default setting where processing is terminated in the event of a
307                        // parsing error
308                        System.err.println(e.getLocalizedMessage());
309                        for (int i = 0; i < analyzer.getExceptions().size(); i++) {
310                                System.err.println("Line "
311                                                + analyzer.getExceptions().get(i).getLine() + ": "
312                                                + analyzer.getExceptions().get(i).getMessage());
313                        }
314                        // TODO: Isolate different steps and implement a recovery mechanism:
315
316                }
317        }
318
319        private void initialize() {
320                T3D.setLoggingInterface(new LoggingInterface(T3D.activeProfile.getLoggingConfiguration()));
321                if (isGenerateMainXML() || isGenerateHTML()) {
322                        xmlPrinter = new XMLPrinter();
323                        importPrinter = new ImportPrinter();
324                }
325                if (isGenerateDependenciesXML()) {
326                        depPrinter = new DependencyPrinter();
327                }
328               
329        }
330
331        private void handlePaths() {
332                String finalOutputPath = getFinalOutputPath(this.getDestinationPath());
333               
334                String finalXMLfilePath = finalOutputPath + File.separator + documentationXmlFile;
335                String finalDependencyfilePath = finalOutputPath + File.separator + dependencyXmlFile;
336                String finalImportfilePath = finalOutputPath + File.separator + importXmlFile;
337                String finalLogfilePath = finalOutputPath + File.separator + documentationLogFile;
338                //System.out.println("*********" + finalXMLfilePath);
339               
340                System.out.println("Output path: "+finalOutputPath);
341               
342                if (!(new File(finalOutputPath).isDirectory())) {
343                        new File(finalOutputPath).mkdirs();
344                }
345                if (isGenerateMainXML() || isGenerateHTML()) {
346                        xmlPrinter.setXMLPath(finalXMLfilePath);
347                        importPrinter.setXMLPath(finalImportfilePath);
348                }
349                if (isGenerateDependenciesXML()) {
350                        depPrinter.setXMLPath(finalDependencyfilePath);
351                }
352                //TODO: revise XML usage
353                //loggingInterface.setXMLPath(finalLogfilePath);
354        }
355
356       
357        private void handleOutput() {
358                //TODO: this is duplicated in handlePaths
359                String finalOutputPath = getFinalOutputPath(this.getDestinationPath());
360                generateXML();
361                // TODO: uncomment
362                //validateXMLoutput(finalOutputPath);
363                handleTransformation(finalOutputPath);
364        }
365
366        private String getFinalOutputPath(String outputDirectory) {
367                return MiscTools.getProperOutputPath(outputDirectory) + File.separator + MiscTools.getSubPath(inputPaths.get(0));
368        }
369
370        private void generateXML() {
371                if (isGenerateMainXML() || isGenerateHTML()) {
372                        xmlPrinter.finishXML();
373                        importPrinter.finishXML();
374                }
375                if (isGenerateDependenciesXML()) {
376                        depPrinter.finishXML();
377                }
378                // TODO: what do we do with this one?
379                //loggingInterface.finishXML();
380        }
381
382        private void validateXMLoutput(String finalOutputPath) {
383                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
384
385                factory.setValidating(true);
386
387                factory.setAttribute(
388                                "http://java.sun.com/xml/jaxp/properties/schemaLanguage",
389                                "http://www.w3.org/2001/XMLSchema");
390                factory.setAttribute(
391                                "http://java.sun.com/xml/jaxp/properties/schemaSource",
392                                new File(xsdFile));
393                try {
394                        factory.newDocumentBuilder().parse("file:///"+
395                                        new File(finalOutputPath + "/" + documentationXmlFile).getAbsolutePath());
396                } catch (ParserConfigurationException e) {
397                        System.out.println("Parser not configured: " + e.getMessage());
398                } catch (SAXException e) {
399                        System.out.print("Parsing XML failed due to a "
400                                        + e.getClass().getName() + ":");
401                        System.out.println(e.getMessage());
402                } catch (IOException e) {
403                        System.out.println("Validation failed due to an IO Error!" +
404                                        "\n  File: "+new File(finalOutputPath + "/" + documentationXmlFile).getAbsolutePath());
405                        e.printStackTrace();
406                }
407        }
408
409        private void handleTransformation(String outputPath) {
410                long start;
411                long end;
412                long dur;
413                double durMinutes;
414                if (isGenerateHTML()) {
415                        start = System.currentTimeMillis();
416                        System.out.print("Generating html...");
417                        xml2html(outputPath, documentationXmlFile, T3D.activeProfile.getXsltFileHTML());
418                        xml2html(outputPath, importXmlFile, T3D.activeProfile.getXsltFileImport());
419                        end = System.currentTimeMillis();
420                        dur = end - start;
421                        durMinutes = ((double) dur) / 1000.0 / 60.0;
422                        System.out.println(" Generated " + (xmlPrinter.getFileCount())
423                                        + " HTML files in " + dur + "ms (" + MiscTools.doubleToString(durMinutes)
424                                        + "minutes),");
425
426                        MiscTools.streamCopyFile(T3D.activeProfile.getCssFile(),
427                                        outputPath
428                                                        + "/html/css/"
429                                                        + new File(T3D.activeProfile.getCssFile())
430                                                                        .getName());
431                        MiscTools.streamCopyFile(T3D.activeProfile.getJsFile(),
432                                        outputPath
433                                                        + "/html/js/"
434                                                        + new File(T3D.activeProfile.getJsFile())
435                                                                        .getName());
436                }
437        }
438       
439    private void xml2html(String foldername, String xmlFileName, String xsltFileName){         
440        System.setProperty("javax.xml.transform.TransformerFactory",
441        "net.sf.saxon.TransformerFactoryImpl");
442       
443        TransformerFactory tfactory = TransformerFactory.newInstance();
444        Transformer transformer;
445                try {
446                        transformer = tfactory.newTransformer(new StreamSource(new File(xsltFileName)));
447                        transformer.setParameter("folder", foldername);
448                        if(activeProfile.isIncludeConstructBody())
449                                transformer.setParameter("includeconstructbodies", "true");
450                        else
451                                transformer.setParameter("includeconstructbodies", "false");
452                        if(activeProfile.isHideConstructBody())
453                                transformer.setParameter("hideconstructbodies", "true");
454                        else
455                                transformer.setParameter("hideconstructbodies", "false");
456                        if(activeProfile.isShowOriginalT3DocTags())
457                                transformer.setParameter("showOriginalT3DocTags", "true");
458                        else
459                                transformer.setParameter("showOriginalT3DocTags", "false");
460                       
461                transformer.transform(new StreamSource(new File(foldername + "/" + xmlFileName)),
462                        new StreamResult(new FileOutputStream(foldername + "/xsltlog.txt")));
463                } catch (TransformerConfigurationException e) {
464                        e.printStackTrace();
465                } catch (TransformerException e) {
466                        e.printStackTrace();
467                } catch (FileNotFoundException e) {
468                        e.printStackTrace();
469                }
470        }
471        //TODO: DUPLICATED MOSTLY
472        private boolean handleCommandLineArguments(String[] args) throws TerminationException {
473                //parseCommandLineArguments(args);
474                CommandLine commandLine = parseCommandLineArguments(args);
475                if (commandLine == null) {
476                        return false;
477                }
478                String arguments[] = evaluateCommandLineOptions(commandLine);
479
480                if (commandLine.hasOption("help")) {
481                        showHelp();
482                        return false;
483                }
484
485                if (commandLine.hasOption("config") && arguments.length < 1) {
486                        System.out.println("ERROR: Missing input location(s)");
487                        showHelp();
488                        return false;
489                }
490
491                for (String arg : arguments) {
492                        //TODO: add validity checks
493                        inputPaths.add(arg);
494                }
495               
496                return true;
497        }
498
499        // --------------------------------------------------------------------------
500        //TODO: DUPLICATE
501        private CommandLine parseCommandLineArguments(String[] args) {
502                CommandLineParser parser = new GnuParser();
503                T3DOptionsHandler optionsHandler = new T3DOptionsHandler();
504                CommandLine commandLine = null;
505                try {
506                        commandLine = parser.parse(optionsHandler.getOptions(), args);
507                } catch (ParseException e) {
508                        System.out.println("ERROR: " + e.getMessage() );
509                        showHelp();
510                }
511                return commandLine;
512        }
513
514        // --------------------------------------------------------------------------
515        //TODO: DUPLICATED MOSTLY
516        private String[] evaluateCommandLineOptions(CommandLine commandLine) throws TerminationException {
517                this.setConfigurationFilename(commandLine.getOptionValue("config"));
518                if (commandLine.hasOption("generate-config")) {
519                        this.setConfigurationFilename(commandLine.getOptionValue("generate-config"));
520                        this.setGenerateNewConfiguration(true);
521                } else if (commandLine.hasOption("config")) {
522                        this.setConfigurationFilename(commandLine.getOptionValue("config"));
523                } else {
524                        System.out.println("ERROR: No configuration file selected!");
525                        showHelp();
526                        throw new TerminationException("");
527                }
528               
529                if (commandLine.hasOption("profile")) {
530                        this.setSelectedProfileName(commandLine.getOptionValue("profile"));
531                }
532                boolean targetFormatSet = false;
533                if (commandLine.hasOption("local-dependencies")){
534                        setGenerateDependenciesXML(true);
535                        targetFormatSet = true;
536                }
537                if (commandLine.hasOption("html")){
538                        setGenerateHTML(true);
539                        targetFormatSet = true;
540                }
541                if (commandLine.hasOption("xml-only")){
542                        setGenerateMainXML(true);
543                        targetFormatSet = true;
544                }
545               
546                if (!targetFormatSet && !this.isGenerateNewConfiguration()) {
547                        System.out.println("ERROR: No target output format set!");
548                        showHelp();
549                        System.exit(1);
550                }
551               
552                if (commandLine.hasOption("verbosity")){
553                        this.selectLogLevel(commandLine.getOptionValue("verbosity"));
554                }
555
556                if (commandLine.hasOption("output-path")){
557                        this.setDestinationPath(commandLine.getOptionValue("output-path"));
558                }
559
560                return commandLine.getArgs();
561        }
562       
563        // --------------------------------------------------------------------------
564
565        //TODO: THIS SHALL BE DEPRECATED NOW
566//      private void parseCommandLineArguments(String[] args) {
567//              String key = "";
568//              String value = "";
569//              //inputPath = "";
570//
571//              boolean lastKey = false;
572//              for (int i = 0; i < args.length; i++) {
573//                      if (args[i].startsWith("--")) {
574//                              key = args[i].replaceAll("--", "").toLowerCase();
575//
576//                              if (lastKey) {
577//                                      argsMap.put(key, "true");
578//                                      key = null;
579//                                      value = null;
580//                                      lastKey = false;
581//                              }
582//
583//                              lastKey = true;
584//                      } else {
585//                              value = args[i];
586//                              if ((key != null) && (argsMap.get(key) == null)
587//                                              && (key.length() > 0)) {
588//                                      argsMap.put(key, value);
589//                                      key = null;
590//                                      value = null;
591//                              } else {
592//                                      inputPaths.add(value);
593//                              }
594//                              lastKey = false;
595//                      }
596//              }
597//
598//              if (key != null) {
599//                      if ((argsMap.get(key) == null) && (key.length() > 0)) {
600//                              argsMap.put(key, "true");
601//                      }
602//              }
603//      }
604
605        // --------------------------------------------------------------------------
606        //TODO: DUPLICATE MOSTLY
607        private void handleConfig(String specifiedProfile) throws TerminationException {
608                ConfigTools configTools = new ConfigTools(configurationClassName, configurationProfileClassName);
609                configTools.setToolVersion(getVersionNumber());
610               
611                try {
612                        if (isGenerateNewConfiguration()) {
613                                configTools.initializeNewDefaultConfig(getConfigurationFilename());
614                                System.exit(0);
615                        } else {
616                                configTools.loadConfig(getConfigurationFilename());
617                                activeProfile = (DocumentationProfile) configTools.selectProfile(specifiedProfile);
618                                if (this.getDestinationPath()==null) {
619                                        setDestinationPath(T3D.activeProfile.getOutputDirectory());
620                                }
621                        }
622                } catch (InstantiationException e) {
623                        throw new TerminationException("ERROR: Instantiation problems encountered while loading configuration profile. "+e.getMessage());
624                } catch (IllegalAccessException e) {
625                        throw new TerminationException("ERROR: Instantiation problems encountered while loading configuration profile. "+e.getMessage());
626                } catch (ClassNotFoundException e) {
627                        throw new TerminationException("ERROR: Instantiation problems encountered while loading configuration profile. "+e.getMessage());
628                }
629               
630                if (!isProfileVersionValid()) {
631                        System.out.println("\nERROR: Selected profile \"" + activeProfile.getProfileName()
632                                        + "\" has a mismatching or no version (required: \""+getVersionNumber()+"\").\n" +
633                                                        "  Consider upgrading the profile by transfering the relevant parts to an auto-generated profile or selecting a different profile.\n");
634                        throw new TerminationException("");
635                }
636        }
637        //TODO: DUPLICATE
638        private boolean isProfileVersionValid() {
639                if (activeProfile.getProfileVersion() != null && activeProfile.getProfileVersion().equals(getVersionNumber())){
640                        return true;
641                } else {
642                        return false;
643                }
644        }
645        //TODO: DUPLICATE
646        private void selectLogLevel(String logLevel) throws TerminationException{
647                boolean selected = false;
648                String possibleValues ="";
649                for (LogLevel l : LogLevel.values()){
650                        if (l.toString().equals(logLevel)){
651                                setLogLevel(l);
652                                selected = true;
653                                System.out.println("Selected log level \""+logLevel+"\"");
654                        }
655                        if (!l.toString().equals("FIXME") && !l.toString().equals("DEBUG"))
656                        possibleValues+=l.toString()+", ";
657                }
658                if (!selected){
659                        System.out.println("\nERROR: No valid log level provided! Possible values are (in ascending inclusive order): "+ possibleValues.substring(0,possibleValues.length()-2)+".");
660                        throw new TerminationException("");
661                }
662               
663        }
664
665       
666
667
668        // --------------------------------------------------------------------------
669//      //TODO: should be obsolete now?
670//      List<String> findTTCN3Resources(String directory) {
671//              List<String> files = new LinkedList<String>();
672//
673//              File f = new File(directory);
674//
675//              File[] fileNames = f.listFiles(new FileFilter() {
676//                      public boolean accept(File pathname) {
677//                              if (pathname.getPath().endsWith(".ttcn3")
678//                                              || pathname.getPath().endsWith(".ttcn")
679//                                              || pathname.getPath().endsWith(".3mp"))
680//                                      return true;
681//                              return false;
682//                      }
683//              });
684//
685//              for (int i = 0; i < fileNames.length; i++) {
686//                      files.add(fileNames[i].getPath());
687//              }
688//
689//              File[] directories = f.listFiles(new FileFilter() {
690//                      public boolean accept(File pathname) {
691//                              if (pathname.isDirectory())
692//                                      return true;
693//                              return false;
694//                      }
695//              });
696//
697//              for (int i = 0; i < directories.length; i++) {
698//                      files.addAll(findTTCN3Resources(directories[i].getPath()));
699//              }
700//
701//              return files;
702//      }
703
704        // --------------------------------------------------------------------------
705        //TODO: DUPLICATED
706        private TTCN3Analyzer analyzeFile(String filename) {
707                TTCN3AnalyzerFlyweightFactory analyzerFactory = TTCN3AnalyzerFlyweightFactory
708                                .getInstance();
709                analyzerFactory.setStandaloneUsage(true);
710                String code = MiscTools.readFile(filename);
711
712                int loc = MiscTools.getLOC(filename);
713                linesOfCodeMap.put(filename, loc);
714                totalLoc += loc;
715
716                System.out.println("  Parsing file: " + filename + " (LOC: "
717                                + linesOfCodeMap.get(filename) + ") ...");
718                long startTime = System.currentTimeMillis();
719
720                TTCN3Analyzer analyzer = analyzerFactory.getTTCN3Analyzer(filename,
721                                code);
722                try {
723                        analyzer.analyze();
724                } catch (MismatchedTokenException e) {
725                        e.printStackTrace();
726                } catch (RecognitionException e) {
727                        e.printStackTrace();
728                } catch (TokenStreamException e) {
729                        e.printStackTrace();
730                } catch (Exception e) {
731                        e.printStackTrace();
732                }
733                long endTime = System.currentTimeMillis();
734                long elapsed = endTime - startTime;
735                double elapsedMinutes = ((double) elapsed) / 1000.0 / 60.0;
736
737                System.out.println("    ...done in " + elapsed + "ms ("
738                                + MiscTools.doubleToString(elapsedMinutes) + " minutes).");
739
740                return analyzer;
741        }
742
743        // --------------------------------------------------------------------------
744        //TODO: DUPLICATE
745        public static void setVersionNumber(String versionNumber) {
746                T3D.versionNumber = versionNumber;
747        }
748        //TODO: DUPLICATE       
749        public static String getVersionNumber() {
750                return versionNumber;
751        }
752
753        public static void main(String[] args) {
754                T3D tool = new T3D();
755                tool.run(args);
756        }
757        //TODO: DUPLICATE
758        public void setConfigurationFilename(String configurationFilename) {
759                this.configurationFilename = configurationFilename;
760        }
761        //TODO: DUPLICATE
762        public String getConfigurationFilename() {
763                return configurationFilename;
764        }
765        //TODO: DUPLICATE
766        public void setSelectedProfileName(String selectedProfileName) {
767                this.selectedProfileName = selectedProfileName;
768        }
769        //TODO: DUPLICATE
770        public String getSelectedProfileName() {
771                return selectedProfileName;
772        }
773        //TODO: DUPLICATE
774        public static void setLogLevel(LogLevel logLevel) {
775                T3D.logLevel = logLevel;
776        }
777        //TODO: DUPLICATE
778        public static LogLevel getLogLevel() {
779                return logLevel;
780        }
781
782        public static void setGenerateDependenciesXML(boolean generateDependenciesXML) {
783                T3D.generateDependenciesXML = generateDependenciesXML;
784        }
785
786        public static boolean isGenerateDependenciesXML() {
787                return generateDependenciesXML;
788        }
789
790        public static void setGenerateMainXML(boolean generateMainXML) {
791                T3D.generateMainXML = generateMainXML;
792        }
793
794        public static boolean isGenerateMainXML() {
795                return generateMainXML;
796        }
797
798        public static void setGenerateHTML(boolean generateHTML) {
799                T3D.generateHTML = generateHTML;
800        }
801
802        public static boolean isGenerateHTML() {
803                return generateHTML;
804        }
805
806        public static void setLoggingInterface(LoggingInterface logger) {
807                T3D.logger = logger;
808        }
809
810        public static LoggingInterface getLoggingInterface() {
811                return T3D.logger;
812        }
813
814        public void setGenerateNewConfiguration(boolean generateNewConfiguration) {
815                this.generateNewConfiguration = generateNewConfiguration;
816        }
817
818        public boolean isGenerateNewConfiguration() {
819                return generateNewConfiguration;
820        }
821
822        public void setDestinationPath(String destinationPath) {
823                this.destinationPath = destinationPath;
824        }
825
826        public String getDestinationPath() {
827                return destinationPath;
828        }
829
830        public static void setBuildStamp(String buildStamp) {
831                T3D.buildStamp = buildStamp;
832        }
833
834        public static String getBuildStamp() {
835                return buildStamp;
836        }
837
838}
Note: See TracBrowser for help on using the repository browser.