source: trunk/autoquest-plugin-uml/src/main/java/de/ugoe/cs/autoquest/plugin/uml/UMLUtils.java @ 2000

Last change on this file since 2000 was 2000, checked in by sherbold, 9 years ago
  • minor fix: now all instance specifications should have a unique name
  • Property svn:mime-type set to text/plain
File size: 72.5 KB
Line 
1//   Copyright 2012 Georg-August-Universität Göttingen, Germany
2//
3//   Licensed under the Apache License, Version 2.0 (the "License");
4//   you may not use this file except in compliance with the License.
5//   You may obtain a copy of the License at
6//
7//       http://www.apache.org/licenses/LICENSE-2.0
8//
9//   Unless required by applicable law or agreed to in writing, software
10//   distributed under the License is distributed on an "AS IS" BASIS,
11//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//   See the License for the specific language governing permissions and
13//   limitations under the License.
14
15package de.ugoe.cs.autoquest.plugin.uml;
16
17import java.util.Collection;
18import java.util.Collections;
19import java.util.Comparator;
20import java.util.HashMap;
21import java.util.HashSet;
22import java.util.Iterator;
23import java.util.LinkedHashMap;
24import java.util.LinkedList;
25import java.util.List;
26import java.util.Map;
27import java.util.Map.Entry;
28import java.util.Set;
29import java.util.TreeSet;
30import java.util.logging.Level;
31
32import org.apache.commons.lang.mutable.MutableInt;
33import org.eclipse.emf.common.util.EList;
34import org.eclipse.uml2.uml.Activity;
35import org.eclipse.uml2.uml.ActivityEdge;
36import org.eclipse.uml2.uml.ActivityNode;
37import org.eclipse.uml2.uml.CallConcurrencyKind;
38import org.eclipse.uml2.uml.CallEvent;
39import org.eclipse.uml2.uml.CallOperationAction;
40import org.eclipse.uml2.uml.Comment;
41import org.eclipse.uml2.uml.Component;
42import org.eclipse.uml2.uml.Connector;
43import org.eclipse.uml2.uml.ConnectorEnd;
44import org.eclipse.uml2.uml.DataType;
45import org.eclipse.uml2.uml.Element;
46import org.eclipse.uml2.uml.Expression;
47import org.eclipse.uml2.uml.InstanceSpecification;
48import org.eclipse.uml2.uml.InstanceValue;
49import org.eclipse.uml2.uml.Interaction;
50import org.eclipse.uml2.uml.InteractionFragment;
51import org.eclipse.uml2.uml.Interface;
52import org.eclipse.uml2.uml.Lifeline;
53import org.eclipse.uml2.uml.LiteralBoolean;
54import org.eclipse.uml2.uml.LiteralInteger;
55import org.eclipse.uml2.uml.LiteralNull;
56import org.eclipse.uml2.uml.LiteralReal;
57import org.eclipse.uml2.uml.LiteralString;
58import org.eclipse.uml2.uml.Message;
59import org.eclipse.uml2.uml.MessageOccurrenceSpecification;
60import org.eclipse.uml2.uml.MessageSort;
61import org.eclipse.uml2.uml.Model;
62import org.eclipse.uml2.uml.Operation;
63import org.eclipse.uml2.uml.Package;
64import org.eclipse.uml2.uml.Parameter;
65import org.eclipse.uml2.uml.ParameterDirectionKind;
66import org.eclipse.uml2.uml.Port;
67import org.eclipse.uml2.uml.PrimitiveType;
68import org.eclipse.uml2.uml.Property;
69import org.eclipse.uml2.uml.Region;
70import org.eclipse.uml2.uml.Slot;
71import org.eclipse.uml2.uml.StateMachine;
72import org.eclipse.uml2.uml.Stereotype;
73import org.eclipse.uml2.uml.Transition;
74import org.eclipse.uml2.uml.Trigger;
75import org.eclipse.uml2.uml.UMLPackage;
76import org.eclipse.uml2.uml.Vertex;
77
78import de.ugoe.cs.autoquest.eventcore.Event;
79import de.ugoe.cs.autoquest.eventcore.EventUtils;
80import de.ugoe.cs.autoquest.plugin.http.SOAPUtils;
81import de.ugoe.cs.autoquest.plugin.http.eventcore.SOAPEventType;
82import de.ugoe.cs.autoquest.plugin.http.eventcore.SimpleSOAPEventType;
83import de.ugoe.cs.autoquest.plugin.http.eventcore.SimpleSOAPEventType.CallType;
84import de.ugoe.cs.autoquest.plugin.uml.eventcore.UMLTransitionType;
85import de.ugoe.cs.autoquest.usageprofiles.IStochasticProcess;
86import de.ugoe.cs.util.StringTools;
87import de.ugoe.cs.util.console.Console;
88
89/**
90 * <p>
91 * Utilities for working with UML.
92 * </p>
93 *
94 * @author Steffen Herbold
95 */
96public class UMLUtils {
97
98    /**
99     * In case a multiplicity is defined as *, this value defines the highest one that can be picked
100     */
101    final static int MAX_MULTIPLICITY = 10;
102
103    /**
104     * <p>
105     * Method for checking if the information in a usage journal can be mapped to the SUT model. In
106     * case this is not possible, the violations are reported.
107     * </p>
108     *
109     * @param sequences
110     *            sequences of the usage journal
111     * @param model
112     *            SUT model that is validated
113     * @param testContextName
114     *            name of the test context to be used; if null, the first test context found is used
115     * @return number of violations
116     */
117    public static int validateModelWithLog(Collection<List<Event>> sequences,
118                                           Model model,
119                                           String testContextName)
120    {
121        int violationCount = 0;
122        Component testContext = fetchTestContext(model, testContextName);
123        if (testContext == null) {
124            violationCount++;
125            if (testContextName == null) {
126                Console.traceln(Level.SEVERE, "Could not find any TestContext in the model.");
127
128            }
129            else {
130                Console.traceln(Level.SEVERE, "Could not find TestContext in the model: " +
131                    testContextName);
132            }
133            Console
134                .traceln(Level.SEVERE,
135                         "Hint: Check if you have applied the TestContext stereotype correctly in the model.");
136            Console.traceln(Level.SEVERE, "Aborting");
137            return violationCount;
138        }
139
140        // Create list of unique methods calls
141        HashMap<String, Set<String>> calledMethods = new HashMap<>();
142        for (List<Event> sequence : sequences) {
143            for (Event event : sequence) {
144                String serviceName = SOAPUtils.getServiceNameFromEvent(event);
145                String calledMethod = SOAPUtils.getCalledMethodFromEvent(event);
146                if (serviceName != null) {
147                    Set<String> curCalledMethods = calledMethods.get(serviceName);
148                    if (curCalledMethods == null) {
149                        curCalledMethods = new TreeSet<>();
150                        calledMethods.put(serviceName, curCalledMethods);
151                    }
152                    curCalledMethods.add(calledMethod);
153                }
154            }
155        }
156
157        Console.traceln(Level.INFO,
158                        "Found the following services and operations in the usage data: ");
159        for (Entry<String, Set<String>> entry : calledMethods.entrySet()) {
160            Console.traceln(Level.INFO, "\tService \"" + entry.getKey() + "\": ");
161            for (String method : entry.getValue()) {
162                Console.traceln(Level.INFO, "\t\t" + method);
163            }
164        }
165
166        // fetch all SUTs and TestComponents
167        HashMap<String, Property> properties = new HashMap<>();
168        for (Property property : fetchAllSUTProperties(testContext)) {
169            properties.put(property.getName(), property);
170        }
171        for (Property property : fetchAllTestComponentProperties(testContext)) {
172            properties.put(property.getName(), property);
173        }
174        Console.traceln(Level.INFO, "Found the following services in the TestConfiguration:");
175        for (Entry<String, Property> entry : properties.entrySet()) {
176            Console.traceln(Level.INFO, "\t" + entry.getKey());
177        }
178
179        for (Entry<String, Set<String>> entry : calledMethods.entrySet()) {
180            String serviceName = entry.getKey();
181            Console.traceln(Level.INFO, "Checking service: " + serviceName);
182            Set<String> methodNames = entry.getValue();
183            Property property = properties.get(serviceName);
184            if (property == null) {
185                violationCount++;
186                Console.traceln(Level.SEVERE, "\tCould not find property for service: " +
187                    serviceName);
188                Console
189                    .traceln(Level.SEVERE,
190                             "\tHint: Check service name map and/or model if the service is present and spelled correctly.");
191                Console
192                    .traceln(Level.SEVERE,
193                             "\tHint: Check if the SUT/TestComponent stereotype has been applied correctly in this TestContext.");
194            }
195            else {
196                Set<Interface> interfaces = getRealizedInterfacesFromProperty(property);
197                if (interfaces.isEmpty()) {
198                    violationCount++;
199                    Console
200                        .traceln(Level.SEVERE,
201                                 "\tCould not find any interfaces implementing the property for service: " +
202                                     serviceName);
203                    Console
204                        .traceln(Level.SEVERE,
205                                 "\tHint: Check if the property correctly realizes the interfaces in the model.");
206                }
207                else {
208                    Console.traceln(Level.INFO,
209                                    "\tFound the following realized interfaces for the service \"" +
210                                        serviceName + "\": ");
211                    for (Interface intface : interfaces) {
212                        Console.traceln(Level.INFO, "\t" + intface.getName());
213                        for (Operation operation : intface.getAllOperations()) {
214                            Console.traceln(Level.INFO, "\t\t" + operation.getName());
215                        }
216                    }
217                    for (String methodName : methodNames) {
218                        boolean methodFound = false;
219                        for (Interface intface : interfaces) {
220                            if (getOperationFromName(intface.getOperations(), methodName) != null) {
221                                // interface found
222                                Console.traceln(Level.INFO, "\tMethod " + methodName +
223                                    " found in interface " + intface.getName());
224                                methodFound = true;
225                            }
226                        }
227                        if (!methodFound) {
228                            violationCount++;
229                            Console.traceln(Level.SEVERE, "\tCould not find operation: " +
230                                methodName);
231                        }
232                    }
233                }
234            }
235        }
236        return violationCount;
237    }
238
239    /**
240     * <p>
241     * Creates a sequence of events with {@link UMLTransitionType} as event type from a given
242     * sequence of events with the {@link SOAPEventType} or {@link SimpleSOAPEventType}, by matching
243     * the sequences to a state machine.
244     * </p>
245     *
246     * @param sequence
247     *            SOAP sequences
248     * @param stateMachine
249     *            the state machine
250     * @return create UML sequences
251     */
252    public static List<Event> createUMLTransitionSequence(List<Event> sequence,
253                                                          StateMachine stateMachine)
254    {
255        List<List<Transition>> matchingSequences =
256            determineMatchingTransitionSequences(sequence, stateMachine);
257
258        if (matchingSequences.size() != 1) {
259            throw new RuntimeException("no unique match found; " + matchingSequences.size() +
260                " matches");
261        }
262        List<Event> umlEventSequence = new LinkedList<>();
263        for (Transition transition : matchingSequences.get(0)) {
264            umlEventSequence.add(new Event(new UMLTransitionType(transition)));
265        }
266        return umlEventSequence;
267    }
268
269    /**
270     * <p>
271     * Uses a sequences of events with the {@link UMLTransitionType} to determine the transition
272     * probabilities for the state machine.
273     * </p>
274     *
275     * @param sequences
276     *            UML sequences
277     * @param stateMachine
278     *            state machine to be converted to a usage profile
279     */
280    public static void convertStateMachineToUsageProfile(Collection<List<Event>> sequences,
281                                                         StateMachine stateMachine)
282    {
283        // create state->outgoings hashmap
284        Map<Vertex, Map<Transition, Integer>> stateMap = new HashMap<>();
285        for (Region region : stateMachine.getRegions()) {
286            for (Vertex state : region.getSubvertices()) {
287                stateMap.put(state, new HashMap<Transition, Integer>());
288            }
289        }
290
291        // create counters for each transition
292        for (List<Event> sequence : sequences) {
293            for (Event event : sequence) {
294                if (event.getType() instanceof UMLTransitionType) {
295                    Transition transition = ((UMLTransitionType) event.getType()).getTransition();
296                    Map<Transition, Integer> transitionMap = stateMap.get(transition.getSource());
297                    Integer value = transitionMap.get(transition);
298                    if (value == null) {
299                        value = 0;
300                    }
301                    transitionMap.put(transition, value + 1);
302                }
303                else {
304                    throw new RuntimeException(
305                                               "Wrong event type. Only UMLTransitionType supported but was: " +
306                                                   event.getType().getClass().getName());
307                }
308            }
309        }
310
311        // calculate probabilities
312        for (Region region : stateMachine.getRegions()) {
313            for (Vertex state : region.getSubvertices()) {
314                Map<Transition, Integer> transitionMap = stateMap.get(state);
315                int totalCount = 0;
316                for (Entry<Transition, Integer> entry : transitionMap.entrySet()) {
317                    totalCount += entry.getValue();
318                }
319                if (totalCount != 0) {
320                    for (Transition transition : state.getOutgoings()) {
321                        double prob = 0.0d;
322                        if (transitionMap.containsKey(transition)) {
323                            prob = ((double) transitionMap.get(transition)) / totalCount;
324                        }
325                        Comment comment = transition.createOwnedComment();
326                        comment.setBody("" + prob);
327                    }
328                }
329                else {
330                    // system has never been in this state, all transitions equally likely
331                    int numOutgoings = state.getOutgoings().size();
332                    for (Transition transition : state.getOutgoings()) {
333                        Comment comment = transition.createOwnedComment();
334                        comment.setBody("" + (1.0d / numOutgoings));
335                    }
336                }
337            }
338        }
339    }
340
341    /**
342     * <p>
343     * Determines all matching {@link Transition} sequences in a state machine for a given sequence
344     * of SOAP events.
345     * </p>
346     *
347     * @param sequence
348     *            SOAP sequence
349     * @param stateMachine
350     *            the state machine
351     * @return all matching {@link Transition} sequences
352     */
353    public static List<List<Transition>> determineMatchingTransitionSequences(List<Event> sequence,
354                                                                              StateMachine stateMachine)
355    {
356        EList<Region> regions = stateMachine.getRegions();
357        EList<Vertex> states = null;
358        for (Region region : regions) {
359            if (states == null) {
360                states = region.getSubvertices();
361            }
362            else {
363                states.addAll(region.getSubvertices());
364            }
365        }
366        List<Transition> allTransitions = new LinkedList<>();
367        for (Vertex state : states) {
368            allTransitions.addAll(state.getOutgoings());
369        }
370
371        List<List<Transition>> matchingSequences = null;
372        List<Transition> currentTransitions = null;
373
374        // first, we try to find a single unique transition that we can match using the method name
375        for (Iterator<Event> eventIterator = sequence.iterator(); eventIterator.hasNext();) {
376            Event event = eventIterator.next();
377            if (matchingSequences == null) {
378                matchingSequences = new LinkedList<>();
379                List<Transition> initialMatches = matchTransitions(allTransitions, event);
380                for (Transition transition : initialMatches) {
381                    List<Transition> candidate = new LinkedList<>();
382                    candidate.add(transition);
383                    matchingSequences.add(candidate);
384                }
385                currentTransitions = initialMatches;
386            }
387            else {
388                List<List<Transition>> nextMatchingSequences = new LinkedList<>();
389                List<Transition> nextCurrentTransitions = new LinkedList<>();
390                Iterator<Transition> currentTransitionIterator = currentTransitions.iterator();
391                Iterator<List<Transition>> currentMatchingSequencesIterator =
392                    matchingSequences.iterator();
393                while (currentTransitionIterator.hasNext()) {
394                    Transition currentTransition = currentTransitionIterator.next();
395                    List<Transition> currentMatch = currentMatchingSequencesIterator.next();
396
397                    List<Transition> matches =
398                        matchTransitions(currentTransition.getTarget().getOutgoings(), event);
399                    if (matches.isEmpty()) {
400                        throw new RuntimeException("no matches found");
401                    }
402                    for (Transition matchingTransition : matches) {
403                        List<Transition> candidate = new LinkedList<>(currentMatch);
404                        candidate.add(matchingTransition);
405                        nextMatchingSequences.add(candidate);
406                        nextCurrentTransitions.add(matchingTransition);
407                    }
408                }
409                matchingSequences = nextMatchingSequences;
410                currentTransitions = nextCurrentTransitions;
411            }
412        }
413        return matchingSequences;
414    }
415
416    /**
417     * <p>
418     * Extends a given model with an interaction that represents an observed sequence.
419     * </p>
420     *
421     * @param sequence
422     *            sequence that is added as sequence diagram
423     * @param model
424     *            UML model to which the interaction is added
425     * @param interactionName
426     *            name of the interaction
427     * @param testContextName
428     *            Name of the test context that should be used. If this value is null, the first
429     *            test context found is used.
430     * @param useRandomRequestBodies
431     *            defines is random request bodies are used or the body of the associated event
432     */
433    public static Interaction createInteractionFromEventSequence(List<Event> sequence,
434                                                                 Model model,
435                                                                 String interactionName,
436                                                                 String testContextName,
437                                                                 boolean useRandomRequestBodies)
438    {
439        final Component testContext = fetchTestContext(model, testContextName);
440        if (testContext == null) {
441            throw new RuntimeException("Could not find any test context in the model");
442        }
443
444        final Operation operation = testContext.createOwnedOperation(interactionName, null, null);
445        operation.applyStereotype(UTPUtils.getTestCaseStereotype(model));
446
447        final Interaction interaction =
448            (Interaction) testContext.createPackagedElement(interactionName + "_Impl",
449                                                            UMLPackage.Literals.INTERACTION);
450        operation.getMethods().add(interaction);
451
452        // create lifelines
453        Lifeline userLifeline = null;
454
455        for (Property property : fetchAllSUTProperties(testContext)) {
456            String serviceName = property.getName();
457            Lifeline targetLifeline = interaction.createLifeline(serviceName);
458            targetLifeline.setRepresents(property);
459        }
460        for (Property property : fetchAllTestComponentProperties(testContext)) {
461            // TODO check if this is still required
462            /*
463             * if (userLifeline != null) { throw new RuntimeException(
464             * "TestContext must only have one TestComponent for the application of usage-based testing."
465             * ); }
466             */
467            userLifeline = interaction.createLifeline(property.getName());
468            userLifeline.setRepresents(property);
469        }
470
471        if (userLifeline == null) {
472            throw new RuntimeException("No TestComponent found, could not create user lifeline.");
473        }
474        if (interaction.getLifelines().size() < 2) {
475            throw new RuntimeException("Fewer than two lifelines created. No SUT found.");
476        }
477
478        int i = 0;
479        for (Event event : sequence) {
480            if (!(event.equals(Event.STARTEVENT) || event.equals(Event.ENDEVENT))) {
481                String serviceName = SOAPUtils.getServiceNameFromEvent(event);
482                String methodName = SOAPUtils.getCalledMethodFromEvent(event);
483                String clientName = SOAPUtils.getClientNameFromEvent(event);
484                String prefix = interactionName + "_" + i + "_" + methodName + "_";
485                // determine lifelines
486                Lifeline msgTargetLifeline;
487                Lifeline msgSourceLifeline;
488
489                msgSourceLifeline = interaction.getLifeline(clientName);
490                msgTargetLifeline = interaction.getLifeline(serviceName);
491
492                if (msgSourceLifeline == null) {
493                    throw new RuntimeException(
494                                               "Error creating message: could not determine source lifeline for component: " +
495                                                   clientName);
496                }
497                if (msgTargetLifeline == null) {
498                    throw new RuntimeException(
499                                               "Error creating message: could not determine target lifeline for component: " +
500                                                   serviceName);
501                }
502                // determine correct target interface
503                Set<Interface> targetInterfaces =
504                    getRealizedInterfacesFromProperty((Property) msgTargetLifeline.getRepresents());
505                if (targetInterfaces.isEmpty()) {
506                    throw new RuntimeException("no interface associated with the property " +
507                        msgTargetLifeline.getRepresents().getName());
508                }
509                Interface targetInterface = null;
510                for (Interface intface : targetInterfaces) {
511                    if (getOperationFromName(intface.getOperations(), methodName) != null) {
512                        // interface found
513                        targetInterface = intface;
514                        break;
515                    }
516                }
517                if (targetInterface == null) {
518                    StringBuilder errStrBuilder = new StringBuilder();
519                    errStrBuilder
520                        .append("Error creating message: operation not found in the implementing interfaces (");
521                    Iterator<Interface> iter = targetInterfaces.iterator();
522                    while (iter.hasNext()) {
523                        String interfaceName = iter.next().getName();
524                        errStrBuilder.append(interfaceName);
525                        if (iter.hasNext()) {
526                            errStrBuilder.append(",");
527                        }
528                        else {
529                            errStrBuilder.append("): " + methodName);
530                        }
531                    }
532                    throw new RuntimeException(errStrBuilder.toString());
533                }
534
535                Operation calledOperation =
536                    getOperationFromName(targetInterface.getOperations(), methodName);
537                // get connector
538                Connector connector = inferConnector(msgSourceLifeline, msgTargetLifeline);
539
540                boolean asynch = false;
541                if (calledOperation.getConcurrency() == CallConcurrencyKind.CONCURRENT_LITERAL) {
542                    asynch = true;
543                }
544
545                if (SOAPUtils.isSOAPRequest(event)) {
546                    // setup for both SYNCH and ASYNCH calls
547                    MessageOccurrenceSpecification callSendFragment =
548                        (MessageOccurrenceSpecification) interaction
549                            .createFragment(prefix + "callSendFragment",
550                                            UMLPackage.Literals.MESSAGE_OCCURRENCE_SPECIFICATION);
551                    MessageOccurrenceSpecification callRecvFragment =
552                        (MessageOccurrenceSpecification) interaction
553                            .createFragment(prefix + "callRecvFragment",
554                                            UMLPackage.Literals.MESSAGE_OCCURRENCE_SPECIFICATION);
555
556                    callSendFragment.setCovered(msgSourceLifeline);
557                    callRecvFragment.setCovered(msgTargetLifeline);
558
559                    // create call
560                    Message callMessage = interaction.createMessage(prefix + "call");
561                    callMessage.setSignature(calledOperation);
562                    setMessageParameters(callMessage, calledOperation, event,
563                                         useRandomRequestBodies, prefix);
564                    callMessage.setConnector(connector);
565                    callMessage.setSendEvent(callSendFragment);
566                    callMessage.setReceiveEvent(callRecvFragment);
567                    callSendFragment.setMessage(callMessage);
568                    callRecvFragment.setMessage(callMessage);
569
570                    if (asynch) {
571                        // Create ASYNCH call
572                        callMessage.setMessageSort(MessageSort.ASYNCH_CALL_LITERAL);
573                    }
574                    else {
575                        // SYNCH call
576                        callMessage.setMessageSort(MessageSort.SYNCH_CALL_LITERAL);
577                    }
578                }
579                if (!asynch && SOAPUtils.isSOAPResponse(event)) {
580                    // setup reply and behavior execution specifications
581                    MessageOccurrenceSpecification replySendFragment =
582                        (MessageOccurrenceSpecification) interaction
583                            .createFragment(prefix + "replySendFragment",
584                                            UMLPackage.Literals.MESSAGE_OCCURRENCE_SPECIFICATION);
585                    MessageOccurrenceSpecification replyRecvFragment =
586                        (MessageOccurrenceSpecification) interaction
587                            .createFragment(prefix + "replyRecvFragment",
588                                            UMLPackage.Literals.MESSAGE_OCCURRENCE_SPECIFICATION);
589
590                    replySendFragment.setCovered(msgTargetLifeline);
591                    replyRecvFragment.setCovered(msgSourceLifeline);
592
593                    /*
594                     * BehaviorExecutionSpecification sourceBehaviorExecutionSpecification =
595                     * (BehaviorExecutionSpecification) interaction .createFragment(":" + methodName
596                     * + "_sourceBhvExecSpec",
597                     * UMLPackage.Literals.BEHAVIOR_EXECUTION_SPECIFICATION);
598                     * BehaviorExecutionSpecification targetBehaviorExecutionSpecification =
599                     * (BehaviorExecutionSpecification) interaction .createFragment(":" + methodName
600                     * + "_targetBhvExecSpec",
601                     * UMLPackage.Literals.BEHAVIOR_EXECUTION_SPECIFICATION);
602                     *
603                     * sourceBehaviorExecutionSpecification.setStart(callSendFragment);
604                     * sourceBehaviorExecutionSpecification.setFinish(replyRecvFragment);
605                     * targetBehaviorExecutionSpecification.setStart(callRecvFragment);
606                     * targetBehaviorExecutionSpecification.setFinish(replySendFragment);
607                     */
608
609                    // create reply
610                    Message replyMessage = interaction.createMessage(prefix + "_reply");
611                    replyMessage.setMessageSort(MessageSort.REPLY_LITERAL);
612                    replyMessage.setSignature(calledOperation);
613                    // setReplyMessageParameters(replyMessage, calledOperation);
614                    setMessageParameters(replyMessage, calledOperation, event,
615                                         useRandomRequestBodies, prefix);
616                    replyMessage.setConnector(connector);
617                    replyMessage.setSendEvent(replySendFragment);
618                    replyMessage.setReceiveEvent(replyRecvFragment);
619                    replySendFragment.setMessage(replyMessage);
620                    replyRecvFragment.setMessage(replyMessage);
621                }
622
623                i++;
624            }
625        }
626        return interaction;
627    }
628
629    /**
630     * <p>
631     * Calculates the usage score of an interaction as the logsum of the event probabilities
632     * multiplied with the length of the interaction.
633     * </p>
634     *
635     * @param interaction
636     *            interaction for which the score is calculated
637     * @param usageProfile
638     *            usage profile used for the calculation
639     * @return calculated usage score
640     */
641    public static double calculateUsageScore(Interaction interaction,
642                                             IStochasticProcess usageProfile)
643    {
644        double usageScore = 0.0d;
645        EList<InteractionFragment> interactionFragments = interaction.getFragments();
646        List<Event> eventSequence = new LinkedList<>();
647        eventSequence.add(Event.STARTEVENT);
648        for (InteractionFragment interactionFragment : interactionFragments) {
649            if (interactionFragment instanceof MessageOccurrenceSpecification) {
650                Message message =
651                    ((MessageOccurrenceSpecification) interactionFragment).getMessage();
652                // if (message.getReceiveEvent().equals(interactionFragment) &&
653                // isCallMessage(message))
654                if (message.getReceiveEvent().equals(interactionFragment)) {
655                    String clientName;
656                    String serviceName;
657                    String methodName = message.getSignature().getName();
658                    CallType callType;
659                    if (isCallMessage(message)) {
660                        clientName =
661                            ((MessageOccurrenceSpecification) message.getSendEvent()).getCovereds()
662                                .get(0).getName();
663                        serviceName =
664                            ((MessageOccurrenceSpecification) message.getReceiveEvent())
665                                .getCovereds().get(0).getName();
666                        callType = CallType.REQUEST;
667                    }
668                    else {
669                        clientName =
670                            ((MessageOccurrenceSpecification) message.getReceiveEvent())
671                                .getCovereds().get(0).getName();
672                        serviceName =
673                            ((MessageOccurrenceSpecification) message.getSendEvent()).getCovereds()
674                                .get(0).getName();
675                        callType = CallType.RESPONSE;
676                    }
677                    eventSequence.add(new Event(new SimpleSOAPEventType(methodName, serviceName,
678                                                                        clientName, null, null,
679                                                                        callType)));
680                }
681            }
682        }
683        eventSequence.add(Event.ENDEVENT);
684        double prob = usageProfile.getLogSum(eventSequence);
685        usageScore = eventSequence.size() * prob;
686
687        return usageScore;
688    }
689
690    /**
691     * <p>
692     * Extends the given model with an activity for usage-based scheduling of the test cases.
693     * </p>
694     *
695     * @param model
696     *            model to be extended
697     * @param usageProfile
698     *            usage profile used as foundation
699     */
700    public static void createScheduling(Model model,
701                                        IStochasticProcess usageProfile,
702                                        String testContextName)
703    {
704        final Component testContext = fetchTestContext(model, testContextName);
705        if (testContext == null) {
706            throw new RuntimeException("Could not find any test context in the model");
707        }
708
709        Map<Operation, Double> usageScoreMapUnsorted = new HashMap<>();
710
711        // first, we determine all test cases and calculate their usage scores
712        final Stereotype utpTestCase = UTPUtils.getTestCaseStereotype(model);
713        for (Operation operation : testContext.getAllOperations()) {
714            if (operation.getAppliedStereotypes().contains(utpTestCase) &&
715                !operation.getMethods().isEmpty())
716            {
717                Interaction interaction = (Interaction) operation.getMethods().get(0);
718                usageScoreMapUnsorted
719                    .put(operation, calculateUsageScore(interaction, usageProfile));
720            }
721        }
722        Map<Operation, Double> usageScoreMapSorted = sortByValue(usageScoreMapUnsorted);
723
724        // now we create the scheduling
725        Activity schedulingActivity =
726            (Activity) testContext.createOwnedBehavior("UsageBasedScheduling",
727                                                       UMLPackage.Literals.ACTIVITY);
728        testContext.setClassifierBehavior(schedulingActivity);
729
730        ActivityNode startNode =
731            schedulingActivity.createOwnedNode("final", UMLPackage.Literals.INITIAL_NODE);
732        ActivityNode finalNode =
733            schedulingActivity.createOwnedNode("final", UMLPackage.Literals.ACTIVITY_FINAL_NODE);
734
735        ActivityNode currentOperationNode = startNode;
736
737        for (Entry<Operation, Double> entry : usageScoreMapSorted.entrySet()) {
738            Operation operation = entry.getKey();
739            CallOperationAction nextOperationNode =
740                (CallOperationAction) schedulingActivity
741                    .createOwnedNode(operation.getName(), UMLPackage.Literals.CALL_OPERATION_ACTION);
742            nextOperationNode.setOperation(operation);
743
744            ActivityEdge edge =
745                schedulingActivity.createEdge(currentOperationNode.getName() + "_to_" +
746                    nextOperationNode.getName(), UMLPackage.Literals.CONTROL_FLOW);
747            edge.setSource(currentOperationNode);
748            edge.setTarget(nextOperationNode);
749
750            currentOperationNode = nextOperationNode;
751        }
752
753        ActivityEdge edge =
754            schedulingActivity
755                .createEdge(currentOperationNode.getName() + "_to_" + finalNode.getName(),
756                            UMLPackage.Literals.CONTROL_FLOW);
757        edge.setSource(currentOperationNode);
758        edge.setTarget(finalNode);
759    }
760
761    /**
762     * <p>
763     * Fetches an operation using only its name from a list of operations. Returns the first match
764     * found or null if no match is found.
765     * </p>
766     *
767     * @param operations
768     *            list of operations
769     * @param name
770     *            name of the operation
771     * @return first matching operation; null if no match is found
772     */
773    private static Operation getOperationFromName(EList<Operation> operations, String name) {
774        if (name == null) {
775            throw new IllegalArgumentException("name of the operation must not be null");
776        }
777        if (operations != null) {
778            for (Operation operation : operations) {
779                if (operation.getName() != null && operation.getName().equals(name)) {
780                    return operation;
781                }
782            }
783        }
784        return null;
785    }
786
787    /**
788     * <p>
789     * Determines which transitions match a given {@link SOAPEventType}.
790     * </p>
791     *
792     * @param transitions
793     *            the transitions
794     * @param eventType
795     *            the SOAP event
796     * @return matching transitions
797     */
798    private static List<Transition> matchTransitions(List<Transition> transitions, Event event) {
799        String eventService = SOAPUtils.getServiceNameFromEvent(event);
800        String eventMethod = SOAPUtils.getCalledMethodFromEvent(event);
801
802        Map<Interface, String> interfaceServiceMap =
803            createInterfaceServiceMap(transitions.get(0).getModel());
804
805        List<Transition> matching = new LinkedList<>();
806        for (Transition transition : transitions) {
807            EList<Trigger> triggers = transition.getTriggers();
808            if (triggers.size() == 1) {
809                if (triggers.get(0).getEvent() instanceof CallEvent) {
810                    CallEvent callEvent = (CallEvent) triggers.get(0).getEvent();
811                    String transitionMethod = callEvent.getOperation().getName();
812                    String transitionService =
813                        interfaceServiceMap.get(callEvent.getOperation().getInterface());
814
815                    if (eventMethod.equals(transitionMethod) &&
816                        eventService.equals(transitionService))
817                    {
818                        matching.add(transition);
819                    }
820                }
821            }
822            else {
823                throw new RuntimeException(
824                                           "only one trigger of type CallEvent per transition allowed: " +
825                                               transition.getName());
826            }
827
828        }
829        return matching;
830    }
831
832    /**
833     * <p>
834     * Fetches all realized interfaces from the type of a UML {@link Property} (i.e.,
835     * property.getType()). If no interfaces are realized, an empty set is returned.
836     * </p>
837     *
838     * @param property
839     *            property, of the whose realized interfaces of the type are determined
840     * @return realized interfaces
841     */
842    private static Set<Interface> getRealizedInterfacesFromProperty(Property property) {
843        return getRealizedInterfaceFromComponent((Component) property.getType());
844    }
845
846    /**
847     * <p>
848     * Fetches all realized interfaces from a UML {@link Component}. If no interfaces are realized,
849     * an empty set is returned.
850     * </p>
851     *
852     * @param comp
853     *            component whose realized interfaces are determined
854     * @return realized interfaces
855     */
856    private static Set<Interface> getRealizedInterfaceFromComponent(Component component) {
857        Set<Interface> interfaces = new HashSet<>();
858        // Interface myInterface = null;
859        for (Property property : component.getAllAttributes()) {
860            if (property instanceof Port) {
861                Port port = (Port) property;
862                if (!port.isConjugated()) {
863                    interfaces.addAll(port.getProvideds());
864                }
865            }
866        }
867        return interfaces;
868    }
869
870    /**
871     * <p>
872     * Determines searches within a {@link Package} for a component to which the UTP TestContext
873     * stereotype is applied.
874     * <ul>
875     * <li>If no testContextName is provided, the first test context found is returned.</li>
876     * <li>In case no test context is found, null is returned.</li>
877     * </p>
878     *
879     * @param pkg
880     *            package where the test context is being locked for
881     * @param testContextName
882     *            name of the test context; in case no test name is specified, use null and not the
883     *            empty String.
884     * @return {@link Component} to which the TestContext stereotype is applied
885     */
886    private static Component fetchTestContext(final Package pkg, final String testContextName) {
887        List<Component> testContexts = fetchAllTestContexts(pkg);
888        if (testContexts.isEmpty()) {
889            return null;
890        }
891        if (testContextName != null) {
892            for (Component testContext : testContexts) {
893                if (testContextName.equals(testContext.getName())) {
894                    return testContext;
895                }
896            }
897            return null;
898        }
899        else {
900            return testContexts.get(0);
901        }
902    }
903
904    /**
905     * <p>
906     * Retrieves all UML {@link Component}s to which the UTP TestContext stereotype is applied from
907     * a package. This method calls itself recursively to include all components contained in
908     * sub-packages.
909     * </p>
910     * <p>
911     * In case no test context is found, an empty list is returned.
912     * </p>
913     *
914     * @param pkg
915     *            package from which the test contexts are retrieved
916     * @return {@link List} of test contexts
917     */
918    private static List<Component> fetchAllTestContexts(final Package pkg) {
919        final Stereotype utpTestContext = UTPUtils.getTestContextStereotype(pkg.getModel());
920        final List<Component> testContexts = new LinkedList<>();
921        for (Element element : pkg.getOwnedElements()) {
922            if (element instanceof Package) {
923                testContexts.addAll(fetchAllTestContexts((Package) element));
924            }
925            if (element instanceof Component &&
926                element.getAppliedStereotypes().contains(utpTestContext))
927            {
928                testContexts.add((Component) element);
929            }
930        }
931        return testContexts;
932    }
933
934    /**
935     * <p>
936     * Retrieves all properties that represent a UTP TestComponent from a test context.
937     * </p>
938     *
939     * @param testContext
940     *            test context from which the properties are retrieved
941     * @return properties that represent test components
942     */
943    private static Set<Property> fetchAllTestComponentProperties(final Component testContext) {
944        // fetch all SUTs and TestComponents
945        final Stereotype utpTestComponent =
946            UTPUtils.getTestComponentStereotype(testContext.getModel());
947        final Set<Property> properties = new HashSet<>();
948        for (Property property : testContext.getAllAttributes()) {
949            if (property.getType().getAppliedStereotypes().contains(utpTestComponent)) {
950                properties.add(property);
951            }
952        }
953        return properties;
954    }
955
956    /**
957     * <p>
958     * Retrieves all properties that represent a UTP SUT from a test context.
959     * </p>
960     *
961     * @param testContext
962     *            test context from which the properties are retrieved
963     * @return properties that represent the SUTs
964     */
965    private static Set<Property> fetchAllSUTProperties(final Component testContext) {
966        // fetch all SUTs and TestComponents
967        final Stereotype utpSUT = UTPUtils.getSUTStereotype(testContext.getModel());
968        final Set<Property> properties = new HashSet<>();
969        for (Property property : testContext.getAllAttributes()) {
970            if (property.getAppliedStereotypes().contains(utpSUT)) {
971                properties.add(property);
972            }
973        }
974        return properties;
975    }
976
977    /**
978     * <p>
979     * Infers connector between two lifelines.
980     * </p>
981     * <p>
982     * TODO: Currently assumes only one connector between two lifelines possible. This assumption is
983     * invalid as soon as there are two ports that connect the same two properties.
984     * </p>
985     *
986     * @param msgSourceLifeline
987     *            source lifeline of the message
988     * @param targetAttributes
989     *            target lifeline of the message
990     */
991    private static Connector inferConnector(Lifeline msgSourceLifeline, Lifeline msgTargetLifeline)
992    {
993        EList<Property> userAttributes =
994            ((Component) msgSourceLifeline.getRepresents().getType()).getAttributes();
995        EList<Property> targetAttributes =
996            ((Component) msgTargetLifeline.getRepresents().getType()).getAttributes();
997        for (Property userAttribute : userAttributes) {
998            if (userAttribute instanceof Port) {
999                EList<ConnectorEnd> userEnds = ((Port) userAttribute).getEnds();
1000                for (ConnectorEnd userEnd : userEnds) {
1001                    Connector userConnector = (Connector) userEnd.eContainer();
1002                    for (Property targetAttribute : targetAttributes) {
1003                        if (targetAttribute instanceof Port) {
1004                            EList<ConnectorEnd> targetEnds = ((Port) targetAttribute).getEnds();
1005                            for (ConnectorEnd targetEnd : targetEnds) {
1006                                Connector targetConnector = (Connector) targetEnd.eContainer();
1007                                if (targetConnector == userConnector) {
1008                                    return targetConnector;
1009                                }
1010                            }
1011                        }
1012                    }
1013                }
1014            }
1015        }
1016        return null;
1017    }
1018
1019    /**
1020     * <p>
1021     * Creates a map that maps the interfaces to the properties, i.e., services that they are
1022     * represented by.
1023     * </p>
1024     * <p>
1025     * TODO: currently assumes that each interfaces is only realized by one property
1026     * </p>
1027     *
1028     * @param model
1029     *            model for which the interface->service map is created
1030     * @return the map
1031     */
1032    private static Map<Interface, String> createInterfaceServiceMap(Model model) {
1033        Map<Interface, String> interfaceServiceMap = new HashMap<>();
1034        List<Component> testContexts = fetchAllTestContexts(model.getModel());
1035        for (Component testContext : testContexts) {
1036            for (Property property : fetchAllSUTProperties(testContext)) {
1037                for (Interface intface : getRealizedInterfacesFromProperty(property)) {
1038                    interfaceServiceMap.put(intface, property.getName());
1039                }
1040            }
1041            for (Property property : fetchAllTestComponentProperties(testContext)) {
1042                for (Interface intface : getRealizedInterfacesFromProperty(property)) {
1043                    interfaceServiceMap.put(intface, property.getName());
1044                }
1045            }
1046        }
1047        return interfaceServiceMap;
1048    }
1049
1050    /**
1051     * <p>
1052     * Sets values for the parameters of a call message. The values are, if possible, inferred from
1053     * the event that is provided.
1054     * </p>
1055     *
1056     * @param message
1057     *            call message for which the parameters are set
1058     * @param calledOperation
1059     *            operation that is called by the message
1060     * @param event
1061     *            event that provides the parameters; in case of null, default values are assumed
1062     * @param useRandomMsgBodies
1063     *            defines is random request bodies are used or the body of the associated event
1064     * @param prefix
1065     *            prefix of the call message; used to create good warnings and debugging information
1066     */
1067    private static void setMessageParameters(Message message,
1068                                             Operation calledOperation,
1069                                             Event event,
1070                                             boolean useRandomMsgBodies,
1071                                             String prefix)
1072    {
1073        org.w3c.dom.Element requestBody;
1074        if (SOAPUtils.isSOAPRequest(event)) {
1075            requestBody =
1076                SOAPUtils.getSoapBodyFromEvent(event, useRandomMsgBodies, CallType.REQUEST);
1077        }
1078        else {
1079            requestBody =
1080                SOAPUtils.getSoapBodyFromEvent(event, useRandomMsgBodies, CallType.RESPONSE);
1081        }
1082        Package instSpecPkg = null;
1083        MutableInt instSpecNumber = new MutableInt(0);
1084
1085        // FOR DEBUGGING
1086        // Console.traceln(Level.FINE, "XML structure of path:" + StringTools.ENDLINE +
1087        // SOAPUtils.getSerialization(requestBody));
1088        // for( Parameter param : calledOperation.getOwnedParameters() ) {
1089        // System.out.println(param.getName());
1090        // if( param.getType() instanceof DataType ) {
1091        // for( Property prop1 : ((DataType) param.getType()).getAllAttributes() ) {
1092        // System.out.println("  " + prop1.getName());
1093        // if( prop1.getType() instanceof DataType ) {
1094        // for( Property prop2 : ((DataType) prop1.getType()).getAllAttributes() ) {
1095        // System.out.println("    " + prop2.getName());
1096        // if( prop2.getType() instanceof DataType ) {
1097        // for( Property prop3 : ((DataType) prop2.getType()).getAllAttributes() ) {
1098        // System.out.println("      " + prop3.getName());
1099        // if( prop3.getType() instanceof DataType ) {
1100        // for( Property prop4 : ((DataType) prop3.getType()).getAllAttributes() ) {
1101        // System.out.println("        " + prop4.getName());
1102        // }
1103        // }
1104        // }
1105        // }
1106        // }
1107        // }
1108        // }
1109        // }
1110        // }
1111
1112        // Set parameters of operation
1113        for (Parameter param : calledOperation.getOwnedParameters()) {
1114            if (instSpecPkg == null) {
1115                instSpecPkg = getOrCreateInstanceSpecificationPackage(message.getModel(), event);
1116            }
1117
1118            // TODO String path = calledOperation.getName() + ":" + param.getName();
1119            String path = calledOperation.getName() + ":" + param.getType().getName();
1120            // create param node
1121            // Expression argument =
1122            // (Expression) callMessage.createArgument(param.getName(), param.getType(),
1123            // UMLPackage.Literals.EXPRESSION);
1124            if ((isInParameter(param) && SOAPUtils.isSOAPRequest(event)) ||
1125                (isOutParameter(param) && SOAPUtils.isSOAPResponse(event)))
1126            {
1127
1128                // create parameters node
1129                if (!(param.getType() instanceof DataType)) {
1130                    throw new RuntimeException("TODO error handling; parameters missing");
1131                }
1132                DataType parametersNode = (DataType) param.getType();
1133                InstanceSpecification instSpecParameters =
1134                    (InstanceSpecification) instSpecPkg.createPackagedElement(prefix + "instspec" + instSpecNumber.intValue() + "_" +
1135                        param.getType().getName(), UMLPackage.Literals.INSTANCE_SPECIFICATION);
1136                instSpecParameters.getClassifiers().add((DataType) param.getType());
1137                instSpecNumber.setValue(instSpecNumber.intValue()+1);
1138                // InstanceValue parametersValue =
1139                // (InstanceValue) argument
1140                // .createOperand(param.getType().getName(), param.getType(),
1141                // UMLPackage.Literals.INSTANCE_VALUE);
1142                // parametersValue.setInstance(instSpecParameters);
1143                InstanceValue instanceValue =
1144                    (InstanceValue) message.createArgument(param.getName(), param.getType(),
1145                                                           UMLPackage.Literals.INSTANCE_VALUE);
1146                instanceValue.setInstance(instSpecParameters);
1147
1148                for (Property internalParameter : parametersNode.getAllAttributes()) {
1149                    if (internalParameter.getType() instanceof DataType) {
1150                        List<org.w3c.dom.Element> paramNodes =
1151                            SOAPUtils.getMatchingChildNode(internalParameter.getType().getName(),
1152                                                           requestBody);
1153                        // TODO the mistake is somewhere around here ... probably
1154                        // List<org.w3c.dom.Element> paramNodes =
1155                        // SOAPUtils.getMatchingChildNode(param.getName(), requestBody);
1156                        int multiplicityChosen = paramNodes.size();
1157
1158                        if (multiplicityChosen == 0 && internalParameter.getLower() > 0) {
1159                            Console
1160                                .traceln(Level.WARNING,
1161                                         "required attribute not found in SOAP message: " + path);
1162                            Console
1163                                .traceln(Level.WARNING,
1164                                         "setting default values for this attribute and all its children");
1165                            Console.traceln(Level.FINE, "XML structure of path:" +
1166                                StringTools.ENDLINE + SOAPUtils.getSerialization(requestBody));
1167                            multiplicityChosen = internalParameter.getLower();
1168                        }
1169                        for (int i = 0; i < multiplicityChosen; i++) {
1170                            org.w3c.dom.Element paramNode = null;
1171                            if (!paramNodes.isEmpty()) {
1172                                paramNode = paramNodes.get(i);
1173                            }
1174
1175                            Slot slot = instSpecParameters.createSlot();
1176                            slot.setDefiningFeature(internalParameter);
1177
1178                            InstanceValue value =
1179                                (InstanceValue) slot
1180                                    .createValue(internalParameter.getName() + "_" + i,
1181                                                 internalParameter.getType(),
1182                                                 UMLPackage.Literals.INSTANCE_VALUE);
1183                            value
1184                                .setInstance(createInstanceSpecification((DataType) internalParameter
1185                                                                             .getType(),
1186                                                                         instSpecPkg, prefix, instSpecNumber,
1187                                                                         paramNode, path));
1188                            /*
1189                             * InstanceValue value = (InstanceValue) argument .createOperand(null,
1190                             * internalParameter.getType(), UMLPackage.Literals.INSTANCE_VALUE);
1191                             * value.setInstance(instSpec);
1192                             */
1193                        }
1194                    }
1195                    else if (internalParameter.getType() instanceof PrimitiveType) {
1196                        createSlotPrimitiveType(instSpecParameters, internalParameter, requestBody,
1197                                                path);
1198                    }
1199                }
1200            }
1201            else {
1202                // set literalNull for out and return parameters
1203                // argument.createOperand(null, param.getType(), UMLPackage.Literals.LITERAL_NULL);
1204                message.createArgument(param.getName(), param.getType(),
1205                                       UMLPackage.Literals.LITERAL_NULL);
1206            }
1207        }
1208    }
1209
1210    /**
1211     * <p>
1212     * Creates an {@link InstanceSpecification} for a data type in the given package. The values are
1213     * inferred, if possible, from the DOM node. The prefix and the path are used for naming the
1214     * instance specification and to provide good warnings and debug information in case of
1215     * problems.
1216     * </p>
1217     *
1218     * @param type
1219     *            DataType for which the {@link InstanceSpecification} is created
1220     * @param pkg
1221     *            package in which the {@link InstanceSpecification} is created
1222     * @param prefix
1223     *            prefix used for naming the {@link InstanceSpecification}
1224     * @param currentNode
1225     *            node of a DOM from which values are inferred
1226     * @param path
1227     *            used for warnings and debug information
1228     * @return {@link InstanceSpecification} for the given type
1229     */
1230    private static InstanceSpecification createInstanceSpecification(DataType type,
1231                                                                     Package pkg,
1232                                                                     String prefix,
1233                                                                     MutableInt instSpecNumber,
1234                                                                     org.w3c.dom.Element currentNode,
1235                                                                     String path)
1236    {
1237        if ("".equals(path)) {
1238            path = type.getName();
1239        }
1240
1241        InstanceSpecification instSpec =
1242            (InstanceSpecification) pkg
1243                .createPackagedElement(prefix + "instspec" + instSpecNumber.intValue() + "_" + type.getName(),
1244                                       UMLPackage.Literals.INSTANCE_SPECIFICATION);
1245        instSpec.getClassifiers().add(type);
1246        instSpecNumber.setValue(instSpecNumber.intValue()+1);
1247        for (Property prop : type.getAllAttributes()) {
1248            if (prop.getType() instanceof PrimitiveType) {
1249                createSlotPrimitiveType(instSpec, prop, currentNode, path);
1250            }
1251            else if (prop.getType() instanceof DataType) {
1252                List<org.w3c.dom.Element> attributeNodes = null;
1253                int multiplicityChosen = 0;
1254                if (currentNode != null) {
1255                    // TODO attributeNodes = SOAPUtils.getMatchingChildNode(prop.getName(),
1256                    // currentNode);
1257                    attributeNodes = SOAPUtils.getMatchingChildNode(prop.getName(), currentNode);
1258                    multiplicityChosen = attributeNodes.size();
1259                }
1260
1261                if (multiplicityChosen == 0 && prop.getLower() > 0) {
1262                    if (currentNode != null) {
1263                        Console.traceln(Level.WARNING,
1264                                        "required attribute not found in SOAP message: " + path +
1265                                            "." + prop.getName());
1266                        Console
1267                            .traceln(Level.WARNING,
1268                                     "setting default values for this attribute and all its children");
1269                        Console.traceln(Level.FINE, "XML structure of path:" + StringTools.ENDLINE +
1270                            SOAPUtils.getSerialization(currentNode));
1271                    }
1272                    multiplicityChosen = prop.getLower();
1273                }
1274                for (int i = 0; i < multiplicityChosen; i++) {
1275                    org.w3c.dom.Element attributeNode = null;
1276                    if (attributeNodes != null && !attributeNodes.isEmpty()) {
1277                        attributeNode = attributeNodes.get(i);
1278                    }
1279
1280                    Slot slot = instSpec.createSlot();
1281                    slot.setDefiningFeature(prop);
1282
1283                    InstanceValue value =
1284                        (InstanceValue) slot.createValue(prop.getName() + "_" + i, prop.getType(),
1285                                                         UMLPackage.Literals.INSTANCE_VALUE);
1286                    value.setInstance(createInstanceSpecification((DataType) prop.getType(), pkg,
1287                                                                  prefix, instSpecNumber, attributeNode, path +
1288                                                                      "." + prop.getName()));
1289                }
1290            }
1291            else {
1292                Console.traceln(Level.SEVERE, "property neither DataType nor PrimitiveType: " +
1293                    prop.getType());
1294                // TODO abort?
1295            }
1296        }
1297        return instSpec;
1298    }
1299
1300    /**
1301     * <p>
1302     * Gets or creates a {@link Package} for {@link InstanceSpecification} created by the
1303     * usage-based testing. Each service gets its own sub-package within a package called
1304     * UBT_InstanceSpecifications. "
1305     * </p>
1306     *
1307     * @param model
1308     *            model in which the package is generated
1309     * @param event
1310     *            event from which the service name is inferred
1311     * @return package for the {@link InstanceSpecification}s
1312     */
1313    private static Package getOrCreateInstanceSpecificationPackage(Model model, Event event) {
1314        String pkgUBTInstSpecs = "UBT_InstanceSpecifications";
1315        Package ubtInstSpecPkg = (Package) model.getOwnedMember(pkgUBTInstSpecs);
1316        if (ubtInstSpecPkg == null) {
1317            ubtInstSpecPkg =
1318                (Package) model.createPackagedElement(pkgUBTInstSpecs, UMLPackage.Literals.PACKAGE);
1319        }
1320        String serviceName = SOAPUtils.getServiceNameFromEvent(event);
1321        Package serviceInstSpecPkg = (Package) ubtInstSpecPkg.getOwnedMember(serviceName);
1322        if (serviceInstSpecPkg == null) {
1323            serviceInstSpecPkg =
1324                (Package) ubtInstSpecPkg.createPackagedElement(serviceName,
1325                                                               UMLPackage.Literals.PACKAGE);
1326        }
1327        return serviceInstSpecPkg;
1328    }
1329
1330    /**
1331     * <p>
1332     * Creates an operand that defines a {@link PrimitiveType}.
1333     * </p>
1334     * <p>
1335     * TODO: Currently does nothing in case of multiplicity 0. I am not sure if, in that case, one
1336     * has to define LiteralNull instead.
1337     * </p>
1338     *
1339     * @param param
1340     *            parameter for which the operand is created
1341     * @param argument
1342     *            argument to which the operand is added
1343     * @param currentNode
1344     *            DOM node from which is value for the operand is inferred
1345     * @param path
1346     *            used for warnings and debug information
1347     */
1348    private static void createOperandPrimitiveType(Parameter param,
1349                                                   Expression argument,
1350                                                   org.w3c.dom.Element currentNode,
1351                                                   String path)
1352    {
1353        List<String> attributeValues = SOAPUtils.getValuesFromElement(param.getName(), currentNode);
1354
1355        if (attributeValues.isEmpty()) {
1356            if (param.getLower() == 0) {
1357                // ignoring optional attribute
1358                return;
1359            }
1360            else {
1361                if (currentNode != null) {
1362                    Console.traceln(Level.WARNING,
1363                                    "required attribute not found in SOAP message: " + path + "." +
1364                                        param.getName());
1365                    Console.traceln(Level.WARNING, "setting default values for this attribute");
1366                    Console.traceln(Level.FINE, "XML structure of path:" + StringTools.ENDLINE +
1367                        SOAPUtils.getSerialization(currentNode));
1368                }
1369                attributeValues.add(null);
1370            }
1371        }
1372        for (String attributeValue : attributeValues) {
1373            if ("String".equals(param.getType().getName())) {
1374                LiteralString spec =
1375                    (LiteralString) argument.createOperand(param.getName(), null,
1376                                                           UMLPackage.Literals.LITERAL_STRING);
1377                if (attributeValue != null) {
1378                    spec.setValue(attributeValue);
1379                }
1380                else {
1381                    spec.setValue("foobar");
1382                }
1383            }
1384            else if ("Integer".equals(param.getType().getName())) {
1385                LiteralInteger spec =
1386                    (LiteralInteger) argument.createOperand(param.getName(), null,
1387                                                            UMLPackage.Literals.LITERAL_INTEGER);
1388                if (attributeValue != null) {
1389                    spec.setValue(Integer.parseInt(attributeValue));
1390                }
1391                else {
1392                    spec.setValue(42);
1393                }
1394            }
1395            else if ("Boolean".equals(param.getType().getName())) {
1396                LiteralBoolean spec =
1397                    (LiteralBoolean) argument.createOperand(param.getName(), null,
1398                                                            UMLPackage.Literals.LITERAL_BOOLEAN);
1399                if (attributeValue != null) {
1400                    spec.setValue(Boolean.parseBoolean(attributeValue));
1401                }
1402                else {
1403                    spec.setValue(true);
1404                }
1405            }
1406            else if ("Real".equals(param.getType().getName())) {
1407                LiteralReal spec =
1408                    (LiteralReal) argument.createOperand(param.getName(), null,
1409                                                         UMLPackage.Literals.LITERAL_REAL);
1410                if (attributeValue != null) {
1411                    spec.setValue(Double.parseDouble(attributeValue));
1412                }
1413                else {
1414                    spec.setValue(3.14);
1415                }
1416            }
1417        }
1418    }
1419
1420    /**
1421     * <p>
1422     * Creates a {@link Slot} in an {@link InstanceSpecification} for a primitive type.
1423     * </p>
1424     *
1425     * @param instSpec
1426     *            instance specification to which the slot is added
1427     * @param prop
1428     *            property that describes the slot
1429     * @param currentNode
1430     *            DOM node from which is value for the slot is inferred
1431     * @param path
1432     *            used for warnings and debug information
1433     */
1434    private static void createSlotPrimitiveType(InstanceSpecification instSpec,
1435                                                Property prop,
1436                                                org.w3c.dom.Element currentNode,
1437                                                String path)
1438    {
1439        List<String> attributeValues = SOAPUtils.getValuesFromElement(prop.getName(), currentNode);
1440
1441        if (attributeValues.isEmpty()) {
1442            if (prop.getLower() == 0) {
1443                // ignoring optional attribute
1444                return;
1445            }
1446            else {
1447                if (currentNode != null) {
1448                    Console.traceln(Level.WARNING,
1449                                    "required attribute not found in SOAP message: " + path + "." +
1450                                        prop.getName());
1451                    Console.traceln(Level.WARNING, "setting default values for this attribute");
1452                    Console.traceln(Level.FINE, "XML structure of path:" + StringTools.ENDLINE +
1453                        SOAPUtils.getSerialization(currentNode));
1454                }
1455                attributeValues.add(null);
1456            }
1457        }
1458        for (String attributeValue : attributeValues) {
1459            Slot slot = instSpec.createSlot();
1460            slot.setDefiningFeature(prop);
1461            if ("String".equals(prop.getType().getName())) {
1462                LiteralString value =
1463                    (LiteralString) slot.createValue(prop.getName(), null,
1464                                                     UMLPackage.Literals.LITERAL_STRING);
1465                if (attributeValue != null) {
1466                    value.setValue(attributeValue);
1467                }
1468                else {
1469                    value.setValue("foobar");
1470                }
1471            }
1472            else if ("Integer".equals(prop.getType().getName())) {
1473                LiteralInteger value =
1474                    (LiteralInteger) slot.createValue(prop.getName(), null,
1475                                                      UMLPackage.Literals.LITERAL_INTEGER);
1476                if (attributeValue != null) {
1477                    value.setValue(Integer.parseInt(attributeValue));
1478                }
1479                else {
1480                    value.setValue(42);
1481                }
1482            }
1483            else if ("Boolean".equals(prop.getType().getName())) {
1484                LiteralBoolean value =
1485                    (LiteralBoolean) slot.createValue(prop.getName(), null,
1486                                                      UMLPackage.Literals.LITERAL_BOOLEAN);
1487                if (attributeValue != null) {
1488                    value.setValue(Boolean.parseBoolean(attributeValue));
1489                }
1490                else {
1491                    value.setValue(true);
1492                }
1493            }
1494            else if ("Real".equals(prop.getType().getName())) {
1495                LiteralReal value =
1496                    (LiteralReal) slot.createValue(prop.getName(), null,
1497                                                   UMLPackage.Literals.LITERAL_REAL);
1498                if (attributeValue != null) {
1499                    value.setValue(Double.parseDouble(attributeValue));
1500                }
1501                else {
1502                    value.setValue(3.14);
1503                }
1504            }
1505            else {
1506                Console.traceln(Level.SEVERE, "could not create literal for primitive type: " +
1507                    prop.getType().getName());
1508                // TODO abort?
1509            }
1510        }
1511    }
1512
1513    /**
1514     * <p>
1515     * Sets values for the parameters of a reply message. The values are, all LiterealNull and to
1516     * the INOUT, OUT and REPLY parameters, the UTP stereotype LiteralAny is applied.
1517     * </p>
1518     *
1519     * @param replyMessage
1520     *            reply message for which the parameters are set
1521     * @param calledOperation
1522     *            operation that is replied for by the message
1523     */
1524    private static void setReplyMessageParameters(Message replyMessage, Operation calledOperation) {
1525        for (Parameter param : calledOperation.getOwnedParameters()) {
1526            LiteralNull argument =
1527                (LiteralNull) replyMessage.createArgument(param.getName(), param.getType(),
1528                                                          UMLPackage.Literals.LITERAL_NULL);
1529
1530            if (isOutParameter(param)) {
1531                argument.applyStereotype(UTPUtils.getLiteralAnyStereotype(replyMessage.getModel()));
1532            }
1533        }
1534    }
1535
1536    /**
1537     * <p>
1538     * Checks if a parameter has the direction IN or INOUT
1539     * </p>
1540     *
1541     * @param parameter
1542     *            parameter that is checked
1543     * @return true if the direction is IN or INOUT; false otherwise
1544     */
1545    private static boolean isInParameter(Parameter parameter) {
1546        return parameter.getDirection() == ParameterDirectionKind.IN_LITERAL ||
1547            parameter.getDirection() == ParameterDirectionKind.INOUT_LITERAL;
1548    }
1549
1550    /**
1551     * <p>
1552     * Checks if a parameter has the direction RETURN, OUT or INOUT
1553     * </p>
1554     *
1555     * @param parameter
1556     *            parameter that is checked
1557     * @return true if the direction is RETURN, OUT, or INOUT; false otherwise
1558     */
1559    private static boolean isOutParameter(Parameter parameter) {
1560        return parameter.getDirection() == ParameterDirectionKind.RETURN_LITERAL ||
1561            parameter.getDirection() == ParameterDirectionKind.OUT_LITERAL ||
1562            parameter.getDirection() == ParameterDirectionKind.INOUT_LITERAL;
1563    }
1564
1565    /**
1566     * <p>
1567     * Checks if the {@link MessageSort} of a message is a call message, i.e., ASYNCH_CALL or
1568     * SYNCH_CALL.
1569     * </p>
1570     *
1571     * @param message
1572     *            message that is checked
1573     * @return true if the message is a call message; false otherwise
1574     */
1575    private static boolean isCallMessage(Message message) {
1576        if (message == null) {
1577            return false;
1578        }
1579        MessageSort msgSort = message.getMessageSort();
1580        return msgSort == MessageSort.ASYNCH_CALL_LITERAL ||
1581            msgSort == MessageSort.SYNCH_CALL_LITERAL;
1582    }
1583
1584    /**
1585     * <p>
1586     * inverse-sorts the values of a map. Has been adapted from <a href=
1587     * "http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java"
1588     * >this</a> StackOverflow post.
1589     * </p>
1590     *
1591     * @param map
1592     *            map whose values are sorted
1593     * @return sorted version of the map
1594     */
1595    private static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
1596        // TODO possibly move to another class
1597        List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
1598        Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
1599            @Override
1600            public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
1601                return -1 * (o1.getValue()).compareTo(o2.getValue());
1602            }
1603        });
1604
1605        Map<K, V> result = new LinkedHashMap<>();
1606        for (Map.Entry<K, V> entry : list) {
1607            result.put(entry.getKey(), entry.getValue());
1608        }
1609        return result;
1610    }
1611}
Note: See TracBrowser for help on using the repository browser.