From 9de81e9204bacf398fd9e7e2c4311af0c456027e Mon Sep 17 00:00:00 2001
From: Omar Waldmann
Date: Wed, 24 May 2017 16:48:59 +0200
Subject: [PATCH] Update #16 Using an analyzer service to run analysis.
Changelog :
- Removal of the old Analyzer in the Analyzer plugin;
- Removal of the analysis handler in the UI plugin
- Add of an Analyzer plugin runnable from any third using
applyRules(List,List,List) and
computeMetrics(List,List,List) indicating files &
languages to run the analysis on.
- Analyzer is now responsible to run the appropriate files on the good
analyzers
- Add of a new analysis handler in UI sending every selected file to the
analyzer.
The current changes are not complete, javadoc and cleaning task should
be realized to use clean files.
---
fr.cnes.analysis.tools.analyzer/.classpath | 14 +-
.../META-INF/MANIFEST.MF | 1 +
.../build.properties | 1 +
.../fr.cnes.analysis.tools.analyzer.exsd | 15 +
.../tools/analyzer/AbstractAnalysisJob.java | 130 --
.../tools/analyzer/AbstractAnalyzer.java | 217 ---
.../analysis/tools/analyzer/Analyzer.java | 230 +++
.../analyzer/CallableMetricAnalyzer.java | 27 +
.../tools/analyzer/CallableRuleAnalyzer.java | 28 +
.../tools/analyzer/MetricAnalysisJob.java | 115 --
.../tools/analyzer/MetricAnalyzer.java | 161 --
.../tools/analyzer/RuleAnalysisJob.java | 114 --
.../analysis/tools/analyzer/RuleAnalyzer.java | 168 --
.../plugin.xml | 12 +
.../plugin.xml | 12 +
.../plugin.xml | 18 +
fr.cnes.analysis.tools.ui/plugin.xml | 2 +-
.../tools/ui/handler/AnalysisHandler.java | 281 ++++
.../ui/handler/MetricAnalysisAllHandler.java | 234 ---
.../ui/handler/MetricAnalysisHandler.java | 137 --
.../tools/ui/handler/MetricAnalysisJob.java | 79 +
.../MetricAndRulesAnalysisAllHandler.java | 66 -
.../ui/handler/RuleAnalysisAllHandler.java | 230 ---
.../tools/ui/handler/RuleAnalysisHandler.java | 137 --
.../tools/ui/handler/RuleAnalysisJob.java | 82 +
.../handler/UIAndCommandAbstractHandler.java | 40 +-
.../analysis/tools/ui/view/MetricsView.java | 988 ++++++------
.../tools/ui/view/ViolationsView.java | 1365 ++++++++---------
.../uml/handler_omar.ucls | 47 -
29 files changed, 1964 insertions(+), 2987 deletions(-)
delete mode 100755 fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/AbstractAnalysisJob.java
delete mode 100755 fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/AbstractAnalyzer.java
create mode 100644 fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/Analyzer.java
create mode 100644 fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/CallableMetricAnalyzer.java
create mode 100644 fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/CallableRuleAnalyzer.java
delete mode 100755 fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/MetricAnalysisJob.java
delete mode 100755 fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/MetricAnalyzer.java
delete mode 100755 fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/RuleAnalysisJob.java
delete mode 100755 fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/RuleAnalyzer.java
create mode 100755 fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/AnalysisHandler.java
delete mode 100755 fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/MetricAnalysisAllHandler.java
delete mode 100755 fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/MetricAnalysisHandler.java
create mode 100644 fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/MetricAnalysisJob.java
delete mode 100755 fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/MetricAndRulesAnalysisAllHandler.java
delete mode 100755 fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/RuleAnalysisAllHandler.java
delete mode 100755 fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/RuleAnalysisHandler.java
create mode 100644 fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/RuleAnalysisJob.java
delete mode 100755 fr.cnes.analysis.tools.ui/uml/handler_omar.ucls
diff --git a/fr.cnes.analysis.tools.analyzer/.classpath b/fr.cnes.analysis.tools.analyzer/.classpath
index eca7bdba..b862a296 100755
--- a/fr.cnes.analysis.tools.analyzer/.classpath
+++ b/fr.cnes.analysis.tools.analyzer/.classpath
@@ -1,7 +1,7 @@
-
-
-
-
-
-
-
+
+
+
+
+
+
+
diff --git a/fr.cnes.analysis.tools.analyzer/META-INF/MANIFEST.MF b/fr.cnes.analysis.tools.analyzer/META-INF/MANIFEST.MF
index 6b552c78..7b7c3569 100755
--- a/fr.cnes.analysis.tools.analyzer/META-INF/MANIFEST.MF
+++ b/fr.cnes.analysis.tools.analyzer/META-INF/MANIFEST.MF
@@ -14,3 +14,4 @@ Export-Package: fr.cnes.analysis.tools.analyzer;uses:="org.osgi.framework,org.ec
fr.cnes.analysis.tools.analyzer.exception
Import-Package: org.junit
Bundle-Vendor: CNES
+Bundle-ClassPath: .
diff --git a/fr.cnes.analysis.tools.analyzer/build.properties b/fr.cnes.analysis.tools.analyzer/build.properties
index 6f20375d..c125ab4d 100755
--- a/fr.cnes.analysis.tools.analyzer/build.properties
+++ b/fr.cnes.analysis.tools.analyzer/build.properties
@@ -3,3 +3,4 @@ output.. = bin/
bin.includes = META-INF/,\
.,\
plugin.xml
+source.. = src/
diff --git a/fr.cnes.analysis.tools.analyzer/schema/fr.cnes.analysis.tools.analyzer.exsd b/fr.cnes.analysis.tools.analyzer/schema/fr.cnes.analysis.tools.analyzer.exsd
index b386703e..58607857 100755
--- a/fr.cnes.analysis.tools.analyzer/schema/fr.cnes.analysis.tools.analyzer.exsd
+++ b/fr.cnes.analysis.tools.analyzer/schema/fr.cnes.analysis.tools.analyzer.exsd
@@ -49,6 +49,9 @@
+
+
+
@@ -73,6 +76,18 @@
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/AbstractAnalysisJob.java b/fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/AbstractAnalysisJob.java
deleted file mode 100755
index 125f198d..00000000
--- a/fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/AbstractAnalysisJob.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * i-Code CNES is a static code analyser.
- * This software is a free software, under the terms of the Eclipse Public License version 1.0.
- * http://www.eclipse.org/legal/epl-v10.html
- *
- */
-
-
-package fr.cnes.analysis.tools.analyzer;
-
-import java.io.File;
-import java.util.List;
-import java.util.logging.Logger;
-
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.jobs.Job;
-
-import fr.cnes.analysis.tools.analyzer.exception.NullContributionException;
-
-/**
- * This class is used run analysis on one analyzer.
- */
-public abstract class AbstractAnalysisJob extends Job {
- /** Extension point id. **/
- public static final String ANALYSIS_EXT_ID =
- "fr.cnes.analysis.tools.analyzer";
- /** Logger. **/
- public static final Logger LOGGER = Logger
- .getLogger(AbstractAnalysisJob.class.getName());
-
- /** Extension id for the analyzer to use. **/
- private String extensionId;
- /** List of files to analyze. **/
- private List files;
-
- /**
- * Constructor for this Job with extension id in parameter and files' path.
- *
- * @param pExtensionId
- * the extension id of the analyzer on which this job applies
- * @param pFiles
- * list of path for files to analyze
- */
- public AbstractAnalysisJob(final String pExtensionId,
- final List pFiles) {
- super("Running analysis...");
- this.extensionId = pExtensionId;
- this.files = pFiles;
- }
-
- /**
- * Getter for the extension id.
- *
- * @return the extensionId
- */
- public String getExtensionId() {
- return this.extensionId;
- }
-
- /**
- * Getter for the files
- *
- * @return the files
- */
- public List getFiles() {
- return this.files;
- }
-
- /**
- * Setter for the extension id.
- *
- * @param pExtensionId
- * the extensionId to set
- */
- public void setExtensionId(final String pExtensionId) {
- this.extensionId = pExtensionId;
- }
-
- /**
- * Setter for the files
- *
- * @param pFiles
- * the files to set
- */
- public void setFiles(final List pFiles) {
- this.files = pFiles;
- }
-
- /**
- * This method returns an analyzer contribution giving analyzer extension
- * point contribution id. If no analyzer corresponds to the id, the method
- * returns null.
- *
- * @param analyzerId
- * the analyzer id
- * @return the analyzer contribution
- * @throws NullContributionException
- * when there is no contribution associated to this id
- */
- public static IConfigurationElement
- getContribution(final String analyzerId)
- throws NullContributionException {
- LOGGER.finest("Begin getContribution method");
-
- // Get all contributions
- final IConfigurationElement[] contributions =
- Platform.getExtensionRegistry().getConfigurationElementsFor(
- ANALYSIS_EXT_ID);
-
- // Look for the corresponding one
- IConfigurationElement analyzeContrib = null;
- int index = 0;
- while ((analyzeContrib == null) && index < contributions.length) {
- if (contributions[index].getAttribute("id").equals(analyzerId)) {
- analyzeContrib = contributions[index];
- }
- index = index + 1;
- }
-
- if (analyzeContrib == null) {
- throw new NullContributionException("No contribution found for "
- + analyzerId);
- } else {
- LOGGER.finest("End getContribution method");
- return analyzeContrib;
- }
-
- }
-}
diff --git a/fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/AbstractAnalyzer.java b/fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/AbstractAnalyzer.java
deleted file mode 100755
index 24ee61cf..00000000
--- a/fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/AbstractAnalyzer.java
+++ /dev/null
@@ -1,217 +0,0 @@
-/*
- * i-Code CNES is a static code analyser.
- * This software is a free software, under the terms of the Eclipse Public License version 1.0.
- * http://www.eclipse.org/legal/epl-v10.html
- *
- */
-
-package fr.cnes.analysis.tools.analyzer;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.util.List;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.ui.PlatformUI;
-
-import fr.cnes.analysis.tools.analyzer.exception.JFlexException;
-
-/**
- * This class defines the structure of an analyzer. The analyzer is the class
- * that runs all the analysis, for all rules or metrics. Each analyzer, for
- * metric or rule, for each language, must extend this class.
- */
-public abstract class AbstractAnalyzer extends Job {
- /** Logger. */
- private static final Logger LOGGER = Logger
- .getLogger(AbstractAnalyzer.class.getName());
-
- /** Files to be analyzed. */
- private List files;
- /** the id of rule/metric contribution **/
- private String extensionId;
-
- /**
- * Constructor that set the job with string name, extension id and a list
- * of {@link org.eclipse.core.runtime.IPath}.
- *
- * @param name
- * the name of this Job
- * @param pFilePath
- * the files to analyze
- * @param pExtensionId
- * the id of rule/metric contribution
- */
- public AbstractAnalyzer(final String name, final List pFilePath,
- final String pExtensionId) {
- super(name);
- this.files = pFilePath;
- this.extensionId = pExtensionId;
- }
-
- /**
- * Retrieve the files.
- *
- * @return the files path.
- */
- public List getFiles() {
- return this.files;
- }
-
- /**
- * Getter for the extension id.
- *
- * @return the id of rule/metric contribution
- */
- public String getExtensionId() {
- return this.extensionId;
- }
-
- /**
- * Set the files path.
- *
- * @param inputFiles
- * the files path.
- */
- public void setFiles(final List inputFiles) {
- this.files = inputFiles;
- }
-
- /**
- * Setter for the id of rule/metric contribution.
- *
- * @param pExtensionId
- * the extensionId to set
- */
- public void setExtensionId(final String pExtensionId) {
- this.extensionId = pExtensionId;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.
- * IProgressMonitor)
- */
- @Override
- protected IStatus run(final IProgressMonitor monitor) {
- LOGGER.finest("Begin run method");
-
- // Instantiate return variable
- IStatus status = Status.OK_STATUS;
-
- try {
- // Instantiate other variables
- final IConfigurationElement[] evalContribs =
- Platform.getExtensionRegistry()
- .getConfigurationElementsFor(this.extensionId);
-
- // Calculate total work to do
- final List pFiles = this.getFiles();
- int totalEval = 0;
- for (final IConfigurationElement contribution : evalContribs) {
- if (PlatformUI.getPreferenceStore().getBoolean(
- contribution.getAttribute("id"))) {
- totalEval = totalEval + 1;
- }
- }
- final int totalWork = pFiles.size() * totalEval;
-
- // Begin global analysis
- monitor.beginTask("Running analysis...", totalWork);
- for (final IConfigurationElement contribution : evalContribs) {
-
- // Run analysis for this evaluation if it is allowed in the
- // preference store
- if (PlatformUI.getPreferenceStore().getBoolean(
- contribution.getAttribute("id"))) {
- status = this.runEvaluation(contribution, pFiles, monitor);
- }
-
- // Stop analysis if cancel button selected
- if (Status.CANCEL_STATUS.equals(status)) {
- break;
- }
- }
-
- // End the job
- monitor.done();
-
- } catch (final CoreException exception) {
- LOGGER.log(Level.FINER,
- exception.getClass() + " : " + exception.getMessage(),
- exception);
- status =
- new Status(Status.ERROR,
- "fr.cnes.analysis.tools.fortran.analyzer",
- exception.getMessage());
- } catch (final FileNotFoundException exception) {
- LOGGER.log(Level.FINER,
- exception.getClass() + " : " + exception.getMessage(),
- exception);
- status =
- new Status(Status.ERROR,
- "fr.cnes.analysis.tools.fortran.analyzer",
- exception.getMessage());
- } catch (final IOException exception) {
- LOGGER.log(Level.FINER,
- exception.getClass() + " : " + exception.getMessage(),
- exception);
- status =
- new Status(Status.ERROR,
- "fr.cnes.analysis.tools.fortran.analyzer",
- exception.getMessage());
- } catch (final JFlexException exception) {
- LOGGER.log(Level.FINER,
- exception.getClass() + " : " + exception.getMessage(),
- exception);
- status =
- new Status(Status.ERROR,
- "fr.cnes.analysis.tools.fortran.analyzer",
- exception.getMessage());
- } catch (final CloneNotSupportedException exception) {
- LOGGER.log(Level.FINER,
- exception.getClass() + " : " + exception.getMessage(),
- exception);
- status =
- new Status(Status.ERROR,
- "fr.cnes.analysis.tools.fortran.analyzer",
- exception.getMessage());
- }
- LOGGER.finest("End run method");
- return status;
- }
-
- /**
- * Compute the provided evaluation on all files.
- *
- * @param contribution
- * evaluation contribution
- * @param pFiles
- * files to analyze
- * @param monitor
- * the monitor on which Job is run
- * @return status of this job
- * @throws CloneNotSupportedException
- * when cloning fails
- * @throws CoreException
- * internal exception
- * @throws IOException
- * internal exception
- * @throws JFlexException
- * JFlex analysis exception
- */
- protected abstract IStatus runEvaluation(
- final IConfigurationElement contribution,
- final List pFiles, final IProgressMonitor monitor)
- throws CloneNotSupportedException, CoreException,
- IOException, JFlexException;
-}
diff --git a/fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/Analyzer.java b/fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/Analyzer.java
new file mode 100644
index 00000000..065ad8f7
--- /dev/null
+++ b/fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/Analyzer.java
@@ -0,0 +1,230 @@
+package fr.cnes.analysis.tools.analyzer;
+
+import fr.cnes.analysis.tools.analyzer.datas.AbstractMetric;
+import fr.cnes.analysis.tools.analyzer.datas.AbstractRule;
+import fr.cnes.analysis.tools.analyzer.datas.FileValue;
+import fr.cnes.analysis.tools.analyzer.datas.Violation;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IConfigurationElement;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.ui.PlatformUI;
+
+/**
+ * i-Code CNES analyzer service
+ *
+ * This class can be used by any third using {@link File} and {@link String} to run an analysis.
+ *
+ *
+ * Using the methods {@link #applyRules(List, List)} and {@link #computeMetrics(List, File)}, the
+ * {@link File} list must contain all files to analyze and the {@link String} list all rules id of
+ * different plugin contributing to the
+ *
+ *
+ */
+public class Analyzer {
+
+ public static String Analyzer_ExtensionPoint_ID = "fr.cnes.analysis.tools.analyzer";
+
+ /**
+ * This method run an analysis using a {@link List} of {@link File} and identifier of i-Code CNES
+ * rules contributing to the plugin.
+ *
+ * This analysis is being run
+ *
+ * @param files
+ * @param rulesId
+ * @return
+ * @throws FileNotFoundException
+ */
+ public List applyRules(List files, List pLanguageIds,
+ List pExcludedCheckIds) throws FileNotFoundException, Exception {
+ List languageIds = pLanguageIds;
+ if (languageIds == null) {
+ languageIds = new ArrayList();
+ }
+ List excludedCheckIds = pExcludedCheckIds;
+ if (pExcludedCheckIds == null) {
+ excludedCheckIds = new ArrayList();
+ }
+ List analysisResultViolation = new ArrayList<>();
+ /*
+ * The number of threads could be defined by the number of files or the number of rule or both
+ * of them. This is pending how we decide to run the analysis.
+ *
+ * TODO : Chose one solution for the number of threads
+ */
+ ExecutorService service = Executors.newFixedThreadPool(25);
+ List>> analyzers = new ArrayList>>();
+ /*
+
+ */
+ for (IConfigurationElement analyzerContribution : Platform.getExtensionRegistry()
+ .getConfigurationElementsFor(Analyzer.Analyzer_ExtensionPoint_ID)) {
+ if (languageIds.contains(analyzerContribution.getAttribute("extensionId"))) {
+ /*
+ * The current extension is one of the analyzer contribution that will be run. We are now
+ * configuring it.
+ */
+ // 1. Setting files that will be analyzed
+ // 1.1. Finding allowed extension from the plugin analyzer
+
+ ArrayList allowedExtension = new ArrayList<>();
+ for (IConfigurationElement fileExtension : analyzerContribution
+ .getChildren("fileExtension")) {
+ allowedExtension.add(fileExtension.getAttribute("name"));
+ }
+ // 1.2. Restricting analysis only on file that the plugin can handle.
+ // Note : The restriction is for file without extension and file that will be already
+ // analyzed. This is causing crash from the analysis.
+ ArrayList restrictedFiles = new ArrayList<>();
+ for (File file : files) {
+ if (allowedExtension.contains(this.getFileExtension(file.getAbsolutePath()))
+ && !restrictedFiles.contains(file)) {
+ restrictedFiles.add(file);
+ }
+ }
+ // 2. Running all rules that are not excluded from the analysis.
+ // 2.1 Retrieving all rules from the extension point.
+ for (IConfigurationElement contribution : Platform.getExtensionRegistry()
+ .getConfigurationElementsFor(analyzerContribution.getAttribute("extensionId"))) {
+ // 2.2 If the rule is not excluded, run the analysis.
+ if (PlatformUI.getPreferenceStore().contains(contribution.getAttribute("id"))
+ && !excludedCheckIds.contains((contribution.getAttribute("id")))) {
+ AbstractRule rule;
+ /*
+ * We are currently to load as much Rule as there is files because the lex files are
+ * designed to be run only on one file.
+ */
+ for (File analyzedFile : restrictedFiles) {
+ try {
+ rule = (AbstractRule) contribution.createExecutableExtension("class");
+ rule.setContribution(contribution);
+ CallableRuleAnalyzer callableAnalysis = new CallableRuleAnalyzer(rule,
+ analyzedFile);
+ analyzers.add(service.submit(callableAnalysis));
+ } catch (CoreException e) {
+
+ // TODO : Define how to warn here of the execution failure without throwing new
+ // exception
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+ }
+ }
+
+ for (Future> analysis : analyzers) {
+ try {
+ analysisResultViolation.addAll(analysis.get());
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (ExecutionException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ }
+ return analysisResultViolation;
+ }
+
+ /**
+ * @param fileName
+ * @return The extension name of the file
+ */
+ private String getFileExtension(String fileName) {
+ String extension = null;
+
+ int i = fileName.lastIndexOf('.');
+ int p = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));
+
+ if (i > p) {
+ extension = fileName.substring(i + 1);
+ }
+ return extension;
+ }
+
+ public List computeMetrics(List files, List pLanguageIds,
+ List pExcludedCheckIds) {
+ List languageIds = pLanguageIds;
+ if (languageIds == null) {
+ languageIds = new ArrayList();
+ }
+ List excludedCheckIds = pExcludedCheckIds;
+ if (pExcludedCheckIds == null) {
+ excludedCheckIds = new ArrayList();
+ }
+ List analysisResultFileValues = new ArrayList<>();
+ /*
+ * The number of threads could be defined by the number of files or the number of rule or both
+ * of them. This is pending how we decide to run the analysis.
+ *
+ * TODO : Chose one solution for the number of threads
+ */
+ ExecutorService service = Executors.newSingleThreadExecutor();
+ List>> analyzers = new ArrayList>>();
+
+ for (IConfigurationElement analyzerContribution : Platform.getExtensionRegistry()
+ .getConfigurationElementsFor(Analyzer.Analyzer_ExtensionPoint_ID)) {
+ if (languageIds.contains(analyzerContribution.getAttribute("extensionId"))) {
+ ArrayList allowedExtension = new ArrayList<>();
+ for (IConfigurationElement fileExtension : analyzerContribution
+ .getChildren("fileExtension")) {
+ allowedExtension.add(fileExtension.getAttribute("name"));
+ }
+ // 1.2. Restricting analysis only on file that the plugin can handle.
+ ArrayList restrictedFiles = new ArrayList<>();
+ for (File file : files) {
+ if (allowedExtension.contains(this.getFileExtension(file.getAbsolutePath()))
+ && !restrictedFiles.contains(file)) {
+ restrictedFiles.add(file);
+ }
+ }
+ for (IConfigurationElement contribution : Platform.getExtensionRegistry()
+ .getConfigurationElementsFor(analyzerContribution.getAttribute("extensionId"))) {
+ if (PlatformUI.getPreferenceStore().contains(contribution.getAttribute("id"))
+ && !excludedCheckIds.contains(contribution.getAttribute("id"))) {
+ AbstractMetric metric;
+ for (File analysisFile : restrictedFiles) {
+ try {
+ metric = (AbstractMetric) contribution.createExecutableExtension("class");
+ metric.setContribution(contribution);
+ CallableMetricAnalyzer callableAnalysis = new CallableMetricAnalyzer(metric,
+ analysisFile);
+ analyzers.add(service.submit(callableAnalysis));
+ } catch (CoreException e) {
+
+ // TODO : Define how to warn here of the execution failure without throwing new
+ // exception
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+ }
+ }
+
+ for (Future> analysis : analyzers) {
+ try {
+ analysisResultFileValues.addAll(analysis.get());
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (ExecutionException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+ return analysisResultFileValues;
+ }
+
+}
diff --git a/fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/CallableMetricAnalyzer.java b/fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/CallableMetricAnalyzer.java
new file mode 100644
index 00000000..e00b338d
--- /dev/null
+++ b/fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/CallableMetricAnalyzer.java
@@ -0,0 +1,27 @@
+package fr.cnes.analysis.tools.analyzer;
+
+import fr.cnes.analysis.tools.analyzer.datas.AbstractMetric;
+import fr.cnes.analysis.tools.analyzer.datas.FileValue;
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.Callable;
+
+public class CallableMetricAnalyzer implements Callable> {
+
+ private AbstractMetric metric;
+ private File file;
+
+ public CallableMetricAnalyzer(AbstractMetric pMetric, File pFile) {
+ this.metric = pMetric;
+ this.file = pFile;
+ }
+
+ @Override
+ public List call() throws Exception {
+ List results = new ArrayList<>();
+ metric.setInputFile(file);
+ results.add(metric.run());
+ return results;
+ }
+}
diff --git a/fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/CallableRuleAnalyzer.java b/fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/CallableRuleAnalyzer.java
new file mode 100644
index 00000000..b4b98af4
--- /dev/null
+++ b/fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/CallableRuleAnalyzer.java
@@ -0,0 +1,28 @@
+package fr.cnes.analysis.tools.analyzer;
+
+import fr.cnes.analysis.tools.analyzer.datas.AbstractRule;
+import fr.cnes.analysis.tools.analyzer.datas.Violation;
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.Callable;
+
+public class CallableRuleAnalyzer implements Callable> {
+
+ private AbstractRule rule;
+ private File file;
+
+ public CallableRuleAnalyzer(AbstractRule rule, File file) {
+ this.rule = rule;
+ this.file = file;
+ }
+
+ @Override
+ public List call() throws Exception {
+ List results = new ArrayList<>();
+ rule.setInputFile(file);
+ results.addAll(rule.run());
+ return results;
+ }
+
+}
diff --git a/fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/MetricAnalysisJob.java b/fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/MetricAnalysisJob.java
deleted file mode 100755
index c45f8aa6..00000000
--- a/fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/MetricAnalysisJob.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * i-Code CNES is a static code analyser.
- * This software is a free software, under the terms of the Eclipse Public License version 1.0.
- * http://www.eclipse.org/legal/epl-v10.html
- *
- */
-package fr.cnes.analysis.tools.analyzer;
-
-import java.io.File;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.logging.Level;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-
-import fr.cnes.analysis.tools.analyzer.datas.FileValue;
-import fr.cnes.analysis.tools.analyzer.exception.NullContributionException;
-
-/**
- * This class is used for metric analysis on a metric analyzer.
- */
-public class MetricAnalysisJob extends AbstractAnalysisJob {
- /** Array of descriptors used to store result of analysis. **/
- private List values;
-
- /**
- * Constructor for this Job with extension id in parameter and files' path.
- *
- * @param pExtensionId
- * the extension id of the analyzer on which this job applies
- * @param pFiles
- * list of path for files to analyze
- */
- public MetricAnalysisJob(final String pExtensionId,
- final List pFiles) {
- super(pExtensionId, pFiles);
- this.values = new LinkedList();
- }
-
- /**
- * Getter for the values.
- *
- * @return the values
- */
- public List getValues() {
- return this.values;
- }
-
- /**
- * Setter for the values.
- *
- * @param pValues
- * the values to set
- */
- public void setValues(final List pValues) {
- this.values = pValues;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.
- * IProgressMonitor)
- */
- @Override
- public IStatus run(final IProgressMonitor monitor) {
- LOGGER.finest("Begin run method");
-
- // Instantiate return variable
- IStatus status = Status.OK_STATUS;
-
- try {
- final IConfigurationElement contribution =
- AbstractAnalysisJob.getContribution(this.getExtensionId());
- if (contribution == null) {
- throw new CoreException(new Status(IStatus.ERROR,
- "AnalysisJob", 0, "No contribution for analyzer id : "
- + this.getExtensionId(), null));
- } else {
- final MetricAnalyzer analyzer =
- new MetricAnalyzer("Run "
- + contribution.getAttribute("name")
- + " computation...", this.getFiles(),
- contribution.getAttribute("extensionId"));
-
- analyzer.setUser(true);
-
- status = analyzer.run(monitor);
- this.values = analyzer.getValues();
-
- }
- } catch (final CoreException exception) {
- LOGGER.log(Level.FINER,
- exception.getClass() + " : " + exception.getMessage(),
- exception);
- status =
- new Status(Status.ERROR,
- "fr.cnes.analysis.tools.fortran.analyzer",
- Status.ERROR, exception.getMessage(), exception);
- } catch (final NullContributionException exception) {
- LOGGER.log(Level.FINER,
- exception.getClass() + " : " + exception.getMessage(),
- exception);
- status =
- new Status(Status.ERROR,
- "fr.cnes.analysis.tools.fortran.analyzer",
- Status.ERROR, exception.getMessage(), exception);
- }
- LOGGER.finest("End run method");
- return status;
- }
-}
diff --git a/fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/MetricAnalyzer.java b/fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/MetricAnalyzer.java
deleted file mode 100755
index e2218cd0..00000000
--- a/fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/MetricAnalyzer.java
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- * i-Code CNES is a static code analyser.
- * This software is a free software, under the terms of the Eclipse Public License version 1.0.
- * http://www.eclipse.org/legal/epl-v10.html
- *
- */
-package fr.cnes.analysis.tools.analyzer;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.logging.Logger;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-
-import fr.cnes.analysis.tools.analyzer.datas.AbstractMetric;
-import fr.cnes.analysis.tools.analyzer.datas.FileValue;
-import fr.cnes.analysis.tools.analyzer.exception.JFlexException;
-
-/**
- * This class is used to instantiate a new metric analyzer.
- */
-public class MetricAnalyzer extends AbstractAnalyzer {
- /** Logger. */
- private static final Logger LOGGER = Logger.getLogger(MetricAnalyzer.class
- .getName());
-
- /** List of values found during analysis. **/
- private List values;
-
- /**
- * Constructor that set the job with string name, extension id and a list
- * of {@link org.eclipse.core.runtime.IPath}.
- *
- * @param name
- * the name of this Job
- * @param pFile
- * the files to analyze
- * @param pExtensionId
- * the id of rule/metric contribution
- */
- public MetricAnalyzer(final String name, final List pFile,
- final String pExtensionId) {
- super(name, pFile, pExtensionId);
- this.values = new LinkedList();
- }
-
- /**
- * Retrieve the values of analysis.
- *
- * @return values of the metric analysis
- */
- public List getValues() {
- return this.values;
- }
-
- /**
- * Set the values with a list.
- *
- * @param pValues
- * the list of values to set
- */
- public void setValues(final List pValues) {
- this.values = pValues;
- }
-
- /**
- * Set the values with an array.
- *
- * @param pValues
- * the array of values to set
- */
- public void setValues(final FileValue[] pValues) {
- this.values = new LinkedList();
- for (final FileValue value : pValues) {
- this.values.add(value);
- }
- }
-
- /*
- * (non-Javadoc)
- * @see
- * fr.cnes.analysis.tools.analyzer.AbstractAnalyzer#runEvaluation(org.eclipse
- * .core.runtime.IConfigurationElement, java.util.List,
- * org.eclipse.core.runtime.IProgressMonitor)
- */
- @Override
- protected IStatus runEvaluation(final IConfigurationElement contribution,
- final List pFiles, final IProgressMonitor monitor)
- throws CloneNotSupportedException, CoreException,
- IOException, JFlexException {
- LOGGER.finest("Begin runEvaluation method");
-
- // Instantiate return variable
- IStatus status = Status.OK_STATUS;
-
- // Run analysis on all files
- for (final File file : pFiles) {
- // Get the evaluation
- final AbstractMetric metric =
- (AbstractMetric) contribution
- .createExecutableExtension("class");
- metric.setContribution(contribution);
-
- // Run the evaluation
- LOGGER.finest("File : " + file.getName());
- monitor.subTask("Analyzing " + contribution.getAttribute("id")
- + " on file " + file.getName());
- this.values.add(this.runMetricOnFile(metric, file));
- monitor.worked(1);
-
- // Stop analysis if cancel button selected
- if (monitor.isCanceled()) {
- status = Status.CANCEL_STATUS;
- break;
- }
- }
-
- LOGGER.finest("End runEvaluation method");
- return status;
- }
-
- /**
- * Compute the provided metric on the file.
- *
- * @param metric
- * the evaluation to compute
- * @param file
- * the file to measure
- * @return list of evaluation (metric value or rule violations)
- * @throws IOException
- * internal error
- * @throws JFlexException
- * JFlex analysis error
- */
- private FileValue runMetricOnFile(final AbstractMetric metric,
- final File file) throws IOException,
- JFlexException {
- LOGGER.finest("Begin runEvaluationOnFile method");
-
- // Initializing file reader in the metric
- metric.setInputFile(file);
-
- LOGGER.finest("End runEvaluationOnFile method");
- return metric.run();
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.core.runtime.jobs.Job#canceling()
- */
- @Override
- protected void canceling() {
- this.values.clear();
- }
-}
diff --git a/fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/RuleAnalysisJob.java b/fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/RuleAnalysisJob.java
deleted file mode 100755
index c9a2ec1c..00000000
--- a/fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/RuleAnalysisJob.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * i-Code CNES is a static code analyser.
- * This software is a free software, under the terms of the Eclipse Public License version 1.0.
- * http://www.eclipse.org/legal/epl-v10.html
- *
- */
-package fr.cnes.analysis.tools.analyzer;
-
-import java.io.File;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.logging.Level;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-
-import fr.cnes.analysis.tools.analyzer.datas.Violation;
-import fr.cnes.analysis.tools.analyzer.exception.NullContributionException;
-
-/**
- * This class is used run analysis on a rule analyzer.
- */
-public class RuleAnalysisJob extends AbstractAnalysisJob {
- /** Array of descriptors used to store result of analysis. **/
- private List violations;
-
- /**
- * Constructor for this Job with extension id in parameter and files' path.
- *
- * @param pExtensionId
- * the extension id of the analyzer on which this job applies
- * @param pFiles
- * list of path for files to analyze
- */
- public RuleAnalysisJob(final String pExtensionId, final List pFiles) {
- super(pExtensionId, pFiles);
- this.violations = new LinkedList();
- }
-
- /**
- * Getter for the violations.
- *
- * @return the violations
- */
- public List getViolations() {
- return this.violations;
- }
-
- /**
- * Setter for the violations.
- *
- * @param pViolations
- * the violations to set
- */
- public void setViolations(final List pViolations) {
- this.violations = pViolations;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.
- * IProgressMonitor)
- */
- @Override
- public IStatus run(final IProgressMonitor monitor) {
- LOGGER.finest("Begin run method");
-
- // Instantiate return variable
- IStatus status = Status.OK_STATUS;
-
- try {
- final IConfigurationElement contribution =
- AbstractAnalysisJob.getContribution(this.getExtensionId());
- if (contribution == null) {
- throw new CoreException(new Status(IStatus.ERROR,
- "AnalysisJob", 0, "No contribution for analyzer id : "
- + this.getExtensionId(), null));
- } else {
- final RuleAnalyzer analyzer =
- new RuleAnalyzer("Run "
- + contribution.getAttribute("name")
- + " computation...", this.getFiles(),
- contribution.getAttribute("extensionId"));
-
- analyzer.setUser(true);
-
- status = analyzer.run(monitor);
- this.violations = analyzer.getViolations();
-
- }
- } catch (final CoreException exception) {
- LOGGER.log(Level.FINER,
- exception.getClass() + " : " + exception.getMessage(),
- exception);
- status =
- new Status(Status.ERROR,
- "fr.cnes.analysis.tools.fortran.analyzer",
- Status.ERROR, exception.getMessage(), exception);
- } catch (final NullContributionException exception) {
- LOGGER.log(Level.FINER,
- exception.getClass() + " : " + exception.getMessage(),
- exception);
- status =
- new Status(Status.ERROR,
- "fr.cnes.analysis.tools.fortran.analyzer",
- Status.ERROR, exception.getMessage(), exception);
- }
- LOGGER.finest("End run method");
- return status;
- }
-}
diff --git a/fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/RuleAnalyzer.java b/fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/RuleAnalyzer.java
deleted file mode 100755
index e84a4770..00000000
--- a/fr.cnes.analysis.tools.analyzer/src/fr/cnes/analysis/tools/analyzer/RuleAnalyzer.java
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
- * i-Code CNES is a static code analyser.
- * This software is a free software, under the terms of the Eclipse Public License version 1.0.
- * http://www.eclipse.org/legal/epl-v10.html
- *
- */
-package fr.cnes.analysis.tools.analyzer;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.logging.Logger;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-
-import fr.cnes.analysis.tools.analyzer.datas.AbstractRule;
-import fr.cnes.analysis.tools.analyzer.datas.Violation;
-import fr.cnes.analysis.tools.analyzer.exception.JFlexException;
-
-/**
- * This class is used to instantiate a new rule analyzer.
- */
-public class RuleAnalyzer extends AbstractAnalyzer {
- /** Logger. */
- private static final Logger LOGGER = Logger.getLogger(RuleAnalyzer.class
- .getName());
-
- /** List of values found during analysis. **/
- private List violations;
-
- /**
- * Constructor that set the job with string name, extension id and a list of
- * {@link org.eclipse.core.runtime.IPath}.
- *
- * @param name
- * the name of this Job
- * @param list
- * the files to analyze
- * @param pExtensionId
- * the id of rule/metric contribution
- */
- public RuleAnalyzer(final String name, final List list,
- final String pExtensionId) {
- super(name, list, pExtensionId);
- this.violations = new LinkedList();
- }
-
- /**
- * Retrieve the violations of analysis.
- *
- * @return violations of the rule analysis
- */
- public List getViolations() {
- return this.violations;
- }
-
- /**
- * Set the values with a list.
- *
- * @param pViolations
- * the list of violations to set
- */
- public void setViolations(final List pViolations) {
- this.violations = pViolations;
- }
-
- /**
- * Set the values with an array.
- *
- * @param pViolations
- * the array of violations to set
- */
- public void setDescriptors(final Violation[] pViolations) {
- this.violations = new LinkedList();
- for (final Violation value : pViolations) {
- this.violations.add(value);
- }
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * fr.cnes.analysis.tools.analyzer.AbstractAnalyzer#runEvaluation(org.eclipse
- * .core.runtime.IConfigurationElement, java.util.List,
- * org.eclipse.core.runtime.IProgressMonitor)
- */
- @Override
- protected IStatus runEvaluation(final IConfigurationElement contribution,
- final List pFiles, final IProgressMonitor monitor)
- throws CloneNotSupportedException, CoreException, IOException,
- JFlexException {
- LOGGER.finest("Begin runEvaluation method");
-
- // Instantiate return variable
- IStatus status = Status.OK_STATUS;
-
- // Run analysis on all files
- for (final File file : pFiles) {
-
- // Get the evaluation
- final AbstractRule rule = (AbstractRule) contribution
- .createExecutableExtension("class");
- rule.setContribution(contribution);
-
- // Run the evaluation
- LOGGER.finest("File : " + file.getName());
- monitor.subTask("Analyzing " + contribution.getAttribute("id")
- + " on file " + file.getName());
- this.violations.addAll(this.runRuleOnFile(rule, file));
- monitor.worked(1);
-
- // Stop analysis if cancel button selected
- if (monitor.isCanceled()) {
- status = Status.CANCEL_STATUS;
- break;
- }
- }
-
- LOGGER.finest("End runEvaluation method");
- return status;
- }
-
- /**
- * Compute the provided rule on the file.
- *
- * @param rule
- * the rule to compute
- * @param file
- * the file to measure
- * @return list of evaluation (metric value or rule violations)
- * @throws IOException
- * internal error
- * @throws JFlexException
- * JFlex analysis error
- */
- private List runRuleOnFile(final AbstractRule rule,
- final File file) throws IOException, JFlexException {
- LOGGER.finest("Begin runRuleOnFile method");
-
- // Initializing file reader in the metric
- rule.setInputFile(file);
-
- LOGGER.finest("End runRuleOnFile method");
- try {
- return rule.run();
- } catch (JFlexException e) {
- String msg = e.getCause().getMessage() + " : file " + file
- + " : rule " + rule.getClass();
- throw new JFlexException(new Exception(msg));
- }
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.core.runtime.jobs.Job#canceling()
- */
- @Override
- protected void canceling() {
- this.violations.clear();
- }
-}
diff --git a/fr.cnes.analysis.tools.fortran77.analyzer/plugin.xml b/fr.cnes.analysis.tools.fortran77.analyzer/plugin.xml
index 1899056b..e6cc78aa 100755
--- a/fr.cnes.analysis.tools.fortran77.analyzer/plugin.xml
+++ b/fr.cnes.analysis.tools.fortran77.analyzer/plugin.xml
@@ -9,11 +9,23 @@
extensionId="fr.cnes.analysis.tools.fortran77.metric"
id="fr.cnes.analysis.tools.fortran77.analyzer.metric"
name="Fortran 77 Metric">
+
+
+
+
+
+
+
+
diff --git a/fr.cnes.analysis.tools.fortran90.analyzer/plugin.xml b/fr.cnes.analysis.tools.fortran90.analyzer/plugin.xml
index b9a395cd..388dd21f 100755
--- a/fr.cnes.analysis.tools.fortran90.analyzer/plugin.xml
+++ b/fr.cnes.analysis.tools.fortran90.analyzer/plugin.xml
@@ -9,11 +9,23 @@
extensionId="fr.cnes.analysis.tools.fortran90.rule"
id="fr.cnes.analysis.tools.fortran90.analyzer.rule"
name="Fortran 90 Rule">
+
+
+
+
+
+
+
+
diff --git a/fr.cnes.analysis.tools.shell.analyzer/plugin.xml b/fr.cnes.analysis.tools.shell.analyzer/plugin.xml
index 914e21eb..22eda5e0 100755
--- a/fr.cnes.analysis.tools.shell.analyzer/plugin.xml
+++ b/fr.cnes.analysis.tools.shell.analyzer/plugin.xml
@@ -9,11 +9,29 @@
extensionId="fr.cnes.analysis.tools.shell.rule"
id="fr.cnes.analysis.tools.shell.analyzer.rule"
name="Shell Rule">
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/fr.cnes.analysis.tools.ui/plugin.xml b/fr.cnes.analysis.tools.ui/plugin.xml
index d397be20..3975c851 100755
--- a/fr.cnes.analysis.tools.ui/plugin.xml
+++ b/fr.cnes.analysis.tools.ui/plugin.xml
@@ -167,7 +167,7 @@
+ class="fr.cnes.analysis.tools.ui.handler.AnalysisHandler">
+ * On {@link #execute(ExecutionEvent)} :
+ *
+ * - Identify which languages should be analyzed in {@link IPreferenceStore}.
+ * - Identify which Rules or Metric should be analyzed in {@link IPreferenceStore}
+ * - Identify which {@link File}s should be analyzed using {@link PlatformUI}'s selection
+ * service.
+ * - Run an analysis using {@link RuleAnalysisJob}
+ *
+ *
+ *
+ * @since 3.0
+ */
+public class AnalysisHandler extends UIAndCommandAbstractHandler {
+ /** Logger. **/
+ private static final Logger LOGGER = Logger.getLogger(AnalysisHandler.class.getName());
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands. ExecutionEvent)
+ */
+ @Override
+ public Object execute(final ExecutionEvent event) throws ExecutionException {
+
+ /*
+ * 1.Identification the languages to analyze :
+ *
+ */
+ List analysisRules = new ArrayList<>();
+ List analysisMetrics = new ArrayList<>();
+ IPreferenceStore store = PlatformUI.getPreferenceStore();
+ for (IConfigurationElement contribution : Platform.getExtensionRegistry()
+ .getConfigurationElementsFor(PreferencesUIUtils.PREF_EXT_PT_ID)) {
+ /*
+ * 1.1. Identification of the rules plugin activated :
+ */
+ if (store.getBoolean(contribution.getAttribute(PreferencesUIUtils.PARENT_ID))
+ && store.getBoolean(contribution.getAttribute(PreferencesUIUtils.RULE_PAGE_ID))) {
+ analysisRules.add(contribution.getAttribute(PreferencesUIUtils.RULE_EXT_ID));
+ }
+ /*
+ * 1.2. Identification of the metric plugin activated :
+ */
+ if (store.getBoolean(contribution.getAttribute(PreferencesUIUtils.PARENT_ID))
+ && store.getBoolean(contribution.getAttribute(PreferencesUIUtils.METRIC_PAGE_ID))) {
+ analysisMetrics.add(contribution.getAttribute(PreferencesUIUtils.METRIC_EXT_ID));
+ }
+ }
+
+ /*
+ * 2. Identification the rule & metrics that are deactivated :
+ */
+ List excludedRules = new ArrayList<>();
+ List excludedMetrics = new ArrayList<>();
+ for (IConfigurationElement analyzerContribution : Platform.getExtensionRegistry()
+ .getConfigurationElementsFor(Analyzer.Analyzer_ExtensionPoint_ID)) {
+ if (analysisRules.contains(analyzerContribution.getAttribute("extensionId"))) {
+ for (IConfigurationElement contribution : Platform.getExtensionRegistry()
+ .getConfigurationElementsFor(analyzerContribution.getAttribute("extensionId"))) {
+ if (store.contains(contribution.getAttribute("id"))
+ && !store.getBoolean(contribution.getAttribute("id"))) {
+ excludedRules.add(contribution.getAttribute("id"));
+ }
+ }
+ } else if (analysisMetrics.contains(analyzerContribution.getAttribute("extensionId"))) {
+ for (IConfigurationElement contribution : Platform.getExtensionRegistry()
+ .getConfigurationElementsFor(analyzerContribution.getAttribute("extensionId"))) {
+ if (store.contains(contribution.getAttribute("id"))
+ && !store.getBoolean(contribution.getAttribute("id"))) {
+ excludedMetrics.add(contribution.getAttribute("id"));
+ }
+ }
+ }
+ }
+
+ /*
+ * 3. Identification of the selected files
+ */
+ List files = new ArrayList<>();
+ Iterator selectionIterator = HandlerUtil.getCurrentStructuredSelection(event).iterator();
+ while (selectionIterator.hasNext()) {
+ Object selection = selectionIterator.next();
+ try {
+ files.addAll(this.findFiles(selection));
+ } catch (CoreException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ }
+
+ /*
+ * 3. Creation of jobs to run analysis.
+ */
+ RuleAnalysisJob rulesJob = new RuleAnalysisJob("Applying rules...", files, analysisRules,
+ excludedRules);
+ rulesJob.addJobChangeListener(new JobChangeAdapter() {
+
+ @Override
+ public void done(final IJobChangeEvent event) {
+ Display.getDefault().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ if (rulesJob.getResult().isOK()) {
+ AnalysisHandler
+ .updateViolationView(((RuleAnalysisJob) event.getJob()).getViolations());
+ }
+ }
+
+ });
+ }
+ });
+ rulesJob.setUser(true);
+
+ MetricAnalysisJob metricsJob = new MetricAnalysisJob("Computing metrics...", files,
+ analysisMetrics, excludedMetrics);
+ metricsJob.addJobChangeListener(new JobChangeAdapter() {
+ @Override
+ public void done(final IJobChangeEvent event) {
+ Display.getDefault().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ if (metricsJob.getResult().isOK()) {
+ AnalysisHandler.updateMetricsView(((MetricAnalysisJob) event.getJob()).getMetrics());
+ }
+ }
+
+ });
+ }
+ });
+ metricsJob.setUser(true);
+ JobGroup group = new JobGroup("i-Code CNES Analysis.", 2, 2);
+ rulesJob.setJobGroup(group);
+ metricsJob.setJobGroup(group);
+
+ metricsJob.schedule();
+ rulesJob.schedule();
+ return null;
+ }
+
+ /**
+ * This method can be used to find different File element of a selection.
+ *
+ *
+ * Warning : this method is recursive
+ *
+ *
+ * @param selection
+ * The selection to search for files
+ * @return a list of file included in the selection
+ * @throws CoreException
+ * when resources of a {@link IProject} or {@link IFolder} couldn't be reached
+ */
+ private List findFiles(Object selection) throws CoreException {
+ List files = new ArrayList<>();
+ if (selection instanceof IProject) {
+ for (Object resource : ((IProject) selection).members()) {
+ files.addAll(this.findFiles(resource));
+ }
+ } else if (selection instanceof IFolder) {
+ for (Object resource : ((IFolder) selection).members()) {
+ files.addAll(this.findFiles(resource));
+ }
+ } else if (selection instanceof IFile) {
+ files.add(((IFile) selection).getLocation().toFile().getAbsoluteFile());
+ }
+ return files;
+ }
+
+ /**
+ * Update the violation's view
+ *
+ * @param violations
+ * .
+ */
+ protected static void updateViolationView(final List violations) {
+ LOGGER.finest("Begin updateView method");
+
+ try {
+ // get the page
+ final IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
+ .getActivePage();
+
+ // open view
+ page.showView(ViolationsView.VIEW_ID);
+
+ // get view
+ final ViolationsView view = (ViolationsView) page.findView(ViolationsView.VIEW_ID);
+
+ // show rules analyze results
+ if (view != null) {
+ view.display(violations);
+ }
+
+ } catch (final PartInitException exception) {
+ LOGGER.log(Level.FINER, exception.getClass() + " : " + exception.getMessage(), exception);
+ showError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Internal Error",
+ "Contact support service : \n" + exception.getMessage());
+ }
+
+ LOGGER.finest("End updateView method");
+ }
+
+ private static void updateMetricsView(final List values) {
+ LOGGER.finest("Begin updateView method");
+
+ try {
+ // get the page
+ final IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
+ .getActivePage();
+
+ // open view
+ page.showView(MetricsView.VIEW_ID);
+
+ // get view
+ final MetricsView view = (MetricsView) page.findView(MetricsView.VIEW_ID);
+
+ // show rules analyze results
+ if (view != null) {
+ view.display(values);
+ /* Add IMarkers everywhere there is a metric event */
+ view.insertMarkers();
+ }
+
+ } catch (final PartInitException exception) {
+ LOGGER.log(Level.FINER, exception.getClass() + " : " + exception.getMessage(), exception);
+ showError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Internal Error",
+ "Contact support service : \n" + exception.getMessage());
+ } catch (final EmptyProviderException exception) {
+ LOGGER.log(Level.FINER, exception.getClass() + " : " + exception.getMessage(), exception);
+ showError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Internal Error",
+ "Contact support service : \n" + exception.getMessage());
+ }
+
+ LOGGER.finest("End updateView method");
+ }
+
+}
diff --git a/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/MetricAnalysisAllHandler.java b/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/MetricAnalysisAllHandler.java
deleted file mode 100755
index 37d50240..00000000
--- a/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/MetricAnalysisAllHandler.java
+++ /dev/null
@@ -1,234 +0,0 @@
-/************************************************************************************************/
-/* i-Code CNES is a static code analyzer. */
-/* This software is a free software, under the terms of the Eclipse Public License version 1.0. */
-/* http://www.eclipse.org/legal/epl-v10.html */
-/************************************************************************************************/
-package fr.cnes.analysis.tools.ui.handler;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IExtensionRegistry;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-import fr.cnes.analysis.tools.analyzer.exception.NullContributionException;
-import fr.cnes.analysis.tools.ui.exception.EmptyResourceException;
-import fr.cnes.analysis.tools.ui.exception.EmptySelectionException;
-import fr.cnes.analysis.tools.ui.exception.InvalidResourceTypeException;
-import fr.cnes.analysis.tools.ui.exception.NonAccessibleResourceException;
-import fr.cnes.analysis.tools.ui.exception.UnknownResourceTypeException;
-import fr.cnes.analysis.tools.ui.utils.AnalysisHandlerUIUtils;
-import fr.cnes.analysis.tools.ui.utils.PreferencesUIUtils;
-
-/**
- * Metric Handler.
- *
- */
-public class MetricAnalysisAllHandler extends UIAndCommandAbstractHandler {
- /** Logger. **/
- private static final Logger LOGGER = Logger.getLogger(AbstractAnalysisHandler.class.getName());
-
- /** Selection into the package explorer. */
- private IStructuredSelection selection;
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.
- * ExecutionEvent)
- */
- @Override
- public Object execute(ExecutionEvent event) throws ExecutionException {
- try {
- LOGGER.finest("Begin execute method");
-
- // retrieve the active selection in the package explorer
- final IStructuredSelection selection = HandlerUtil.getCurrentStructuredSelection(event);
-
- // check selection
- AnalysisHandlerUIUtils.checkSelection(selection);
-
- final IExtensionRegistry registry = Platform.getExtensionRegistry();
- final IConfigurationElement[] configurationElem = registry
- .getConfigurationElementsFor("org.eclipse.ui.handlers");
-
- if (configurationElem != null) {
- for (int i = 0; i < configurationElem.length; i++) {
- // local variables to save extensionId and fileExtenion
- String extId = "";
- final List fileExt = new ArrayList();
- // plugin.xml navigation
- final String command = configurationElem[i].getAttribute("commandId");
- if (command.contains("fr.cnes.analysis.tools.") && command.contains("metric")) {
- // depend on the handler -> execute the rules or metrics
- // get file extensions and extensions id
- final IConfigurationElement[] classAttr = configurationElem[i]
- .getChildren("class");
- for (int j = 0; j < classAttr.length; j++) {
- final IConfigurationElement[] param = classAttr[j]
- .getChildren("parameter");
- for (int z = 0; z < param.length; z++) {
- final String name = param[z].getAttribute("name");
- if ("extensionId".equals(name)) {
- extId = param[z].getAttribute("value");
- } else if (name.contains("fileExtension")) {
- fileExt.add(param[z].getAttribute("value"));
- }
- }
- }
- // execution
- final String[] extensions = new String[fileExt.size()];
- fileExt.toArray(extensions);
- try {
- runMetric(selection, extensions, extId);
- } catch (EmptyResourceException | UnknownResourceTypeException
- | InvalidResourceTypeException
- | EmptySelectionException exception) {
- LOGGER.log(Level.FINER,
- exception.getClass() + " : " + exception.getMessage(),
- exception);
- }
- }
- }
- LOGGER.finest("End execute method");
- }
- } catch (NonAccessibleResourceException exception) {
- LOGGER.log(Level.FINER, exception.getClass() + " : " + exception.getMessage(),
- exception);
- showWarning(
- HandlerUtil.getActiveShell(event),
- "The resource is not accessible", exception.getMessage());
- } catch (CoreException exception) {
- LOGGER.log(Level.FINER, exception.getClass() + " : " + exception.getMessage(),
- exception);
- showWarning(
- HandlerUtil.getActiveShell(event),
- "Core exception", exception.getMessage());
- } catch (NullContributionException exception) {
- LOGGER.log(Level.FINER, exception.getClass() + " : " + exception.getMessage(),
- exception);
- showWarning(
- HandlerUtil.getActiveShell(event),
- "Contribution is null", exception.getMessage());
- } catch (EmptySelectionException exception) {
- LOGGER.log(Level.FINER, exception.getClass() + " : " + exception.getMessage(),
- exception);
- showWarning(
- HandlerUtil.getActiveShell(event),
- "Selection is empty", exception.getMessage());
- }
- return null;
- }
-
- /**
- * Execute the analyzer on metrics over the list of files
- *
- * @param selection
- * files to execute the analysis
- * @param fileExtension
- * list of extensions depend on the language
- * @param analyzerID
- * identifier of the analysis language
- *
- * @throws EmptyResourceException
- * Resource is empty
- * @throws UnknownResourceTypeException
- * Resource is unknown
- * @throws InvalidResourceTypeException
- * Resource type is invalid
- * @throws NonAccessibleResourceException
- * Resource is not accessible
- * @throws EmptySelectionException
- * Selection is empty
- * @throws CoreException
- * Internal error
- * @throws NullContributionException
- * Contribution is null
- */
- private void runMetric(IStructuredSelection selection, String[] fileExtension,
- String analyzerID) throws EmptyResourceException, UnknownResourceTypeException,
- InvalidResourceTypeException, NonAccessibleResourceException,
- EmptySelectionException, CoreException, NullContributionException {
-
- final boolean analyserActivated = isAnalyzerActivated(analyzerID);
-
- if (analyserActivated) {
- // retrieve the file(s) of the selected language
- final List files = AnalysisHandlerUIUtils.retrieveFiles(selection,
- fileExtension);
-
- // run the analysis on the retrieved files
- final MetricAnalysisHandler metricAnalyzer = new MetricAnalysisHandler();
-
- metricAnalyzer.setAnalyzerId(analyzerID);
- metricAnalyzer.runAnalysis(files, analyzerID);
- }
-
- }
-
- /**
- * Check if the analyzer is activated in the preferences.
- *
- * @param analyzerID
- * analyzer id.
- * @return true if the analyzer is activated and false otherwise.
- */
- private boolean isAnalyzerActivated(String analyzerID) {
- final IPreferenceStore store = PlatformUI.getPreferenceStore();
- boolean analyserActivated = false;
- final String sh = "shell";
- final String f77 = "fortran77";
- final String f90 = "fortran90";
-
- final IConfigurationElement[] contributions = Platform.getExtensionRegistry()
- .getConfigurationElementsFor(PreferencesUIUtils.PREF_EXT_PT_ID);
- String contributionId = "";
- for (final IConfigurationElement contribution : contributions) {
- contributionId = contribution.getAttribute(PreferencesUIUtils.CONTRIB_ID);
- if (analyzerID.contains(f90) && contributionId.contains(f90)) {
- analyserActivated = store
- .getBoolean(contribution.getAttribute(PreferencesUIUtils.PARENT_ID))
- && store.getBoolean(
- contribution.getAttribute(PreferencesUIUtils.METRIC_PAGE_ID));
- } else if (analyzerID.contains(f77) && contributionId.contains(f77)) {
- analyserActivated = store
- .getBoolean(contribution.getAttribute(PreferencesUIUtils.PARENT_ID))
- && store.getBoolean(
- contribution.getAttribute(PreferencesUIUtils.METRIC_PAGE_ID));
- } else if (analyzerID.contains(sh) && contributionId.contains(sh)) {
- analyserActivated = store
- .getBoolean(contribution.getAttribute(PreferencesUIUtils.PARENT_ID))
- && store.getBoolean(
- contribution.getAttribute(PreferencesUIUtils.METRIC_PAGE_ID));
- }
- }
- return analyserActivated;
- }
-
- /**
- * @return the selection
- */
- public IStructuredSelection getSelection() {
- return selection;
- }
-
- /**
- * @param pSelection
- * the selection to set
- */
- public void setSelection(IStructuredSelection pSelection) {
- this.selection = pSelection;
- }
-}
diff --git a/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/MetricAnalysisHandler.java b/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/MetricAnalysisHandler.java
deleted file mode 100755
index d29cf96e..00000000
--- a/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/MetricAnalysisHandler.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/************************************************************************************************/
-/* i-Code CNES is a static code analyzer. */
-/* This software is a free software, under the terms of the Eclipse Public License version 1.0. */
-/* http://www.eclipse.org/legal/epl-v10.html */
-/************************************************************************************************/
-package fr.cnes.analysis.tools.ui.handler;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.jobs.IJobChangeEvent;
-import org.eclipse.core.runtime.jobs.JobChangeAdapter;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PartInitException;
-
-import fr.cnes.analysis.tools.analyzer.MetricAnalysisJob;
-import fr.cnes.analysis.tools.analyzer.datas.FileValue;
-import fr.cnes.analysis.tools.ui.exception.EmptyProviderException;
-import fr.cnes.analysis.tools.ui.view.MetricsView;
-
-/**
- * This class is the Handler that linked together action button on the menu and
- * analyze function located
- */
-public class MetricAnalysisHandler extends AbstractAnalysisHandler {
- /** Logger. **/
- private static final Logger LOGGER = Logger.getLogger(MetricAnalysisHandler.class.getName());
-
- /**
- * List of analyzed files
- */
- private final List analyzedFiles = new ArrayList();
-
- public MetricAnalysisHandler() {
- this(null);
- }
-
-
- public MetricAnalysisHandler(IPlatformUIProvider p) {
- super(p);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * fr.cnes.analysis.tools.ui.handler.AbstractAnalysisHandler#runAnalysis
- * (java.util.List, java.lang.String)
- */
- @Override
- public void runAnalysis(final List files, final String pAnalyzerID) {
- LOGGER.finest("Begin runAnalysis method");
-
- // Clear the analyzedFiles list in order to have the new analyzed files
- analyzedFiles.clear();
- List analysisFiles = new ArrayList<>();
- for(IPath file : files){
- analysisFiles.add(file.toFile());
- }
- // Instantiate analyzer
- final MetricAnalysisJob analysis = new MetricAnalysisJob(pAnalyzerID, analysisFiles);
-
- // run analysis
- analysis.setUser(true);
- analysis.schedule();
-
- // add change listener to check when the job is done
- analysis.addJobChangeListener(new JobChangeAdapter() {
-
- @Override
- public void done(final IJobChangeEvent event) {
- Display.getDefault().asyncExec(new Runnable() {
-
- @Override
- public void run() {
- // We generate an XML file only if the analysis wasn't
- // interrupted
- if (analysis.getResult().isOK()) {
- MetricAnalysisHandler.this.updateView(analysis.getValues());
- }
- }
- });
- }
- });
-
- LOGGER.finest("End runAnalysis method");
- }
-
- /**
- * Update the view
- *
- * @param values
- * list of file value .
- */
- private void updateView(final List values) {
- LOGGER.finest("Begin updateView method");
-
- try {
- // get the page
- final IWorkbenchPage page = getPlatformUIProvider().getWorkbench().getActiveWorkbenchWindow()
- .getActivePage();
-
- // open view
- page.showView(MetricsView.VIEW_ID);
-
- // get view
- final MetricsView view = (MetricsView) page.findView(MetricsView.VIEW_ID);
-
- // show rules analyze results
- if (view != null) {
- view.display(values, this.getSelectedProject(), this.getAuthor(), this.getDate());
- /* Add IMarkers everywhere there is a metric event */
- view.insertMarkers();
- }
-
- } catch (final PartInitException exception) {
- LOGGER.log(Level.FINER, exception.getClass() + " : " + exception.getMessage(), exception);
- showError(getPlatformUIProvider().getWorkbench().getActiveWorkbenchWindow().getShell(),
- "Internal Error", "Contact support service : \n" + exception.getMessage());
- } catch (final EmptyProviderException exception) {
- LOGGER.log(Level.FINER, exception.getClass() + " : " + exception.getMessage(), exception);
- showError(getPlatformUIProvider().getWorkbench().getActiveWorkbenchWindow().getShell(),
- "Internal Error", "Contact support service : \n" + exception.getMessage());
- }
-
- LOGGER.finest("End updateView method");
- }
-
-
-
-
-}
diff --git a/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/MetricAnalysisJob.java b/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/MetricAnalysisJob.java
new file mode 100644
index 00000000..53b1b81c
--- /dev/null
+++ b/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/MetricAnalysisJob.java
@@ -0,0 +1,79 @@
+package fr.cnes.analysis.tools.ui.handler;
+
+import fr.cnes.analysis.tools.analyzer.Analyzer;
+import fr.cnes.analysis.tools.analyzer.datas.FileValue;
+import java.io.File;
+import java.util.List;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.core.runtime.jobs.Job;
+
+public class MetricAnalysisJob extends Job {
+ private Analyzer analyzer;
+ private List files;
+ private List languageIds;
+ private List excludedIds;
+ private List metrics;
+
+ public MetricAnalysisJob(String name, List files, List languageIds,
+ List excludedIds) {
+ super(name);
+ this.files = files;
+ this.languageIds = languageIds;
+ this.excludedIds = excludedIds;
+ this.analyzer = new Analyzer();
+ }
+
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ IStatus status = Status.OK_STATUS;
+ try {
+ this.metrics = analyzer.computeMetrics(files, languageIds, excludedIds);
+ } catch (Exception exception) {
+ new Status(Status.ERROR, "fr.cnes.analysis.tools.analyzer", exception.getMessage());
+ }
+ return status;
+ }
+
+ public Analyzer getAnalyzer() {
+ return analyzer;
+ }
+
+ public void setAnalyzer(Analyzer analyzer) {
+ this.analyzer = analyzer;
+ }
+
+ public List getFiles() {
+ return files;
+ }
+
+ public void setFiles(List files) {
+ this.files = files;
+ }
+
+ public List getLanguageIds() {
+ return languageIds;
+ }
+
+ public void setLanguageIds(List languageIds) {
+ this.languageIds = languageIds;
+ }
+
+ public List getExcludedIds() {
+ return excludedIds;
+ }
+
+ public void setExcludedIds(List excludedIds) {
+ this.excludedIds = excludedIds;
+ }
+
+ public List getMetrics() {
+ return metrics;
+ }
+
+ public void setFileValue(List metrics) {
+ this.metrics = metrics;
+ }
+
+}
diff --git a/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/MetricAndRulesAnalysisAllHandler.java b/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/MetricAndRulesAnalysisAllHandler.java
deleted file mode 100755
index 919be550..00000000
--- a/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/MetricAndRulesAnalysisAllHandler.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/************************************************************************************************/
-/* i-Code CNES is a static code analyzer. */
-/* This software is a free software, under the terms of the Eclipse Public License version 1.0. */
-/* http://www.eclipse.org/legal/epl-v10.html */
-/************************************************************************************************/
-package fr.cnes.analysis.tools.ui.handler;
-
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-import fr.cnes.analysis.tools.ui.exception.EmptySelectionException;
-import fr.cnes.analysis.tools.ui.utils.AnalysisHandlerUIUtils;
-
-/**
- * Handler to manage both run Metrics and Rules.
- *
- */
-public class MetricAndRulesAnalysisAllHandler extends AbstractHandler {
- /** Logger. **/
- private static final Logger LOGGER = Logger
- .getLogger(MetricAndRulesAnalysisAllHandler.class.getName());
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.
- * ExecutionEvent)
- */
- @Override
- public Object execute(final ExecutionEvent event) throws ExecutionException {
- try {
- // retrieve the active selection in the package explorer
- final IStructuredSelection selection = HandlerUtil.getCurrentStructuredSelection(event);
-
- // check selection
- AnalysisHandlerUIUtils.checkSelection(selection);
-
- // Run rules
- final RuleAnalysisAllHandler ruleAnalysis = new RuleAnalysisAllHandler();
- ruleAnalysis.setSelection(selection);
- ruleAnalysis.execute(event);
-
- // Run metrics
- final MetricAnalysisAllHandler metricAnalysis = new MetricAnalysisAllHandler();
- ruleAnalysis.setSelection(selection);
- metricAnalysis.execute(event);
-
- } catch (EmptySelectionException exception) {
- LOGGER.log(Level.FINER, exception.getClass() + " : " + exception.getMessage(),
- exception);
- MessageDialog.openWarning(
- HandlerUtil.getActiveShell(event),
- "Selection is empty", exception.getMessage());
- }
- return null;
- }
-
-}
diff --git a/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/RuleAnalysisAllHandler.java b/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/RuleAnalysisAllHandler.java
deleted file mode 100755
index 895b6d28..00000000
--- a/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/RuleAnalysisAllHandler.java
+++ /dev/null
@@ -1,230 +0,0 @@
-/************************************************************************************************/
-/* i-Code CNES is a static code analyzer. */
-/* This software is a free software, under the terms of the Eclipse Public License version 1.0. */
-/* http://www.eclipse.org/legal/epl-v10.html */
-/************************************************************************************************/
-package fr.cnes.analysis.tools.ui.handler;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IExtensionRegistry;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-import fr.cnes.analysis.tools.analyzer.exception.NullContributionException;
-import fr.cnes.analysis.tools.ui.exception.EmptyResourceException;
-import fr.cnes.analysis.tools.ui.exception.EmptySelectionException;
-import fr.cnes.analysis.tools.ui.exception.InvalidResourceTypeException;
-import fr.cnes.analysis.tools.ui.exception.NonAccessibleResourceException;
-import fr.cnes.analysis.tools.ui.exception.UnknownResourceTypeException;
-import fr.cnes.analysis.tools.ui.utils.AnalysisHandlerUIUtils;
-import fr.cnes.analysis.tools.ui.utils.PreferencesUIUtils;
-
-/**
- * Handler to manage the rule analysis.
- *
- */
-public class RuleAnalysisAllHandler extends AbstractHandler {
- /** Logger. **/
- private static final Logger LOGGER = Logger.getLogger(AbstractAnalysisHandler.class.getName());
-
- /** Selection into the package explorer. */
- private IStructuredSelection selection;
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.
- * ExecutionEvent)
- */
- @Override
- public Object execute(ExecutionEvent event) throws ExecutionException {
- try {
- LOGGER.finest("Begin execute method");
-
- final IExtensionRegistry registry = Platform.getExtensionRegistry();
- final IConfigurationElement[] configurationElem = registry
- .getConfigurationElementsFor("org.eclipse.ui.handlers");
-
- if (configurationElem != null) {
- // local variables to save extensionId and
- // fileExtenion
- String extId = "";
- final List fileExt = new ArrayList();
- String[] extensions = new String[fileExt.size()];
- for (int i = 0; i < configurationElem.length; i++) {
- extId = "";
- fileExt.clear();
- // plugin.xml navigation
- final String command = configurationElem[i].getAttribute("commandId");
- if (command.contains("fr.cnes.analysis.tools.") && command.contains("rule")) {
- // depend on the handler -> execute the
- // rules or metrics
- // get file extensions and extensions id
- final IConfigurationElement[] classAttr = configurationElem[i]
- .getChildren("class");
- for (int j = 0; j < classAttr.length; j++) {
- final IConfigurationElement[] param = classAttr[j]
- .getChildren("parameter");
- for (int z = 0; z < param.length; z++) {
- final String name = param[z].getAttribute("name");
- if ("extensionId".equals(name)) {
- extId = param[z].getAttribute("value");
- } else if (name.contains("fileExtension")) {
- fileExt.add(param[z].getAttribute("value"));
- }
- }
- }
- // execution
- extensions = new String[fileExt.size()];
- fileExt.toArray(extensions);
- try {
- runRule(selection, extensions, extId);
- } catch (EmptyResourceException | UnknownResourceTypeException
- | InvalidResourceTypeException
- | EmptySelectionException exception) {
- LOGGER.log(Level.FINER,
- exception.getClass() + " : " + exception.getMessage(),
- exception);
- }
- }
- }
- LOGGER.finest("End execute method");
- }
- } catch (NonAccessibleResourceException exception) {
- LOGGER.log(Level.FINER, exception.getClass() + " : " + exception.getMessage(),
- exception);
- MessageDialog.openWarning(
- HandlerUtil.getActiveShell(event),
- "The resource is not accessible", exception.getMessage());
- } catch (CoreException exception) {
- LOGGER.log(Level.FINER, exception.getClass() + " : " + exception.getMessage(),
- exception);
- MessageDialog.openWarning(
- HandlerUtil.getActiveShell(event),
- "Core exception", exception.getMessage());
- } catch (NullContributionException exception) {
- LOGGER.log(Level.FINER, exception.getClass() + " : " + exception.getMessage(),
- exception);
- MessageDialog.openWarning(
- HandlerUtil.getActiveShell(event),
- "Contribution is null", exception.getMessage());
- }
- return null;
- }
-
- /**
- * Execute the analyzer on rules over the list of files
- *
- * @param selection
- * files to execute the analysis
- * @param fileExtension
- * list of extensions depend on the language
- * @param analyzerID
- * identifier of the analysis language
- *
- * @throws EmptyResourceException
- * Resource is empty
- * @throws UnknownResourceTypeException
- * Resource is unknown
- * @throws InvalidResourceTypeException
- * Resource type is invalid
- * @throws NonAccessibleResourceException
- * Resource is not accessible
- * @throws EmptySelectionException
- * Selection is empty
- * @throws CoreException
- * Internal error
- * @throws NullContributionException
- * Contribution is null
- */
- private void runRule(final IStructuredSelection selection, final String[] fileExtension,
- final String analyzerID) throws EmptyResourceException, UnknownResourceTypeException,
- InvalidResourceTypeException, NonAccessibleResourceException,
- EmptySelectionException, CoreException, NullContributionException {
-
- final boolean analyserActivated = isAnalyzerActivated(analyzerID);
-
- if (analyserActivated) {
- // retrieve the file(s) of the selected language
- final List files = AnalysisHandlerUIUtils.retrieveFiles(selection,
- fileExtension);
-
- // run the analysis on the retrieved files
- final RuleAnalysisHandler ruleAnalyzer = new RuleAnalysisHandler();
-
- ruleAnalyzer.setAnalyzerId(analyzerID);
- ruleAnalyzer.runAnalysis(files, analyzerID);
- }
-
- }
-
- /**
- * Check if the analyzer is activated in the preferences.
- *
- * @param analyzerID
- * analyzer id.
- * @return true if the analyzer is activated and false otherwise.
- */
- private boolean isAnalyzerActivated(final String analyzerID) {
- final IPreferenceStore store = PlatformUI.getPreferenceStore();
- boolean analyserActivated = false;
- final String shell = "shell";
- final String f77 = "fortran77";
- final String f90 = "fortran90";
-
- final IConfigurationElement[] contributions = Platform.getExtensionRegistry()
- .getConfigurationElementsFor(PreferencesUIUtils.PREF_EXT_PT_ID);
- String contributionId = "";
- for (final IConfigurationElement contribution : contributions) {
- contributionId = contribution.getAttribute(PreferencesUIUtils.CONTRIB_ID);
- if (analyzerID.contains(f90) && contributionId.contains(f90)) {
- analyserActivated = store
- .getBoolean(contribution.getAttribute(PreferencesUIUtils.PARENT_ID))
- && store.getBoolean(
- contribution.getAttribute(PreferencesUIUtils.RULE_PAGE_ID));
- } else if (analyzerID.contains(f77) && contributionId.contains(f77)) {
- analyserActivated = store
- .getBoolean(contribution.getAttribute(PreferencesUIUtils.PARENT_ID))
- && store.getBoolean(
- contribution.getAttribute(PreferencesUIUtils.RULE_PAGE_ID));
- } else if (analyzerID.contains(shell) && contributionId.contains(shell)) {
- analyserActivated = store
- .getBoolean(contribution.getAttribute(PreferencesUIUtils.PARENT_ID))
- && store.getBoolean(
- contribution.getAttribute(PreferencesUIUtils.RULE_PAGE_ID));
- }
- }
- return analyserActivated;
- }
-
- /**
- * @return the selection
- */
- public IStructuredSelection getSelection() {
- return selection;
- }
-
- /**
- * @param pSelection
- * the selection to set
- */
- public void setSelection(IStructuredSelection pSelection) {
- this.selection = pSelection;
- }
-
-}
diff --git a/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/RuleAnalysisHandler.java b/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/RuleAnalysisHandler.java
deleted file mode 100755
index 0d3582a3..00000000
--- a/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/RuleAnalysisHandler.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/************************************************************************************************/
-/* i-Code CNES is a static code analyzer. */
-/* This software is a free software, under the terms of the Eclipse Public License version 1.0. */
-/* http://www.eclipse.org/legal/epl-v10.html */
-/************************************************************************************************/
-package fr.cnes.analysis.tools.ui.handler;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.jobs.IJobChangeEvent;
-import org.eclipse.core.runtime.jobs.JobChangeAdapter;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-
-import fr.cnes.analysis.tools.analyzer.AbstractAnalysisJob;
-import fr.cnes.analysis.tools.analyzer.RuleAnalysisJob;
-import fr.cnes.analysis.tools.analyzer.datas.Violation;
-import fr.cnes.analysis.tools.ui.view.ViolationsView;
-
-/**
- * This class is the Handler that linked together action button on the menu and
- * analyze function located
- *
- */
-public class RuleAnalysisHandler extends AbstractAnalysisHandler {
- /**
- * Logger
- */
- private static final Logger LOGGER = Logger.getLogger(RuleAnalysisHandler.class.getName());
-
- /**
- * List of all files that will be analyzed
- */
- private List analyzedFiles = new ArrayList();
-
- public RuleAnalysisHandler() {
- this(null);
- }
-
- public RuleAnalysisHandler(IPlatformUIProvider p) {
- super(p);
- }
-
- /**
- * Run the analysis on the retrieved files.
- *
- * @param files
- * the files to analyze
- * @param pAnalyzerID
- * the id of analyzer on which the analysis is made
- */
- @Override
- public void runAnalysis(final List files, final String pAnalyzerID) {
-
- LOGGER.finest("Begin runAnalysis method");
-
- // Clear the analyzedFiles list in order to have the new analyzed files
- analyzedFiles.clear();
-
- // Instantiate analyzer
- List analysisFiles = new ArrayList<>();
- for(IPath file : files){
- analysisFiles.add(file.toFile());
- }
- final AbstractAnalysisJob analysis = new RuleAnalysisJob(pAnalyzerID, analysisFiles);
-
- // run analysis
- analysis.setUser(true);
- analysis.schedule();
-
- // add change listener to check when the job is done
- analysis.addJobChangeListener(new JobChangeAdapter() {
-
- @Override
- public void done(final IJobChangeEvent event) {
- Display.getDefault().asyncExec(new Runnable() {
-
- @Override
-
- public void run() {
- if (analysis.getResult().isOK()) {
- RuleAnalysisHandler.this
- .updateView(((RuleAnalysisJob) event.getJob()).getViolations());
- }
- }
-
- });
- }
- });
-
- LOGGER.finest("End runAnalysis method");
- }
-
- /**
- * Update the violation's view
- *
- * @param violations
- * .
- */
- protected void updateView(final List violations) {
- LOGGER.finest("Begin updateView method");
-
- try {
- // get the page
- final IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
- .getActivePage();
-
- // open view
- page.showView(ViolationsView.VIEW_ID);
-
- // get view
- final ViolationsView view = (ViolationsView) page.findView(ViolationsView.VIEW_ID);
-
- // show rules analyze results
- if (view != null) {
- view.display(violations, this.getSelectedProject(), this.getAuthor(),
- this.getDate());
- }
-
- } catch (final PartInitException exception) {
- LOGGER.log(Level.FINER, exception.getClass() + " : " + exception.getMessage(),
- exception);
- showError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
- "Internal Error", "Contact support service : \n" + exception.getMessage());
- }
-
- LOGGER.finest("End updateView method");
- }
-
-}
diff --git a/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/RuleAnalysisJob.java b/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/RuleAnalysisJob.java
new file mode 100644
index 00000000..0596b900
--- /dev/null
+++ b/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/RuleAnalysisJob.java
@@ -0,0 +1,82 @@
+package fr.cnes.analysis.tools.ui.handler;
+
+import fr.cnes.analysis.tools.analyzer.Analyzer;
+import fr.cnes.analysis.tools.analyzer.datas.Violation;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.util.List;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.core.runtime.jobs.Job;
+
+public class RuleAnalysisJob extends Job {
+ private Analyzer analyzer;
+ private List files;
+ private List languageIds;
+ private List excludedIds;
+ private List violations;
+
+ public RuleAnalysisJob(String name, List files, List languageIds,
+ List excludedIds) {
+ super(name);
+ this.files = files;
+ this.languageIds = languageIds;
+ this.excludedIds = excludedIds;
+ this.analyzer = new Analyzer();
+ }
+
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ IStatus status = Status.OK_STATUS;
+ try {
+ this.violations = analyzer.applyRules(files, languageIds, excludedIds);
+ } catch (FileNotFoundException exception) {
+ new Status(Status.ERROR, "fr.cnes.analysis.tools.analyzer", exception.getMessage());
+ } catch (Exception exception) {
+ new Status(Status.ERROR, "fr.cnes.analysis.tools.analyzer", exception.getMessage());
+ }
+ return status;
+ }
+
+ public Analyzer getAnalyzer() {
+ return analyzer;
+ }
+
+ public void setAnalyzer(Analyzer analyzer) {
+ this.analyzer = analyzer;
+ }
+
+ public List getFiles() {
+ return files;
+ }
+
+ public void setFiles(List files) {
+ this.files = files;
+ }
+
+ public List getLanguageIds() {
+ return languageIds;
+ }
+
+ public void setLanguageIds(List languageIds) {
+ this.languageIds = languageIds;
+ }
+
+ public List getExcludedIds() {
+ return excludedIds;
+ }
+
+ public void setExcludedIds(List excludedIds) {
+ this.excludedIds = excludedIds;
+ }
+
+ public List getViolations() {
+ return violations;
+ }
+
+ public void setViolations(List violations) {
+ this.violations = violations;
+ }
+
+}
diff --git a/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/UIAndCommandAbstractHandler.java b/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/UIAndCommandAbstractHandler.java
index ec2dedad..4d590668 100644
--- a/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/UIAndCommandAbstractHandler.java
+++ b/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/handler/UIAndCommandAbstractHandler.java
@@ -5,35 +5,33 @@
import org.eclipse.swt.widgets.Shell;
/**
- * This class is provided to manage both handler usage in UI or in a command
- * mode In command mode, it is not possible to display dialogs (no workbench
- * available) It provides warning and error methods available for all handlers
- * This class should be used as base class for all handlers
+ * This class is provided to manage both handler usage in UI or in a command mode In command mode,
+ * it is not possible to display dialogs (no workbench available) It provides warning and error
+ * methods available for all handlers This class should be used as base class for all handlers
*
* @author olivier
*
*/
public abstract class UIAndCommandAbstractHandler extends AbstractHandler {
- protected void showWarning(Shell s, String title, String message) {
- if (s != null) { // IN UI Mode
- MessageDialog.openWarning(s, title, message);
- } else {
- // In command mode -> no dialogs available
- System.out.println("WARN : " + title + " : " + message);
- }
+ protected void showWarning(Shell s, String title, String message) {
+ if (s != null) { // IN UI Mode
+ MessageDialog.openWarning(s, title, message);
+ } else {
+ // In command mode -> no dialogs available
+ System.out.println("WARN : " + title + " : " + message);
+ }
- }
-
- protected void showError(Shell s, String title, String message) {
- if (s != null) { // IN UI Mode
- MessageDialog.openWarning(s, title, message);
- } else {
- // In command mode -> no dialogs available
- System.out.println("ERROR : " + title + " : " + message);
- }
+ }
- }
+ protected static void showError(Shell s, String title, String message) {
+ if (s != null) { // IN UI Mode
+ MessageDialog.openWarning(s, title, message);
+ } else {
+ // In command mode -> no dialogs available
+ System.out.println("ERROR : " + title + " : " + message);
+ }
+ }
}
diff --git a/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/view/MetricsView.java b/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/view/MetricsView.java
index 8eb9a687..2035f15b 100755
--- a/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/view/MetricsView.java
+++ b/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/view/MetricsView.java
@@ -1,10 +1,21 @@
/************************************************************************************************/
-/* i-Code CNES is a static code analyzer. */
+/* i-Code CNES is a static code analyzer. */
/* This software is a free software, under the terms of the Eclipse Public License version 1.0. */
-/* http://www.eclipse.org/legal/epl-v10.html */
+/* http://www.eclipse.org/legal/epl-v10.html */
/************************************************************************************************/
package fr.cnes.analysis.tools.ui.view;
+import fr.cnes.analysis.tools.analyzer.datas.FileValue;
+import fr.cnes.analysis.tools.analyzer.datas.FunctionValue;
+import fr.cnes.analysis.tools.ui.exception.EmptyProviderException;
+import fr.cnes.analysis.tools.ui.markers.ViolationErrorMarker;
+import fr.cnes.analysis.tools.ui.utils.PreferencesUIUtils;
+import fr.cnes.analysis.tools.ui.view.metrics.FileMetricDescriptor;
+import fr.cnes.analysis.tools.ui.view.metrics.FunctionMetricDescriptor;
+import fr.cnes.analysis.tools.ui.view.metrics.IMetricDescriptor;
+import fr.cnes.analysis.tools.ui.view.metrics.MetricContentProvider;
+import fr.cnes.analysis.tools.ui.view.metrics.MetricDescriptor;
+import fr.cnes.analysis.tools.ui.view.metrics.MetricLabelProvider;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@@ -17,13 +28,11 @@
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
-
import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
-
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
@@ -48,18 +57,6 @@
import org.jdom2.output.XMLOutputter;
import org.xml.sax.SAXException;
-import fr.cnes.analysis.tools.analyzer.datas.FileValue;
-import fr.cnes.analysis.tools.analyzer.datas.FunctionValue;
-import fr.cnes.analysis.tools.ui.exception.EmptyProviderException;
-import fr.cnes.analysis.tools.ui.markers.ViolationErrorMarker;
-import fr.cnes.analysis.tools.ui.utils.PreferencesUIUtils;
-import fr.cnes.analysis.tools.ui.view.metrics.FileMetricDescriptor;
-import fr.cnes.analysis.tools.ui.view.metrics.FunctionMetricDescriptor;
-import fr.cnes.analysis.tools.ui.view.metrics.IMetricDescriptor;
-import fr.cnes.analysis.tools.ui.view.metrics.MetricContentProvider;
-import fr.cnes.analysis.tools.ui.view.metrics.MetricDescriptor;
-import fr.cnes.analysis.tools.ui.view.metrics.MetricLabelProvider;
-
/**
* View displaying the metrics computation results.
*
@@ -67,556 +64,531 @@
*/
public class MetricsView extends AbstractExportableView {
- /**
- * Relative path to the XSD contained in the project for XML analysisResult
- * file validation.
- */
- public static final String XSD_FILEPATH = "resource/xsd/analysisResult.xsd";
+ /**
+ * Relative path to the XSD contained in the project for XML analysisResult file validation.
+ */
+ public static final String XSD_FILEPATH = "resource/xsd/analysisResult.xsd";
- /** View ID. **/
- public static final String VIEW_ID = MetricsView.class.getName();
+ /** View ID. **/
+ public static final String VIEW_ID = MetricsView.class.getName();
- /** Bounds value. **/
- public static final int[] BOUNDS = { 200, 75, 75, 75, 75, 200, 200 };
+ /** Bounds value. **/
+ public static final int[] BOUNDS = { 200, 75, 75, 75, 75, 200, 200 };
- /** Columns titles **/
- public static final String[] TITLES = { "Metric", "Total", "Mean", "Minimum", "Maximum" };
+ /** Columns titles **/
+ public static final String[] TITLES = { "Metric", "Total", "Mean", "Minimum",
+ "Maximum" };
- /**
- *
- */
- public static final List MARKERS = new ArrayList();
+ /**
+ *
+ */
+ public static final List MARKERS = new ArrayList();
- /** Logger **/
- private static final Logger LOGGER = Logger.getLogger(MetricsView.class.getName());
+ /** Logger **/
+ private static final Logger LOGGER = Logger.getLogger(MetricsView.class.getName());
- /**
- * This attribute store all the analysis results files.
- */
- private Set analysisResult = new HashSet();
+ /**
+ * This attribute store all the analysis results files.
+ */
+ private Set analysisResult = new HashSet();
- /** The project analyzed */
- private IProject analysisProject;
+ /** The project analyzed */
+ private IProject analysisProject;
- /** The name of the user who ran the analysis */
- private String author;
+ /** The name of the user who ran the analysis */
+ private String author;
- /** The moment of the analysis */
- private String date;
+ /** The moment of the analysis */
+ private String date;
- /**
- * Empty constructor.
- */
- public MetricsView() {
- super(BOUNDS, TITLES);
- analysisResult = new TreeSet<>(new Comparator() {
-
- @Override
- public int compare(final FileValue value1, final FileValue value2) {
-
- int res = value1.getMetricId().compareTo(value2.getMetricId());
- if (res == 0) {
- res = value1.getFile().getAbsolutePath()
- .compareTo(value2.getFile().getAbsolutePath());
- }
- return res;
- }
- });
- }
+ /**
+ * Empty constructor.
+ */
+ public MetricsView() {
+ super(BOUNDS, TITLES);
+ analysisResult = new TreeSet<>(new Comparator() {
- /*
- * (non-Javadoc)
- *
- * @see fr.cnes.analysis.tools.ui.view.AbstractAnalysisView#createColumns()
- */
- @Override
- protected void createColumns() {
- LOGGER.finest("Begin createColumns method");
-
- this.getViewer().setContentProvider(new MetricContentProvider());
- TreeViewerColumn col;
- for (int i = 0; i < this.getTitles().length; i++) {
- // Create the column
- col = this.createTreeViewerColumn(this.getTitles()[i], this.getBounds()[i]);
-
- // Add a label provider
- col.setLabelProvider(new MetricLabelProvider(i));
- }
+ @Override
+ public int compare(final FileValue value1, final FileValue value2) {
- LOGGER.finest("End createColumns method");
+ int res = value1.getMetricId().compareTo(value2.getMetricId());
+ if (res == 0) {
+ res = value1.getFile().getAbsolutePath().compareTo(value2.getFile().getAbsolutePath());
+ }
+ return res;
+ }
+ });
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see fr.cnes.analysis.tools.ui.view.AbstractAnalysisView#createColumns()
+ */
+ @Override
+ protected void createColumns() {
+ LOGGER.finest("Begin createColumns method");
+
+ this.getViewer().setContentProvider(new MetricContentProvider());
+ TreeViewerColumn col;
+ for (int i = 0; i < this.getTitles().length; i++) {
+ // Create the column
+ col = this.createTreeViewerColumn(this.getTitles()[i], this.getBounds()[i]);
+
+ // Add a label provider
+ col.setLabelProvider(new MetricLabelProvider(i));
}
- /*
- * (non-Javadoc)
- *
- * @see fr.cnes.analysis.tools.ui.view.AbstractAnalysisView#
- * addDoubleClickAction ()
- */
-
- @Override
- protected void addDoubleClickAction() {
- LOGGER.finest("begin method addDoubleClickAction");
- final TreeViewer viewer = this.getViewer();
+ LOGGER.finest("End createColumns method");
+ }
- viewer.addDoubleClickListener(new IDoubleClickListener() {
+ /*
+ * (non-Javadoc)
+ *
+ * @see fr.cnes.analysis.tools.ui.view.AbstractAnalysisView# addDoubleClickAction ()
+ */
- @Override
- public void doubleClick(final DoubleClickEvent event) {
- final TreeViewer tViewer = (TreeViewer) event.getViewer();
- final IStructuredSelection thisSelection = (IStructuredSelection) event
- .getSelection();
- final Object selectedNode = thisSelection.getFirstElement();
+ @Override
+ protected void addDoubleClickAction() {
+ LOGGER.finest("begin method addDoubleClickAction");
+ final TreeViewer viewer = this.getViewer();
- tViewer.setExpandedState(selectedNode, !tViewer.getExpandedState(selectedNode));
- // if it is a leaf -> open the file
- if (!tViewer.isExpandable(selectedNode)
- && selectedNode instanceof FunctionMetricDescriptor) {
+ viewer.addDoubleClickListener(new IDoubleClickListener() {
- // get Path of the file & Line of the
- // File containing the
- // Metric
- final IPath path = ((FunctionMetricDescriptor) selectedNode).getFilePath();
- final int line = ((FunctionMetricDescriptor) selectedNode).getLine();
+ @Override
+ public void doubleClick(final DoubleClickEvent event) {
+ final TreeViewer tViewer = (TreeViewer) event.getViewer();
+ final IStructuredSelection thisSelection = (IStructuredSelection) event.getSelection();
+ final Object selectedNode = thisSelection.getFirstElement();
- // get resource
- final IFile fileToOpen = ResourcesPlugin.getWorkspace().getRoot()
- .getFileForLocation(path);
- final IResource res = fileToOpen;
+ tViewer.setExpandedState(selectedNode, !tViewer.getExpandedState(selectedNode));
+ // if it is a leaf -> open the file
+ if (!tViewer.isExpandable(selectedNode)
+ && selectedNode instanceof FunctionMetricDescriptor) {
- // open file in editor
- MetricsView.this.openFileInEditor(res, line);
+ // get Path of the file & Line of the
+ // File containing the
+ // Metric
+ final IPath path = ((FunctionMetricDescriptor) selectedNode).getFilePath();
+ final int line = ((FunctionMetricDescriptor) selectedNode).getLine();
- }
- }
+ // get resource
+ final IFile fileToOpen = ResourcesPlugin.getWorkspace().getRoot()
+ .getFileForLocation(path);
+ final IResource res = fileToOpen;
- });
+ // open file in editor
+ MetricsView.this.openFileInEditor(res, line);
- LOGGER.finest("end method addDoubleClickAction");
- }
-
- /**
- * Procedure insertMarkers
- *
- * Clean every marker in a file of the type violation error and then add the
- * ones violating metric limits.
- *
- */
- public void insertMarkers() {
- LOGGER.finest("begin method insertMarkers");
- /*
- * To avoid to clean two times markers in the same document, we use an
- * HashSet to refer cleaned files.
- */
- final HashSet cleanedFiles = new HashSet();
- String metricName;
- Float value, limit;
- IFile file;
- try {
- for (final MetricDescriptor metricD : ((MetricContentProvider) this.getViewer()
- .getContentProvider()).getConverter().getContainer()) {
- metricName = metricD.getName();
- for (final FileMetricDescriptor fileMetricD : metricD.getDescriptors()) {
- for (final FunctionMetricDescriptor funMetric : fileMetricD.getDescriptors()) {
- if (!funMetric.hasRightValue()) {
- // Has we are going to
- // add a new marker, we
- // verify
- // that
- // the file was clean
- file = ResourcesPlugin.getWorkspace().getRoot()
- .getFileForLocation(funMetric.getFilePath());
- value = funMetric.getValue();
- limit = PlatformUI.getPreferenceStore()
- .getFloat(funMetric.getMetricId() + PreferencesUIUtils.VALUE
- + PreferencesUIUtils.LEVELS[PlatformUI
- .getPreferenceStore()
- .getInt(PreferencesUIUtils.LEVEL)]);
- if (!cleanedFiles.contains(file)) {
- // if it's not,
- // then we clean
- // markers in it
- cleanedFiles.add(file);
- file.deleteMarkers(
- "fr.cnes.analysis.tools.ui.markers.ViolationErrorMarker",
- true, 1);
- }
- ViolationErrorMarker.createMarker(file, funMetric.getLine(),
- funMetric.getName(), metricName + " | Value is " + value
- + " while limit was set to " + limit);
- }
- }
-
- }
- }
- // One time all markers have been insert, we refresh all
- // decorators.
- final IDecoratorManager manager = PlatformUI.getWorkbench().getDecoratorManager();
-
- manager.update("fr.cnes.analysis.tools.ui.decorators.violationwarningdecorator");
- manager.update("fr.cnes.analysis.tools.ui.decorators.violationerrordecorator");
- } catch (final CoreException exception) {
- LOGGER.log(Level.FINER, exception.getClass() + " : " + exception.getMessage(),
- exception);
- MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
- "Marker problem", exception.getMessage());
}
-
- LOGGER.finest("end method insertMarkers");
-
- }
-
- /**
- * Open the file containing the metric at the metric's function line.
- *
- * @param res
- * the file to open
- * @param line
- * the line where the file should open
- */
- private void openFileInEditor(final IResource res, final int line) {
- LOGGER.finest("begin method openFileInEditor");
- final IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
- .getActivePage();
- try {
- // Before creating the marker
- res.deleteMarkers(IMarker.MARKER, false, 1);
- final IMarker marker = res.createMarker(IMarker.MARKER);
- marker.setAttribute(IMarker.LINE_NUMBER, line);
- marker.setAttribute("Class", "Metric");
-
- IDE.openEditor(page, marker);
- } catch (final CoreException exception) {
- LOGGER.log(Level.FINER, exception.getClass() + " : " + exception.getMessage(),
- exception);
- MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
- "Marker problem", exception.getMessage());
- }
- LOGGER.finest("end method openFileInEditor");
- }
-
+ }
+
+ });
+
+ LOGGER.finest("end method addDoubleClickAction");
+ }
+
+ /**
+ * Procedure insertMarkers
+ *
+ * Clean every marker in a file of the type violation error and then add the ones violating metric
+ * limits.
+ *
+ */
+ public void insertMarkers() {
+ LOGGER.finest("begin method insertMarkers");
/*
- * (non-Javadoc)
- *
- * @see fr.cnes.analysis.tools.ui.view.ExportableView#toCSV()
+ * To avoid to clean two times markers in the same document, we use an HashSet to refer cleaned
+ * files.
*/
- @Override
- protected void toCSV() throws IOException {
- LOGGER.finest("Begin toCSV method");
-
- getOut().write("Metric, File, Location, Total, "
- + "Mean, Minimum, Maximum, Resource Causing Minimum , Resource Causing Maximum\n");
-
- for (final MetricDescriptor value : ((MetricContentProvider) this.getViewer()
- .getContentProvider()).getConverter().getContainer()) {
- this.getOut().write(value.getName() + ",,," + this.getCSVText(value));
- for (final FileMetricDescriptor fValue : value.getDescriptors()) {
- this.getOut().write(
- value.getName() + "," + fValue.getName() + ",," + this.getCSVText(fValue));
- if (!fValue.getDescriptors().isEmpty()) {
- for (final FunctionMetricDescriptor funcValue : fValue.getDescriptors()) {
- this.getOut().write(value.getName() + "," + fValue.getName() + ","
- + funcValue.getName() + "," + this.getCSVText(funcValue));
- }
- }
+ final HashSet cleanedFiles = new HashSet();
+ String metricName;
+ Float value, limit;
+ IFile file;
+ try {
+ for (final MetricDescriptor metricD : ((MetricContentProvider) this.getViewer()
+ .getContentProvider()).getConverter().getContainer()) {
+ metricName = metricD.getName();
+ for (final FileMetricDescriptor fileMetricD : metricD.getDescriptors()) {
+ for (final FunctionMetricDescriptor funMetric : fileMetricD.getDescriptors()) {
+ if (!funMetric.hasRightValue()) {
+ // Has we are going to
+ // add a new marker, we
+ // verify
+ // that
+ // the file was clean
+ file = ResourcesPlugin.getWorkspace().getRoot()
+ .getFileForLocation(funMetric.getFilePath());
+ value = funMetric.getValue();
+ limit = PlatformUI.getPreferenceStore()
+ .getFloat(funMetric.getMetricId() + PreferencesUIUtils.VALUE
+ + PreferencesUIUtils.LEVELS[PlatformUI.getPreferenceStore()
+ .getInt(PreferencesUIUtils.LEVEL)]);
+ if (!cleanedFiles.contains(file)) {
+ // if it's not,
+ // then we clean
+ // markers in it
+ cleanedFiles.add(file);
+ file.deleteMarkers("fr.cnes.analysis.tools.ui.markers.ViolationErrorMarker", true,
+ 1);
+ }
+ ViolationErrorMarker.createMarker(file, funMetric.getLine(), funMetric.getName(),
+ metricName + " | Value is " + value + " while limit was set to " + limit);
}
- }
+ }
- LOGGER.finest("End toCSV method");
+ }
+ }
+ // One time all markers have been insert, we refresh all
+ // decorators.
+ final IDecoratorManager manager = PlatformUI.getWorkbench().getDecoratorManager();
+
+ manager.update("fr.cnes.analysis.tools.ui.decorators.violationwarningdecorator");
+ manager.update("fr.cnes.analysis.tools.ui.decorators.violationerrordecorator");
+ } catch (final CoreException exception) {
+ LOGGER.log(Level.FINER, exception.getClass() + " : " + exception.getMessage(), exception);
+ MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
+ "Marker problem", exception.getMessage());
}
- /**
- * This method creates the common text for any Viewable to put in the CSV
- * file.
- *
- * @param element
- * the Viewable element to get text
- * @return CSV formatted text of this element
- */
- private String getCSVText(final IMetricDescriptor element) {
- LOGGER.finest("Begin getText method");
-
- final String text = this.convertToString(element.getValue()) + ","
- + this.convertToString(element.getMean()) + ","
- + this.convertToString(element.getMinimum()) + ","
- + this.convertToString(element.getMaximum()) + "," + element.getMinCause() + ","
- + element.getMaxCause() + "\n";
-
- LOGGER.finest("End getText method");
- return text;
+ LOGGER.finest("end method insertMarkers");
+
+ }
+
+ /**
+ * Open the file containing the metric at the metric's function line.
+ *
+ * @param res
+ * the file to open
+ * @param line
+ * the line where the file should open
+ */
+ private void openFileInEditor(final IResource res, final int line) {
+ LOGGER.finest("begin method openFileInEditor");
+ final IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
+ .getActivePage();
+ try {
+ // Before creating the marker
+ res.deleteMarkers(IMarker.MARKER, false, 1);
+ final IMarker marker = res.createMarker(IMarker.MARKER);
+ marker.setAttribute(IMarker.LINE_NUMBER, line);
+ marker.setAttribute("Class", "Metric");
+
+ IDE.openEditor(page, marker);
+ } catch (final CoreException exception) {
+ LOGGER.log(Level.FINER, exception.getClass() + " : " + exception.getMessage(), exception);
+ MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
+ "Marker problem", exception.getMessage());
}
-
- /**
- * Method used to convert float value into String value for CSV export. If
- * the float value is infinite or NaN, the text returned is "--". Otherwise,
- * it returns Float.toString() value.
- *
- * @param value
- * float value to convert into String
- * @return toString() value, "--" if the value is infinite or NaN
- */
- private String convertToString(final Float value) {
- String text;
- if (value.isInfinite() || value.isNaN()) {
- text = "--";
- } else {
- text = value.toString();
+ LOGGER.finest("end method openFileInEditor");
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see fr.cnes.analysis.tools.ui.view.ExportableView#toCSV()
+ */
+ @Override
+ protected void toCSV() throws IOException {
+ LOGGER.finest("Begin toCSV method");
+
+ getOut().write("Metric, File, Location, Total, "
+ + "Mean, Minimum, Maximum, Resource Causing Minimum , Resource Causing Maximum\n");
+
+ for (final MetricDescriptor value : ((MetricContentProvider) this.getViewer()
+ .getContentProvider()).getConverter().getContainer()) {
+ this.getOut().write(value.getName() + ",,," + this.getCSVText(value));
+ for (final FileMetricDescriptor fValue : value.getDescriptors()) {
+ this.getOut()
+ .write(value.getName() + "," + fValue.getName() + ",," + this.getCSVText(fValue));
+ if (!fValue.getDescriptors().isEmpty()) {
+ for (final FunctionMetricDescriptor funcValue : fValue.getDescriptors()) {
+ this.getOut().write(value.getName() + "," + fValue.getName() + "," + funcValue.getName()
+ + "," + this.getCSVText(funcValue));
+ }
}
- return text;
+ }
}
- /**
- * Displays the analyze results on the view.
- *
- * @param values
- * the descriptors to show on the view
- * @param pProject
- * The project selected to run the analysis
- * @param pAnalysisDate
- * The date of the analysis
- * @param pAnalysisAuthor
- * The user who ran the analysis
- * @return
- * @throws EmptyProviderException
- * when source provider to determine view type is not found (not
- * necessarily used)
- */
- public void display(final List values, final IProject pProject,
- final String pAnalysisAuthor, final String pAnalysisDate)
- throws EmptyProviderException {
- LOGGER.finest("Begin display method");
-
- this.analysisProject = pProject;
- this.author = pAnalysisAuthor;
- this.date = pAnalysisDate;
-
- synchronized (this) {
- final Set listInputs = new TreeSet(new Comparator() {
-
- @Override
- public int compare(final FileValue value1, final FileValue value2) {
-
- int res = value1.getMetricId().compareTo(value2.getMetricId());
- if (res == 0) {
- res = value1.getFile().getAbsolutePath()
- .compareTo(value2.getFile().getAbsolutePath());
- }
- return res;
- }
- });
-
- if (this.getViewer().getInput() != null) {
- for (final FileValue input : (FileValue[]) this.getViewer().getInput()) {
- listInputs.add(input);
- }
- }
-
- for (final FileValue value : values) {
- listInputs.add(value);
- }
- analysisResult = listInputs;
- this.getViewer().setInput(listInputs.toArray(new FileValue[listInputs.size()]));
+ LOGGER.finest("End toCSV method");
+ }
+
+ /**
+ * This method creates the common text for any Viewable to put in the CSV file.
+ *
+ * @param element
+ * the Viewable element to get text
+ * @return CSV formatted text of this element
+ */
+ private String getCSVText(final IMetricDescriptor element) {
+ LOGGER.finest("Begin getText method");
+
+ final String text = this.convertToString(element.getValue()) + ","
+ + this.convertToString(element.getMean()) + "," + this.convertToString(element.getMinimum())
+ + "," + this.convertToString(element.getMaximum()) + "," + element.getMinCause() + ","
+ + element.getMaxCause() + "\n";
+
+ LOGGER.finest("End getText method");
+ return text;
+ }
+
+ /**
+ * Method used to convert float value into String value for CSV export. If the float value is
+ * infinite or NaN, the text returned is "--". Otherwise, it returns Float.toString() value.
+ *
+ * @param value
+ * float value to convert into String
+ * @return toString() value, "--" if the value is infinite or NaN
+ */
+ private String convertToString(final Float value) {
+ String text;
+ if (value.isInfinite() || value.isNaN()) {
+ text = "--";
+ } else {
+ text = value.toString();
+ }
+ return text;
+ }
+
+ /**
+ * Displays the analyze results on the view.
+ *
+ * @param values
+ * the descriptors to show on the view
+ * @param pProject
+ * The project selected to run the analysis
+ * @param pAnalysisDate
+ * The date of the analysis
+ * @param pAnalysisAuthor
+ * The user who ran the analysis
+ * @return
+ * @throws EmptyProviderException
+ * when source provider to determine view type is not found (not necessarily used)
+ */
+ public void display(final List values) throws EmptyProviderException {
+ LOGGER.finest("Begin display method");
+
+ synchronized (this) {
+ final Set listInputs = new TreeSet(new Comparator() {
+
+ @Override
+ public int compare(final FileValue value1, final FileValue value2) {
+
+ int res = value1.getMetricId().compareTo(value2.getMetricId());
+ if (res == 0) {
+ res = value1.getFile().getAbsolutePath().compareTo(value2.getFile().getAbsolutePath());
+ }
+ return res;
}
+ });
- this.getViewer().refresh();
- LOGGER.finest("End display method");
- }
+ if (this.getViewer().getInput() != null) {
+ for (final FileValue input : (FileValue[]) this.getViewer().getInput()) {
+ listInputs.add(input);
+ }
+ }
- /**
- * This method will clear the message and make it appear on the view.
- *
- * @throws EmptyProviderException
- * when source provider to determine view type is not found (not
- * necessarily used)
- */
- public void clear() throws EmptyProviderException {
- this.getViewer().setInput(new FileValue[0]);
- this.getViewer().refresh();
+ for (final FileValue value : values) {
+ listInputs.add(value);
+ }
+ analysisResult = listInputs;
+ this.getViewer().setInput(listInputs.toArray(new FileValue[listInputs.size()]));
}
- @Override
- protected void fillView() {
- // TODO not implemented yet
-
- }
+ this.getViewer().refresh();
+ LOGGER.finest("End display method");
+ }
+
+ /**
+ * This method will clear the message and make it appear on the view.
+ *
+ * @throws EmptyProviderException
+ * when source provider to determine view type is not found (not necessarily used)
+ */
+ public void clear() throws EmptyProviderException {
+ this.getViewer().setInput(new FileValue[0]);
+ this.getViewer().refresh();
+ }
+
+ @Override
+ protected void fillView() {
+ // TODO not implemented yet
+
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see fr.cnes.analysis.tools.ui.view.AbstractExportableView#toXML(java.io.File)
+ */
+ @Override
+ protected void toXML(final File file) throws IOException {
+ LOGGER.finest("begin method toXML");
+ // We initiate a list that will be usefull to add attributes to
+ // elements.
+ final List attributes = new ArrayList();
+ final List resultAttributes = new ArrayList();
/*
- * (non-Javadoc)
- *
- * @see
- * fr.cnes.analysis.tools.ui.view.AbstractExportableView#toXML(java.io.File)
+ * Creation of the root element
*/
- @Override
- protected void toXML(final File file) throws IOException {
- LOGGER.finest("begin method toXML");
- // We initiate a list that will be usefull to add attributes to
- // elements.
- final List attributes = new ArrayList();
- final List resultAttributes = new ArrayList();
-
- /*
- * Creation of the root element
- */
- final Element analysisProjectEl = new Element("analysisProject");
- analysisProjectEl
- .setAttribute(new Attribute("analysisProjectName", this.analysisProject.getName()));
- final Document document = new Document(analysisProjectEl);
-
- // BEGINNING OF SEQUENCE
- // --
-
- final Element analysisInfo = new Element("analysisInformations");
- attributes.add(new Attribute("analysisConfigurationId", "standard"));
- attributes.add(new Attribute("analysisDate", this.date));
- attributes.add(new Attribute("author", this.author));
-
- analysisInfo.setAttributes(attributes);
- document.getRootElement().addContent(analysisInfo);
- // --
- for (final FileValue fv : this.analysisResult) {
- attributes.clear();
-
- // --
- // Note : We take only the last segment of the filepath to
- // get
- // the filename.
- // --
- final String language = this.getFileExtension(fv.getFile().getAbsolutePath());
- final String fileName = fv.getFile().getName();
- // The analysisFile element is being added only and only if it's not
- // already in the XML document.
- boolean analysisFileMarked = false;
- for (final Element element : document.getRootElement().getChildren("analysisFile")) {
- if (element.getAttributeValue("fileName").equals(fileName)
- && element.getAttributeValue("language").equals(language)) {
- analysisFileMarked = true;
- }
- }
- if (!analysisFileMarked) {
- final Element analysisFile = new Element("analysisFile");
- attributes.add(new Attribute("language", language));
- attributes.add(new Attribute("fileName", fileName));
- analysisFile.setAttributes(attributes);
- document.getRootElement().addContent(analysisFile);
- }
-
+ final Element analysisProjectEl = new Element("analysisProject");
+ analysisProjectEl
+ .setAttribute(new Attribute("analysisProjectName", this.analysisProject.getName()));
+ final Document document = new Document(analysisProjectEl);
+
+ // BEGINNING OF SEQUENCE
+ // --
+
+ final Element analysisInfo = new Element("analysisInformations");
+ attributes.add(new Attribute("analysisConfigurationId", "standard"));
+ attributes.add(new Attribute("analysisDate", this.date));
+ attributes.add(new Attribute("author", this.author));
+
+ analysisInfo.setAttributes(attributes);
+ document.getRootElement().addContent(analysisInfo);
+ // --
+ for (final FileValue fv : this.analysisResult) {
+ attributes.clear();
+
+ // --
+ // Note : We take only the last segment of the filepath to
+ // get
+ // the filename.
+ // --
+ final String language = this.getFileExtension(fv.getFile().getAbsolutePath());
+ final String fileName = fv.getFile().getName();
+ // The analysisFile element is being added only and only if it's not
+ // already in the XML document.
+ boolean analysisFileMarked = false;
+ for (final Element element : document.getRootElement().getChildren("analysisFile")) {
+ if (element.getAttributeValue("fileName").equals(fileName)
+ && element.getAttributeValue("language").equals(language)) {
+ analysisFileMarked = true;
}
+ }
+ if (!analysisFileMarked) {
+ final Element analysisFile = new Element("analysisFile");
+ attributes.add(new Attribute("language", language));
+ attributes.add(new Attribute("fileName", fileName));
+ analysisFile.setAttributes(attributes);
+ document.getRootElement().addContent(analysisFile);
+ }
- Element result, analysisRule = null;
- int resultId = 1;
- for (final FileValue fileV : this.analysisResult) {
- boolean elementAlreadyExisting = false;
- Element existingElement = null;
- for (final Element element : document.getRootElement().getChildren("analysisRule")) {
- for (final Attribute attribute : element.getAttributes()) {
- if (attribute.getName().equals("analysisRuleId")
- && attribute.getValue().equals(fileV.getMetricId())) {
- elementAlreadyExisting = true;
- existingElement = element;
- }
- }
- }
- if (!elementAlreadyExisting || existingElement == null) {
- analysisRule = new Element("analysisRule");
- analysisRule.setAttribute(new Attribute("analysisRuleId", fileV.getMetricId()));
- } else {
- analysisRule = existingElement;
- }
- for (final FunctionValue functionV : fileV.getFunctionValues()) {
+ }
- result = new Element("result");
- resultAttributes.clear();
- // no justification for now
- // no outputDetail for now neither
+ Element result, analysisRule = null;
+ int resultId = 1;
+ for (final FileValue fileV : this.analysisResult) {
+ boolean elementAlreadyExisting = false;
+ Element existingElement = null;
+ for (final Element element : document.getRootElement().getChildren("analysisRule")) {
+ for (final Attribute attribute : element.getAttributes()) {
+ if (attribute.getName().equals("analysisRuleId")
+ && attribute.getValue().equals(fileV.getMetricId())) {
+ elementAlreadyExisting = true;
+ existingElement = element;
+ }
+ }
+ }
+ if (!elementAlreadyExisting || existingElement == null) {
+ analysisRule = new Element("analysisRule");
+ analysisRule.setAttribute(new Attribute("analysisRuleId", fileV.getMetricId()));
+ } else {
+ analysisRule = existingElement;
+ }
+ for (final FunctionValue functionV : fileV.getFunctionValues()) {
- resultAttributes.add(new Attribute("resultId", Integer.toString(resultId)));
- resultId++;
+ result = new Element("result");
+ resultAttributes.clear();
+ // no justification for now
+ // no outputDetail for now neither
- resultAttributes.add(new Attribute("fileName", fileV.getFile().getAbsolutePath()));
+ resultAttributes.add(new Attribute("resultId", Integer.toString(resultId)));
+ resultId++;
- resultAttributes.add(new Attribute("resultValue", functionV.getValue().toString()));
+ resultAttributes.add(new Attribute("fileName", fileV.getFile().getAbsolutePath()));
- resultAttributes
- .add(new Attribute("resultLine", Integer.toString(functionV.getLine())));
+ resultAttributes.add(new Attribute("resultValue", functionV.getValue().toString()));
- resultAttributes.add(new Attribute("resultNamePlace", functionV.getLocation()));
+ resultAttributes.add(new Attribute("resultLine", Integer.toString(functionV.getLine())));
- result.setAttributes(resultAttributes);
+ resultAttributes.add(new Attribute("resultNamePlace", functionV.getLocation()));
- analysisRule.addContent(result);
- }
- if (!elementAlreadyExisting) {
- document.getRootElement().addContent(analysisRule);
- }
+ result.setAttributes(resultAttributes);
- }
- final XMLOutputter xmlOutput = new XMLOutputter();
- xmlOutput.setFormat(Format.getPrettyFormat());
- final FileOutputStream fileOutput = new FileOutputStream(file);
-
- xmlOutput.output(document, fileOutput);
- fileOutput.close();
- this.verifyXMLandXSDValidity(file);
- LOGGER.finest("end method toXML");
+ analysisRule.addContent(result);
+ }
+ if (!elementAlreadyExisting) {
+ document.getRootElement().addContent(analysisRule);
+ }
}
+ final XMLOutputter xmlOutput = new XMLOutputter();
+ xmlOutput.setFormat(Format.getPrettyFormat());
+ final FileOutputStream fileOutput = new FileOutputStream(file);
- /**
- * @param fileName
- * @return The extension name of the file
- */
- private String getFileExtension(String fileName) {
- String extension = "unknown";
-
- int i = fileName.lastIndexOf('.');
- int p = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));
-
- if (i > p) {
- extension = fileName.substring(i+1);
- }
- return extension;
- }
-
- /**
- * @param file
- * The XML file to validate
- *
- * @return Returns if XSD is W3C valid and XML is W3C valid and respecting
- * XSD specifications.
- *
- * @throws IOException
- * when XSD file can't be read.
- */
- public boolean verifyXMLandXSDValidity(final File file) throws IOException {
- LOGGER.finest("begin method verifyXMLandXSDValidity");
- boolean validity;
- try {
- final SchemaFactory factory = SchemaFactory
- .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
-
- // TODO : Find better way to locate the XSD file in resources
- final URL globalPath = new URL(
- this.getClass().getProtectionDomain().getCodeSource().getLocation()
- + MetricsView.XSD_FILEPATH);
-
- final Schema dda = factory.newSchema(globalPath);
-
- final Validator validator = dda.newValidator();
- validator.validate(new StreamSource(file));
- validity = true;
- } catch (SAXException exception) {
- validity = false;
- LOGGER.log(Level.WARNING, exception.getClass() + " : " + exception.getMessage(),
- exception);
- }
+ xmlOutput.output(document, fileOutput);
+ fileOutput.close();
+ this.verifyXMLandXSDValidity(file);
+ LOGGER.finest("end method toXML");
- LOGGER.finest("end method verifyXMLandXSDValidity");
- return validity;
+ }
+ /**
+ * @param fileName
+ * @return The extension name of the file
+ */
+ private String getFileExtension(String fileName) {
+ String extension = "unknown";
+
+ int i = fileName.lastIndexOf('.');
+ int p = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));
+
+ if (i > p) {
+ extension = fileName.substring(i + 1);
+ }
+ return extension;
+ }
+
+ /**
+ * @param file
+ * The XML file to validate
+ *
+ * @return Returns if XSD is W3C valid and XML is W3C valid and respecting XSD specifications.
+ *
+ * @throws IOException
+ * when XSD file can't be read.
+ */
+ public boolean verifyXMLandXSDValidity(final File file) throws IOException {
+ LOGGER.finest("begin method verifyXMLandXSDValidity");
+ boolean validity;
+ try {
+ final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
+
+ // TODO : Find better way to locate the XSD file in resources
+ final URL globalPath = new URL(
+ this.getClass().getProtectionDomain().getCodeSource().getLocation()
+ + MetricsView.XSD_FILEPATH);
+
+ final Schema dda = factory.newSchema(globalPath);
+
+ final Validator validator = dda.newValidator();
+ validator.validate(new StreamSource(file));
+ validity = true;
+ } catch (SAXException exception) {
+ validity = false;
+ LOGGER.log(Level.WARNING, exception.getClass() + " : " + exception.getMessage(), exception);
}
+ LOGGER.finest("end method verifyXMLandXSDValidity");
+ return validity;
+
+ }
+
}
diff --git a/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/view/ViolationsView.java b/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/view/ViolationsView.java
index 285478d1..e08cfa10 100755
--- a/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/view/ViolationsView.java
+++ b/fr.cnes.analysis.tools.ui/src/fr/cnes/analysis/tools/ui/view/ViolationsView.java
@@ -1,5 +1,16 @@
package fr.cnes.analysis.tools.ui.view;
+import fr.cnes.analysis.tools.analyzer.datas.Violation;
+import fr.cnes.analysis.tools.ui.exception.EmptyProviderException;
+import fr.cnes.analysis.tools.ui.markers.ViolationErrorMarker;
+import fr.cnes.analysis.tools.ui.markers.ViolationWarningMarker;
+import fr.cnes.analysis.tools.ui.view.violation.treeviewer.IUpdatableAnalysisFilter;
+import fr.cnes.analysis.tools.ui.view.violation.treeviewer.file.FileTreeViewer;
+import fr.cnes.analysis.tools.ui.view.violation.treeviewer.file.FileTreeViewerContentProvider;
+import fr.cnes.analysis.tools.ui.view.violation.treeviewer.file.filter.FileTreeViewerFilter;
+import fr.cnes.analysis.tools.ui.view.violation.treeviewer.rule.RuleTreeViewer;
+import fr.cnes.analysis.tools.ui.view.violation.treeviewer.rule.RuleTreeViewerContentProvider;
+import fr.cnes.analysis.tools.ui.view.violation.treeviewer.rule.filter.RuleViewerFilter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
@@ -14,13 +25,11 @@
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
-
import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
-
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
@@ -53,760 +62,728 @@
import org.jdom2.output.XMLOutputter;
import org.xml.sax.SAXException;
-import fr.cnes.analysis.tools.analyzer.datas.Violation;
-import fr.cnes.analysis.tools.ui.exception.EmptyProviderException;
-import fr.cnes.analysis.tools.ui.markers.ViolationErrorMarker;
-import fr.cnes.analysis.tools.ui.markers.ViolationWarningMarker;
-import fr.cnes.analysis.tools.ui.view.violation.treeviewer.IUpdatableAnalysisFilter;
-import fr.cnes.analysis.tools.ui.view.violation.treeviewer.file.FileTreeViewer;
-import fr.cnes.analysis.tools.ui.view.violation.treeviewer.file.FileTreeViewerContentProvider;
-import fr.cnes.analysis.tools.ui.view.violation.treeviewer.file.filter.FileTreeViewerFilter;
-import fr.cnes.analysis.tools.ui.view.violation.treeviewer.rule.RuleTreeViewer;
-import fr.cnes.analysis.tools.ui.view.violation.treeviewer.rule.RuleTreeViewerContentProvider;
-import fr.cnes.analysis.tools.ui.view.violation.treeviewer.rule.filter.RuleViewerFilter;
-
public class ViolationsView extends ViewPart implements IExportableView {
- /** Logger. **/
- public final static Logger LOGGER = Logger.getLogger(ViolationsView.class.getName());
-
- public static final String VIEW_ID = ViolationsView.class.getName();
-
- public static final String RULE_TREE_VIEWER_TYPE = "RuleTreeViewer";
-
- /**
- * FILE_TREE_VIEWER_TYPE
+ /** Logger. **/
+ public final static Logger LOGGER = Logger
+ .getLogger(ViolationsView.class.getName());
+
+ public static final String VIEW_ID = ViolationsView.class.getName();
+
+ public static final String RULE_TREE_VIEWER_TYPE = "RuleTreeViewer";
+
+ /**
+ * FILE_TREE_VIEWER_TYPE
+ */
+ public static final String FILE_TREE_VIEWER_TYPE = "FileTreeViewer";
+
+ /** The project on which was run the displayed analysis */
+ private IProject analysisProject;
+
+ /** The user who ran the analysis */
+ private String author = "unknown";
+
+ /** The date of the analysis */
+ private String date = "unknown";
+
+ /** The string to filter results in the TreeViewer */
+ private String searchString = "";
+
+ /** Indicate is violation of level warning must be shown */
+ private boolean showWarning = true;
+ /** Indicate is violation of level error must be shown */
+ private boolean showError = true;
+
+ /**
+ * Contain the identifier of the type of TreeViewer currently being displayed in the view. By
+ * default, the view show a RuleTreeViewer one
+ */
+ private String treeViewerType = RULE_TREE_VIEWER_TYPE;
+
+ /**
+ * The list of all violation used by the TreeViewer of the view, useful to make an export of the
+ * view
+ */
+ private Set analysisResults = new TreeSet<>(new Comparator() {
+
+ @Override
+ public int compare(final Violation value1,
+ final Violation value2) {
+
+ int res = value1.getRuleId()
+ .compareTo(value2.getRuleId());
+ if (res == 0) {
+ res = value1.getFile().getAbsoluteFile()
+ .compareTo(value2.getFile()
+ .getAbsoluteFile());
+ }
+ return res;
+ }
+ });
+
+ /** The viewer which display results. **/
+ private TreeViewer viewer;
+
+ /** Composite contained in the view and displaying it's elements */
+ private Composite parent;
+
+ /**
+ * Constructor with an integer array for table bounds and string array for the titles, as
+ * parameters.
+ */
+ public ViolationsView() {
+ super();
+ }
+
+ /**
+ * Getter for the viewer.
+ *
+ * @return the viewer
+ */
+ public TreeViewer getViewer() {
+ return this.viewer;
+ }
+
+ /**
+ * Setter for the viewer.
+ *
+ * @param pViewer
+ * this.descriptors.clone() set
+ */
+ public void setViewer(final TreeViewer pViewer) {
+ this.viewer = pViewer;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt. widgets.Composite)
+ */
+ @Override
+ public void createPartControl(final Composite pParent) {
+ LOGGER.finest("Begin createPartControl method");
+ this.parent = pParent;
+ final GridLayout layout = new GridLayout();
+
+ pParent.setLayout(layout);
+ /*
+ * Adding the filter field
*/
- public static final String FILE_TREE_VIEWER_TYPE = "FileTreeViewer";
-
- /** The project on which was run the displayed analysis */
- private IProject analysisProject;
-
- /** The user who ran the analysis */
- private String author;
-
- /** The date of the analysis */
- private String date;
-
- /** The string to filter results in the TreeViewer */
- private String searchString = "";
-
- /** Indicate is violation of level warning must be shown */
- private boolean showWarning = true;
- /** Indicate is violation of level error must be shown */
- private boolean showError = true;
+ final Text search = new Text(pParent, SWT.SEARCH | SWT.CANCEL | SWT.ICON_SEARCH);
+ search.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
+ search.setMessage("Filter : Enter part of file path, name, rule name or function's name... "
+ + "(not case sensitive)");
- /**
- * Contain the identifier of the type of TreeViewer currently being
- * displayed in the view. By default, the view show a RuleTreeViewer one
+ /*
+ * Updating search attribute every time the search field is being modified.
*/
- private String treeViewerType = RULE_TREE_VIEWER_TYPE;
+ search.addModifyListener(new ModifyListener() {
- /**
- * The list of all violation used by the TreeViewer of the view, useful to
- * make an export of the view
- */
- private Set analysisResults = new TreeSet<>(new Comparator() {
+ @Override
+ public void modifyText(final ModifyEvent event) {
+ final Text source = (Text) event.getSource();
+ searchString = source.getText();
+ update();
+ }
- @Override
- public int compare(final Violation value1, final Violation value2) {
+ });
- int res = value1.getRuleId().compareTo(value2.getRuleId());
- if (res == 0) {
- res = value1.getFile().getAbsoluteFile()
- .compareTo(value2.getFile().getAbsoluteFile());
- }
- return res;
+ /*
+ * Add a selection adapter for the button SWT.CANCEL of the search field that set the searching
+ * field to null when the user click on the button. Note : SWT.CANCEL do not exist in Windows 7.
+ */
+ search.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetDefaultSelected(final SelectionEvent event) {
+ if (event.detail == SWT.CANCEL) {
+ final Text text = (Text) event.getSource();
+ text.setText("");
+ update();
}
+ }
});
- /** The viewer which display results. **/
- private TreeViewer viewer;
+ final Button warningBtn = new Button(pParent, SWT.CHECK | SWT.SELECTED);
+ warningBtn.setText("Warning");
+ warningBtn.setSelection(true);
+ final Button errorBtn = new Button(pParent, SWT.CHECK | SWT.CHECK);
+ errorBtn.setText("Error");
+ errorBtn.setSelection(true);
+ warningBtn.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(final SelectionEvent event) {
+ final Button btn = (Button) event.getSource();
+ showWarning = btn.getSelection();
+ update();
+ }
- /** Composite contained in the view and displaying it's elements */
- private Composite parent;
+ });
- /**
- * Constructor with an integer array for table bounds and string array for
- * the titles, as parameters.
- */
- public ViolationsView() {
- super();
- }
+ errorBtn.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(final SelectionEvent event) {
+ final Button btn = (Button) event.getSource();
+ showError = btn.getSelection();
+ update();
+ }
+ });
- /**
- * Getter for the viewer.
- *
- * @return the viewer
- */
- public TreeViewer getViewer() {
- return this.viewer;
+ this.createRuleTreeViewer(pParent);
+ layout.numColumns = this.getViewer().getTree().getColumnCount();
+ LOGGER.finest("End createPartControl method");
+ }
+
+ /**
+ *
+ */
+ public void update() {
+ for (final ViewerFilter filter : this.viewer.getFilters()) {
+ if (filter instanceof IUpdatableAnalysisFilter) {
+ ((IUpdatableAnalysisFilter) filter).update(searchString, showWarning, showError);
+ }
}
+ viewer.refresh();
+ }
+
+ /**
+ * This method create the viewer, which is a tree table.
+ *
+ * @param parent
+ * the parent composite
+ */
+ private void createRuleTreeViewer(final Composite parent) {
+ LOGGER.finest("Begin createViewer method");
+
+ // Defining overall style for TreeViewer
+ final int scrollStyle = SWT.H_SCROLL | SWT.V_SCROLL;
+ final int selecStyle = SWT.MULTI | SWT.FULL_SELECTION;
+ final int style = scrollStyle | selecStyle;
+ this.viewer = new RuleTreeViewer(parent, style | SWT.FILL);
+ // Make headers and lines of the tree visible
+ final Tree tree = this.viewer.getTree();
+ tree.setHeaderVisible(true);
+ tree.setLinesVisible(true);
+
+ // Expand the tree
+ this.viewer.setAutoExpandLevel(1);
+
+ // Add selection provider which allows to listen to each
+ // selection made on this viewer.
+ this.getSite().setSelectionProvider(this.viewer);
+
+ // TODO: verify XML
+ // Fill tree with values from xml
+ // this.fillView();
+
+ // Layout the viewer
+ final GridData gridData = new GridData();
+ gridData.verticalAlignment = GridData.FILL;
+ gridData.horizontalSpan = this.viewer.getTree().getColumnCount();
+ gridData.grabExcessHorizontalSpace = true;
+ gridData.grabExcessVerticalSpace = true;
+ gridData.horizontalAlignment = GridData.FILL;
+ this.viewer.getTree().setLayoutData(gridData);
- /**
- * Setter for the viewer.
+ /*
+ * Creating a filter using field search & check buttons Warning and Error.
*
- * @param pViewer
- * this.descriptors.clone() set
+ * Show only element selected by the user.
*/
- public void setViewer(final TreeViewer pViewer) {
- this.viewer = pViewer;
- }
+ final RuleViewerFilter ruleFilter = new RuleViewerFilter();
+ viewer.addFilter(ruleFilter);
+
+ LOGGER.finest("End createViewer method");
+
+ }
+
+ /**
+ * This method create the viewer, which is a tree table.
+ *
+ * @param pParent
+ * the parent composite
+ */
+ private void createFileTreeViewer(final Composite pParent) {
+ LOGGER.finest("Begin createViewer method");
+
+ // Defining overall style for TreeViewer
+ final int scrollStyle = SWT.H_SCROLL | SWT.V_SCROLL;
+ final int selecStyle = SWT.MULTI | SWT.FULL_SELECTION;
+ final int style = scrollStyle | selecStyle;
+ this.viewer = new FileTreeViewer(pParent, style | SWT.FILL);
+ // Make headers and lines of the tree visible
+ final Tree tree = this.viewer.getTree();
+ tree.setHeaderVisible(true);
+ tree.setLinesVisible(true);
+
+ // Expand the tree
+ this.viewer.setAutoExpandLevel(1);
+
+ // Add selection provider which allows to listen to each
+ // selection made on this viewer.
+ this.getSite().setSelectionProvider(this.viewer);
+
+ // TODO: verify XML
+ // Fill tree with values from xml
+ // this.fillView();
+
+ // Layout the viewer
+ final GridData gridData = new GridData();
+ gridData.verticalAlignment = GridData.FILL;
+ gridData.horizontalSpan = this.viewer.getTree().getColumnCount();
+ gridData.grabExcessHorizontalSpace = true;
+ gridData.grabExcessVerticalSpace = true;
+ gridData.horizontalAlignment = GridData.FILL;
+ this.viewer.getTree().setLayoutData(gridData);
/*
- * (non-Javadoc)
+ * Creating a filter using field search & check buttons Warning and Error.
*
- * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.
- * widgets.Composite)
+ * Show only element selected by the user.
*/
- @Override
- public void createPartControl(final Composite pParent) {
- LOGGER.finest("Begin createPartControl method");
- this.parent = pParent;
- final GridLayout layout = new GridLayout();
-
- pParent.setLayout(layout);
- /*
- * Adding the filter field
- */
- final Text search = new Text(pParent, SWT.SEARCH | SWT.CANCEL | SWT.ICON_SEARCH);
- search.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
- search.setMessage("Filter : Enter part of file path, name, rule name or function's name... "
- + "(not case sensitive)");
-
- /*
- * Updating search attribute every time the search field is being
- * modified.
- */
- search.addModifyListener(new ModifyListener() {
-
- @Override
- public void modifyText(final ModifyEvent event) {
- final Text source = (Text) event.getSource();
- searchString = source.getText();
- update();
- }
+ final FileTreeViewerFilter fileFilter = new FileTreeViewerFilter();
+ this.viewer.addFilter(fileFilter);
+
+ LOGGER.finest("End createViewer method");
+
+ }
+
+ /**
+ * Fill view with the values from the xml file
+ */
+ protected void fillView() {
+ // TODO Fille view with XML file
+ }
+
+ /**
+ * Display violations found during analysis in the violations view.
+ *
+ * @param violations
+ * the violations to display
+ * @param pDate
+ * The date of the analysis
+ * @param pAuthor
+ * The user who ran the analysis
+ * @param pProject
+ * The project selected while running the analysis
+ */
+ public void display(final List violations) {
+ LOGGER.finest("Begin display(Descriptor[]) method");
+
+ synchronized (this) {
+ final Set listInputs = new TreeSet(new Comparator() {
- });
-
- /*
- * Add a selection adapter for the button SWT.CANCEL of the search field
- * that set the searching field to null when the user click on the
- * button. Note : SWT.CANCEL do not exist in Windows 7.
- */
- search.addSelectionListener(new SelectionAdapter() {
- public void widgetDefaultSelected(final SelectionEvent event) {
- if (event.detail == SWT.CANCEL) {
- final Text text = (Text) event.getSource();
- text.setText("");
- update();
+ @Override
+ public int compare(final Violation viol1, final Violation viol2) {
+ int res = viol1.getRuleName().split("\\.")[0]
+ .compareTo(viol2.getRuleName().split("\\.")[0]);
+ if (res == 0) {
+ res = viol1.getRuleName().split("\\.")[1]
+ .compareTo(viol2.getRuleName().split("\\.")[1]);
+ if (res == 0) {
+ res = viol1.getRuleName().split("\\.")[2]
+ .compareTo(viol2.getRuleName().split("\\.")[2]);
+ if (res == 0) {
+ res = viol1.getFile().getAbsolutePath()
+ .compareTo(viol2.getFile().getAbsolutePath());
+ if (res == 0) {
+ res = viol1.getLine().compareTo(viol2.getLine());
+ if (res == 0) {
+ res = viol1.getLocation().compareTo(viol2.getLocation());
+ }
}
+ }
}
- });
-
- final Button warningBtn = new Button(pParent, SWT.CHECK | SWT.SELECTED);
- warningBtn.setText("Warning");
- warningBtn.setSelection(true);
- final Button errorBtn = new Button(pParent, SWT.CHECK | SWT.CHECK);
- errorBtn.setText("Error");
- errorBtn.setSelection(true);
- warningBtn.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(final SelectionEvent event) {
- final Button btn = (Button) event.getSource();
- showWarning = btn.getSelection();
- update();
- }
-
- });
-
- errorBtn.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(final SelectionEvent event) {
- final Button btn = (Button) event.getSource();
- showError = btn.getSelection();
- update();
- }
- });
-
- this.createRuleTreeViewer(pParent);
- layout.numColumns = this.getViewer().getTree().getColumnCount();
- LOGGER.finest("End createPartControl method");
- }
-
- /**
- *
- */
- public void update() {
- for (final ViewerFilter filter : this.viewer.getFilters()) {
- if (filter instanceof IUpdatableAnalysisFilter) {
- ((IUpdatableAnalysisFilter) filter).update(searchString, showWarning, showError);
- }
+ }
+ return res;
}
- viewer.refresh();
- }
- /**
- * This method create the viewer, which is a tree table.
- *
- * @param parent
- * the parent composite
- */
- private void createRuleTreeViewer(final Composite parent) {
- LOGGER.finest("Begin createViewer method");
-
- // Defining overall style for TreeViewer
- final int scrollStyle = SWT.H_SCROLL | SWT.V_SCROLL;
- final int selecStyle = SWT.MULTI | SWT.FULL_SELECTION;
- final int style = scrollStyle | selecStyle;
- this.viewer = new RuleTreeViewer(parent, style | SWT.FILL);
- // Make headers and lines of the tree visible
- final Tree tree = this.viewer.getTree();
- tree.setHeaderVisible(true);
- tree.setLinesVisible(true);
-
- // Expand the tree
- this.viewer.setAutoExpandLevel(1);
-
- // Add selection provider which allows to listen to each
- // selection made on this viewer.
- this.getSite().setSelectionProvider(this.viewer);
-
- // TODO: verify XML
- // Fill tree with values from xml
- // this.fillView();
-
- // Layout the viewer
- final GridData gridData = new GridData();
- gridData.verticalAlignment = GridData.FILL;
- gridData.horizontalSpan = this.viewer.getTree().getColumnCount();
- gridData.grabExcessHorizontalSpace = true;
- gridData.grabExcessVerticalSpace = true;
- gridData.horizontalAlignment = GridData.FILL;
- this.viewer.getTree().setLayoutData(gridData);
-
- /*
- * Creating a filter using field search & check buttons Warning and
- * Error.
- *
- * Show only element selected by the user.
- */
- final RuleViewerFilter ruleFilter = new RuleViewerFilter();
- viewer.addFilter(ruleFilter);
-
- LOGGER.finest("End createViewer method");
+ });
- }
+ if (this.treeViewerType.equals(FILE_TREE_VIEWER_TYPE)
+ && ((FileTreeViewerContentProvider) this.viewer.getContentProvider()).getConverter()
+ .getInputs() != null) {
+ for (final Violation value : ((FileTreeViewerContentProvider) this.getViewer()
+ .getContentProvider()).getConverter().getInputs()) {
+ listInputs.add(value);
+ }
+ }
+ if (this.treeViewerType.equals(RULE_TREE_VIEWER_TYPE)
+ && ((RuleTreeViewerContentProvider) this.viewer.getContentProvider()).getConverter()
+ .getInputs() != null) {
+ for (final Violation value : ((RuleTreeViewerContentProvider) this.getViewer()
+ .getContentProvider()).getConverter().getInputs()) {
+ listInputs.add(value);
+ }
+ }
+ for (final Violation value : violations) {
+ listInputs.add(value);
+ }
- /**
- * This method create the viewer, which is a tree table.
- *
- * @param pParent
- * the parent composite
- */
- private void createFileTreeViewer(final Composite pParent) {
- LOGGER.finest("Begin createViewer method");
-
- // Defining overall style for TreeViewer
- final int scrollStyle = SWT.H_SCROLL | SWT.V_SCROLL;
- final int selecStyle = SWT.MULTI | SWT.FULL_SELECTION;
- final int style = scrollStyle | selecStyle;
- this.viewer = new FileTreeViewer(pParent, style | SWT.FILL);
- // Make headers and lines of the tree visible
- final Tree tree = this.viewer.getTree();
- tree.setHeaderVisible(true);
- tree.setLinesVisible(true);
-
- // Expand the tree
- this.viewer.setAutoExpandLevel(1);
-
- // Add selection provider which allows to listen to each
- // selection made on this viewer.
- this.getSite().setSelectionProvider(this.viewer);
-
- // TODO: verify XML
- // Fill tree with values from xml
- // this.fillView();
-
- // Layout the viewer
- final GridData gridData = new GridData();
- gridData.verticalAlignment = GridData.FILL;
- gridData.horizontalSpan = this.viewer.getTree().getColumnCount();
- gridData.grabExcessHorizontalSpace = true;
- gridData.grabExcessVerticalSpace = true;
- gridData.horizontalAlignment = GridData.FILL;
- this.viewer.getTree().setLayoutData(gridData);
-
- /*
- * Creating a filter using field search & check buttons Warning and
- * Error.
- *
- * Show only element selected by the user.
- */
- final FileTreeViewerFilter fileFilter = new FileTreeViewerFilter();
- this.viewer.addFilter(fileFilter);
-
- LOGGER.finest("End createViewer method");
+ this.analysisResults = listInputs;
+ this.getViewer().setInput(listInputs.toArray(new Violation[listInputs.size()]));
}
-
- /**
- * Fill view with the values from the xml file
- */
- protected void fillView() {
- // TODO Fille view with XML file
+ this.getViewer().refresh();
+ try {
+ this.insertMarkers();
+ } catch (InvocationTargetException exception) {
+ LOGGER.log(Level.WARNING, exception.getClass() + " : " + exception.getMessage(), exception);
+ MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
+ "Internal Error", "Contact support service : \n" + exception.getMessage());
+ } catch (InterruptedException exception) {
+ LOGGER.log(Level.WARNING, exception.getClass() + " : " + exception.getMessage(), exception);
+ MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
+ "Internal Error", "Contact support service : \n" + exception.getMessage());
}
- /**
- * Display violations found during analysis in the violations view.
- *
- * @param violations
- * the violations to display
- * @param pDate
- * The date of the analysis
- * @param pAuthor
- * The user who ran the analysis
- * @param pProject
- * The project selected while running the analysis
- */
- public void display(final List violations, final IProject pProject,
- final String pAuthor, final String pDate) {
- LOGGER.finest("Begin display(Descriptor[]) method");
- this.analysisProject = pProject;
- this.author = pAuthor;
- this.date = pDate;
-
- synchronized (this) {
- final Set listInputs = new TreeSet(new Comparator() {
-
- @Override
- public int compare(final Violation viol1, final Violation viol2) {
- int res = viol1.getRuleName().split("\\.")[0]
- .compareTo(viol2.getRuleName().split("\\.")[0]);
- if (res == 0) {
- res = viol1.getRuleName().split("\\.")[1]
- .compareTo(viol2.getRuleName().split("\\.")[1]);
- if (res == 0) {
- res = viol1.getRuleName().split("\\.")[2]
- .compareTo(viol2.getRuleName().split("\\.")[2]);
- if (res == 0) {
- res = viol1.getFile().getAbsolutePath()
- .compareTo(viol2.getFile().getAbsolutePath());
- if (res == 0) {
- res = viol1.getLine().compareTo(viol2.getLine());
- if (res == 0) {
- res = viol1.getLocation().compareTo(viol2.getLocation());
- }
- }
- }
- }
- }
- return res;
- }
+ LOGGER.finest("End display(Descriptor[]) method");
+ }
+
+ /**
+ * This method insert for each violation detected a new marker on the line of the violation.
+ *
+ * @throws InterruptedException
+ * @throws InvocationTargetException
+ */
+ public void insertMarkers() throws InvocationTargetException, InterruptedException {
+ LOGGER.finest("begin method insertMarkers");
+ final ProgressMonitorDialog pmdialog = new ProgressMonitorDialog(
+ PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell());
+ pmdialog.run(true, true, new WorkspaceModifyOperation() {
+
+ @Override
+ protected void execute(final IProgressMonitor monitor)
+ throws CoreException, InvocationTargetException, InterruptedException {
+ // create all my markers here
- });
+ try {
- if (this.treeViewerType.equals(FILE_TREE_VIEWER_TYPE)
- && ((FileTreeViewerContentProvider) this.viewer.getContentProvider())
- .getConverter().getInputs() != null) {
- for (final Violation value : ((FileTreeViewerContentProvider) this.getViewer()
- .getContentProvider()).getConverter().getInputs()) {
- listInputs.add(value);
- }
- }
- if (this.treeViewerType.equals(RULE_TREE_VIEWER_TYPE)
- && ((RuleTreeViewerContentProvider) this.viewer.getContentProvider())
- .getConverter().getInputs() != null) {
- for (final Violation value : ((RuleTreeViewerContentProvider) this.getViewer()
- .getContentProvider()).getConverter().getInputs()) {
- listInputs.add(value);
- }
+ final HashSet cleanedFiles = new HashSet();
+ String ruleName, criticity, message = "Violation detected here.";
+ Integer line;
+ IFile file;
+ for (final Violation violation : analysisResults) {
+ if (violation.getMessage().isEmpty()) {
+ message = "No message in description. Please refer to CNES RNC.";
+ } else {
+ message = violation.getMessage();
}
- for (final Violation value : violations) {
- listInputs.add(value);
+ ruleName = violation.getRuleName();
+ criticity = PlatformUI.getPreferenceStore()
+ .getString(violation.getRuleId() + ".Criticity");
+ line = violation.getLine();
+ file = ResourcesPlugin.getWorkspace().getRoot()
+ .getFileForLocation(new Path(violation.getFile().getAbsolutePath())
+ .makeRelativeTo(ResourcesPlugin.getWorkspace().getRoot().getFullPath()));
+
+ // If the file already has marker of type violations
+ // then we clean the file once
+ if (file != null && !cleanedFiles.contains(file)) {
+ cleanedFiles.add(file);
+ file.deleteMarkers("fr.cnes.analysis.tools.ui.markers.ViolationErrorMarker", true, 1);
+ file.deleteMarkers("fr.cnes.analysis.tools.ui.markers.ViolationWarningMarker", true,
+ 1);
}
+ // Then we add the new markers
+ if ("Error".equals(criticity)) {
- this.analysisResults = listInputs;
-
- this.getViewer().setInput(listInputs.toArray(new Violation[listInputs.size()]));
- }
- this.getViewer().refresh();
- try {
- this.insertMarkers();
- } catch (InvocationTargetException exception) {
- LOGGER.log(Level.WARNING, exception.getClass() + " : " + exception.getMessage(),
- exception);
- MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
- "Internal Error", "Contact support service : \n" + exception.getMessage());
- } catch (InterruptedException exception) {
- LOGGER.log(Level.WARNING, exception.getClass() + " : " + exception.getMessage(),
- exception);
- MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
- "Internal Error", "Contact support service : \n" + exception.getMessage());
- }
-
- LOGGER.finest("End display(Descriptor[]) method");
- }
+ // If the criticity is at level "Error" then we pop
+ // a
+ // new ViolationErrorMarker.
+ ViolationErrorMarker.createMarker(file, line, ruleName, ruleName + " | " + message);
- /**
- * This method insert for each violation detected a new marker on the line
- * of the violation.
- *
- * @throws InterruptedException
- * @throws InvocationTargetException
- */
- public void insertMarkers() throws InvocationTargetException, InterruptedException {
- LOGGER.finest("begin method insertMarkers");
- final ProgressMonitorDialog pmdialog = new ProgressMonitorDialog(
- PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell());
- pmdialog.run(true, true, new WorkspaceModifyOperation() {
-
- @Override
- protected void execute(final IProgressMonitor monitor)
- throws CoreException, InvocationTargetException, InterruptedException {
- // create all my markers here
-
- try {
-
- final HashSet cleanedFiles = new HashSet();
- String ruleName, criticity, message = "Violation detected here.";
- Integer line;
- IFile file;
- for (final Violation violation : analysisResults) {
- if (violation.getMessage().isEmpty()) {
- message = "No message in description. Please refer to CNES RNC.";
- } else {
- message = violation.getMessage();
- }
- ruleName = violation.getRuleName();
- criticity = PlatformUI.getPreferenceStore()
- .getString(violation.getRuleId() + ".Criticity");
- line = violation.getLine();
- file = ResourcesPlugin.getWorkspace().getRoot()
- .getFileForLocation(new Path(violation.getFile().getAbsolutePath()).makeRelativeTo(ResourcesPlugin.getWorkspace().getRoot().getFullPath()));
-
- // If the file already has marker of type violations
- // then we clean the file once
- if (file != null && !cleanedFiles.contains(file)) {
- cleanedFiles.add(file);
- file.deleteMarkers(
- "fr.cnes.analysis.tools.ui.markers.ViolationErrorMarker", true,
- 1);
- file.deleteMarkers(
- "fr.cnes.analysis.tools.ui.markers.ViolationWarningMarker",
- true, 1);
- }
- // Then we add the new markers
- if ("Error".equals(criticity)) {
-
- // If the criticity is at level "Error" then we pop
- // a
- // new ViolationErrorMarker.
- ViolationErrorMarker.createMarker(file, line, ruleName,
- ruleName + " | " + message);
-
- } else if ("Warning".equals(criticity)) {
- // else if the criticity is set on Warning then we
- // pop a ViolationWarningMarker
- // new ViolationErrorDecorator();
- ViolationWarningMarker.createMarker(file, line, ruleName,
- ruleName + " | " + message);
-
- }
-
- }
- } catch (final CoreException exception) {
- LOGGER.log(Level.FINER, exception.getClass() + " : " + exception.getMessage(),
- exception);
- MessageDialog.openError(
- PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
- "Marker problem", exception.getMessage());
+ } else if ("Warning".equals(criticity)) {
+ // else if the criticity is set on Warning then we
+ // pop a ViolationWarningMarker
+ // new ViolationErrorDecorator();
+ ViolationWarningMarker.createMarker(file, line, ruleName, ruleName + " | " + message);
- }
}
- });
- // One time all markers have been insert, we refresh all
- // decorators.
- final IDecoratorManager manager = PlatformUI.getWorkbench().getDecoratorManager();
+ }
+ } catch (final CoreException exception) {
+ LOGGER.log(Level.FINER, exception.getClass() + " : " + exception.getMessage(), exception);
+ MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
+ "Marker problem", exception.getMessage());
- manager.update("fr.cnes.analysis.tools.ui.decorators.violationwarningdecorator");
- manager.update("fr.cnes.analysis.tools.ui.decorators.violationerrordecorator");
+ }
+ }
+ });
+ // One time all markers have been insert, we refresh all
+ // decorators.
+
+ final IDecoratorManager manager = PlatformUI.getWorkbench().getDecoratorManager();
+
+ manager.update("fr.cnes.analysis.tools.ui.decorators.violationwarningdecorator");
+ manager.update("fr.cnes.analysis.tools.ui.decorators.violationerrordecorator");
+
+ LOGGER.finest("end method insertMarkers");
+
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.ui.part.WorkbenchPart#setFocus()
+ */
+ @Override
+ public void setFocus() {
+ this.viewer.getControl().setFocus();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see fr.cnes.analysis.tools.ui.view.IExportableView#exportToCSV(java.io.File)
+ */
+ @Override
+ public void exportToCSV(final File file) throws IOException {
+ final FileWriter out = new FileWriter(file);
+ out.write("Rule, File, Location, Value, Criticity\n");
+ for (final Violation violation : (Violation[]) this.getViewer().getInput()) {
+ out.write(violation.getRuleName() + "," + violation.getFile().getAbsolutePath() + ","
+ + violation.getLocation() + "," + violation.getLine().toString() + "\n");
+ }
- LOGGER.finest("end method insertMarkers");
+ out.close();
- }
+ }
+ /*
+ * (non-Javadoc)
+ *
+ * @see fr.cnes.analysis.tools.ui.view.IExportableView#exportToXML(java.io.File)
+ */
+ @Override
+ public void exportToXML(final File file) throws IOException {
+ LOGGER.finest("begin method toXML");
+ final List attributes = new ArrayList();
+ final List resultAttributes = new ArrayList();
/*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.part.WorkbenchPart#setFocus()
+ * Creation of the root element
*/
- @Override
- public void setFocus() {
- this.viewer.getControl().setFocus();
- }
- /*
- * (non-Javadoc)
- *
- * @see
- * fr.cnes.analysis.tools.ui.view.IExportableView#exportToCSV(java.io.File)
- */
- @Override
- public void exportToCSV(final File file) throws IOException {
- final FileWriter out = new FileWriter(file);
- out.write("Rule, File, Location, Value, Criticity\n");
- for (final Violation violation : (Violation[]) this.getViewer().getInput()) {
- out.write(violation.getRuleName() + "," + violation.getFile().getAbsolutePath()
- + "," + violation.getLocation() + "," + violation.getLine().toString() + "\n");
+ final Element analysisProjectElement = new Element("analysisProject");
+ analysisProjectElement.setAttribute(new Attribute("analysisProjectName", "unknown"));
+ final Document document = new Document(analysisProjectElement);
+
+ // BEGINNING OF SEQUENCE
+ // --
+
+ final Element analysisInformation = new Element("analysisInformations");
+ attributes.add(new Attribute("analysisConfigurationId", "standard"));
+ attributes.add(new Attribute("analysisDate", this.date));
+ attributes.add(new Attribute("author", this.author));
+
+ analysisInformation.setAttributes(attributes);
+ document.getRootElement().addContent(analysisInformation);
+ // --
+ for (final Violation violation : this.analysisResults) {
+ attributes.clear();
+
+ // --
+ // Note : We take only the last segment of the filepath to
+ // get
+ // the filename.
+ // --
+ final String language = this.getFileExtension(file.getAbsolutePath());
+ final String fileName = violation.getFile().getAbsolutePath();
+ // The analysisFile element is being added only and only if it's not
+ // already in the XML document.
+ boolean analysisFileMarked = false;
+ for (final Element element : document.getRootElement().getChildren("analysisFile")) {
+ if (element.getAttributeValue("fileName").equals(fileName)
+ && element.getAttributeValue("language").equals(language)) {
+ analysisFileMarked = true;
}
-
- out.close();
-
+ }
+ if (!analysisFileMarked) {
+ final Element analysisFile = new Element("analysisFile");
+ attributes.add(new Attribute("language", language));
+ attributes.add(new Attribute("fileName", fileName));
+ analysisFile.setAttributes(attributes);
+ document.getRootElement().addContent(analysisFile);
+ }
}
-
- /*
- * (non-Javadoc)
- *
- * @see
- * fr.cnes.analysis.tools.ui.view.IExportableView#exportToXML(java.io.File)
- */
- @Override
- public void exportToXML(final File file) throws IOException {
- LOGGER.finest("begin method toXML");
- final List attributes = new ArrayList();
- final List resultAttributes = new ArrayList();
- /*
- * Creation of the root element
- */
-
- final Element analysisProjectElement = new Element("analysisProject");
- analysisProjectElement
- .setAttribute(new Attribute("analysisProjectName", this.analysisProject.getName()));
- final Document document = new Document(analysisProjectElement);
-
- // BEGINNING OF SEQUENCE
- // --
-
- final Element analysisInformation = new Element("analysisInformations");
- attributes.add(new Attribute("analysisConfigurationId", "standard"));
- attributes.add(new Attribute("analysisDate", this.date));
- attributes.add(new Attribute("author", this.author));
-
- analysisInformation.setAttributes(attributes);
- document.getRootElement().addContent(analysisInformation);
- // --
- for (final Violation violation : this.analysisResults) {
- attributes.clear();
-
- // --
- // Note : We take only the last segment of the filepath to
- // get
- // the filename.
- // --
- final String language = this.getFileExtension(file.getAbsolutePath());
- final String fileName = violation.getFile().getAbsolutePath();
- // The analysisFile element is being added only and only if it's not
- // already in the XML document.
- boolean analysisFileMarked = false;
- for (final Element element : document.getRootElement().getChildren("analysisFile")) {
- if (element.getAttributeValue("fileName").equals(fileName)
- && element.getAttributeValue("language").equals(language)) {
- analysisFileMarked = true;
- }
- }
- if (!analysisFileMarked) {
- final Element analysisFile = new Element("analysisFile");
- attributes.add(new Attribute("language", language));
- attributes.add(new Attribute("fileName", fileName));
- analysisFile.setAttributes(attributes);
- document.getRootElement().addContent(analysisFile);
- }
+ Element result, analysisRule = null;
+ int resultId = 1;
+ for (final Violation violation : this.analysisResults) {
+ boolean elementAlreadyExisting = false;
+ Element existingElement = null;
+ for (final Element element : document.getRootElement().getChildren("analysisRule")) {
+ for (final Attribute attribute : element.getAttributes()) {
+ if (attribute.getName().equals("analysisRuleId")
+ && attribute.getValue().equals(violation.getRuleId())) {
+ elementAlreadyExisting = true;
+ existingElement = element;
+ }
}
- Element result, analysisRule = null;
- int resultId = 1;
- for (final Violation violation : this.analysisResults) {
- boolean elementAlreadyExisting = false;
- Element existingElement = null;
- for (final Element element : document.getRootElement().getChildren("analysisRule")) {
- for (final Attribute attribute : element.getAttributes()) {
- if (attribute.getName().equals("analysisRuleId")
- && attribute.getValue().equals(violation.getRuleId())) {
- elementAlreadyExisting = true;
- existingElement = element;
- }
- }
- }
- if (!elementAlreadyExisting || existingElement == null) {
- analysisRule = new Element("analysisRule");
- analysisRule.setAttribute(new Attribute("analysisRuleId", violation.getRuleName()));
- } else {
- analysisRule = existingElement;
- }
-
- result = new Element("result");
- resultAttributes.clear();
- // no justification for now
- // no outputDetail for now neither
-
- resultAttributes.add(new Attribute("resultId", Integer.toString(resultId)));
- resultId++;
- resultAttributes.add(new Attribute("fileName", violation.getFile().getAbsolutePath()));
- resultAttributes.add(new Attribute("resultLine", violation.getLine().toString()));
-
- /*
- * The location and message are defined in violations by only one
- * attribute (String) made this way: [Location -> Message], so we
- * split it to get the two exploitable strings.
- */
- resultAttributes.add(new Attribute("resultNamePlace", violation.getLocation()));
- /*
- * The result message is defined by the XSD as a sequence of element
- * resultMessage (not an attribute).
- */
- final Element resultMessage = new Element("resultMessage");
-
- resultMessage.addContent(violation.getMessage());
-
- result.addContent(resultMessage);
- result.setAttributes(resultAttributes);
- /*
- * The result is being added to the analysisRule element;
- */
- analysisRule.addContent(result);
-
- /*
- * If the rule analysisRule was already in the document, then it's
- * not necessary to add it again in the document, however if it's
- * the first time that this analysisRule appear in the document we
- * have to add it to the Root element.
- */
- if (!elementAlreadyExisting) {
- document.getRootElement().addContent(analysisRule);
- }
- }
-
- final XMLOutputter xmlOutput = new XMLOutputter();
- xmlOutput.setFormat(Format.getPrettyFormat());
- final FileOutputStream fileOutput = new FileOutputStream(file);
+ }
+ if (!elementAlreadyExisting || existingElement == null) {
+ analysisRule = new Element("analysisRule");
+ analysisRule.setAttribute(new Attribute("analysisRuleId", violation.getRuleName()));
+ } else {
+ analysisRule = existingElement;
+ }
+
+ result = new Element("result");
+ resultAttributes.clear();
+ // no justification for now
+ // no outputDetail for now neither
+
+ resultAttributes.add(new Attribute("resultId", Integer.toString(resultId)));
+ resultId++;
+ resultAttributes.add(new Attribute("fileName", violation.getFile().getAbsolutePath()));
+ resultAttributes.add(new Attribute("resultLine", violation.getLine().toString()));
+
+ /*
+ * The location and message are defined in violations by only one attribute (String) made this
+ * way: [Location -> Message], so we split it to get the two exploitable strings.
+ */
+ resultAttributes.add(new Attribute("resultNamePlace", violation.getLocation()));
+ /*
+ * The result message is defined by the XSD as a sequence of element resultMessage (not an
+ * attribute).
+ */
+ final Element resultMessage = new Element("resultMessage");
+
+ resultMessage.addContent(violation.getMessage());
+
+ result.addContent(resultMessage);
+ result.setAttributes(resultAttributes);
+ /*
+ * The result is being added to the analysisRule element;
+ */
+ analysisRule.addContent(result);
+
+ /*
+ * If the rule analysisRule was already in the document, then it's not necessary to add it
+ * again in the document, however if it's the first time that this analysisRule appear in the
+ * document we have to add it to the Root element.
+ */
+ if (!elementAlreadyExisting) {
+ document.getRootElement().addContent(analysisRule);
+ }
+ }
- xmlOutput.output(document, fileOutput);
- fileOutput.close();
- this.verifyXMLandXSDValidity(file);
+ final XMLOutputter xmlOutput = new XMLOutputter();
+ xmlOutput.setFormat(Format.getPrettyFormat());
+ final FileOutputStream fileOutput = new FileOutputStream(file);
- LOGGER.finest("end method toXML");
+ xmlOutput.output(document, fileOutput);
+ fileOutput.close();
+ this.verifyXMLandXSDValidity(file);
- }
-
- /**
- * @param fileName
- * @return The extension name of the file
- */
- private String getFileExtension(String fileName) {
- String extension = "unknown";
+ LOGGER.finest("end method toXML");
- int i = fileName.lastIndexOf('.');
- int p = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));
+ }
- if (i > p) {
- extension = fileName.substring(i+1);
- }
- return extension;
- }
+ /**
+ * @param fileName
+ * @return The extension name of the file
+ */
+ private String getFileExtension(String fileName) {
+ String extension = "unknown";
- /**
- * @param file
- * The XML file to validate
- *
- * @return Returns if XSD is W3C valid and XML is W3C valid and respecting
- * XSD specifications.
- *
- * @throws IOException
- * when XSD file can't be read.
- */
- public boolean verifyXMLandXSDValidity(final File file) throws IOException {
- LOGGER.finest("begin method verifyXMLandXSDValidity");
- boolean validity;
- try {
- final SchemaFactory factory = SchemaFactory
- .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
-
- // TODO : Find better way to locate the XSD file in resources
- final URL globalPath = new URL(
- this.getClass().getProtectionDomain().getCodeSource().getLocation()
- + MetricsView.XSD_FILEPATH);
-
- final Schema dda = factory.newSchema(globalPath);
-
- final Validator validator = dda.newValidator();
- validator.validate(new StreamSource(file));
- validity = true;
- } catch (SAXException exception) {
- validity = false;
- exception.printStackTrace();
- }
- LOGGER.finest("end method verifyXMLandXSDValidity");
- return validity;
+ int i = fileName.lastIndexOf('.');
+ int p = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));
+ if (i > p) {
+ extension = fileName.substring(i + 1);
}
-
- /**
- * This method will clear the message and make it appear on the view.
- *
- * @throws EmptyProviderException
- * when source provider to determine view type is not found (not
- * necessarily used)
- */
- public void clear() throws EmptyProviderException {
- this.getViewer().setInput(new Violation[0]);
- this.getViewer().refresh();
+ return extension;
+ }
+
+ /**
+ * @param file
+ * The XML file to validate
+ *
+ * @return Returns if XSD is W3C valid and XML is W3C valid and respecting XSD specifications.
+ *
+ * @throws IOException
+ * when XSD file can't be read.
+ */
+ public boolean verifyXMLandXSDValidity(final File file) throws IOException {
+ LOGGER.finest("begin method verifyXMLandXSDValidity");
+ boolean validity;
+ try {
+ final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
+
+ // TODO : Find better way to locate the XSD file in resources
+ final URL globalPath = new URL(
+ this.getClass().getProtectionDomain().getCodeSource().getLocation()
+ + MetricsView.XSD_FILEPATH);
+
+ final Schema dda = factory.newSchema(globalPath);
+
+ final Validator validator = dda.newValidator();
+ validator.validate(new StreamSource(file));
+ validity = true;
+ } catch (SAXException exception) {
+ validity = false;
+ exception.printStackTrace();
}
-
- /**
- * @return the Treeviewer type
- */
- public String getTreeViewerType() {
- return this.treeViewerType;
+ LOGGER.finest("end method verifyXMLandXSDValidity");
+ return validity;
+
+ }
+
+ /**
+ * This method will clear the message and make it appear on the view.
+ *
+ * @throws EmptyProviderException
+ * when source provider to determine view type is not found (not necessarily used)
+ */
+ public void clear() throws EmptyProviderException {
+ this.getViewer().setInput(new Violation[0]);
+ this.getViewer().refresh();
+ }
+
+ /**
+ * @return the Treeviewer type
+ */
+ public String getTreeViewerType() {
+ return this.treeViewerType;
+ }
+
+ /**
+ * Set the TreeViewerType by modifying the attribute and also processing to dispose if necessary
+ * the old TreeViewer and create a new one with the type requested.
+ *
+ * @param name
+ * Name or identifier of the TreeViewerType requested.
+ */
+ public void setTreeViewerType(final String name) {
+ if (!this.treeViewerType.equals(name)) {
+ // Disposal of the old TreeViewer
+ this.viewer.getControl().dispose();
+ if (name.equals(FILE_TREE_VIEWER_TYPE)) {
+ this.createFileTreeViewer(this.parent);
+ // We reinsert inputs from previous TreeViewer in the current
+ // one
+ this.getViewer()
+ .setInput(this.analysisResults.toArray(new Violation[this.analysisResults.size()]));
+ this.treeViewerType = name;
+
+ } else if (name.equals(RULE_TREE_VIEWER_TYPE)) {
+ this.createRuleTreeViewer(this.parent);
+ // We reinsert inputs from previous TreeViewer in the current
+ // one
+ this.getViewer()
+ .setInput(this.analysisResults.toArray(new Violation[this.analysisResults.size()]));
+ this.treeViewerType = name;
+
+ }
+ // This call is necessary to refresh the table in the parent
+ // Composite.
+ this.parent.layout();
}
- /**
- * Set the TreeViewerType by modifying the attribute and also processing to
- * dispose if necessary the old TreeViewer and create a new one with the
- * type requested.
- *
- * @param name
- * Name or identifier of the TreeViewerType requested.
- */
- public void setTreeViewerType(final String name) {
- if (!this.treeViewerType.equals(name)) {
- // Disposal of the old TreeViewer
- this.viewer.getControl().dispose();
- if (name.equals(FILE_TREE_VIEWER_TYPE)) {
- this.createFileTreeViewer(this.parent);
- // We reinsert inputs from previous TreeViewer in the current
- // one
- this.getViewer().setInput(
- this.analysisResults.toArray(new Violation[this.analysisResults.size()]));
- this.treeViewerType = name;
-
- } else if (name.equals(RULE_TREE_VIEWER_TYPE)) {
- this.createRuleTreeViewer(this.parent);
- // We reinsert inputs from previous TreeViewer in the current
- // one
- this.getViewer().setInput(
- this.analysisResults.toArray(new Violation[this.analysisResults.size()]));
- this.treeViewerType = name;
-
- }
- // This call is necessary to refresh the table in the parent
- // Composite.
- this.parent.layout();
- }
-
- }
+ }
}
diff --git a/fr.cnes.analysis.tools.ui/uml/handler_omar.ucls b/fr.cnes.analysis.tools.ui/uml/handler_omar.ucls
deleted file mode 100755
index f8629721..00000000
--- a/fr.cnes.analysis.tools.ui/uml/handler_omar.ucls
+++ /dev/null
@@ -1,47 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file