diff --git a/plugins/org.polarsys.chess.checkers/about.html b/plugins/org.polarsys.chess.checkers/about.html new file mode 100644 index 0000000000000000000000000000000000000000..164f781a8fd2195f87c3d3d49946d56bce58992f --- /dev/null +++ b/plugins/org.polarsys.chess.checkers/about.html @@ -0,0 +1,36 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml"> +<head> +<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> +<title>About</title> +</head> +<body lang="EN-US"> + <h2>About This Content</h2> + + <p>November 30, 2017</p> + <h3>License</h3> + + <p> + The Eclipse Foundation makes available all content in this plug-in + ("Content"). Unless otherwise indicated below, the Content + is provided to you under the terms and conditions of the Eclipse + Public License Version 2.0 ("EPL"). A copy of the EPL is + available at <a href="http://www.eclipse.org/legal/epl-2.0">http://www.eclipse.org/legal/epl-2.0</a>. + For purposes of the EPL, "Program" will mean the Content. + </p> + + <p> + If you did not receive this Content directly from the Eclipse + Foundation, the Content is being redistributed by another party + ("Redistributor") and different terms and conditions may + apply to your use of any object code in the Content. Check the + Redistributor's license that was provided with the Content. If no such + license exists, contact the Redistributor. Unless otherwise indicated + below, the terms and conditions of the EPL still apply to any source + code in the Content and such source code may be obtained at <a + href="http://www.eclipse.org/">http://www.eclipse.org</a>. + </p> + +</body> +</html> \ No newline at end of file diff --git a/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/checkerManager/Checker.java b/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/checkerManager/Checker.java index 6b0973d9d074be3f3480b8fe297f72f5269916bd..6e80da96a8811dd60b5e2a9be43486fc1034c60c 100644 --- a/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/checkerManager/Checker.java +++ b/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/checkerManager/Checker.java @@ -1,136 +1,143 @@ -package org.polarsys.chess.checkers.core.checkerManager; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -import org.apache.log4j.Logger; -import org.eclipse.core.resources.IFile; -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; -import org.eclipse.emf.workspace.util.WorkspaceSynchronizer; -import org.polarsys.chess.contracts.profile.chesscontract.util.EntityUtil; - -public abstract class Checker { - - private static final Logger logger = Logger.getLogger(Checker.class); - -// private static String pluginID = "org.polarsys.chess.checkers"; - - public final String unifiedName; - protected final Set<String> checkerTags; - protected final int registerPriority; - private ArrayList<Exception> errors = new ArrayList<Exception>(); - - protected Checker(String unifiedName, Set<String> checkerTags) { - this(unifiedName, checkerTags, 0); - } - - public Checker(String unifiedName, Set<String> checkerTags, int registerPriority) { - - this.unifiedName = unifiedName; - this.checkerTags = checkerTags; - this.registerPriority = registerPriority; - - CheckerManager checkerManager = org.polarsys.chess.checkers.Activator.getCheckerManager(); - logger.debug("register " + unifiedName); - checkerManager.getCheckersContainter().register(this); - } - - public abstract List<CheckerMessage> check(IProgressMonitor monitor) throws Exception; - - public abstract void init() throws Exception; - - public void asyncCheck(boolean isFirstChecker) throws Exception { - - CheckerManager checkerManager = org.polarsys.chess.checkers.Activator.getCheckerManager(); - - org.eclipse.uml2.uml.Package pack = EntityUtil.getInstance().getCurrentSystemView(); - if(pack==null){ - IFile file = EntityUtil.getInstance().getCurrentIFile(); - System.out.println("file: "+file); - EntityUtil.getInstance().openCurrentModelIntoEditor(file); - } - - IFile iFile = WorkspaceSynchronizer.getFile(EntityUtil.getInstance().getCurrentSystemView().eResource()); - init(); - - logger.debug("running checker: "+unifiedName); - Job job = new Job("Checker Manager: " + unifiedName) { - @Override - protected IStatus run(IProgressMonitor monitor) { - try { - errors = new ArrayList<Exception>(); - List<CheckerMessage> messages = check(monitor); - if (messages != null) { -// checkerManager.deleteMarkers(iFile, unifiedName); - checkerManager.deleteProjectMarkers(iFile.getProject(), unifiedName); - checkerManager.addMessages(unifiedName, messages); - } - } catch (Exception e) { - e.printStackTrace(); - logger.error("Checker '"+unifiedName+"' exception: "+e.getMessage()); - return Status.CANCEL_STATUS; - } - if (monitor.isCanceled()) { - logger.warn("checker '" + unifiedName + "' isCanceled"); - return Status.CANCEL_STATUS; - } - // use this to open a Shell in the UI thread - return Status.OK_STATUS; - } - }; - - job.setUser(isFirstChecker); - job.schedule(); - } - -// /** -// * Recursively returns all the files in the given container -// * @param container the IContainer -// * @return -// */ -// private List<IFile> getProjectFiles(IContainer container) { -// final List<IFile> files = new ArrayList<IFile>(); -// try { -// for (IResource member : container.members()) { -// if (member instanceof IContainer) { -// files.addAll(getProjectFiles((IContainer) member)); -// } else if (member instanceof IFile) { -// files.add((IFile) member); -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return files; -// } - - /* - * private void syncWithUI(Shell shell) { Display.getDefault().asyncExec(new - * Runnable() { public void run() { MessageDialog.openInformation(shell, - * "message", "completed!"); } }); } - */ - - public boolean belongsTo(Set<String> checkersTags) { - for (String tag : checkersTags) { - if (checkerTags.contains(tag)) - return true; - } - return false; - } - - public String getUnifiedName() { - return unifiedName; - } - - public Set<String> getCheckerTags() { - return checkerTags; - } - - public void addError(Exception e){ - errors.add(e); - } -} \ No newline at end of file +/******************************************************************************* + * Copyright (C) 2020 Fondazione Bruno Kessler. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v2.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v20.html + ******************************************************************************/ +package org.polarsys.chess.checkers.core.checkerManager; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import org.apache.log4j.Logger; +import org.eclipse.core.resources.IFile; +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; +import org.eclipse.emf.workspace.util.WorkspaceSynchronizer; +import org.polarsys.chess.contracts.profile.chesscontract.util.EntityUtil; + +public abstract class Checker { + + private static final Logger logger = Logger.getLogger(Checker.class); + +// private static String pluginID = "org.polarsys.chess.checkers"; + + public final String unifiedName; + protected final Set<String> checkerTags; + protected final int registerPriority; + private ArrayList<Exception> errors = new ArrayList<Exception>(); + + protected Checker(String unifiedName, Set<String> checkerTags) { + this(unifiedName, checkerTags, 0); + } + + public Checker(String unifiedName, Set<String> checkerTags, int registerPriority) { + + this.unifiedName = unifiedName; + this.checkerTags = checkerTags; + this.registerPriority = registerPriority; + + CheckerManager checkerManager = org.polarsys.chess.checkers.Activator.getCheckerManager(); + logger.debug("register " + unifiedName); + checkerManager.getCheckersContainter().register(this); + } + + public abstract List<CheckerMessage> check(IProgressMonitor monitor) throws Exception; + + public abstract void init() throws Exception; + + public void asyncCheck(boolean isFirstChecker) throws Exception { + + CheckerManager checkerManager = org.polarsys.chess.checkers.Activator.getCheckerManager(); + + org.eclipse.uml2.uml.Package pack = EntityUtil.getInstance().getCurrentSystemView(); + if(pack==null){ + IFile file = EntityUtil.getInstance().getCurrentIFile(); + System.out.println("file: "+file); + EntityUtil.getInstance().openCurrentModelIntoEditor(file); + } + + IFile iFile = WorkspaceSynchronizer.getFile(EntityUtil.getInstance().getCurrentSystemView().eResource()); + init(); + + logger.debug("running checker: "+unifiedName); + Job job = new Job("Checker Manager: " + unifiedName) { + @Override + protected IStatus run(IProgressMonitor monitor) { + try { + errors = new ArrayList<Exception>(); + List<CheckerMessage> messages = check(monitor); + if (messages != null) { +// checkerManager.deleteMarkers(iFile, unifiedName); + checkerManager.deleteProjectMarkers(iFile.getProject(), unifiedName); + checkerManager.addMessages(unifiedName, messages); + } + } catch (Exception e) { + e.printStackTrace(); + logger.error("Checker '"+unifiedName+"' exception: "+e.getMessage()); + return Status.CANCEL_STATUS; + } + if (monitor.isCanceled()) { + logger.warn("checker '" + unifiedName + "' isCanceled"); + return Status.CANCEL_STATUS; + } + // use this to open a Shell in the UI thread + return Status.OK_STATUS; + } + }; + + job.setUser(isFirstChecker); + job.schedule(); + } + +// /** +// * Recursively returns all the files in the given container +// * @param container the IContainer +// * @return +// */ +// private List<IFile> getProjectFiles(IContainer container) { +// final List<IFile> files = new ArrayList<IFile>(); +// try { +// for (IResource member : container.members()) { +// if (member instanceof IContainer) { +// files.addAll(getProjectFiles((IContainer) member)); +// } else if (member instanceof IFile) { +// files.add((IFile) member); +// } +// } +// } catch (Exception e) { +// e.printStackTrace(); +// } +// return files; +// } + + /* + * private void syncWithUI(Shell shell) { Display.getDefault().asyncExec(new + * Runnable() { public void run() { MessageDialog.openInformation(shell, + * "message", "completed!"); } }); } + */ + + public boolean belongsTo(Set<String> checkersTags) { + for (String tag : checkersTags) { + if (checkerTags.contains(tag)) + return true; + } + return false; + } + + public String getUnifiedName() { + return unifiedName; + } + + public Set<String> getCheckerTags() { + return checkerTags; + } + + public void addError(Exception e){ + errors.add(e); + } +} diff --git a/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/checkerManager/CheckerManager.java b/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/checkerManager/CheckerManager.java index c7184e30141aecff1867f355cdcaed62111f8e7a..d5411c13689f733f951cffd2ff16efd7e6a717c8 100644 --- a/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/checkerManager/CheckerManager.java +++ b/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/checkerManager/CheckerManager.java @@ -1,222 +1,229 @@ -package org.polarsys.chess.checkers.core.checkerManager; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.apache.log4j.Logger; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.emf.ecore.EObject; -import org.eclipse.emf.ecore.EValidator; -import org.eclipse.emf.ecore.util.EcoreUtil; -import org.eclipse.papyrus.views.modelexplorer.ModelExplorerPage; -import org.eclipse.papyrus.views.modelexplorer.ModelExplorerPageBookView; -import org.eclipse.papyrus.views.modelexplorer.ModelExplorerView; -import org.eclipse.ui.IViewPart; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.part.IPage; -import org.eclipse.uml2.uml.NamedElement; -import org.eclipse.xtext.nodemodel.INode; -import org.polarsys.chess.service.gui.utils.ReportProblemsUtil; - -public class CheckerManager { - - private static final Logger logger = Logger.getLogger(CheckerManager.class); - - private static final String CHECKER_NAME = "checkerName"; - List<CheckersContainer> checkersContainers; - List<CheckerMessage> messages; - HashMap<String, Boolean> checkerStatus; - - // ModelExplorerPageBookView modelExplorerPageBookView; - // ModelExplorerView modelExplorerView ; - // test test; - public CheckerManager() { - logger.debug("Instantiate CheckerManager"); - this.checkersContainers = new ArrayList<CheckersContainer>(); - new CheckersContainer(this); - // checkersContainers.add(checkersContainer); - } - - public void run(Set<String> selectedCheckersTags) throws Exception { - logger.debug("run"); - checkerStatus = new HashMap<String, Boolean>(); - messages = new ArrayList<CheckerMessage>(); - // modelExplorerPageBookView = getModelExplorerPageBookView(); - // modelExplorerView = getModelExplorerView(); - // test = new test(modelExplorerView); - for (CheckersContainer checkersContainer : checkersContainers) { - logger.debug("run checkersContainer"); - checkersContainer.run(selectedCheckersTags); - } - } - - public void register(CheckersContainer checkersContainer) { - logger.debug("register CheckersContainer"); - this.checkersContainers.add(checkersContainer); - } - - public Set<String> getTags() { - Set<String> tags = new HashSet<String>(); - - for (CheckersContainer containter : checkersContainers) { - tags.addAll(containter.getTags()); - } - - return tags; - } - - public CheckersContainer getCheckersContainter() { - return checkersContainers.get(0); - } - - public void addMessages(String unifiedName, List<CheckerMessage> newMessages) throws Exception { - // this.messages.addAll(newMessages); - checkerStatus.put(unifiedName, true); - - // logger.debug("addMessages '" + unifiedName + "' : " + - // newMessages.size()); - - /* - * for (Boolean value : checkerStatus.values()) { if - * (value.booleanValue() == false) return; } - */ - - // IViewPart modelexplorer = - // PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() - // .showView(ModelExplorerPageBookView.VIEW_ID); - // modelExplorerView = getModelExplorerPageBookView(); - // System.out.println("modelexplorer: "+modelExplorerView); - - // Set<IFile> iFiles = extractIFiles(newMessages); - - // for (IFile iFile : iFiles) { - // deleteMarkers(iFile, unifiedName); - // } - - for (CheckerMessage msn : newMessages) { - if (msn.object != null && msn.object instanceof EObject) { - IMarker marker = msn.file.createMarker(EValidator.MARKER); - marker.setAttribute(CHECKER_NAME, msn.checkerName); - marker.setAttribute(IMarker.MESSAGE, msn.message); - String location = EcoreUtil.getURI((EObject) msn.object).toString(); - if (msn.object instanceof NamedElement) { - location = ((NamedElement) msn.object).getQualifiedName(); - } - marker.setAttribute(IMarker.LOCATION, location); - marker.setAttribute(IMarker.SEVERITY, msn.severity); - marker.setAttribute(EValidator.URI_ATTRIBUTE, EcoreUtil.getURI((EObject) msn.object).toString()); - } else if (msn.object != null && msn.object instanceof INode) { - try { - final INode node = (INode) msn.object; - if (msn.severity == IMarker.SEVERITY_INFO) { - ReportProblemsUtil.reportInfo(msn.file, CHECKER_NAME, msn.checkerName, msn.message, node.getStartLine(), - node.getOffset(), node.getEndOffset()); - } else if (msn.severity == IMarker.SEVERITY_WARNING) { - ReportProblemsUtil.reportWarning(msn.file, CHECKER_NAME, msn.checkerName, msn.message, node.getStartLine(), - node.getOffset(), node.getEndOffset()); - } else if (msn.severity == IMarker.SEVERITY_ERROR) { - ReportProblemsUtil.reportError(msn.file, CHECKER_NAME, msn.checkerName, msn.message, node.getStartLine(), - node.getOffset(), node.getEndOffset()); - } - } catch (NullPointerException | CoreException e) { - e.printStackTrace(); - } - } - } - } - - private Set<IFile> extractIFiles(List<CheckerMessage> checkerMessages) { - - Set<IFile> iFiles = new HashSet<IFile>(); - if (checkerMessages != null) { - for (CheckerMessage checkerMessage : checkerMessages) { - if (checkerMessage.file != null) { - iFiles.add(checkerMessage.file); - } - } - } - return iFiles; - } - - void deleteMarkers(IFile file, String checkerName) throws CoreException { - IMarker[] markers = file.findMarkers(EValidator.MARKER, false, IResource.DEPTH_ONE); - for (IMarker marker : markers) { - if (marker != null && marker.exists() && marker.getAttribute(CHECKER_NAME, "").equals(checkerName)) { - marker.delete(); - } - } - } - - /** - * Deletes all the matching markers inside the given project. - * @param project the active project - * @param checkerName the name of the creating checker - * @throws CoreException - */ - void deleteProjectMarkers(IProject project, String checkerName) throws CoreException { - IMarker[] markers = project.findMarkers(null, false, IResource.DEPTH_INFINITE); - for (IMarker marker : markers) { - if (marker != null && marker.exists() && marker.getAttribute(CHECKER_NAME, "").equals(checkerName)) { - marker.delete(); - } - } - } - - private ModelExplorerPageBookView getModelExplorerPageBookView() { - - IWorkbench workbench = PlatformUI.getWorkbench(); - - System.out.println("workbench: " + workbench); - IWorkbenchWindow window = workbench.getActiveWorkbenchWindow(); - - System.out.println("window: " + window); - - IWorkbenchPage workbenchPage = window.getActivePage(); - - System.out.println("workbenchPage: " + workbenchPage); - - IViewPart modelExplorerViewPart = null; - - for (IViewPart view : workbenchPage.getViews()) { - System.out.println("view: " + view.getTitle()); - } - - try { - modelExplorerViewPart = window.getActivePage().showView(ModelExplorerPageBookView.VIEW_ID); - } catch (PartInitException ex) { - ex.printStackTrace(System.out); - } - - ModelExplorerPageBookView view = (ModelExplorerPageBookView) modelExplorerViewPart; - return view; - - } - - private ModelExplorerView getModelExplorerView() { - - ModelExplorerPageBookView view = getModelExplorerPageBookView(); - IPage currentPage = view.getCurrentPage(); - ModelExplorerPage page = (ModelExplorerPage) currentPage; - IViewPart viewer = page.getViewer(); - ModelExplorerView modelExplorerView = (ModelExplorerView) viewer; - - return modelExplorerView; - - } - - public void updateCheckerStatus(String unifiedName, boolean b) { - checkerStatus.put(unifiedName, b); - } - -} +/******************************************************************************* + * Copyright (C) 2020 Fondazione Bruno Kessler. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v2.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v20.html + ******************************************************************************/ +package org.polarsys.chess.checkers.core.checkerManager; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.apache.log4j.Logger; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EValidator; +import org.eclipse.emf.ecore.util.EcoreUtil; +import org.eclipse.papyrus.views.modelexplorer.ModelExplorerPage; +import org.eclipse.papyrus.views.modelexplorer.ModelExplorerPageBookView; +import org.eclipse.papyrus.views.modelexplorer.ModelExplorerView; +import org.eclipse.ui.IViewPart; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.part.IPage; +import org.eclipse.uml2.uml.NamedElement; +import org.eclipse.xtext.nodemodel.INode; +import org.polarsys.chess.service.gui.utils.ReportProblemsUtil; + +public class CheckerManager { + + private static final Logger logger = Logger.getLogger(CheckerManager.class); + + private static final String CHECKER_NAME = "checkerName"; + List<CheckersContainer> checkersContainers; + List<CheckerMessage> messages; + HashMap<String, Boolean> checkerStatus; + + // ModelExplorerPageBookView modelExplorerPageBookView; + // ModelExplorerView modelExplorerView ; + // test test; + public CheckerManager() { + logger.debug("Instantiate CheckerManager"); + this.checkersContainers = new ArrayList<CheckersContainer>(); + new CheckersContainer(this); + // checkersContainers.add(checkersContainer); + } + + public void run(Set<String> selectedCheckersTags) throws Exception { + logger.debug("run"); + checkerStatus = new HashMap<String, Boolean>(); + messages = new ArrayList<CheckerMessage>(); + // modelExplorerPageBookView = getModelExplorerPageBookView(); + // modelExplorerView = getModelExplorerView(); + // test = new test(modelExplorerView); + for (CheckersContainer checkersContainer : checkersContainers) { + logger.debug("run checkersContainer"); + checkersContainer.run(selectedCheckersTags); + } + } + + public void register(CheckersContainer checkersContainer) { + logger.debug("register CheckersContainer"); + this.checkersContainers.add(checkersContainer); + } + + public Set<String> getTags() { + Set<String> tags = new HashSet<String>(); + + for (CheckersContainer containter : checkersContainers) { + tags.addAll(containter.getTags()); + } + + return tags; + } + + public CheckersContainer getCheckersContainter() { + return checkersContainers.get(0); + } + + public void addMessages(String unifiedName, List<CheckerMessage> newMessages) throws Exception { + // this.messages.addAll(newMessages); + checkerStatus.put(unifiedName, true); + + // logger.debug("addMessages '" + unifiedName + "' : " + + // newMessages.size()); + + /* + * for (Boolean value : checkerStatus.values()) { if + * (value.booleanValue() == false) return; } + */ + + // IViewPart modelexplorer = + // PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() + // .showView(ModelExplorerPageBookView.VIEW_ID); + // modelExplorerView = getModelExplorerPageBookView(); + // System.out.println("modelexplorer: "+modelExplorerView); + + // Set<IFile> iFiles = extractIFiles(newMessages); + + // for (IFile iFile : iFiles) { + // deleteMarkers(iFile, unifiedName); + // } + + for (CheckerMessage msn : newMessages) { + if (msn.object != null && msn.object instanceof EObject) { + IMarker marker = msn.file.createMarker(EValidator.MARKER); + marker.setAttribute(CHECKER_NAME, msn.checkerName); + marker.setAttribute(IMarker.MESSAGE, msn.message); + String location = EcoreUtil.getURI((EObject) msn.object).toString(); + if (msn.object instanceof NamedElement) { + location = ((NamedElement) msn.object).getQualifiedName(); + } + marker.setAttribute(IMarker.LOCATION, location); + marker.setAttribute(IMarker.SEVERITY, msn.severity); + marker.setAttribute(EValidator.URI_ATTRIBUTE, EcoreUtil.getURI((EObject) msn.object).toString()); + } else if (msn.object != null && msn.object instanceof INode) { + try { + final INode node = (INode) msn.object; + if (msn.severity == IMarker.SEVERITY_INFO) { + ReportProblemsUtil.reportInfo(msn.file, CHECKER_NAME, msn.checkerName, msn.message, node.getStartLine(), + node.getOffset(), node.getEndOffset()); + } else if (msn.severity == IMarker.SEVERITY_WARNING) { + ReportProblemsUtil.reportWarning(msn.file, CHECKER_NAME, msn.checkerName, msn.message, node.getStartLine(), + node.getOffset(), node.getEndOffset()); + } else if (msn.severity == IMarker.SEVERITY_ERROR) { + ReportProblemsUtil.reportError(msn.file, CHECKER_NAME, msn.checkerName, msn.message, node.getStartLine(), + node.getOffset(), node.getEndOffset()); + } + } catch (NullPointerException | CoreException e) { + e.printStackTrace(); + } + } + } + } + + private Set<IFile> extractIFiles(List<CheckerMessage> checkerMessages) { + + Set<IFile> iFiles = new HashSet<IFile>(); + if (checkerMessages != null) { + for (CheckerMessage checkerMessage : checkerMessages) { + if (checkerMessage.file != null) { + iFiles.add(checkerMessage.file); + } + } + } + return iFiles; + } + + void deleteMarkers(IFile file, String checkerName) throws CoreException { + IMarker[] markers = file.findMarkers(EValidator.MARKER, false, IResource.DEPTH_ONE); + for (IMarker marker : markers) { + if (marker != null && marker.exists() && marker.getAttribute(CHECKER_NAME, "").equals(checkerName)) { + marker.delete(); + } + } + } + + /** + * Deletes all the matching markers inside the given project. + * @param project the active project + * @param checkerName the name of the creating checker + * @throws CoreException + */ + void deleteProjectMarkers(IProject project, String checkerName) throws CoreException { + IMarker[] markers = project.findMarkers(null, false, IResource.DEPTH_INFINITE); + for (IMarker marker : markers) { + if (marker != null && marker.exists() && marker.getAttribute(CHECKER_NAME, "").equals(checkerName)) { + marker.delete(); + } + } + } + + private ModelExplorerPageBookView getModelExplorerPageBookView() { + + IWorkbench workbench = PlatformUI.getWorkbench(); + + System.out.println("workbench: " + workbench); + IWorkbenchWindow window = workbench.getActiveWorkbenchWindow(); + + System.out.println("window: " + window); + + IWorkbenchPage workbenchPage = window.getActivePage(); + + System.out.println("workbenchPage: " + workbenchPage); + + IViewPart modelExplorerViewPart = null; + + for (IViewPart view : workbenchPage.getViews()) { + System.out.println("view: " + view.getTitle()); + } + + try { + modelExplorerViewPart = window.getActivePage().showView(ModelExplorerPageBookView.VIEW_ID); + } catch (PartInitException ex) { + ex.printStackTrace(System.out); + } + + ModelExplorerPageBookView view = (ModelExplorerPageBookView) modelExplorerViewPart; + return view; + + } + + private ModelExplorerView getModelExplorerView() { + + ModelExplorerPageBookView view = getModelExplorerPageBookView(); + IPage currentPage = view.getCurrentPage(); + ModelExplorerPage page = (ModelExplorerPage) currentPage; + IViewPart viewer = page.getViewer(); + ModelExplorerView modelExplorerView = (ModelExplorerView) viewer; + + return modelExplorerView; + + } + + public void updateCheckerStatus(String unifiedName, boolean b) { + checkerStatus.put(unifiedName, b); + } + +} diff --git a/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/checkerManager/CheckerMessage.java b/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/checkerManager/CheckerMessage.java index c0f5c5e095b839af41992c1e3618433ea7c64ba6..bce10f3e6294fafe2706511575d9770db2ea15fb 100644 --- a/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/checkerManager/CheckerMessage.java +++ b/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/checkerManager/CheckerMessage.java @@ -1,33 +1,40 @@ -package org.polarsys.chess.checkers.core.checkerManager; - -import org.eclipse.core.resources.IFile; -import org.eclipse.emf.ecore.EObject; -import org.eclipse.emf.workspace.util.WorkspaceSynchronizer; - -public class CheckerMessage { - - protected IFile file; - protected int severity; - protected String message; - protected Object object; - protected String checkerName; - - public CheckerMessage(String message, int severity ,Object object, String checkerName ) { - this((object instanceof EObject) ? WorkspaceSynchronizer.getFile(((EObject) object).eResource()) : null, - severity, message, object, checkerName); - } - - public CheckerMessage(IFile file, int severity, String message, Object object, String checkerName) { - super(); - this.file = file; - this.severity = severity; - this.message = message; - this.object = object; - this.checkerName = checkerName; - } - - public String getMessage() { - return message; - } - -} \ No newline at end of file +/******************************************************************************* + * Copyright (C) 2020 Fondazione Bruno Kessler. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v2.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v20.html + ******************************************************************************/ +package org.polarsys.chess.checkers.core.checkerManager; + +import org.eclipse.core.resources.IFile; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.workspace.util.WorkspaceSynchronizer; + +public class CheckerMessage { + + protected IFile file; + protected int severity; + protected String message; + protected Object object; + protected String checkerName; + + public CheckerMessage(String message, int severity ,Object object, String checkerName ) { + this((object instanceof EObject) ? WorkspaceSynchronizer.getFile(((EObject) object).eResource()) : null, + severity, message, object, checkerName); + } + + public CheckerMessage(IFile file, int severity, String message, Object object, String checkerName) { + super(); + this.file = file; + this.severity = severity; + this.message = message; + this.object = object; + this.checkerName = checkerName; + } + + public String getMessage() { + return message; + } + +} diff --git a/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/checkerManager/CheckerTriggerManager.java b/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/checkerManager/CheckerTriggerManager.java index 1e8d188c1a88d9df83189f282674a1860c965472..296256a2d8d1b454a88777bc3d65404081718917 100644 --- a/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/checkerManager/CheckerTriggerManager.java +++ b/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/checkerManager/CheckerTriggerManager.java @@ -1,38 +1,45 @@ -package org.polarsys.chess.checkers.core.checkerManager; - -import java.util.List; - -import com.google.common.collect.HashBasedTable; -import com.google.common.collect.Table; - -public class CheckerTriggerManager { - Table<String, String, Integer> targetIdHashMap = HashBasedTable.create(); - - public void loadCheckersRegistry() { - // TODO Auto-generated method stub - - } - - public void saveCheckersRegistry() { - // TODO Auto-generated method stub - - } - - public boolean isTriggered(String checkerUnifiedName, String targetId, int targetCurrentHashCode) { - Integer lastTargetHashCode = targetIdHashMap.get(checkerUnifiedName, targetId); - if ((lastTargetHashCode != null) && (!lastTargetHashCode.equals(targetCurrentHashCode))) { - return true; - } - return false; - } - - public void updateCheckersRegistryEntry(String checkerUnifiedName, String targetId, int targetCurrentHashCode) { - targetIdHashMap.put(checkerUnifiedName, targetId, targetCurrentHashCode); - - } - - public void updateCheckersRegistry(List<?> targets) { - // TODO Auto-generated method stub - - } -} \ No newline at end of file +/******************************************************************************* + * Copyright (C) 2020 Fondazione Bruno Kessler. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v2.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v20.html + ******************************************************************************/ +package org.polarsys.chess.checkers.core.checkerManager; + +import java.util.List; + +import com.google.common.collect.HashBasedTable; +import com.google.common.collect.Table; + +public class CheckerTriggerManager { + Table<String, String, Integer> targetIdHashMap = HashBasedTable.create(); + + public void loadCheckersRegistry() { + // TODO Auto-generated method stub + + } + + public void saveCheckersRegistry() { + // TODO Auto-generated method stub + + } + + public boolean isTriggered(String checkerUnifiedName, String targetId, int targetCurrentHashCode) { + Integer lastTargetHashCode = targetIdHashMap.get(checkerUnifiedName, targetId); + if ((lastTargetHashCode != null) && (!lastTargetHashCode.equals(targetCurrentHashCode))) { + return true; + } + return false; + } + + public void updateCheckersRegistryEntry(String checkerUnifiedName, String targetId, int targetCurrentHashCode) { + targetIdHashMap.put(checkerUnifiedName, targetId, targetCurrentHashCode); + + } + + public void updateCheckersRegistry(List<?> targets) { + // TODO Auto-generated method stub + + } +} diff --git a/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/checkerManager/CheckersContainer.java b/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/checkerManager/CheckersContainer.java index 89ea55312566789b16d5213fb60b86474660b828..ae4adb145ea7b2a9c268bca938fee2bf3d5fcb8a 100644 --- a/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/checkerManager/CheckersContainer.java +++ b/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/checkerManager/CheckersContainer.java @@ -1,72 +1,79 @@ -package org.polarsys.chess.checkers.core.checkerManager; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; - -import org.apache.log4j.Logger; - -public class CheckersContainer { - - private static final Logger logger = Logger.getLogger(CheckersContainer.class); - - List<Checker> checkers; - CheckerManager checkerManager; - - public CheckersContainer(CheckerManager checkerManager) { - this.checkers = new ArrayList<Checker>(); - this.checkerManager = checkerManager; - checkerManager.register(this); - } - - public void run(Set<String> checkersTags) throws Exception { - - boolean isFirstChecker = true; - - for (Checker checker : checkers) { - - checkerManager.updateCheckerStatus(checker.unifiedName, false); - - if (checker.belongsTo(checkersTags)) { - logger.debug("run " + checker.getUnifiedName()); - checker.asyncCheck(isFirstChecker); - isFirstChecker=false; - } - } - - } - - public void register(Checker checker) { - Optional<Checker> alreadyRegisteredChecker = find(this.checkers,checker.unifiedName); - if(!alreadyRegisteredChecker.isPresent()){ - logger.debug("register checker not present: "+checker.registerPriority); - this.checkers.add(checker); - }else if((alreadyRegisteredChecker.get().registerPriority < checker.registerPriority)){ - logger.debug("register checker already registered with priority: "+alreadyRegisteredChecker.get().registerPriority); - logger.debug("checker to register with priority: "+checker.registerPriority); - - this.checkers.remove(alreadyRegisteredChecker.get()); - this.checkers.add(checker); - //return; - } - //this.checkers.add(checker); - } - - public Optional<Checker> find(final List<Checker> list, final String name){ - return list.stream().filter(o -> o.unifiedName.equals(name)).findFirst(); - } - - public Collection<? extends String> getTags() { - Set<String> tags = new HashSet<String>(); - for (Checker checker : checkers) { - tags.addAll(checker.getCheckerTags()); - } - return tags; - } - - - -} \ No newline at end of file +/******************************************************************************* + * Copyright (C) 2020 Fondazione Bruno Kessler. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v2.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v20.html + ******************************************************************************/ +package org.polarsys.chess.checkers.core.checkerManager; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +import org.apache.log4j.Logger; + +public class CheckersContainer { + + private static final Logger logger = Logger.getLogger(CheckersContainer.class); + + List<Checker> checkers; + CheckerManager checkerManager; + + public CheckersContainer(CheckerManager checkerManager) { + this.checkers = new ArrayList<Checker>(); + this.checkerManager = checkerManager; + checkerManager.register(this); + } + + public void run(Set<String> checkersTags) throws Exception { + + boolean isFirstChecker = true; + + for (Checker checker : checkers) { + + checkerManager.updateCheckerStatus(checker.unifiedName, false); + + if (checker.belongsTo(checkersTags)) { + logger.debug("run " + checker.getUnifiedName()); + checker.asyncCheck(isFirstChecker); + isFirstChecker=false; + } + } + + } + + public void register(Checker checker) { + Optional<Checker> alreadyRegisteredChecker = find(this.checkers,checker.unifiedName); + if(!alreadyRegisteredChecker.isPresent()){ + logger.debug("register checker not present: "+checker.registerPriority); + this.checkers.add(checker); + }else if((alreadyRegisteredChecker.get().registerPriority < checker.registerPriority)){ + logger.debug("register checker already registered with priority: "+alreadyRegisteredChecker.get().registerPriority); + logger.debug("checker to register with priority: "+checker.registerPriority); + + this.checkers.remove(alreadyRegisteredChecker.get()); + this.checkers.add(checker); + //return; + } + //this.checkers.add(checker); + } + + public Optional<Checker> find(final List<Checker> list, final String name){ + return list.stream().filter(o -> o.unifiedName.equals(name)).findFirst(); + } + + public Collection<? extends String> getTags() { + Set<String> tags = new HashSet<String>(); + for (Checker checker : checkers) { + tags.addAll(checker.getCheckerTags()); + } + return tags; + } + + + +} diff --git a/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/checkerManager/test.java b/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/checkerManager/test.java index 997c9d6989f703bb8740fb0265bef87e2264cbc8..064472611b998b7e6fcab3f605f2128837c97219 100644 --- a/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/checkerManager/test.java +++ b/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/checkerManager/test.java @@ -1,53 +1,60 @@ -package org.polarsys.chess.checkers.core.checkerManager; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.core.resources.IMarker; -import org.eclipse.emf.common.util.URI; -import org.eclipse.emf.ecore.EObject; -import org.eclipse.emf.ecore.EValidator; -import org.eclipse.emf.edit.domain.EditingDomain; -import org.eclipse.papyrus.views.modelexplorer.ModelExplorerView; -import org.eclipse.ui.IViewPart; -import org.eclipse.ui.ide.IDE; -import org.eclipse.ui.ide.IGotoMarker; -import org.eclipse.ui.navigator.CommonViewer; - -import com.google.common.collect.Lists; - -public class test implements IGotoMarker { - - ModelExplorerView modelExplorerView; - - - public test(ModelExplorerView modelExplorerView) { - super(); - this.modelExplorerView = modelExplorerView; - } - - - @Override - public void gotoMarker(IMarker marker) { - - String uriAttribute = marker.getAttribute(EValidator.URI_ATTRIBUTE, null); - if (uriAttribute != null) { - URI uri = URI.createURI(uriAttribute); - - EditingDomain domain = modelExplorerView.getEditingDomain(); - EObject eObject = domain.getResourceSet().getEObject(uri, false); - if (eObject != null) { - - modelExplorerView.revealSemanticElement(Lists.newArrayList(eObject)); - //CommonViewer treeViewer = modelExplorerView.getCommonViewer(); - // The common viewer is in fact a tree viewer - // bug enhancement: use function in ModelExplorerView instead of findElementForEObject - //ModelExplorerView.reveal(Lists.newArrayList(eObject), treeViewer); - } - } - - } - - - -} +/******************************************************************************* + * Copyright (C) 2020 Fondazione Bruno Kessler. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v2.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v20.html + ******************************************************************************/ +package org.polarsys.chess.checkers.core.checkerManager; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.resources.IMarker; +import org.eclipse.emf.common.util.URI; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EValidator; +import org.eclipse.emf.edit.domain.EditingDomain; +import org.eclipse.papyrus.views.modelexplorer.ModelExplorerView; +import org.eclipse.ui.IViewPart; +import org.eclipse.ui.ide.IDE; +import org.eclipse.ui.ide.IGotoMarker; +import org.eclipse.ui.navigator.CommonViewer; + +import com.google.common.collect.Lists; + +public class test implements IGotoMarker { + + ModelExplorerView modelExplorerView; + + + public test(ModelExplorerView modelExplorerView) { + super(); + this.modelExplorerView = modelExplorerView; + } + + + @Override + public void gotoMarker(IMarker marker) { + + String uriAttribute = marker.getAttribute(EValidator.URI_ATTRIBUTE, null); + if (uriAttribute != null) { + URI uri = URI.createURI(uriAttribute); + + EditingDomain domain = modelExplorerView.getEditingDomain(); + EObject eObject = domain.getResourceSet().getEObject(uri, false); + if (eObject != null) { + + modelExplorerView.revealSemanticElement(Lists.newArrayList(eObject)); + //CommonViewer treeViewer = modelExplorerView.getCommonViewer(); + // The common viewer is in fact a tree viewer + // bug enhancement: use function in ModelExplorerView instead of findElementForEObject + //ModelExplorerView.reveal(Lists.newArrayList(eObject), treeViewer); + } + } + + } + + + +} diff --git a/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/impl/IdentifiersChecker.java b/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/impl/IdentifiersChecker.java index 62be6d48a9f860af1a2bc4cacab10415d4c6fb58..9dcd2f572102bc330c3602a57835d07b2d8c0f1f 100644 --- a/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/impl/IdentifiersChecker.java +++ b/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/impl/IdentifiersChecker.java @@ -1,154 +1,161 @@ -package org.polarsys.chess.checkers.core.impl; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.apache.log4j.Logger; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.emf.common.util.BasicEList; -import org.eclipse.emf.common.util.EList; -import org.eclipse.emf.ecore.EObject; -import org.eclipse.uml2.uml.Behavior; -import org.eclipse.uml2.uml.Class; -import org.eclipse.uml2.uml.NamedElement; -import org.eclipse.uml2.uml.Operation; -import org.eclipse.uml2.uml.Package; -import org.eclipse.uml2.uml.Port; -import org.eclipse.uml2.uml.Property; -import org.polarsys.chess.checkers.core.checkerManager.Checker; -import org.polarsys.chess.checkers.core.checkerManager.CheckerMessage; -import org.polarsys.chess.contracts.profile.chesscontract.util.EntityUtil; - -public class IdentifiersChecker extends Checker { - protected Package systemViewPackage; - private static final Logger logger = Logger.getLogger(IdentifiersChecker.class); - private static final String checkerName = "IdentifierChecker"; - - /** - * Default constructor - */ - public IdentifiersChecker() { - super(checkerName, getTags()); - } - - /** - * Creates the checker with the given priority. - * @param priority the priority - */ - public IdentifiersChecker(int priority) { - super(checkerName, getTags(), priority); - } - - /** - * Constructor with explicit tags. - * @param tags the tags identifying this checker - */ - public IdentifiersChecker(Set<String> tags) { - super(checkerName, tags); - } - - /** - * Constructor with explicit tags and priority. - * @param tags the tags identifying this checker - * @param priority the priority - */ - public IdentifiersChecker(Set<String> tags, int priority) { - super(checkerName, tags, priority); - } - - @Override - public List<CheckerMessage> check(IProgressMonitor monitor) throws Exception { - List<CheckerMessage> messages = new ArrayList<CheckerMessage>(); - Collection<Class> blocks = null; - try { - blocks = (Collection<Class>) EntityUtil.getInstance().getAllClasses(systemViewPackage); - } catch (Exception e) { - e.printStackTrace(); - } - - monitor.beginTask(checkerName, blocks.size()); - for (Class block : blocks) { - messages.addAll(processBlock(block)); - if (monitor.isCanceled()) - throw new Exception("Checker interrupted"); - monitor.worked(1); - } - return messages; - } - - /** - * Processes the given block. - * - * @param block - * the block to process - * @return a list of messages - */ - protected List<CheckerMessage> processBlock(Class block) { - final EList<NamedElement> elements = filterElements(block); - return processElements(elements); - } - - /** - * Processes the given list of elements. - * - * @param block - * the list to process - * @return a list of warnings - */ - protected List<CheckerMessage> processElements(EList<NamedElement> elements) { - List<CheckerMessage> messages = new ArrayList<CheckerMessage>(); - - for (NamedElement element : elements) { - final String name = element.getName(); - logger.debug("Processing " + name); - if (!isValidId(name)) { - logger.debug("The element name is not a valid identifier: " + name); - final String msg = "The element name is not a valid identifier: " + name; - messages.add(new CheckerMessage(msg, IMarker.SEVERITY_WARNING, element, checkerName)); - } - } - return messages; - } - - protected boolean isValidId(String id) { - return javax.lang.model.SourceVersion.isIdentifier(id) && (!javax.lang.model.SourceVersion.isKeyword(id)); - } - - /** - * Creates the list of elements to be analized (incuding the block itself). Can be overridden if necessary. - * @param elements - * @return the filtered elements - */ - protected EList<NamedElement> filterElements(Class block) { - final EList<Property> attributes = block.getOwnedAttributes(); - final EList<Operation> operations = block.getOwnedOperations(); - final EList<Behavior> behaviors = block.getOwnedBehaviors(); - final EList<Port> ports = block.getOwnedPorts(); - - final EList<NamedElement> elements = new BasicEList<NamedElement>(attributes.size() + - operations.size() + behaviors.size() + ports.size() + 1); - elements.addAll(attributes); - elements.addAll(operations); - elements.addAll(behaviors); - elements.addAll(ports); - elements.add(block); - return elements; - } - - private static Set<String> getTags() { - Set<String> tags = new HashSet<String>(); - tags.add("fast"); - tags.add("warnings"); - tags.add("sysml"); - return tags; - } - - @Override - public void init() throws Exception { - systemViewPackage = EntityUtil.getInstance().getCurrentSystemView(); - } -} +/******************************************************************************* + * Copyright (C) 2020 Fondazione Bruno Kessler. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v2.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v20.html + ******************************************************************************/ +package org.polarsys.chess.checkers.core.impl; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.apache.log4j.Logger; +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.emf.common.util.BasicEList; +import org.eclipse.emf.common.util.EList; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.uml2.uml.Behavior; +import org.eclipse.uml2.uml.Class; +import org.eclipse.uml2.uml.NamedElement; +import org.eclipse.uml2.uml.Operation; +import org.eclipse.uml2.uml.Package; +import org.eclipse.uml2.uml.Port; +import org.eclipse.uml2.uml.Property; +import org.polarsys.chess.checkers.core.checkerManager.Checker; +import org.polarsys.chess.checkers.core.checkerManager.CheckerMessage; +import org.polarsys.chess.contracts.profile.chesscontract.util.EntityUtil; + +public class IdentifiersChecker extends Checker { + protected Package systemViewPackage; + private static final Logger logger = Logger.getLogger(IdentifiersChecker.class); + private static final String checkerName = "IdentifierChecker"; + + /** + * Default constructor + */ + public IdentifiersChecker() { + super(checkerName, getTags()); + } + + /** + * Creates the checker with the given priority. + * @param priority the priority + */ + public IdentifiersChecker(int priority) { + super(checkerName, getTags(), priority); + } + + /** + * Constructor with explicit tags. + * @param tags the tags identifying this checker + */ + public IdentifiersChecker(Set<String> tags) { + super(checkerName, tags); + } + + /** + * Constructor with explicit tags and priority. + * @param tags the tags identifying this checker + * @param priority the priority + */ + public IdentifiersChecker(Set<String> tags, int priority) { + super(checkerName, tags, priority); + } + + @Override + public List<CheckerMessage> check(IProgressMonitor monitor) throws Exception { + List<CheckerMessage> messages = new ArrayList<CheckerMessage>(); + Collection<Class> blocks = null; + try { + blocks = (Collection<Class>) EntityUtil.getInstance().getAllClasses(systemViewPackage); + } catch (Exception e) { + e.printStackTrace(); + } + + monitor.beginTask(checkerName, blocks.size()); + for (Class block : blocks) { + messages.addAll(processBlock(block)); + if (monitor.isCanceled()) + throw new Exception("Checker interrupted"); + monitor.worked(1); + } + return messages; + } + + /** + * Processes the given block. + * + * @param block + * the block to process + * @return a list of messages + */ + protected List<CheckerMessage> processBlock(Class block) { + final EList<NamedElement> elements = filterElements(block); + return processElements(elements); + } + + /** + * Processes the given list of elements. + * + * @param block + * the list to process + * @return a list of warnings + */ + protected List<CheckerMessage> processElements(EList<NamedElement> elements) { + List<CheckerMessage> messages = new ArrayList<CheckerMessage>(); + + for (NamedElement element : elements) { + final String name = element.getName(); + logger.debug("Processing " + name); + if (!isValidId(name)) { + logger.debug("The element name is not a valid identifier: " + name); + final String msg = "The element name is not a valid identifier: " + name; + messages.add(new CheckerMessage(msg, IMarker.SEVERITY_WARNING, element, checkerName)); + } + } + return messages; + } + + protected boolean isValidId(String id) { + return javax.lang.model.SourceVersion.isIdentifier(id) && (!javax.lang.model.SourceVersion.isKeyword(id)); + } + + /** + * Creates the list of elements to be analized (incuding the block itself). Can be overridden if necessary. + * @param elements + * @return the filtered elements + */ + protected EList<NamedElement> filterElements(Class block) { + final EList<Property> attributes = block.getOwnedAttributes(); + final EList<Operation> operations = block.getOwnedOperations(); + final EList<Behavior> behaviors = block.getOwnedBehaviors(); + final EList<Port> ports = block.getOwnedPorts(); + + final EList<NamedElement> elements = new BasicEList<NamedElement>(attributes.size() + + operations.size() + behaviors.size() + ports.size() + 1); + elements.addAll(attributes); + elements.addAll(operations); + elements.addAll(behaviors); + elements.addAll(ports); + elements.add(block); + return elements; + } + + private static Set<String> getTags() { + Set<String> tags = new HashSet<String>(); + tags.add("fast"); + tags.add("warnings"); + tags.add("sysml"); + return tags; + } + + @Override + public void init() throws Exception { + systemViewPackage = EntityUtil.getInstance().getCurrentSystemView(); + } +} diff --git a/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/impl/NameDistance.java b/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/impl/NameDistance.java index 00a6a42319c9ffdeda31091f5ae44576c0dcfdeb..8d569672b712fad9fee2229335b34c93c55b2aab 100644 --- a/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/impl/NameDistance.java +++ b/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/impl/NameDistance.java @@ -1,291 +1,298 @@ -package org.polarsys.chess.checkers.core.impl; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import org.apache.log4j.Logger; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.emf.common.util.BasicEList; -import org.eclipse.emf.common.util.EList; -import org.eclipse.emf.ecore.EObject; -import org.polarsys.chess.checkers.core.checkerManager.Checker; -import org.polarsys.chess.checkers.core.checkerManager.CheckerMessage; -import org.polarsys.chess.contracts.profile.chesscontract.util.EntityUtil; -import org.eclipse.uml2.uml.Package; -import org.eclipse.uml2.uml.Port; -import org.eclipse.uml2.uml.Property; -import org.eclipse.uml2.uml.Behavior; -import org.eclipse.uml2.uml.Class; -import org.eclipse.uml2.uml.NamedElement; -import org.eclipse.uml2.uml.Operation; - -/** - * Computes the minimum distance among properties inside SysML Blocks. - * - * @author cristofo - * - */ -public class NameDistance extends Checker { - - /** Minimum distance between two elements; below it, marks as suspect. */ - private int threshold = 2; - private Package systemViewPackage; - private static final Logger logger = Logger.getLogger(NameDistance.class); - private static final String checkerName = "NameDistance"; - - /** - * Creates a name distance checker with default threshold. - */ - public NameDistance() { - super(checkerName, getTags()); - } - - /** - * Creates a name distance checker with the given priority. - * @param priority the priority - */ - public NameDistance(int priority) { - super(checkerName, getTags(), priority); - } - - /** - * Creates a name distance checker with the given priority and threshold. - * @param priority the priority - * @param threshold the threshold to use - */ - public NameDistance(int priority, int threshold) { - super(checkerName, getTags(), priority); - setThreshold(threshold); - } - - /** - * Constructor with explicit tags. - * @param tags the tags identifying this checker - */ - public NameDistance(Set<String> tags) { - super(checkerName, tags); - } - - /** - * Constructor with explicit tags and priority. - * @param tags the tags identifying this checker - * @param priority the priority - */ - public NameDistance(Set<String> tags, int priority) { - super(checkerName, tags, priority); - } - - /** - * Constructor with explicit tags, priority and threshold. - * @param tags the tags identifying this checker - * @param priority the priority - * @param threshold the threshold to use - */ - public NameDistance(Set<String> tags, int priority, int threshold) { - super(checkerName, tags, priority); - setThreshold(threshold); - } - - private static Set<String> getTags() { - Set<String> tags = new HashSet<String>(); - tags.add("fast"); - tags.add("warnings"); - tags.add("errors"); - tags.add("sysml"); - return tags; - } - - public int getThreshold() { - return threshold; - } - - public void setThreshold(int threshold) { - this.threshold = threshold; - } - - @Override - public List<CheckerMessage> check(IProgressMonitor monitor) throws Exception { - List<CheckerMessage> messages = new ArrayList<CheckerMessage>(); - Collection<Class> blocks = null; - try { - blocks = (Collection<Class>) EntityUtil.getInstance().getAllClasses(systemViewPackage); - } catch (Exception e) { - e.printStackTrace(); - } - - monitor.beginTask(unifiedName, blocks.size()); - for (Class block : blocks) { - messages.addAll(processBlock(block)); - if (monitor.isCanceled()) - throw new Exception("Checker interrupted"); - monitor.worked(1); - } - return messages; - } - - /** - * Processes the given block. - * - * @param block - * the block to process - * @return a list of warnings - */ - private List<CheckerMessage> processBlock(Class block) { - final EList<NamedElement> elements = filterElements(block); - return processElements(elements); - } - - /** - * Creates the list of elements to be analized. Can be overridden if necessary. - * @param elements - * @return the filtered elements - */ - protected EList<NamedElement> filterElements(Class block) { - final EList<Property> attributes = block.getOwnedAttributes(); - final EList<Operation> operations = block.getOwnedOperations(); - final EList<Behavior> behaviors = block.getOwnedBehaviors(); - final EList<Port> ports = block.getOwnedPorts(); - - final EList<NamedElement> elements = new BasicEList<NamedElement>(attributes.size() + - operations.size() + behaviors.size() + ports.size()); - elements.addAll(attributes); - elements.addAll(operations); - elements.addAll(behaviors); - elements.addAll(ports); - return elements; - } - - /** - * Processes the given list of elements. - * - * @param block - * the list to process - * @return a list of warnings - */ - private List<CheckerMessage> processElements(EList<NamedElement> elements) { - List<CheckerMessage> messages = new ArrayList<CheckerMessage>(); - - for (int i = 0; i < elements.size(); i++) { - final NamedElement first = elements.get(i); - final String firstName = normalizeName(first.getName()); - ArrayList<String> similarNames = new ArrayList<String>(2); - for (int j = 0; j < elements.size(); j++) { - if (j == i) - continue; - final NamedElement second = elements.get(j); - - final String secondName = normalizeName(second.getName()); - final int distance = levenshteinDistance(firstName, secondName); - logger.debug(firstName + " and " + secondName + " distance = " + distance); - - if (distance == 0) { - final String msg = equalsMsg(first, second); - messages.add(createMessage(msg, IMarker.SEVERITY_ERROR, first, unifiedName)); - } - if (distance <= threshold) { - similarNames.add(second.getName()); - } - } - - // If some similarities are found, store the entry in the warnings - if (similarNames.size() > 0) { - final String msg = similarMsg(first, similarNames); - messages.add(createMessage(msg, IMarker.SEVERITY_WARNING, first, unifiedName)); - } - } - return messages; - } - - protected String equalsMsg(NamedElement first, NamedElement second) { - return "The term '" + first.getName() + "' is equal to '" + second.getName() + - "' in block '" + ((Class) first.getOwner()).getName() + "'"; - } - - protected String similarMsg(NamedElement first, ArrayList<String> similarNames) { - return "The term '" + first.getName() + "' is very similar to '" - + String.join("' and '", similarNames) + "' in block '" + ((Class) first.getOwner()).getName() + "'"; - } - - /** - * Removes macro and event prefixes from the name, and put it in lowercase. - * - * @param name - * @return - */ - private String normalizeName(String name) { - // if (name.startsWith(RfiAccEntityUtil.MACRO_PREFIX) && - // Character.isUpperCase(name.charAt(RfiAccEntityUtil.MACRO_PREFIX.length()))) - // { - // name = name.substring(RfiAccEntityUtil.MACRO_PREFIX.length()); - // } else if (name.startsWith(RfiAccEntityUtil.EVENT_PREFIX) && - // Character.isUpperCase(name.charAt(RfiAccEntityUtil.EVENT_PREFIX.length()))) - // { - // name = name.substring(RfiAccEntityUtil.EVENT_PREFIX.length()); - // } - - return name.toLowerCase(); - } - - /** - * Computes the Levenshtein distance. Code taken from - * https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Java - * - * @param lhs - * @param rhs - * @return the distance - */ - private static int levenshteinDistance(CharSequence lhs, CharSequence rhs) { - int len0 = lhs.length() + 1; - int len1 = rhs.length() + 1; - - // the array of distances - int[] cost = new int[len0]; - int[] newcost = new int[len0]; - - // initial cost of skipping prefix in String s0 - for (int i = 0; i < len0; i++) - cost[i] = i; - - // dynamically computing the array of distances - - // transformation cost for each letter in s1 - for (int j = 1; j < len1; j++) { - // initial cost of skipping prefix in String s1 - newcost[0] = j; - - // transformation cost for each letter in s0 - for (int i = 1; i < len0; i++) { - // matching current letters in both strings - int match = (lhs.charAt(i - 1) == rhs.charAt(j - 1)) ? 0 : 1; - - // computing cost for each transformation - int cost_replace = cost[i - 1] + match; - int cost_insert = cost[i] + 1; - int cost_delete = newcost[i - 1] + 1; - - // keep minimum cost - newcost[i] = Math.min(Math.min(cost_insert, cost_delete), cost_replace); - } - - // swap cost/newcost arrays - int[] swap = cost; - cost = newcost; - newcost = swap; - } - - // the distance is the cost for transforming all letters in both strings - return cost[len0 - 1]; - } - - protected CheckerMessage createMessage(String msg, int severity, EObject element, String unifiedName) { - return new CheckerMessage(msg, severity, element, unifiedName); - } - - @Override - public void init() throws Exception { - systemViewPackage = EntityUtil.getInstance().getCurrentSystemView(); - } -} +/******************************************************************************* + * Copyright (C) 2020 Fondazione Bruno Kessler. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v2.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v20.html + ******************************************************************************/ +package org.polarsys.chess.checkers.core.impl; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.apache.log4j.Logger; +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.emf.common.util.BasicEList; +import org.eclipse.emf.common.util.EList; +import org.eclipse.emf.ecore.EObject; +import org.polarsys.chess.checkers.core.checkerManager.Checker; +import org.polarsys.chess.checkers.core.checkerManager.CheckerMessage; +import org.polarsys.chess.contracts.profile.chesscontract.util.EntityUtil; +import org.eclipse.uml2.uml.Package; +import org.eclipse.uml2.uml.Port; +import org.eclipse.uml2.uml.Property; +import org.eclipse.uml2.uml.Behavior; +import org.eclipse.uml2.uml.Class; +import org.eclipse.uml2.uml.NamedElement; +import org.eclipse.uml2.uml.Operation; + +/** + * Computes the minimum distance among properties inside SysML Blocks. + * + * @author cristofo + * + */ +public class NameDistance extends Checker { + + /** Minimum distance between two elements; below it, marks as suspect. */ + private int threshold = 2; + private Package systemViewPackage; + private static final Logger logger = Logger.getLogger(NameDistance.class); + private static final String checkerName = "NameDistance"; + + /** + * Creates a name distance checker with default threshold. + */ + public NameDistance() { + super(checkerName, getTags()); + } + + /** + * Creates a name distance checker with the given priority. + * @param priority the priority + */ + public NameDistance(int priority) { + super(checkerName, getTags(), priority); + } + + /** + * Creates a name distance checker with the given priority and threshold. + * @param priority the priority + * @param threshold the threshold to use + */ + public NameDistance(int priority, int threshold) { + super(checkerName, getTags(), priority); + setThreshold(threshold); + } + + /** + * Constructor with explicit tags. + * @param tags the tags identifying this checker + */ + public NameDistance(Set<String> tags) { + super(checkerName, tags); + } + + /** + * Constructor with explicit tags and priority. + * @param tags the tags identifying this checker + * @param priority the priority + */ + public NameDistance(Set<String> tags, int priority) { + super(checkerName, tags, priority); + } + + /** + * Constructor with explicit tags, priority and threshold. + * @param tags the tags identifying this checker + * @param priority the priority + * @param threshold the threshold to use + */ + public NameDistance(Set<String> tags, int priority, int threshold) { + super(checkerName, tags, priority); + setThreshold(threshold); + } + + private static Set<String> getTags() { + Set<String> tags = new HashSet<String>(); + tags.add("fast"); + tags.add("warnings"); + tags.add("errors"); + tags.add("sysml"); + return tags; + } + + public int getThreshold() { + return threshold; + } + + public void setThreshold(int threshold) { + this.threshold = threshold; + } + + @Override + public List<CheckerMessage> check(IProgressMonitor monitor) throws Exception { + List<CheckerMessage> messages = new ArrayList<CheckerMessage>(); + Collection<Class> blocks = null; + try { + blocks = (Collection<Class>) EntityUtil.getInstance().getAllClasses(systemViewPackage); + } catch (Exception e) { + e.printStackTrace(); + } + + monitor.beginTask(unifiedName, blocks.size()); + for (Class block : blocks) { + messages.addAll(processBlock(block)); + if (monitor.isCanceled()) + throw new Exception("Checker interrupted"); + monitor.worked(1); + } + return messages; + } + + /** + * Processes the given block. + * + * @param block + * the block to process + * @return a list of warnings + */ + private List<CheckerMessage> processBlock(Class block) { + final EList<NamedElement> elements = filterElements(block); + return processElements(elements); + } + + /** + * Creates the list of elements to be analized. Can be overridden if necessary. + * @param elements + * @return the filtered elements + */ + protected EList<NamedElement> filterElements(Class block) { + final EList<Property> attributes = block.getOwnedAttributes(); + final EList<Operation> operations = block.getOwnedOperations(); + final EList<Behavior> behaviors = block.getOwnedBehaviors(); + final EList<Port> ports = block.getOwnedPorts(); + + final EList<NamedElement> elements = new BasicEList<NamedElement>(attributes.size() + + operations.size() + behaviors.size() + ports.size()); + elements.addAll(attributes); + elements.addAll(operations); + elements.addAll(behaviors); + elements.addAll(ports); + return elements; + } + + /** + * Processes the given list of elements. + * + * @param block + * the list to process + * @return a list of warnings + */ + private List<CheckerMessage> processElements(EList<NamedElement> elements) { + List<CheckerMessage> messages = new ArrayList<CheckerMessage>(); + + for (int i = 0; i < elements.size(); i++) { + final NamedElement first = elements.get(i); + final String firstName = normalizeName(first.getName()); + ArrayList<String> similarNames = new ArrayList<String>(2); + for (int j = 0; j < elements.size(); j++) { + if (j == i) + continue; + final NamedElement second = elements.get(j); + + final String secondName = normalizeName(second.getName()); + final int distance = levenshteinDistance(firstName, secondName); + logger.debug(firstName + " and " + secondName + " distance = " + distance); + + if (distance == 0) { + final String msg = equalsMsg(first, second); + messages.add(createMessage(msg, IMarker.SEVERITY_ERROR, first, unifiedName)); + } + if (distance <= threshold) { + similarNames.add(second.getName()); + } + } + + // If some similarities are found, store the entry in the warnings + if (similarNames.size() > 0) { + final String msg = similarMsg(first, similarNames); + messages.add(createMessage(msg, IMarker.SEVERITY_WARNING, first, unifiedName)); + } + } + return messages; + } + + protected String equalsMsg(NamedElement first, NamedElement second) { + return "The term '" + first.getName() + "' is equal to '" + second.getName() + + "' in block '" + ((Class) first.getOwner()).getName() + "'"; + } + + protected String similarMsg(NamedElement first, ArrayList<String> similarNames) { + return "The term '" + first.getName() + "' is very similar to '" + + String.join("' and '", similarNames) + "' in block '" + ((Class) first.getOwner()).getName() + "'"; + } + + /** + * Removes macro and event prefixes from the name, and put it in lowercase. + * + * @param name + * @return + */ + private String normalizeName(String name) { + // if (name.startsWith(RfiAccEntityUtil.MACRO_PREFIX) && + // Character.isUpperCase(name.charAt(RfiAccEntityUtil.MACRO_PREFIX.length()))) + // { + // name = name.substring(RfiAccEntityUtil.MACRO_PREFIX.length()); + // } else if (name.startsWith(RfiAccEntityUtil.EVENT_PREFIX) && + // Character.isUpperCase(name.charAt(RfiAccEntityUtil.EVENT_PREFIX.length()))) + // { + // name = name.substring(RfiAccEntityUtil.EVENT_PREFIX.length()); + // } + + return name.toLowerCase(); + } + + /** + * Computes the Levenshtein distance. Code taken from + * https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Java + * + * @param lhs + * @param rhs + * @return the distance + */ + private static int levenshteinDistance(CharSequence lhs, CharSequence rhs) { + int len0 = lhs.length() + 1; + int len1 = rhs.length() + 1; + + // the array of distances + int[] cost = new int[len0]; + int[] newcost = new int[len0]; + + // initial cost of skipping prefix in String s0 + for (int i = 0; i < len0; i++) + cost[i] = i; + + // dynamically computing the array of distances + + // transformation cost for each letter in s1 + for (int j = 1; j < len1; j++) { + // initial cost of skipping prefix in String s1 + newcost[0] = j; + + // transformation cost for each letter in s0 + for (int i = 1; i < len0; i++) { + // matching current letters in both strings + int match = (lhs.charAt(i - 1) == rhs.charAt(j - 1)) ? 0 : 1; + + // computing cost for each transformation + int cost_replace = cost[i - 1] + match; + int cost_insert = cost[i] + 1; + int cost_delete = newcost[i - 1] + 1; + + // keep minimum cost + newcost[i] = Math.min(Math.min(cost_insert, cost_delete), cost_replace); + } + + // swap cost/newcost arrays + int[] swap = cost; + cost = newcost; + newcost = swap; + } + + // the distance is the cost for transforming all letters in both strings + return cost[len0 - 1]; + } + + protected CheckerMessage createMessage(String msg, int severity, EObject element, String unifiedName) { + return new CheckerMessage(msg, severity, element, unifiedName); + } + + @Override + public void init() throws Exception { + systemViewPackage = EntityUtil.getInstance().getCurrentSystemView(); + } +} diff --git a/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/impl/StateStatus.java b/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/impl/StateStatus.java index e7c02047b1e58e5e26223f651fed30316a71567e..edbe85c06968d992e677b34053c922282e895c65 100644 --- a/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/impl/StateStatus.java +++ b/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/impl/StateStatus.java @@ -1,322 +1,329 @@ -package org.polarsys.chess.checkers.core.impl; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.apache.log4j.Logger; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.emf.common.util.EList; -import org.eclipse.emf.ecore.EObject; -import org.eclipse.uml2.uml.Class; -import org.eclipse.uml2.uml.Package; -import org.eclipse.uml2.uml.Region; -import org.eclipse.uml2.uml.StateMachine; -import org.eclipse.uml2.uml.Transition; -import org.eclipse.uml2.uml.Vertex; -import org.polarsys.chess.checkers.core.checkerManager.Checker; -import org.polarsys.chess.checkers.core.checkerManager.CheckerMessage; -import org.polarsys.chess.contracts.profile.chesscontract.util.EntityUtil; - -/** - * Two checkers that detect unreachable states and states without transitions to other - * states, inside a StateMachine. - * - * @author cristofo - * - */ -public class StateStatus extends Checker { - private Package systemViewPackage; - protected static final Logger logger = Logger.getLogger(StateStatus.class); - private final EntityUtil entityUtil = EntityUtil.getInstance(); - private static final String checkerName = "StateStatus"; - - /** - * Creates a state checker - */ - public StateStatus() { - super(checkerName, getTags()); - } - - /** - * Creates a state checker with the given priority - * @param priority the priority - */ - public StateStatus(int priority) { - super(checkerName, getTags(), priority); - } - - /** - * Constructor with explicit tags. - * @param tags the tags identifying this checker - */ - public StateStatus(Set<String> tags) { - super(checkerName, tags); - } - - /** - * Constructor with explicit tags and priority. - * @param tags the tags identifying this checker - * @param priority the priority - */ - public StateStatus(Set<String> tags, int priority) { - super(checkerName, tags, priority); - } - - private static Set<String> getTags() { - Set<String> tags = new HashSet<String>(); - tags.add("fast"); - tags.add("errors"); - tags.add("state machine"); - return tags; - } - - @Override - public List<CheckerMessage> check(IProgressMonitor monitor) throws Exception { - List<CheckerMessage> messages = new ArrayList<CheckerMessage>(); - Collection<Class> blocks = null; - blocks = getBlocks(systemViewPackage); - - monitor.beginTask(unifiedName, blocks.size()); - for (Class block : blocks) { -// warnings.addAll(checkForDeadAndUnreachableStates(block)); - messages.addAll(checkForDeadStates(block)); - messages.addAll(checkForUnreachableStates(block)); - if (monitor.isCanceled()) - throw new Exception("Checker interrupted"); - monitor.worked(1); - } - return messages; - } - - /** - * Returns the blocks that should be checked inside the model. Can be overwritter if necessary. - * @param systemViewPackage - * @return - */ - protected Collection<Class> getBlocks(Package systemViewPackage) { - try { - return (Collection<Class>) EntityUtil.getInstance().getAllClasses(systemViewPackage); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * A dead state is a state with no transitions to other states. - * @param block - * @return list of errors - */ - protected List<CheckerMessage> checkForDeadStates(Class block) { - List<CheckerMessage> errors = new ArrayList<CheckerMessage>(); - - final Set<StateMachine> stateMachines = entityUtil.getNominalStateMachines(block); - if (stateMachines.isEmpty()) { - logger.error("No state machines are present in block " + block.getName()); - } - - for (StateMachine stateMachine : stateMachines) { - if (stateMachine == null) continue; - final String stateMachineName = stateMachine.getName(); - final Region region = stateMachine.getRegion(null); // Assume that only one region is present - if (region == null) { - logger.error("State machine " + stateMachineName + " of block " + block.getName() + - " is not valid"); - continue; - } - - // If there is only one intermediate state, don't do any check - if (entityUtil.getIntermediateStates(stateMachine).size() <= 1) continue; - - final EList<Vertex> states = entityUtil.getStates(stateMachine); - final List<String> deadStates = new ArrayList<String>(1); - for (Vertex state : states) { - if (entityUtil.isFinalState(state)) continue; - boolean dead = true; - final EList<Transition> outgoingTransitions = entityUtil.getOutgoingTransitions(state); - for (Transition transition : outgoingTransitions) { - if (entityUtil.getTransitionNextState(transition) != state) { - dead = false; - break; - } - } - if (dead) { - final String msg = deadMsg(state, block); - errors.add(createMessage(msg, IMarker.SEVERITY_ERROR, state, unifiedName)); - - deadStates.add(state.getName()); - } - } - if (deadStates.size() == 0) { - logger.debug("State machine " + stateMachineName + ": all states are valid"); - } else { - logger.error("State machine " + stateMachineName + ": the following states are dead: " + - String.join(", ", deadStates)); - } - } - - return errors; - } - - /** - * An unreachable state is a state that is no reachable from other states. - * @param block - * @return list of errors - */ - private List<CheckerMessage> checkForUnreachableStates(Class block) { - List<CheckerMessage> errors = new ArrayList<CheckerMessage>(); - - final Set<StateMachine> stateMachines = entityUtil.getNominalStateMachines(block); - if (stateMachines.isEmpty()) { - logger.error("No state machines are present in block " + block.getName()); - } - - for (StateMachine stateMachine : stateMachines) { - if (stateMachine == null) continue; - final String stateMachineName = stateMachine.getName(); - final Region region = stateMachine.getRegion(null); // Assume that only one region is present - if (region == null) { - logger.error("State machine " + stateMachineName + " of block " + block.getName() + - " is not valid"); - continue; - } - final EList<Vertex> states = entityUtil.getIntermediateStates(stateMachine); - final List<String> unreachableStates = new ArrayList<String>(1); - for (Vertex state : states) { - boolean unreachable = true; - final EList<Transition> incomingTransitions = entityUtil.getIncomingTransitions(state); - for (Transition transition : incomingTransitions) { - if (entityUtil.getTransitionSourceState(transition) != state) { - unreachable = false; - break; - } - } - if (unreachable) { - final String msg = unreachableMsg(state, block); - errors.add(createMessage(msg, IMarker.SEVERITY_ERROR, state, unifiedName)); - unreachableStates.add(state.getName()); - } - } - if (unreachableStates.size() == 0) { - logger.debug("State machine " + stateMachineName + ": all states are valid"); - } else { - logger.error("State machine " + stateMachineName + ": the following states are not reachable: " + - String.join(", ", unreachableStates)); - } - } - - return errors; - } - - /** - * An unreachable state is a state that is no reachable from other states. - * @param block - * @return list of errors - */ - private List<CheckerMessage> checkForDeadAndUnreachableStates(Class block) { - List<CheckerMessage> errors = new ArrayList<CheckerMessage>(); - - final Set<StateMachine> stateMachines = entityUtil.getNominalStateMachines(block); - if (stateMachines.isEmpty()) { - logger.error("No state machines are present in block " + block.getName()); - } - - for (StateMachine stateMachine : stateMachines) { - if (stateMachine == null) continue; - final String stateMachineName = stateMachine.getName(); - final Region region = stateMachine.getRegion(null); // Assume that only one region is present - if (region == null) { - logger.error("State machine " + stateMachineName + " of block " + block.getName() + - " is not valid"); - continue; - } - final EList<Vertex> states = entityUtil.getStates(stateMachine); - final List<String> deadStates = new ArrayList<String>(1); - final List<String> unreachableStates = new ArrayList<String>(1); - - int stateCounter = 0; - for (Vertex state : states) { - if (!entityUtil.isFinalState(state)) { - stateCounter++; - } - } - - for (Vertex state : states) { - boolean dead = false; - boolean unreachable = false; - if (!entityUtil.isFinalState(state)) { - dead = true; - final EList<Transition> outgoingTransitions = entityUtil.getOutgoingTransitions(state); - for (Transition transition : outgoingTransitions) { - if (entityUtil.getTransitionNextState(transition) != state) { - dead = false; - break; - } - } - } - - if (!entityUtil.isInitialState(state)) { - unreachable = true; - final EList<Transition> incomingTransitions = entityUtil.getIncomingTransitions(state); - for (Transition transition : incomingTransitions) { - if (entityUtil.getTransitionSourceState(transition) != state) { - unreachable = false; - break; - } - } - } - - if ((dead && stateCounter > 2)) { - final String msg = deadMsg(state, block); - errors.add(createMessage(msg, IMarker.SEVERITY_ERROR, state, unifiedName)); - deadStates.add(state.getName()); - } - - if ((unreachable)) { - final String msg = unreachableMsg(state, block); - errors.add(createMessage(msg, IMarker.SEVERITY_ERROR, state, unifiedName)); - unreachableStates.add(state.getName()); - } - } - if (deadStates.size() == 0) { - logger.debug("State machine " + stateMachineName + ": all states are valid"); - } else { - logger.error("State machine " + stateMachineName + ": the following states are dead: " + - String.join(", ", deadStates)); - } - if (unreachableStates.size() == 0) { - logger.debug("State machine " + stateMachineName + ": all states are valid"); - } else { - logger.error("State machine " + stateMachineName + ": the following states are not reachable: " + - String.join(", ", unreachableStates)); - } - } - return errors; - } - - protected CheckerMessage createMessage(String msg, int severity, EObject state, String unifiedName) { - return new CheckerMessage(msg, severity, state, unifiedName); - } - - protected String deadMsg(Vertex state, Class block) { - return "The state '" + state.getName() + "' of block '" + - block.getName() + "' does not have any transitions to other states"; - } - - protected String unreachableMsg(Vertex state, Class block) { - return "The state '" + state.getName() + "' of block '" + - block.getName() + "' is never reachable"; - } - - @Override - public void init() throws Exception { - systemViewPackage = EntityUtil.getInstance().getCurrentSystemView(); - - //TODO: aprire esattamente il progetto corretto, dove sono quando lancio il check? Devo essere su un progetto, - // e quello viene analizzato - } -} +/******************************************************************************* + * Copyright (C) 2020 Fondazione Bruno Kessler. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v2.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v20.html + ******************************************************************************/ +package org.polarsys.chess.checkers.core.impl; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.apache.log4j.Logger; +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.emf.common.util.EList; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.uml2.uml.Class; +import org.eclipse.uml2.uml.Package; +import org.eclipse.uml2.uml.Region; +import org.eclipse.uml2.uml.StateMachine; +import org.eclipse.uml2.uml.Transition; +import org.eclipse.uml2.uml.Vertex; +import org.polarsys.chess.checkers.core.checkerManager.Checker; +import org.polarsys.chess.checkers.core.checkerManager.CheckerMessage; +import org.polarsys.chess.contracts.profile.chesscontract.util.EntityUtil; + +/** + * Two checkers that detect unreachable states and states without transitions to other + * states, inside a StateMachine. + * + * @author cristofo + * + */ +public class StateStatus extends Checker { + private Package systemViewPackage; + protected static final Logger logger = Logger.getLogger(StateStatus.class); + private final EntityUtil entityUtil = EntityUtil.getInstance(); + private static final String checkerName = "StateStatus"; + + /** + * Creates a state checker + */ + public StateStatus() { + super(checkerName, getTags()); + } + + /** + * Creates a state checker with the given priority + * @param priority the priority + */ + public StateStatus(int priority) { + super(checkerName, getTags(), priority); + } + + /** + * Constructor with explicit tags. + * @param tags the tags identifying this checker + */ + public StateStatus(Set<String> tags) { + super(checkerName, tags); + } + + /** + * Constructor with explicit tags and priority. + * @param tags the tags identifying this checker + * @param priority the priority + */ + public StateStatus(Set<String> tags, int priority) { + super(checkerName, tags, priority); + } + + private static Set<String> getTags() { + Set<String> tags = new HashSet<String>(); + tags.add("fast"); + tags.add("errors"); + tags.add("state machine"); + return tags; + } + + @Override + public List<CheckerMessage> check(IProgressMonitor monitor) throws Exception { + List<CheckerMessage> messages = new ArrayList<CheckerMessage>(); + Collection<Class> blocks = null; + blocks = getBlocks(systemViewPackage); + + monitor.beginTask(unifiedName, blocks.size()); + for (Class block : blocks) { +// warnings.addAll(checkForDeadAndUnreachableStates(block)); + messages.addAll(checkForDeadStates(block)); + messages.addAll(checkForUnreachableStates(block)); + if (monitor.isCanceled()) + throw new Exception("Checker interrupted"); + monitor.worked(1); + } + return messages; + } + + /** + * Returns the blocks that should be checked inside the model. Can be overwritter if necessary. + * @param systemViewPackage + * @return + */ + protected Collection<Class> getBlocks(Package systemViewPackage) { + try { + return (Collection<Class>) EntityUtil.getInstance().getAllClasses(systemViewPackage); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * A dead state is a state with no transitions to other states. + * @param block + * @return list of errors + */ + protected List<CheckerMessage> checkForDeadStates(Class block) { + List<CheckerMessage> errors = new ArrayList<CheckerMessage>(); + + final Set<StateMachine> stateMachines = entityUtil.getNominalStateMachines(block); + if (stateMachines.isEmpty()) { + logger.error("No state machines are present in block " + block.getName()); + } + + for (StateMachine stateMachine : stateMachines) { + if (stateMachine == null) continue; + final String stateMachineName = stateMachine.getName(); + final Region region = stateMachine.getRegion(null); // Assume that only one region is present + if (region == null) { + logger.error("State machine " + stateMachineName + " of block " + block.getName() + + " is not valid"); + continue; + } + + // If there is only one intermediate state, don't do any check + if (entityUtil.getIntermediateStates(stateMachine).size() <= 1) continue; + + final EList<Vertex> states = entityUtil.getStates(stateMachine); + final List<String> deadStates = new ArrayList<String>(1); + for (Vertex state : states) { + if (entityUtil.isFinalState(state)) continue; + boolean dead = true; + final EList<Transition> outgoingTransitions = entityUtil.getOutgoingTransitions(state); + for (Transition transition : outgoingTransitions) { + if (entityUtil.getTransitionNextState(transition) != state) { + dead = false; + break; + } + } + if (dead) { + final String msg = deadMsg(state, block); + errors.add(createMessage(msg, IMarker.SEVERITY_ERROR, state, unifiedName)); + + deadStates.add(state.getName()); + } + } + if (deadStates.size() == 0) { + logger.debug("State machine " + stateMachineName + ": all states are valid"); + } else { + logger.error("State machine " + stateMachineName + ": the following states are dead: " + + String.join(", ", deadStates)); + } + } + + return errors; + } + + /** + * An unreachable state is a state that is no reachable from other states. + * @param block + * @return list of errors + */ + private List<CheckerMessage> checkForUnreachableStates(Class block) { + List<CheckerMessage> errors = new ArrayList<CheckerMessage>(); + + final Set<StateMachine> stateMachines = entityUtil.getNominalStateMachines(block); + if (stateMachines.isEmpty()) { + logger.error("No state machines are present in block " + block.getName()); + } + + for (StateMachine stateMachine : stateMachines) { + if (stateMachine == null) continue; + final String stateMachineName = stateMachine.getName(); + final Region region = stateMachine.getRegion(null); // Assume that only one region is present + if (region == null) { + logger.error("State machine " + stateMachineName + " of block " + block.getName() + + " is not valid"); + continue; + } + final EList<Vertex> states = entityUtil.getIntermediateStates(stateMachine); + final List<String> unreachableStates = new ArrayList<String>(1); + for (Vertex state : states) { + boolean unreachable = true; + final EList<Transition> incomingTransitions = entityUtil.getIncomingTransitions(state); + for (Transition transition : incomingTransitions) { + if (entityUtil.getTransitionSourceState(transition) != state) { + unreachable = false; + break; + } + } + if (unreachable) { + final String msg = unreachableMsg(state, block); + errors.add(createMessage(msg, IMarker.SEVERITY_ERROR, state, unifiedName)); + unreachableStates.add(state.getName()); + } + } + if (unreachableStates.size() == 0) { + logger.debug("State machine " + stateMachineName + ": all states are valid"); + } else { + logger.error("State machine " + stateMachineName + ": the following states are not reachable: " + + String.join(", ", unreachableStates)); + } + } + + return errors; + } + + /** + * An unreachable state is a state that is no reachable from other states. + * @param block + * @return list of errors + */ + private List<CheckerMessage> checkForDeadAndUnreachableStates(Class block) { + List<CheckerMessage> errors = new ArrayList<CheckerMessage>(); + + final Set<StateMachine> stateMachines = entityUtil.getNominalStateMachines(block); + if (stateMachines.isEmpty()) { + logger.error("No state machines are present in block " + block.getName()); + } + + for (StateMachine stateMachine : stateMachines) { + if (stateMachine == null) continue; + final String stateMachineName = stateMachine.getName(); + final Region region = stateMachine.getRegion(null); // Assume that only one region is present + if (region == null) { + logger.error("State machine " + stateMachineName + " of block " + block.getName() + + " is not valid"); + continue; + } + final EList<Vertex> states = entityUtil.getStates(stateMachine); + final List<String> deadStates = new ArrayList<String>(1); + final List<String> unreachableStates = new ArrayList<String>(1); + + int stateCounter = 0; + for (Vertex state : states) { + if (!entityUtil.isFinalState(state)) { + stateCounter++; + } + } + + for (Vertex state : states) { + boolean dead = false; + boolean unreachable = false; + if (!entityUtil.isFinalState(state)) { + dead = true; + final EList<Transition> outgoingTransitions = entityUtil.getOutgoingTransitions(state); + for (Transition transition : outgoingTransitions) { + if (entityUtil.getTransitionNextState(transition) != state) { + dead = false; + break; + } + } + } + + if (!entityUtil.isInitialState(state)) { + unreachable = true; + final EList<Transition> incomingTransitions = entityUtil.getIncomingTransitions(state); + for (Transition transition : incomingTransitions) { + if (entityUtil.getTransitionSourceState(transition) != state) { + unreachable = false; + break; + } + } + } + + if ((dead && stateCounter > 2)) { + final String msg = deadMsg(state, block); + errors.add(createMessage(msg, IMarker.SEVERITY_ERROR, state, unifiedName)); + deadStates.add(state.getName()); + } + + if ((unreachable)) { + final String msg = unreachableMsg(state, block); + errors.add(createMessage(msg, IMarker.SEVERITY_ERROR, state, unifiedName)); + unreachableStates.add(state.getName()); + } + } + if (deadStates.size() == 0) { + logger.debug("State machine " + stateMachineName + ": all states are valid"); + } else { + logger.error("State machine " + stateMachineName + ": the following states are dead: " + + String.join(", ", deadStates)); + } + if (unreachableStates.size() == 0) { + logger.debug("State machine " + stateMachineName + ": all states are valid"); + } else { + logger.error("State machine " + stateMachineName + ": the following states are not reachable: " + + String.join(", ", unreachableStates)); + } + } + return errors; + } + + protected CheckerMessage createMessage(String msg, int severity, EObject state, String unifiedName) { + return new CheckerMessage(msg, severity, state, unifiedName); + } + + protected String deadMsg(Vertex state, Class block) { + return "The state '" + state.getName() + "' of block '" + + block.getName() + "' does not have any transitions to other states"; + } + + protected String unreachableMsg(Vertex state, Class block) { + return "The state '" + state.getName() + "' of block '" + + block.getName() + "' is never reachable"; + } + + @Override + public void init() throws Exception { + systemViewPackage = EntityUtil.getInstance().getCurrentSystemView(); + + //TODO: aprire esattamente il progetto corretto, dove sono quando lancio il check? Devo essere su un progetto, + // e quello viene analizzato + } +} diff --git a/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/impl/TestChecker1.java b/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/impl/TestChecker1.java index 391caaaec216acfdc63f6066c0370595f9b1a66e..52596140100586458e661615b3ed58b04c785e5e 100644 --- a/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/impl/TestChecker1.java +++ b/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/impl/TestChecker1.java @@ -1,77 +1,84 @@ -package org.polarsys.chess.checkers.core.impl; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.emf.ecore.EObject; -import org.eclipse.emf.ecore.util.EcoreUtil; -import org.eclipse.emf.workspace.util.WorkspaceSynchronizer; -import org.polarsys.chess.checkers.core.checkerManager.Checker; -import org.polarsys.chess.checkers.core.checkerManager.CheckerMessage; -import org.polarsys.chess.contracts.profile.chesscontract.util.EntityUtil; - - -public class TestChecker1 extends Checker { - - org.eclipse.uml2.uml.Package systemViewPackage; - IResource resource; - IFile file; - public TestChecker1(String unifiedName, Set<String> checkerTags, int priority) { - super(unifiedName, checkerTags,priority); - } - - @Override - public List<CheckerMessage> check(IProgressMonitor monitor) throws Exception { - - monitor.beginTask(unifiedName, 3); - System.out.println("systemViewPackage: "+systemViewPackage); - //Resource resource = systemViewPackage.eResource(); - - //IResource resource = getResourceForModel(systemViewPackage); - List<CheckerMessage> res = new ArrayList<CheckerMessage>(); - long time = 0; - while(time<10){ - res.add(new CheckerMessage("StateMachineChecker2 "+time+" priority "+registerPriority, IMarker.SEVERITY_ERROR, systemViewPackage,unifiedName)); - TimeUnit.SECONDS.sleep(1); - time++; - monitor.worked(1); - } - return res; - } - - - - public IResource getResourceForModel(EObject obj) { - //org.eclipse.emf.common.util.URI uri = obj.eResource().getURI(); - org.eclipse.emf.common.util.URI uri = EcoreUtil.getURI(obj); - System.out.println("uri: "+uri); - // assuming platform://resource/project/path/to/file - String projectStr = uri.segment(1); - IPath path = new Path(uri.path()).removeFirstSegments(2); - System.out.println("path: "+path); - IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectStr); - System.out.println("project: "+project); - return project.findMember(path); - } - - @Override - public void init() throws Exception { - systemViewPackage = EntityUtil.getInstance().getCurrentSystemView(); - //resource = ResourcesPlugin.getWorkspace().getRoot(); - resource = getResourceForModel(systemViewPackage); - file = WorkspaceSynchronizer.getFile(systemViewPackage.eResource()); - System.out.println("resource: "+resource); - - } - - -} +/******************************************************************************* + * Copyright (C) 2020 Fondazione Bruno Kessler. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v2.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v20.html + ******************************************************************************/ +package org.polarsys.chess.checkers.core.impl; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import org.eclipse.core.runtime.Path; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.util.EcoreUtil; +import org.eclipse.emf.workspace.util.WorkspaceSynchronizer; +import org.polarsys.chess.checkers.core.checkerManager.Checker; +import org.polarsys.chess.checkers.core.checkerManager.CheckerMessage; +import org.polarsys.chess.contracts.profile.chesscontract.util.EntityUtil; + + +public class TestChecker1 extends Checker { + + org.eclipse.uml2.uml.Package systemViewPackage; + IResource resource; + IFile file; + public TestChecker1(String unifiedName, Set<String> checkerTags, int priority) { + super(unifiedName, checkerTags,priority); + } + + @Override + public List<CheckerMessage> check(IProgressMonitor monitor) throws Exception { + + monitor.beginTask(unifiedName, 3); + System.out.println("systemViewPackage: "+systemViewPackage); + //Resource resource = systemViewPackage.eResource(); + + //IResource resource = getResourceForModel(systemViewPackage); + List<CheckerMessage> res = new ArrayList<CheckerMessage>(); + long time = 0; + while(time<10){ + res.add(new CheckerMessage("StateMachineChecker2 "+time+" priority "+registerPriority, IMarker.SEVERITY_ERROR, systemViewPackage,unifiedName)); + TimeUnit.SECONDS.sleep(1); + time++; + monitor.worked(1); + } + return res; + } + + + + public IResource getResourceForModel(EObject obj) { + //org.eclipse.emf.common.util.URI uri = obj.eResource().getURI(); + org.eclipse.emf.common.util.URI uri = EcoreUtil.getURI(obj); + System.out.println("uri: "+uri); + // assuming platform://resource/project/path/to/file + String projectStr = uri.segment(1); + IPath path = new Path(uri.path()).removeFirstSegments(2); + System.out.println("path: "+path); + IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectStr); + System.out.println("project: "+project); + return project.findMember(path); + } + + @Override + public void init() throws Exception { + systemViewPackage = EntityUtil.getInstance().getCurrentSystemView(); + //resource = ResourcesPlugin.getWorkspace().getRoot(); + resource = getResourceForModel(systemViewPackage); + file = WorkspaceSynchronizer.getFile(systemViewPackage.eResource()); + System.out.println("resource: "+resource); + + } + + +} diff --git a/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/impl/TestChecker2.java b/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/impl/TestChecker2.java index dec8dc3018184bfa48874d8bdfeb3008efa83969..8d9dee450c7faa6d218e8fbd8e3ddab374ca426b 100644 --- a/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/impl/TestChecker2.java +++ b/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/impl/TestChecker2.java @@ -1,56 +1,63 @@ -package org.polarsys.chess.checkers.core.impl; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import java.util.concurrent.TimeUnit; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.Status; -import org.eclipse.emf.workspace.util.WorkspaceSynchronizer; -import org.polarsys.chess.checkers.core.checkerManager.Checker; -import org.polarsys.chess.checkers.core.checkerManager.CheckerMessage; -import org.polarsys.chess.contracts.profile.chesscontract.util.EntityUtil; - - -public class TestChecker2 extends Checker { - - org.eclipse.uml2.uml.Package systemViewPackage; - private IFile file; - - public TestChecker2(String unifiedName, Set<String> checkerTags) { - super(unifiedName, checkerTags); - } - - - @Override - public List<CheckerMessage> check(IProgressMonitor monitor) throws Exception { - - monitor.beginTask(unifiedName, 6); - - List<CheckerMessage> res = new ArrayList<CheckerMessage>(); - long time = 0; - while(time<6){ - res.add(new CheckerMessage("SysMLChecker1 "+time, IMarker.SEVERITY_ERROR,systemViewPackage,unifiedName)); - if (monitor.isCanceled()) { - System.out.println("monitor.isCanceled()"); - throw new Exception(); - } - TimeUnit.SECONDS.sleep(1); - time++; - monitor.worked(1); - } - return res; - } - - - @Override - public void init() throws Exception { - systemViewPackage = EntityUtil.getInstance().getCurrentSystemView(); - file = WorkspaceSynchronizer.getFile(systemViewPackage.eResource()); - - } - -} +/******************************************************************************* + * Copyright (C) 2020 Fondazione Bruno Kessler. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v2.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v20.html + ******************************************************************************/ +package org.polarsys.chess.checkers.core.impl; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.Status; +import org.eclipse.emf.workspace.util.WorkspaceSynchronizer; +import org.polarsys.chess.checkers.core.checkerManager.Checker; +import org.polarsys.chess.checkers.core.checkerManager.CheckerMessage; +import org.polarsys.chess.contracts.profile.chesscontract.util.EntityUtil; + + +public class TestChecker2 extends Checker { + + org.eclipse.uml2.uml.Package systemViewPackage; + private IFile file; + + public TestChecker2(String unifiedName, Set<String> checkerTags) { + super(unifiedName, checkerTags); + } + + + @Override + public List<CheckerMessage> check(IProgressMonitor monitor) throws Exception { + + monitor.beginTask(unifiedName, 6); + + List<CheckerMessage> res = new ArrayList<CheckerMessage>(); + long time = 0; + while(time<6){ + res.add(new CheckerMessage("SysMLChecker1 "+time, IMarker.SEVERITY_ERROR,systemViewPackage,unifiedName)); + if (monitor.isCanceled()) { + System.out.println("monitor.isCanceled()"); + throw new Exception(); + } + TimeUnit.SECONDS.sleep(1); + time++; + monitor.worked(1); + } + return res; + } + + + @Override + public void init() throws Exception { + systemViewPackage = EntityUtil.getInstance().getCurrentSystemView(); + file = WorkspaceSynchronizer.getFile(systemViewPackage.eResource()); + + } + +} diff --git a/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/utils/HashCodeUtils.java b/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/utils/HashCodeUtils.java index ba09ca4d72cf574a5f069f3a032992f098aa68d0..b17d297264e369be98965cba2292f59e3ed73771 100644 --- a/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/utils/HashCodeUtils.java +++ b/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/core/utils/HashCodeUtils.java @@ -1,78 +1,85 @@ -package org.polarsys.chess.checkers.core.utils; - -import java.util.Objects; - -import org.apache.log4j.Logger; -import org.eclipse.uml2.uml.Class; -import org.eclipse.uml2.uml.Enumeration; -import org.eclipse.uml2.uml.EnumerationLiteral; -import org.eclipse.uml2.uml.Package; -import org.eclipse.uml2.uml.Property; -import org.polarsys.chess.contracts.profile.chesscontract.util.EntityUtil; - -public class HashCodeUtils { - private static final Logger logger = Logger.getLogger(HashCodeUtils.class); - - public int hashCodeStructuralPart(Package mainPackage) throws Exception { - int hash = 0; - for (Class clazz : EntityUtil.getInstance().getAllClasses(mainPackage)) { - int hashClass = hashCodeClassStructuralPart(clazz); - hash = Objects.hash(hash, hashClass); - } - - logger.warn("hash for classes: " + hash); - - int hashEnums = Objects.hash(EntityUtil.getInstance().getAllEnumeratives(mainPackage)); - for (Enumeration enumeration : EntityUtil.getInstance().getAllEnumeratives(mainPackage)) { - int hashEnum = hashCodeEnumeration(enumeration); - hash = Objects.hash(hash, hashEnum); - } - - logger.warn("hash for enums: " + hashEnums); - - hash = Objects.hash(hash, hashEnums); - - return hash; - } - - public int hashCodeClassStructuralPart(Class clazz) { - int hash = clazz.getName().hashCode(); - for (Property property : clazz.allAttributes()) { - int hashProperty = hashCodeAttribute(property); - hash = Objects.hash(hash, hashProperty); - } - - logger.warn("hash for class " + clazz.getName() + ": " + hash); - - return hash; - } - - public int hashCodeAttribute(Property property) { - - int hash = Objects.hash(property.getName(), property.getType().getName()); - logger.warn("hash for property " + property.getName() + ": " + hash); - - return hash; - } - - public int hashCodeEnumeration(Enumeration enumeration) { - - int hash = enumeration.hashCode(); - for (EnumerationLiteral literal : enumeration.getOwnedLiterals()) { - int hashLiteral = hashCodeLiteral(literal); - hash = Objects.hash(hash, hashLiteral); - } - - logger.warn("hash for enum " + enumeration.getName() + ": " + hash); - - return hash; - } - - public int hashCodeLiteral(EnumerationLiteral literal) { - - int hash = literal.getName().hashCode(); - logger.warn("hash for literal " + literal.getName() + ": " + hash); - - return hash; - } -} +/******************************************************************************* + * Copyright (C) 2020 Fondazione Bruno Kessler. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v2.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v20.html + ******************************************************************************/ +package org.polarsys.chess.checkers.core.utils; + +import java.util.Objects; + +import org.apache.log4j.Logger; +import org.eclipse.uml2.uml.Class; +import org.eclipse.uml2.uml.Enumeration; +import org.eclipse.uml2.uml.EnumerationLiteral; +import org.eclipse.uml2.uml.Package; +import org.eclipse.uml2.uml.Property; +import org.polarsys.chess.contracts.profile.chesscontract.util.EntityUtil; + +public class HashCodeUtils { + private static final Logger logger = Logger.getLogger(HashCodeUtils.class); + + public int hashCodeStructuralPart(Package mainPackage) throws Exception { + int hash = 0; + for (Class clazz : EntityUtil.getInstance().getAllClasses(mainPackage)) { + int hashClass = hashCodeClassStructuralPart(clazz); + hash = Objects.hash(hash, hashClass); + } + + logger.warn("hash for classes: " + hash); + + int hashEnums = Objects.hash(EntityUtil.getInstance().getAllEnumeratives(mainPackage)); + for (Enumeration enumeration : EntityUtil.getInstance().getAllEnumeratives(mainPackage)) { + int hashEnum = hashCodeEnumeration(enumeration); + hash = Objects.hash(hash, hashEnum); + } + + logger.warn("hash for enums: " + hashEnums); + + hash = Objects.hash(hash, hashEnums); + + return hash; + } + + public int hashCodeClassStructuralPart(Class clazz) { + int hash = clazz.getName().hashCode(); + for (Property property : clazz.allAttributes()) { + int hashProperty = hashCodeAttribute(property); + hash = Objects.hash(hash, hashProperty); + } + + logger.warn("hash for class " + clazz.getName() + ": " + hash); + + return hash; + } + + public int hashCodeAttribute(Property property) { + + int hash = Objects.hash(property.getName(), property.getType().getName()); + logger.warn("hash for property " + property.getName() + ": " + hash); + + return hash; + } + + public int hashCodeEnumeration(Enumeration enumeration) { + + int hash = enumeration.hashCode(); + for (EnumerationLiteral literal : enumeration.getOwnedLiterals()) { + int hashLiteral = hashCodeLiteral(literal); + hash = Objects.hash(hash, hashLiteral); + } + + logger.warn("hash for enum " + enumeration.getName() + ": " + hash); + + return hash; + } + + public int hashCodeLiteral(EnumerationLiteral literal) { + + int hash = literal.getName().hashCode(); + logger.warn("hash for literal " + literal.getName() + ": " + hash); + + return hash; + } +} diff --git a/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/ui/commands/RunCheckers.java b/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/ui/commands/RunCheckers.java index 237e1133c64ea1867f4cbf2c9bff18fbc99d184f..502f6c2ba8ddd2dc16ba89e20a8e7fd12aad165e 100644 --- a/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/ui/commands/RunCheckers.java +++ b/plugins/org.polarsys.chess.checkers/src/org/polarsys/chess/checkers/ui/commands/RunCheckers.java @@ -1,31 +1,38 @@ -package org.polarsys.chess.checkers.ui.commands; - -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.polarsys.chess.checkers.Activator; -import eu.fbk.eclipse.standardtools.utils.ui.utils.DialogUtil; - -import org.apache.log4j.Logger; - -public class RunCheckers extends AbstractHandler { - - private static final Logger logger = Logger.getLogger(RunCheckers.class); - - public RunCheckers() { - } - - @Override - public Object execute(ExecutionEvent event) throws ExecutionException { - try { - Activator.getCheckerManager().run(Activator.getDefault().getTags()); - } catch (Exception e) { - e.printStackTrace(); - logger.error(e); - DialogUtil.getInstance().showMessage_ExceptionError(e); - } - - return null; - } - -} +/******************************************************************************* + * Copyright (C) 2020 Fondazione Bruno Kessler. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v2.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v20.html + ******************************************************************************/ +package org.polarsys.chess.checkers.ui.commands; + +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.commands.ExecutionException; +import org.polarsys.chess.checkers.Activator; +import eu.fbk.eclipse.standardtools.utils.ui.utils.DialogUtil; + +import org.apache.log4j.Logger; + +public class RunCheckers extends AbstractHandler { + + private static final Logger logger = Logger.getLogger(RunCheckers.class); + + public RunCheckers() { + } + + @Override + public Object execute(ExecutionEvent event) throws ExecutionException { + try { + Activator.getCheckerManager().run(Activator.getDefault().getTags()); + } catch (Exception e) { + e.printStackTrace(); + logger.error(e); + DialogUtil.getInstance().showMessage_ExceptionError(e); + } + + return null; + } + +}