Index: trunk/autoquest-plugin-uml/src/main/java/de/ugoe/cs/autoquest/plugin/uml/UMLUtils.java
===================================================================
--- trunk/autoquest-plugin-uml/src/main/java/de/ugoe/cs/autoquest/plugin/uml/UMLUtils.java	(revision 1761)
+++ trunk/autoquest-plugin-uml/src/main/java/de/ugoe/cs/autoquest/plugin/uml/UMLUtils.java	(revision 1763)
@@ -16,6 +16,9 @@
 
 import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
 import java.util.HashMap;
 import java.util.Iterator;
+import java.util.LinkedHashMap;
 import java.util.LinkedList;
 import java.util.List;
@@ -24,9 +27,12 @@
 
 import org.eclipse.emf.common.util.EList;
+import org.eclipse.uml2.uml.Activity;
+import org.eclipse.uml2.uml.ActivityEdge;
+import org.eclipse.uml2.uml.ActivityNode;
+import org.eclipse.uml2.uml.CallOperationAction;
 import org.eclipse.uml2.uml.Comment;
 import org.eclipse.uml2.uml.Component;
 import org.eclipse.uml2.uml.Connector;
 import org.eclipse.uml2.uml.ConnectorEnd;
-import org.eclipse.uml2.uml.Element;
 import org.eclipse.uml2.uml.Interaction;
 import org.eclipse.uml2.uml.InteractionFragment;
@@ -41,4 +47,5 @@
 import org.eclipse.uml2.uml.Profile;
 import org.eclipse.uml2.uml.Property;
+import org.eclipse.uml2.uml.Realization;
 import org.eclipse.uml2.uml.Region;
 import org.eclipse.uml2.uml.StateMachine;
@@ -52,5 +59,5 @@
 import de.ugoe.cs.autoquest.plugin.http.eventcore.SimpleSOAPEventType;
 import de.ugoe.cs.autoquest.plugin.uml.eventcore.UMLTransitionType;
-import de.ugoe.cs.autoquest.usageprofiles.TrieBasedModel;
+import de.ugoe.cs.autoquest.usageprofiles.IStochasticProcess;
 
 /**
@@ -265,13 +272,5 @@
                                                           String interactionName)
     {
-        Map<String, Interface> interfaceMap = new HashMap<>();
         Map<String, Port> portMap = new HashMap<>();
-
-        EList<Element> elements = model.getOwnedElements();
-        for (Element element : elements) {
-            if (element instanceof Interface) {
-                interfaceMap.put(((Interface) element).getName(), (Interface) element);
-            }
-        }
 
         Component testContext =
@@ -281,4 +280,7 @@
         final Profile utpProfile = model.getAppliedProfile("utp");
         final Stereotype utpTestCase = (Stereotype) utpProfile.getOwnedMember("TestCase");
+        final Stereotype utpTestComponent = (Stereotype) utpProfile.getOwnedMember("TestComponent");
+        final Stereotype utpSUT = (Stereotype) utpProfile.getOwnedMember("SUT");
+        
         Operation operation = testContext.createOwnedOperation(interactionName, null, null);
         operation.applyStereotype(utpTestCase);
@@ -287,20 +289,28 @@
             (Interaction) testContext.createPackagedElement(interactionName + "_Impl",
                                                             UMLPackage.Literals.INTERACTION);
+        operation.getMethods().add(interaction);
         
-        operation.getMethods().add(interaction);
-
-        Lifeline userLifeline = interaction.createLifeline("user");
-
-        userLifeline.setRepresents(testContext.getAttribute("user", null));
-
-        Component userComponent =
-            (Component) model.getPackagedElement("User", true, UMLPackage.Literals.COMPONENT, true);
-        
-        EList<Property> userAttributes = userComponent.getAttributes();
+        // create lifelines
+        Lifeline userLifeline = null;
         List<Port> userPorts = new LinkedList<>();
-        for( Property userAttribute : userAttributes ) {
-            if( userAttribute instanceof Port ) {
-                userPorts.add((Port) userAttribute);
-            }
+        for (Property property : testContext.getAllAttributes()) {
+            if (property.getAppliedStereotypes().contains(utpSUT)) {
+                String serviceName = getRealizedInterfaceFromProperty(property).getName();
+                
+                Lifeline targetLifeline = interaction.createLifeline(serviceName);
+                targetLifeline.setRepresents(property);
+                portMap.put(serviceName,
+                            (Port) ((Component) property.getType()).getAttribute("p_" + serviceName, null));
+            }
+            else if (property.getType().getAppliedStereotypes().contains(utpTestComponent)) {
+                userLifeline = interaction.createLifeline(property.getName());
+                userLifeline.setRepresents(property);
+                EList<Property> userAttributes = ((Component) property.getType()).getAttributes();
+                for (Property userAttribute : userAttributes) {
+                    if (userAttribute instanceof Port) {
+                        userPorts.add((Port) userAttribute);
+                    }
+                }
+            } 
         }
 
@@ -311,24 +321,7 @@
                 String methodName = getCalledMethodFromEvent(event);
 
-                Interface targetInterface = interfaceMap.get(serviceName);
-                if (targetInterface == null) {
-                    throw new RuntimeException(
-                                               "Could not find interface in the UML model that belong to the service: " +
-                                                   serviceName);
-                }
-
                 Lifeline targetLifeline = interaction.getLifeline(serviceName);
-                if (targetLifeline == null) {
-                    targetLifeline = interaction.createLifeline(serviceName);
-
-                    targetLifeline.setRepresents(testContext
-                        .getAttribute(serviceName + "_property", null));
-
-                    Component component =
-                        (Component) model.getPackagedElement(serviceName, true,
-                                                             UMLPackage.Literals.COMPONENT, true);
-                    portMap.put(serviceName,
-                                (Port) component.getAttribute("p_" + serviceName, null));
-                }
+                Interface targetInterface = getRealizedInterfaceFromProperty((Property) targetLifeline.getRepresents());
+
                 MessageOccurrenceSpecification sendFragment =
                     (MessageOccurrenceSpecification) interaction
@@ -352,8 +345,8 @@
                 message.setSendEvent(sendFragment);
                 message.setReceiveEvent(recvFragment);
-                
+
                 EList<ConnectorEnd> targetEnds = portMap.get(serviceName).getEnds();
 
-                for( Port userPort : userPorts ) {
+                for (Port userPort : userPorts) {
                     EList<ConnectorEnd> sourceEnds = userPort.getEnds();
                     for (ConnectorEnd sourceEnd : sourceEnds) {
@@ -388,5 +381,7 @@
      * @return calculated usage score
      */
-    public static double calculateUsageScore(Interaction interaction, TrieBasedModel usageProfile) {
+    public static double calculateUsageScore(Interaction interaction,
+                                             IStochasticProcess usageProfile)
+    {
         double usageScore = 0.0d;
 
@@ -399,5 +394,5 @@
             {
                 String serviceName =
-                    interactionFragment.getCovereds().get(0).getRepresents().getName();
+                    interactionFragment.getCovereds().get(0).getRepresents().getName().split("_")[0];
                 String methodName = "UNKNOWN";
                 if (interactionFragment instanceof MessageOccurrenceSpecification) {
@@ -409,8 +404,98 @@
             }
         }
+        eventSequence.add(Event.ENDEVENT);
         double prob = usageProfile.getLogSum(eventSequence);
-        usageScore = prob * eventSequence.size();
+        usageScore = eventSequence.size() * prob;
 
         return usageScore;
+    }
+
+    /**
+     * <p>
+     * Extends the given model with an activity for usage-based scheduling of the test cases.
+     * </p>
+     * 
+     * @param model
+     *            model to be extended
+     * @param usageProfile
+     *            usage profile used as foundation
+     */
+    public static void createScheduling(Model model, IStochasticProcess usageProfile) {
+
+        final Profile utpProfile = model.getAppliedProfile("utp");
+        final Stereotype utpTestCase = (Stereotype) utpProfile.getOwnedMember("TestCase");
+
+        Component testContext =
+            (Component) model.getPackagedElement("TestContext", true,
+                                                 UMLPackage.Literals.COMPONENT, true);
+
+        Map<Operation, Double> usageScoreMapUnsorted = new HashMap<>();
+
+        // first, we determine all test cases and calculate their usage scores
+        for (Operation operation : testContext.getAllOperations()) {
+            if (operation.getAppliedStereotypes().contains(utpTestCase)) {
+                Interaction interaction = (Interaction) operation.getMethods().get(0);
+                usageScoreMapUnsorted
+                    .put(operation, calculateUsageScore(interaction, usageProfile));
+            }
+        }
+        Map<Operation, Double> usageScoreMapSorted = sortByValue(usageScoreMapUnsorted);
+
+        // now we create the scheduling
+        Activity schedulingActivity =
+            (Activity) testContext.createOwnedBehavior("UsageBasedScheduling",
+                                                       UMLPackage.Literals.ACTIVITY);
+        testContext.setClassifierBehavior(schedulingActivity);
+
+        ActivityNode startNode =
+            schedulingActivity.createOwnedNode("final", UMLPackage.Literals.INITIAL_NODE);
+        ActivityNode finalNode =
+            schedulingActivity.createOwnedNode("final", UMLPackage.Literals.ACTIVITY_FINAL_NODE);
+
+        ActivityNode currentOperationNode = startNode;
+
+        for (Entry<Operation, Double> entry : usageScoreMapSorted.entrySet()) {
+            Operation operation = entry.getKey();
+            CallOperationAction nextOperationNode =
+                (CallOperationAction) schedulingActivity
+                    .createOwnedNode(operation.getName(), UMLPackage.Literals.CALL_OPERATION_ACTION);
+            nextOperationNode.setOperation(operation);
+
+            ActivityEdge edge =
+                schedulingActivity.createEdge(currentOperationNode.getName() + "_to_" +
+                    nextOperationNode.getName(), UMLPackage.Literals.CONTROL_FLOW);
+            edge.setSource(currentOperationNode);
+            edge.setTarget(nextOperationNode);
+
+            currentOperationNode = nextOperationNode;
+        }
+
+        ActivityEdge edge =
+            schedulingActivity
+                .createEdge(currentOperationNode.getName() + "_to_" + finalNode.getName(),
+                            UMLPackage.Literals.CONTROL_FLOW);
+        edge.setSource(currentOperationNode);
+        edge.setTarget(finalNode);
+    }
+
+    /**
+     * From
+     * http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java
+     * and adapted to do an inverse sorting
+     */
+    public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
+        List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
+        Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
+            @Override
+            public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
+                return -1 * (o1.getValue()).compareTo(o2.getValue());
+            }
+        });
+
+        Map<K, V> result = new LinkedHashMap<>();
+        for (Map.Entry<K, V> entry : list) {
+            result.put(entry.getKey(), entry.getValue());
+        }
+        return result;
     }
 
@@ -512,4 +597,13 @@
         return matching;
     }
+    
+    private static Interface getRealizedInterfaceFromProperty(Property property) {
+        return getRealizedInterfaceFromComponent((Component) property.getType());
+    }
+    
+    private static Interface getRealizedInterfaceFromComponent(Component comp) {
+        Realization realization = (Realization) comp.getNestedClassifiers().get(0).getRelationships(UMLPackage.Literals.REALIZATION).get(0);
+        return (Interface) realization.getSuppliers().get(0);
+    }
 
 }
