From 8caf827ca553efd474b6c2dfda1f4a8b41f931f4 Mon Sep 17 00:00:00 2001
From: Nikolaus Huber <nikolaus.huber@uni-wuerzburg.de>
Date: Tue, 14 May 2013 09:11:58 +0000
Subject: [PATCH] refactorings

git-svn-id: https://se1.informatik.uni-wuerzburg.de/usvn/svn/code/code/DMM/trunk@11534 9e42b895-fcda-4063-8a3b-11be15eb1bbd
---
 .../adaptation/AdaptationControl.java         |  44 +++---
 .../descartes/adaptation/TacticExecutor.java  | 136 +++++++++---------
 .../model/dmm/DmmModelActionHandler.java      |   2 +-
 .../model/dmm/util/DmmModelChanger.java       |  10 +-
 4 files changed, 98 insertions(+), 94 deletions(-)

diff --git a/edu.kit.ipd.descartes.adaptation/src/edu/kit/ipd/descartes/adaptation/AdaptationControl.java b/edu.kit.ipd.descartes.adaptation/src/edu/kit/ipd/descartes/adaptation/AdaptationControl.java
index 050652fb..26ae6d5b 100644
--- a/edu.kit.ipd.descartes.adaptation/src/edu/kit/ipd/descartes/adaptation/AdaptationControl.java
+++ b/edu.kit.ipd.descartes.adaptation/src/edu/kit/ipd/descartes/adaptation/AdaptationControl.java
@@ -30,20 +30,19 @@ public class AdaptationControl {
 
 	public enum EventType {
 	    SLA_VIOLATION ("SlaViolatedEvent", "12345"),
-	    SCHEDULED_MAINTENANCE ("ScheduledMaintenanceEvent", "_H_MTgIAnEeKW2vVcg5ekRw"),
+	    SCHEDULED_OPTIMIZATION ("ScheduledOptimizationEvent", "_H_MTgIAnEeKW2vVcg5ekRw"),
 	    BOTTLENECK_FOUND ("BottleneckFoundEvent", "_VvZEwKEoEeKDl52Xojo4CQ");
 
 	    private final String name;   
-	    private final String id; 
-	    
+        private final String id; 
 	    EventType(String name, String id) {
 	        this.name = name;
 	        this.id = id;
 	    }
-
+	    
         public static EventType getEventType(String eventTypeName) {
             if (eventTypeName.equals(SLA_VIOLATION.name)) return SLA_VIOLATION;
-            if (eventTypeName.equals(SCHEDULED_MAINTENANCE.name)) return SCHEDULED_MAINTENANCE;
+            if (eventTypeName.equals(SCHEDULED_OPTIMIZATION.name)) return SCHEDULED_OPTIMIZATION;
             if (eventTypeName.equals(BOTTLENECK_FOUND.name)) return BOTTLENECK_FOUND;
             return null;
         }
@@ -54,7 +53,7 @@ public class AdaptationControl {
 	private static final String PROP_PERF_DATA_REPO_XMI_FILE_PATH_NAME = "performanceDataRepositoryModel";
     private static final String PROP_ADAPTATION_PROCESS_NAME = "processName";
     private static final String PROP_MAX_ITERATIONS = "maxIterations";
-    private static final String PROP_TRIGGERING_EVENT_TYPE = "event";
+    private static final String PROP_TRIGGERING_EVENT_TYPE = "eventType";
 	
 	private static Logger logger = Logger.getLogger(AdaptationControl.class);
 
@@ -92,7 +91,19 @@ public class AdaptationControl {
 		adaptationController.doAdaptation(triggeringEvent);
 	}
 	
-	public void init() {
+	private void loadProperties(String propertiesFilePath) throws IOException {
+        Properties properties = new Properties();
+        FileInputStream  propFile = new FileInputStream(propertiesFilePath);
+        properties.load(propFile);
+        logger.debug("Loaded properties of " + properties.getProperty(PROP_ADAPTATION_PROCESS_NAME));
+        adaptationProcessXmiFilePath=properties.getProperty(PROP_ADAPTATION_PROCESS_XMI_FILE_PATH_NAME);
+        performanceDataRepoXmiFilePath=properties.getProperty(PROP_PERF_DATA_REPO_XMI_FILE_PATH_NAME);
+        maxIterations=Integer.parseInt(properties.getProperty(PROP_MAX_ITERATIONS));
+        eventType=properties.getProperty(PROP_TRIGGERING_EVENT_TYPE).trim();
+        logger.debug("Maximum iterations till abort: " + maxIterations);
+    }
+
+    public void init() {
 		try {
 		    loadProperties(DEFAULT_PROP_FILE_PATH);
 			adaptationProcess = adaptationProcessModelManager.load(URI
@@ -112,6 +123,11 @@ public class AdaptationControl {
     private Event createTriggeringEvent() {
         EventType type = EventType.getEventType(eventType);
         
+        if(type==null) {
+            logger.error("Could not create event " + eventType);
+            abort();
+        }
+        
         Event triggeringEvent = AdaptationFactory.eINSTANCE.createEvent();
         triggeringEvent.setName(type.name);
         triggeringEvent.setId(type.id);
@@ -119,19 +135,7 @@ public class AdaptationControl {
         return triggeringEvent;
     }
 
-	private void loadProperties(String propertiesFilePath) throws IOException {
-	    Properties properties = new Properties();
-	    FileInputStream  propFile = new FileInputStream(propertiesFilePath);
-	    properties.load(propFile);
-	    logger.debug("Loaded properties of " + properties.getProperty(PROP_ADAPTATION_PROCESS_NAME));
-	    adaptationProcessXmiFilePath=properties.getProperty(PROP_ADAPTATION_PROCESS_XMI_FILE_PATH_NAME);
-	    performanceDataRepoXmiFilePath=properties.getProperty(PROP_PERF_DATA_REPO_XMI_FILE_PATH_NAME);
-	    maxIterations=Integer.parseInt(properties.getProperty(PROP_MAX_ITERATIONS));
-	    eventType=properties.getProperty(PROP_TRIGGERING_EVENT_TYPE);
-	    logger.debug("Maximum iterations till abort: " + maxIterations);
-    }
-
-    public void doAdaptation(Event triggeringEvent) {
+	public void doAdaptation(Event triggeringEvent) {
 
 		// Determine the suitable strategy via the objective
 		// which is currently implemented as the first element
diff --git a/edu.kit.ipd.descartes.adaptation/src/edu/kit/ipd/descartes/adaptation/TacticExecutor.java b/edu.kit.ipd.descartes.adaptation/src/edu/kit/ipd/descartes/adaptation/TacticExecutor.java
index 1b0526cf..77d1d8e8 100644
--- a/edu.kit.ipd.descartes.adaptation/src/edu/kit/ipd/descartes/adaptation/TacticExecutor.java
+++ b/edu.kit.ipd.descartes.adaptation/src/edu/kit/ipd/descartes/adaptation/TacticExecutor.java
@@ -35,6 +35,47 @@ public class TacticExecutor {
 	}
 	
 	/**
+     * Applies the the given tactic.
+     * 
+     * @param currentTactic
+     *            The tactic to execute
+     * @return
+     */
+    public void applyTactic(WeightedTactic weightedTactic) {
+    	try {
+            executeAdaptationPlan(weightedTactic.getUsedTactic().getImplementedPlan());
+            logger.info("Tactic " + weightedTactic.getUsedTactic().getName()
+                    + " successfully applied.");
+            hist.add(weightedTactic, TacticsHistory.NO_RESULT, true);
+    
+            // if this point is reached everything was fine, so persist them (save the models)
+            dmmModelActionHandler.persistActions();
+            return;
+        } catch (OperationNotPerformedException e) {
+    		logger.error("Tactic " + weightedTactic.getUsedTactic().getName()
+    				+ " could not be executed. Please check adaptation plan and/or log files for errors.", e);
+    		weightedTactic.setCurrentWeight(0.0);
+    		hist.add(weightedTactic, TacticsHistory.NO_RESULT, false);
+            /*
+             * TODO Something went wrong. 
+             * 1) Detect error 
+             * 2) reevaluate tactics
+             * 3) apply different tactic.
+             */
+        }
+    }
+
+    private StartAction findStartAction(AdaptationPlan plan) {
+    	for (AbstractControlFlowElement abstractControlFlowElement : plan.getSteps()) {
+    		// Find start of adaptation plan
+    		if (abstractControlFlowElement instanceof StartAction) {
+    			return (StartAction) abstractControlFlowElement;
+    		}
+    	}
+    	return null;
+    }
+
+    /**
      * Executes the given {@link AdaptationPlan}.
      * 
      * @param plan
@@ -57,16 +98,6 @@ public class TacticExecutor {
         logger.info("Adaptation plan of adaptation plan <<" + plan.getName() + ">> terminated.");
     }
 
-	private StartAction findStartAction(AdaptationPlan plan) {
-		for (AbstractControlFlowElement abstractControlFlowElement : plan.getSteps()) {
-			// Find start of adaptation plan
-			if (abstractControlFlowElement instanceof StartAction) {
-				return (StartAction) abstractControlFlowElement;
-			}
-		}
-		return null;
-	}
-
 	private void executeNextStep(AbstractControlFlowElement step)
 			throws OperationNotPerformedException, InvalidAdaptationPlan {
 	    
@@ -90,15 +121,38 @@ public class TacticExecutor {
 		executeNextStep(step.getSuccessor());
 	}
 
+    private void executeReferredAction(AbstractControlFlowElement step) throws OperationNotPerformedException {
+        ActionReference ref = (ActionReference) step;
+        Action action = ref.getRefersTo();
+        logger.info("Executing action <<" + action.getName() + ">>.");
+        AdaptationPoint currentAdaptationPoint = action
+        		.getReferredAdaptationPoint();
+    
+        dmmModelActionHandler.execute(currentAdaptationPoint,
+        		action.getAdaptationActionOperation());
+    }
+
     private void executeBranchAction(AbstractControlFlowElement branchAction) throws OperationNotPerformedException {
         BranchAction branch = (BranchAction) branchAction;
-        if (isTrue(branch.getContext(), branch.getCondition()))
+        if (isBranchConditionTrue(branch.getContext(), branch.getCondition()))
             executeAdaptationPlan(branch.getConditionTrueBranch());
         else
             executeAdaptationPlan(branch.getConditionFalseBranch());
     }
 
-    private boolean isTrue(EObject obj, String branchCondition) {
+    private void execLoopAction(AbstractControlFlowElement loopAction) throws OperationNotPerformedException {
+        LoopAction loop = (LoopAction) loopAction;
+        int numberOfIterations = loop.getCounter();
+        int i = 1;
+    
+        while (i <= numberOfIterations) {
+            logger.debug("Executing iteration " + i + " of loop action " + loop.getBody().getName());
+            executeAdaptationPlan(loop.getBody());
+            i++;
+        }
+    }
+
+    private boolean isBranchConditionTrue(EObject obj, String branchCondition) {
 
         EClass context = null;
 
@@ -119,62 +173,4 @@ public class TacticExecutor {
         return invariant;
     }
 
-    private void executeReferredAction(AbstractControlFlowElement step) throws OperationNotPerformedException {
-        ActionReference ref = (ActionReference) step;
-        Action action = ref.getRefersTo();
-        logger.info("Executing action <<" + action.getName() + ">>.");
-        AdaptationPoint currentAdaptationPoint = action
-        		.getReferredAdaptationPoint();
-
-        dmmModelActionHandler.execute(currentAdaptationPoint,
-        		action.getAdaptationActionOperation());
-    }
-
-    private void execLoopAction(AbstractControlFlowElement loopAction) throws OperationNotPerformedException {
-        LoopAction loop = (LoopAction) loopAction;
-        int numberOfIterations = loop.getCounter();
-        int i = 1;
-
-        while (i <= numberOfIterations) {
-            logger.debug("Executing iteration " + i + " of loop action " + loop.getBody().getName());
-            executeAdaptationPlan(loop.getBody());
-            i++;
-        }
-    }
-
-	/**
-	 * Applies the the given tactic.
-	 * 
-	 * @param currentTactic
-	 *            The tactic to execute
-	 * @return
-	 */
-	public void applyTactic(WeightedTactic weightedTactic) {
-		try {
-            executeAdaptationPlanOfTactic(weightedTactic);
-            logger.info("Tactic " + weightedTactic.getUsedTactic().getName()
-                    + " successfully applied.");
-            hist.add(weightedTactic, TacticsHistory.NO_RESULT, true);
-
-            // if this point is reached everything was fine, so persist them (save the models)
-            dmmModelActionHandler.persistActions();
-            return;
-        } catch (OperationNotPerformedException e) {
-			logger.error("Tactic " + weightedTactic.getUsedTactic().getName()
-					+ " could not be executed. Please check adaptation plan and/or log files for errors.", e);
-			weightedTactic.setCurrentWeight(0.0);
-			hist.add(weightedTactic, TacticsHistory.NO_RESULT, false);
-            /*
-             * TODO Something went wrong. 
-             * 1) Detect error 
-             * 2) reevaluate tactics
-             * 3) apply different tactic.
-             */
-        }
-	}
-
-    public void executeAdaptationPlanOfTactic(WeightedTactic weightedTactic) throws OperationNotPerformedException {
-        executeAdaptationPlan(weightedTactic.getUsedTactic().getImplementedPlan());
-    }
-
 }
diff --git a/edu.kit.ipd.descartes.adaptation/src/edu/kit/ipd/descartes/adaptation/model/dmm/DmmModelActionHandler.java b/edu.kit.ipd.descartes.adaptation/src/edu/kit/ipd/descartes/adaptation/model/dmm/DmmModelActionHandler.java
index 619403e4..e3eeb147 100644
--- a/edu.kit.ipd.descartes.adaptation/src/edu/kit/ipd/descartes/adaptation/model/dmm/DmmModelActionHandler.java
+++ b/edu.kit.ipd.descartes.adaptation/src/edu/kit/ipd/descartes/adaptation/model/dmm/DmmModelActionHandler.java
@@ -177,8 +177,8 @@ public class DmmModelActionHandler implements IActionHandler {
             if (!(targets instanceof SetOfConfigurations))
                 throw new IllegalArgumentException(
                         "Migration could not be performed because no target specification found!");
-
             EList<Entity> migrationTargets = ((SetOfConfigurations) targets).getVariants();
+            
             RuntimeEnvironment migratedEntity = (RuntimeEnvironment) adaptableEntity;
             Container parent = migratedEntity.getContainedIn();
             // TODO Here you could implement something more sophisticated
diff --git a/edu.kit.ipd.descartes.adaptation/src/edu/kit/ipd/descartes/adaptation/model/dmm/util/DmmModelChanger.java b/edu.kit.ipd.descartes.adaptation/src/edu/kit/ipd/descartes/adaptation/model/dmm/util/DmmModelChanger.java
index 2b5597c0..f3cde05b 100644
--- a/edu.kit.ipd.descartes.adaptation/src/edu/kit/ipd/descartes/adaptation/model/dmm/util/DmmModelChanger.java
+++ b/edu.kit.ipd.descartes.adaptation/src/edu/kit/ipd/descartes/adaptation/model/dmm/util/DmmModelChanger.java
@@ -121,10 +121,14 @@ public class DmmModelChanger {
         newRuntimeEnvironment.setName(newRuntimeEnvironment.getName() + COPY_MARK);
         newRuntimeEnvironment.setTemplate(runtimeEnvironment.getTemplate());
         runtimeEnvironment.getTemplate().getReferringContainers().add(newRuntimeEnvironment);
-        newRuntimeEnvironment.getConfigSpec().clear();
-        newRuntimeEnvironment.getConfigSpec().addAll(EcoreUtil.copyAll(runtimeEnvironment.getTemplate().getTemplateConfig()));
+        
+        if (runtimeEnvironment.getConfigSpec().size() > 0) {
+            newRuntimeEnvironment.getConfigSpec().clear();
+            newRuntimeEnvironment.getConfigSpec().addAll(EcoreUtil.copyAll(runtimeEnvironment.getTemplate().getTemplateConfig()));
+        }
+       
         runtimeEnvironment.getContainedIn().getContains().add(newRuntimeEnvironment);
-        logger.info("New RuntimeEnvironment " + newRuntimeEnvironment.getName() + " (ID: " +
+        logger.debug("New RuntimeEnvironment " + newRuntimeEnvironment.getName() + " (ID: " +
                 newRuntimeEnvironment.getId() + ") to " +
                 newRuntimeEnvironment.getContainedIn().getName() + " (ID: " + newRuntimeEnvironment.getContainedIn().getId() + ") added." );
         return newRuntimeEnvironment;
-- 
GitLab