Initial import.

This commit is contained in:
Achim D. Brucker 2016-12-26 14:51:39 +00:00
parent c352de5bac
commit 9d9a1e8e8d
205 changed files with 27940 additions and 0 deletions

4
.gitignore vendored
View File

@ -12,3 +12,7 @@
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
# local ignores
local.properties
build

226
build.xml Normal file
View File

@ -0,0 +1,226 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="argouml-module" default="usage" basedir=".">
<property file="local.properties"/>
<property file="module.properties"/>
<property name="Name" value="ArgoModule-${argo.module.name}"/>
<property name="name" value="argomodule-${argo.module.name}"/>
<tstamp>
<format property="year" pattern="yyyy"/>
</tstamp>
<property name="version" value="0.9.3-${DSTAMP}-${TSTAMP}"/>
<echo message="------------------- ${Name} ${version} [${year}] ----------------" level="info"/>
<path id="argo.classpath">
<pathelement path="${classpath}"/>
<fileset dir="${argo.home.dir}">
<include name="**/*.jar"/>
</fileset>
<pathelement location="classes"/>
<pathelement location="${junit.lib.file}"/>
</path>
<property name="module.build.dir" value="build"/>
<property name="module.build.src" value="src"/>
<property name="module.build.dest" value="${module.build.dir}/classes"/>
<property name="javadoc.dir" value="${basedir}/javadoc"/>
<property name="packages" value="ch.ethz.*"/>
<property name="manifest" value="manifest.mf"/>
<property name="manifest.src" value="${module.build.src}/${manifest}"/>
<property name="module.jarfile.name" value="${argo.module.jarfile}.jar"/>
<property name="module.jarfile" value="${module.build.dir}/${module.jarfile.name}"/>
<property name="test.src" value="test"/>
<property name="test.dir" value="${module.build.dir}/test"/>
<property name="test.data.dir" value="${test.dir}/data"/>
<property name="test.reports.dir" value="${test.dir}/reports"/>
<property file="${user.home}/.argo.ant.properties"/>
<property file="${user.home}/.ant.properties"/>
<!-- Compiler flags -->
<property name="debug" value="on"/>
<property name="optimize" value="off"/>
<property name="deprecation" value="off"/>
<property name="developer.lib.dir" value="${argo.build.dir}"/>
<property name="pmd.report.file" value="pmd_report.html"/>
<property name="argo.log.file.name" value="out.txt"/>
<!-- =================================================================== -->
<!-- Initialization target -->
<!-- =================================================================== -->
<target name="init">
<!-- create directories -->
<mkdir dir="${module.build.dest}"/>
<mkdir dir="${test.dir}"/>
<delete dir="${test.reports.dir}"/>
<delete dir="${test.data.dir}"/>
<mkdir dir="${test.reports.dir}"/>
<mkdir dir="${test.data.dir}"/>
</target>
<!-- Note this file can only make Ant display values set in the file correctly, -->
<!-- but external values in the environment or properties file will be operational. -->
<!-- =================================================================== -->
<!-- Help on usage -->
<!-- =================================================================== -->
<target name="usage" depends="init" description="Show the usage and the different targets">
<echo level="info">
${Name} Build file
-------------------------------------------------------------
available targets are:
usage --&gt; Show this message (default).
compile --&gt; Compiles the source code to the tree under '${module.build.src}'.
package --&gt; Generates the '${module.jarfile.name}' file.
install --&gt; Install module '${argo.module.name}'.
clean --&gt; Removes compiled files.
javadoc --&gt; Generates the JavaDoc in '${javadoc.dir}'.
checkstyle --&gt; Check code style with CheckStyle
pmd --&gt; Check the code sanity with PMD and write the report to '${pmd.report.file}'.
junit --&gt; Run the JUnit test suites.
run --&gt; Run argouml with the newest version of the secure uml module.
Caution:
=========
The build process assumes that ${argo.hom} points to
the ArgoUML installation, i.e., the directory that
contains the ArgoUML jar files. For example, this property
can be set on the command line as follows:
ant -Dargo.home.dir="/usr/local/argouml-0.24/" install
or you may adapt the property in the 'local.properties' file.
-------------------------------------------------------------
</echo>
</target>
<!-- =================================================================== -->
<!-- Compiles the source directory -->
<!-- =================================================================== -->
<target name="compile" depends="init" description="Compile the project">
<javac srcdir="${module.build.src}" destdir="${module.build.dest}" excludes="*.txt,*.bat,*.xml,*.sh" debug="${debug}" deprecation="${deprecation}" optimize="${optimize}">
<classpath>
<path refid="argo.classpath"/>
</classpath>
</javac>
</target>
<!-- =================================================================== -->
<!-- Creates the class package -->
<!-- =================================================================== -->
<target name="package" depends="compile" description="Generate the jar package of the module">
<filter token="version" value="${version}"/>
<copy file="${manifest.src}" tofile="${module.build.dest}/${manifest}" filtering="on" overwrite="on"/>
<copy todir="${module.build.dest}">
<fileset dir="${module.build.src}" includes="**/*.png"/>
</copy>
<jar jarfile="${module.jarfile}" basedir="${module.build.dest}" includes="ch/ethz/**,**/*.png,**/*.xmi" excludes="*.txt,*.bat,*.xml,*.sh,${manifest}" manifest="${module.build.dest}/${manifest}"/>
</target>
<!-- =================================================================== -->
<!-- Clean targets -->
<!-- =================================================================== -->
<target name="clean" description="Remove the compiled files">
<delete includeemptydirs="true">
<fileset dir="build" includes="**/*"/>
</delete>
</target>
<!-- =================================================================== -->
<!-- Move the jar file into the extension directory. -->
<!-- =================================================================== -->
<target name="install" depends="package" description="Install the newest module in the argouml 'ext' directory">
<copy todir="${argo.home.dir}/ext">
<fileset dir="${module.build.dir}" includes="${module.jarfile.name}"/>
<fileset dir="metamodels" includes="**/*mof.xmi"/>
</copy>
<!-- <mkdir dir="${argo.home.dir}/ext/icons"/> -->
<!-- <copy todir="${argo.home.dir}/ext/icons"> -->
<!-- <fileset dir="icons" includes="**/*.png"/> -->
<!-- </copy> -->
</target>
<!-- Generate javadoc -->
<target name="javadoc" description="Generate JavaDoc in '${javadoc.dir}'">
<path id="javadoc.path">
<pathelement location="${module.build.src}"/>
<pathelement location="${test.src}"/>
</path>
<javadoc sourcepathref="javadoc.path" destdir="${javadoc.dir}" access="private" overview="${module.build.src}/overview.html">
<group title="SecureUML GUI">
<package name="ch.ethz.*"/>
<!-- <excludepackage name="ch.ethz.infsec.secureumlgui.usecasemapper.*" /> -->
</group>
<group title="Use-Case Mapper" packages="ch.ethz.infsec.secureumlgui.usecasemapper.*"/>
<classpath>
<pathelement location="${junit.lib.file}"/>
<pathelement location="${module.build.src}"/>
<path refid="argo.classpath"/>
</classpath>
</javadoc>
</target>
<!-- Check code style with CheckStyle -->
<target name="checkstyle" description="Check code style with CheckStyle" depends="init">
<path id="checkstyle.path">
<pathelement location="${checkstyle.lib.path}/checkstyle-all-4.4.jar"/>
</path>
<taskdef resource="checkstyletask.properties" classpathref="checkstyle.path"/>
<checkstyle config="checkstyle.xml" failOnViolation="false" failureProperty="test.failed">
<classpath refid="argo.classpath"/>
<fileset dir="${module.build.src}" includes="**/usecasemapper/**/*.java"/>
<fileset dir="${test.src}" includes="**/usecasemapper/**/*.java"/>
<formatter type="plain"/>
<formatter type="xml" toFile="${test.data.dir}/checkstyle_report.xml"/>
</checkstyle>
<xslt in="${test.data.dir}/checkstyle_report.xml" out="${test.reports.dir}/checkstyle_report.html" style="${checkstyle.lib.path}/contrib/checkstyle-frames.xsl"/>
</target>
<!-- Check code sanity with PMD -->
<target name="pmd" description="Check code sanity with PMD and write to '${pmd.report.file}'" depends="init">
<path id="pmd.classpath">
<fileset dir="${pmd.lib.path}">
<include name="**/*.jar"/>
</fileset>
</path>
<taskdef name="pmd" classname="net.sourceforge.pmd.ant.PMDTask" classpathref="pmd.classpath"/>
<pmd rulesetfiles="basic,braces,codesize,coupling,design,imports,logging-java,naming,optimizations,strings,unusedcode" shortFilenames="true">
<formatter type="html" toFile="${test.reports.dir}/${pmd.report.file}" linkPrefix="http://pmd.sourceforge.net/xref/"/>
<fileset dir="${module.build.src}">
<include name="**/usecasemapper/**/*.java"/>
</fileset>
<fileset dir="${test.src}" includes="**/usecasemapper/**/*.java"/>
</pmd>
</target>
<!-- Compile JUnit tests -->
<target name="test-compile" depends="init">
<javac srcdir="${test.src}" destdir="${module.build.dest}" excludes="*.txt,*.bat,*.xml,*.sh" debug="${debug}" deprecation="${deprecation}" optimize="${optimize}">
<classpath>
<pathelement location="${junit.lib.file}"/>
<pathelement path="${module.build.dest}"/>
<path refid="argo.classpath"/>
</classpath>
</javac>
</target>
<!-- Run JUnit tests -->
<!-- Note: The junitreport-task requires an XSLT-processor, so to use the
XML-reporting you must have a XSLT-Library in your ant environment, ie.
in $ANT_HOME/lib or ~/.ant/lib or passed either by the $ANT_ARGS environment variable
or directly to ant with the option -lib.
For this setup, the xalan XSLT-processor http://xml.apache.org/xalan-j/ has been used. -->
<target name="test" depends="compile, test-compile" description="Runs the JUnit test suites">
<junit fork="true" errorProperty="test.failed" failureProperty="test.failed">
<formatter type="brief" usefile="false"/>
<formatter type="xml"/>
<classpath>
<pathelement location="${junit.lib.file}"/>
<pathelement path="${module.build.dest}"/>
<path refid="argo.classpath"/>
<pathelement location="${test.src}"/>
</classpath>
<batchtest todir="${test.data.dir}">
<fileset dir="${module.build.dest}" includes="**/*Test.class"/>
</batchtest>
</junit>
<junitreport todir="${test.data.dir}">
<fileset dir="${test.data.dir}" includes="TEST-*.xml"/>
<report format="frames" todir="${test.reports.dir}"/>
</junitreport>
<fail message="Tests failed!" if="test.failed"/>
</target>
<!-- Run argouml with newest module -->
<target name="run" depends="install" description="Starts argouml with the newest version of the SecureUML GUI">
<java dir="${argo.home.dir}" jar="${argo.home.dir}/argouml.jar" fork="true" failOnError="true" output="${argo.log.file.name}">
<classpath>
<pathelement location="${argo.home.dir}"/>
</classpath>
<!-- <jvmarg value="-Dlog4j.configuration=org/argouml/resource/full_console.lcf"/> -->
</java>
</target>
</project>
<!-- End of file -->

1
local.properties.in Normal file
View File

@ -0,0 +1 @@
argo.home.dir=<ArgoUML 0.26 installation directory>

View File

@ -0,0 +1,14 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui;
import java.io.File;
/**
*
*/
public interface DialectMetamodelSelectedListener
{
public void dialectMetamodelSelected(File xmiFile);
}

View File

@ -0,0 +1,386 @@
package ch.ethz.infsec.secureumlgui;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import org.argouml.ui.targetmanager.TargetManager;
import org.omg.uml.foundation.core.AssociationClass;
import org.omg.uml.foundation.core.Namespace;
import org.omg.uml.foundation.core.Attribute;
import org.omg.uml.foundation.core.ModelElement;
import org.omg.uml.foundation.core.Operation;
import org.omg.uml.foundation.core.UmlClass;
//import ch.ethz.infsec.secureumlgui.gui.SecureUmlComponentManager;
import ch.ethz.infsec.secureumlgui.logging.MultiContextLogger;
import ch.ethz.infsec.secureumlgui.modelmapping.GenericDialectHelper;
import ch.ethz.infsec.secureumlgui.modelmapping.GenericDialectModelMapper;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.DialectMetaModelInfo;
import ch.ethz.infsec.secureumlgui.securemodel.secureuml.Role;
import ch.ethz.infsec.secureumlgui.wrapper.ActionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.PermissionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.PolicyWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.ResourceWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.RoleWrapper;
import ch.ethz.infsec.secureumlgui.transformation.ModelMap;
import ch.ethz.infsec.secureumlgui.util.PermissionDummy;
/**
* Central controller instance between the GUI (SecureUML property tab)
* and the modelmapper (ArgoUml model -> SecureUML entities).
*
*
*/
public class ModuleController
/* TODO: refactor: introduce abstract class for this class
* & use the abstract class in PropPanels
*/
{
private static Logger aLog = Logger.getLogger(ModuleController.class);
private ModuleController()
{
//TargetManager.getInstance().
modelMapper = GenericDialectModelMapper.getInstance();
if(modelMapper == null)
logger.error("modelMapper = null");
}
private GenericDialectHelper helper = GenericDialectHelper.getInstance();
private static ModuleController moduleControllerInstance = null;
public static ModuleController getInstance()
{
if(moduleControllerInstance == null)
moduleControllerInstance = new ModuleController();
if(modelMapper==null) {
moduleControllerInstance = null;
return null;
}
return moduleControllerInstance;
}
// public static ModuleController getInstance()
// {
// if(moduleControllerInstance == null)
// moduleControllerInstance = new ModuleController();
// if(modelMapper==null)
// return null;
// return moduleControllerInstance;
//
// }
MultiContextLogger logger = MultiContextLogger.getDefault();
static GenericDialectModelMapper modelMapper = null;
/** initialize ModelMapper: clear cached mapped elements
*
*/
public void initModelMapper()
{
//logger.info("initModelMapper");
if(modelMapper == null) {
//logger.info("modelMapper = null");
modelMapper = GenericDialectModelMapper.getInstance();
}
if(modelMapper != null)
modelMapper.init();
}
public Object transform(ModelElement modelElement)
{
if(modelMapper == null) {
logger.error("transform without modelmapper");
return null;
}
else
{
modelMapper.transform(modelElement);
return modelMapper.getModelMap().getElement(modelElement);
}
}
/** returns a PermissionDummy containing only the necessary
* information.
*
* associated ModelElements are mapped, but not used. In
* Addition, the Mapping permissionAssociationClass <->
* PermissionDummy is put to the ModelMap.
*
*/
public PermissionDummy getSecureUmlPermission(
AssociationClass permissionAssociationClass)
{
PermissionDummy permissionDummy = (PermissionDummy)
ModelMap.getDefault().getElement(
permissionAssociationClass);
return permissionDummy;
}
/* DONE: rethink design (maybe move part of this to the modelmapper bzw.
* to a separate 'modelWriter' class
*/
public void addPermission(PermissionWrapper permission)
{
modelMapper.getModelWriter().addPermission(permission);
// moved to proppanels (they update theirselves)
// reloadMappings(permission);
refreshPropPanel(permission);
}
//XXX
// public void addPermission(
// ActionWrapper actionWrapper,
// RoleWrapper roleWrapper)
// {
// modelMapper.getModelWriter().addPermission(
// actionWrapper, roleWrapper);
//
// // moved to proppanels (they update theirselves)
// // reloadMappings(permission);
//
// refreshPropPanel();
//
// }
public void addPermission(ActionWrapper actionWrapper,
RoleWrapper roleWrapper, Set<PolicyWrapper> policies)
{
aLog.debug("add permission: action " + actionWrapper.getName() + " role " + roleWrapper.getName() + " policies " + policies.size());
modelMapper.getModelWriter().addPermission(
actionWrapper, roleWrapper, policies);
// moved to proppanels (they update theirselves)
// reloadMappings(permission);
refreshPropPanel();
}
// public UmlClass addPolicy(String policyName, Namespace namespace) {
// return modelMapper.getModelWriter().createPolicy(policyName, namespace);
// //return new PolicyWrapper(modelMapper.getModelMap().getElement(policyClass));
// }
public UmlClass createPolicy(String policyName, Set<PolicyWrapper> refined_by, Namespace namespace) {
aLog.debug("write to modelwriter");
UmlClass policyClass = modelMapper.getModelWriter().createPolicy(policyName, refined_by, namespace);
aLog.debug("received new UmlClass: " + policyClass + " .. " + policyClass.getClass().toString());
TargetManager.getInstance().setTarget(policyClass);
//modelMapper.init();
modelMapper.examineUmlClass(policyClass);
Object policyObject = modelMapper.getModelMap().getElement(policyClass);
// aLog.debug("new policyObject: " + policyObject);
// logger.info("added Policy: class" + policyClass +" \nObject " + policyObject);
// return new PolicyWrapper(policyObject);
return policyClass;
}
//hack
public ModelMap getModelMap() {
return modelMapper.getModelMap();
}
public void addRole(String roleName, ResourceWrapper resourceWrapper)
{
try
{
ModelElement modelElement = (ModelElement)
modelMapper.getModelMap().getUmlElement(resourceWrapper.getModelElement());
Namespace namespace = getNamespace(modelElement);
//Role role = new RoleImpl(roleName);
UmlClass newRole = modelMapper.getModelWriter().
createRole(roleName, namespace);
if(newRole != null)
TargetManager.getInstance().setTarget(newRole);
logger.info("Added role: " + roleName);
}
catch (Exception e)
{
logger.logException(e);
}
// PropPanelClassSecureUml.getInstance().onTargetSet();
}
public Namespace getNamespace(ModelElement modelElement)
{
if(modelElement instanceof UmlClass)
{
return modelElement.getNamespace();
}
else if(modelElement instanceof Attribute)
{
return ((Attribute)modelElement).getOwner().getNamespace();
}
else if(modelElement instanceof Operation)
{
return ((Operation)modelElement).getOwner().getNamespace();
}
return null;
}
protected void refreshPropPanel()
{
logger.info(//logger.TARGET_EVENTS,
"Model changed - triggering update " );
// + resource);
SecureUmlModule.getTab().onTargetSet();
}
/**
* @param permission
*/
protected void refreshPropPanel(PermissionWrapper permission)
{
try
{
logger.info(//logger.TARGET_EVENTS,
"Model changed - triggering update " +
"of PropPanel with Resource: " );
// + resource);
// TODO: refresh proppanels
SecureUmlModule.getTab().onTargetSet();
}
catch (Exception e)
{
logger.logException(e);
}
}
public Role getSecureUmlRole(UmlClass roleClass)
{
if(roleClass == null)
return null;
return (Role) ModelMap.getDefault().getElement(roleClass);
}
public List/*<Role>*/ getAllRoles(Object resource)
{
try
{
List roles = new LinkedList();
for (Iterator iter = modelMapper.getRoleClasses().iterator(); iter.hasNext();)
{
UmlClass roleClass = (UmlClass) iter.next();
roles.add(modelMapper.getModelMap().getElement(roleClass));
}
return roles;
}
catch (Exception ex)
{
logger.logException(ex);
return new LinkedList<Role>();
}
}
public List<Object> getAllPolicies() {
List<Object> policies = new LinkedList<Object>();
for ( UmlClass umlClass : modelMapper.getPolicyClasses() ) {
policies.add( modelMapper.getModelMap().getElement(umlClass));
}
return policies;
}
// public List<Role> getAllRoles(Entity entity)
// {
// try
// {
// ModelElement modelElement = (ModelElement) ModelMap.getDefault().getUmlElement(entity);
//
// return getAllRoles((Namespace) modelElement.getNamespace());
// }
// catch (Exception ex)
// {
// logger.logException(ex);
// return null;
// }
// }
public List/*<Role>*/ getAllRoles(Namespace namespace)
{
return null;
//return modelMapper.transformAllRoles(namespace);
}
public void deletePermission(PermissionWrapper permissionWrapper)
{
// TODO: take from da;
modelMapper.getModelWriter().deletePermission(permissionWrapper);
refreshPropPanel(permissionWrapper);
}
// // unused
// public void setPermissionName(PermissionWrapper permission, String name)
// {
// modelMapper.getModelWriter().
// setPermissionName(permission, name);
// }
//
public void setAuthorizationConstraint(PermissionDummy permissionDummy, String constraint)
{
// TODO: take from da;
modelMapper.getModelWriter().
setAuthorizationConstraint(permissionDummy, constraint);
}
DialectMetaModelInfo dialectMetaModelInfo;
public DialectMetaModelInfo getDialectMetaModelInfo()
{
return dialectMetaModelInfo;
}
public void setDialectMetaModelInfo(
DialectMetaModelInfo dialectMetaModelInfo)
{
this.dialectMetaModelInfo = dialectMetaModelInfo;
}
/* Event Handlers */
}

View File

@ -0,0 +1,125 @@
package ch.ethz.infsec.secureumlgui;
import javax.swing.ImageIcon;
import ch.ethz.infsec.secureumlgui.logging.MultiContextLogger;
/**
* Provides access to the different icons needed by the SecureUML GUI.
* The icons are loaded from the folder <code>IMAGE_FOLDER</code> in the jar file.
* Note this makes it necessary, this class resides at the same point
* in the directory hierarchy, as the <code>IMAGE_FOLDER</code>.
*
* @version 1.0
*/
public class ResourceFilesManager
{
public static final String IMAGE_FOLDER = "icons/";
MultiContextLogger logger = MultiContextLogger.getDefault();
private ImageIcon createRoleIcon;
private ImageIcon constrainedIcon;
private ImageIcon inheritedRoleIcon;
private ImageIcon inheritedPolicyIcon;
private ImageIcon implicitIcon;
private ImageIcon compositeFullIcon;
private ImageIcon implicitByCompositeIcon;
public ResourceFilesManager()
{
initImageIcons();
}
/**
* Loads the icons from the jar file. If an icon cannot be loaded,
* the logger will report an error.
*/
private void initImageIcons()
{
try {
createRoleIcon = createImageIcon(IMAGE_FOLDER + "createRoleIcon.png","create Role");
constrainedIcon = createImageIcon(IMAGE_FOLDER + "constrained_icon.png","constrained Permission");
inheritedRoleIcon = createImageIcon(IMAGE_FOLDER + "inherited_icon.png","inherited Permission");
inheritedPolicyIcon = createImageIcon(IMAGE_FOLDER + "inherited_policy_icon.png","inherited Permission");
implicitIcon = createImageIcon(IMAGE_FOLDER + "implicit_icon.png","implicit Permission");
compositeFullIcon = createImageIcon(IMAGE_FOLDER + "composite_full_icon.png","composite Permission");
implicitByCompositeIcon = createImageIcon(IMAGE_FOLDER + "implicit_by_composite.png", "implicit by composite Permission");
}
catch(Exception e) {
logger.error("Could not load image icons in folder: " + IMAGE_FOLDER);
}
if (createRoleIcon == null ||
constrainedIcon == null||
inheritedRoleIcon == null ||
implicitIcon == null ||
compositeFullIcon == null ||
implicitByCompositeIcon == null) {
logger.error("error creating icons");
}
}
/** Returns an ImageIcon, or null if the path was invalid. */
private ImageIcon createImageIcon(String path,
String description) {
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
logger.error("Couldn't find file: " + path);
return null;
}
}
/**
* @return the compositeFullIcon
*/
public ImageIcon getCompositeFullIcon()
{
return compositeFullIcon;
}
/**
* @return the constrainedIcon
*/
public ImageIcon getConstrainedIcon()
{
return constrainedIcon;
}
/**
* @return the implicitIcon
*/
public ImageIcon getImplicitIcon()
{
return implicitIcon;
}
public ImageIcon getImplicitByInheritedIcon() {
return implicitByCompositeIcon;
}
/**
* @return the inheritedIcon
*/
public ImageIcon getInheritedRoleIcon()
{
return inheritedRoleIcon;
}
public ImageIcon getInheritedPolicyIcon() {
return inheritedPolicyIcon;
}
/**
* @return the createRoleIcon
*/
public ImageIcon getCreateRoleIcon()
{
return createRoleIcon;
}
}

View File

@ -0,0 +1,319 @@
package ch.ethz.infsec.secureumlgui;
// $Id: ActionTestLoadableModule.java,v 1.5 2005/10/10 21:06:32 linus Exp $
// Copyright (c) 2004-2005 The Regents of the University of California. All
// Rights Reserved. Permission to use, copy, modify, and distribute this
// software and its documentation without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph appear in all copies. This software program and
// documentation are copyrighted by The Regents of the University of
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
//package org.argouml.ui.test;
//import java.awt.event.*;
import java.awt.event.KeyEvent;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import javax.swing.ButtonGroup;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
import java.lang.Thread;
import ch.ethz.infsec.secureumlgui.logging.MultiContextLogger;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.parser.DialectMetaModelParser;
import ch.ethz.infsec.secureumlgui.usecasemapper.control.MenuActionListener;
import ch.ethz.infsec.secureumlgui.util.ExtensionFilenameFilter;
import ch.ethz.infsec.secureumlgui.util.SelectMetamodelActionListener;
import ch.ethz.infsec.secureumlgui.main.ClassLoaderProviderImpl;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.argouml.moduleloader.ModuleInterface;
import org.argouml.ui.ProjectBrowser;
import org.argouml.ui.cmd.GenericArgoMenuBar;
import org.argouml.ui.targetmanager.TargetManager;
import org.netbeans.mdr.handlers.BaseObjectHandler;
//import org.netbeans.mdr.handlers.MDRClassLoader;
/**
* SecureUmlModule: ArgoUml Module for editing and displaying SecureUML policies.
*
* Adds SecureUmlComponents to PropertyPanels of ModelElements
* representing SecureUml Entities with basic Functionalities like
* displaying, adding & removing Permissions for Entities,
* textually editing Authorization Constraints of Permissions.
* All Changes performed through the SecureUmlComponent are immediately
* written down to the underlying Uml ModelElements
*
*/
public final class SecureUmlModule implements
ModuleInterface
//, ActionListener, TargetListener
{
private static boolean enabled=false;
// private static SecureUmlComponentManager suManager;
private boolean isPropPanelsInitialized = false;
private static TabSecureUml tab;
private MultiContextLogger logger = new MultiContextLogger(
MultiContextLogger.STARTUP);
DialectMetaModelParser dialectMetaModelParser = new DialectMetaModelParser();
private static Logger aLog = Logger.getLogger(SecureUmlModule.class);
/**
* This is creatable from the module loader.
*/
public SecureUmlModule()
{
Properties log4jProps = new Properties();
try {
log4jProps.load(new BufferedInputStream(new FileInputStream(new File("ext/log4j.properties"))));
PropertyConfigurator.configure(log4jProps);
aLog.info("Loaded log4j configuration from \"ext/log4j.properties\"");
} catch (IOException e) {
logger.error("Could not load log4j configuration from \"ext/log4j.properties\" IOException: " + e.getMessage());
}
aLog.info("SecureUML Module initialized");
logger.info("SecureUML Module initialized");
//unfortunately, this is too late. this should be done, before mdr is initialized...
BaseObjectHandler.setClassLoaderProvider(new ClassLoaderProviderImpl());
// Thread.currentThread().setContextClassLoader(new MDRClassLoader(new ClassLoaderProviderImpl()));
}
static public TabSecureUml getTab() {
return tab;
}
static public String findSecureUMLDir ()
{
List<String> ext_dirs =
org.argouml.moduleloader.ModuleLoader2.getInstance().getExtensionLocations();
for (String dir: ext_dirs) {
File su_ext = new File(dir+"/argo_secureuml_gui.jar");
if(su_ext.exists()) return dir;
}
throw (new java.lang.RuntimeException("SecureUML GUI Plugin not found"));
}
/**
*
*/
private void initializeMenu()
{
GenericArgoMenuBar menubar = (GenericArgoMenuBar) ProjectBrowser
.getInstance().getJMenuBar();
JMenu secureUMLMenu = new JMenu("SecureUML");
secureUMLMenu.setMnemonic(KeyEvent.VK_S);
menubar.getTools().addSeparator();
secureUMLMenu.add(new JMenuItem("Selected Dialect Metamodel:"));
File[] xmiFiles = findDialectMetamodelFiles();
ButtonGroup menuItemsGroup = new ButtonGroup();
for (int i = 0; i < xmiFiles.length; i++)
{
File xmiFile = xmiFiles[i];
JRadioButtonMenuItem menuItem =
new JRadioButtonMenuItem(xmiFile.getName());
SelectMetamodelActionListener selectActionListener =
new SelectMetamodelActionListener(
xmiFile, dialectMetaModelParser);
menuItem.addActionListener(selectActionListener);
menuItemsGroup.add(menuItem);
secureUMLMenu.add(menuItem);
}
secureUMLMenu.addSeparator();
JMenu useCaseMapperMenu = new JMenu("Use Case Mapper");
JMenuItem mapUseCasesItem = new JMenuItem("Map Use Cases...");
mapUseCasesItem.addActionListener(new MenuActionListener());
useCaseMapperMenu.add(mapUseCasesItem);
secureUMLMenu.add(useCaseMapperMenu);
secureUMLMenu.addSeparator();
// (JD) show when it is finished:
JMenuItem writeXmiItem = new JMenuItem("Write XMI");
writeXmiItem.addActionListener(new WriteXmiActionListener());
writeXmiItem.setEnabled(true);
secureUMLMenu.add(writeXmiItem);
menubar.add(secureUMLMenu);
}
boolean isEnabled = true;
/**
* looks for .xmi files in the ArgoUML ext/ directory.
*
* @return an array containing the found files
*/
public File[] findDialectMetamodelFiles()
{
File extDirectory = new File(findSecureUMLDir());
if(!extDirectory.exists())
{
logger.error("'ext' Directory not found - cannot load Dialect metamodels");
return null;
}
else
{
FilenameFilter xmiFilenameFilter = new ExtensionFilenameFilter("xmi");
File[] xmiFiles = extDirectory.listFiles(xmiFilenameFilter);
for (int i = 0; i < xmiFiles.length; i++)
{
File xmiFile = xmiFiles[i];
//logger.info("XMI File found: " + xmiFile.getName());
}
return xmiFiles;
}
}
// Methods from the ModuleLoader interface
/**
*
* @see ModuleInterface#enable()
*/
public boolean enable()
{
if(!enabled) {
enabled=true;
logger.info("SecureUML Module enabled");
initializeMenu();
isEnabled = true;
TabSecureUml tabSecureUml = new TabSecureUml();
tab=tabSecureUml;
TargetManager.getInstance().addTargetListener(tabSecureUml);
Object target = TargetManager.getInstance().getTarget();
TargetManager.getInstance().setTarget(null);
TargetManager.getInstance().setTarget(target);
org.argouml.ui.DetailsPane detailsPane = (org.argouml.ui.DetailsPane)ProjectBrowser.getInstance().getDetailsPane();
//dont just add, as otherwise probably confilcts with the way, the property tab
//is resolved by using the last non null tab
//DetailsPane.java 223
tabSecureUml.setName("SecureUML Properties");
detailsPane.addTab( tabSecureUml, true);
//(JD) A hack. ArgoUML tries to translate the title, and fails...
int i = detailsPane.getTabs().indexOfComponent(tabSecureUml);
detailsPane.getTabs().setTitleAt(i,"SecureUML Properties");
tabSecureUml.setEnabled(false);
}
return true;
}
/**
* @see ModuleInterface#disable()
*
* This removes us from the Tools menu. If we were not registered there we
* don't care.
*/
public boolean disable()
{
isEnabled = false;
isPropPanelsInitialized = false;
Object target = TargetManager.getInstance().getTarget();
TargetManager.getInstance().setTarget(null);
TargetManager.getInstance().setTarget(target);
return true;
}
/**
* @see ModuleInterface#getName()
*/
public String getName()
{
return "SecureUMLGUI Module";
}
/**
* @see ModuleInterface#getInfo(int)
*/
public String getInfo(int type)
{
switch (type)
{
case DESCRIPTION:
return "This is the SecureUmlGui Module " +
"offering an alternative GUI to edit " +
"SecureUML-permissions ";
// break;
case AUTHOR:
return "Marcel Beer";
// break;
case VERSION:
return "0.42";
// break;
default:
return null;
}
}
/**
* The version uid.
*/
private static final long serialVersionUID = -2570516012301142091L;
}

View File

@ -0,0 +1,308 @@
package ch.ethz.infsec.secureumlgui;
import org.argouml.ui.*;
import org.omg.uml.foundation.core.ModelElement;
import org.argouml.model.Model;
import org.argouml.ui.targetmanager.TargetEvent;
import org.argouml.ui.TabModelTarget;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.BorderLayout;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import javax.swing.ListSelectionModel;
import java.util.LinkedHashMap;
import java.util.Map;
import ch.ethz.infsec.secureumlgui.gui.*;
import ch.ethz.infsec.secureumlgui.ModuleController;
import ch.ethz.infsec.secureumlgui.ResourceFilesManager;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.ResourceType;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.MetaModelConst;
import ch.ethz.infsec.secureumlgui.wrapper.ResourceWrapper;
import ch.ethz.infsec.secureumlgui.modelmapping.permissions.ActionPermissionSet;
import ch.ethz.infsec.secureumlgui.modelmapping.GenericDialectHelper;
import ch.ethz.infsec.secureumlgui.modelmapping.GenericDialectModelMapper;
import ch.ethz.infsec.secureumlgui.wrapper.ActionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.AtomicActionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.CompositeActionWrapper;
import ch.ethz.infsec.secureumlgui.transformation.ModelMap;
import ch.ethz.infsec.secureumlgui.main.SecureUmlConstants;
import ch.ethz.infsec.secureumlgui.logging.MultiContextLogger;
// (JD) I'm trying to move only the needed parts from SecureUmlComponentContainer
// into this class. then probably only SecureUmlComponentManager has to be adjusted.
/**
* Represents the SecureUML properties tab in the ArgoUML details pane.
*
* Also manages to select which SecureUML Component to show in the tab,
* i.e., one of {@link SecureUmlComponent}, {@link SecureUmlRoleComponent},
* {@link SecureUmlPermissionComponent}, depending on the type of the selected element.
*
* @version 1.0
*/
public class TabSecureUml
extends AbstractArgoJPanel
implements TabModelTarget
// extends AbstractArgoJPanel
//implements TabModelTarget, ActionListener, ListSelectionListener, ComponentListener
{
private Object target;
private boolean shouldBeEnabled = false;
private boolean hack_init = false;
public TabSecureUml()
{
this.setLayout(new BorderLayout());
}
/**
* show the given component in the SecureUML properties tab.
*
* the previously shown component is hidden.
* @param comp the component to be shown.
*/
public void setComponent(AbstractSecureUmlComponent comp) {
this.removeAll();
if(comp != null) {
this.add(comp,BorderLayout.CENTER);
}
this.validate();
this.repaint();
}
public void setEnabled(boolean enabled) {
shouldBeEnabled = enabled;
}
private Map<ResourceType, AbstractSecureUmlComponent> secureUmlComponents
= new LinkedHashMap<ResourceType, AbstractSecureUmlComponent>();
MultiContextLogger logger = new MultiContextLogger(MultiContextLogger.GUI);
public AbstractSecureUmlComponent getSecureUMLComponent(String stereotype)
{
if(stereotype == null)
return null;
else
return secureUmlComponents.get(stereotype);
}
public void registerSecureUmlComponent(ResourceType resourceType,
AbstractSecureUmlComponent suComponent)
{
if(resourceType == null)
{
logger.error("stereotype == null @ SecureUMLComponentContainer.registerSecureUMLComponent");
}
else
secureUmlComponents.put(resourceType, suComponent);
}
public void registerSecureUmlComponent(ResourceType resourceType)
// TODO: change s.t. modelElements which are Resources,
// but not directly stereotyped are supported, too
{
registerSecureUmlComponent(resourceType, null);
}
// // Target Events Handlers
/**
* Display the proper panel component for this resourcetype.
*
* This method is only called, if the newTarget
* is a SecureUML Element
*
*/
public void onTargetSet(Object newTarget, ResourceType rt)
{
if (newTarget instanceof ModelElement) {
ModelElement me = (ModelElement) newTarget;
AbstractSecureUmlComponent suComponent = null;
if(me != null
&& me.getName() != null
&& me.getName().length()>0
&& rt != null) {
suComponent = secureUmlComponents.get(rt);
}
if(suComponent != null) {
Object suElement = ModelMap.getDefault().getElement(me);
if(suElement != null) {
suComponent.setDisplayedSecureUmlElement(suElement, rt);
this.setComponent(suComponent);
}
}
else {
logger.info("no SecureUML Component found " +
"for ResourceType: " + rt);
this.setComponent(null);
}
}
else logger.error("new Target is not an ArgoUML ModelElement: "
+ newTarget);
}
public Object getTarget() {
return target;
}
public void refresh() {
setTarget(target);
}
public void setTarget(Object target) {
if (!(Model.getFacade().isAModelElement(target))) {
this.target = null;
shouldBeEnabled = false;
return;
}
this.target = target;
shouldBeEnabled = false;
}
public boolean shouldBeEnabled() {
return shouldBeEnabled;
}
public boolean shouldBeEnabled(Object target) {
boolean shouldBeEnabled=false;
if (target instanceof ModelElement) {
if (Model.getFacade().isAModelElement(target))
shouldBeEnabled=isSecureUmlElement((ModelElement)target);
}
this.shouldBeEnabled=shouldBeEnabled;
return shouldBeEnabled;
}
public void onTargetSet()
{
onTargetSet(target);
}
/**
* Find out the type of the newTarget (Role, Permission, or Resource), and act accordingly.
*
* @param newTarget
*/
public void onTargetSet(Object newTarget)
{
// logger.info("executing SecureUmlComponentManager.onTargetSet()");// + newTarget + ")");
if(GenericDialectModelMapper.getInstance()==null) return;
target = newTarget;
if(newTarget == null)
return;
String newTargetClassName = newTarget.getClass().getSimpleName()
.split(MetaModelConst.MDR_IMPL_SUFFIX_REGEXP)[0];
if (newTarget instanceof ModelElement) {
ModelElement me = (ModelElement) newTarget;
// don't handle unnamed Elements
if(me.getName() == null || me.getName().length() == 0) {
logger.info("unnamed model element");
onTargetSet(newTarget, null);
} else { // if Element != null and named
logger.info("model element: " + me.getName());
try {
ResourceType targetResourceType = GenericDialectHelper.getInstance().getSecureUmlType(me);
if(targetResourceType != null ) {
logger.info("targetResourceType: " + targetResourceType.getName());
ModuleController.getInstance().initModelMapper();
Object secureUmlElement = ModuleController.getInstance().transform(me);
if(secureUmlElement == null) {
logger.error("new target could not be mapped");
return;
}
} else {
logger.info("Could not find ResourceType for " + me);
if ( ! hack_init && !me.getName().contains("untitled")) { //untitledModel
hack_init = true;
GenericDialectModelMapper.getInstance().transform(me);
}
}
onTargetSet(newTarget, targetResourceType);
}
catch (Exception ex) {
//secureumlComponent.setErrorMessage(ex.getMessage());
logger.logException(ex);
}
}
}
}
public boolean isSecureUmlElement(ModelElement me) {
return GenericDialectHelper.getInstance().isSecureUmlRole(me)
|| GenericDialectHelper.getInstance().isSecureUmlPermission(me)
|| GenericDialectHelper.getInstance().getResourceType(me) != null;
}
public void targetSet(TargetEvent e) {
onTargetSet(e.getNewTarget());
}
public void targetAdded(TargetEvent e)
{
//logger.info("** target Added");
try
{
if(e != null && e.getAddedTargetCollection() != null
&& e.getAddedTargetCollection().size()>0)
{
Object addedTarget =
e.getAddedTargetCollection().iterator().next();
onTargetSet(addedTarget);
}
else
{
logger.error("added target = null");
onTargetSet(null);
}
}
catch (Exception ex)
{
logger.error("** targetAdded: AddedTargetCollection is empty!");
}
}
public void targetRemoved(TargetEvent e)
{
if(e != null)
{
Object newTarget = e.getNewTarget();
//FIXME: and now?
}
}
}

View File

@ -0,0 +1,426 @@
package ch.ethz.infsec.secureumlgui;
import java.io.File;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Iterator;
import org.omg.uml.foundation.core.Stereotype;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.MetaModelConst;
import ch.ethz.infsec.secureumlgui.logging.MultiContextLogger;
/**
* Misc. Utility methods.
*
* @version 1.0
*/
public class Util
{
/**
* Returns a capitalized string
*
* @param name the string to capitalize
* @return the capitalized String
*/
public static String capitalize(String name)
{
if(name != null && name.length() > 0)
return name.substring(0, 1).toUpperCase()
+ name.substring(1, name.length());
else
return name;
}
/**
* @param type
* @param methodName
* @return the first Method of Type 'type' with name equals 'methodName'
*/
public static Method findMethodByName(Class type, String methodName)
{
if(type != null && methodName != null)
{
Method[] methods = type.getMethods();
for (int i = 0; i < methods.length; i++)
{
Method m = methods[i];
if(methodName.equals(m.getName()))
return m;
}
}
return null;
}
public static boolean isInstanceof(Class c, String parentClassName)
{
if(c == null
|| parentClassName == null
|| parentClassName.length()==0)
{
return false;
}
String className = c.getSimpleName();
if(className.equals(parentClassName))
return true;
else
{
return isInstanceof(c.getSuperclass(), parentClassName);
}
}
public static boolean hasType(Object modelElement, String className)
{
className += MetaModelConst.MDR_IMPL_SUFFIX;
if (modelElement != null && className != null)
return modelElement.getClass().getSimpleName().startsWith(className);
else
return false;
}
public static boolean hasStereotype(
org.omg.uml.foundation.core.ModelElement element, String stereotype)
{
if (element == null || stereotype == null || stereotype.length() == 0)
return false;
Collection stereotypes = element.getStereotype();
int nofStereotypes = stereotypes.size();
if (stereotypes == null || stereotypes.size() == 0)
return false;
for (Iterator it = stereotypes.iterator(); it.hasNext();)
{
Stereotype s = (Stereotype) it.next();
if (s.getName().equals(stereotype))
{
return true;
}
}
return false;
}
public static Object invokeParameterlessMethod(Object object, String methodName)
{
try
{
java.lang.reflect.Method getter =
object.getClass().getMethod(
methodName, new Class[0]);
return getter.invoke(object, new Object[0]);
}
catch (Exception e)
{
logger.info("Problem invoking method '"
+ methodName + "' on: " + object);
Util.printInterfaces(object.getClass());
logger.logException(e);
}
return null;
}
public static Object getProperty(Object object, String propertyName)
{
// exception is only logged if both trys fail
Exception ex;
if (object==null)
logger.error("trying to get property "+propertyName+" from null object");
try
{
//logger.info("trying get"+capitalize(propertyName));
java.lang.reflect.Method getter = object.getClass().getMethod(
"get" + capitalize(propertyName), new Class[0]);
return getter.invoke(object, new Object[0]);
}
catch (Exception e)
{
ex = e;
}
// boolean case
try
{
//logger.info("trying is"+capitalize(propertyName));
java.lang.reflect.Method getter = object.getClass().getMethod(
"is" + capitalize(propertyName), new Class[0]);
return getter.invoke(object, new Object[0]);
}
catch (Exception e)
{
logger.info("Problem getting property '"
+ propertyName + "' from: " + object);
Util.printInterfaces(object.getClass());
logger.logException(ex);
logger.logException(e);
}
return null;
}
public static Object tryGetProperty(Object object, String propertyName)
{
try
{
java.lang.reflect.Method getter = object.getClass().getMethod(
"get" + capitalize(propertyName), new Class[0]);
return getter.invoke(object, new Object[0]);
}
catch (Exception e)
{
//logger.logException(e);
// case for boolean properties
try
{
java.lang.reflect.Method getter = object.getClass().getMethod(
"is" + capitalize(propertyName), new Class[0]);
return getter.invoke(object, new Object[0]);
}
catch (Exception ex)
{
// logger.logException(e);
}
}
return null;
}
/**
* @param object
* @param value
* @param propertyName
*/
public static void setProperty(Object object, String propertyName, Object value)
{
try
{
java.lang.reflect.Method getter = null;
try
{
getter = object.getClass().getMethod(
"get" + capitalize(propertyName), new Class[0]);
}
catch (Exception e)
{
}
if(getter == null)
{
try
{
getter = object.getClass().getMethod(
"is" + capitalize(propertyName), new Class[0]);
}
catch (Exception e)
{
logger.logException(e);
}
}
if(getter.getReturnType() == Collection.class
&& getter.getParameterTypes().length == 0)
{
Collection collectionValue = (Collection)
getter.invoke(object, new Object[0]);
if(collectionValue != null)
{
collectionValue.add(value);
}
}
else
{
Class[] setterArgTypes = { getter.getReturnType() };
java.lang.reflect.Method setter = object.getClass().getMethod(
"set" + capitalize(propertyName), setterArgTypes);
Object[] setterArgs = { value };
setter.invoke(object, setterArgs);
}
}
catch(NoSuchMethodException e)
{
logger.error("Setter Method for Property '"
+ propertyName
+ "' not found: \n"
+ "Available Methods: \n");
Util.printInterfaces(object.getClass());
}
catch (Exception e)
{
logger.logException(e);
}
}
static MultiContextLogger logger = MultiContextLogger.getDefault();
/**
* checks whether a file name exists and the file can be read.
*
* Aborts the program, if not.
* @param filename the file name to check for
* @return the File object of the given file name
*/
public static File checkAndGetFile(String filename)
{
if(filename == null || filename.length() == 0)
{
logger.error("empty filename given for required file!" +
" ...exiting");
}
else
{
File file =
new File(filename);
if(file.exists() && file.canRead())
{
return file;
}
}
System.exit(1);
// unreachable, but needed to compile
return null;
}
public static void printInterfaces(Class cl)
{
if (cl != null)
{
Class[] interfaces = cl.getInterfaces();
System.out
.println(" - Interfaces of class '" + cl.getName() + " :");
for (int i = 0; i < interfaces.length; i++)
{
System.out.println("i: " + interfaces[i].getName());
for (int j = 0; j < interfaces[i].getMethods().length; j++)
{
Method method = interfaces[i].getMethods()[j];
System.out.println(" m: " + method.toString());
}
//
}
}
}
public static void printJmiNamespace(javax.jmi.model.Namespace namespace, String prefix)
{
Collection packages = namespace.getContents();
for (Iterator iter = packages.iterator(); iter.hasNext();)
{
javax.jmi.model.ModelElement element = (javax.jmi.model.ModelElement) iter.next();
logger.info(prefix + element.getName());
if (element instanceof javax.jmi.model.Namespace)
{
prefix = " " + prefix;
javax.jmi.model.Namespace n = (javax.jmi.model.Namespace) element;
printJmiNamespace(n, prefix);
}
}
}
public static void printJmiNamespace(javax.jmi.model.Namespace namespace)
{
printJmiNamespace(namespace, "");
}
/**
* Adds all elements from the Collection addables to the Collection c - and
* performs each add-operation in a seperate try-catch-statement
*
*
* @param c
* a Collection
* @param addables
* collection of Elements which are to be added to c
*/
public static void addAllSave(Collection c, Collection addables)
{
if (c == null || addables == null)
return;
for (Iterator iter = addables.iterator(); iter.hasNext();)
{
try
{
Object o = (Object) iter.next();
c.add(o);
}
catch (Exception e)
{
logger.logException(e);
}
}
}
// public static Stereotype findStereotypeByName(Collection availableStereotypes, String name, boolean loggingOn)
// {
// String stereotypeMessge = "searching Stereotype: " + name + " among: \n";
//
// Stereotype result = null;
//
// for (Iterator iter = availableStereotypes.iterator(); iter.hasNext();)
// {
// Stereotype stereotype = (Stereotype) iter.next();
//
// if( stereotype.getName().equals(name))
// {
// stereotypeMessge += ">" + stereotype.getName() + "\n";
//
// result = stereotype;
// }
// stereotypeMessge += stereotype.getName() + "\n";
// }
// if(loggingOn)
// logger.info(logger.MODELWRITER,stereotypeMessge);
//
// return result;
// }
// private static String permissionNamePrefix = "Permission";
// private static String permissionNameSuffix = "Permission";
private static int permissionNumber = 42;
/* returns a number for a permission that is being created
* (currenty strategy is to number'em ascending from 42)
*/
public static int getNewPermissionNumber()
{
return permissionNumber++;
}
private static int roleNumber = 42;
/* returns a number for a permission that is being created
* (currenty strategy is to number'em ascending from 42)
*/
public static int getNewRoleNumber()
{
return roleNumber++;
}
}

View File

@ -0,0 +1,60 @@
package ch.ethz.infsec.secureumlgui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import ch.ethz.infsec.secureumlgui.modelmapping.GenericDialectModelMapper;
import java.io.File;
import javax.jmi.reflect.RefPackage;
import javax.swing.JFileChooser;
import org.netbeans.api.xmi.XMIWriter;
import org.netbeans.api.xmi.XMIWriterFactory;
import java.io.FileOutputStream;
/**
* ActionListener for the Write Xmi Menu item (FIXME: move to proper
* place). This is a hack at the moment. We just write the current
* contents of the repository. We should be more careful here to make
* sure that really everything gets mapped. I.e., transform with a
* "MapAll" strategie into a separate extent, and write from there.
* @version 1.0
*/
// FIXME (JD): this can be made an inner class of SecureUmlModule?
public class WriteXmiActionListener implements ActionListener {
JFileChooser fc;
WriteXmiActionListener() {
fc = new JFileChooser();
}
/**
* Responds to the <code>ActionEvents</code> from the module menu.
*
* @param event the <code>ActionEvent</code> to be handled.
*/
public final void actionPerformed(final ActionEvent event) {
int val = fc.showSaveDialog(null);
if (val == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
RefPackage model = (RefPackage) GenericDialectModelMapper.getInstance().dialectMetaModelInfo.getDialectExtent();
//System.out.print(mof);
XMIWriter writer = XMIWriterFactory.getDefault().createXMIWriter();
try {
FileOutputStream out = new FileOutputStream(file);
writer.write(out, model, null);
} catch (Exception e) {
System.out.println("Fatal error writing XMI.");
e.printStackTrace();
}
}
}
}

View File

@ -0,0 +1,257 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.gui;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.swing.event.TableModelEvent;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.JTableHeader;
import org.argouml.ui.targetmanager.TargetManager;
import org.omg.uml.foundation.core.UmlClass;
import ch.ethz.infsec.secureumlgui.ModuleController;
import ch.ethz.infsec.secureumlgui.logging.MultiContextLogger;
import ch.ethz.infsec.secureumlgui.main.SecureUmlConstants;
import ch.ethz.infsec.secureumlgui.modelmapping.permissions.ActionPermissionSet;
//import ch.ethz.infsec.secureumlgui.securemodel.secureuml.Permission;
//import ch.ethz.infsec.secureumlgui.securemodel.secureuml.Resource;
//import ch.ethz.infsec.secureumlgui.securemodel.secureuml.Role;
import ch.ethz.infsec.secureumlgui.wrapper.PermissionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.RoleWrapper;
import ch.ethz.infsec.secureumlgui.securemodelimpl.SecureModelFactory;
import ch.ethz.infsec.secureumlgui.transformation.ModelMap;
/**
*
*/
public abstract class AbstractPermissionsTableModel
extends AbstractTableModel
implements MouseListener
{
/**
*
*/
public AbstractPermissionsTableModel(Object resource)
{
super();
//setResource(resource);
}
/**
* @param resource
*/
protected void setResource(Object resource)
{
roleWrappers.clear();
for (Object role : ModuleController.getInstance().getAllRoles(resource)) {
RoleWrapper rw = new RoleWrapper(role);
roleWrappers.add(rw);
}
}
protected String newPermissionSuffix = SecureUmlConstants.NEW_PERMISSION_SUFFIX;
/**
* @return the newPermissionSuffix
*/
protected String getNewPermissionSuffix()
{
return newPermissionSuffix;// + newPermissionNumber++;
}
/**
* @param newPermissionSuffix the newPermissionSuffix to set
*/
protected void setNewPermissionSuffix(String newPermissionSuffix)
{
this.newPermissionSuffix = newPermissionSuffix;
}
protected List<RoleWrapper> roleWrappers =
new ArrayList<RoleWrapper>();
protected MultiContextLogger logger = new MultiContextLogger(
MultiContextLogger.GUI);
public int getColumnCount()
{
/* TODO: constant in first Version
* (could do via reflection later)
*
* // old, swapped layout
*
* // 4 = 1 (for the role name)
* // + 3 (for the attribute Actions -read, change, full access)
*/
return roleWrappers.size() + 1;
}
@Override
public Class<?> getColumnClass(int columnIndex)
{
// if(columnIndex == 0)
// return String.class;
//else
if(columnIndex >= 1)
// return Boolean.class;
return ActionPermissionSet.class;
else
return super.getColumnClass(columnIndex);
}
@Override
public String getColumnName(int column)
{
//logger.info(logger.GUI, "requesting Column Name " + column);
if(column == 0)
return "ACTION";
else
{
try
{
RoleWrapper roleWrapper = roleWrappers.get(column-1);
return roleWrapper.getName();
}
catch (Exception e)
{
e.printStackTrace();
return super.getColumnName(column);
}
}
}
public boolean isCellEditable(int row, int col)
{
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
if (col == 0)
{
return false;
}
else
{
return true;
}
}
public void fireManually()
{
fireTableStructureChanged();
fireTableDataChanged();
fireTableChanged(new TableModelEvent(this));
}
// helper methods
/* creates a new Permission object connects it
* to the role given as argument
*/
protected PermissionWrapper createPermission(
RoleWrapper/*Role*/ roleWrapper)
{
/*Permission*/ Object o =
SecureModelFactory.getInstance().
createPermission();
PermissionWrapper p = new PermissionWrapper(o);
p.setRoleWrapper(roleWrapper);
return p;
}
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
*/
public void mouseClicked(MouseEvent e)
{
// logger.info("Table Header Mouse Clicked"
// + "\n source: " + e.getSource()
// + "\n component: " + e.getComponent()
// + "\n point:" + e.getPoint());
if(e.getClickCount() == 2)
{
try
{
JTableHeader header = (JTableHeader) e.getSource();
int clickedColumnIndex =
header.getColumnModel().getColumnIndexAtX(e.getX());
Object clickedSuRole =
roleWrappers.get(clickedColumnIndex-1).
getModelElement();
Object roleUml =
ModelMap.getDefault().getUmlElement(clickedSuRole);
if (roleUml instanceof UmlClass)
{
UmlClass roleUmlClass = (UmlClass) roleUml;
TargetManager.getInstance().setTarget(roleUmlClass);
}
}
catch (Exception ex)
{
logger.logException(ex);
}
}
}
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
*/
public void mouseEntered(MouseEvent e)
{
}
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
*/
public void mouseExited(MouseEvent e)
{
}
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
*/
public void mousePressed(MouseEvent e)
{
}
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
*/
public void mouseReleased(MouseEvent e)
{
}
}

View File

@ -0,0 +1,83 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.gui;
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.LayoutManager;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import org.openide.util.datatransfer.ExTransferable.Multi;
import ch.ethz.infsec.secureumlgui.Util;
import ch.ethz.infsec.secureumlgui.logging.MultiContextLogger;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.MetaModelEntity;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.ResourceType;
import ch.ethz.infsec.secureumlgui.wrapper.PermissionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.ResourceWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.RoleWrapper;
/**
* Abstract base class for all SecureUML properties components to be
* displayed in the Details Pane.
*
* Holds stuff that is common to all SecureUml components, but
* independent of the type of the resource that is displayed.
*
* {@link ch.ethz.infsec.secureumlgui.TabSecureUml} displays instances
* of this class based on the selected model element.
*
*
*/
public abstract class AbstractSecureUmlComponent
extends JPanel
{
/**
*
*/
public AbstractSecureUmlComponent()
{
this.setLayout(new BorderLayout());
}
public void setDisplayedSecureUmlElement(
Object suElement, ResourceType rt)
{
}
/**
*
*/
private void initLayout()
{
}
// public AbstractSecureUmlComponent(String titl)
// {
// initLayout();
// //initBorder();
// //setTitle(title);
// }
MultiContextLogger logger = new MultiContextLogger(
MultiContextLogger.GUI);
LayoutManager defaultLayout;
// public LayoutManager getDefaultLayout()
// {
// return defaultLayout;
// }
}

View File

@ -0,0 +1,151 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.gui;
import java.awt.Component;
import java.util.Collection;
import java.util.EventObject;
import java.util.Iterator;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JToolTip;
import javax.swing.event.CellEditorListener;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import ch.ethz.infsec.secureumlgui.logging.MultiContextLogger;
import ch.ethz.infsec.secureumlgui.modelmapping.GenericDialectHelper;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.ActionType;
import ch.ethz.infsec.secureumlgui.wrapper.ActionWrapper;
/**
*
*/
public class ActionNameTableCellRenderer extends Object
implements TableCellRenderer, TableCellEditor
{
/**
*
*/
public ActionNameTableCellRenderer()
{
}
MultiContextLogger logger = MultiContextLogger.getDefault();
/* (non-Javadoc)
* @see javax.swing.table.TableCellRenderer#getTableCellRendererComponent(javax.swing.JTable, java.lang.Object, boolean, boolean, int, int)
*/
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
// logger.info("executing " +
// "ActionNameTableCellRenderer.getTableCellRendererComponent("
// + value + ")");
if (value instanceof ActionWrapper)
{
ActionWrapper actionWrapper = (ActionWrapper) value;
ActionNameTableCellRendererComponent container =
new ActionNameTableCellRendererComponent(
actionWrapper);
return container;
}
else
return new JTextField("error");
}
/* (non-Javadoc)
* @see javax.swing.CellEditor#isCellEditable(java.util.EventObject)
*/
public boolean isCellEditable(EventObject anEvent)
{
return false;
}
/* (non-Javadoc)
* @see javax.swing.CellEditor#addCellEditorListener(javax.swing.event.CellEditorListener)
*/
public void addCellEditorListener(CellEditorListener l)
{
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see javax.swing.CellEditor#cancelCellEditing()
*/
public void cancelCellEditing()
{
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see javax.swing.CellEditor#getCellEditorValue()
*/
public Object getCellEditorValue()
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.swing.table.TableCellEditor#getTableCellEditorComponent(javax.swing.JTable, java.lang.Object, boolean, int, int)
*/
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
{
return getTableCellRendererComponent(
table, value, isSelected, false, row, column);
}
/* (non-Javadoc)
* @see javax.swing.CellEditor#removeCellEditorListener(javax.swing.event.CellEditorListener)
*/
public void removeCellEditorListener(CellEditorListener l)
{
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see javax.swing.CellEditor#shouldSelectCell(java.util.EventObject)
*/
public boolean shouldSelectCell(EventObject anEvent)
{
// TODO Auto-generated method stub
return false;
}
/* (non-Javadoc)
* @see javax.swing.CellEditor#stopCellEditing()
*/
public boolean stopCellEditing()
{
// TODO Auto-generated method stub
return false;
}
}

View File

@ -0,0 +1,126 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.gui;
import java.util.Collection;
import java.util.Iterator;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JToolTip;
import ch.ethz.infsec.secureumlgui.modelmapping.GenericDialectHelper;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.ActionType;
import ch.ethz.infsec.secureumlgui.wrapper.ActionWrapper;
/**
*
*/
public class ActionNameTableCellRendererComponent extends JPanel
{
/**
*
*/
public ActionNameTableCellRendererComponent(ActionWrapper actionWrapper)
{
JLabel lbActionName =
new JLabel(actionWrapper.getName());
add(lbActionName);
String tooltip = "";
//txActionName.setToolTipText();//"Action Composition Info..."
ActionType at = GenericDialectHelper.getInstance().
getActionType(actionWrapper.getModelElement());
if(at == null)
{
tooltip = "couldn't determine actiontype";
}
else if(at.getSubactionsDefinition() == null
|| at.getSubactionsDefinition().length() == 0)
{
tooltip = "Atomic Action";
}
else
{
tooltip = "Composite Action";// ("
// + at.getSubactionsDefinition() + ")";
Collection<ActionWrapper> subactions =
actionWrapper.getSubActionWrappers();
if(subactions.size() == 0)
{
//tooltip += "with no Subactions";
}
else
{
if(subactions.size() == 1)
tooltip += "\n - Subaction (";
else
tooltip += "\n - Subactions (";
for (Iterator iter = subactions.iterator(); iter.hasNext();)
{
ActionWrapper aw = (ActionWrapper) iter.next();
tooltip += //"\n" +
aw.getResourceWrapper().getResourcePath()
+ "." +aw.getName();
if(iter.hasNext())
tooltip += ", ";
}
tooltip += ")";
}
}
Collection superactions =
actionWrapper.getSuperActionWrappers();
if(superactions.size() == 0)
{
//tooltip += "with no Superactions";
}
else
{
if(superactions.size() == 1)
tooltip += "\n - Superaction (";
else
tooltip += "\n - Superactions (";
for (Iterator iter = superactions.iterator(); iter.hasNext();)
{
ActionWrapper aw = (ActionWrapper) iter.next();
tooltip += //"\n" +
aw.getResourceWrapper().getResourcePath()
+ "." +aw.getName();
if(iter.hasNext())
tooltip += ", ";
}
tooltip += ")";
}
// logger.info("set action tooltip: " + tooltip);
//
setToolTipText(tooltip);
//return txActionName;
}
@Override
public JToolTip createToolTip() {
MultiLineToolTip tip = new MultiLineToolTip();
tip.setComponent(this);
return tip;
}
}

View File

@ -0,0 +1,26 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.gui;
import javax.swing.DefaultCellEditor;
import javax.swing.JCheckBox;
import javax.swing.table.TableCellEditor;
/**
*
*/
public class ActionPermissionTableCellEditor
//extends DefaultCellEditor
//implements TableCellEditor
{
/**
*
*/
public ActionPermissionTableCellEditor()
{
}
}

View File

@ -0,0 +1,83 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.gui;
import javax.swing.JCheckBox;
import ch.ethz.infsec.secureumlgui.logging.MultiContextLogger;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;;
/**
*
*/
public class ActionPermissionTableCellListener
implements MouseListener
{
/**
*
*/
public ActionPermissionTableCellListener(JCheckBox editorCheckbox)
{
this.editorCheckbox = editorCheckbox;
}
MultiContextLogger logger =
MultiContextLogger.getDefault();
JCheckBox editorCheckbox;
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
*/
public void mouseClicked(MouseEvent e)
{
editorCheckbox.doClick();
logger.info("mouse clicked");
}
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
*/
public void mouseEntered(MouseEvent e)
{
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
*/
public void mouseExited(MouseEvent e)
{
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
*/
public void mousePressed(MouseEvent e)
{
logger.info("mouse Pressed");
}
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
*/
public void mouseReleased(MouseEvent e)
{
// TODO Auto-generated method stub
}
}

View File

@ -0,0 +1,174 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.gui;
import java.awt.Component;
import java.util.EventObject;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.event.CellEditorListener;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import org.omg.uml.foundation.core.UmlClass;
import ch.ethz.infsec.secureumlgui.ModuleController;
import ch.ethz.infsec.secureumlgui.logging.MultiContextLogger;
import ch.ethz.infsec.secureumlgui.modelmapping.permissions.ActionPermissionSet;
import ch.ethz.infsec.secureumlgui.wrapper.PolicyWrapper;
/**
*
*/
public class ActionPermissionTableCellRenderer
implements TableCellEditor,
TableCellRenderer
{
//private PolicyWrapper currentPolicy;
private UmlClass currentPolicy;
/**
*
*/
// public ActionPermissionTableCellRenderer(PolicyWrapper currentPolicy) {
// this.currentPolicy = currentPolicy;
// }
public ActionPermissionTableCellRenderer(UmlClass currentPolicy) {
this.currentPolicy = currentPolicy;
}
MultiContextLogger logger =
MultiContextLogger.getDefault();
// static int globalN = 0;
// int n;
ActionPermissionsTableCellRendererComponent
container = null;
/* (non-Javadoc)
* @see javax.swing.table.TableCellRenderer#getTableCellRendererComponent(javax.swing.JTable, java.lang.Object, boolean, boolean, int, int)
*/
public Component getTableCellRendererComponent(
JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column)
{
if (value instanceof ActionPermissionSet)
{
ActionPermissionSet actionPermissions =
(ActionPermissionSet) value;
container = new
ActionPermissionsTableCellRendererComponent(
actionPermissions, new PolicyWrapper(ModuleController.getInstance().getModelMap().getElement(currentPolicy)));
return container;
}
else
return new JLabel("error");
}
/* (non-Javadoc)
* @see javax.swing.DefaultCellEditor#getTableCellEditorComponent(javax.swing.JTable, java.lang.Object, boolean, int, int)
*/
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
{
// TODO Auto-generated method stub
//return super.getTableCellEditorComponent(table, value, isSelected, row, column);
return getTableCellRendererComponent(
table, value,
isSelected, false,
row, column);
}
/* (non-Javadoc)
* @see javax.swing.CellEditor#addCellEditorListener(javax.swing.event.CellEditorListener)
*/
public void addCellEditorListener(CellEditorListener l)
{
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see javax.swing.CellEditor#cancelCellEditing()
*/
public void cancelCellEditing()
{
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see javax.swing.CellEditor#getCellEditorValue()
*/
public Object getCellEditorValue()
{
if(container.getCbExplicitPermission().hasFocus())
return !(container.getCbExplicitPermission().isSelected());
else
return container.getCbExplicitPermission().isSelected();
// if(cbExplicitPermission.hasFocus())
// return !(cbExplicitPermission.isSelected());
// else
// return cbExplicitPermission.isSelected();
// TODO Auto-generated method stub
//return null;
}
/* (non-Javadoc)
* @see javax.swing.CellEditor#isCellEditable(java.util.EventObject)
*/
public boolean isCellEditable(EventObject anEvent)
{
// TODO Auto-generated method stub
return true;
}
/* (non-Javadoc)
* @see javax.swing.CellEditor#removeCellEditorListener(javax.swing.event.CellEditorListener)
*/
public void removeCellEditorListener(CellEditorListener l)
{
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see javax.swing.CellEditor#shouldSelectCell(java.util.EventObject)
*/
public boolean shouldSelectCell(EventObject anEvent)
{
// TODO Auto-generated method stub
return true;
}
/* (non-Javadoc)
* @see javax.swing.CellEditor#stopCellEditing()
*/
public boolean stopCellEditing()
{
//return cbExplicitPermission.hasFocus();
// TODO Auto-generated method stub
return true;
}
}

View File

@ -0,0 +1,37 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.gui;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import ch.ethz.infsec.secureumlgui.logging.MultiContextLogger;
/**
*
*/
public class ActionPermissionTableCellSelectionListener
implements ListSelectionListener
{
MultiContextLogger logger = MultiContextLogger.getDefault();
/* (non-Javadoc)
* @see javax.swing.event.ListSelectionListener#valueChanged(javax.swing.event.ListSelectionEvent)
*/
public void valueChanged(ListSelectionEvent e)
{
logger.info("value changed " + e.getSource());
ListSelectionModel lsm =
(ListSelectionModel)e.getSource();
if (!lsm.isSelectionEmpty())
{
int selectedCol = lsm.getMinSelectionIndex();
}
}
}

View File

@ -0,0 +1,335 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.gui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JToolTip;
import org.apache.log4j.Logger;
import org.omg.uml.foundation.core.AssociationEnd;
import org.omg.uml.foundation.core.UmlClass;
import ch.ethz.infsec.secureumlgui.ModuleController;
import ch.ethz.infsec.secureumlgui.ResourceFilesManager;
import ch.ethz.infsec.secureumlgui.logging.MultiContextLogger;
import ch.ethz.infsec.secureumlgui.modelmapping.permissions.ActionPermissionSet;
import ch.ethz.infsec.secureumlgui.modelmapping.permissions.PermissionValue;
import ch.ethz.infsec.secureumlgui.wrapper.ActionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.PermissionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.PolicyWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.RoleWrapper;
/**
*
*/
public class ActionPermissionsTableCellRendererComponent
extends JPanel
implements ActionListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
private PolicyWrapper policy;
//private UmlClass policy;
private static Logger aLog = Logger.getLogger(ActionPermissionsTableCellRendererComponent.class);
/**
*
*/
public ActionPermissionsTableCellRendererComponent(
ActionPermissionSet actionPermissions, PolicyWrapper policy)
{
//
this.actionPermissions = actionPermissions;
this.policy = policy;
this.add(cbExplicitPermission);
initIconLabels();
//this.add(lbOtherPermissions);
// container.addMouseListener(
// new ActionPermissionTableCellListener(
// cbExplicitPermission));
// cbExplicitPermission.addMouseListener(
// new ActionPermissionTableCellListener(
// cbExplicitPermission));
processPermissions(actionPermissions);
cbExplicitPermission.addActionListener(this);
// lbOtherPermissions.setText(
// actionPermissions.toString());
// this.setToolTipText(
// "Description of the origin of all permissions");
//
}
static ResourceFilesManager resourceFilesManager =
new ResourceFilesManager();
ActionPermissionSet actionPermissions = null;
MultiContextLogger logger =
MultiContextLogger.getDefault();
JCheckBox cbExplicitPermission = new JCheckBox();
//JLabel lbOtherPermissions = new JLabel();
JLabel lbConstrained = new JLabel();
JLabel lbImplicit = new JLabel();
JLabel lbImplicitConstrained = new JLabel();
JLabel lbInheritedRole = new JLabel();
JLabel lbInheritedPolicy = new JLabel();
JLabel lbInheritedConstrained = new JLabel();
JLabel lbCompositeFull = new JLabel();
JLabel lbCompositeFullConstrained = new JLabel();
JLabel lbImplicitByComposite = new JLabel();
//PermissionValue explicitPermissionValue = null;
protected void initIconLabels()
{
lbConstrained.setIcon(resourceFilesManager.getConstrainedIcon());
lbInheritedRole.setIcon(resourceFilesManager.getInheritedRoleIcon());
lbInheritedPolicy.setIcon(resourceFilesManager.getInheritedPolicyIcon());
lbInheritedConstrained.setIcon(resourceFilesManager.getConstrainedIcon());
lbImplicit.setIcon(resourceFilesManager.getImplicitIcon());
lbImplicitConstrained.setIcon(resourceFilesManager.getConstrainedIcon());
lbCompositeFull.setIcon(resourceFilesManager.getCompositeFullIcon());
lbCompositeFullConstrained.setIcon(resourceFilesManager.getConstrainedIcon());
lbImplicitByComposite.setIcon(resourceFilesManager.getImplicitByInheritedIcon());
this.add(lbConstrained);
this.add(lbInheritedRole);
this.add(lbInheritedPolicy);
this.add(lbInheritedConstrained);
this.add(lbImplicit);
this.add(lbImplicitConstrained);
this.add(lbCompositeFull);
this.add(lbCompositeFullConstrained);
this.add(lbImplicitByComposite);
}
/**
* @param actionPermissions
*/
private void processPermissions(ActionPermissionSet actionPermissions)
{
cbExplicitPermission.setSelected(actionPermissions.isExplicitPermitted(policy));
// XXX
// explicitPermissionValue =
// actionPermissions.getExplicitPermission();
//
// cbExplicitPermission.setSelected(
// actionPermissions.getExplicitPermission().
// getValue() ==
// PermissionValue.GRANTED.getValue());
// first set all icons invisible
lbConstrained.setVisible(false);
lbInheritedRole.setVisible(false);
lbInheritedPolicy.setVisible(false);
lbInheritedConstrained.setVisible(false);
lbImplicit.setVisible(false);
lbImplicitConstrained.setVisible(false);
lbCompositeFull.setVisible(false);
lbCompositeFullConstrained.setVisible(false);
lbImplicitByComposite.setVisible(false);
String tooltip = "";
// and then show the ones for the defined permissions
for (Iterator iter = actionPermissions.getPermissions(policy).iterator(); iter.hasNext();)
{
PermissionValue pv = (PermissionValue) iter.next();
tooltip += pv.getDescription() + " *** \n";
int flags = pv.getFlags();
aLog.debug("permission (0x" + Integer.toHexString(flags) + ") " + pv.getPermissionWrapper().getName());
if ( ( flags & PermissionValue.INT_GRANTED & PermissionValue.INT_CONSTRAINED) > 0 ) {
if(pv.isConstrained())
lbConstrained.setVisible(true);
}
if ( (flags & PermissionValue.INT_INHERITED_POLICY ) > 0) {
//ignore all types from super polices
lbInheritedPolicy.setVisible(true);
} else {
if ( (flags & PermissionValue.INT_INHERITED) > 0 ) {
lbInheritedRole.setVisible(true);
if ( (flags & PermissionValue.INT_CONSTRAINED) > 0 ) {
lbInheritedConstrained.setVisible(true);
}
}
if ( (flags & (PermissionValue.INT_IMPLICIT | PermissionValue.INT_COMPOSITE) ) > 0 ) {
lbImplicitByComposite.setVisible(true);
}
else {
if ( (flags & PermissionValue.INT_IMPLICIT) > 0 ) {
lbImplicit.setVisible(true);
if ( (flags & PermissionValue.INT_CONSTRAINED) > 0 ) {
lbImplicitConstrained.setVisible(true);
}
}
if ( (flags & PermissionValue.INT_COMPOSITE) > 0 ) {
lbCompositeFull.setVisible(true);
if ( (flags & PermissionValue.INT_CONSTRAINED) > 0 ) {
lbCompositeFullConstrained.setVisible(true);
}
}
}
}
// int value = pv.getValue();
//
// if(value == pv.GRANTED.getValue())
// {
// // this is the explicit permission
// // -> checkbox is displayed and initialized already
// if(pv.isConstrained())
// lbConstrained.setVisible(true);
// }
// else if(value == pv.DENIED.getValue())
// {
// // denied permission =^= no permission
// // do nothing
// }
// else if(value == pv.INHERITED.getValue())
// {
// lbInherited.setVisible(true);
// if(pv.isConstrained())
// lbInheritedConstrained.setVisible(true);
// }
// else if(value == pv.IMPLICIT.getValue())
// {
// lbImplicit.setVisible(true);
// if(pv.isConstrained())
// lbImplicitConstrained.setVisible(true);
// }
// else if(value == pv.COMPOSITE.getValue())
// {
// lbCompositeFull.setVisible(true);
// if(pv.isConstrained())
// lbCompositeFullConstrained.setVisible(true);
// }
// else
// {
// aLog.warn("unhandled permission value: " + pv);
// logger.error(
// "unhandled permission value: " + pv);
// }
}
this.setToolTipText(tooltip);
}
/**
* @return the cbExplicitPermission
*/
public JCheckBox getCbExplicitPermission()
{
return cbExplicitPermission;
}
/* (non-Javadoc)
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent e)
{
// PermissionWrapper pw =
// explicitPermissionValue.getPermissionWrapper();
//
// logger.info("Editing a Permission, old PermissionValue: "
// + explicitPermissionValue + "\n");
// if(pw == null)
// {
// logger.error("PermissionWrapper == null");
// }
// else
// {
// logger.info("Action: "
// + pw.getActionWrapper().getName()
// + ", Role: "
// + pw.getRoleWrapper().getName());
// }
logger.info("Action: "
+ actionPermissions.getExplicitActionWrapper()
+ ", Role: "
+ actionPermissions.getExplicitRoleWrapper());
PermissionWrapper pw = actionPermissions.getExplicitPermittedPermission(policy);
//explicitPermissionValue.getPermissionWrapper();
if(pw == null)
{
logger.info("creating permission...");
Set<PolicyWrapper> policies = new HashSet<PolicyWrapper>();
policies.add(policy);
logger.info("existing permissions: "+actionPermissions);
ModuleController.getInstance().addPermission(
actionPermissions.getExplicitActionWrapper(),
actionPermissions.getExplicitRoleWrapper(),
policies);
}
else
{
logger.info("deleting permission...");
ModuleController.getInstance().deletePermission(
pw);
}
}
@Override
public JToolTip createToolTip() {
MultiLineToolTip tip = new MultiLineToolTip();
tip.setComponent(this);
return tip;
}
}

View File

@ -0,0 +1,227 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.gui;
import java.util.Collection;
import java.util.Set;
import org.apache.log4j.Logger;
import org.omg.uml.foundation.core.ModelElement;
import ch.ethz.infsec.secureumlgui.modelmapping.GenericDialectHelper;
import ch.ethz.infsec.secureumlgui.modelmapping.permissions.ActionPermissionSet;
import ch.ethz.infsec.secureumlgui.modelmapping.permissions.HierarchicalPermissionsExplorer;
import ch.ethz.infsec.secureumlgui.modelmapping.permissions.HierarchicalPolicyExplorer;
import ch.ethz.infsec.secureumlgui.modelmapping.permissions.PermissionSet;
import ch.ethz.infsec.secureumlgui.modelmapping.permissions.PermissionValue;
import ch.ethz.infsec.secureumlgui.modelmapping.permissions.ResourcePermissionsSet;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.DialectMetaModelInfo;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.ResourceType;
import ch.ethz.infsec.secureumlgui.transformation.ModelMap;
import ch.ethz.infsec.secureumlgui.wrapper.ActionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.PermissionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.PolicyWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.ResourceWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.RoleWrapper;
/**
* Swing table model for the permission table displayed in the
* SecureUML properties tab for resources.
* Columns are roles, rows are actions on the resource.
*
*/
public class GenericResourcePermissionsTableModel extends AbstractPermissionsTableModel
{
private static final long serialVersionUID = 1L;
ResourceWrapper resourceWrapper;
PermissionSet permissions = new PermissionSet();
Collection<ActionWrapper> actionWrappers;
private static Logger aLog = Logger.getLogger(GenericResourcePermissionsTableModel.class);
public GenericResourcePermissionsTableModel(
ResourceWrapper resourceWrapper)
{
super(resourceWrapper.getModelElement());
setResource(resourceWrapper);
}
/**
* @param resourceWrapper
*/
protected void setResource(ResourceWrapper resourceWrapper)
{
super.setResource(resourceWrapper);
this.resourceWrapper = resourceWrapper;
initActionPermissionSets();
// init
// TODO realy needed????
// Object suModelElement = resourceWrapper.getModelElement();
// ModelElement umlModelElement = (ModelElement) ModelMap.getDefault().getUmlElement(suModelElement);
// ResourceType rt = GenericDialectHelper.getInstance().getResourceType(umlModelElement);
// DialectMetaModelInfo mmInfo = GenericDialectHelper.getInstance().getDialectMetaModelInfo();
actionWrappers = resourceWrapper.getActionWrapper();
initExplicitPermissions(resourceWrapper);
HierarchicalPermissionsExplorer permissionsExplorer = new HierarchicalPermissionsExplorer();
permissionsExplorer.collectNonExplicitPermissions(resourceWrapper, permissions);
}
/**
* creates the objects that will be filled with explicit and interhited/implicit permissions
*
*/
protected void initActionPermissionSets() {
for (RoleWrapper role : roleWrappers) {
ResourcePermissionsSet resourcePermissions = permissions.getResourcePermissionsSet(role);
for (ActionWrapper action : resourceWrapper.getActionWrapper()) {
ActionPermissionSet actionPermissions = resourcePermissions.getPermissions(action);
actionPermissions.setExplicitRoleWrapper(role);
actionPermissions.setExplicitActionWrapper(action);
}
}
}
private void initExplicitPermissions(ResourceWrapper resource) {
PolicyWrapper defaultPolicy = HierarchicalPolicyExplorer.getInstance().getDefaultPolicyWrapper();
for (ActionWrapper action : resource.getActionWrapper()) {
for (PermissionWrapper permission : action.getPermissionWrappers()) {
RoleWrapper role = permission.getRoleWrapper();
if(role != null) {
Set<PolicyWrapper> policies = permission.getPolicyWrappers();
PolicyWrapper policy = null;
if (policies != null || policies.size() > 0) {
policy = policies.iterator().next();
if (policies.size() > 1 ) {
aLog.error("ignoring all policies except first one.. TODO");
}
}
aLog.debug("policy: " + (policies == null ? "NULL" : policy.getModelElement()));
// permissions.getResourcePermissionsSet(role).addPermission(
// action, PermissionValue.create(PermissionValue.GRANTED, permission));
if ( policy == null ) {
policy = defaultPolicy;
}
//policy = defaultPolicy;
aLog.debug("G: add explicit permission: " + role.getName() + " on " + action.getName() + " on policy " + (policy == null ? "NULL" : policy.getName()));
permissions.getResourcePermissionsSet(role).addPermission(
action, PermissionValue.createGranted(permission), policy);
permissions.getResourcePermissionsSet(role).getPermissions(action).
addExplicitPermission(policy, PermissionValue.createGranted(permission));
// if ( defaultPolicy == null ) {
// permissions.getResourcePermissionsSet(role).getPermissions(action).
// addDefaultPermission(PermissionValue.createGranted(permission));
// } else {
//// permissions.getResourcePermissionsSet(role).getActionPermissionSet(action).
//// addPermission(policy, PermissionValue.createGranted(permission));
// }
ResourcePermissionsSet rps = permissions.getResourcePermissionsSet(
new RoleWrapper(role.getModelElement()));
//hel ActionPermissionSet aps = rps.getPermissions(actionName);
ActionPermissionSet aps = rps.getPermissions(action.getName());
aps.setExplicitRoleWrapper(role);
// logger.info("Test: fetch the added Permission: " + aps.getFlatPermission());
}
else {
aLog.warn("Permission without role");
}
}
}
}
/* (non-Javadoc)
* @see javax.swing.table.TableModel#getRowCount()
*/
public int getRowCount()
{
return actionWrappers.size();
}
/* (non-Javadoc)
* @see javax.swing.table.TableModel#getValueAt(int, int)
*/
public Object getValueAt(int row, int col)
{
ActionWrapper aw = (ActionWrapper) actionWrappers.toArray()[row];
if(col == 0) {
String actionName = aw.getName();
return aw;
}
else { // other columns - i.e. return ROLEs and the assigned permissions
RoleWrapper roleWrapper = roleWrappers.get(col-1);
ResourcePermissionsSet resourcePermissions =
permissions.getResourcePermissionsSet(roleWrapper);
ActionPermissionSet actionPermissions =
resourcePermissions.getPermissions(aw.getName());
return actionPermissions;
}
}
/* (non-Javadoc)
* @see ch.ethz.infsec.secureumlgui.gui.AbstractPermissionsTableModel#isCellEditable(int, int)
*/
@Override
public boolean isCellEditable(int row, int col) {
if(col == 0)
return false;
else
return true;
}
/* (non-Javadoc)
* @see ch.ethz.infsec.secureumlgui.gui.AbstractPermissionsTableModel#getColumnClass(int)
*/
@Override
public Class<?> getColumnClass(int columnIndex)
{
if(columnIndex == 0)
return ActionWrapper.class;
else
return ActionPermissionSet.class;
}
}

View File

@ -0,0 +1,227 @@
package ch.ethz.infsec.secureumlgui.gui;
import javax.swing.*;
import javax.swing.event.ChangeListener;
import javax.swing.plaf.ActionMapUIResource;
import java.awt.event.*;
/**
* 2003-12-02 The Java Specialists' Newsletter [Issue 082]
* TristateCheckBox based on the Swing JCheckBox
* Author: Dr. Heinz M. Kabutz *
* from http://www.javaspecialists.co.za/archive/Issue082.html
*
* Maintenance tip - There were some tricks to getting this code
* working:
*
* 1. You have to overwite addMouseListener() to do nothing
* 2. You have to add a mouse event on mousePressed by calling
* super.addMouseListener()
* 3. You have to replace the UIActionMap for the keyboard event
* "pressed" with your own one.
* 4. You have to remove the UIActionMap for the keyboard event
* "released".
* 5. You have to grab focus when the next state is entered,
* otherwise clicking on the component won't get the focus.
* 6. You have to make a TristateDecorator as a button model that
* wraps the original button model and does state management.
*/
public class JTristateCheckBox extends JCheckBox
{
/** This is a type-safe enumerated type */
public static class State {
private State() { }
}
public static final State NOT_SELECTED = new State();
public static final State SELECTED = new State();
public static final State DONT_CARE = new State();
private final TristateDecorator model;
public JTristateCheckBox(String text, Icon icon, State initial)
{
super(text, icon);
// Add a listener for when the mouse is pressed
super.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
grabFocus();
model.nextState();
}
});
// Reset the keyboard action map
ActionMap map = new ActionMapUIResource();
map.put("pressed", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
grabFocus();
model.nextState();
}
});
map.put("released", null);
SwingUtilities.replaceUIActionMap(this, map);
// set the model to the adapted model
model = new TristateDecorator(getModel());
setModel(model);
setState(initial);
}
public JTristateCheckBox(String text, State initial) {
this(text, null, initial);
}
public JTristateCheckBox(String text) {
this(text, DONT_CARE);
}
public JTristateCheckBox() {
this(null);
}
/** No one may add mouse listeners, not even Swing! */
public void addMouseListener(MouseListener l) { }
/**
* Set the new state to either SELECTED, NOT_SELECTED or
* DONT_CARE. If state == null, it is treated as DONT_CARE.
*/
public void setState(State state) {
model.setState(state);
}
/** Return the current state, which is determined by the
* selection status of the model. */
public State getState() {
return model.getState();
}
public void setSelected(boolean b) {
if (b) {
setState(SELECTED);
} else {
setState(NOT_SELECTED);
}
}
/**
* Exactly which Design Pattern is this? Is it an Adapter,
* a Proxy or a Decorator? In this case, my vote lies with the
* Decorator, because we are extending functionality and
* "decorating" the original model with a more powerful model.
*/
private class TristateDecorator implements ButtonModel {
private final ButtonModel other;
private TristateDecorator(ButtonModel other) {
this.other = other;
}
private void setState(State state) {
if (state == NOT_SELECTED) {
other.setArmed(false);
setPressed(false);
setSelected(false);
} else if (state == SELECTED) {
other.setArmed(false);
setPressed(false);
setSelected(true);
} else { // either "null" or DONT_CARE
other.setArmed(true);
setPressed(true);
setSelected(true);
}
}
/**
* The current state is embedded in the selection / armed
* state of the model.
*
* We return the SELECTED state when the checkbox is selected
* but not armed, DONT_CARE state when the checkbox is
* selected and armed (grey) and NOT_SELECTED when the
* checkbox is deselected.
*/
private State getState() {
if (isSelected() && !isArmed()) {
// normal black tick
return SELECTED;
} else if (isSelected() && isArmed()) {
// don't care grey tick
return DONT_CARE;
} else {
// normal deselected
return NOT_SELECTED;
}
}
/** We rotate between NOT_SELECTED, SELECTED and DONT_CARE.*/
private void nextState() {
State current = getState();
if (current == NOT_SELECTED) {
setState(SELECTED);
} else if (current == SELECTED) {
setState(DONT_CARE);
} else if (current == DONT_CARE) {
setState(NOT_SELECTED);
}
}
/** Filter: No one may change the armed status except us. */
public void setArmed(boolean b) {
}
/** We disable focusing on the component when it is not
* enabled. */
public void setEnabled(boolean b) {
setFocusable(b);
other.setEnabled(b);
}
/** All these methods simply delegate to the "other" model
* that is being decorated. */
public boolean isArmed() {
return other.isArmed();
}
public boolean isSelected() {
return other.isSelected();
}
public boolean isEnabled() {
return other.isEnabled();
}
public boolean isPressed() {
return other.isPressed();
}
public boolean isRollover() {
return other.isRollover();
}
public void setSelected(boolean b) {
other.setSelected(b);
}
public void setPressed(boolean b) {
other.setPressed(b);
}
public void setRollover(boolean b) {
other.setRollover(b);
}
public void setMnemonic(int key) {
other.setMnemonic(key);
}
public int getMnemonic() {
return other.getMnemonic();
}
public void setActionCommand(String s) {
other.setActionCommand(s);
}
public String getActionCommand() {
return other.getActionCommand();
}
public void setGroup(ButtonGroup group) {
other.setGroup(group);
}
public void addActionListener(ActionListener l) {
other.addActionListener(l);
}
public void removeActionListener(ActionListener l) {
other.removeActionListener(l);
}
public void addItemListener(ItemListener l) {
other.addItemListener(l);
}
public void removeItemListener(ItemListener l) {
other.removeItemListener(l);
}
public void addChangeListener(ChangeListener l) {
other.addChangeListener(l);
}
public void removeChangeListener(ChangeListener l) {
other.removeChangeListener(l);
}
public Object[] getSelectedObjects() {
return other.getSelectedObjects();
}
}
}

View File

@ -0,0 +1,63 @@
/**
* http://www.codeguru.com/java/articles/122.shtml
*
* Author: Zafir Anjum
*/
package ch.ethz.infsec.secureumlgui.gui;
import javax.swing.*;
import javax.swing.plaf.*;
import java.awt.*;
import java.awt.font.*;
import java.awt.event.*;
import javax.swing.plaf.*;
import javax.swing.plaf.basic.BasicToolTipUI;
import javax.swing.text.*;
/**
* @author Zafir Anjum
*/
public class MultiLineToolTip extends JToolTip
{
private static final String uiClassID = "ToolTipUI";
String tipText;
JComponent component;
public MultiLineToolTip() {
updateUI();
}
public void updateUI() {
setUI(MultiLineToolTipUI.createUI(this));
}
public void setColumns(int columns)
{
this.columns = columns;
this.fixedwidth = 0;
}
public int getColumns()
{
return columns;
}
public void setFixedWidth(int width)
{
this.fixedwidth = width;
this.columns = 0;
}
public int getFixedWidth()
{
return fixedwidth;
}
protected int columns = 20;
protected int fixedwidth = 20;
}

View File

@ -0,0 +1,101 @@
/**
* http://www.codeguru.com/java/articles/122.shtml
*
* Author: Zafir Anjum
*/
package ch.ethz.infsec.secureumlgui.gui;
import javax.swing.*;
import javax.swing.plaf.*;
import java.awt.*;
import java.awt.font.*;
import java.awt.event.*;
import javax.swing.plaf.*;
import javax.swing.plaf.basic.BasicToolTipUI;
import javax.swing.text.*;
class MultiLineToolTipUI extends BasicToolTipUI {
static MultiLineToolTipUI sharedInstance = new MultiLineToolTipUI();
Font smallFont;
static JToolTip tip;
protected CellRendererPane rendererPane;
private static JTextArea textArea ;
public static ComponentUI createUI(JComponent c) {
return sharedInstance;
}
public MultiLineToolTipUI() {
super();
}
public void installUI(JComponent c) {
super.installUI(c);
tip = (JToolTip)c;
rendererPane = new CellRendererPane();
c.add(rendererPane);
}
public void uninstallUI(JComponent c) {
super.uninstallUI(c);
c.remove(rendererPane);
rendererPane = null;
}
public void paint(Graphics g, JComponent c) {
Dimension size = c.getSize();
textArea.setBackground(c.getBackground());
rendererPane.paintComponent(g, textArea, c, 1, 1,
size.width - 1, size.height - 1, true);
}
public Dimension getPreferredSize(JComponent c) {
String tipText = ((JToolTip)c).getTipText();
if (tipText == null)
return new Dimension(0,0);
textArea = new JTextArea(tipText );
rendererPane.removeAll();
rendererPane.add(textArea );
textArea.setWrapStyleWord(true);
int width = ((MultiLineToolTip)c).getFixedWidth();
int columns = ((MultiLineToolTip)c).getColumns();
if( columns > 0 )
{
textArea.setColumns(columns);
textArea.setSize(0,0);
textArea.setLineWrap(true);
textArea.setSize( textArea.getPreferredSize() );
}
else if( width > 0 )
{
textArea.setLineWrap(true);
Dimension d = textArea.getPreferredSize();
d.width = width;
d.height++;
textArea.setSize(d);
}
else
textArea.setLineWrap(false);
Dimension dim = textArea.getPreferredSize();
dim.height += 1;
dim.width += 1;
return dim;
}
public Dimension getMinimumSize(JComponent c) {
return getPreferredSize(c);
}
public Dimension getMaximumSize(JComponent c) {
return getPreferredSize(c);
}
}

View File

@ -0,0 +1,218 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.gui;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import javax.swing.event.TableModelEvent;
import javax.swing.table.AbstractTableModel;
import ch.ethz.infsec.secureumlgui.logging.MultiContextLogger;
import ch.ethz.infsec.secureumlgui.wrapper.ActionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.PermissionWrapper;
/**
* Swing table model for the permission table displayed in the
* SecureUML properties tab for permissions.
* Each row is one resource-action pair.
*
*/
public class PermissionAttributesTableModel extends AbstractTableModel
{
/**
*
*/
public PermissionAttributesTableModel(
List<PermissionWrapper> permissions)
{
super();
setCurrentPermissionWrappers(permissions);
}
List<PermissionWrapper> currentPermissionWrappers;
ArrayList<ActionWrapper> actionWrappers =
new ArrayList<ActionWrapper>();
MultiContextLogger logger = MultiContextLogger.getDefault();
public void setCurrentPermissionWrappers(
List<PermissionWrapper> permissionWrappers)
{
actionWrappers.clear();
currentPermissionWrappers = permissionWrappers;
try
{
for (Iterator iter = currentPermissionWrappers.iterator(); iter.hasNext();)
{
PermissionWrapper permissionWrapper = (PermissionWrapper) iter.next();
actionWrappers.add(permissionWrapper.getActionWrapper());
//logger.info(logger.TARGET_EVENTS, "RolePermissionsTable: Added" + actions.size() + " Action(s)");
// for (Iterator iterator = permission.getAction().iterator(); iterator.hasNext();)
// {
// Action action = (Action) iterator.next();
//
// actions.add(action);
//// txPermissions.append(action.getResource()
//// + ": " + action.getName()
//// + "\n");
// }
}
sortByResource();
}
catch (Exception e)
{
logger.logException(e);
}
}
public String getColumnName(int column)
{
//logger.info("requesting Column Name " + column);
if(column == 0)
{
return "RESOURCE";
}
else if(column == 1)
{
return "ACTION";
}
else
return "#ERROR#";
}
/* (non-Javadoc)
* @see javax.swing.table.TableModel#getRowCount()
*/
public int getRowCount()
{
try
{
return actionWrappers.size();
}
catch (Exception e)
{
return 0;
}
}
public int getColumnCount()
{
return 2;
}
public Object getValueAt(int row, int col)
{
if(col == 0)
{
String val = actionWrappers.get(row).getResourceWrapper().getResourcePath();
if(val==null || val.equals(""))
return "N/A";
else
return val;
}
else if(col == 1)
{
String val = actionWrappers.get(row).getName();
if(val==null || val.equals(""))
return "N/A";
else
return val;
}
else
return null;
}
/* (non-Javadoc)
* @see javax.swing.table.AbstractTableModel#getColumnClass(int)
*/
@Override
public Class<?> getColumnClass(int columnIndex)
{
return String.class;
}
public void fireManually()
{
fireTableStructureChanged();
fireTableDataChanged();
fireTableChanged(new TableModelEvent(this));
}
private void sortByResource()
{
Collections.sort(actionWrappers, new actionResourceComparator());
}
private void sortByActionName()
{
Collections.sort(actionWrappers, new actionNameComparator());
}
public class actionResourceComparator implements Comparator<ActionWrapper>
{
public int compare(ActionWrapper a1, ActionWrapper a2)
{
try
{
if(a1 == null || a2 == null)
{
if (a1 != null)
return a1.getResource().toString().compareTo("");
else if(a2 != null)
return a2.getResource().toString().compareTo("");
else
return 0;
}
else
return a1.getResource().toString().compareTo(a2.getResource().toString());
}
catch (Exception e)
{
return 0;
}
}
}
public class actionNameComparator implements Comparator<ActionWrapper>
{
public int compare(ActionWrapper a1, ActionWrapper a2)
{
try
{
if(a1 == null || a2 == null)
{
if (a1 != null)
return a1.getResource().toString().compareTo("");
else if(a2 != null)
return a2.getResource().toString().compareTo("");
else
return 0;
}
else
return a1.getName().compareTo(a2.getName());
}
catch (Exception e)
{
return 0;
}
}
}
}

View File

@ -0,0 +1,37 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.gui;
import java.awt.Component;
import java.awt.Container;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
import ch.ethz.infsec.secureumlgui.modelmapping.permissions.PermissionValue;
/**
*
*/
public class PermissionIconTableCellRenderer
implements TableCellRenderer
{
public Component getTableCellRendererComponent(
JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column)
{
//Container container = new JPanel();
if (value instanceof PermissionValue)
{
PermissionValue pv = (PermissionValue) value;
return new PermissionIconTableCellRendererComponent(pv);
}
else
return new JLabel("error");
}
}

View File

@ -0,0 +1,89 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.gui;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import ch.ethz.infsec.secureumlgui.ResourceFilesManager;
import ch.ethz.infsec.secureumlgui.logging.MultiContextLogger;
import ch.ethz.infsec.secureumlgui.modelmapping.permissions.PermissionValue;
/**
*
*/
public class PermissionIconTableCellRendererComponent
extends JPanel
{
static ResourceFilesManager resourceFilesManager =
new ResourceFilesManager();
MultiContextLogger logger =
MultiContextLogger.getDefault();
JCheckBox cbExplicitPermission = new JCheckBox();
JLabel lbConstrained = new JLabel();
JLabel lbImplicit = new JLabel();
JLabel lbInherited = new JLabel();
//JLabel lbValue = new JLabel();
/**
*
*/
public PermissionIconTableCellRendererComponent(PermissionValue pv)
{
initIconLabels();
//lbValue.setText(pv.getName());
setVisible(true);
//this.add(lbValue);
String tooltip = pv.getDescription();
if(pv.getValue() == pv.GRANTED.getValue())
{
this.add(cbExplicitPermission);
cbExplicitPermission.setVisible(true);
}
else if(pv.getValue() == pv.IMPLICIT.getValue())
{
this.add(lbImplicit);
lbImplicit.setVisible(true);
}
else if(pv.getValue() == pv.INHERITED.getValue())
{
this.add(lbInherited);
lbImplicit.setVisible(true);
}
else
{
this.add(new JLabel("error"));
}
if(pv.isConstrained())
{
this.add(lbConstrained);
lbConstrained.setVisible(true);
}
setToolTipText(tooltip);
}
protected void initIconLabels()
{
cbExplicitPermission.setSelected(true);
lbConstrained.setIcon(resourceFilesManager.getConstrainedIcon());
lbInherited.setIcon(resourceFilesManager.getInheritedRoleIcon());
lbImplicit.setIcon(resourceFilesManager.getImplicitIcon());
}
}

View File

@ -0,0 +1,9 @@
package ch.ethz.infsec.secureumlgui.gui;
import javax.swing.JPanel;
public class PolicyLevelCreator extends JPanel {
}

View File

@ -0,0 +1,452 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.gui;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import javax.swing.event.TableModelEvent;
import javax.swing.table.AbstractTableModel;
import org.apache.log4j.Logger;
import org.omg.uml.foundation.core.ModelElement;
import ch.ethz.infsec.secureumlgui.Util;
import ch.ethz.infsec.secureumlgui.logging.MultiContextLogger;
import ch.ethz.infsec.secureumlgui.modelmapping.GenericDialectHelper;
import ch.ethz.infsec.secureumlgui.modelmapping.GenericDialectModelMapper;
import ch.ethz.infsec.secureumlgui.modelmapping.permissions.ActionPermissionSet;
import ch.ethz.infsec.secureumlgui.modelmapping.permissions.HierarchicalPermissionsExplorer;
import ch.ethz.infsec.secureumlgui.modelmapping.permissions.PermissionSet;
import ch.ethz.infsec.secureumlgui.modelmapping.permissions.PermissionValue;
import ch.ethz.infsec.secureumlgui.modelmapping.permissions.ResourcePermissionsSet;
import ch.ethz.infsec.secureumlgui.transformation.ModelMap;
import ch.ethz.infsec.secureumlgui.wrapper.ActionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.PermissionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.RoleWrapper;
/**
* Swing table model for the permission table displayed in the
* SecureUML properties tab for roles. Each row represents a
* permission for a specific resource-action pair. The first column
* describes the kind of permission (explicit, implicit, inherited,
* etc), the second and third column are resource and action, resp.
*
*
*/
public class RolePermissionsTableModel extends AbstractTableModel
{
/**
*
*/
public RolePermissionsTableModel(RoleWrapper roleWrapper)
{
super();
setCurrentRole(roleWrapper);
}
private static Logger aLog = Logger.getLogger(RolePermissionsTableModel.class);
RoleWrapper currentRoleWrapper;
//ArrayList<ActionWrapper> actionWrappers = new ArrayList<ActionWrapper>();
ArrayList<PermissionValue> permissionValues =
new ArrayList<PermissionValue>();
MultiContextLogger logger = new MultiContextLogger(MultiContextLogger.GUI);
public void setCurrentRole(RoleWrapper roleWrapper)
{
String loggerString = "RolePermissionsTableModel.setCurrentRole with " ;
if(roleWrapper.getPermissionWrapper() == null)
loggerString += "0";
else
loggerString += roleWrapper.getPermissionWrapper().size();
loggerString += " Permissions";
//logger.info(loggerString);
//actionWrappers.clear();
permissionValues.clear();
currentRoleWrapper = roleWrapper;
try
{
HierarchicalPermissionsExplorer hps =
new HierarchicalPermissionsExplorer();
for (Iterator iter = currentRoleWrapper.getPermissionWrapper().iterator(); iter.hasNext();)
{
PermissionWrapper permission = (PermissionWrapper) iter.next();
//actionWrappers.add(permission.getActionWrapper());
PermissionValue pv =
PermissionValue.create(
PermissionValue.GRANTED,
permission);
permissionValues.add(pv);
//logger.info(logger.TARGET_EVENTS, "RolePermissionsTable: Added" + actions.size() + " Action(s)");
// for (Iterator iterator = permission.getAction().iterator(); iterator.hasNext();)
// {
// Action action = (Action) iterator.next();
//
// actions.add(action);
//// txPermissions.append(action.getResource()
//// + ": " + action.getName()
//// + "\n");
// }
PermissionSet permissions = hps.getExplicitPermissions(permission.getActionWrapper().getResourceWrapper());
hps.collectNonExplicitPermissions(permission.getActionWrapper().getResourceWrapper(), permissions);
ResourcePermissionsSet rps =
permissions.getResourcePermissionsSet(roleWrapper);
// collect implicit permissions
for (Iterator iterator = rps.getActions().iterator(); iterator
.hasNext();)
{
Object action = iterator.next();
ActionPermissionSet aps =
rps.getPermissions(action);
aLog.warn("setCurrentRole: which policy? using default policy");
for (Iterator it = aps.getDefaultPolicyPermissionSet().getPermissions().iterator(); it
.hasNext();)
{
PermissionValue permissionValue =
(PermissionValue) it.next();
if(!permissionValues.contains(permissionValue)
&& !(permissionValue.getValue() == permissionValue.INHERITED.getValue()))
permissionValues.add(permissionValue);
//permissionValue.getPermissionWrapper().setAction(
//aps.getExplicitActionWrapper().getModelElement());
//action);
// aps.getExplicitActionWrapper().getModelElement());
}
}
// ActionPermissionSet aps = new ActionPermissionSet();
// aps.setExplicitActionWrapper(permission.getActionWrapper());
// aps.setExplicitRoleWrapper(roleWrapper);
//
// aps.addPermission(
// PermissionValue.create(
// PermissionValue.GRANTED,
// permission));
}
// collect inherited permissions
Collection superroles = hps.getSuperRoleWrappersDeep(roleWrapper);
for (Iterator iterator = superroles.iterator(); iterator
.hasNext();)
{
RoleWrapper superrole = (RoleWrapper) iterator.next();
Collection<PermissionWrapper> permissionWrappers =
superrole.getPermissionWrapper();
for (Iterator iter = permissionWrappers.iterator(); iter.hasNext();)
{
PermissionWrapper pw = (PermissionWrapper) iter.next();
PermissionValue pv =
PermissionValue.create(
PermissionValue.INHERITED, pw);
permissionValues.add(pv);
}
}
sortByResource();
sortByPermissionValue();
}
catch (Exception e)
{
logger.logException(e);
}
}
public String getColumnName(int column)
{
//logger.info("requesting Column Name " + column);
if(column == 0)
{
return "PERMISSION";
}
if(column == 1)
{
return "RESOURCE";
}
else if(column == 2)
{
return "ACTION";
}
else
return "#ERROR#";
}
/* (non-Javadoc)
* @see javax.swing.table.TableModel#getRowCount()
*/
public int getRowCount()
{
try
{
return permissionValues.size();
//return actionWrappers.size();
}
catch (Exception e)
{
return 0;
}
}
public int getColumnCount()
{
return 3;
}
public Object getValueAt(int row, int col)
{
if(col == 0)
{
return permissionValues.get(row);
}
else if(col == 1)
{
if(permissionValues.get(row) == null)
return "null";
else
{
//return actionWrappers.get(row).getResource().toString();
String resourcePath =
permissionValues.get(row).getPermissionWrapper().
getActionWrapper().getResourceWrapper().
getResourcePath();
//actionWrappers.get(row).getResourceWrapper().getResourcePath();
return resourcePath;
}
}
else if(col == 2)
{
if(permissionValues.get(row) == null)
return "null";
else
{
return permissionValues.get(row).getPermissionWrapper().
getActionWrapper().getName();
//return actionWrappers.get(row).getName();
}
}
else
return null;
}
/* (non-Javadoc)
* @see javax.swing.table.AbstractTableModel#getColumnClass(int)
*/
@Override
public Class<?> getColumnClass(int columnIndex)
{
if(columnIndex == 0)
return PermissionValue.class;
else
return String.class;
}
public void fireManually()
{
fireTableStructureChanged();
fireTableDataChanged();
fireTableChanged(new TableModelEvent(this));
}
private void sortByResource()
{
Collections.sort(permissionValues, new permissionActionResourceComparator());
//Collections.sort(actionWrappers, new actionResourceComparator());
}
private void sortByActionName()
{
Collections.sort(//actionWrappers, new actionNameComparator()
permissionValues, new permissionActionNameComparator());
}
private void sortByPermissionValue()
{
Collections.sort(permissionValues,
new permissionValuesComparator());
}
// public class actionResourceComparator implements Comparator<ActionWrapper>
// {
// public int compare(ActionWrapper a1, ActionWrapper a2)
// {
// try
// {
// if(a1 == null || a2 == null)
// {
// if (a1 != null)
// return a1.getResource().toString().compareTo("");
// else if(a2 != null)
// return a2.getResource().toString().compareTo("");
// else
// return 0;
// }
// else
// return a1.getResource().toString().
// compareTo(a2.getResource().toString());
// }
// catch (Exception e)
// {
// return 0;
// }
// }
// }
public class permissionActionResourceComparator
implements Comparator<PermissionValue>
{
public int compare(PermissionValue pv1, PermissionValue pv2)
{
try
{
if(pv1 == null || pv2 == null)
{
if (pv1 != null)
return pv1.getPermissionWrapper().getActionWrapper().
getResource().toString().compareTo("");
else if(pv2 != null)
return pv2.getPermissionWrapper().getActionWrapper().
getResource().toString().compareTo("");
else
return 0;
}
else
return pv1.getPermissionWrapper().getActionWrapper().
getResource().toString().
compareTo(pv2.getPermissionWrapper().getActionWrapper().
getResource().toString());
}
catch (Exception e)
{
return 0;
}
}
}
// public class actionNameComparator implements Comparator<ActionWrapper>
// {
// public int compare(ActionWrapper a1, ActionWrapper a2)
// {
// try
// {
// if(a1 == null || a2 == null)
// {
// if (a1 != null)
// return a1.getResource().toString().compareTo("");
// else if(a2 != null)
// return a2.getResource().toString().compareTo("");
// else
// return 0;
// }
// else
// return a1.getName().compareTo(a2.getName());
// }
// catch (Exception e)
// {
// return 0;
// }
// }
// }
public class permissionActionNameComparator
implements Comparator<PermissionValue>
{
public int compare(PermissionValue pv1, PermissionValue pv2)
{
try
{
if(pv1 == null || pv2 == null)
{
if (pv1 != null)
return pv1.getPermissionWrapper().getActionWrapper().
getResource().toString().compareTo("");
else if(pv2 != null)
return pv2.getPermissionWrapper().getActionWrapper().
getResource().toString().compareTo("");
else
return 0;
}
else
return pv1.getPermissionWrapper().getActionWrapper().
getName().compareTo(pv2.getName());
}
catch (Exception e)
{
return 0;
}
}
}
// sorts descending
public class permissionValuesComparator
implements Comparator<PermissionValue>
{
public int compare(PermissionValue pv1, PermissionValue pv2)
{
try
{
if(pv1 == null || pv2 == null)
{
if (pv1 != null)
return -pv1.getValue();
else if(pv2 != null)
return pv2.getValue();
else
return 0;
}
else
return -pv1.compareTo(pv2);
}
catch (Exception e)
{
return 0;
}
}
}
}

View File

@ -0,0 +1,422 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.gui;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.swing.DefaultCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.TableColumn;
import org.apache.log4j.Logger;
import org.argouml.uml.diagram.ui.UMLDiagram;
import org.omg.uml.foundation.core.UmlClass;
import ch.ethz.infsec.secureumlgui.ModuleController;
import ch.ethz.infsec.secureumlgui.ResourceFilesManager;
import ch.ethz.infsec.secureumlgui.modelmapping.permissions.ActionPermissionSet;
import ch.ethz.infsec.secureumlgui.modelmapping.permissions.HierarchicalPolicyExplorer;
import ch.ethz.infsec.secureumlgui.wrapper.ActionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.AtomicActionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.CompositeActionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.PolicyWrapper;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.ResourceType;
import ch.ethz.infsec.secureumlgui.wrapper.ResourceWrapper;
/**
* generic SecureUML properties component for Resources.
*
* Displays which roles have which permissions for which actions on this resource.
* distinguishes between explicit, implicit, and inherited permissions.
*
*/
public class SecureUmlComponent
extends AbstractSecureUmlComponent
//implements MouseListener
implements ChangeListener
{
/**
*
*/
public SecureUmlComponent()
{
super();
initComponents();
}
private String NEW_ROLE_NAME = "NewRole";
private JTabbedPane tabPane;
//private Map<String, PolicyWrapper> polices;
//private List<PolicyWrapper> policies = new ArrayList<PolicyWrapper>();
private List<UmlClass> policies = new ArrayList<UmlClass>();
private List<JTable> tables = new ArrayList<JTable>();
private PolicyLevelCreator policyCreator;
// private JScrollPane jScrollPane;
// private JTable tblPermissions;
private TableSorter tableSorter;
private JTextField txName;
private JLabel lbType;
private JLabel lbName;
private ResourceWrapper displayedResourceWrapper = null;
private GenericResourcePermissionsTableModel tableModel;
private static Logger aLog = Logger.getLogger(SecureUmlComponent.class);
public void initComponents()
{
JButton btNewRole = new JButton("New Role");
btNewRole.setToolTipText("New Role");
btNewRole.addActionListener(new createRoleActionListener());
try
{ //SecureUmlComponent.class
ResourceFilesManager resourceFilesManager =
new ResourceFilesManager();
ImageIcon icon = resourceFilesManager.getCreateRoleIcon();
if (icon != null)
{
btNewRole.setIcon(icon);
}
else
{
logger.warn(logger.STARTUP,
"Image File for Button 'New Role' " +
"not found - showing Text only");
}
}
catch (Exception e)
{
logger.logException(e);
}
/* NOTE: If a JTable is put on a JScrollPane, the Header
* is displayed automatically (otherwise this needs to be
* done manually). The Column Names are fetched from the
* Method 'TableModel.getColumnName(int col)'
*/
// tblPermissions = new JTable();
// tblPermissions.setColumnSelectionAllowed(false);
// tblPermissions.setDragEnabled(false);
tableSorter = new TableSorter();
//tblPermissions.getTableHeader().setSize(200, 50);
tabPane = new JTabbedPane(SwingConstants.LEFT);
tabPane.addChangeListener(this);
//JScrollPane jScrollPane = new JScrollPane(tblPermissions);
tabPane.add("Create Policy", policyCreator);
// int dummyPol = 4;
// policies = new PolicyWrapper[dummyPol+1];
// for ( int i = 0 ; i < dummyPol; ++i ) {
// tabPane.add("policy Name " + i, new JScrollPane(tblPermissions) );
// policies[i+1] = null;
// }
policyCreator = new PolicyLevelCreator();
// tblPermissions.setFillsViewportHeight(true);
lbName=new JLabel("SecureUML Resource:");
txName= new JTextField();
txName.setEditable(false);
lbType = new JLabel("unknown Resource");
JPanel topPane = new JPanel();
JPanel labels = new JPanel();
labels.add(lbName,BorderLayout.LINE_START);
labels.add(lbType,BorderLayout.LINE_START);
labels.add(txName,BorderLayout.LINE_START);
topPane.add(labels,BorderLayout.LINE_START);
topPane.add(btNewRole,BorderLayout.CENTER);
this.add(topPane,BorderLayout.PAGE_START);
//this.add(jScrollPane,BorderLayout.CENTER);
this.add(tabPane,BorderLayout.CENTER);
}
//protected void setDisplayedResourceWrapper(AbstractPermissionsTableModel tableModel)
protected void setDisplayedResourceWrapper()
{
int selectedTab = tabPane.getSelectedIndex();
if ( selectedTab < 0 || selectedTab >= policies.size()) {
//no policies, create Policy is selected
return;
}
//PolicyWrapper currentPolicy = policies.get(selectedTab); //policies[tabPane.getSelectedIndex()];
UmlClass currentPolicy = policies.get(selectedTab); //policies[tabPane.getSelectedIndex()];
JTable tblPermissions = tables.get(selectedTab);
txName.setText(displayedResourceWrapper.getResourcePath());
aLog.debug("setDisplayedResourceWrapper tab: " + selectedTab + " policy: " + currentPolicy.getName());
try
{
//tblPermissions.setModel(tableModel);
tableSorter.setTableModel(tableModel);
tblPermissions.setModel(tableSorter);
tableSorter.setTableHeader(tblPermissions.getTableHeader());
tblPermissions.setSelectionMode(
ListSelectionModel.SINGLE_SELECTION);
//tblPermissions.setAutoResizeMode(
// JTable.AUTO_RESIZE_OFF);
tblPermissions.setCellSelectionEnabled(true);
tblPermissions.setColumnSelectionAllowed(false);
tblPermissions.setRowSelectionAllowed(false);
initTableCellDimensions(tblPermissions);
// tblPermissions.getColumnModel().getColumn(0).
// setCellRenderer(
// new ActionNameTableCellRenderer());
// tblPermissions.getColumnModel().getColumn(1).
// setCellRenderer(
// new ActionPermissionTableCellRenderer());
tblPermissions.setDefaultRenderer(
ActionPermissionSet.class,
new ActionPermissionTableCellRenderer(currentPolicy));
tblPermissions.setDefaultEditor(
ActionPermissionSet.class,
new ActionPermissionTableCellRenderer(currentPolicy));
tblPermissions.setDefaultRenderer(
ActionWrapper.class,
new ActionNameTableCellRenderer());
tblPermissions.setDefaultEditor(
ActionWrapper.class,
new ActionNameTableCellRenderer());
tblPermissions.setDefaultRenderer(
AtomicActionWrapper.class,
new ActionNameTableCellRenderer());
tblPermissions.setDefaultRenderer(
CompositeActionWrapper.class,
new ActionNameTableCellRenderer());
tblPermissions.getColumnModel().
getColumn(0).setCellRenderer(
new ActionNameTableCellRenderer());
//(new ActionPermissionTableCellRenderer()).addCellEditorListener(l)
//tblPermissions.addMouseListener(l);
tblPermissions.getTableHeader().
setToolTipText("SecureUML Roles");
// logger.info("tableCellRenderer(1,0): "
// + tblPermissions.getCellRenderer(1, 0));
//
// int columnCount = tableModel.getColumnCount();
//
tableModel.fireManually();
tblPermissions.getTableHeader().addMouseListener(tableModel);
// tblPermissions.repaint();
// tblPermissions.setValueAt(tblPermissions.getValueAt(1, 0),1,0);
//
// throws NullpointerException only when a first
// UML Element is selected
//jScrollPane.getColumnHeader().setVisible(true);
}
catch (Exception e)
{
logger.logException(e);
}
}
/**
*
*/
private void initTableCellDimensions(JTable tblPermissions)
{
// hack
tblPermissions.setRowHeight(26);
tblPermissions.getColumnModel().getColumn(0).setMaxWidth(52);
for (Enumeration<TableColumn> cols = tblPermissions.getColumnModel().getColumns(); cols.hasMoreElements();)
{
TableColumn col = (TableColumn) cols.nextElement();
col.setMinWidth(525);
}
}
private class createRoleActionListener implements ActionListener
{
/* (non-Javadoc)
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent e)
{
ModuleController.getInstance().addRole(
NEW_ROLE_NAME,
displayedResourceWrapper);
}
}
private void updatePolicyTabs () {
aLog.debug("updatePolicyTabs");
boolean rebuild = false;
//List<PolicyWrapper> sortedPolicies = HierarchicalPolicyExplorer.getInstance().getSortedPolicies();
List<UmlClass> sortedPolicies = HierarchicalPolicyExplorer.getInstance().getSortedPolicies();
int policiesCount = 0;
int tabCount = tabPane.getTabCount();
if ( sortedPolicies != null ) {
policiesCount = sortedPolicies.size();
}
if ( tabPane.getTabCount()-1 != policiesCount ) {
rebuild = true;
} else {
for (int i = 0; i < policiesCount && i < tabCount; ++i) {
if ( ! sortedPolicies.get(i).getName().equals(tabPane.getTitleAt(i))) {
rebuild = true;
break;
}
}
}
aLog.debug("updatePolicyTabs: tabCount: " + tabCount+ ", policiesCount: " + policiesCount + " rebuild: " + rebuild);
if ( rebuild ) {
for ( int i = 0; i < policiesCount && i < tabCount - 1; ++i) {
tabPane.setTitleAt(i, sortedPolicies.get(i).getName());
policies.set(i, sortedPolicies.get(i));
aLog.debug("set permissonPanel at index " + i +" for policy " + sortedPolicies.get(i).getName());
}
if ( policiesCount > (tabCount - 1)) {
//remove (the last) create policy tab
tabPane.remove(tabCount - 1);
//for (int i = policiesCount; i < (tabCount - 1); ++i) {
for (int i = tabCount - 1; i < policiesCount; ++i) {
JTable tblPermissions;
if (tables.size() > i && tables.get(i) != null) {
tblPermissions = tables.get(i);
} else {
tblPermissions = new JTable();
tblPermissions.setColumnSelectionAllowed(false);
tblPermissions.setDragEnabled(false);
}
JScrollPane jScrollPane = new JScrollPane(tblPermissions);
tabPane.add(sortedPolicies.get(i).getName(), jScrollPane);
policies.add(i, sortedPolicies.get(i)); //#
tables.add(i, tblPermissions);
aLog.debug("added permissonPanel at index " + i +" for policy " + sortedPolicies.get(i).getName());
}
tabPane.add("Create Policy", policyCreator);
} else if ( policiesCount < (tabCount - 1) ) {
for (int i = policiesCount; i < (tabCount - 1); ++i) {
tabPane.remove(i);
policies.remove(i);
aLog.debug("removed permission panel from index " + i);
}
}
aLog.debug("updatePolicyTabs: done");
}
// if ( sortedPolicies != null) {
// policies = new PolicyWrapper[sortedPolicies.size()];
// for (int i = 0 ; i < sortedPolicies.size(); ++i) {
// tabPane.add(sortedPolicies.get(i).getName(), new JScrollPane(tblPermissions));
// policies[i] = sortedPolicies.get(i);
// }
// }
}
public void setDisplayedSecureUmlElement(
Object suElement, ResourceType rt)
{
aLog.debug("setDisplayedSecureUmlElement");
updatePolicyTabs();
super.setDisplayedSecureUmlElement(suElement, rt);
lbType.setText(rt.getName());
this.displayedResourceWrapper = new ResourceWrapper(suElement);
this.tableModel = new GenericResourcePermissionsTableModel(displayedResourceWrapper);
//setDisplayedResourceWrapper(tableModel);
setDisplayedResourceWrapper();
}
public void stateChanged(ChangeEvent arg0) {
if (tableModel != null) {
setDisplayedResourceWrapper();
}
}
}

View File

@ -0,0 +1,65 @@
package ch.ethz.infsec.secureumlgui.gui;
import java.awt.Dimension;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import ch.ethz.infsec.secureumlgui.util.ExcpPermissionDummy;
import ch.ethz.infsec.secureumlgui.util.PermissionDummy;
/**
*
*
*/
public class SecureUmlExcpPermissionComponent extends
SecureUmlPermissionComponent {
JLabel lbExcpLevel;
JTextField txExcpLevel;
public SecureUmlExcpPermissionComponent()
{
super();
initExcpComponents();
}
private void initExcpComponents() {
super.lbName.setText("Exception Permission Name: ");
lbExcpLevel = new JLabel("Exception Level: ");
txExcpLevel = new JTextField();
txExcpLevel.setEditable(false);
}
//hack...
protected void addAdditionalPanels(JPanel boxes) {
lbExcpLevel = new JLabel("Exception Level: ");
txExcpLevel = new JTextField();
txExcpLevel.setEditable(false);
JPanel excpLevel = new JPanel();
excpLevel.setLayout(new BoxLayout(excpLevel, BoxLayout.LINE_AXIS));
excpLevel.setMaximumSize(new Dimension(1000,20));
excpLevel.add(lbExcpLevel);
excpLevel.add(txExcpLevel);
boxes.add(excpLevel);
}
public void setDisplayedPermission(ExcpPermissionDummy displayedPermission) {
super.setDisplayedPermission(displayedPermission);
}
}

View File

@ -0,0 +1,366 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.gui;
import java.awt.Dimension;
import java.awt.BorderLayout;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import ch.ethz.infsec.secureumlgui.ModuleController;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.ResourceType;
import ch.ethz.infsec.secureumlgui.securemodel.secureuml.Permission;
import ch.ethz.infsec.secureumlgui.util.PermissionDummy;
import ch.ethz.infsec.secureumlgui.wrapper.PermissionWrapper;
/**
* SecureUML Properties component for permissions.
*
* Displays the role which has this permission, as well as the action,
* this permission permits.
*
*/
public class SecureUmlPermissionComponent
extends AbstractSecureUmlComponent
//implements DocumentListener
{
/**
*
*/
public SecureUmlPermissionComponent()
{
super();
initComponents();
}
JPanel textboxesPanel;
JLabel lbName;
JTextField txName;
JLabel lbAnchor;
JTextField txAnchor;
JLabel lbRole;
JTextField txRole;
JLabel lbConstraint;
JTextArea txConstraint;
JLabel lbPermissionAttributes;
JScrollPane scpPermissionAttributes;
JTable tblPermissionAttributes;
public void initComponents()
{
lbName = new JLabel("Permission Name: ");
txName = new JTextField();
txName.setEditable(false);
lbAnchor = new JLabel("Anchor: ");
txAnchor = new JTextField();
txAnchor.setEditable(false);
lbRole = new JLabel("Role: ");
txRole = new JTextField();
txRole.setEditable(false);
lbConstraint = new JLabel("OCL Constraint: ");
txConstraint = new JTextArea(10,60);
txConstraint.setEditable(true);
JScrollPane scpConstr = new JScrollPane(txConstraint);
tblPermissionAttributes = new JTable();
scpPermissionAttributes = new JScrollPane(tblPermissionAttributes);
// scpPermissionAttributes.setMinimumSize(
// new Dimension(200, 140));
JPanel names = new JPanel();
names.setLayout(new BoxLayout(names, BoxLayout.LINE_AXIS));
names.setMaximumSize(new Dimension(1000,20));
names.add(lbName);
names.add(txName);
JPanel roles = new JPanel();
roles.setLayout(new BoxLayout(roles, BoxLayout.LINE_AXIS));
roles.setMaximumSize(new Dimension(1000,20));
roles.add(lbRole);
roles.add(txRole);
JPanel anchors = new JPanel();
anchors.setLayout(new BoxLayout(anchors, BoxLayout.LINE_AXIS));
anchors.setMaximumSize(new Dimension(1000,20));
anchors.add(lbAnchor);
anchors.add(txAnchor);
anchors.setAlignmentX(LEFT_ALIGNMENT);
names.setAlignmentX(LEFT_ALIGNMENT);
roles.setAlignmentX(LEFT_ALIGNMENT);
lbConstraint.setAlignmentX(LEFT_ALIGNMENT);
scpConstr.setAlignmentX(LEFT_ALIGNMENT);
JPanel boxes = new JPanel();
boxes.setLayout(new BoxLayout(boxes, BoxLayout.PAGE_AXIS));
addAdditionalPanels(boxes);
boxes.add(names);
boxes.add(roles);
boxes.add(anchors);
boxes.add(lbConstraint);
boxes.add(scpConstr);
txConstraint.getDocument().addDocumentListener(new ConstraintListener());
this.add(boxes, BorderLayout.LINE_START);
this.add(scpPermissionAttributes, BorderLayout.CENTER);
}
//hack...
protected void addAdditionalPanels(JPanel boxes) {
;
}
private PermissionDummy displayedPermission;
public PermissionDummy getDisplayedPermission()
{
return displayedPermission;
}
List<PermissionWrapper> displayedPermissionAttributes;
public void setDisplayedPermission(PermissionDummy displayedPermission)
{
if (displayedPermission == null) logger.error("null in setDisplayedPermission");
this.displayedPermission = displayedPermission;
// logger.info(logger.TARGET_EVENTS, "displayedPermission set to: "
// + displayedPermission
// + "\n named: " + displayedPermission.getName()
// + ",\n for anchor: "
// + displayedPermission.getAnchor().getName()
// + ",\n and role: "
// + displayedPermission.getRole().getName());
try
{
if (displayedPermission.getAnchor() == null) logger.error("displayed Permission has no anchor set");
txName.setText(displayedPermission.getName());
txAnchor.setText(displayedPermission.
getAnchorWrapper().getName());
txRole.setText(displayedPermission.
getRoleWrapper().getName());
if(displayedPermission.
getAuthorizationConstraintWrapper().
getModelElement() != null)
{
txConstraint.setText(displayedPermission.
getAuthorizationConstraintWrapper().getConstraint());
}
else
txConstraint.setText("");
// setTitle(displayedPermission.getName()
// + " - SecureUML Permission");
this.invalidate();
}
catch (Exception e)
{
logger.logException(e);
}
displayPermissionAttributes(
displayedPermission.getPermissionAttributeWrappers());
}
private void onAuthorizationConstraintChanged()
{
// too verbose -
// 2 lines for each single character change in Textbox
// logger.info(logger.GUI,
// "AuthorizationConstraint changed to: '"
// + txConstraint.getText() + "'");
ModuleController.getInstance().
setAuthorizationConstraint(displayedPermission,
txConstraint.getText());
}
private void onPermissionNameChanged()
{
// ModuleController.getInstance().
// setPermissionName(displayedPermission,
// txName.getText());
}
protected void displayPermissionAttributes(
List<PermissionWrapper> permissionAttributes)
{
this.displayedPermissionAttributes = permissionAttributes;
try
{
PermissionAttributesTableModel tableModel =
new PermissionAttributesTableModel(
displayedPermissionAttributes);
//tblPermissions.setModel(tableModel);
TableSorter sorter = new TableSorter(tableModel);
tblPermissionAttributes.setModel(sorter);
//sorter.addMouseListenerToHeaderInTable(tblPermissions);
sorter.setTableHeader(
tblPermissionAttributes.getTableHeader());
// http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#sorting
tableModel.fireManually();
sorter.fireTableStructureChanged();
sorter.fireTableDataChanged();
//tblPermissions.validate();
//scpPermissions.validate();
//tblPermissions.setTableHeader(new JTableHeader(tableModel))
// moved to RolePermissionsTableModel
// for (Iterator iter = displayedRole.getPermission().iterator(); iter.hasNext();)
// {
// Permission permission = (Permission) iter.next();
//
// for (Iterator iterator = permission.getAction().iterator(); iterator.hasNext();)
// {
// Action action = (Action) iterator.next();
//
// txPermissions.append(action.getResource()
// + ": " + action.getName()
// + "\n");
// }
// }
}
catch (Exception e)
{
logger.logException(e);
}
}
private class ConstraintListener implements DocumentListener
{
/* Document Listener Handlers */
/**
* @see javax.swing.event.DocumentListener#changedUpdate(javax.swing.event.DocumentEvent)
*/
public void changedUpdate(DocumentEvent e)
{
onAuthorizationConstraintChanged();
}
/**
* @see javax.swing.event.DocumentListener#insertUpdate(javax.swing.event.DocumentEvent)
*/
public void insertUpdate(DocumentEvent e)
{
onAuthorizationConstraintChanged();
}
/**
* @see javax.swing.event.DocumentListener#removeUpdate(javax.swing.event.DocumentEvent)
*/
public void removeUpdate(DocumentEvent e)
{
onAuthorizationConstraintChanged();
}
}
private class PermissionNameListener implements DocumentListener
{
/* Document Listener Handlers */
/**
* @see javax.swing.event.DocumentListener#changedUpdate(javax.swing.event.DocumentEvent)
*/
public void changedUpdate(DocumentEvent e)
{
onPermissionNameChanged();
//txConstraint.getDocument().get
//e.getChange(null).
}
/**
* @see javax.swing.event.DocumentListener#insertUpdate(javax.swing.event.DocumentEvent)
*/
public void insertUpdate(DocumentEvent e)
{
onPermissionNameChanged();
}
/**
* @see javax.swing.event.DocumentListener#removeUpdate(javax.swing.event.DocumentEvent)
*/
public void removeUpdate(DocumentEvent e)
{
onPermissionNameChanged();
}
}
/* (non-Javadoc)
* @see ch.ethz.infsec.secureumlgui.gui.AbstractSecureUmlComponent#setDisplayedSecureUmlElement(java.lang.Object, ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.ResourceType)
*/
@Override
public void setDisplayedSecureUmlElement(Object suElement, ResourceType rt)
{
//setTitle("SecureUML Permission");
// TODO Auto-generated method stub
if (suElement == null) logger.error("null in setDisplayedSecureUmlElement");
if (rt == null) logger.error("null in setDisplayedSecureUmlElement");
super.setDisplayedSecureUmlElement(suElement, rt);
setDisplayedPermission((PermissionDummy)suElement);
}
/* (non-Javadoc)
* @see javax.swing.JComponent#setMinimumSize(java.awt.Dimension)
*/
@Override
public void setMinimumSize(Dimension minimumSize)
{
// TODO Auto-generated method stub
//super.setMinimumSize(minimumSize);
// minimumSize.height -= 100;
// minimumSize.height /= 2;
//
// if(minimumSize.height >0)
// scpPermissionAttributes.setMinimumSize(minimumSize);
}
}

View File

@ -0,0 +1,161 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.gui;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JPanel;
import org.tigris.swidgets.LabelledLayout;
import ch.ethz.infsec.secureumlgui.gui.RolePermissionsTableModel;
import ch.ethz.infsec.secureumlgui.modelmapping.permissions.PermissionValue;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.ResourceType;
import ch.ethz.infsec.secureumlgui.wrapper.ActionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.RoleWrapper;
/**
* SecureUML Properties component for Roles.
*
* Displays all actions this role has (explicit, implicit, or inherited)
*
*/
public class SecureUmlRoleComponent extends AbstractSecureUmlComponent
{
/**
*
*/
public SecureUmlRoleComponent()
{
super();//"SecureUml Role Permissions");//Properties");
initComponents();
}
JLabel lbName;
JTextField txName;
JLabel lbPermissions;
JScrollPane scpPermissions;
JTable tblPermissions;
JButton btNewRole;
public void initComponents()
{
lbName = new JLabel("Role Name: ");
txName = new JTextField();
txName.setEditable(false);
tblPermissions= new JTable();
// already displayed by the default PropPanel
// but here for testing purposes
JPanel labels = new JPanel();
labels.add(lbName,BorderLayout.LINE_START);
labels.add(txName, BorderLayout.CENTER);
/* NOTE: If a JTable is put on a JScrollPane, the Header
* is displayed automatically (otherwise this needs to be
* done manually). The Column Names are fetched from the
* Method 'TableModel.getColumnName(int col)'
*/
scpPermissions = new JScrollPane(tblPermissions);
tblPermissions.setRowHeight(26);
//scpPermissions.setMinimumSize(new Dimension(0, 120));
//this.add(tblPermissions);
this.add(labels, BorderLayout.LINE_START);
this.add(scpPermissions, BorderLayout.CENTER);
//this.validate();
}
private RoleWrapper displayedRoleWrapper;
public RoleWrapper getDisplayedRoleWrapper()
{
return displayedRoleWrapper;
}
public void setDisplayedRoleWrapper(RoleWrapper displayedRoleWrapper)
{
tblPermissions.setDefaultRenderer(
PermissionValue.class,
new PermissionIconTableCellRenderer());
// tblPermissions.getColumnModel().
// getColumn(0).setCellRenderer(
// new PermissionIconTableCellRenderer());
this.displayedRoleWrapper = displayedRoleWrapper;
if(displayedRoleWrapper != null)
{
txName.setText(displayedRoleWrapper.getName());
// setTitle(displayedRoleWrapper.getName()
// + " - SecureUML Role");
}
displayPermissions();
}
protected void displayPermissions()
{
try
{
RolePermissionsTableModel tableModel =
new RolePermissionsTableModel(
displayedRoleWrapper);
//tblPermissions.setModel(tableModel);
TableSorter sorter = new TableSorter(tableModel);
tblPermissions.setModel(sorter);
//sorter.addMouseListenerToHeaderInTable(tblPermissions);
sorter.setTableHeader(tblPermissions.getTableHeader());
// http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#sorting
tableModel.fireManually();
sorter.fireTableStructureChanged();
sorter.fireTableDataChanged();
}
catch (Exception e)
{
logger.logException(e);
}
}
/* (non-Javadoc)
* @see ch.ethz.infsec.secureumlgui.gui.AbstractSecureUmlComponent#setDisplayedSecureUmlElement(java.lang.Object, ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.ResourceType)
*/
@Override
public void setDisplayedSecureUmlElement(Object suElement, ResourceType rt)
{
//setTitle("SecureUML Role");
// TODO Auto-generated method stub
super.setDisplayedSecureUmlElement(suElement, rt);
setDisplayedRoleWrapper(new RoleWrapper(suElement));
}
}

View File

@ -0,0 +1,486 @@
package ch.ethz.infsec.secureumlgui.gui;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.*;
/**
* from: http://java.sun.com/docs/books/tutorial/uiswing/components/examples/TableSorter.java
*
*
* TableSorter is a decorator for TableModels; adding sorting
* functionality to a supplied TableModel. TableSorter does
* not store or copy the data in its TableModel; instead it maintains
* a map from the row indexes of the view to the row indexes of the
* model. As requests are made of the sorter (like getValueAt(row, col))
* they are passed to the underlying model after the row numbers
* have been translated via the internal mapping array. This way,
* the TableSorter appears to hold another copy of the table
* with the rows in a different order.
* <p/>
* TableSorter registers itself as a listener to the underlying model,
* just as the JTable itself would. Events recieved from the model
* are examined, sometimes manipulated (typically widened), and then
* passed on to the TableSorter's listeners (typically the JTable).
* If a change to the model has invalidated the order of TableSorter's
* rows, a note of this is made and the sorter will resort the
* rows the next time a value is requested.
* <p/>
* When the tableHeader property is set, either by using the
* setTableHeader() method or the two argument constructor, the
* table header may be used as a complete UI for TableSorter.
* The default renderer of the tableHeader is decorated with a renderer
* that indicates the sorting status of each column. In addition,
* a mouse listener is installed with the following behavior:
* <ul>
* <li>
* Mouse-click: Clears the sorting status of all other columns
* and advances the sorting status of that column through three
* values: {NOT_SORTED, ASCENDING, DESCENDING} (then back to
* NOT_SORTED again).
* <li>
* SHIFT-mouse-click: Clears the sorting status of all other columns
* and cycles the sorting status of the column through the same
* three values, in the opposite order: {NOT_SORTED, DESCENDING, ASCENDING}.
* <li>
* CONTROL-mouse-click and CONTROL-SHIFT-mouse-click: as above except
* that the changes to the column do not cancel the statuses of columns
* that are already sorting - giving a way to initiate a compound
* sort.
* </ul>
* <p/>
* This is a long overdue rewrite of a class of the same name that
* first appeared in the swing table demos in 1997.
*
* @author Philip Milne
* @author Brendon McLean
* @author Dan van Enckevort
* @author Parwinder Sekhon
* @version 2.0 02/27/04
*/
public class TableSorter extends AbstractTableModel {
protected TableModel tableModel;
public static final int DESCENDING = -1;
public static final int NOT_SORTED = 0;
public static final int ASCENDING = 1;
private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
public static final Comparator COMPARABLE_COMAPRATOR = new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) o1).compareTo(o2);
}
};
public static final Comparator LEXICAL_COMPARATOR = new Comparator() {
public int compare(Object o1, Object o2) {
return o1.toString().compareTo(o2.toString());
}
};
private Row[] viewToModel;
private int[] modelToView;
private JTableHeader tableHeader;
private MouseListener mouseListener;
private TableModelListener tableModelListener;
private Map columnComparators = new HashMap();
private List sortingColumns = new ArrayList();
public TableSorter() {
this.mouseListener = new MouseHandler();
this.tableModelListener = new TableModelHandler();
}
public TableSorter(TableModel tableModel) {
this();
setTableModel(tableModel);
}
public TableSorter(TableModel tableModel, JTableHeader tableHeader) {
this();
setTableHeader(tableHeader);
setTableModel(tableModel);
}
private void clearSortingState() {
viewToModel = null;
modelToView = null;
}
public TableModel getTableModel() {
return tableModel;
}
public void setTableModel(TableModel tableModel) {
if (this.tableModel != null) {
this.tableModel.removeTableModelListener(tableModelListener);
}
this.tableModel = tableModel;
if (this.tableModel != null) {
this.tableModel.addTableModelListener(tableModelListener);
}
clearSortingState();
fireTableStructureChanged();
}
public JTableHeader getTableHeader() {
return tableHeader;
}
public void setTableHeader(JTableHeader tableHeader) {
if (this.tableHeader != null) {
this.tableHeader.removeMouseListener(mouseListener);
TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer();
if (defaultRenderer instanceof SortableHeaderRenderer) {
this.tableHeader.setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
}
}
this.tableHeader = tableHeader;
if (this.tableHeader != null) {
this.tableHeader.addMouseListener(mouseListener);
this.tableHeader.setDefaultRenderer(
new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer()));
}
}
public boolean isSorting() {
return sortingColumns.size() != 0;
}
private Directive getDirective(int column) {
for (int i = 0; i < sortingColumns.size(); i++) {
Directive directive = (Directive)sortingColumns.get(i);
if (directive.column == column) {
return directive;
}
}
return EMPTY_DIRECTIVE;
}
public int getSortingStatus(int column) {
return getDirective(column).direction;
}
private void sortingStatusChanged() {
clearSortingState();
fireTableDataChanged();
if (tableHeader != null) {
tableHeader.repaint();
}
}
public void setSortingStatus(int column, int status) {
Directive directive = getDirective(column);
if (directive != EMPTY_DIRECTIVE) {
sortingColumns.remove(directive);
}
if (status != NOT_SORTED) {
sortingColumns.add(new Directive(column, status));
}
sortingStatusChanged();
}
protected Icon getHeaderRendererIcon(int column, int size) {
Directive directive = getDirective(column);
if (directive == EMPTY_DIRECTIVE) {
return null;
}
return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive));
}
private void cancelSorting() {
sortingColumns.clear();
sortingStatusChanged();
}
public void setColumnComparator(Class type, Comparator comparator) {
if (comparator == null) {
columnComparators.remove(type);
} else {
columnComparators.put(type, comparator);
}
}
protected Comparator getComparator(int column) {
Class columnType = tableModel.getColumnClass(column);
Comparator comparator = (Comparator) columnComparators.get(columnType);
if (comparator != null) {
return comparator;
}
if (Comparable.class.isAssignableFrom(columnType)) {
return COMPARABLE_COMAPRATOR;
}
return LEXICAL_COMPARATOR;
}
private Row[] getViewToModel() {
if (viewToModel == null) {
int tableModelRowCount = tableModel.getRowCount();
viewToModel = new Row[tableModelRowCount];
for (int row = 0; row < tableModelRowCount; row++) {
viewToModel[row] = new Row(row);
}
if (isSorting()) {
Arrays.sort(viewToModel);
}
}
return viewToModel;
}
public int modelIndex(int viewIndex) {
return getViewToModel()[viewIndex].modelIndex;
}
private int[] getModelToView() {
if (modelToView == null) {
int n = getViewToModel().length;
modelToView = new int[n];
for (int i = 0; i < n; i++) {
modelToView[modelIndex(i)] = i;
}
}
return modelToView;
}
// TableModel interface methods
public int getRowCount() {
return (tableModel == null) ? 0 : tableModel.getRowCount();
}
public int getColumnCount() {
return (tableModel == null) ? 0 : tableModel.getColumnCount();
}
public String getColumnName(int column) {
return tableModel.getColumnName(column);
}
public Class getColumnClass(int column) {
return tableModel.getColumnClass(column);
}
public boolean isCellEditable(int row, int column) {
return tableModel.isCellEditable(modelIndex(row), column);
}
public Object getValueAt(int row, int column) {
return tableModel.getValueAt(modelIndex(row), column);
}
public void setValueAt(Object aValue, int row, int column) {
tableModel.setValueAt(aValue, modelIndex(row), column);
}
// Helper classes
private class Row implements Comparable {
private int modelIndex;
public Row(int index) {
this.modelIndex = index;
}
public int compareTo(Object o) {
int row1 = modelIndex;
int row2 = ((Row) o).modelIndex;
for (Iterator it = sortingColumns.iterator(); it.hasNext();) {
Directive directive = (Directive) it.next();
int column = directive.column;
Object o1 = tableModel.getValueAt(row1, column);
Object o2 = tableModel.getValueAt(row2, column);
int comparison = 0;
// Define null less than everything, except null.
if (o1 == null && o2 == null) {
comparison = 0;
} else if (o1 == null) {
comparison = -1;
} else if (o2 == null) {
comparison = 1;
} else {
comparison = getComparator(column).compare(o1, o2);
}
if (comparison != 0) {
return directive.direction == DESCENDING ? -comparison : comparison;
}
}
return 0;
}
}
private class TableModelHandler implements TableModelListener {
public void tableChanged(TableModelEvent e) {
// If we're not sorting by anything, just pass the event along.
if (!isSorting()) {
clearSortingState();
fireTableChanged(e);
return;
}
// If the table structure has changed, cancel the sorting; the
// sorting columns may have been either moved or deleted from
// the model.
if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
cancelSorting();
fireTableChanged(e);
return;
}
// We can map a cell event through to the view without widening
// when the following conditions apply:
//
// a) all the changes are on one row (e.getFirstRow() == e.getLastRow()) and,
// b) all the changes are in one column (column != TableModelEvent.ALL_COLUMNS) and,
// c) we are not sorting on that column (getSortingStatus(column) == NOT_SORTED) and,
// d) a reverse lookup will not trigger a sort (modelToView != null)
//
// Note: INSERT and DELETE events fail this test as they have column == ALL_COLUMNS.
//
// The last check, for (modelToView != null) is to see if modelToView
// is already allocated. If we don't do this check; sorting can become
// a performance bottleneck for applications where cells
// change rapidly in different parts of the table. If cells
// change alternately in the sorting column and then outside of
// it this class can end up re-sorting on alternate cell updates -
// which can be a performance problem for large tables. The last
// clause avoids this problem.
int column = e.getColumn();
if (e.getFirstRow() == e.getLastRow()
&& column != TableModelEvent.ALL_COLUMNS
&& getSortingStatus(column) == NOT_SORTED
&& modelToView != null) {
int viewIndex = getModelToView()[e.getFirstRow()];
fireTableChanged(new TableModelEvent(TableSorter.this,
viewIndex, viewIndex,
column, e.getType()));
return;
}
// Something has happened to the data that may have invalidated the row order.
clearSortingState();
fireTableDataChanged();
return;
}
}
private class MouseHandler extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
JTableHeader h = (JTableHeader) e.getSource();
TableColumnModel columnModel = h.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
int column = columnModel.getColumn(viewColumn).getModelIndex();
if (column != -1) {
int status = getSortingStatus(column);
if (!e.isControlDown()) {
cancelSorting();
}
// Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or
// {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed.
status = status + (e.isShiftDown() ? -1 : 1);
status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
setSortingStatus(column, status);
}
}
}
private static class Arrow implements Icon {
private boolean descending;
private int size;
private int priority;
public Arrow(boolean descending, int size, int priority) {
this.descending = descending;
this.size = size;
this.priority = priority;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
Color color = c == null ? Color.GRAY : c.getBackground();
// In a compound sort, make each succesive triangle 20%
// smaller than the previous one.
int dx = (int)(size/2*Math.pow(0.8, priority));
int dy = descending ? dx : -dx;
// Align icon (roughly) with font baseline.
y = y + 5*size/6 + (descending ? -dy : 0);
int shift = descending ? 1 : -1;
g.translate(x, y);
// Right diagonal.
g.setColor(color.darker());
g.drawLine(dx / 2, dy, 0, 0);
g.drawLine(dx / 2, dy + shift, 0, shift);
// Left diagonal.
g.setColor(color.brighter());
g.drawLine(dx / 2, dy, dx, 0);
g.drawLine(dx / 2, dy + shift, dx, shift);
// Horizontal line.
if (descending) {
g.setColor(color.darker().darker());
} else {
g.setColor(color.brighter().brighter());
}
g.drawLine(dx, 0, 0, 0);
g.setColor(color);
g.translate(-x, -y);
}
public int getIconWidth() {
return size;
}
public int getIconHeight() {
return size;
}
}
private class SortableHeaderRenderer implements TableCellRenderer {
private TableCellRenderer tableCellRenderer;
public SortableHeaderRenderer(TableCellRenderer tableCellRenderer) {
this.tableCellRenderer = tableCellRenderer;
}
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
Component c = tableCellRenderer.getTableCellRendererComponent(table,
value, isSelected, hasFocus, row, column);
if (c instanceof JLabel) {
JLabel l = (JLabel) c;
l.setHorizontalTextPosition(JLabel.LEFT);
int modelColumn = table.convertColumnIndexToModel(column);
l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
}
return c;
}
}
private static class Directive {
private int column;
private int direction;
public Directive(int column, int direction) {
this.column = column;
this.direction = direction;
}
}
}

View File

@ -0,0 +1,10 @@
<html>
<head>
<title></title>
</head>
<body>GUI components for the SecureUML GUI.
Basically everything that is displayed in the details pane in ArgoUML.
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 570 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 230 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 222 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 686 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 204 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 235 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 686 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 570 B

View File

@ -0,0 +1,59 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.logging;
/**
*
*/
public class LoggerContext
{
public static final LoggerContext other = new LoggerContext("other", "other");
public LoggerContext(String longName, String shortName)
{
this.longName = longName;
this.shortName = shortName;
//this.enabled = true;
}
// public LoggerContext(String longName, String shortName, boolean enabled)
// {
// this.longName = longName;
// this.shortName = shortName;
// //this.enabled = enabled;
// }
String longName;
public String getLongName()
{
return longName;
}
// public void setLongName(String longName)
// {
// this.longName = longName;
// }
String shortName;
public String getShortName()
{
return shortName;
}
// public void setShortName(String longName)
// {
// this.longName = longName;
// }
// moved to MultiContextLogger Class
// boolean enabled;
// public boolean isEnabled()
// {
// return enabled;
// }
// public void setEnabled(boolean enabled)
// {
// this.enabled = enabled;
// }
}

View File

@ -0,0 +1,301 @@
package ch.ethz.infsec.secureumlgui.logging;
import java.util.HashSet;
import ch.ethz.infsec.secureumlgui.util.NotImplementedException;
public class MultiContextLogger extends SimpleLogger
{
public MultiContextLogger()
{
super();
// /* enabled by default */
// enabledLoggers.add(MODELMAPPER);
// enabledLoggers.add(MY_JMI_IMPL);
// enabledLoggers.add(TARGET_EVENTS);
// enabledLoggers.add(MODELMAP);
// enabledLoggers.add(GUI);
}
public MultiContextLogger(LoggerContext context)
{
super();
this.defaultContext = context;
}
public static MultiContextLogger getDefault()
{
return defaultLogger;
}
public static MultiContextLogger defaultLogger = new MultiContextLogger();
/* Contexts */
public static final LoggerContext STARTUP = new LoggerContext("Startup and Loading of Module", "Startup");
public static final LoggerContext METAMODEL_PARSER =
new LoggerContext("MetamodelParser", "MetamodelParser");
public static final LoggerContext MODELMAPPER = new LoggerContext("Modelmapper", "ModelMapper");
public static final LoggerContext MODELWRITER = new LoggerContext("Modelwriter", "ModelWriter");
public static final LoggerContext ACTIONINSTANTIATOR = new LoggerContext("ActionInstantiator", "Actions");
public static final LoggerContext MY_JMI_IMPL = new LoggerContext("My JMI Implementation", "JMIImpl");
public static final LoggerContext TARGET_EVENTS = new LoggerContext("Target Events", "Target");
public static final LoggerContext MODELMAP = new LoggerContext("SecureUml Model Map", "Modelmap");
public static final LoggerContext GUI = new LoggerContext("Graphical User Interface (SecureModel Component)", "GUI");
public static LoggerContext MODELMAPPER_DETAILLED =
new LoggerContext(
"Modelmapper Detailled Logging Information",
"ModelMapperDetailed");
private boolean debug = true;
public boolean getDebug()
{
return debug;
}
public void setDebug(boolean debug)
{
//this.debug = debug;
}
// disabling / enabling contexts
HashSet<LoggerContext> disabledLoggers = new HashSet<LoggerContext>();
public boolean isLoggerContextDisabled(LoggerContext context)
{
return disabledLoggers.contains(context);
}
public void enableLoggerContext(LoggerContext context)
{
disabledLoggers.remove(context);
}
public void disableLoggerContext(LoggerContext context)
{
//disabledLoggers.add(context);
}
/**
* @param context
*
*/
private void logContext(LoggerContext context)
{
if(getGlobalCurrentContext() != context)
{
if(defaultContext == null)
{
setIndent(indent = " ");
}
else
{
setIndent("");
log(" o ");// + getCurrentContext().getLongName() + " ");
}
if(context != null)
{
setIndent(indent = "");
log("");
log("-+ <<< " + context.getLongName() + " >>>");
//System.out.println("");
//setCurrentContext(context);
setGlobalCurrentContext(context);
setIndent(indent = " |- ");
setAdditionalLineIndent(" | ");
}
}
else
{
;
}
}
/* Global Properties */
private static LoggerContext globalCurrentContext = null;
public static LoggerContext getGlobalCurrentContext()
{
return globalCurrentContext;
}
public static void setGlobalCurrentContext(LoggerContext globalCurrentContext)
{
MultiContextLogger.globalCurrentContext = globalCurrentContext;
}
/* Logger Properties */
private LoggerContext defaultContext = null;
public LoggerContext getDefaultContext()
{
return defaultContext;
}
// public void setCurrentContext(LoggerContext currentContext)
// {
// this.defaultContext = currentContext;
// }
//Set<LoggerContext> loggerContexts = new HashSet<LoggerContext>();
/* standard logging */
public void log(int type, LoggerContext context, String message)
{
// if(context != null && !isLoggerContextDisabled(context))
// {
logContext(context);
//
super.log(type, message);
// }
//
// else
// ;
}
public void log(int type, String message)
{
logContext(getDefaultContext());
super.log(type, message);
}
// public void log(String message)
// {
// logContext(getCurrentContext());
// super.log(message);
// }
public void info(String message)
{
//For release, just log warnings and errors, not informational messages.
log(2,message);
}
public void warn(String message)
{
log(1,message);
}
public void error(String message)
{
log(0,message);
}
/* special debug logging */
/** standard logging action when an Exception occurred
* (to call from 'catch' or 'finally' blocks)
*/
public void logException(Exception e)
{
//if(debug)
{
try
{
e.printStackTrace();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
/** log Method to call from unimplemented Methods
* (currently used from unimplemented Methods
* in my Implementations of the JMI Interfaces)
*/
public void logUnimplemented()
{
try
{
throw new NotImplementedException();
}
catch (Exception e)
{
logException(e);
}
}
public void logUnimplemented(LoggerContext context)
{
if(context != null && !isLoggerContextDisabled(context))
{
try
{
throw new NotImplementedException();
}
catch (Exception e)
{
log(ERROR, MY_JMI_IMPL, e.getStackTrace().toString());
}
}
else
;
}
public void logCallstack()
{
try
{
throw new Exception();
}
catch (Exception e)
{
logException(e);
}
}
/* shortcuts */
public void info(LoggerContext context, String message)
{
if(context != null && !isLoggerContextDisabled(context))
{
//logContext(context);
// log(INFORMATIONAL, context, message);
}
}
public void warn(LoggerContext context, String message)
{
if(context != null && !isLoggerContextDisabled(context))
{
//logContext(context);
log(WARNING, context, message);
}
}
public void error(LoggerContext context, String message)
{
if(context != null && !isLoggerContextDisabled(context))
{
// logContext(context);
log(ERROR, context, message);
}
}
}

View File

@ -0,0 +1,309 @@
package ch.ethz.infsec.secureumlgui.logging;
import java.util.ArrayList;
public class SimpleLogger implements SimpleMessageSink
{
public SimpleLogger()
{
;
}
/* Types */
public static final int ERROR = 0;
public static final int WARNING = 1;
public static final int INFORMATIONAL = 2;
/* Logger Properties */
protected boolean verbose = true;
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
public boolean isVerbose() {
return verbose;
}
private int maxCharactersPerLine = 78;
public int getMaxCharactersPerLine()
{
return maxCharactersPerLine;
}
//@require maxCharactersPerLine>10
public void setMaxCharactersPerLine(int maxCharactersPerLine)
{
this.maxCharactersPerLine = maxCharactersPerLine;
}
protected String indent = " ";
protected String additionalLineIndent = " ";
public String getAdditionalLineIndent()
{
return additionalLineIndent;
}
public void setAdditionalLineIndent(String additionalLineIndent)
{
this.additionalLineIndent = additionalLineIndent;
if(additionalLineIndent == null)
additionalLineIndent = "";
}
public String getIndent()
{
return indent;
}
public void setIndent(String indent)
{
this.indent = indent;
if(indent == null)
this.indent = "";
}
/* standard logging */
protected void log(String message)
{
try
{
printString(message);
//System.out.println(message);
}
catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
}
}
public void log(int type, String message)
{
String out_message = "";
try
{
switch (type) {
case 0:
out_message += "[ERROR] " + message;
break;
case 1:
out_message += "[WARN] " + message;
break;
case 2:
out_message += "[INFO] " + message;
break;
}
}
catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
}
log(out_message);
}
// public void printString(String s)
// {
// try
// {
// if(s!=null)
// {
//
//
// if(s.length() <= maxCharactersPerLine)
// {
// System.out.println(indent + s);
// }
// else
// {
//
// while(s.length() > maxCharactersPerLine)
// {
// System.out.println(additionalLineIndent + s.substring(0, maxCharactersPerLine));
// s = s.substring(maxCharactersPerLine);
// }
//
// System.out.println(additionalLineIndent + s);
// }
//
// }
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// advanced multiline support
public void printString(String s)
{
if(maxCharactersPerLine < 1)
return;
try
{
if(s!=null)
{
String[] lines = s.split("\n");
//if(lines.length > 1)
//System.out.println("@@@@@ logging " + lines.length + " lines");
String firstline = lines[0];
int startindex = 0;
// print first line - with original indent
if(firstline.length() <= maxCharactersPerLine)
{
System.out.println(indent + firstline);
startindex = 1;
}
else
{
System.out.println(indent + firstline.substring(0, maxCharactersPerLine));
lines[0] = firstline.substring(maxCharactersPerLine);
startindex = 0;
}
// print other lines with empty indent
// one longer than the orignial indent
for (int i = startindex; i < lines.length; i++)
{
String line = lines[i];
while(line.length() > maxCharactersPerLine)
{
System.out.println(additionalLineIndent + line.substring(0, maxCharactersPerLine));
line = line.substring(maxCharactersPerLine);
}
System.out.println(additionalLineIndent + line);
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
// advanced multiline support
// public void printString(String s)
// {
// try
// {
// if(s!=null)
// {
// System.out.println(s);
// ArrayList<String> lines = split(s, '\n');
// lines = split(s, '\r');
//
// if(lines.size() > 1)
// System.out.println("@@@@@ logging " + lines.size() + " lines");
//
// String firstline = lines.get(0);
// // print first line - with original indent
// if(firstline.length() <= maxCharactersPerLine)
// {
// System.out.println(indent + firstline);
// }
// else
// {
// System.out.println(indent + s.substring(0, maxCharactersPerLine));
// firstline = firstline.substring(maxCharactersPerLine);
//
// lines.set(0, firstline);
// // print other lines with empty indent
// // one longer than the orignial indent
// for (int i = 0; i < lines.size(); i++)
// {
// String line = lines.get(i);
// while(line.length() > maxCharactersPerLine)
// {
// System.out.println(additionalLineIndent + line.substring(0, maxCharactersPerLine));
// line = line.substring(maxCharactersPerLine);
// }
//
// System.out.println(additionalLineIndent + line);
// }
// }
// }
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
/* shortcuts */
public void info(String s) {
if (verbose)
{
log(INFORMATIONAL, s);
}
}
public void warning(String s) {
log(WARNING, s);
}
public void error(String s) {
log(ERROR, s);
}
public void error(Exception e) {
log(ERROR, e.toString());
try
{
e.printStackTrace();
}
catch (Exception ex)
{
// TODO: handle exception
ex.printStackTrace();
}
}
public ArrayList<String> split(String s, Character c)
{
ArrayList<String> lines = new ArrayList<String>();
while(s.length() > 1 && s.indexOf(c)>=0)
{
if(s.indexOf(c) == 0)
{
s = s.substring(1);
}
else
{
String line = s.substring(0, s.indexOf(c));
lines.add(line);
s = s.substring(s.indexOf(c));
}
}
lines.add(s);
return lines;
}
/* simplemessagesink */
public void processMessage(String s) {
info(s);
}
}

View File

@ -0,0 +1,7 @@
package ch.ethz.infsec.secureumlgui.logging;
public interface SimpleMessageSink
{
void processMessage(String arg);
}

View File

@ -0,0 +1,44 @@
package ch.ethz.infsec.secureumlgui.main;
//import org.argouml.uml.reveng.ImportClassLoader;
import org.netbeans.mdr.handlers.ClassLoaderProvider;
import ch.ethz.infsec.secureumlgui.securemodel.SecureModelPackage;
//import ch.ethz.infsec.secureumlgui.securemodelimpl.SecureModelFactory;
import ch.ethz.infsec.secureumlgui.logging.MultiContextLogger;
import org.argouml.application.Main;
public class ClassLoaderProviderImpl implements ClassLoaderProvider
{
private MultiContextLogger logger = new MultiContextLogger(
MultiContextLogger.STARTUP);
public ClassLoaderProviderImpl() {
super();
logger.info("ClassLoaderProviderImpl constructed");
}
public ClassLoader getClassLoader()
{
//return ImportClassLoader.getSystemClassLoader();
logger.info("*** ClassLoaderProvider invoked - returned Classlodader: "
+ Main.class.getClassLoader());
return Main.class.getClassLoader();
}
public Class defineClass(String className, byte[] classFile)
{
//return this.getClassLoader().defineClass(className, classFile, 0, classFile.length);
// TODO Auto-generated method stub
logger.info("*** defineClass called!");
//return this.getClassLoader().defineClass(arg0, arg1, 0, arg0.length());
return null;
}
}

View File

@ -0,0 +1,84 @@
package ch.ethz.infsec.secureumlgui.main;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import ch.ethz.infsec.secureumlgui.logging.MultiContextLogger;
public class FileLoader {
private static MultiContextLogger logger = new MultiContextLogger();
public static File loadXmiFromArgoFile(String inputFile) {
try {
// load the .argo file
File argoFile = loadFile(inputFile);
// extract the xmi file
String argoName = argoFile.getName();
String baseName = argoName.substring(0, argoName.indexOf("."));
File temp = File.createTempFile(baseName, ".xmi");
temp.deleteOnExit();
ZipFile argoZipFile = new ZipFile(argoFile);
ZipEntry xmiFile = argoZipFile.getEntry(baseName + ".xmi");
if (xmiFile != null) {
argoZipFile.getInputStream(xmiFile);
copyInputStream(argoZipFile.getInputStream(argoZipFile
.getEntry(baseName + ".xmi")),
new BufferedOutputStream(new FileOutputStream(temp)));
argoZipFile.close();
return temp;
}
logger
.error("invalid argo file, does not contain a xmi file named "
+ baseName + ".xmi");
return null;
} catch (IOException ioe) {
System.err.println("Unhandled exception:");
ioe.printStackTrace();
}
return null;
}
public static File loadFile(String fileName) {
if (fileName == null || fileName.equals("")) {
return null;
}
try {
File file = new File(fileName);
return file;
} catch (Exception e) {
logger.error("could not load " + fileName);
return null;
}
}
public static File createFile(String fileName) {
try {
File file = loadFile(fileName);
file.createNewFile();
return file;
} catch (Exception e) {
logger.error("could not load " + fileName);
return null;
}
}
private static void copyInputStream(InputStream in, OutputStream out)
throws IOException {
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) >= 0)
out.write(buffer, 0, len);
in.close();
out.close();
}
}

View File

@ -0,0 +1,193 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.main;
import org.omg.uml.foundation.core.Classifier;
import ch.ethz.infsec.secureumlgui.logging.MultiContextLogger;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.ResourceType;
/**
*
* SecureUml-related Constants used by several Classes
*/
public class SecureUmlConstants
{
// public static final String STEREOTYPE_COMPUML_ENTITY = "compuml.entity";
public static final String BASE_CLASS = "Class";
public static final String BASE_ASSOCCLASS = "AssociationClass";
public static enum SECUML_STEREOTYPES {
STEREOTYPE_SECUML_USER ( "secuml.user", BASE_CLASS ),
STEREOTYPE_SECUML_ROLE ( "secuml.role", BASE_CLASS),
STEREOTYPE_SECUML_RESOURCE ( "secuml.resource", null ),
STEREOTYPE_SECUML_ACTIONTYPE ( "secuml.actiontype", null ),
STEREOTYPE_SECUML_PERMISSION ( "secuml.permission", BASE_ASSOCCLASS ),
STEREOTYPE_SECUML_CONSTRAINT ( "secuml.constraint", null ),
STEREOTYPE_SECUML_POLICY ( "secuml.policy", BASE_CLASS );
private String value;
private String base;
SECUML_STEREOTYPES ( String value, String baseClass) {
this.value = value;
this.base = baseClass;
}
public String toString() {
return value;
}
public String getBase() {
return base;
}
}
public static enum UML_OCL {
OCL_ANY ("OclAny", new UML_OCL[] {}),
// OCL_TYPE ("OclType", new UML_OCL[] {OCL_ANY}),
// OCL_STATE ("OclState", new UML_OCL[] {OCL_ANY}),
// OCL_MODELELEMENT ("OclModelElement", new UML_OCL[] {OCL_ANY}),
OCL_BOOLEAN ("Boolean", new UML_OCL[] {OCL_ANY}),
OCL_REAL ("Real", new UML_OCL[] {OCL_ANY}),
OCL_STRING ("String", new UML_OCL[] {OCL_ANY}),
OCL_INTEGER ("Integer", new UML_OCL[] {OCL_REAL}),
// OCL_VOID ("OclVoid", new UML_OCL[] {OCL_TYPE, OCL_STATE, OCL_MODELELEMENT,
// OCL_BOOLEAN, OCL_INTEGER, OCL_STRING});
OCL_VOID ("OclVoid", new UML_OCL[] {OCL_BOOLEAN, OCL_INTEGER, OCL_STRING});
private String value;
private UML_OCL superTypes[];
UML_OCL (String value, UML_OCL superTypes[]) {
this.value = value;
this.superTypes = superTypes;
}
public String toString() {
return this.value;
}
public UML_OCL[] getSuperTypes() {
return this.superTypes;
}
}
public static final String STEREOTYPE_SECUML_PERMISSION = SECUML_STEREOTYPES.STEREOTYPE_SECUML_PERMISSION.toString();
//public static final String STEREOTYPE_SECUML_EXCP_PERMISSION = "secuml.excppermission";
public static final String STEREOTYPE_SECUML_POLICY = SECUML_STEREOTYPES.STEREOTYPE_SECUML_POLICY.toString();
public static final String STEREOTYPE_SECUML_ROLE = SECUML_STEREOTYPES.STEREOTYPE_SECUML_ROLE.toString();
public static final String STEREOTYPE_SECUML_ACTIONTYPE = SECUML_STEREOTYPES.STEREOTYPE_SECUML_ACTIONTYPE.toString();
// public static final String STEREOTYPE_ENTITY_ATTRIBUTE_ACTION = "dialect.entityattributeaction";
//
// public static final String STEREOTYPE_ENTITY_ACTION = "dialect.entityaction";
//
// public static final String STEREOTYPE_ENTITY_OPERATION_ACTION = "dialect.entityoperationaction";
public static final String STEREOTYPE_SECUML_CONSTRAINT = SECUML_STEREOTYPES.STEREOTYPE_SECUML_CONSTRAINT.toString();
public static final String STEREOTYPE_SECUML_RESOURCE = SECUML_STEREOTYPES.STEREOTYPE_SECUML_RESOURCE.toString();
public static final String STEREOTYPE_SECUML_USER = SECUML_STEREOTYPES.STEREOTYPE_SECUML_USER.toString();
public static final String STEREOTYPE_OCL_TYPE = "ocltype";
public static final String TAG_DEFINITION_AUTHORIZATION_CONSTRAINT = "authorizationConstraint";
private static ResourceType permissionResourceTypeDummy;
//private static ResourceType excpPermissionResourceTypeDummy;
private static ResourceType roleResourceTypeDummy;
//private static ResourceType excpLevelResourceTypeDummy;
private static ResourceType policyResourceTypeDummy;
public static final String NEW_PERMISSION_SUFFIX = "Perm";
//public static final String AuthorizationConstraintTagName = "AuthorizationConstraint";
public static final String UML_CLASS = "UmlClass";
public static final String UML_ASSOCIATION = "AssociationClass";
public static final String ROLE_NAME = "Role";
public static final String ROLE_CLASSNAME = UML_CLASS;
public static final String POLICY_NAME = "Policy";
public static final String POLICY_CLASSNAME = UML_CLASS;
public static final String DEFAULT_POLICY_NAME = "DefaultPolicy";
public static final String POLICY_INHERITANCE_REFINEDBY = "refinedBy";
public static final String POLICY_INHERITANCE_REFINES = "refines";
public static final String PERMISSION_NAME = "Permission";
public static final String PERMISSION_CLASSNAME = UML_ASSOCIATION;
public static final String PACKAGE_SECUML = "secUML";
public static final String PACKAGE_PERMISSIONS = "permissions";
public static final String PACKAGE_OCL ="UML_OCL";
/**
* @return the permissionResourceTypeDummy
*/
public static ResourceType getPermissionResourceTypeDummy()
{
if(permissionResourceTypeDummy == null)
{
permissionResourceTypeDummy = new ResourceType();
permissionResourceTypeDummy.setName(PERMISSION_NAME);
permissionResourceTypeDummy.setUmlClassName(PERMISSION_CLASSNAME);
permissionResourceTypeDummy.setModelElementStereotype(
SecureUmlConstants.STEREOTYPE_SECUML_PERMISSION);
}
return permissionResourceTypeDummy;
}
public static ResourceType getPolicyResourceTypeDummy() {
if ( policyResourceTypeDummy == null ) {
policyResourceTypeDummy = new ResourceType();
policyResourceTypeDummy.setName(POLICY_NAME);
policyResourceTypeDummy.setUmlClassName(POLICY_CLASSNAME);
policyResourceTypeDummy.setModelElementStereotype(STEREOTYPE_SECUML_POLICY);
}
return policyResourceTypeDummy;
}
public static ResourceType getRoleResourceTypeDummy()
{
if(roleResourceTypeDummy == null)
{
roleResourceTypeDummy = new ResourceType();
roleResourceTypeDummy.setName(ROLE_NAME);
roleResourceTypeDummy.setUmlClassName(ROLE_CLASSNAME);
roleResourceTypeDummy.setModelElementStereotype(
SecureUmlConstants.STEREOTYPE_SECUML_ROLE);
//roleResourceTypeDummy.setAnchorPath("self");
}
return roleResourceTypeDummy;
}
}

View File

@ -0,0 +1,36 @@
package ch.ethz.infsec.secureumlgui.modelmanagement;
public class ExtentInfo {
private final String name;
private final String topPackage;
private final Class type;
private final String metamodelName;
public ExtentInfo(String name, String topPackage, String metamodelName, Class type) {
this.name = name;
this.topPackage = topPackage;
this.type = type;
this.metamodelName = metamodelName;
}
public String getName() {
return name;
}
public String getTopPackage() {
return topPackage;
}
public Class getType() {
return type;
}
public String getMetaModelName() {
return metamodelName;
}
}

View File

@ -0,0 +1,68 @@
package ch.ethz.infsec.secureumlgui.modelmanagement;
import ch.ethz.infsec.secureumlgui.main.SecureUmlConstants;
import ch.ethz.infsec.secureumlgui.modelmanagement.OclModelInfo.MetaModelName;
import ch.ethz.infsec.secureumlgui.securemodel.SecureModelPackage;
public class ModelConst {
// note: xmi files must be given as absolute path vs. ocl files must be
// given as URI
private static final String BASE = System.getProperty("user.dir");
private static final String URI_BASE = "file:" + BASE;
public static final OclModelInfo seccompuml;
public static final ExtentInfo secureuml_componentuml_extent;
static {
// metamodel extents
secureuml_componentuml_extent = new ExtentInfo(
"securityModel"/* name */, "SecureModel"/* packagename */,
"su2holocl_metamodel"/* metamodel */, SecureModelPackage.class/* type */);
// secureuml/componentuml metamodel
seccompuml = new OclModelInfo(URI_BASE
+ "/metamodels/securecomponentuml/securecomponentuml_mof.xmi",
BASE + "/metamodels/securecomponentuml/securecomponentuml.ocl",
"securecomponentuml", MetaModelName.MOF14);
}
public static final String SECUREUML_TYPES_PACKAGE = "UML_OCL";
public static final String ENVIRONMENTPACKAGE_NAME = "AuthorizationEnvironment";
// additional
public static final String SECUREUML_PACKAGE_NAME = "SecureUML";
public static final String SECUREMODEL_PACKAGE_NAME = "SecureModel";
public static final String SECUREMODEL_EXTENT_NAME = "SecureModel";
public static final String SECUREMODEL_INSTANCE_NAME = "mySecureModel";
public static final String DIALECT_PACKAGE_NAME_PART = "dialect";
public static final String DIALECT_PACKAGE_SUFFIX = "Dialect";
public static final String SECUREUML_RESOURCE_NAME = "Resource";
public static final String SECUREUML_ACTION_NAME = "ActionClass";
public static final String SECUREUML_ATOMIC_ACTION_NAME = "AtomicAction";
public static final String SECUREUML_COMPOSITE_ACTION_NAME = "CompositeAction";
@Deprecated
public static final String STEREOTYPE_SECUML_ACTIONTYPE = SecureUmlConstants.STEREOTYPE_SECUML_ACTIONTYPE; //"secuml.actiontype";
@Deprecated
public static final String STEREOTYPE_SECUML_ROLE = SecureUmlConstants.STEREOTYPE_SECUML_ROLE;
@Deprecated
public static final String STEREOTYPE_SECUML_PERMISSION = SecureUmlConstants.STEREOTYPE_SECUML_PERMISSION;
public static String getDialectPackageName(String dialectName)
{
return dialectName + DIALECT_PACKAGE_SUFFIX;
}
public static final String ACTION_RESOURCE_ASSOCIATION_NAME = "actionResource";
}

View File

@ -0,0 +1,50 @@
package ch.ethz.infsec.secureumlgui.modelmanagement;
public class OclModelInfo {
public static enum MetaModelName {
UML15, MOF14
}
private final String xmi;
private final String name;
private MetaModelName metaModelName;
private String oclUri;
public OclModelInfo(String xmi, String oclUri, String name, MetaModelName metaModelName) {
this.xmi = xmi;
this.name = name;
this.metaModelName = metaModelName;
this.oclUri = oclUri;
}
public String getName() {
return name;
}
public String getXmi() {
return xmi;
}
public MetaModelName getMetaModelName() {
return metaModelName;
}
public String getMetaModelNameString() {
switch (metaModelName) {
case MOF14:
return "MOF14";
case UML15:
return "UML15";
}
return null;
}
public String getOclUri() {
return oclUri;
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,70 @@
package ch.ethz.infsec.secureumlgui.modelmapping;
import javax.jmi.reflect.RefPackage;
// import tudresden.ocl20.core.jmi.uml15.core.Association;
// import tudresden.ocl20.core.jmi.uml15.core.Generalization;
// import tudresden.ocl20.core.jmi.uml15.core.UmlAssociationClass;
// import tudresden.ocl20.core.jmi.uml15.core.UmlClass;
import org.omg.uml.foundation.core.UmlClass;
import org.omg.uml.foundation.core.Generalization;
import org.omg.uml.foundation.core.UmlAssociation;
import org.omg.uml.foundation.core.UmlAssociationClass;
import ch.ethz.infsec.secureumlgui.logging.MultiContextLogger;
import ch.ethz.infsec.secureumlgui.transformation.ModelMap;
/**
* Base class that doesn't do much. The real functionality is in the subclasses.
*
* @version 1.0
*/
public class ModelMapper
{
public ModelMapper()
{
}
public void init()
{
map.clear();
}
protected static MultiContextLogger logger = new MultiContextLogger(MultiContextLogger.MODELMAPPER);
protected ModelMap map = ModelMap.getDefault();
@SuppressWarnings("unchecked")
public void transform()
{
// empty
}
protected void examineUmlClass(UmlClass umlClass)
{
// empty
}
protected void examineUmlGeneralization(Generalization generalization)
{
// empty
}
protected void examineUmlAssociationClass(
UmlAssociationClass associationClass)
{
// empty
}
protected void examineUmlAssociation(UmlAssociation assoc)
{
// empty
}
public ModelMap getModelMap()
{
return map;
}
}

View File

@ -0,0 +1,860 @@
package ch.ethz.infsec.secureumlgui.modelmapping;
import java.security.InvalidParameterException;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.jmi.model.Association;
import javax.jmi.reflect.RefObject;
import org.apache.log4j.Logger;
import org.argouml.kernel.Project;
import org.argouml.kernel.ProjectManager;
import org.argouml.model.CoreFactory;
import org.argouml.model.CoreHelper;
import org.argouml.model.Facade;
import org.argouml.model.Model;
import org.omg.uml.foundation.core.AssociationClass;
import org.omg.uml.foundation.core.AssociationEnd;
import org.omg.uml.foundation.core.Attribute;
import org.omg.uml.foundation.core.Classifier;
import org.omg.uml.foundation.core.ModelElement;
import org.omg.uml.foundation.core.Namespace;
import org.omg.uml.foundation.core.Operation;
import org.omg.uml.foundation.core.Stereotype;
import org.omg.uml.foundation.core.UmlAssociation;
import org.omg.uml.foundation.core.UmlClass;
import org.omg.uml.modelmanagement.UmlPackage;
//import java.lang.String;
import ch.ethz.infsec.secureumlgui.Util;
import ch.ethz.infsec.secureumlgui.logging.MultiContextLogger;
import ch.ethz.infsec.secureumlgui.main.SecureUmlConstants;
import ch.ethz.infsec.secureumlgui.modelmanagement.ModelConst;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.ActionType;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.MetaModelConst;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.ResourceType;
import ch.ethz.infsec.secureumlgui.transformation.ModelMap;
import ch.ethz.infsec.secureumlgui.util.PermissionDummy;
import ch.ethz.infsec.secureumlgui.wrapper.ActionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.NamedModelElementWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.PermissionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.PolicyWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.ResourceWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.RoleWrapper;
/**
* Writes SecureUml Model Elements to UML Model.
*
* Only elements for which a mapping is contained in modelmap can be written
*
*
*/
public class ModelWriter {
public ModelWriter(ModelMap modelmap) {
this.modelmap = modelmap;
}
ModelMap modelmap;
GenericDialectHelper helper = GenericDialectHelper.getInstance();
private Logger aLog = Logger.getLogger(ModelWriter.class);
private int hack_count = 0;
/**
* ModelMap containing (both-sided) Mapping between UML Model Elements and
* SecureUml Entities.
*
*/
public ModelMap getModelmap() {
return modelmap;
}
MultiContextLogger logger = MultiContextLogger.getDefault();
public void createPermission(Object resourceUml, Object roleUml,
ActionWrapper actionWrapper, Set<PolicyWrapper> policies) {
String name = helper.getResourcePath((ModelElement) resourceUml);
createPermission(resourceUml, roleUml, name, actionWrapper, policies);
}
public void createPermission(ResourceWrapper resourceWrapper,
RoleWrapper roleWrapper, ActionWrapper actionWrapper, Set<PolicyWrapper> policies) {
Object secUmlModelElement = resourceWrapper.getModelElement();
ModelElement resourceUml = (ModelElement) getModelmap().getUmlElement(
secUmlModelElement);
String permissionAttributeName = getPermissionAttributeName(resourceUml);
createPermission(resourceWrapper, roleWrapper, permissionAttributeName,
actionWrapper, policies);
}
protected void createPermission(Object resourceUml, Object roleUml,
String permissionAttributeName, ActionWrapper actionWrapper, Set<PolicyWrapper> policies) {
Classifier anchor = helper.findAnchor((ModelElement) resourceUml);
createPermissionViaModelCore(permissionAttributeName, resourceUml,
(Classifier) anchor, (Classifier) roleUml, actionWrapper, policies);
}
//XXX
// protected void createPermission(ResourceWrapper resourceWrapper,
// RoleWrapper roleWrapper, String permissionAttributeName,
// ActionWrapper actionWrapper) {
// try {
// logger.info(logger.MODELWRITER, "creating Permission: \n"
// + " resourceWrapper: " + resourceWrapper.getName() + "\n"
// + " roleWrapper: " + roleWrapper.getName() + "\n"
// + " actionWrapper: " + actionWrapper.getName());
//
// RefObject resourceUml = getModelmap().getUmlElement(
// resourceWrapper.getModelElement());
//
// Classifier anchor = helper.findAnchor((ModelElement) resourceUml);
//
// Classifier roleClassifier = (Classifier) getModelmap()
// .getUmlElement(roleWrapper.getModelElement());
//
// createPermissionViaModelCore(permissionAttributeName, resourceUml,
// anchor, roleClassifier, actionWrapper);
// } catch (Exception e) {
// logger.logException(e);
// }
// }
protected void createPermission(ResourceWrapper resourceWrapper,
RoleWrapper roleWrapper, String permissionAttributeName,
ActionWrapper actionWrapper, Set<PolicyWrapper> policies) {
try {
logger.info(logger.MODELWRITER, "creating Permission: \n"
+ " resourceWrapper: " + resourceWrapper.getName() + "\n"
+ " roleWrapper: " + roleWrapper.getName() + "\n"
+ " actionWrapper: " + actionWrapper.getName());
RefObject resourceUml = getModelmap().getUmlElement(
resourceWrapper.getModelElement());
Classifier anchor = helper.findAnchor((ModelElement) resourceUml);
Classifier roleClassifier = (Classifier) getModelmap()
.getUmlElement(roleWrapper.getModelElement());
//Classifier policyClassifier = (Classifier) getModelmap().getUmlElement(policyWrapper.getModelElement());
createPermissionViaModelCore(permissionAttributeName, resourceUml,
anchor, roleClassifier, actionWrapper, policies);
} catch (Exception e) {
logger.logException(e);
}
}
/**
* @param anchor
* @param roleClass
* @param actionWrapper
*/
protected void createPermissionViaModelCore(String permissionName,
Object resourceUml, Classifier anchor, Classifier roleClass,
ActionWrapper actionWrapper, Set<PolicyWrapper> policies) {
try {
// check if Association class
// with same Name already exists!
String newPermissionName = permissionName
+ Util.getNewPermissionNumber();
Collection classifiers = null;
boolean isNameAlreadyUsed = false;
do {
isNameAlreadyUsed = false;
if (classifiers != null) {
for (Iterator iter = classifiers.iterator(); iter.hasNext();) {
Classifier classifier = (Classifier) iter.next();
if (classifier.getName().equalsIgnoreCase(
newPermissionName)) {
isNameAlreadyUsed = true;
logger.info(logger.MODELWRITER,
"AssociationClass with Name "
+ newPermissionName
+ " already exists -> "
+ "incrementing sequence Number");
newPermissionName = permissionName
+ Util.getNewPermissionNumber();
break;
}
}
}
} while (isNameAlreadyUsed);
AssociationClass newUmlPermission = (AssociationClass) Model
.getCoreFactory().buildAssociationClass(anchor, roleClass);
logger.info("Permission AssociationClass created: "
+ newUmlPermission.getName());
UmlPackage permissionPackage = GenericDialectModelMapper.getInstance().getPermissionPackage();
newUmlPermission.setName(newPermissionName);
newUmlPermission.setNamespace(permissionPackage); // TODO
// hel put permission in sub namespace
newUmlPermission.setActive(true);
Stereotype stereotype = null;// Util.findStereotypeByName(newUmlPermission,
// SecureUmlConstants.STEREOTYPE_SECUML_PERMISSION);
// TODO;
// Util.findStereotypeByName(newUmlPermission,
// SecureUmlConstants.STEREOTYPE_SECUML_PERMISSION);
stereotype = getOrCreateStereotype(newUmlPermission,
SecureUmlConstants.STEREOTYPE_SECUML_PERMISSION,
newUmlPermission.getNamespace());
// modelmap.getStereotype(SecureUmlConstants.STEREOTYPE_SECUML_PERMISSION);
newUmlPermission.getStereotype().add(stereotype);
String permissionAttributeName = getPermissionAttributeName((ModelElement) resourceUml);
String actionShortname = actionWrapper.getName();
Classifier actionType = getOrCreateActionType(actionShortname,
newUmlPermission.getNamespace());
// TODO: examine the Type
// String attributeName = helper.getResourcePath(
// (ModelElement)resourceUml);
Attribute permissionAttribute = (Attribute) addAttribute(
newUmlPermission, "foobar", actionType);
permissionAttribute.setName(permissionAttributeName);
permissionAttribute.setType(actionType);
// TODO: examine Stereotype
String stereotypeName = getActionStereotype(resourceUml);
stereotype = getOrCreateStereotype(permissionAttribute,
stereotypeName, newUmlPermission.getNamespace());
if (stereotype != null)
permissionAttribute.getStereotype().add(stereotype);
if (policies != null || policies.size() == 0 ) {
if (policies.size() != 1) {
aLog.error("All policies than the first are ignored.... TODO!");
}
PolicyWrapper policyWrapper = policies.iterator().next();
Classifier policy = (Classifier) getModelmap().getUmlElement(policyWrapper.getModelElement());
// UmlAssociation perm_pol = (UmlAssociation) Model.getCoreFactory().buildAssociation(
// newUmlPermission, true, policy, true, "permission_policy_" + ++hack_count);
UmlAssociation perm_pol = (UmlAssociation) Model.getCoreFactory().buildAssociation(
newUmlPermission, true, policy, true, policyWrapper.getName() + "_permission_" + ++hack_count);
perm_pol.setNamespace(permissionPackage);
// System.out.println("assoc connection count: " +perm_pol.getConnection().size());
//
// Object assE1 = Model.getCoreFactory().buildAssociationEnd(newUmlPermission, perm_pol);
// System.out.println("XX1: " + assE1.getClass().toString());
//
//
// Object assE2 = Model.getCoreFactory().buildAssociationEnd(policy, perm_pol);
// System.out.println("XX2: " + assE2.getClass().toString());
//
// System.out.println("assoc connection count: " +perm_pol.getConnection().size());
logger.info("added association to policy " + policyWrapper.getName() + " result: " + perm_pol.getClass().toString());
aLog.debug("added association to policy " + policyWrapper.getName() + " result: " + perm_pol.getClass().toString());
// System.out.println(perm_pol + " ## " + newUmlPermission);
// AssociationEnd newAss = (AssociationEnd) Model.getCoreFactory().buildAssociationEnd(perm_pol, newUmlPermission );
CoreFactory coreFact = Model.getCoreFactory();
List<AssociationEnd> newEnds = perm_pol.getConnection();
try {
for (AssociationEnd end : newEnds ) {
if (end.getParticipant().equals(newUmlPermission)) {
aLog.debug("found association end: " + end + "\nnavigateable: " + end.isNavigable() + " " + end.getAggregation());
//newUmlPermission.getConnection().add(end);
}
else {
aLog.debug("not the right end... " + end.getParticipant());
}
}
} catch(Exception e) {
aLog.error("Error at adding association end: ", e);
e.printStackTrace();
}
// try {
//
// AssociationEnd newAss = (AssociationEnd) coreFact.buildAssociationEnd(newUmlPermission.getConnection().get(0).getParticipant(), perm_pol);
// //AssociationEnd newAss = (AssociationEnd) coreFact.buildAssociationEnd(newUmlPermission, perm_pol);
// //AssociationEnd newAss = (AssociationEnd) coreFact.buildAssociationEnd(policy, perm_pol);
// //newUmlPermission.get
// aLog.debug("Created AssociationEnd: " + newAss);
// aLog.debug("getParticipant: " + newAss.getParticipant());
//
// newUmlPermission.getConnection().add(newAss);
// aLog.debug("Added AssociationEnd to new permission");
//
// //newUmlPermission.getConnection().
// //perm_pol.getConnection().add(newAss);
//
// } catch (Exception e) {
// aLog.error("Could not create/add AssociationEnd: " + e.getClass() + ": " + e.getMessage());
// System.out.println("####################################################");
// e.printStackTrace();
//
// aLog.error(e);
// }
// AssociationEnd newAss = (AssociationEnd) Model.getCoreFactory().buildAssociationEnd(
// perm_pol,
// "assEnd_" + ++hack_count2,
// newUmlPermission,
//
//
//
//
// assoc - The associaton this end will be part of
// name - The name of the association end
// type - The type (classifier) the end will connect. The end is a connection piece between an association and a classifier
// multi - The multiplicity
// stereo - The stereotype
// navigable - The navigability. True if this association end can be 'passed' from the other classifier.
// order - Ordering of the association
// aggregation - the aggregationkind
// scope - the scope kind
// changeable - the changeablekind
// visibility - the visibilitykind
// newUmlPermission.getConnection().add(newAss);
// for ( AssociationEnd assEnd : perm_pol.getConnection() ) {
// Classifier classf = assEnd.getParticipant();
//
//
// if ( classf != policy ) {
// newUmlPermission.getConnection().add(assEnd);
// }
// //classf.
//
// //AssociationClass (perm_pol) bzw.
// //UmlClass (policy)
//
// //policy.get
//
//
// //aLog.debug(classf + " == " + ( classf == policy ) + " equals " + (classf.equals(policy))+ " ### == " + ( classf == perm_pol ) + " equals " + (classf.equals(perm_pol)));
// }
aLog.debug("PERMISSION:");
for ( AssociationEnd assEnd : newUmlPermission.getConnection() ) {
aLog.debug(" with AssociationEnd " + assEnd);
}
aLog.debug("POLICY: " + policy);
// ModelElement asdf = null;
// asdf.
//UmlClass policyUml = (UmlClass) policy;
// for ( AssociationEnd assEnd : ( (UmlClass) policy)..getOwnedElement()..getConnection() ) {
// aLog.debug(" with AssociationEnd " + assEnd);
// }
}
} catch (Exception e) {
logger.logException(e);
}
}
/**
* @param actionShortname
* @return the action classifier
*/
private Classifier getOrCreateActionType(String actionShortname,
Namespace ns) {
try {
Classifier actionType = modelmap.getActionClass(actionShortname);
if (actionType == null) {
// Namespace secureUmlNs = helper.findNamespaceByName(ns,
// "SecureUML");
Namespace secureUmlNs = GenericDialectModelMapper.getInstance().getSecUMLPackage();
if (secureUmlNs != null)
ns = secureUmlNs;
actionType = (UmlClass) Model.getCoreFactory().createClass();
Stereotype actionTypeStereotype = getOrCreateStereotype(
actionType,
SecureUmlConstants.STEREOTYPE_SECUML_ACTIONTYPE, ns);
actionType.setName(actionShortname);
actionType.setNamespace(ns);
actionType.getStereotype().add(actionTypeStereotype);
}
return actionType;
} catch (Exception e) {
logger.logException(e);
return null;
}
}
/**
* If Stereotype with the passed name exists (-> is stored in the Modelmap),
* return it. Otherwise, create new Stereotype in the Namespace passed as
* Argument
*
* @param name
* @param ns
* @return the stereotype
*/
public Stereotype getOrCreateStereotype(ModelElement modelElementObject,
String name, Namespace ns) {
Stereotype stereotype = modelmap.getStereotype(name);
if (stereotype == null) {
stereotype = (Stereotype) Model.getExtensionMechanismsFactory()
.buildStereotype(modelElementObject, name, ns);
}
return stereotype;
}
public Stereotype getOrCreateStereotype(String name, UmlPackage secUMLPackage, String base) {
Stereotype stereotype = modelmap.getStereotype(name);
if (stereotype == null) {
stereotype = (Stereotype) Model.getExtensionMechanismsFactory().buildStereotype(name, secUMLPackage);
if ( base != null ) {
stereotype.getBaseClass().add(base);
}
//Model.getCoreHelper().setOwner(stereotype, secUMLPackage);
modelmap.putStereotype(stereotype);
}
return stereotype;
}
/**
* @param resourceUml
*/
private String getPermissionAttributeName(ModelElement resourceUml) {
// String resourceName = resourceUml.getName();
try {
String resourcePath = helper.getResourcePath(resourceUml);
return resourcePath;
} catch (Exception e) {
logger.logException(e);
}
return "";
}
private String getActionStereotype(Object resourceUml) {
try {
ModelElement umlModelElement = (ModelElement) resourceUml;
ResourceType rt = helper.getResourceType(umlModelElement);
return rt.getActionStereotype();
} catch (Exception e) {
logger.logException(e);
return null;
}
}
/**
* To add a permission-Attribute to a Permission AssociationClass
*
* copied from org.argouml.ui.targetmanager.ActionWrapperAddAttribute
*
*/
public Object addAttribute(Classifier classifier, String name,
Classifier type) {
Attribute attribute = (Attribute) Model.getCoreFactory()
.createAttribute();
attribute.setName(name);
attribute.setType(type);
classifier.getFeature().add(attribute);
return attribute;
}
/**
* Adds a new Permission with the first ActionWrapper of the permission
* Argument to the underlying Uml Model
*/
public void addPermission(PermissionWrapper permissionWrapper) {
try {
ActionWrapper actionWrapper = permissionWrapper.getActionWrapper();
if (actionWrapper == null) {
logger.error(logger.MODELMAPPER,
"added Permission contains no action "
+ "-> abort adding");
} else {
RoleWrapper roleWrapper = permissionWrapper.getRoleWrapper();
addPermission(actionWrapper, roleWrapper, permissionWrapper.getPolicyWrappers());
}
} catch (Exception e) {
logger.logException(e);
}
}
//XXX
// /**
// * @param actionWrapper
// * @param roleWrapper
// */
// public void addPermission(ActionWrapper actionWrapper,
// RoleWrapper roleWrapper) {
// ResourceWrapper resourceWrapper = actionWrapper.getResourceWrapper();
//
// ModelElement resourceUml = (ModelElement) modelmap
// .getUmlElement(actionWrapper.getResource());
// ModelElement anchorUml = helper.findAnchor(resourceUml);
//
// logger.info("addPermission(anchor: " + anchorUml.getName()
// + ", resource: " + resourceUml.getName() + ", action: "
// + actionWrapper.getName());
//
// Object suAnchor = modelmap.getElement(anchorUml);
// NamedModelElementWrapper anchorWrapper = new NamedModelElementWrapper(
// suAnchor);
//
// String permissionName = "" + roleWrapper.getName()
// // + resourceWrapper.getName()
// // +anchorWrapper.getName()
// + anchorUml.getName()
// // + getNewPermissionSuffix();
// + SecureUmlConstants.NEW_PERMISSION_SUFFIX;
//
// createPermission(resourceWrapper, roleWrapper, permissionName,
// actionWrapper);
// }
/**
* @param actionWrapper
* @param roleWrapper
*/
public void addPermission(ActionWrapper actionWrapper,
RoleWrapper roleWrapper, Set<PolicyWrapper> policies) {
ResourceWrapper resourceWrapper = actionWrapper.getResourceWrapper();
ModelElement resourceUml = (ModelElement) modelmap
.getUmlElement(actionWrapper.getResource());
ModelElement anchorUml = helper.findAnchor(resourceUml);
logger.info("addPermission(anchor: " + anchorUml.getName()
+ ", resource: " + resourceUml.getName() + ", action: "
+ actionWrapper.getName());
Object suAnchor = modelmap.getElement(anchorUml);
NamedModelElementWrapper anchorWrapper = new NamedModelElementWrapper(
suAnchor);
String permissionName = "" + roleWrapper.getName()
// + resourceWrapper.getName()
// +anchorWrapper.getName()
+ anchorUml.getName()
// + getNewPermissionSuffix();
+ SecureUmlConstants.NEW_PERMISSION_SUFFIX;
createPermission(resourceWrapper, roleWrapper, permissionName,
actionWrapper, policies);
}
public void deletePermission(PermissionWrapper permissionWrapper) {
deletePermissionViaModelUml(permissionWrapper);
}
public UmlClass createRole(String roleName, Namespace namespace) {
try {
// check if Class
// with same Name already exists!
String newRoleName = roleName + Util.getNewPermissionNumber();
Collection classifiers = Model.getCoreHelper().getAllClassifiers(
namespace);
boolean isNameAlreadyUsed = false;
do {
isNameAlreadyUsed = false;
for (Iterator iter = classifiers.iterator(); iter.hasNext();) {
Classifier classifier = (Classifier) iter.next();
if (classifier.getName().equalsIgnoreCase(newRoleName)) {
isNameAlreadyUsed = true;
logger.info(logger.MODELWRITER, "Class with Name "
+ newRoleName + " already exists -> "
+ "incrementing sequence Number");
newRoleName = roleName + Util.getNewPermissionNumber();
break;
}
}
} while (isNameAlreadyUsed);
// END - found unique Name for the new role
UmlClass newRole = (UmlClass) Model.getCoreFactory().buildClass(
newRoleName);
Stereotype secumlRole = getOrCreateStereotype(newRole,
SecureUmlConstants.STEREOTYPE_SECUML_ROLE, newRole
.getNamespace());
newRole.getStereotype().add(secumlRole);
newRole.setNamespace(namespace);
newRole.setActive(true);
return newRole;
} catch (Exception e) {
logger.logException(e);
return null;
}
}
public UmlClass createPolicy(String policyName, Namespace namespace) {
// TODO assure that the policy does not exist
aLog.debug("createPolicy: Model.getCoreFactory().buildClass(policyName)");
UmlClass newPolicy = (UmlClass) Model.getCoreFactory().buildClass(
policyName);
aLog.debug("get stereotype");
Stereotype secumlPolicy = getOrCreateStereotype(newPolicy,
SecureUmlConstants.STEREOTYPE_SECUML_POLICY, newPolicy.getNamespace());
newPolicy.getStereotype().add(secumlPolicy);
newPolicy.setNamespace(namespace);
newPolicy.setActive(true);
return newPolicy;
}
public UmlClass createOclType(String name, Set<UmlClass> superTypes) {
UmlClass newOcl = (UmlClass) Model.getCoreFactory().buildClass(name);
Namespace namespace = GenericDialectModelMapper.getInstance().getOclPackage();
newOcl.setNamespace(namespace);
// Stereotype oclType = getOrCreateStereotype(newOcl, SecureUmlConstants.STEREOTYPE_OCL_TYPE, namespace);
// newOcl.getStereotype().add(oclType);
if ( superTypes != null && superTypes.size() > 0 ) {
for ( UmlClass superType : superTypes ) {
Object asdf = Model.getCoreFactory().buildGeneralization(newOcl, superType, superType.getName() + "__" + name);
aLog.debug("build gen. " + asdf.getClass());
}
}
return newOcl;
}
public UmlClass createPolicy(String policyName, Set<PolicyWrapper> refined_by, Namespace namespace) {
// if (refined_by == null || refined_by.size() == 0) {
// throw new InvalidParameterException(
// "refined_by may not be null or empty");
// }
// aLog.debug("start ModelWriter.createPolicy");
// PolicyWrapper asdf = refined_by.iterator().next();
// aLog.debug("XXXX1: " + asdf );
// Namespace namespace = ((UmlClass) modelmap.getUmlElement(asdf.getModelElement())).getNamespace();
// aLog.debug("XXXX2");
UmlClass newPolicy = createPolicy(policyName, namespace);
aLog.debug("buildGeneralizations");
for (PolicyWrapper ref : refined_by) {
aLog.debug(ref.getName());
UmlClass refinedBy_class = (UmlClass) modelmap.getUmlElement(ref
.getModelElement());
Model.getCoreFactory().buildGeneralization(refinedBy_class, newPolicy);
}
return newPolicy;
}
/**
* @param permissionWrapper
*/
private void deletePermissionViaModelUml(PermissionWrapper permissionWrapper) {
try {
/*
* A SecureUmlPermission corresponds to an Attribute of an
* AssociationClass in the Uml Model
*/
RefObject permission = (RefObject) permissionWrapper
.getModelElement();
// logger.info("Deleting Permission " + permission);
Attribute permissionAttribute = (Attribute) modelmap
.getUmlElement(permission);
AssociationClass permissionClass = (AssociationClass) permissionAttribute
.getOwner();
// logger.log(logger.INFORMATIONAL, logger.MODELWRITER,
// "Deleting PermissionAttribute " + permissionAttribute);
// logger.log(logger.INFORMATIONAL, logger.MODELWRITER,
// corresponds to Permission: " + permissionClass + " )");
/*
* delete the attribute (stated like this in the cookbook
*/
// String permissionName =
// permissionAttribute.getName().substring(0);
permissionAttribute.refDelete();
if (permissionClass.getFeature() == null
|| permissionClass.getFeature().size() == 0) {
// logger.log(logger.INFORMATIONAL, logger.MODELWRITER,
// "would delete permission AssociationClass " +
// permissionClass);
permissionClass.refDelete();
}
// logger.log(logger.INFORMATIONAL, logger.MODELWRITER,
// "Permission deleted: " + permissionName);
} catch (Exception e) {
logger.error(logger.MODELWRITER, "deleting Permission failed");
logger.logException(e);
}
}
public void deleteModelElement(Object modelElement) {
Project p = ProjectManager.getManager().getCurrentProject();
p.moveToTrash(modelElement);
}
public void setPermissionName(Object permission, String name) {
if (permission == null) {
logger.error(logger.MODELWRITER, "setPermissionName(): "
+ "permission Argument must not be 'null'!");
return;
}
try {
UmlAssociation permissionAssociation = (UmlAssociation) modelmap
.getUmlElement(permission);
if (name == null || name.length() == 0)
logger.error(logger.MODELWRITER, "setPermissionName(): "
+ " new Permission Name is null or empty "
+ "-> leaving unchanged");
else
permissionAssociation.setName(name);
} catch (Exception e) {
logger.logException(e);
}
}
public void setAuthorizationConstraint(PermissionDummy permissionDummy,
String constraint) {
if (permissionDummy == null) {
logger.error(logger.MODELWRITER, "setAuthorizationConstraint(): "
+ "permission Argument must not be 'null'!");
return;
}
try {
AssociationClass permissionAssociation = (AssociationClass) modelmap
.getUmlElement(permissionDummy);
if (constraint == null || constraint.length() == 0) {
// remove TaggedValue
Model
.getExtensionMechanismsHelper()
.removeTaggedValue(
permissionAssociation,
SecureUmlConstants.TAG_DEFINITION_AUTHORIZATION_CONSTRAINT);
} else {
// set Tagged Value
Model
.getCoreHelper()
.setTaggedValue(
permissionAssociation,
SecureUmlConstants.TAG_DEFINITION_AUTHORIZATION_CONSTRAINT,
constraint);
}
} catch (Exception e) {
logger.logException(e);
}
}
/* Util methods */
public String getActionType(Object action) {
if (action != null) {
ActionType actionType = GenericDialectHelper.getInstance()
.getActionType(action);
return actionType.getShortName();
} else {
return null;
}
}
}

View File

@ -0,0 +1,129 @@
package ch.ethz.infsec.secureumlgui.modelmapping;
import java.util.Collection;
import org.argouml.model.Model;
import org.omg.uml.foundation.core.Classifier;
import org.omg.uml.foundation.core.ModelElement;
import org.omg.uml.behavioralelements.statemachines.StateMachine;
import org.omg.uml.behavioralelements.statemachines.Transition;
//import tudresden.ocl20.core.MetaModelConst.MetaModelInfo;
import ch.ethz.infsec.secureumlgui.logging.MultiContextLogger;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.DialectMetaModelInfo;
@Deprecated
public class PathNameResolver {
private static MultiContextLogger logger = new MultiContextLogger();
/**
* Finds an element with the given name inside its containing
* object.
*
* @param elem
* @param name
* @return the found element
*/
@SuppressWarnings("unchecked")
private static ModelElement findInAnchor(ModelElement elem, String name) {
if (elem instanceof Classifier) {
Classifier anchor = (Classifier) elem;
// search attributes
/* TODO: inserted manually 5 */
Collection attributes = Model.getCoreHelper().getAllAttributes(anchor);
ModelElement result = find(attributes, name);
//ModelElement result = find(anchor.allAttributes(), name);
if (result != null) {
return result;
}
// search operations
/* TODO: inserted manually 6 */
Collection operations = Model.getFacade().getOperations(anchor);
result = find(operations, name);
//result = find(anchor.allOperations(), name);
if (result != null) {
return result;
}
// search statemachine states and transitions
for (ModelElement ownedElem : (Collection<ModelElement>) anchor
.getOwnedElement()) {
if (ownedElem instanceof StateMachine) {
StateMachine sm = (StateMachine) ownedElem;
for (Transition t : (Collection<Transition>) sm
.getTransitions()) {
// search transitions
// transitions are addressed by their trigger (event) name
if (t.getTrigger() != null && t.getTrigger().getName().equals(name)) {
return t;
}
// search states
if (t.getSource() != null &&t.getSource().getName().equals(name)) {
return t.getSource();
}
if (t.getTarget() != null && t.getTarget().getName().equals(name)) {
return t.getTarget();
}
}
}
}
} else {
logger.error("unknown anchor type "
+ elem.getClass().getSimpleName());
}
return null;
}
private static ModelElement find(Collection<ModelElement> elems, String name) {
for (ModelElement elem : elems) {
if (elem.getName().equals(name)) {
return elem;
}
}
return null;
}
/**
* Find a resource in a modelelement according to the given pathName.
*
* @param pathName
* @param anchor
* @return the found element
*/
@SuppressWarnings("unchecked")
public static ModelElement resolve(String pathName, ModelElement anchor) {
String[] components = pathName.split("\\.");
if (components.length == 0) {
logger.error("invalid path expression: " + pathName);
return null;
}
int pathOffset = 0;
if (components[pathOffset].equals(anchor.getName())) {
if (components.length == 1) {
// path name denotes the anchor, return it
return anchor;
} else {
// path name has an anchor prefix, skip it
pathOffset = 1;
}
}
ModelElement result = anchor;
// follow path to find resource
while (pathOffset < components.length) {
result = findInAnchor(result, components[pathOffset]);
pathOffset++;
}
if (result == null) {
logger.error("invalid path expression: " + pathName);
}
return result;
}
}

View File

@ -0,0 +1,606 @@
package ch.ethz.infsec.secureumlgui.modelmapping;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.jmi.reflect.RefObject;
import javax.jmi.reflect.RefPackage;
//import org.argouml.ui.secureuml.modelmanagement.ModelConst;
import org.apache.log4j.Logger;
import org.omg.uml.foundation.core.AssociationEnd;
import org.omg.uml.foundation.core.Attribute;
import org.omg.uml.foundation.core.Classifier;
import org.omg.uml.foundation.core.Feature;
import org.omg.uml.foundation.core.Generalization;
import org.omg.uml.foundation.core.ModelElement;
import org.omg.uml.foundation.core.Stereotype;
import org.omg.uml.foundation.core.AssociationClass;
import org.omg.uml.foundation.core.TaggedValue;
import org.omg.uml.foundation.core.UmlClass;
//import tudresden.ocl20.core.MetaModelConst;
import ch.ethz.infsec.secureumlgui.main.SecureUmlConstants;
import ch.ethz.infsec.secureumlgui.Util;
import ch.ethz.infsec.secureumlgui.modelmapping.counters.SecureUmlMappingCounter;
//import ch.ethz.infsec.secureumlgui.oclconstraintloader.ConstraintLoader;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.DialectMetaModelInfo;
import ch.ethz.infsec.secureumlgui.util.PermissionDummy;
import ch.ethz.infsec.secureumlgui.wrapper.ActionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.PermissionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.PolicyWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.ResourceWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.RoleWrapper;
import ch.ethz.infsec.secureumlgui.securemodelimpl.SecureModelFactory;
/**
* Abstract class for mapping the SecureUML (non-dialect) elements.
*
* Subclasses will do the mapping for the dialect specific elements.
*
* @version 1.0
*/
public abstract class SecureUmlModelMapper extends ModelMapper {
private static final boolean verbose = true;
@Deprecated
protected static final String STEREOTYPE_SECUML_ROLE = SecureUmlConstants.STEREOTYPE_SECUML_ROLE;
@Deprecated
protected static final String STEREOTYPE_SECUML_PERMISSION = SecureUmlConstants.STEREOTYPE_SECUML_PERMISSION;
private Collection<Classifier> permissionAnchors = new ArrayList<Classifier>();
// private ConstraintLoader constraintLoader;
public DialectMetaModelInfo dialectMetaModelInfo;
GenericDialectHelper helper = GenericDialectHelper.getInstance();
private SecureUmlMappingCounter counter = new SecureUmlMappingCounter();
private static Logger aLog = Logger.getLogger(SecureUmlModelMapper.class);
public SecureUmlModelMapper() {
logger.info("SecureUmlModelMapper");
}
public void init() {
super.init();
counter = new SecureUmlMappingCounter();
permissionAnchors.clear();
}
// public static <T> String join(final Collection<T> objs, final String
// delimiter) {
//
// return null;
// }
//
// public static void test() {
// Collection<Integer> asdf = null;
//
// <Integer> String result = join(asdf, ";");
// }
/* mapping of general uml elements (identification of stereotyped elements) */
@SuppressWarnings("unchecked")
public void transform() {
super.transform();
logger.info(counter.toString());
}
public void examineUmlClass(UmlClass umlClass) {
if (isOfType(umlClass, SecureUmlConstants.STEREOTYPE_SECUML_ROLE)) {
transformRole(umlClass);
} else if (isOfType(umlClass,
SecureUmlConstants.STEREOTYPE_SECUML_POLICY)) {
transformPolicy(umlClass);
}
}
protected void examineUmlGeneralization(Generalization generalization) {
if (isOfType(generalization.getChild(),
SecureUmlConstants.STEREOTYPE_SECUML_ROLE)
&& isOfType(generalization.getParent(),
SecureUmlConstants.STEREOTYPE_SECUML_ROLE)) {
transformRoleInheritance(generalization);
}
}
@SuppressWarnings("unchecked")
protected void examineAssociationClass(AssociationClass associationClass) {
if (isOfType(associationClass,
SecureUmlConstants.STEREOTYPE_SECUML_PERMISSION)) {
transformPermissionClass(associationClass);
}
}
/* mapping of stereotyped elements */
@SuppressWarnings("unchecked")
protected void transformPermissionClass(AssociationClass associationClass) {
Classifier roleClassifier = null;
Classifier policyClassifier = null;
Classifier anchorClassifier = null;
Object role = null;
Object policy = null;
Object anchor = null;
// if (verbose)
// logger.info("-- permission: "
// + associationClass.getName());
// association ends => role and anchor
for (AssociationEnd end : associationClass.getConnection()) {
Classifier participant = end.getParticipant();
if (isOfType(participant, SecureUmlConstants.STEREOTYPE_SECUML_ROLE)) {
roleClassifier = participant;
aLog.debug("found role " + roleClassifier);
// } else if (isOfType(participant,
// SecureUmlConstants.STEREOTYPE_SECUML_POLICY)) {
// policyClassifier = participant;
// aLog.debug("found policy " + policyClassifier);
} else if (!isOfType(participant,
SecureUmlConstants.STEREOTYPE_SECUML_PERMISSION)) {
anchorClassifier = participant;
aLog.debug("found anchor " + anchorClassifier);
} else {
aLog.debug("what did i find?" + participant);
}
}
policyClassifier = GenericDialectModelMapper.getInstance().getPolicy(associationClass);
// fail if either role or anchor are missing
if (roleClassifier == null) {
logger.error("no role associated with permission "
+ associationClass.getName());
return;
} else {
role = map.getElement(roleClassifier);
aLog.debug("permission "+associationClass.getName()+ " associatied with Role "+role);
}
if (policyClassifier == null) {
aLog.debug("no policyClassifier found for permission "
+ associationClass.getName() );
// policy = GenericDialectModelMapper.getInstance().getDefaultPolicy();
} else {
policy = map.getElement(policyClassifier);
aLog.debug("found policy for permission: " + policy);
}
if (anchorClassifier == null) {
logger.error("no anchor associated with permission "
+ associationClass.getName());
return;
} else {
anchor = map.getElement(anchorClassifier);
// logger.info("permission "+associationClass.getName()+"
// associatied with Anchor "+anchor);
}
// logger.info("role: " + role
// + "anchor:" + anchor);
// if(role==null){logger.error("role not found while transforming
// permission "+associationClass.getName());}
// if(anchor==null){logger.error("anchor not found while transforming
// permission "+associationClass.getName());}
counter.incPermissionClassCount();
// may happen if the anchor wasn't in the mapping scope:
if (anchor == null)
return;
// constraint => constraint for all permissions
String constraint = getAuthorizationConstraint(associationClass);
Object authorizationConstraint = null;
if (constraint != null && constraint.length() > 0) {
authorizationConstraint = SecureModelFactory.getInstance()
.createAuthorizationConstraint(constraint);
}
PermissionDummy permissionDummy = new PermissionDummy(associationClass
.getName());
// RoleWrapper roleWrapper = new RoleWrapper(role);
// ResourceWrapper anchorWrapper = new ResourceWrapper(anchor);
permissionDummy.setRole(role);
if (policy != null ) {
permissionDummy.setPolicy(policy);
}
permissionDummy.setAnchor(anchor);
permissionDummy.setAuthorizationConstraint(authorizationConstraint);
map.put(associationClass, permissionDummy);
// attributes => the permissions
//for (Object o : (List) associationClass.getFeature())
for (Feature feature : associationClass.getFeature())
// .allAttributes())
{
if (feature instanceof Attribute) {
Attribute a = (Attribute) feature;
transformPermission(associationClass.getName(), a,
anchorClassifier, roleClassifier, policyClassifier,
authorizationConstraint);
Object permission = map.getElement(a);
if (permission != null) {
PermissionWrapper pw = new PermissionWrapper(permission);
pw.setAuthorizationConstraint(authorizationConstraint);
//PermissionWrapper permissionWrapper = new PermissionWrapper(permission);
//aLog.debug("permissionWrapper " + pw.getName() + " with policy: " + (pw.getPolicyWrapper() == null ? "NULL" : pw.getPolicyWrapper().getName()));
permissionDummy.addPermissionWrapper(pw);
}
}
}
// map.addForDeletion(associationClass);
// map.printMap();
}
/**
* looks for the proper tagged value of the assocation class.
*/
private String getAuthorizationConstraint(AssociationClass associationClass) {
String constraint = "";
Collection taggedValues = associationClass.getTaggedValue();
if (taggedValues != null && taggedValues.size() > 0) {
for (Iterator iter = taggedValues.iterator(); iter.hasNext();) {
TaggedValue taggedValue = (TaggedValue) iter.next();
if (taggedValue != null && taggedValue.getDataValue() != null
&& taggedValue.getDataValue().size() > 0) {
logger.info("### TaggedValue found( type: "
+ taggedValue.getType().getName() + ", dataValue: "
+ taggedValue.getDataValue().iterator().next());
if (taggedValue != null
&& taggedValue.getType().getName() != null
&& taggedValue
.getType()
.getName()
.equals(
SecureUmlConstants.TAG_DEFINITION_AUTHORIZATION_CONSTRAINT)) {
constraint = taggedValue.getDataValue().iterator()
.next().toString();
}
}
}
}
return fixSpacing(constraint);
}
/**
* replace " . " by "."
*
* @param constraint
* @return the transformed string
*/
private String fixSpacing(String constraint) {
if (constraint == null) {
return null;
}
return constraint.replaceAll("\\s\\.\\s", "\\.");
}
@SuppressWarnings("unchecked")
protected void transformPermission(String permissionName, Attribute attr,
Classifier anchorClassifier, Classifier roleClassifier, Classifier policyClassifier,
Object constraint) {
// TODO:
// find the resource by resolving the attribute name, which is the
// path name of the resource inside the anchor
ModelElement targetResource =
// PathNameResolver.resolve(
helper.resolvePath(attr.getName(), anchorClassifier);
// String attributeName = a.getName();
// logger.info("transforming Permission on Resource '"
// + targetResourceName
// + "' for action'"
// + attributeType);
if (targetResource != null && attr != null && attr.getType() != null) {
String attributeType = attr.getType().getName();
String targetResourceName = targetResource.getName();
// if (verbose)
// logger.info(" resource: " + targetResourceName
// + ", action: " + a.getType().getName());
// create the permission
// TODO:
// Permission suPermission = null;
// = target.getSecureUml().getPermission()
// .createPermission(permissionName);
// connect with role
RefObject permission = SecureModelFactory
.getInstance()
.createPermission(attr.getName() + "_" + attr.getType().getName());
// logger.info("Permission "+ a.getName() + "_" +
// a.getType().getName() + " created");
// permission.setRole((Role) map.getElement(role));
Util
.setProperty(permission, "role", map
.getElement(roleClassifier));
Util.setProperty(permission, "name", permissionName);
Object suPolicy = map.getElement(policyClassifier);
if ( suPolicy != null ) {
// Util.setProperty(permission, "policy", suPolicy);
// aLog.debug("SET POLICY " + suPolicy + " to PERMISSION " + permission);
PermissionWrapper perm = new PermissionWrapper(permission);
perm.setPolicy(suPolicy);
Set<PolicyWrapper> pol = perm.getPolicyWrappers();
aLog.debug("check: " + (pol == null ? "NULL" : pol.size()));
}
map.put(attr, permission);
// instantiate the corresponding action
RefObject suTargetResource = (RefObject) map.getElement(targetResource);
// ResourceWrapper rw = new ResourceWrapper(suTargetResource);
// rw.get
if (suTargetResource == null)
logger.error("suTargetResource = null, targetResource = "
+ targetResource + " " + targetResourceName
+ ", permission = " + permissionName);
RefObject suAction = getOrCreateAction(suTargetResource, attr
.getType().getName());
// RefObject suAction =
// ActionInstantiator.initializeAction(a.getType().getName(),
// suAction,
// suTargetResource);
if (suAction == null) {
logger.error("instantiation of action " + attr.getType().getName()
+ " failed");
return;
}
ActionWrapper aw = ActionWrapper.createActionWrapper(suAction);
aw.addPermission(permission);
Object suRole = map.getElement(roleClassifier);
RoleWrapper roleWrapper = new RoleWrapper(suRole);
roleWrapper.addPermission(permission);
PermissionWrapper permissionwrapper = new PermissionWrapper(
permission);
permissionwrapper.setRole(suRole);
permissionwrapper.setAction(suAction);
if ( suPolicy != null ) {
aLog.debug("set policy for permission " + permissionwrapper.getName() + " policy " + suPolicy + " " + new PermissionWrapper(suPolicy).getName());
permissionwrapper.setPolicy(suPolicy);
}
ResourceWrapper resourceWrapper = new ResourceWrapper(
suTargetResource);
resourceWrapper.getAction().add(suAction);
//PolicyWrapper policy = new PolicyWrapper(suPolicy);
//policy.
// logger.info("Transformed Permission for Role: "
// + roleWrapper.getName()
// + ", permission: "
// + permissionwrapper.getName()
// + " on Action: "
// + permissionwrapper.getActionWrapper().getName());
// TODO: connect the permission with the action
// permission.getAction().add(suAction);
// Util.setProperty(permission, "action", suAction);
// connect the Action with the Resource
if (constraint != null) {
Util.setProperty(permission, "authorizationConstraint",
constraint);
Util.setProperty(constraint, "permission", permission);
}
permissionAnchors.add(anchorClassifier);
counter.incPermissionCount();
} else {
logger.error("target resource not found");
}
}
/** creates a SecureUML role with the name of the UML class */
protected void transformRole(Classifier roleClass) {
if (map.mapContainsKey(roleClass))
return;
// if (verbose)
// logger.info("-- role: " + roleClass.getName());
// RefObject role = createRole(roleClass.getName());
RefObject role = SecureModelFactory.getInstance().createRole(
roleClass.getName());
// TODO
// target.getSecureUml().getRole().createRole();
// role.setName(roleClass.getName());
String propertyName = "name";
Util.setProperty(role, propertyName, roleClass.getName());
map.put(roleClass, role);
// map.addForDeletion(roleClass);
counter.incRoleCount();
}
protected void transformPolicy(Classifier policyClass) {
if (map.mapContainsKey(policyClass)) {
return;
}
RefObject policy = SecureModelFactory.getInstance().createPolicy(policyClass.getName());
//redundant?
Util.setProperty(policy, "name", policyClass.getName());
map.put(policyClass, policy);
counter.incPolicyCount();
}
@SuppressWarnings("unchecked")
protected void transformRoleInheritance(Generalization generalization) {
if (map.mapContainsKey(generalization))
return;
Object child = /* (Role) */map.getElement(generalization.getChild());
Object parent = /* (Role) */map.getElement(generalization.getParent());
if (child != null && parent != null) {
// if (verbose)
// logger.info("-- role inheritance: " + Util.getProperty(parent,
// "name") + "-"
// + Util.getProperty(child, "name"));
// child.getSuperroles().add(parent);
Util.setProperty(child, "superroles", parent);
// parent.getSubroles().add(child);
Util.setProperty(parent, "subroles", child);
counter.incRoleInheritance();
}
}
protected void transformPolicyInheritance(Generalization generalization) {
if (map.mapContainsKey(generalization)) {
return;
}
Object child = /* (Policy) */ map.getElement(generalization.getChild());
Object parent = /* (Policy) */map.getElement(generalization.getParent());
if ( child != null && parent != null ) {
// Method[] methods = child.getClass().getMethods();
// for (Method method : methods) {
// System.out.print(method.getReturnType() + " " + method.getName() + "(");
// for ( Class paramType : method.getParameterTypes() ) {
// System.out.print(paramType + ",");
// }
// System.out.println(")");
// }
Util.setProperty(child, SecureUmlConstants.POLICY_INHERITANCE_REFINEDBY, parent);
Util.setProperty(parent, SecureUmlConstants.POLICY_INHERITANCE_REFINES, child);
counter.incPolicyInheritanceCount();
}
}
/* utility methods */
protected boolean isOfType(ModelElement element, String stereotype) {
if (element == null || stereotype == null)
return false;
Collection stereotypes = element.getStereotype();
int nofStereotypes = stereotypes.size();
if (stereotypes == null || stereotypes.size() == 0)
return false;
for (Iterator it = stereotypes.iterator(); it.hasNext();) {
Stereotype s = (Stereotype) it.next();
if (s.getName().equals(stereotype)) {
return true;
}
}
return false;
}
protected boolean isOfType(Collection<ModelElement> elements,
String stereotype) {
for (ModelElement elem : elements) {
if (!isOfType(elem, stereotype)) {
return false;
}
}
return true;
}
protected boolean endsAreOfTypes(List<AssociationEnd> e, String s1,
String s2) {
if (e.size() != 2) {
logger.warning("expecting 2 collection elements");
return false;
} else {
return ((isOfType(e.get(0).getParticipant(), s1) && isOfType(e.get(
1).getParticipant(), s2)) || (isOfType(e.get(0)
.getParticipant(), s2) && isOfType(e.get(1)
.getParticipant(), s1)));
}
}
// abstract public RefObject createRole(String name);
// abstract public RefObject createPermission(String name);
// abstract public RefObject createAuthorizationConstraint(String
// constraint);
abstract public RefObject getOrCreateAction(RefObject resource,
String shortActionName);
public Collection<Classifier> getPermissionAnchors() {
return permissionAnchors;
}
}

View File

@ -0,0 +1,13 @@
package ch.ethz.infsec.secureumlgui.modelmapping.counters;
public class Counter {
protected String sinPlur(int number, String singular, String plural) {
if (number == 1) {
return singular;
} else {
return plural;
}
}
}

View File

@ -0,0 +1,82 @@
package ch.ethz.infsec.secureumlgui.modelmapping.counters;
public class SecureUmlMappingCounter extends Counter {
private int permissionCount = 0;
private int permissionClassCount = 0;
private int roleCount = 0;
private int roleInheritanceCount = 0;
private int policyCount = 0;
private int policyInheritanceCount = 0;
public int getPermissionClassCount() {
return permissionClassCount;
}
public void incPermissionClassCount() {
this.permissionClassCount++;
}
public int getPermissionCount() {
return permissionCount;
}
public void incPermissionCount() {
this.permissionCount++;
}
public int getRoleCount() {
return roleCount;
}
public void incRoleCount() {
this.roleCount++;
}
public int getRoleInheritanceCount() {
return roleInheritanceCount;
}
public void incRoleInheritance() {
roleInheritanceCount++;
}
public int getPolicyCount() {
return policyCount;
}
public void incPolicyCount() {
this.policyCount++;
}
public int getPolicyInheritanceCount() {
return policyInheritanceCount;
}
public void incPolicyInheritanceCount() {
this.policyInheritanceCount++;
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append(" SecureUML\n");
buf.append(" " + getRoleCount() + " role class"
+ sinPlur(getRoleCount(), "", "es") + "\n");
buf.append(" " + getRoleInheritanceCount()
+ " role inheritance relation"
+ sinPlur(getRoleInheritanceCount(), "", "s") + "\n");
buf.append(" " + getPermissionClassCount() + " permission class"
+ sinPlur(getPermissionClassCount(), "", "es") + "\n");
buf.append(" " + getPermissionCount() + " permission"
+ sinPlur(getPermissionCount(), "", "s") + "\n");
return buf.toString();
}
}

View File

@ -0,0 +1,9 @@
<html>
<head>
<title></title>
</head>
<body>
Calculating the correspondence between SecureUML (dialect) elements
and their UML counterparts.
</body>
</html>

View File

@ -0,0 +1,165 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.modelmapping.permissions;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import ch.ethz.infsec.secureumlgui.modelmapping.permissions.HierarchicalPermissionsExplorer.CHANGES;
import ch.ethz.infsec.secureumlgui.wrapper.ActionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.PermissionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.PolicyWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.RoleWrapper;
/**
* the set of permissions for role {@link #explicitRoleWrapper} on
* action {@link #explicitActionWrapper}.
*
*/
public class ActionPermissionSet
{
Map<Object, PolicyPermissionSet> permissions = new HashMap<Object, PolicyPermissionSet>();
private PolicyPermissionSet defaultPermissions;
private static Logger aLog = Logger.getLogger(ActionPermissionSet.class);
private boolean inserted_default = false; //Very, very bad hack..
public ActionPermissionSet() {
PolicyWrapper defaultPolicy = HierarchicalPolicyExplorer.getInstance().getDefaultPolicyWrapper();
defaultPermissions = new PolicyPermissionSet(defaultPolicy);
if ( defaultPolicy != null ) {
permissions.put(defaultPolicy.getModelElement(), defaultPermissions);
inserted_default = true;
}
}
public void addExplicitDefaultPermission(PermissionValue permissionValue) {
defaultPermissions.addExplicitPermission(permissionValue);
}
public void addExplicitPermission(PolicyWrapper policy, PermissionValue permissionValue) {
getPolicyPermissionSet(policy).addExplicitPermission(permissionValue);
}
public void addDefaultPermission(PermissionValue permissionValue, CHANGES changeReason) {
defaultPermissions.addPermission(permissionValue, changeReason);
}
public void addPermission(PolicyWrapper policy, PermissionValue permissionValue, CHANGES changeReason) {
//aLog.debug("addPermission to policy " +( policy == null ? "NULL" : policy.getName()+ "_" + policy.getModelElement()) + "(" + permissions.size() + ")" );
getPolicyPermissionSet(policy).addPermission(permissionValue, changeReason);
}
public PolicyPermissionSet getDefaultPolicyPermissionSet() {
return defaultPermissions;
}
public PolicyPermissionSet getPolicyPermissionSet(PolicyWrapper policy) {
if ( policy == null ) {
return getDefaultPolicyPermissionSet();
}
if ( ! inserted_default ) {
PolicyWrapper defaultPolicy = HierarchicalPolicyExplorer.getInstance().getDefaultPolicyWrapper();
if ( defaultPolicy != null ) {
permissions.put(defaultPolicy.getModelElement(), defaultPermissions);
inserted_default = true;
}
}
if ( permissions.containsKey(policy.getModelElement())) {
return permissions.get(policy.getModelElement());
} else {
PolicyPermissionSet policyPermissionSet = new PolicyPermissionSet(policy);
permissions.put(policy.getModelElement(), policyPermissionSet);
return policyPermissionSet;
}
}
public Collection<PermissionValue> getPermissions(PolicyWrapper policy) {
//aLog.debug("getPermissions of policy " +( policy == null ? "NULL" : policy.getName()+ "_" + policy.getModelElement()) + "(" + permissions.size() + ")" );
return getPolicyPermissionSet(policy).getPermissions();
}
private RoleWrapper explicitRoleWrapper;
private ActionWrapper explicitActionWrapper;
public RoleWrapper getExplicitRoleWrapper()
{
return explicitRoleWrapper;
}
public void setExplicitRoleWrapper(RoleWrapper explicitRoleWrapper)
{
this.explicitRoleWrapper = explicitRoleWrapper;
}
public ActionWrapper getExplicitActionWrapper()
{
return explicitActionWrapper;
}
public void setExplicitActionWrapper(ActionWrapper explicitActionWrapper)
{
this.explicitActionWrapper = explicitActionWrapper;
}
public boolean isExplicitPermitted(PolicyWrapper policy) {
return getPolicyPermissionSet(policy).isExplicitPermitted();
}
public PermissionWrapper getExplicitPermittedPermission(PolicyWrapper policy) {
return getPolicyPermissionSet(policy).getExplicitPermittedPermission();
}
// public boolean isPermitted() {
// for (PermissionValue permission : permissions ) {
// if ( ! permission.isConstrained()) {
// return true;
// }
// }
// return false;
// }
//
// public boolean isConstrainedPermitted() {
// if (permissions.size() > 0 )
// return true;
// else
// return false;
//
// }
}

View File

@ -0,0 +1,137 @@
package ch.ethz.infsec.secureumlgui.modelmapping.permissions;
import java.util.Collection;
import java.util.List;
import javax.jmi.reflect.RefClass;
import javax.jmi.reflect.RefException;
import javax.jmi.reflect.RefFeatured;
import javax.jmi.reflect.RefObject;
import javax.jmi.reflect.RefPackage;
import ch.ethz.infsec.secureumlgui.securemodel.secureuml.AuthorizationConstraint;
import ch.ethz.infsec.secureumlgui.securemodel.secureuml.Permission;
import ch.ethz.infsec.secureumlgui.securemodel.secureuml.Role;
public class CompositePermission implements Permission {
//public CompositePermission(String name,
public Collection getAction() {
// TODO Auto-generated method stub
return null;
}
public AuthorizationConstraint getAuthorizationConstraint() {
// TODO Auto-generated method stub
return null;
}
public String getName() {
// TODO Auto-generated method stub
return null;
}
public Role getRole() {
// TODO Auto-generated method stub
return null;
}
public void setAuthorizationConstraint(AuthorizationConstraint newValue) {
// TODO Auto-generated method stub
}
public void setName(String newValue) {
// TODO Auto-generated method stub
}
public void setRole(Role newValue) {
// TODO Auto-generated method stub
}
public RefClass refClass() {
// TODO Auto-generated method stub
return null;
}
public void refDelete() {
// TODO Auto-generated method stub
}
public RefFeatured refImmediateComposite() {
// TODO Auto-generated method stub
return null;
}
public boolean refIsInstanceOf(RefObject arg0, boolean arg1) {
// TODO Auto-generated method stub
return false;
}
public RefFeatured refOutermostComposite() {
// TODO Auto-generated method stub
return null;
}
public Object refGetValue(RefObject arg0) {
// TODO Auto-generated method stub
return null;
}
public Object refGetValue(String arg0) {
// TODO Auto-generated method stub
return null;
}
public Object refInvokeOperation(RefObject arg0, List arg1)
throws RefException {
// TODO Auto-generated method stub
return null;
}
public Object refInvokeOperation(String arg0, List arg1)
throws RefException {
// TODO Auto-generated method stub
return null;
}
public void refSetValue(RefObject arg0, Object arg1) {
// TODO Auto-generated method stub
}
public void refSetValue(String arg0, Object arg1) {
// TODO Auto-generated method stub
}
public RefPackage refImmediatePackage() {
// TODO Auto-generated method stub
return null;
}
public RefObject refMetaObject() {
// TODO Auto-generated method stub
return null;
}
public String refMofId() {
// TODO Auto-generated method stub
return null;
}
public RefPackage refOutermostPackage() {
// TODO Auto-generated method stub
return null;
}
public Collection refVerifyConstraints(boolean arg0) {
// TODO Auto-generated method stub
return null;
}
}

View File

@ -0,0 +1,481 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.modelmapping.permissions;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import org.omg.uml.UmlPackage;
import org.omg.uml.foundation.core.UmlClass;
import ch.ethz.infsec.secureumlgui.ModuleController;
import ch.ethz.infsec.secureumlgui.logging.MultiContextLogger;
import ch.ethz.infsec.secureumlgui.wrapper.ActionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.PermissionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.PolicyWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.ResourceWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.RoleWrapper;
/**
* Explore the permission hierarchy generated by role inheritance and
* action composition.
*
*/
public class HierarchicalPermissionsExplorer
{
MultiContextLogger logger = MultiContextLogger.getDefault();
private static Logger aLog = Logger.getLogger(HierarchicalPermissionsExplorer.class);
private static HierarchicalPolicyExplorer policyExplorer = HierarchicalPolicyExplorer.getInstance();
public enum CHANGES {
EXPLICIT, INHERITED, IMPLICIT_SUB, IMPLICIT_SUPER, INHERITED_POLIY
}
public void collectNonExplicitPermissions(ResourceWrapper resource, PermissionSet permissions) {
aLog.debug("collectNonExplicitPermissions: (roles: " + permissions.getAllRoleWrappers().size() + ")");
Date start = new Date();
//List<PolicyWrapper> policies = policyExplorer.getSortedPolicies();
List<UmlClass> policies = policyExplorer.getSortedPolicies();
// PolicyWrapper defaultPolicy = HierarchicalPolicyExplorer.getInstance().getDefaultPolicy();
//
// if ( defaultPolicy == null ) {
// policies.add(0, defaultPolicy);
// }
for ( UmlClass policyClass : policies) {
PolicyWrapper policy = new PolicyWrapper(ModuleController.getInstance().getModelMap().getElement(policyClass));
aLog.debug("collecting directly policy-inherited permissions for resruce " + resource + " and policy: " + policy.getName());
collectPolicyInheritedPermissions(resource, permissions, policy);
aLog.debug("collecting directly implicit, from explicit, permissions for resource " + resource + " and policy: " + policy.getName());
//collect implicit permissions, without taking into account dependencies between implicit and inheritied
collectImplicitPermissions(resource, permissions, policy);
aLog.debug("colling directly inherited, from explicit, permissions for resource " + resource + " and policy: " + policy.getName());
collectInheritedPermissions(resource, permissions, policy);
aLog.debug("collection directly permission END");
//
PermissionSet next, last;
//create an empty next set
next = new PermissionSet();
//for the first run, iterate over all permissions
aLog.debug("collecting indirect implicit permissions, iterating over all permissions");
collectImplicitPermissions(policy, resource, permissions, permissions, next);
while (true) {
last = next;
next = new PermissionSet();
if ( last.getAllRoleWrappers().size() == 0 ) { //nothing changed, finished
aLog.debug("recursion did not find any further permissions by collecting implicit permissions... DONE!");
break;
} else {
if ( aLog.isDebugEnabled() ) {
aLog.debug("starting with search of indirectly inherited permissions, number of roles: " + next.getAllRoleWrappers().size());
}
collectInheritedPermissions(policy, resource, last, permissions, next );
}
last = next;
next = new PermissionSet();
if ( last.getAllRoleWrappers().size() == 0 ) { //nothing changed, finished
aLog.debug("recursion did not find any further permissions by collecting inherited permissions... DONE!");
break;
} else {
if ( aLog.isDebugEnabled() ) {
aLog.debug("starting with search of indirectly implicit permissions, number of roles: " + next.getAllRoleWrappers().size());
}
collectImplicitPermissions(policy, resource, last, permissions, next );
}
}
}
long duration = new Date().getTime() - start.getTime();
aLog.debug("needed: " + duration);
}
private void collectPolicyInheritedPermissions(ResourceWrapper resource, PermissionSet permissions, PolicyWrapper policy) {
aLog.debug("collectPolicyInheritedPermissions for policy (" + policy.getName() + ") START");
Collection refinedBy = policy.getRefinedBy();
if ( refinedBy != null && refinedBy.size() > 0 ) {
for ( PolicyWrapper supPol : policy.getRefinedByWrappers() ) {
aLog.debug("start with policy " + supPol.getName());
for ( RoleWrapper role : permissions.getAllRoleWrappers() ) {
ResourcePermissionsSet resourcePermissions = permissions.getResourcePermissionsSet(role);
for (ActionWrapper action : resource.getActionWrapper()) {
ActionPermissionSet actionPermissions = resourcePermissions.getPermissions(action);
for (PermissionValue permission : actionPermissions.getPermissions(supPol)) {
actionPermissions.addPermission(policy, PermissionValue.createInheritedPolicy(permission), CHANGES.INHERITED_POLIY);
}
}
}
aLog.debug("end with policy " + supPol.getName());
}
}
aLog.debug("collectPolicyInheritedPermissions END");
}
/**
* collects all permissions, which are DIRECTLY IMPLICIT from the explicit permissions
* @param resource
* @param permissions
*/
private void collectImplicitPermissions(ResourceWrapper resource, PermissionSet permissions, PolicyWrapper policy) {
aLog.debug("collectImplicitPermissions START");
//PermissionSet superactionResourcePermissions = getExplicitPermissions(resource);
// for a fixed resource, iterate over ALL roles
for (RoleWrapper role : permissions.getAllRoleWrappers()) {
aLog.debug(" role: " + role.getName());
ResourcePermissionsSet resourcePermissions = permissions.getResourcePermissionsSet(role);
//iterate over all actions of the fixed resource and get the permissions assigned to this action and role, saved in actionPermissions
for (ActionWrapper action : resource.getActionWrapper()) {
aLog.debug(" action: " + action.getName());
ActionPermissionSet actionPermissions = resourcePermissions.getPermissions(action);
//iterate over all super actions (i.e., all composite actions of which this action is part of), => implicit permission from SUPER actions
for ( ActionWrapper superAction : getSuperActionWrappersDeep(action) ) {
//and get all explicit permissions assigned to this resource (any role and action?)
Collection<PermissionValue> superActionPermissions =
permissions.getResourcePermissionsSet(role).getPermissions(superAction).getPermissions(policy);
// Collection<PermissionValue> superActionPermissions =
// superactionResourcePermissions.getResourcePermissionsSet(role).getPermissions(superAction).getPermissions(policy);
// if ( aLog.isDebugEnabled() ) {
// aLog.debug(" superAction: " + superAction.getName() + " with " + superActionPermissions.size() + " permissions");
// }
for (PermissionValue permission : superActionPermissions) {
actionPermissions.addPermission(policy, PermissionValue.createImplicite(permission), CHANGES.IMPLICIT_SUPER);
}
}
//implicit permissions from SUB actions
if ( action.hasSubActions() && isPermittedImplicitBySubactions ( permissions, role, action, policy ) ) {
aLog.debug("IMPLICIT BY SUBACTION: " + role.getName() + " on " + action.getName());
PermissionValue composite = PermissionValue.createComposite(null, action, role);
actionPermissions.addPermission(policy, composite, CHANGES.IMPLICIT_SUB);
}
}
}
aLog.debug("collectImplicitPermissions END");
}
/**
* collects all permissions, which are DIRECTLY INHERITED from explicit permissions
* @param resource
* @param permissions
*/
private void collectInheritedPermissions(ResourceWrapper resource, PermissionSet permissions, PolicyWrapper policy) {
aLog.debug("collectInheritedPermissions START");
// for a fixed resource, iterate over ALL roles
for (RoleWrapper role : permissions.getAllRoleWrappers()) {
aLog.debug(" role: " + role.getName());
ResourcePermissionsSet resourcePermissions = permissions.getResourcePermissionsSet(role);
// get super Roles for this role
Set<RoleWrapper> superRoles = getSuperRoleWrappersDeep(role);
//iterate over all actions of the fixed resources and get the permissions assigned to this action and role, saved in actionPermissions
for (ActionWrapper action : resource.getActionWrapper()) {
aLog.debug(" action: " + action.getName());
ActionPermissionSet actionPermissions = resourcePermissions.getPermissions(action);
//iterate over all super Roles for the current role
for (RoleWrapper superRole : superRoles ) {
Collection<PermissionValue> superRolePermissions =
permissions.getResourcePermissionsSet(superRole).getPermissions(action).getPermissions(policy);
// if ( aLog.isDebugEnabled() ) {
// aLog.debug(" superRole: " + superRole.getName() + " with " + superRolePermissions.size() + " permissions");
// }
aLog.debug("for superrole " + superRole.getName() + " found " + superRolePermissions.size() + " permissions");
//iterate over all permissions, the superrole has and assign as inherited to current role
for (PermissionValue permission : superRolePermissions) {
permission = PermissionValue.createInheritedRole(permission);
//use permission of super role to create an inherited permission for current role
actionPermissions.addPermission(policy, permission, CHANGES.INHERITED);
}
}
}
}
aLog.debug("collectInheritedPermissions END");
}
/**
* collects all permissions, which are INDIRECT IMPLICIT
* @param resource
* @param permissions_last contains the elements which have changed in the last round, i.e., where it is required to look at a second time
* @param permissions_dst contains ALL the permissions which have been calculated so far (i.e., which are the end result and are required to come to a decision if something is permitted or not)
* @param permissions_next in this, the information are stored, which element have to be treated in the next round
*/
private void collectImplicitPermissions(PolicyWrapper policy, ResourceWrapper resource, PermissionSet permissions_last,
PermissionSet permissions_dst, PermissionSet permissions_next) {
aLog.debug("collectImplicitPermissions INDIRECT START");
for (RoleWrapper role : permissions_last.getAllRoleWrappers()) {
aLog.debug(" role: " + role.getName());
ResourcePermissionsSet resourcePermissions = permissions_last.getResourcePermissionsSet(role);
for (Object action : resourcePermissions.getActions()) {
ActionWrapper actionWrapper = ActionWrapper.createActionWrapper(action);
aLog.debug(" action: " + actionWrapper.getName());
ActionPermissionSet actionPermissions = permissions_dst.getResourcePermissionsSet(role).getPermissions(actionWrapper);
for ( ActionWrapper superAction : getSuperActionWrappersDeep(actionWrapper) ) {
Collection<PermissionValue> superActionPermissions = permissions_dst.getResourcePermissionsSet(role).getPermissions(superAction).getPermissions(policy);
// if ( aLog.isDebugEnabled() ) {
// aLog.debug(" superAction: " + superAction.getName() + " with " + superActionPermissions.size() + " permissions");
// }
for (PermissionValue permission : superActionPermissions) {
//permission = PermissionValue.create(PermissionValue.IMPLICIT, permission.getPermissionWrapper()); //TODO add info about etc
permission = PermissionValue.createImplicite(permission);
actionPermissions.getPolicyPermissionSet(policy).addPermission(permission, permissions_next, CHANGES.IMPLICIT_SUPER, superAction, role);
}
}
//implicit permissions from SUB actions
if ( actionWrapper.hasSubActions() && isPermittedImplicitBySubactions ( permissions_dst, role, actionWrapper, policy ) ) {
aLog.debug("IMPLICIT BY SUBACTION: " + role.getName() + " on " + actionWrapper.getName());
PermissionValue composite = PermissionValue.createComposite(null, actionWrapper, role);
//TODO is there a problem caused throw actionWrapper received from permissions_last?
actionPermissions.getPolicyPermissionSet(policy).addPermission(composite, permissions_next, CHANGES.IMPLICIT_SUB, actionWrapper, role);
}
}
}
aLog.debug("collectImplicitPermissions INDIRECT END");
}
/**
* collects all permissions, which are INDIRECT INHERITED
* @param resource
* @param permissions_last
* @param permissions_dst
* @param permissions_next
*/
private void collectInheritedPermissions(PolicyWrapper policy, ResourceWrapper resource, PermissionSet permissions_last,
PermissionSet permissions_dst, PermissionSet permissions_next) {
aLog.debug("collectInheritedPermissions INDIRECT START");
for (RoleWrapper role : permissions_last.getAllRoleWrappers()) {
ResourcePermissionsSet resourcePermissions = permissions_last.getResourcePermissionsSet(role);
aLog.debug(" role: " + role.getName());
for (Object action : resourcePermissions.getActions()) {
ActionWrapper actionWrapper = ActionWrapper.createActionWrapper(action);
aLog.debug(" action: " + actionWrapper.getName());
ActionPermissionSet actionPermissions = permissions_dst.getResourcePermissionsSet(role).getPermissions(actionWrapper);
for (RoleWrapper superRole : getSuperRoleWrappersDeep(role)) {
Collection<PermissionValue> superRolePermissions = permissions_dst.getResourcePermissionsSet(superRole).getPermissions(action).getPermissions(policy);
if ( aLog.isDebugEnabled() ) {
aLog.debug(" superRole: " + superRole.getName() + " with " + superRolePermissions.size() + " permissions");
}
for (PermissionValue permission : superRolePermissions) {
permission = PermissionValue.createInheritedRole(permission);
//use permission of super role to create an inherited permission for current role
actionPermissions.getPolicyPermissionSet(policy).addPermission(permission, permissions_next, CHANGES.INHERITED, actionWrapper, role);
}
}
}
}
aLog.debug("collectInheritedPermissions INDIRECT END");
}
// public PermissionSet getExplicitPermission(ResourceWrapper resource, PolicyWrapper policy) {
// return null;
// }
public PermissionSet getExplicitPermissions(ResourceWrapper resource)
{
PermissionSet result = new PermissionSet();
PolicyWrapper defaultPolicy = HierarchicalPolicyExplorer.getInstance().getDefaultPolicyWrapper();
for (ActionWrapper action : resource.getActionWrapper()) {
for ( PermissionWrapper permission : action.getPermissionWrappers()) {
RoleWrapper role = permission.getRoleWrapper();
if(role != null) {
PolicyWrapper policy = null;
Set<PolicyWrapper> policies = permission.getPolicyWrappers();
if (policies != null || policies.size() > 0) {
policy = policies.iterator().next();
if (policies.size() > 1 ) {
aLog.error("ignoring all policies except first one.. TODO");
}
}
if ( policy == null ) {
policy = defaultPolicy;
}
result.getResourcePermissionsSet(role).addPermission(action, PermissionValue.createGranted(permission), policy);
try {
aLog.debug("H: add explicit permission: " + role.getName() + " on " + action.getName() + " on policy " + (policy == null ? "NULL" : policy.getName() + "_" + policy.getModelElement()));
} catch (Exception e) {
aLog.debug("error at creating log mesasge: " + e.getClass() + "; " + e.getMessage());
}
ResourcePermissionsSet rps = result.getResourcePermissionsSet(
new RoleWrapper(role.getModelElement()));
ActionPermissionSet aps = rps.getPermissions(action.getName());
aps.setExplicitRoleWrapper(role);
}
}
}
return result;
}
/** gets all direct and indirect superroles
*
* @param roleWrapper
* @return the set of superroles
*/
public Set<RoleWrapper> getSuperRoleWrappersDeep(RoleWrapper roleWrapper) {
Set<RoleWrapper> result = new LinkedHashSet<RoleWrapper>();
collectSuperroles(roleWrapper, result);
aLog.debug("for role " + roleWrapper.getName() + " found " + result.size() + " superroles");
return result;
}
private static void collectSuperroles(RoleWrapper role, Set<RoleWrapper> roles) {
if(roles != null && role.getSuperroles() != null) {
for ( RoleWrapper superRole : role.getSuperrolesWrappers() ) {
roles.add(superRole);
// recursion
collectSuperroles(superRole, roles);
}
}
}
public static Set<RoleWrapper> getSubRoleWrapperDeep(RoleWrapper roleWrapper) {
Set<RoleWrapper> result = new LinkedHashSet<RoleWrapper>();
collectSubRoles(roleWrapper, result);
return result;
}
private static void collectSubRoles(RoleWrapper role, Set<RoleWrapper> roles) {
if (roles != null && role.getSubroles() != null ) {
for ( RoleWrapper subRole : role.getSubrolesWrappers() ) {
roles.add(subRole);
collectSubRoles(subRole, roles);
}
}
}
/** gets all direct and indirect superactions
*
* @param action
* @return the set of superactions.
*/
public static Set<ActionWrapper> getSuperActionWrappersDeep(ActionWrapper action) {
Set<ActionWrapper> result = new LinkedHashSet<ActionWrapper>();
collectSuperActions(action, result);
return result;
}
public static Set<ActionWrapper> getSubActionWrappersDeep(ActionWrapper action) {
Set<ActionWrapper> result = new LinkedHashSet<ActionWrapper>();
collectSubActions(action, result);
return result;
}
public static Set<ActionWrapper> getSubAndSuperActionWrappersDeep(ActionWrapper action) {
Set<ActionWrapper> result = getSuperActionWrappersDeep(action);
collectSubActions(action, result);
return result;
}
private static void collectSuperActions(ActionWrapper action, Set<ActionWrapper> result) {
if(action.getSuperActions() != null) {
for ( ActionWrapper superAction : action.getSuperActionWrappers()) {
result.add(superAction);
collectSuperActions(superAction, result);
}
}
}
private static void collectSubActions(ActionWrapper action, Set<ActionWrapper> result) {
if ( action .getSubActions() != null ) {
for ( ActionWrapper superAction : action.getSubActionWrappers()) {
result.add(superAction);
collectSubActions(superAction, result);
}
}
}
private boolean isPermittedImplicitBySubactions(PermissionSet permissions, RoleWrapper role, ActionWrapper action, PolicyWrapper policy) {
//check if explicit permitted
if ( permissions.getResourcePermissionsSet(role).getPermissions(action).getPolicyPermissionSet(policy).isPermitted()) {
return true;
}
else { //check, if implicit permitted by all permitted subactions
Set<ActionWrapper> subActions = action.getSubActionWrappers();
if ( subActions != null && subActions.size() > 0 ) {
for (ActionWrapper subAction : action.getSubActionWrappers()) {
if ( ! isPermittedImplicitBySubactions(permissions, role, subAction, policy) ) {
return false;
}
}
return true;
}
else {
return false;
}
}
}
}

View File

@ -0,0 +1,328 @@
package ch.ethz.infsec.secureumlgui.modelmapping.permissions;
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.omg.uml.foundation.core.Namespace;
import org.omg.uml.foundation.core.UmlClass;
import ch.ethz.infsec.secureumlgui.ModuleController;
import ch.ethz.infsec.secureumlgui.main.SecureUmlConstants;
import ch.ethz.infsec.secureumlgui.modelmapping.GenericDialectModelMapper;
import ch.ethz.infsec.secureumlgui.transformation.ModelMap;
import ch.ethz.infsec.secureumlgui.wrapper.PolicyWrapper;
public class HierarchicalPolicyExplorer {
private static Logger aLog = Logger.getLogger(HierarchicalPolicyExplorer.class);
private static HierarchicalPolicyExplorer INSTANCE;
static {
INSTANCE = new HierarchicalPolicyExplorer();
}
public static HierarchicalPolicyExplorer getInstance() {
return INSTANCE;
}
private HierarchicalPolicyExplorer() {
}
//private PolicyWrapper defaultPolicy;
private UmlClass defaultPolicy;
public UmlClass getDefaultPolicy() {
aLog.debug("getDefaultPolicy");
if ( defaultPolicy == null ) {
ModuleController moduleController = ModuleController.getInstance();
if ( moduleController != null ) {
Set<PolicyWrapper> unrefined = getUnrefinedPolicies();
aLog.debug("got " + unrefined.size() + " unrefined policies");
if ( unrefined != null && unrefined.size() > 0) {
PolicyWrapper pol = unrefined.iterator().next();
aLog.debug("First name: " + pol.getName());
if ( unrefined.size() == 1 && pol.getName().equals(SecureUmlConstants.DEFAULT_POLICY_NAME)) {
aLog.debug("default policy already defined");
//pol.get
defaultPolicy = (UmlClass) ModuleController.getInstance().getModelMap().getUmlElement(pol.getModelElement());
}
}
if ( defaultPolicy == null ) {
// Namespace nm;
// if ( unrefined != null && unrefined.size() > 0) {
// nm = ((UmlClass) unrefined.iterator().next().getModelElement()).getNamespace();
// } else {
// nm = GenericDialectModelMapper.getInstance().getInitNamespace();
// }
try {
aLog.debug("#############################################");
aLog.debug("START ModuleController.getInstance().createPolicy");
defaultPolicy = ModuleController.getInstance().createPolicy(SecureUmlConstants.DEFAULT_POLICY_NAME, unrefined, GenericDialectModelMapper.getInstance().getSecUMLPackage());
//as long as the model object of defaultPolicy is null...
//defaultPolicy = null;
aLog.debug("END ModuleController.getInstance().createPolicy: " + defaultPolicy);
aLog.debug("#############################################2");
} catch(Exception e) {
aLog.error("error at creating default policy: " + e.getClass().toString() + ": " + e.getMessage(), e);
}
}
} else
aLog.debug("ModuleController.getInstance() == null");
}
if (aLog.isDebugEnabled()) {
aLog.debug("getDefaultPolicy: " + (defaultPolicy == null ? "NULL" : defaultPolicy.getName()));
}
return defaultPolicy;
}
// public UmlClass getDefaultPolicy() {
// aLog.debug("getDefaultPolicy");
// if ( defaultPolicy == null ) {
// ModuleController moduleController = ModuleController.getInstance();
// if ( moduleController != null ) {
//
// Set<PolicyWrapper> unrefined = getUnrefinedPolicies();
// aLog.debug("got " + unrefined.size() + " unrefined policies");
// if ( unrefined != null && unrefined.size() > 0) {
// PolicyWrapper pol = unrefined.iterator().next();
// aLog.debug("First name: " + pol.getName());
// if ( unrefined.size() == 1 && pol.getName().equals(SecureUmlConstants.DEFAULT_POLICY_NAME)) {
// aLog.debug("default policy already defined");
// //pol.get
// defaultPolicy = (UmlClass) ModuleController.getInstance().getModelMap().getUmlElement(pol.getModelElement());
// //defaultPolicy = pol;
// } else {
// try {
// aLog.debug("#############################################");
// aLog.debug("START ModuleController.getInstance().createPolicy");
// defaultPolicy = ModuleController.getInstance().createPolicy(SecureUmlConstants.DEFAULT_POLICY_NAME, unrefined);
// //as long as the model object of defaultPolicy is null...
// //defaultPolicy = null;
// aLog.debug("END ModuleController.getInstance().createPolicy: " + defaultPolicy);
// aLog.debug("#############################################2");
//
// } catch(Exception e) {
// aLog.error("error at creating default policy: " + e.getClass().toString() + ": " + e.getMessage(), e);
// }
// }
// } else {
// aLog.error("TODO create default policy and get namespace from somewhere different... ");
// }
// } else
// aLog.debug("ModuleController.getInstance() == null");
// }
// if (aLog.isDebugEnabled()) {
// aLog.debug("getDefaultPolicy: " + (defaultPolicy == null ? "NULL" : defaultPolicy.getName()));
// }
//
// return defaultPolicy;
// }
public PolicyWrapper getDefaultPolicyWrapper() {
return new PolicyWrapper(ModuleController.getInstance().getModelMap().getElement(getDefaultPolicy()));
}
private Set<PolicyWrapper> getUnrefinedPolicies() {
ModuleController moduleController = ModuleController.getInstance();
if (moduleController != null) {
List<Object> allPolicies = moduleController.getAllPolicies();
aLog.debug("found " + allPolicies.size() + " polices");
Set<PolicyWrapper> policies = new HashSet<PolicyWrapper>();
boolean default_exists = false;
for ( Object policy : allPolicies) {
PolicyWrapper policyWrapper = new PolicyWrapper(policy);
Collection refinedBy = policyWrapper.getRefinedBy();
if ( policyWrapper.getRefinedBy() == null || refinedBy.size() == 0 ) {
policies.add(policyWrapper);
}
if (SecureUmlConstants.DEFAULT_POLICY_NAME.equals(policyWrapper.getName())) {
default_exists = true;
if ( policyWrapper.getRefinedBy() != null && policyWrapper.getRefinedBy().size() > 0) {
aLog.error("INVALID DEFAULT POLICY! Policy with name " + SecureUmlConstants.DEFAULT_POLICY_NAME + " must not have a refining policy: " + policyWrapper.getRefinedByWrappers().iterator().next().getName() + "!");
}
}
}
if ( default_exists && policies.size() != 1) {
aLog.error("INVALID DEFAULT POLICY! Policy with name " + SecureUmlConstants.DEFAULT_POLICY_NAME + " must be the only one not being refined!");
}
return policies;
} else {
return null;
}
}
//public List<PolicyWrapper> getSortedPolicies() {
public List<UmlClass> getSortedPolicies() {
PolicyWrapper defaultPolicyWrapper = getDefaultPolicyWrapper();
//list which contains the end result
List<PolicyWrapper> sortedPolicies = new ArrayList<PolicyWrapper>();
//hash set for fast lookup, if a policy is already inserted
Set<PolicyWrapper> alreadyInserted = new HashSet<PolicyWrapper>();
if (defaultPolicyWrapper == null) {
aLog.debug("no default policy found... adding unrefined policies");
//hack... currently the adding of the policy requires a reload.. should be eleminated sooner or later..
alreadyInserted = getUnrefinedPolicies();
sortedPolicies.add(null);
for (PolicyWrapper pol : alreadyInserted) {
sortedPolicies.add(pol);
}
} else {
sortedPolicies.add(defaultPolicyWrapper);
alreadyInserted.add(defaultPolicyWrapper);//?? needed?
}
int start, end;
end = 0;
boolean added = true;
boolean allIn;
//as long as a policy has been added, restart a new round
while (added) {
// do only bother the policies inserted in the last round
start = end;
end = sortedPolicies.size();
added = false;
//clear all marks
// for every policy in the last round
for (int i = start; i < end; ++i) {
//get the policies which refine this policy
Collection<PolicyWrapper> refinesPolicies = sortedPolicies.get(i).getRefinesWrappers();
if ( refinesPolicies != null && refinesPolicies.size() > 0 ) {
//for all refining polices
for ( PolicyWrapper refines : refinesPolicies) {
//if the policy only is refined by one policy, we can add it
if ( refines.getRefinedBy().size() == 1) {
sortedPolicies.add(refines);
added = true;
} else {
allIn = true;
for ( PolicyWrapper supPol : refines.getRefinedByWrappers() ) {
if ( ! alreadyInserted.contains(supPol) ) {
allIn = false;
}
}
if ( allIn ) {
sortedPolicies.add(refines);
added = true;
}
}
}
}
}
//last, we add all this round added policies in the "lookup" set:
//we cannot add them during the main loop, as this would result in wrong loopups
// L0
// / | \
// L1 L2 L3
// | | |
// L4 | L5
// \ /
// L6
//should result in L0 -> L1 -> L2 -> L3 -> L4 -> L5 -> L6
// if we add L4 to alreadyInserted in the loop, the lookup for L6 says, that all
// refinedBy policies are already inserted, i.e., L6 is inserted (before L3)
// resulting in L0 -> L1 -> L2 -> L3 -> L4 -> L6 -> L5
if ( added ) {
for ( int i = end; i < sortedPolicies.size(); ++i ) {
alreadyInserted.add(sortedPolicies.get(i));
}
}
}
aLog.debug("getSortedPolicies: return " + sortedPolicies.size() + " policies");
//hack
ModelMap map = ModuleController.getInstance().getModelMap();
List<UmlClass> sortedPoliciesResolved = new ArrayList<UmlClass>();
for ( PolicyWrapper policy : sortedPolicies) {
sortedPoliciesResolved.add((UmlClass) map.getUmlElement(policy.getModelElement()));
}
return sortedPoliciesResolved;
}
// public static List<PolicyWrapper> getSortedPolicies() {
//
// ModuleController moduleController = ModuleController.getInstance();
//
// if ( moduleController == null ) {
// aLog.error("Received null for ModuleController");
// return new ArrayList<PolicyWrapper>();
// }
//
// List<Object> allPolicies = moduleController.getAllPolicies();
// aLog.debug("found " + allPolicies.size() + " polices");
//
// Set<PolicyWrapper> policies = new HashSet<PolicyWrapper>();
//
// for ( Object policy : allPolicies) {
// PolicyWrapper policyWrapper = new PolicyWrapper(policy);
// if ( policyWrapper.getRefined_by() != null ) {
// policies.add(policyWrapper);
// }
// }
// aLog.debug("found " + policies.size() + " not beeing refined");
//
//
//
// //TODO get default policy ?
// //GenericDialectModelMapper.getInstance().getDefaultPolicyWrapper();
//
// List<PolicyWrapper> sortedPolicies = new ArrayList<PolicyWrapper>();
//
//
// for ( PolicyWrapper policy : policies ) {
// sortedPolicies.add(policy);
// }
//
// int start, end;
// end = 0;
// boolean added = true;
//
// while (added) {
// start = end;
// end = sortedPolicies.size();
// for (int i = start; i < end; ++i) {
// for ( PolicyWrapper refines : sortedPolicies.get(i).getRefinesWrappers()) {
// if ( ! policies.contains(refines) ) {
// sortedPolicies.add(refines);
// policies.add(refines);
// added = true;
// }
// }
// }
// }
// return sortedPolicies;
// }
}

View File

@ -0,0 +1,78 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.modelmapping.permissions;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import ch.ethz.infsec.secureumlgui.wrapper.RoleWrapper;
/**
* A mapping from Roles to {@link ResourcePermissionsSet}s. In the
* end, this gives a mapping from roles and actions to the list of
* permissions the role has for the action.
*
* <pre>
* PermissionSet
*
* ||
*
* Role -> {@link ResourcePermissionsSet}
*
* ||
*
* Action -> {@link ActionPermissionSet}
*
* ||
*
* List&lt;{@link PermissionValue}&gt;
* {@link RoleWrapper}
* {@link ch.ethz.infsec.secureumlgui.wrapper.ActionWrapper}
* </pre>
*
*/
public class PermissionSet
{
Map<Object, ResourcePermissionsSet> permissions =
new LinkedHashMap<Object, ResourcePermissionsSet>();
/**
* returns the resource permission set associated to the roleWrapper's UML model element.
* creates a new, empty one, if necessary.
*/
public ResourcePermissionsSet getResourcePermissionsSet(RoleWrapper roleWrapper)
{
ResourcePermissionsSet result = permissions.get(roleWrapper.getModelElement());
if(result == null)
{
result = new ResourcePermissionsSet();
permissions.put(roleWrapper.getModelElement(), result);
}
return result;
}
/**
* creates a (copy) of the set of all role wrappers.
*/
public Set<RoleWrapper> getAllRoleWrappers()
{
Set<RoleWrapper> roleWrappers =
new LinkedHashSet<RoleWrapper>();
for (Iterator iter = permissions.keySet().iterator(); iter.hasNext();)
{
Object role = (Object) iter.next();
roleWrappers.add(new RoleWrapper(role));
}
return roleWrappers;
}
}

View File

@ -0,0 +1,564 @@
package ch.ethz.infsec.secureumlgui.modelmapping.permissions;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Set;
import java.util.Stack;
import org.apache.log4j.Logger;
import ch.ethz.infsec.secureumlgui.logging.MultiContextLogger;
import ch.ethz.infsec.secureumlgui.securemodelimpl.SecureModelFactory;
import ch.ethz.infsec.secureumlgui.wrapper.ActionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.PermissionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.RoleWrapper;
/**
* The value of a Permission (i.e., denied, granted, inherited, etc).
*
*/
public class PermissionValue implements Comparable<PermissionValue>
{
/**
* not permitted
*/
public static final int INT_DENIED = 0;
/**
* is permitted
*/
public static final int INT_GRANTED = 0x1;
/**
* is permitted, if the corresponding policy is active
*/
public static final int INT_EMERGENCY = 0x2;
/**
* inherited from a super role
*/
public static final int INT_INHERITED_ROLE = 0x10;
/**
* inherited from a super policy
*/
public static final int INT_INHERITED_POLICY = 0x100; //inherited
/**
* is inherited == INT_INHERITED_ROLE | INT_INHERITED_POLICY
*/
public static final int INT_INHERITED = INT_INHERITED_ROLE | INT_INHERITED_POLICY;
/**
* implicit, as a super action is permitted
*/
public static final int INT_IMPLICIT = 0x20;
/**
* implicit, as all sub actions are permitted
*/
public static final int INT_COMPOSITE = 0x40;
/**
* to the permission a constrained is assigned
*/
public static final int INT_CONSTRAINED = 0x80000000;
private int flags;
protected MultiContextLogger logger = MultiContextLogger.getDefault();
protected PermissionWrapper permission;
// may only be != null if INT_COMPOSITE
private Set<ActionWrapper> permittedSubActions;
/*
* may only be != null if
* => permission is NOT an explicit permission
* => OR cannot be DIRECTLY derivated form a explicit permissions
* ATTENTION: may be null AND permission cannot be derivated form a explicit permissions:
* this is the case, if the permission is COMPOSITE => permittedSubActions must be != null
*/
private LinkedHashMap<PermissionValue, Integer> permissionDerivation;
private static Logger aLog = Logger.getLogger(PermissionValue.class);
//counter for tmp permissions
private static int tmp_perm = 0;
@Override
public String toString() {
if (permission == null ) {
return "NO_PERMISSION";
}
StringBuffer buffer = new StringBuffer();
buffer.append(permission.getName());
buffer.append(" Role: ");
RoleWrapper role = permission.getRoleWrapper();
if ( role == null ) {
buffer.append("null");
} else {
buffer.append(role.getName());
}
buffer.append(" Action: ");
ActionWrapper action = permission.getActionWrapper();
if ( action == null ) {
buffer.append("null");
} else {
buffer.append(action.getName());
}
buffer.append(" flags: 0x");
buffer.append(Integer.toHexString(flags));
buffer.append(" subActions: ");
if (permittedSubActions == null) {
buffer.append("null");
} else {
buffer.append(permittedSubActions.size());
}
buffer.append(" derivationStack: ");
if (permissionDerivation == null) {
buffer.append("null");
} else {
buffer.append(permissionDerivation.size());
}
return buffer.toString();
}
/**
* creates a new GANTED permission
* @param permission
*/
public PermissionValue(PermissionWrapper permission) {
this.flags = INT_GRANTED;
this.permission = permission;
checkConstrained();
}
/**
* creates a new permission
* @param flags
* @param permission
*/
public PermissionValue(int flags, PermissionWrapper permission) {
this.flags = flags;
this.permission = permission;
checkConstrained();
}
private PermissionValue() {
}
/**
* create a new GRANTED Permission
* @param permission
* @return
*/
public static PermissionValue createGranted(PermissionWrapper permission) {
return new PermissionValue(permission);
}
/**
* creates a INHERITED BY ROLE Permission
* @param template
* @return
*/
public static PermissionValue createInheritedRole(PermissionValue template) {
return createDerived(template, INT_INHERITED_ROLE);
}
/**
* creates a INHERITED BY POLICY Permission
* @param template
* @return
*/
public static PermissionValue createInheritedPolicy(PermissionValue template) {
return createDerived(template, INT_INHERITED_POLICY);
}
/**
* creates a IMPLICIT Permission
* @param template
* @return
*/
public static PermissionValue createImplicite(PermissionValue template) {
return createDerived(template, INT_IMPLICIT);
}
/**
* creates a COMPOSITE Permission
* @param resourcePermissions currently unsed, but could be needed to calcuclate a correct flags
* @param action
* @param role
* @return
*/
public static PermissionValue createComposite(ResourcePermissionsSet resourcePermissions, ActionWrapper action, RoleWrapper role) {
//create a new SecureUML Permission and assign role and action
PermissionWrapper newPermission = new PermissionWrapper(SecureModelFactory.getInstance().createPermission("tmp_perm_" + ++tmp_perm));
newPermission.setAction(action.getModelElement());
newPermission.setRoleWrapper(role);
PermissionValue newPermVal = new PermissionValue();
newPermVal.permittedSubActions = action.getSubActionWrappers();
newPermVal.flags = INT_COMPOSITE;
newPermVal.permission = newPermission;
// //TODO collect the flags of the subactions! is not distinct...
// for ( ActionWrapper subaction : newPermVal.permittedSubActions ) {
// ActionPermissionSet actionPermissions = resourcePermissions.getPermissions(subaction);
// for ( PermissionValue permValue : actionPermissions.getPermissions() ) {
// newPermVal.flags |= permValue.flags;
// }
// }
// newPermVal.flags = ~(~newPermVal.flags | INT_GRANTED);
newPermVal.checkConstrained();
return newPermVal;
}
private static PermissionValue createDerived(PermissionValue template, int flag) {
int templ_flags = template.getFlags();
if ( (templ_flags & INT_GRANTED) > 0 ) { //can be directly derived from a explicit permission
return createByTemplate(template, ~(~templ_flags | INT_GRANTED) | flag);
}
else {
PermissionValue newPermVal = new PermissionValue();
newPermVal.permission = template.permission;
newPermVal.flags = template.flags | flag;
if (template.permissionDerivation != null ) {
newPermVal.permissionDerivation = (LinkedHashMap<PermissionValue, Integer>) template.permissionDerivation.clone();
} else {
newPermVal.permissionDerivation = new LinkedHashMap<PermissionValue, Integer>();
}
newPermVal.permissionDerivation.put(template, new Integer(flag));
return newPermVal;
}
}
private static PermissionValue createByTemplate(PermissionValue template, int flag) {
return new PermissionValue(template.flags | flag, template.getPermissionWrapper());
}
// public static PermissionValue createInheritedRole(PermissionValue template) {
// int templ_flags = template.getFlags();
// if ( (templ_flags & INT_GRANTED) > 0 ) { //can be directly derived from a explicit permission
// return createByTemplate(template, ~(~templ_flags | INT_GRANTED) | INT_INHERITED_ROLE);
// }
// else { //
// PermissionValue newPermVal = new PermissionValue();
// newPermVal.flags = template.flags | INT_INHERITED_ROLE;
// //newPermVal.permissionDerivation = new LinkedHashMap<PermissionValue>();
// if (template.permissionDerivation != null ) {
// newPermVal.permissionDerivation = (LinkedHashMap<PermissionValue, Integer>) template.permissionDerivation.clone();
//// for (PermissionValue permVal : template.permissionDerivation) {
//// newPermVal.permissionDerivation.add(permVal);
//// }
// } else {
// newPermVal.permissionDerivation = new LinkedHashMap<PermissionValue, Integer>();
// }
// newPermVal.permissionDerivation.put(template, new Integer(INT_INHERITED_ROLE));
//
//
//
// }
//
//
// return createByTemplate(template, INT_INHERITED_ROLE);
//}
//public static PermissionValue createInheritedPolicy(PermissionValue template) {
//return createByTemplate(template, INT_INHERITED_POLICY);
//}
public int getFlags() {
return flags;
}
@Deprecated
public int getValue() {
if ( (flags & INT_IMPLICIT ) > 0) {
return INT_IMPLICIT;
} else if ( (flags & INT_COMPOSITE) > 0) {
return INT_COMPOSITE;
} else if ( (flags & INT_INHERITED_ROLE) > 0) {
return INT_INHERITED_ROLE;
} else if ( (flags & INT_GRANTED ) > 0) {
return INT_GRANTED;
}
return flags;
}
// public void setFlags(int value)
// {
// this.flags = value;
// }
// public void addFlags(int flags) {
// this.flags |= flags;
// }
/**
* @return the suPermission
*/
public PermissionWrapper getPermissionWrapper()
{
return permission;
}
/**
* @param permissionWrapper the PermissionWrapper to set
*/
public void setPermissionWrapper(PermissionWrapper permissionWrapper)
{
this.permission = permissionWrapper;
}
/**
* checks if the encapsulated permission has a constrained
*/
private void checkConstrained() {
if ( (flags & INT_COMPOSITE) > 0 || permittedSubActions != null) {
boolean anyActionContrained = false;
for ( ActionWrapper action : permittedSubActions ) {
boolean anyPermissionUnConstrained = false;
for ( PermissionWrapper permission : action.getPermissionWrappers() ) {
if ( ! permission.isConstrained() ) {
anyPermissionUnConstrained = true;
break;
}
}
if ( ! anyPermissionUnConstrained ) {
anyActionContrained = true;
break;
}
}
if ( anyActionContrained ) {
flags |= INT_CONSTRAINED;
}
}
if ( permission.getAuthorizationConstraint() != null ) {
String constraint = permission.getAuthorizationConstraintWrapper().getConstraint();
if(constraint != null && constraint.length() != 0)
{
flags |= INT_CONSTRAINED;
}
}
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(PermissionValue o)
{
return new Integer(flags).compareTo(new Integer(o.getValue()));
}
// /* (non-Javadoc)
// * @see java.lang.Object#equals(java.lang.Object)
// */
// @Override
// public boolean equals(Object obj)
// {
// if (obj instanceof PermissionValue) {
// PermissionValue pv = (PermissionValue) obj;
//
// return (getValue() == pv.getValue()); //TODO realy? no matter of the permission?
// }
// else {
// return super.equals(obj);
// }
// }
@Override
public boolean equals(Object obj) {
if ( obj instanceof PermissionValue) {
PermissionValue pv = (PermissionValue) obj;
return (flags == pv.flags && permission.equals(pv.permission));
}
else {
return super.equals(obj);
}
}
public boolean isConstrained()
{
if ( (flags & PermissionValue.INT_CONSTRAINED) > 0 )
return true;
else {
return false;
}
}
public void setConstrained(boolean constrained)
{
if ( constrained ) {
flags |= INT_CONSTRAINED;
} else {
flags = ~( (~flags) | INT_CONSTRAINED); //TODO there must be a better way
}
}
public String getDescription() {
StringBuffer buffer = new StringBuffer();
String name;
if ( (flags & INT_COMPOSITE) > 0 ) {
buffer.append("COMPOSITE Permission, ");
} else if ( permission != null && (name = permission.getName()) != null && name.length() > 0 ) {
buffer.append(name);
buffer.append(" Permission, ");
}
if ( (flags & INT_INHERITED_ROLE) > 0 ) {
buffer.append("inherited from role: ");
buffer.append(permission.getRoleWrapper().getName());
buffer.append(", ");
}
if ( (flags & INT_INHERITED_POLICY) > 0 ) {
buffer.append("inherited from policy: ");
//buffer.append(permission.getPolicyWrapper().getName()); //TODO hel fix nullpointer
buffer.append(", ");
}
if ( (flags & INT_IMPLICIT) > 0 ) {
buffer.append("implicit from action: ");
buffer.append(permission.getActionWrapper().getResourceWrapper().getResourcePath());
buffer.append(".");
buffer.append(permission.getActionWrapper().getName());
buffer.append(", ");
}
if ( (flags & INT_COMPOSITE) > 0 ) {
buffer.append("implicit from all permitted subactions");
}
if(isConstrained()) {
buffer.append(" with Authorization Constraint");
}
return buffer.toString();
}
public Set<ActionWrapper> getPermittedSubActions() {
return permittedSubActions;
}
public void setPermittedSubActions(Set<ActionWrapper> permittedSubActions) {
if ( (flags & INT_COMPOSITE ) == 0 ) {
aLog.warn("Setting permittedSubActions, but Permission is not permitted through permitted subactions!");
}
this.permittedSubActions = permittedSubActions;
}
@Deprecated
public static PermissionValue create(PermissionValue template,
PermissionWrapper permissionWrapper, boolean constrained) {
PermissionValue pv = null;
pv = new PermissionValue(
template.getName(), template.getValue());
pv.setPermissionWrapper(permissionWrapper);
pv.setConstrained(constrained);
return pv;
}
@Deprecated
public static PermissionValue create(PermissionValue template,
PermissionWrapper permissionWrapper) {
boolean constrained = false;
if(permissionWrapper.getAuthorizationConstraint() != null)
{
String constraint = permissionWrapper.getAuthorizationConstraintWrapper().getConstraint();
if(constraint != null && constraint.length() != 0)
{
constrained = true;
}
}
return create(template, permissionWrapper, constrained);
}
@Deprecated
public String getName()
{
if ( (flags & INT_GRANTED ) > 0) {
return "Explicit";
} else if ( (flags & INT_INHERITED_ROLE) > 0) {
return "Inherited";
} else if ( (flags & INT_IMPLICIT) > 0) {
return "Implicit";
} else if ( (flags & INT_COMPOSITE ) > 0) {
return "Composite";
}
return "TODO_UNDEFIEND";
}
@Deprecated
public void setName(String name)
{
this.name = name;
}
@Deprecated
private String name;
@Deprecated
private boolean constrained = false;
@Deprecated
protected PermissionValue(String name, int value) {
this.name = name;
this.flags = value;
}
@Deprecated
public static final PermissionValue GRANTED =
new PermissionValue("Explicit", INT_GRANTED);
@Deprecated
public static final PermissionValue DENIED =
new PermissionValue("Denied", INT_DENIED);
// inherited from a super-role
@Deprecated
public static final PermissionValue INHERITED =
new PermissionValue("Inherited", INT_INHERITED_ROLE);
// implicitly granted by a composite action
@Deprecated
public static final PermissionValue IMPLICIT =
new PermissionValue("Implicit", INT_IMPLICIT);
// implicitly there, because permissions for all subactions are there (but not the composite action itself)
@Deprecated
public static final PermissionValue COMPOSITE =
new PermissionValue("Composite", INT_COMPOSITE);
}

View File

@ -0,0 +1,220 @@
package ch.ethz.infsec.secureumlgui.modelmapping.permissions;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;
import org.apache.log4j.Logger;
import ch.ethz.infsec.secureumlgui.modelmapping.permissions.HierarchicalPermissionsExplorer.CHANGES;
import ch.ethz.infsec.secureumlgui.wrapper.ActionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.PermissionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.PolicyWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.RoleWrapper;
public class PolicyPermissionSet {
Collection<PermissionValue> permissions =
new LinkedList<PermissionValue>();
private static Logger aLog = Logger.getLogger(PolicyPermissionSet.class);
private PolicyWrapper policy;
private PolicyWrapper explicitPolicyWrapper;
public PolicyPermissionSet(PolicyWrapper policy) {
this.policy = policy;
}
public void addPermission(PermissionValue permissionValue, CHANGES changeReason)
{
aLog.debug("add permission: " + permissionValue.getPermissionWrapper().getActionWrapper().getName() + " " + permissionValue.getPermissionWrapper().getRoleWrapper().getName() + " " + changeReason);
for (PermissionValue value : permissions ) {
if ( value.equals(permissionValue)) {
aLog.debug("Omitting redundant permission: already \nsaved: " + value + " \nnew: " + permissionValue);
return; //alredy here...
}
}
if ( changeReason == CHANGES.IMPLICIT_SUPER //if this is a new permission
&& isPermitted()
&& (permissionValue.getFlags() & PermissionValue.INT_GRANTED) == 0 ) {
aLog.debug("Omitting an implicit super permission: action already permitted and implicit super permission is not explicit!");
return;
}
permissions.add(permissionValue);
}
public void addExplicitPermission(PermissionValue permissionValue) {
addPermission(permissionValue);
}
private void addPermission(PermissionValue permissionValue) {
permissions.add(permissionValue);
}
public void addPermission(PermissionValue permissionValue, PermissionSet permissions_next, CHANGES changeReason, ActionWrapper action, RoleWrapper role) {
for (PermissionValue value : permissions ) {
if ( value.equals(permissionValue)) {
aLog.debug("Omitting redundant permission: already \nsaved: " + value + " \nnew: " + permissionValue);
return; //alredy here...
}
}
if ( changeReason == CHANGES.IMPLICIT_SUPER //if this is a new permission
&& isPermitted()
&& (permissionValue.getFlags() & PermissionValue.INT_GRANTED) == 0 ) {
aLog.debug("Omitting an implicit super permission: action already permitted and implicit super permission is not explicit!");
return;
}
if ( aLog.isDebugEnabled() ) {
aLog.debug(" addPermission to action: " + permissionValue + " changeReason: " + changeReason + " isPermitted: " + isPermitted());
}
PermissionWrapper permission = permissionValue.getPermissionWrapper();
switch ( changeReason ) {
case INHERITED:
//if change was caused by inerhitance, the implicit may change, i.e.,
Set<ActionWrapper> relatedActions = HierarchicalPermissionsExplorer.getSubAndSuperActionWrappersDeep(permission.getActionWrapper());
//RoleWrapper inh_role = permission.getRoleWrapper();
for ( ActionWrapper inh_action : relatedActions) {
aLog.debug(" Adding permission to next; action = " + inh_action.getName() + " role = " + role.getName());
//permissions_next.getResourcePermissionsSet(inh_role).getPermissions(inh_action).addPermission(permissionValue);
//TODO is CHANGES.INHERITED correct? not sure for now...
permissions_next.getResourcePermissionsSet(role).getPermissions(inh_action).addPermission(policy, permissionValue, changeReason);
}
break;
case IMPLICIT_SUPER://TODO for IMPLICIT_SUB we could "reroute" back and add a listener to do same stuff as inherited?
// relatedActions = HierarchicalPermissionsExplorer.getSubActionWrappersDeep(permission.getActionWrapper());
// inh_role = permission.getRoleWrapper();
// for ( ActionWrapper inh_action : relatedActions) {
// aLog.debug(" Adding permission to next; action = " + inh_action.getName());
// permissions_next.getResourcePermissionsSet(inh_role).getPermissions(inh_action).addPermission(permissionValue);
// }
// //NO BREAK! need to add "indicators" for sub roles too!
case IMPLICIT_SUB:
//if change was caused by an implicit, the inheritance may change, i.e.,
Set<RoleWrapper> superRoles = HierarchicalPermissionsExplorer.getSubRoleWrapperDeep(permission.getRoleWrapper());
//ActionWrapper imp_action = permission.getActionWrapper();
for ( RoleWrapper imp_role : superRoles ) {
aLog.debug(" Adding permission to next; role = " + imp_role.getName() + " action = " + action.getName());
//permissions_next.getResourcePermissionsSet(imp_role).getPermissions(imp_action).addPermission(permissionValue);
//TODO as above - is changeReson correct? not sure
permissions_next.getResourcePermissionsSet(imp_role).getPermissions(action).addPermission(policy, permissionValue, changeReason);
}
break;
}
//finally, add permission
permissions.add(permissionValue);
}
// /** returns GRANTED if the permission was explicitly defined,
// * DENIED in all other cases.
// */
// public PermissionValue getExplicitPermission()
// {
// PermissionValue result = PermissionValue.DENIED;
//
// for (PermissionValue pv : permissions)
// {
// //TODO ordering????? if ordering is not relevant, function can return in case of GRANTED
// if(pv.getValue() == PermissionValue.GRANTED.getValue()
// || pv.getValue() == PermissionValue.DENIED.getValue()) {
// result = pv;
// }
// }
// return result;
// }
public boolean isExplicitPermitted() {
for ( PermissionValue permission : permissions) {
if ( permission.getFlags() == PermissionValue.INT_GRANTED) {
return true;
}
}
return false;
}
public PermissionWrapper getExplicitPermittedPermission() {
for ( PermissionValue permission : permissions) {
if ( permission.getFlags() == PermissionValue.INT_GRANTED) {
return permission.getPermissionWrapper();
}
}
return null;
}
public boolean isPermitted() {
//TODO only on default permissions
if (permissions.size() > 0 )
return true;
else
return false;
}
public Collection<PermissionValue> getPermissions()
{
//TODO only default permissions
return permissions;
}
public PolicyWrapper getExplicitPolicyWapper() {
return explicitPolicyWrapper;
}
public void setExplicitPolicyWrapper(PolicyWrapper eplicitPolicyWrapper) {
this.explicitPolicyWrapper = eplicitPolicyWrapper;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
String resultString = "**";
for (Iterator iter = getPermissions().iterator(); iter.hasNext();)
{
PermissionValue pv = (PermissionValue) iter.next();
if(pv.equals(pv.GRANTED))
{
if(pv.isConstrained())
resultString += "(?)";
}
}
for (Iterator iter = getPermissions().iterator(); iter.hasNext();)
{
PermissionValue pv = (PermissionValue) iter.next();
if(!pv.equals(pv.GRANTED))
{
resultString += pv.getName().charAt(0);
if(pv.isConstrained())
resultString += "(?)";
}
}
return resultString;
}
}

View File

@ -0,0 +1,80 @@
package ch.ethz.infsec.secureumlgui.modelmapping.permissions;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import ch.ethz.infsec.secureumlgui.logging.MultiContextLogger;
import ch.ethz.infsec.secureumlgui.wrapper.ActionWrapper;
import ch.ethz.infsec.secureumlgui.wrapper.PolicyWrapper;
/**
* A mapping from actions to {@link ActionPermissionSet}s
*
*
*/
public class ResourcePermissionsSet {
Map<Object, ActionPermissionSet> resourcePermissions = new LinkedHashMap<Object, ActionPermissionSet>();
MultiContextLogger logger = MultiContextLogger.getDefault();
public void addPermission(ActionWrapper actionWrapper,
PermissionValue permissionValue, PolicyWrapper policy) {
ActionPermissionSet actionPermissions = getPermissions(actionWrapper);
if (actionPermissions == null) {
actionPermissions = new ActionPermissionSet();
resourcePermissions.put(actionWrapper.getModelElement(),
actionPermissions);
}
actionPermissions.addPermission(policy, permissionValue, HierarchicalPermissionsExplorer.CHANGES.EXPLICIT);
}
public ActionPermissionSet getPermissions(Object action) {
ActionPermissionSet result = resourcePermissions.get(action);
if (result == null) {
result = new ActionPermissionSet();
resourcePermissions.put(action, result);
result.setExplicitActionWrapper(new ActionWrapper(action));
}
return result;
}
public ActionPermissionSet getPermissions(ActionWrapper actionWrapper) {
ActionPermissionSet result = resourcePermissions.get(actionWrapper
.getModelElement());
if (result == null) {
result = new ActionPermissionSet();
resourcePermissions.put(actionWrapper.getModelElement(), result);
}
return result;
}
public Collection<Object> getActions() {
return resourcePermissions.keySet();
}
public ActionPermissionSet getPermissions(String actionShortname) {
for (Iterator iter = resourcePermissions.keySet().iterator(); iter
.hasNext();) {
ActionWrapper actionWrapper = ActionWrapper
.createActionWrapper(iter.next());
if (actionWrapper == null)
logger.error("actionWrapper == null");
if (actionShortname != null
&& actionShortname.equals(actionWrapper.getName())) {
return getPermissions(actionWrapper);
}
}
return new ActionPermissionSet();
}
}

View File

@ -0,0 +1,8 @@
<html>
<head>
<title></title>
</head>
<body>
Deals with Permissions and their hierarchy.
</body>
</html>

View File

@ -0,0 +1,32 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.modelmapping.strategies;
import java.util.LinkedHashSet;
import java.util.Set;
import org.omg.uml.foundation.core.ModelElement;
/**
*
* Mapping only the ModelElement itself - too simple.
* This way, composite actions cannot be considered
*/
public class MapSelf extends MappingScopeStrategy
{
/**
* @see ch.ethz.infsec.secureumlgui.modelmapping.strategies.MappingScopeStrategy#getMappingScope(org.omg.uml.foundation.core.ModelElement)
*
* @return Collection containing the @param modelElement as the only Member
*/
@Override
public Set<ModelElement> getMappingScope(ModelElement modelElement)
{
LinkedHashSet<ModelElement> result = new LinkedHashSet<ModelElement>();
result.add(modelElement);
return result;
}
}

View File

@ -0,0 +1,567 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.modelmapping.strategies;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Set;
import org.apache.log4j.Logger;
import org.argouml.model.Model;
import org.omg.uml.foundation.core.AssociationClass;
import org.omg.uml.foundation.core.Classifier;
import org.omg.uml.foundation.core.Generalization;
import org.omg.uml.foundation.core.ModelElement;
import org.omg.uml.foundation.core.Namespace;
import org.omg.uml.behavioralelements.statemachines.State;
import org.omg.uml.behavioralelements.statemachines.Transition;
import ch.ethz.infsec.secureumlgui.Util;
import ch.ethz.infsec.secureumlgui.modelmapping.GenericDialectHelper;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.AssociationEnd;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.DialectMetaModelInfo;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.InterResourceAssociation;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.MetaModelClass;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.ResourceType;
/**
*
*/
public class MapSelfAndAssociatedResources
extends SecureUmlMappingScopeStrategy
{
/**
*
*/
public MapSelfAndAssociatedResources(DialectMetaModelInfo mmInfo)
{
this.mmInfo = mmInfo;
}
DialectMetaModelInfo mmInfo;
/* (non-Javadoc)
* @see ch.ethz.infsec.secureumlgui.modelmapping.MappingScopeStrategy#getMappingScope(tudresden.ocl20.core.jmi.uml15.core.ModelElement)
*/
private int currentNavigationDepth = 6;
private int navigationDepth = 6;
public int getNavigationDepth()
{
return navigationDepth;
}
public void setNavigationDepth(int navigationDepth)
{
this.navigationDepth = navigationDepth;
this.currentNavigationDepth = navigationDepth;
}
Set<ModelElement> result;
private static Logger aLog = Logger.getLogger(MapSelfAndAssociatedResources.class);
@Override
public Set<ModelElement> getMappingScope(
ModelElement startingPoint)
{
System.out.println("---------------------------------");
if(currentNavigationDepth == navigationDepth)
result = super.getMappingScope(startingPoint);
currentNavigationDepth--;
// logger.info("navigationDepth = "+ navigationDepth);
// logger.info("currentNavigationDepth = "+ currentNavigationDepth);
if(currentNavigationDepth <= 0)
return new LinkedHashSet<ModelElement>();
result.add(startingPoint);
ResourceType rt = helper.getResourceType(startingPoint);
MetaModelClass mmc = null;
if(rt != null)
mmc = rt;
else
mmc = helper.getMetaModelClass(startingPoint);
aLog.debug("getMappingScope: " + startingPoint + ";" + rt);
if(helper.isSecureUmlRole(startingPoint))
{
Classifier roleClass = (Classifier) startingPoint;
Collection ends = Model.getFacade().getAssociationEnds(roleClass);
for (Iterator iter = ends.iterator(); iter.hasNext();)
{
org.omg.uml.foundation.core.AssociationEnd end = (org.omg.uml.foundation.core.AssociationEnd) iter.next();
org.omg.uml.foundation.core.AssociationEnd otherEnd = null;
Collection associationsEnds = end.getAssociation().getConnection();
for (Iterator iterator = associationsEnds.iterator(); iterator
.hasNext();)
{
org.omg.uml.foundation.core.AssociationEnd associationEnd = (org.omg.uml.foundation.core.AssociationEnd) iterator.next();
if(end != associationEnd) otherEnd = associationEnd;
}
if(otherEnd != null)
{
result.add(otherEnd);
Classifier otherParticipant = otherEnd.getParticipant();
//result.add(otherParticipant);
addMappingScope(otherParticipant, result);
}
}
Collection g = Model.getFacade().getGeneralizations(roleClass);
for(Iterator iter = g.iterator(); iter.hasNext();) {
Generalization gen = (Generalization) iter.next();
Classifier parent = (Classifier) gen.getParent();
Classifier child = (Classifier) gen.getChild();
if(parent!=roleClass && helper.isSecureUmlRole(parent)) {
addMappingScope(parent, result);
}
if(child!=roleClass && helper.isSecureUmlRole(child)) {
addMappingScope(child, result);
}
}
}
else if (helper.isSecureUmlPolicy(startingPoint)) {
Classifier policyClass = (Classifier) startingPoint;
Collection<org.omg.uml.foundation.core.AssociationEnd> ends = Model.getFacade().getAssociationEnds(policyClass);
for (org.omg.uml.foundation.core.AssociationEnd end : ends) {
org.omg.uml.foundation.core.AssociationEnd otherEnd = null;
for (org.omg.uml.foundation.core.AssociationEnd associationEnd : end.getAssociation().getConnection()) {
if ( end != associationEnd ) {
otherEnd = associationEnd;
}
}
if ( otherEnd != null ) {
result.add(otherEnd);
Classifier otherParticipant = otherEnd.getParticipant();
addMappingScope(otherParticipant, result);
}
}
Collection<Generalization> g = Model.getFacade().getGeneralizations(policyClass);
for (Generalization gen : g) {
Classifier parent = (Classifier) gen.getParent();
Classifier child = (Classifier) gen.getChild();
if ( parent != policyClass && helper.isSecureUmlPolicy(parent)) {
addMappingScope(parent, result);
}
if (child != policyClass && helper.isSecureUmlPolicy(child)) {
addMappingScope(child, result);
}
}
}
else if(helper.isSecureUmlPermission(startingPoint))
{
AssociationClass permissionAssociationClass =
(AssociationClass) startingPoint;
Collection ends = permissionAssociationClass.getConnection();
for (Iterator iter = ends.iterator(); iter.hasNext();)
{
org.omg.uml.foundation.core.AssociationEnd end =
(org.omg.uml.foundation.core.AssociationEnd) iter.next();
Classifier participant = end.getParticipant();
if(participant != null)
{
//result.add(participant);
addMappingScope(participant, result);
}
}
}
else if (mmc != null)
{
Collection associatedAssociations = helper.getDialectMetaModelInfo()
.getInterResourceAssociations(mmc);
// logger.info("found "+associatedAssociations.size()+" associations");
for (Iterator iter = associatedAssociations.iterator(); iter.hasNext();)
{
Object item = iter.next();
if (item instanceof InterResourceAssociation)
{
InterResourceAssociation association = (InterResourceAssociation) item;
AssociationEnd otherEnd = association.getOtherEnd(rt);
Collection c = helper.navigateAssociation(startingPoint, otherEnd);
// if (c instanceof Collection)
// {
if( c != null && c.size() > 0)
addModelElementsToScope(otherEnd, c);
// }
// else if (o instanceof ModelElement)
// {
// ModelElement associatedModelElement = (ModelElement) o;
//
// try
// {
// addModelElementToScope(otherEnd, associatedModelElement);
// }
// catch (Exception e)
// {
// ;
// }
//
// }
else //if (c == null)
{
logger.info("Association could not be navigated");
try
{
// Association could not be navigated
// - try it the other way round
AssociationEnd end = association
.getOtherEnd((MetaModelClass) otherEnd.getType());
Collection allElementsInNamespace = new LinkedList();
Namespace n = startingPoint.getNamespace();
if(n==null) {
//startingPoint doesn't have a namespace, so it has to be contained somewhere else:
//not complete, of course.
if(startingPoint instanceof State) {
n = ((State) startingPoint).getStateMachine().getNamespace();
} else if (startingPoint instanceof Transition) {
n = ((Transition) startingPoint).getStateMachine().getNamespace();
}
}
Collection c1 = n.getOwnedElement();
for (Iterator iterator = c1.iterator(); iterator.hasNext();)
{
Object temp = (Object) iterator.next();
allElementsInNamespace.add(temp);
}
if(startingPoint instanceof Namespace) {
logger.info("starting points is instance of Namespace");
Collection c2 = ((Namespace) startingPoint).getOwnedElement();
for (Iterator iterator = c2.iterator(); iterator.hasNext();) {
Object temp = (Object) iterator.next();
allElementsInNamespace.add(temp);
}
}
// logger.info(
// "try to navigate backwards from "
// + allElementsInNamespace.size()
// + " elements");
Set visitedElements =
tryNavigateBackwards(otherEnd, end,
allElementsInNamespace);//, getNavigationDepth());
logger.info("found "+visitedElements.size()+" elements by navigating backwards");
result.addAll(visitedElements);
//result.addAll(allElementsInNamespace);
}
catch (Exception e)
{
logger.logException(e);
}
}
}
}
// TODO: follow the associations defined in the metamodel
// along the umlGetter paths
}
else {
//logger.error("mmc = null");
}
// try
// {
// Set additionalScope = new LinkedHashSet();
// for (Iterator iter = result.iterator(); iter.hasNext();)
// {
// ModelElement item = (ModelElement) iter.next();
//
// Collection subScope = getMappingScope(item);
//
// additionalScope.addAll(subScope);
// }
// result.addAll(additionalScope);
// }
// catch (Exception e)
// {
// logger.logException(e);
// }
currentNavigationDepth++;
return result;
}
/* recursively find all Elements in mappingScope
*
*/
public void addMappingScope(ModelElement modelElement, Set<ModelElement> mappingScope)
{
if(mappingScope.contains(modelElement))
return;
aLog.debug("adding modelElement "+ modelElement + " to mapping scope");
mappingScope.add(modelElement);
Collection<ModelElement> additionalMappingScope =
getMappingScope(modelElement);
//mappingScope.addAll(additionalMappingScope);
for (Iterator iter = additionalMappingScope.iterator(); iter.hasNext();)
{
ModelElement m = (ModelElement) iter.next();
if(mappingScope.contains(m))
continue;
else
{
aLog.debug("adding modelElement_"+ m + " to mapping scope");
mappingScope.add(m);
//addMappingScope(m, mappingScope);
}
}
}
/**
* @param otherEnd
* @param associatedModelElement
*/
private void addModelElementToScope(AssociationEnd otherEnd, ModelElement associatedModelElement)
{
if (helper.hasType(associatedModelElement,
((MetaModelClass) otherEnd.getType()).getUmlClassName()))
{
//result.add(associatedModelElement);
addMappingScope(associatedModelElement, result);
//addMappingScope(associatedModelElement, result);
}
else
; // not the right Type
}
/**
* @param otherEnd
* @param c
*/
private void addModelElementsToScope(AssociationEnd otherEnd, Collection c)
{
//Collection c = (Collection) o;
for (Iterator iterator = c.iterator(); iterator.hasNext();)
{
ModelElement associatedModelElement = (ModelElement) iterator
.next();
try
{
addModelElementToScope(otherEnd, associatedModelElement);
}
catch (Exception e)
{
logger.logException(e);
}
}
}
/**
* @param otherEnd
* @param end
* @param modelElements
*/
private Set tryNavigateBackwards(
AssociationEnd otherEnd,
AssociationEnd end,
Collection modelElements)//,int maxDepth)
{
Set visitedElements = new LinkedHashSet();
tryNavigateBackwards(otherEnd, end, modelElements, visitedElements);
return visitedElements;
}
/**
* @param otherEnd
* @param end
* @param modelElements
*/
private void tryNavigateBackwards(AssociationEnd otherEnd, AssociationEnd end, Collection modelElements, Set visitedElements)
{
// if(maxDepth <= 0)
// return;
if(modelElements == null || modelElements.size() == 0)
return;
// logger.info(logger.MODELMAPPER_DETAILLED,
// "Try to navigate Association the other way round - "
// + "iterating over all ModelElements in the Namespace - n = "
// + modelElements.size());
for (Iterator iterator = modelElements.iterator(); iterator
.hasNext();)
{
Object object = iterator.next();
// if (object instanceof Namespace)
// {
// Namespace ns = (Namespace) object;
// tryNavigateBackwards(otherEnd, end, ns.getOwnedElement());
////
//// Util.addAllSave(allElementsInNamespace, ns.getOwnedElement());
// }
// TODO: replace this hardcoded hack by a generic solution
if (object instanceof ModelElement)
{
ModelElement m = (ModelElement) object;
if(visitedElements.contains(m))
return;
else
visitedElements.add(m);
if (helper.hasType(m, otherEnd.getType().getName()))
{
logger
.info("try to navigate Association in reverse Direction " +
"from end: "
+ otherEnd.getName());
Collection coll = helper.navigateAssociation(m, end);
String s = "... leads to: ";
if(coll.size()>1)
s = s + " Collection containing: ";
if(coll.size() > 0)
s = s + Util.getProperty(coll.iterator().next(), "name");//+ coll);
logger.info(s);
// if (coll instanceof Collection)
// {
if(coll != null)
{
//Collection c1 = (Collection) coll;
//addModelElementsToScope(otherEnd, coll);
addModelElementToScope(otherEnd, m);
}
// else if (c1 instanceof ModelElement)
// {
// try
// {
// addModelElementToScope(otherEnd, m);
// }
// catch (Exception e)
// {
// ;
// }
//
// }
}
else
{
//
// if(m instanceof Association)
// {
// Association a = (Association) m;
//
// tryNavigateBackwards(otherEnd, end, a.getConnection(), maxDepth/1);
//
////
//// Util.addAllSave(allElementsInNamespace, a.getConnection());
// }
// logger.info("wrong type: "
// + m.getClass().getSimpleName()
// + " : " + m.getName());
// logger.info(
// "can't reach the ModelElement directly, " +
// "try to reach it in several hops...");
// but can try to reach the source ModelElement via
// more than one step
MetaModelClass mmClass = helper.getMetaModelClass(m);
if(mmClass != null && mmClass.getUmlClassName() != null)
{
// logger.info("...from: "
// + m.getClass().getSimpleName()
// + " : "
// + m.getNameA());
Collection associations = mmInfo.getInterResourceAssociations(mmClass);
if(associations != null)
{
for (Iterator iter = associations.iterator(); iter.hasNext();)
{
InterResourceAssociation association = (InterResourceAssociation) iter.next();
Object result = helper.navigateAssociation(m, association.getOtherEnd(mmClass));
Collection coll;
if (result instanceof Collection)
{
coll = (Collection) result;
}
else
{
coll = new LinkedList();
coll.add(result);
}
visitedElements.addAll(coll);
//tryNavigateBackwards(otherEnd, end, coll, maxDepth-1);
tryNavigateBackwards(otherEnd, end, coll, visitedElements);
}
}
}
}
}
}
}
GenericDialectHelper helper = GenericDialectHelper.getInstance();
}

View File

@ -0,0 +1,36 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.modelmapping.strategies;
import java.util.LinkedHashSet;
import java.util.Set;
import org.omg.uml.foundation.core.ModelElement;
import ch.ethz.infsec.secureumlgui.logging.MultiContextLogger;
/**
*
*/
public abstract class MappingScopeStrategy
{
/** Method returns a Collection containing all ModelElements
* that need to be mapped when analyzing Permissions on the
* ModelElement @param modelElement
*
*
* @param startingPoint The analyzed ModelElement
* @return All ModelElements that need to be mapped
*/
public Set<ModelElement> getMappingScope(ModelElement startingPoint)
{
LinkedHashSet<ModelElement> result =
new LinkedHashSet<ModelElement>();
return result;
}
MultiContextLogger logger = MultiContextLogger.getDefault();
}

View File

@ -0,0 +1,55 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.modelmapping.strategies;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import org.argouml.model.Model;
import org.omg.uml.foundation.core.ModelElement;
/**
*
*/
public class SecureUmlMappingScopeStrategy
extends MappingScopeStrategy
{
/* (non-Javadoc)
* @see ch.ethz.infsec.secureumlgui.modelmapping.MappingScopeStrategy#getMappingScope(tudresden.ocl20.core.jmi.uml15.core.ModelElement)
*/
@Override
public Set<ModelElement> getMappingScope(
ModelElement startingPoint)
{
//if(modelElement != null)
{
// TODO: search for the Roles / Permissions to lie in Namespaces, too
Set<ModelElement> result = super.getMappingScope(startingPoint);
//Collection elementsInNamespace = modelElement.getNamespace().getOwnedElement();
// logger.info("There are " + elementsInNamespace.size()
// + " ModelElements in the Namespace where the Permissions / Roles lie");
//
// for (Iterator iter = elementsInNamespace.iterator(); iter.hasNext();)
// {
//
//
// ModelElement m = (ModelElement) iter.next();
//
// logger.info(" - " + m.getName());
//
// }
return result;
}
//else return null;
}
}

View File

@ -0,0 +1,7 @@
<html>
<head>
<title></title>
</head>
<body>Strategies that calculate which elements have to be mapped.
</body>
</html>

View File

@ -0,0 +1,19 @@
package ch.ethz.infsec.secureumlgui.securemodel;
import javax.jmi.reflect.RefPackage;
/**
* SecureModel package interface.
*
* <p><em><strong>Note:</strong> This type should not be subclassed or implemented
* by clients. It is generated from a MOF metamodel and automatically implemented
* by MDR (see <a href="http://mdr.netbeans.org/">mdr.netbeans.org</a>).</em></p>
*/
public interface SecureModelPackage extends RefPackage
{
/**
* Returns nested package SecureUml.
* @return Proxy object related to nested package SecureUml.
*/
public ch.ethz.infsec.secureumlgui.securemodel.secureuml.SecureUmlPackage getSecureUml();
}

View File

@ -0,0 +1,22 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel;
/**
*
*/
public class ActionKind
{
/**
*
*/
private ActionKind()
{
// TODO Auto-generated constructor stub
}
public static ActionKind ATOMIC = new ActionKind();
public static ActionKind COMPOSITE= new ActionKind();
}

View File

@ -0,0 +1,58 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel;
/**
*
*/
public class ActionResourceAssociation extends MetaModelAssociation
{
/**
*
*/
public ActionResourceAssociation(String shortName, ResourceType resourceType, ActionType actionType)
{
super(shortName);
this.shortname = shortName;
this.resourceType = resourceType;
this.actionType = actionType;
}
private String shortname;
public String getShortname()
{
return shortname;
}
public void setShortname(String name)
{
this.shortname = name;
}
private ResourceType resourceType;
public ResourceType getResourceType()
{
return resourceType;
}
public void setResourceType(ResourceType resourceType)
{
this.resourceType = resourceType;
}
private ActionType actionType;
public ActionType getActionType()
{
return actionType;
}
public void setActionType(ActionType actionType)
{
this.actionType = actionType;
}
}

View File

@ -0,0 +1,48 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel;
/**
*
*/
public class ActionType extends MetaModelEntity
{
/**
*
*/
protected ActionType()
{
}
private String shortName = null;
public String getShortName()
{
return shortName;
}
public void setShortName(String shortName)
{
this.shortName = shortName;
}
private String subactionsDefinition = null;
public String getSubactionsDefinition()
{
return subactionsDefinition;
}
public void setSubactionsDefinition(String subactionsDefinition)
{
this.subactionsDefinition = subactionsDefinition;
}
public String toString()
{
return getShortName();
}
}

View File

@ -0,0 +1,127 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel;
import ch.ethz.infsec.secureumlgui.Util;
/**
*
*/
public class AssociationEnd extends MetaModelEntity
{
public AssociationEnd()
{
}
/**
*
*/
public AssociationEnd(String name)
{
this.setName(name);
}
private boolean multiple;
public boolean isMultiple()
{
return multiple;
}
public void setMultiple(boolean multiple)
{
this.multiple = multiple;
}
private InterResourceAssociation owner;
public InterResourceAssociation getOwner()
/** The Association the AssociationEnd belongs to
*
*/
{
return owner;
}
public void setOwner(InterResourceAssociation association)
{
this.owner = association;
}
private MetaModelClass type;
public MetaModelClass getType()
/** The Classifier the Association End
* is attached to
*
*/
{
return type;
}
public void setType(MetaModelClass type)
{
this.type = type;
}
private String umlPropertyGetter;
public String getUmlPropertyGetter()
{
return umlPropertyGetter;
}
public void setUmlPropertyGetter(String umlPropertyGetter)
{
this.umlPropertyGetter = umlPropertyGetter;
}
/**
* @return The name of the Getter Method of this AssociationName
* (for the SecureUML Model)
*/
public String getGetterName()
{
if(getName() != null && getName().length() > 0)
return "get" + Util.capitalize(getName());
else
return null;
}
/**
* @return The name of the Setter Method of this AssociationEnd
* (for the SecureUML Model)
*/
public String getSetterName()
{
if(isMultiple())
// AssociationEnd is a Collection -> no Setter
return null;
else
return "set" + Util.capitalize(getName());
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
String string = "";
if(isMultiple())
string = string + "(*)";
else
string = string + "(1)";
string = string
+ "(" + getName() + ") ["
+ getUmlPropertyGetter()
+ "]" ;
return string;
}
}

View File

@ -0,0 +1,12 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel;
/**
*
*/
public class AtomicActionType extends ActionType
{
}

View File

@ -0,0 +1,13 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel;
/**
*
*/
public class CompositeActionType extends ActionType
{
}

View File

@ -0,0 +1,73 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel;
import java.util.ArrayList;
import java.util.Collection;
/**
*
*/
@Deprecated
public class ContainmentAssociation extends InterResourceAssociation
{
/**
*
*/
public ContainmentAssociation(String name,
AssociationEnd containerEnd, AssociationEnd contentsEnd)
{
super(name, containerEnd, contentsEnd);
this.setName(name);
this.containerEnd = containerEnd;
this.contentsEnd = contentsEnd;
}
private AssociationEnd containerEnd;
public AssociationEnd getContainerEnd()
{
return containerEnd;
}
public void setContainerEnd(AssociationEnd containerEnd)
{
this.containerEnd = containerEnd;
}
private AssociationEnd contentsEnd;
public AssociationEnd getContentsEnd()
{
return contentsEnd;
}
public void setContentsType(AssociationEnd contentsEnd)
{
this.contentsEnd = contentsEnd;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
String string =
getContainerEnd().getType().getName()
+ getContainerEnd().toString()
+ " ----"
+ getName()
+ "----> "
+ getContentsEnd().toString()
+ getContentsEnd().getType().getName();
return string;
}
}

View File

@ -0,0 +1,426 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import javax.jmi.model.MofPackage;
import ch.ethz.infsec.secureumlgui.Util;
import ch.ethz.infsec.secureumlgui.logging.MultiContextLogger;
/**
*
*/
public class DialectMetaModelInfo
{
MultiContextLogger logger = MultiContextLogger.getDefault();
/* Invariants:
* - Collections are never null
* - for each ResourceType in resourceTypes, there is a Mapping
* in actionTypesOfResourceType with a non-null value (Collection<ActionType>)
*/
/** the name of the design modeling language (e.g., ComponentUML, ControllerUML). */
private String dialectName = null;
public String getDialectName()
{
return dialectName;
}
public void setDialectName(String dialectName)
{
this.dialectName = dialectName;
}
/** the extent in which dialect metamodel instances are stored. */
private Object dialectExtent;
public Object getDialectExtent()
{
if(dialectExtent==null)
logger.error("dialectExtent = null");
return dialectExtent;
}
public void setDialectExtent(Object dialectExtent)
{
this.dialectExtent = dialectExtent;
}
/**
* Get the <code>dialectMetaExtent</code> value.
*
* @return a <code>MofPackage</code> value
*/
public final MofPackage getDialectMetaExtent() {
return dialectMetaExtent;
}
/**
* Set the <code>dialectMetaExtent</code> value.
*
* @param newDialectMetaExtent The new DialectMetaExtent value.
*/
public final void setDialectMetaExtent(final MofPackage newDialectMetaExtent) {
this.dialectMetaExtent = newDialectMetaExtent;
}
/**
* The extent for the dialect metamodel. Use this as a parameter
* for <code>MDRepository.createExtent()</code> to create an instanc of the
* dialect metamodel.
*/
private MofPackage dialectMetaExtent;
private Collection<ResourceType> resourceTypes = new ArrayList<ResourceType>();
public Collection<ResourceType> getResourceTypes()
{
return resourceTypes;
}
/**
*
*/
public ResourceType getResourceType(Object secureUmlElement)
{
if(secureUmlElement == null)
return null;
String umlClassName = secureUmlElement.getClass().getSimpleName();
for (ResourceType rt : resourceTypes)
{
if(umlClassName.indexOf('$') >= 0)
umlClassName = umlClassName.split("\\$")[0];
if(rt.getName().equals(umlClassName))
return rt;
}
return null;
}
// public void setResourceTypes(Collection<ResourceType> resourceTypes)
// {
// this.resourceTypes = resourceTypes;
// }
private Collection<MetaModelClass> metaModelClasses =
new ArrayList<MetaModelClass>();
public Collection<MetaModelClass> getMetaModelClasses()
{
return metaModelClasses;
}
// public Collection<MetaModelClass> getMappableMetaModelClasses()
// {
// Collection<MetaModelClass> result = new LinkedList<MetaModelClass>();
//
// for (Iterator iter = metaModelClasses.iterator(); iter.hasNext();)
// {
// MetaModelClass m = (MetaModelClass) iter.next();
//
// if(m.getUmlClassName() != null)
// result.add(m);
// }
//
// return result;
// }
public Collection<MetaModelClass> getResourceTypesAndMetaModelClasses()
{
Collection result = new LinkedList<MetaModelClass>();
Util.addAllSave(result, getMetaModelClasses());
Util.addAllSave(result, resourceTypes);
return result;
}
//
// public void setMetaModelClasses(Collection<MetaModelClass> metaModelClasses)
// {
// this.metaModelClasses = metaModelClasses;
// }
private Collection<ActionType> actionTypes = new ArrayList<ActionType>();
public Collection<ActionType> getActionTypes()
{
return actionTypes;
}
// public void setActionTypes(Collection<ActionType> actionTypes)
// {
// this.actionTypes = actionTypes;
// }
private Collection<AtomicActionType> atomicActionTypes = new ArrayList<AtomicActionType>();
public Collection<AtomicActionType> getAtomicActionTypes()
{
return atomicActionTypes;
}
// public void setAtomicActionTypes(Collection<AtomicActionType> atomicActionTypes)
// {
// this.atomicActionTypes = atomicActionTypes;
// }
private Collection<CompositeActionType> compositeActionTypes = new ArrayList<CompositeActionType>();
public Collection<CompositeActionType> getCompositeActionTypes()
{
return compositeActionTypes;
}
public ActionType getActionTypeByName(String name)
{
for (Iterator iter = actionTypes.iterator(); iter.hasNext();)
{
ActionType actiontype = (ActionType) iter.next();
if(actiontype.getName().equals(name))
{
return actiontype;
}
}
logger.info("action type "+name+" not found in DialectMetaModelInfo");
return null;
}
// public void setCompositeActionTypes(Collection<CompositeActionType> compositeActionTypes)
// {
// this.compositeActionTypes = compositeActionTypes;
// }
private Map<ResourceType, Collection<ActionResourceAssociation>> actionAssociationsOfResourceType = new LinkedHashMap<ResourceType, Collection<ActionResourceAssociation>>();
public Collection<ActionResourceAssociation> getResourceActionAssociations(ResourceType resourceType)
{
return actionAssociationsOfResourceType.get(resourceType);
}
public ResourceType getResourceTypeOfActionType(ActionType actionType)
{
return getResourceActionDependency(actionType).getResourceType();
}
private Map<MetaModelEntity, Set<InterResourceAssociation>>
interResourceAssociationsByEntity =
new LinkedHashMap<MetaModelEntity,
Set<InterResourceAssociation>>();
/**
* @return the interResourceAssociations
*/
public Collection<InterResourceAssociation> getInterResourceAssociations(MetaModelClass metaModelClass)
{
if(metaModelClass == null)
return null;
Set<InterResourceAssociation> result =
interResourceAssociationsByEntity.get(metaModelClass);
// if(result == null)
// {
// result = new LinkedHashSet<InterResourceAssociation>();
// interResourceAssociationsByEntity.put(metaModelClass, result);
// }
return result;
}
/**
* @return all InterResourceAssociations
* - in a newly created Collection
* (copied references to all Values from
* the Map 'interResourceAssociationsByEntity')
*/
public Collection<InterResourceAssociation> getInterResourceAssociations()
{
Collection<InterResourceAssociation> interResourceAssociations = new LinkedList<InterResourceAssociation>();
for (Iterator iter = interResourceAssociationsByEntity.keySet().iterator(); iter
.hasNext();)
{
MetaModelEntity key = (MetaModelEntity) iter.next();
Util.addAllSave(interResourceAssociations, interResourceAssociationsByEntity.get(key));
}
return interResourceAssociations;
}
/**
*
* @param name
* @return the created InterResourceAssociation
*/
public InterResourceAssociation addInterResourceAssociation(String name, MetaModelEntity anchor1, MetaModelEntity anchor2)
{
//logger.info("Adding inter-resource Association: " + name);
AssociationEnd end1 = new AssociationEnd();//containerEndName);
AssociationEnd end2 = new AssociationEnd();//contentsEndName);
// Default values - valid for UMLClasses
// containerEnd.setUmlPropertyGetter("getOwner");
// contentsEnd.setUmlPropertyGetter("getFeature");
InterResourceAssociation m = new InterResourceAssociation(name, end1, end2);
// add mapping for anchor 1
Set<InterResourceAssociation> mas = interResourceAssociationsByEntity.get(anchor1);
if(mas == null)
{
mas = new LinkedHashSet<InterResourceAssociation>();
interResourceAssociationsByEntity.put(anchor1, mas);
}
mas.add(m);
// add mapping for anchor 2
mas = interResourceAssociationsByEntity.get(anchor2);
if(mas == null)
{
mas = new LinkedHashSet<InterResourceAssociation>();
interResourceAssociationsByEntity.put(anchor2, mas);
}
mas.add(m);
return m;
//logger.info("added ContainmentAssociation: " + name);
}
// public void setActionTypesOfResourceTypes(Collection<ActionType> actionTypesOfResourceType)
// {
// this.actionTypesOfResourceType = actionTypesOfResourceType;
// }
private Map<ActionType, ActionResourceAssociation> dependencyOfActionType = new LinkedHashMap<ActionType, ActionResourceAssociation>();
public ActionResourceAssociation getResourceActionDependency(ActionType actionType)
{
return dependencyOfActionType.get(actionType);
}
public Collection<ActionType> getExplicitActionTypesOfResourceType(ResourceType resourceType)
{
Collection<ActionResourceAssociation> associations = getResourceActionAssociations(resourceType);
Collection<ActionType> actionTypes = new ArrayList<ActionType>();
if(associations != null)
{
for (Iterator iter = associations.iterator(); iter.hasNext();)
{
ActionResourceAssociation dependency = (ActionResourceAssociation) iter.next();
actionTypes.add(dependency.getActionType());
}
}
return actionTypes;
}
/** returns all ActionTypes defined for the
* resourceType, including the ActionTypes
* inherited from its parent ResourceType
*
*/
public Collection<ActionType> getActionTypesOfResourceType(ResourceType resourceType)
{
Collection<ActionType> actionTypes = getExplicitActionTypesOfResourceType(resourceType);
if(resourceType != null && resourceType.getParentResourceType() != null)
{
Collection<ActionType> inheritedActionTypes =
getActionTypesOfResourceType(resourceType.getParentResourceType());
actionTypes.addAll(inheritedActionTypes);
}
return actionTypes;
}
public ActionType getActionType(ResourceType resourceType, String shortname)
{
Collection<ActionType> actionTypes = getActionTypesOfResourceType(resourceType);
for (Iterator iter = actionTypes.iterator(); iter.hasNext();)
{
ActionType actionType = (ActionType) iter.next();
if(actionType.getShortName().equals(shortname))
return actionType;
}
return null;
}
public void addResourceType(ResourceType r)
{
resourceTypes.add(r);
actionAssociationsOfResourceType.put(r, new ArrayList<ActionResourceAssociation>());
//interResourceAssociationsByEntity.put(r, new LinkedHashSet<InterResourceAssociation>());
}
public void addMetaModelClass(MetaModelClass c)
{
metaModelClasses.add(c);
//actionAssociationsOfResourceType.put(c, new ArrayList<ResourceActionAssociation>());
interResourceAssociationsByEntity.put(c, new LinkedHashSet<InterResourceAssociation>());
}
public void addAtomicActionType(AtomicActionType a)
{
atomicActionTypes.add(a);
actionTypes.add(a);
}
public void addCompositeActionType(CompositeActionType c)
{
compositeActionTypes.add(c);
actionTypes.add(c);
}
public void addResourceActionAssociation(String name, ResourceType r, ActionType a)
{
if(dependencyOfActionType.containsKey(a))
{
logger.warn("Overwriting existing ResourceActionDependency!");
}
ActionResourceAssociation dependency = new ActionResourceAssociation(name, r, a);
dependencyOfActionType.put(a, dependency);
actionAssociationsOfResourceType.get(r).add(dependency);
}
}

View File

@ -0,0 +1,87 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel;
/**
*
*/
public class InterResourceAssociation extends MetaModelAssociation
{
/**
*
*/
public InterResourceAssociation(String name, AssociationEnd end1, AssociationEnd end2)
{
super(name);
this.end1 = end1;
this.end2 = end2;
end1.setOwner(this);
end2.setOwner(this);
}
private AssociationEnd end1;
public AssociationEnd getEnd1()
{
return end1;
}
public void setEnd1(AssociationEnd end1)
{
this.end1 = end1;
end1.setOwner(this);
}
private AssociationEnd end2;
public AssociationEnd getEnd2()
{
return end2;
}
public void setEnd2(AssociationEnd end2)
{
this.end2 = end2;
end2.setOwner(this);
}
/**
*
* @param mmClass
* @return the Association End which is
* not associated to mmEntity or 'null' if
* mmEntity is not an anchor of this Association
*/
public AssociationEnd getOtherEnd(MetaModelClass mmClass)
{
if(end1.getType() == mmClass)
return end2;
else if(end2.getType() == mmClass)
return end1;
else
return null;
}
public String toString()
{
String string =
getEnd1().getType().getName()
+ getEnd1().toString()
+ " ----"
+ getName()
+ "---- "
+ getEnd2().toString()
+ getEnd2().getType().getName();
return string;
}
}

View File

@ -0,0 +1,19 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel;
/**
*
*/
public class MetaModelAssociation extends MetaModelEntity
{
/**
*
*/
public MetaModelAssociation(String name)
{
super(name);
}
}

View File

@ -0,0 +1,68 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
/**
* A Metamodel Class which corresponds t an UML Class
*
* the corresponding UMLClass needs to be specified in the
* Metamodel by the Tag 'umlClassName'
*
*
*/
public class MetaModelClass extends MetaModelEntity
{
private String umlClassName;
public String getUmlClassName()
{
return umlClassName;
}
public void setUmlClassName(String umlClassName)
{
this.umlClassName = umlClassName;
}
private Collection<MetaModelClassAttribute> attributes =
new LinkedList<MetaModelClassAttribute>();
public Collection<MetaModelClassAttribute> getAttributes()
{
return attributes;
}
// public void setAttributes(Collection<ResourceTypeAttribute> attributes)
// {
// this.attributes = attributes;
// }
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
String resourceString = getName();
resourceString = resourceString
+ "\n umlClassName: " + getUmlClassName();
resourceString = resourceString + "\n Attributes: \n";
for (Iterator iter = getAttributes().iterator(); iter.hasNext();)
{
MetaModelClassAttribute rta = (MetaModelClassAttribute) iter.next();
resourceString = resourceString + " - " + rta.toString() + "\n";
}
return resourceString;
}
}

View File

@ -0,0 +1,91 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel;
import ch.ethz.infsec.secureumlgui.Util;
/**
*
*/
public class MetaModelClassAttribute extends MetaModelEntity
{
/**
*
*/
public MetaModelClassAttribute(String name)
{
super(name);
}
// /**
// * @return The name of the Getter Method of this Attribute
// */
// public String getUmlGetterName()
// {
// String getterPrefix;
// if(getTypeName().equals(MetaModelConst.TYPE_NAME_BOOLEAN))
// {
// getterPrefix = "is";
// }
// else
// {
// getterPrefix = "get";
// }
// if(getUmlName() != null && getUmlName().length() > 0)
// return getterPrefix + Util.capitalize(getUmlName());
// else if(getName() != null && getName().length() > 0)
// return getterPrefix + Util.capitalize(getName());
// else
// return null;
// }
// /**
// * @return The name of the Setter Method of this Attribute
// */
// public String getSetterName()
// {
// return "set" + Util.capitalize(getName());
// }
private String umlName;
public String getUmlName()
{
return umlName;
}
public void setUmlName(String umlName)
{
this.umlName = umlName;
}
private String typeName;
/** Name of the Type of the Attribute (e.g. 'String')
*
* @return the name of the type of the attribute
*/
public String getTypeName()
{
return typeName;
}
public void setTypeName(String typeName)
{
this.typeName = typeName;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
return getName() + " : " + getTypeName();
}
}

View File

@ -0,0 +1,50 @@
package ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel;
/**
* mainly contains names for tagged values that define the concrete
* syntax of a dialect metamodel.
*
*
*/
public class MetaModelConst
{
public final static String TAG_METAMODEL = "metamodel";
public final static String TAG_MODELELEMENT_STEREOTYPE =
"modelElementStereotype";
public final static String TAG_ANCHOR_PATH =
"anchorPath";
public final static String TAG_ACTION_STEREOTYPE =
"actionStereotype";
public final static String TAG_UML_PROPERTY_GETTER =
"umlPropertyGetter";
public final static String TAG_UML_CLASS_NAME =
"umlClassName";
public final static String TAG_RESOURCE_PATH =
"resourcePath";
public final static String TAG_ATTRIBUTE_UML_PROPERTY_NAME =
"umlPropertyName";
public final static String TAG_COMPOSITE_ACTION_SUBACTIONS_DEFINITION =
"subactionsDefinition";
public static final String TAG_SHORTNAME = "shortname";
public final static String SELF_PATH = "self";
public final static String MDR_IMPL_SUFFIX = "$Impl";
public final static String MDR_IMPL_SUFFIX_REGEXP = "\\$Impl";
public final static String ROLE_CLASS_NAME = "Role";
public final static String TYPE_NAME_BOOLEAN = "Boolean";
}

View File

@ -0,0 +1,40 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel;
/**
*
*/
public class MetaModelEntity
{
/**
*
*/
public MetaModelEntity()
{
}
/**
*
*/
public MetaModelEntity(String name)
{
this.name = name;
}
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}

View File

@ -0,0 +1,52 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel;
/**
*
*/
public class MetaModelFactory
{
/**
*
*/
private MetaModelFactory()
{
}
private static MetaModelFactory instance;
public static MetaModelFactory getInstance()
{
if(instance == null)
instance = new MetaModelFactory();
return instance;
}
// public ActionType createActionType(ActionKind actionKind)
// {
// if(actionKind == ActionKind.ATOMIC)
// return new AtomicActionType();
// else if(actionKind == ActionKind.COMPOSITE)
// return new CompositeActionType();
//
//
// else return null;
// }
public AtomicActionType createAtomicActionType()
{
return new AtomicActionType();
}
public CompositeActionType createCompositeActionType()
{
return new CompositeActionType();
}
}

View File

@ -0,0 +1,109 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
/**
*
*/
public class ResourceType extends MetaModelClass
{
/* ResourceType is directly derived from the SecureUML
* Class "Resource" <==> parentResourceType == null */
private ResourceType parentResourceType;
public ResourceType getParentResourceType()
{
return parentResourceType;
}
public void setParentResourceType(ResourceType parentResourceType)
{
this.parentResourceType = parentResourceType;
}
private String modelElementStereotype;
public String getModelElementStereotype()
{
return modelElementStereotype;
}
public void setModelElementStereotype(String anchorStereotype)
{
this.modelElementStereotype = anchorStereotype;
}
private String anchorPath;
public String getAnchorPath()
{
return anchorPath;
}
public void setAnchorPath(String anchorPath)
{
this.anchorPath = anchorPath;
}
private String actionStereotype;
public String getActionStereotype()
{
return actionStereotype;
}
public void setActionStereotype(String actionStereotype)
{
this.actionStereotype = actionStereotype;
}
private String resourcePath;
public String getResoucePath()
{
return resourcePath;
}
public void setResoucePath(String resourcePath)
{
this.resourcePath = resourcePath;
}
public String toString()
{
String resourceString = this.getName();
if(this.getParentResourceType() != null)
{
resourceString = resourceString
+ " inherit "
+ this.getParentResourceType().getName();
}
resourceString = resourceString
+ "\n Tags: "
+ "\n umlClassName: " + getUmlClassName()
+ "\n modelelementStereotype: " + getModelElementStereotype()
+ "\n anchorPath: " + getAnchorPath()
+ "\n actionStereotype: " + getActionStereotype()
+ "\n resourcePath: " + getResoucePath();
resourceString = resourceString + "\n Attributes:";
for (Iterator iter = getAttributes().iterator(); iter.hasNext();)
{
MetaModelClassAttribute rta = (MetaModelClassAttribute) iter.next();
resourceString = resourceString + "\n - " + rta.toString();
}
return resourceString;
}
}

View File

@ -0,0 +1,44 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel;
/**
*
*/
public class TaggedValue extends MetaModelEntity
{
/**
*
*/
public TaggedValue(String name, String value)
{
this.name = name;
this.value = value;
}
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
private String value;
public String getValue()
{
return value;
}
public void setValue(String value)
{
this.value = value;
}
}

View File

@ -0,0 +1,8 @@
<html>
<head>
<title></title>
</head>
<body>
Represents the information in a SecureUML dialect metamodel.
</body>
</html>

View File

@ -0,0 +1,233 @@
package ch.ethz.infsec.secureumlgui.securemodel.dialects.parser;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Iterator;
import javax.jmi.model.ModelPackage;
import javax.jmi.model.MofPackage;
import javax.jmi.reflect.RefClass;
import javax.jmi.reflect.RefPackage;
import org.apache.log4j.Logger;
import org.argouml.model.Model;
import org.netbeans.api.mdr.MDRManager;
import org.netbeans.api.mdr.MDRepository;
import org.netbeans.api.xmi.XMIReader;
import org.netbeans.api.xmi.XMIReaderFactory;
import org.netbeans.lib.jmi.mapping.FileStreamFactory;
import org.netbeans.lib.jmi.mapping.JMIMapperImpl;
import ch.ethz.infsec.secureumlgui.DialectMetamodelSelectedListener;
import ch.ethz.infsec.secureumlgui.SecureUmlModule;
import ch.ethz.infsec.secureumlgui.TabSecureUml;
//import ch.ethz.infsec.secureumlgui.gui.SecureUmlComponentManager;
import ch.ethz.infsec.secureumlgui.gui.SecureUmlPermissionComponent;
import ch.ethz.infsec.secureumlgui.gui.SecureUmlRoleComponent;
import ch.ethz.infsec.secureumlgui.gui.SecureUmlComponent;
import ch.ethz.infsec.secureumlgui.logging.MultiContextLogger;
import ch.ethz.infsec.secureumlgui.main.SecureUmlConstants;
import ch.ethz.infsec.secureumlgui.modelmanagement.ModelConst;
import ch.ethz.infsec.secureumlgui.modelmapping.GenericDialectHelper;
import ch.ethz.infsec.secureumlgui.modelmapping.GenericDialectModelMapper;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.DialectMetaModelInfo;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.ResourceType;
import ch.ethz.infsec.secureumlgui.securemodelimpl.SecureModelFactory;
/**
* loads metamodel from .xmi file and calls {@link
* DialectMetaModelAnalyzer}. The metamodel is assumed to have the
* following structure:
*
* <pre>
* ...
* (MOF) Model SecureModel
* |
* `--Package SecureUML (containing the SecureUML elements, like Role, Permission, Action)
* |
* `--Package &lt;DesignLanguage&gt; (containing the design modeling elements)
* |
* `--Package &lt;DesignLanguage&gt;Dialect (containing the action types and their associations to resources)
* ...
* </pre>
*
* Note that there can be arbitrary many other models in the .xmi
* file, as long as one is called "SecureModel" and containts the
* SecureUML dialect. The content of the .xmi file will be read into
* an extent also called (confusingly) "SecureModel". Note that this
* is not directly the metamodel that will be instantiated. The
* metamodel that will be instantiated is the package called
* "SecureModel" inside this extent. The extent for this instance will
* be called "mySecureModel".
*
*
*/
public class DialectMetaModelParser
implements DialectMetamodelSelectedListener
{
MultiContextLogger logger = MultiContextLogger.getDefault();
private static Logger aLog = Logger.getLogger(DialectMetaModelParser.class);
// /** the file name of the .xmi file containing the dialect metamodel */
// private String dialectMetamodelFilename;
// /** The dialect instance */
// private RefPackage mySecureModelPackage = null;
// /** The SecureModel extent */
// private ModelPackage secureModelExtent = null;
// /** The dialect metamodel package (SecureModel) inside the SecureModel extent */
// private MofPackage secureModelPackage = null;
public void dialectMetamodelSelected(File xmiFile)
{
//String dialectMetamodelFilename = xmiFile.getPath();
ModelPackage secureModelExtent = createMetamodelExtent();
MofPackage secureModelPackage = readMetamodel(secureModelExtent, xmiFile);
RefPackage mySecureModelPackage = createDialectInstanceExtent(secureModelPackage);
DialectMetaModelUtil.generateSrcFiles(mySecureModelPackage);
DialectMetaModelAnalyzer analyzer =
new DialectMetaModelAnalyzer(secureModelPackage);
DialectMetaModelInfo mmInfo = analyzer.analyzeDialect( secureModelPackage);
mmInfo.setDialectExtent(mySecureModelPackage);
mmInfo.setDialectMetaExtent(secureModelPackage);
DialectMetaModelUtil.printMetamodel(mmInfo);
GenericDialectHelper.getInstance().setDialectMetaModelInfo(mmInfo);
registerSuComponents(mmInfo);
GenericDialectModelMapper modelMapper =
new GenericDialectModelMapper(mmInfo);
// System.out.println("try to load Policy class");
// try {
// Class.forName("ch.ethz.infsec.secureumlgui.securemodel.secureuml.Policy");
// } catch (ClassNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
/**
* @param mmInfo
*/
private void registerSuComponents(DialectMetaModelInfo mmInfo)
{
TabSecureUml tab = SecureUmlModule.getTab();
SecureUmlRoleComponent suRoleComponent =
new SecureUmlRoleComponent();
tab.registerSecureUmlComponent(
SecureUmlConstants.getRoleResourceTypeDummy(),
suRoleComponent);
SecureUmlPermissionComponent suPermissionComponent =
new SecureUmlPermissionComponent();
tab.registerSecureUmlComponent(
SecureUmlConstants.getPermissionResourceTypeDummy(),
suPermissionComponent);
SecureUmlComponent suResourceComponent = new SecureUmlComponent();
for (Iterator iter = mmInfo.getResourceTypes().iterator(); iter.hasNext();)
{
ResourceType rt = (ResourceType) iter.next();
tab.registerSecureUmlComponent(rt,suResourceComponent);
}
}
/** creates dialect metamodel extent. Deletes any existing old
* dialect metamodel extent. Initializes {@link
* #secureModelExtent}.
*/
private ModelPackage createMetamodelExtent() {
aLog.debug("createMetamodelExtent");
MDRepository repository = MDRManager.getDefault().getDefaultRepository();
try {
Object oldExtent = repository.getExtent(ModelConst.SECUREMODEL_EXTENT_NAME);
if(oldExtent != null) {
repository.getExtent(ModelConst.SECUREMODEL_EXTENT_NAME).refDelete();
}
return (ModelPackage) repository.createExtent(ModelConst.SECUREMODEL_EXTENT_NAME);
} catch (Exception e) {
logger.error("error while creating dialect metamodel extent: "+e.getMessage());
return null;
}
}
/** reads the dialect metamodel .xmi file into {@link
* #secureModelExtent}, and returns the contained SecureModel
* package.
*/
private MofPackage readMetamodel(ModelPackage extent, File file) {
aLog.debug("readMetamodel " + extent + " from file " + file.getAbsolutePath());
MDRepository repository = MDRManager.getDefault().getDefaultRepository();
aLog.debug("here?");
XMIReader reader = XMIReaderFactory.getDefault().createXMIReader();
aLog.debug("here? b");
try {
FileInputStream inputstream = new FileInputStream(file);
Collection c = reader.read(inputstream, file.getPath(), extent);
aLog.debug("here? c");
for (Object item : c ) {
if(item instanceof javax.jmi.model.MofPackage) {
javax.jmi.model.MofPackage mofPackage = (javax.jmi.model.MofPackage) item;
aLog.debug("found: " + mofPackage.getName());
if (mofPackage.getName().equals(ModelConst.SECUREMODEL_PACKAGE_NAME)) {
return (javax.jmi.model.MofPackage) item;
}
}
}
} catch (Exception e) {
logger.error("error while reading metamodel file: "+e.getMessage());
}
return null;
}
/** creates the dialect instance extent. Initializes {@link #mySecureModelPackage}*/
private RefPackage createDialectInstanceExtent(MofPackage secureModelPackage) {
aLog.debug("createDialectInstanceExtent for MofPackage " + secureModelPackage.getName() + " (" + secureModelPackage + ")");
MDRepository repository = MDRManager.getDefault().getDefaultRepository();
RefPackage pack = repository.getExtent(ModelConst.SECUREMODEL_INSTANCE_NAME);
if(pack == null) {
try {
pack = repository.createExtent(ModelConst.SECUREMODEL_INSTANCE_NAME,
secureModelPackage);
} catch(Exception e) {
logger.error("error while creating dialect instance extent");
}
}
return pack;
}
}

View File

@ -0,0 +1,269 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.securemodel.dialects.parser;
import java.io.File;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.jmi.reflect.RefAssociation;
import javax.jmi.reflect.RefClass;
import javax.jmi.reflect.RefPackage;
import org.apache.log4j.Logger;
import org.netbeans.lib.jmi.mapping.FileStreamFactory;
import org.netbeans.lib.jmi.mapping.JMIMapperImpl;
import ch.ethz.infsec.secureumlgui.Util;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.ActionResourceAssociation;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.ActionType;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.CompositeActionType;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.DialectMetaModelInfo;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.InterResourceAssociation;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.MetaModelClass;
import ch.ethz.infsec.secureumlgui.securemodel.dialects.metamodel.ResourceType;
import ch.ethz.infsec.secureumlgui.logging.MultiContextLogger;
/**
*
*/
public class DialectMetaModelUtil
{
static MultiContextLogger logger = MultiContextLogger.getDefault();
private static Logger aLog = Logger.getLogger(DialectMetaModelUtil.class);
public static String getUri(String filename)
{
File xmiFile = new File(filename);
if(xmiFile.exists())
{
logger.info("XMI Metamodel found: " + filename);
}
else
{
logger.error("XMI Metamodel NOT found: " + filename);
return null;
}
return xmiFile.toURI().toString();
}
public static void generateSrcFiles(RefPackage mySecureModelPackage) {
File destDir = new File("generated");
destDir.mkdirs();
aLog.debug("generate mySecureModelPackage sources to: " + destDir.getAbsolutePath());
JMIMapperImpl mapperImpl = new JMIMapperImpl();
FileStreamFactory fileStreamFactory = new FileStreamFactory(destDir);
Collection<RefPackage> packages = (Collection<RefPackage>) mySecureModelPackage.refAllPackages();
try {
for (RefPackage packa : packages ) {
aLog.debug("Generate package: " + packa);
mapperImpl.generate(fileStreamFactory, packa.refMetaObject());
for ( RefClass cl : (Collection<RefClass>) packa.refAllClasses() ) {
aLog.debug("Generate class: " + cl);
mapperImpl.generate(fileStreamFactory, cl.refMetaObject());
}
for ( RefAssociation ass : (Collection<RefAssociation>) packa.refAllAssociations()) {
aLog.debug("Generate association: " + ass);
mapperImpl.generate(fileStreamFactory, ass.refMetaObject());
}
}
} catch (Exception e) {
e.printStackTrace();
aLog.error(e);
}
}
public static DialectMetaModelInfo printMetamodel(DialectMetaModelInfo metaModelInfo)
{
// for ( Object cont : metaModelInfo.getDialectMetaExtent().getContents() ) {
// if ( cont instanceof javax.jmi.model.Tag ) {
// javax.jmi.model.Tag cont2 = (javax.jmi.model.Tag ) cont;
// if ( cont2.getName().equals("umlClassName")) {
// List cont3 = cont2.getQualifiedName();
// for ( Object cont4 : cont3) {
// System.out.println(cont4.getClass() + "." + cont4.toString());
// }
// }
// }
// }
//
// for ( MetaModelClass mmc : metaModelInfo.getMetaModelClasses() ) {
//
// System.out.println("MetaModelClass: " + mmc.getName() + ", " + mmc.getUmlClassName());
//
// }
// DialectMetaModelParser parser =
// new DialectMetaModelParser(metamodelFilename);
//
// ModelPackage modelPackage;
//
//
// metamodelTopPackage = parser.loadMetamodel();
//
//
//
// //logger.info("Package type: " + topPkg.toString());
//
// //mmTester.traverseMofMetamodel();
//
// //mmTester.printDialectStuff();
//
// metaModelInfo = parser.analyzeDialect(metamodelTopPackage);
// logger.info("## Protected Resource Types ##");
// printResourcesTypes(metaModelInfo.getResourceTypes(), metaModelInfo);
// logger.info("## Atomic Action Types ##");
// printActionsTypes(metaModelInfo.getAtomicActionTypes());
// logger.info("## Composite Action Types ##");
// printActionsTypes(metaModelInfo.getCompositeActionTypes());
// logger.info("## other Metamodel Classes ##");
// printMappableMetaModelClasses(metaModelInfo.getMetaModelClasses());
// logger.info("## Resource-Action Associations##");
// printResourceActionAssociations(metaModelInfo);
// logger.info("## Inter Resource Associations ##");
// printInterResourceAssociations(metaModelInfo);
return metaModelInfo;
// produces ClassCastException within org.netbeans.mdr.NBMDRepositoryImpl.createExtent
// try
// {
// RepositoryManager.getRepository().createModel("test", metamodelTopPackage);
// }
// catch (Exception e)
// {
// logger.logException(e);
// }
//
}
public static void printResourcesTypes(Collection<ResourceType> resourceTypes, DialectMetaModelInfo mmInfo)
{
for (Iterator iter = resourceTypes.iterator(); iter.hasNext();)
{
ResourceType resourceType = (ResourceType) iter.next();
String resourceString = resourceType.toString();
logger.info("Resource: " + resourceString);
printActionsTypes(mmInfo.getActionTypesOfResourceType(resourceType), " ");
}
}
public static void printMetaModelClasses(Collection<MetaModelClass> metaModelClasses)
{
for (Iterator iter = metaModelClasses.iterator(); iter.hasNext();)
{
MetaModelClass metaModelClass = (MetaModelClass) iter.next();
String classString = metaModelClass.toString();
logger.info("MetaModelClass: " + classString);
//printActionsTypes(mmInfo.getActionTypesOfResourceType(metaModelClass), " ");
}
}
public static void printMappableMetaModelClasses(Collection<MetaModelClass> metaModelClasses)
{
for (Iterator iter = metaModelClasses.iterator(); iter.hasNext();)
{
MetaModelClass metaModelClass = (MetaModelClass) iter.next();
String classString = metaModelClass.toString();
if(metaModelClass.getUmlClassName() != null)
logger.info("MetaModelClass: " + classString);
//printActionsTypes(mmInfo.getActionTypesOfResourceType(metaModelClass), " ");
}
}
public static void printActionsTypes(Collection actionTypes)
{
printActionsTypes(actionTypes, "");
}
public static void printActionsTypes(Collection actionTypes, String prefix)
{
if(actionTypes != null)
for (Iterator iter = actionTypes.iterator(); iter.hasNext();)
{
try
{
ActionType actionType = (ActionType) iter.next();
String loggerString = prefix + "Action: " + actionType.getName();
if (actionType instanceof CompositeActionType)
{
CompositeActionType compositeActionType = (CompositeActionType) actionType;
loggerString +=
" - SubactionsDefinition: "
+ compositeActionType.getSubactionsDefinition();
}
logger.info(loggerString);
}
catch (Exception e)
{
logger.logException(e);
}
}
}
public static void printResourceActionAssociations(DialectMetaModelInfo mmInfo)
{
for (Iterator iter = mmInfo.getResourceTypes().iterator(); iter.hasNext();)
{
ResourceType resourceType = (ResourceType) iter.next();
for (Iterator iterator = mmInfo.getResourceActionAssociations(resourceType).iterator(); iterator.hasNext();)
{
ActionResourceAssociation raDependency = (ActionResourceAssociation) iterator.next();
logger.info(raDependency.getResourceType().getName()
+ " ----"
+ raDependency.getShortname()
+ "----> "
+ raDependency.getActionType().getName());
}
}
}
public static void printInterResourceAssociations(DialectMetaModelInfo mmInfo)
{
for (Iterator iter = mmInfo.getInterResourceAssociations().iterator(); iter.hasNext();)
{
InterResourceAssociation interResourceAssociation = (InterResourceAssociation) iter.next();
logger.info(interResourceAssociation.toString());
}
}
}

View File

@ -0,0 +1,27 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.securemodel.dialects.parser.oclexpressions;
/**
*
*/
public abstract class BooleanExpression extends ExpressionFragment
{
private boolean negated = false;
/** is the expression of form (not (...)
* - Default is 'false'
* @return true if the expression is negated.
*/
public boolean isNegated()
{
return negated;
}
public void setNegated(boolean negated)
{
this.negated = negated;
}
}

View File

@ -0,0 +1,41 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.securemodel.dialects.parser.oclexpressions;
/**
*
*/
public class BooleanLiteral extends Literal
{
/**
*
*/
public BooleanLiteral(boolean value)
{
this.value = value;
}
private boolean value;
public boolean getValue()
{
return value;
}
public void setValue(boolean value)
{
this.value = value;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
return "BooleanLiteral("
+ (value?"true":"false")
+ ")";
}
}

View File

@ -0,0 +1,41 @@
/**
*
*/
package ch.ethz.infsec.secureumlgui.securemodel.dialects.parser.oclexpressions;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
/**
*
*/
public class ConjunctiveBooleanExpression extends BooleanExpression
{
private Collection<ExpressionFragment> terms
= new LinkedList<ExpressionFragment>();
public Collection<ExpressionFragment> getTerms()
{
return terms;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
String s = "ConjunctiveBooleanExpression( ";
for (Iterator iter = terms.iterator(); iter.hasNext();)
{
ExpressionFragment term = (ExpressionFragment) iter.next();
s += term.toString();
}
s += " )";
return s;
}
}

Some files were not shown because too many files have changed in this diff Show More