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

Last change on this file since 2002 was 2002, checked in by sherbold, 9 years ago
  • removed debugging output
  • Property svn:mime-type set to text/plain
File size: 72.7 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.NamedElement;
63import org.eclipse.uml2.uml.Operation;
64import org.eclipse.uml2.uml.Package;
65import org.eclipse.uml2.uml.Parameter;
66import org.eclipse.uml2.uml.ParameterDirectionKind;
67import org.eclipse.uml2.uml.Port;
68import org.eclipse.uml2.uml.PrimitiveType;
69import org.eclipse.uml2.uml.Property;
70import org.eclipse.uml2.uml.Region;
71import org.eclipse.uml2.uml.Slot;
72import org.eclipse.uml2.uml.StateMachine;
73import org.eclipse.uml2.uml.Stereotype;
74import org.eclipse.uml2.uml.Transition;
75import org.eclipse.uml2.uml.Trigger;
76import org.eclipse.uml2.uml.UMLPackage;
77import org.eclipse.uml2.uml.Vertex;
78
79import de.ugoe.cs.autoquest.eventcore.Event;
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, targetInterface);
539                if( connector==null ) {
540                    throw new RuntimeException("Error creating message: could not find connector between the two life lines that supports the target interface at the target lifeline");
541                }
542
543                boolean asynch = false;
544                if (calledOperation.getConcurrency() == CallConcurrencyKind.CONCURRENT_LITERAL) {
545                    asynch = true;
546                }
547
548                if (SOAPUtils.isSOAPRequest(event)) {
549                    // setup for both SYNCH and ASYNCH calls
550                    MessageOccurrenceSpecification callSendFragment =
551                        (MessageOccurrenceSpecification) interaction
552                            .createFragment(prefix + "callSendFragment",
553                                            UMLPackage.Literals.MESSAGE_OCCURRENCE_SPECIFICATION);
554                    MessageOccurrenceSpecification callRecvFragment =
555                        (MessageOccurrenceSpecification) interaction
556                            .createFragment(prefix + "callRecvFragment",
557                                            UMLPackage.Literals.MESSAGE_OCCURRENCE_SPECIFICATION);
558
559                    callSendFragment.setCovered(msgSourceLifeline);
560                    callRecvFragment.setCovered(msgTargetLifeline);
561
562                    // create call
563                    Message callMessage = interaction.createMessage(prefix + "call");
564                    callMessage.setSignature(calledOperation);
565                    setMessageParameters(callMessage, calledOperation, event,
566                                         useRandomRequestBodies, prefix);
567                    callMessage.setConnector(connector);
568                    callMessage.setSendEvent(callSendFragment);
569                    callMessage.setReceiveEvent(callRecvFragment);
570                    callSendFragment.setMessage(callMessage);
571                    callRecvFragment.setMessage(callMessage);
572
573                    if (asynch) {
574                        // Create ASYNCH call
575                        callMessage.setMessageSort(MessageSort.ASYNCH_CALL_LITERAL);
576                    }
577                    else {
578                        // SYNCH call
579                        callMessage.setMessageSort(MessageSort.SYNCH_CALL_LITERAL);
580                    }
581                }
582                if (!asynch && SOAPUtils.isSOAPResponse(event)) {
583                    // setup reply and behavior execution specifications
584                    MessageOccurrenceSpecification replySendFragment =
585                        (MessageOccurrenceSpecification) interaction
586                            .createFragment(prefix + "replySendFragment",
587                                            UMLPackage.Literals.MESSAGE_OCCURRENCE_SPECIFICATION);
588                    MessageOccurrenceSpecification replyRecvFragment =
589                        (MessageOccurrenceSpecification) interaction
590                            .createFragment(prefix + "replyRecvFragment",
591                                            UMLPackage.Literals.MESSAGE_OCCURRENCE_SPECIFICATION);
592
593                    replySendFragment.setCovered(msgTargetLifeline);
594                    replyRecvFragment.setCovered(msgSourceLifeline);
595
596                    /*
597                     * BehaviorExecutionSpecification sourceBehaviorExecutionSpecification =
598                     * (BehaviorExecutionSpecification) interaction .createFragment(":" + methodName
599                     * + "_sourceBhvExecSpec",
600                     * UMLPackage.Literals.BEHAVIOR_EXECUTION_SPECIFICATION);
601                     * BehaviorExecutionSpecification targetBehaviorExecutionSpecification =
602                     * (BehaviorExecutionSpecification) interaction .createFragment(":" + methodName
603                     * + "_targetBhvExecSpec",
604                     * UMLPackage.Literals.BEHAVIOR_EXECUTION_SPECIFICATION);
605                     *
606                     * sourceBehaviorExecutionSpecification.setStart(callSendFragment);
607                     * sourceBehaviorExecutionSpecification.setFinish(replyRecvFragment);
608                     * targetBehaviorExecutionSpecification.setStart(callRecvFragment);
609                     * targetBehaviorExecutionSpecification.setFinish(replySendFragment);
610                     */
611
612                    // create reply
613                    Message replyMessage = interaction.createMessage(prefix + "_reply");
614                    replyMessage.setMessageSort(MessageSort.REPLY_LITERAL);
615                    replyMessage.setSignature(calledOperation);
616                    // setReplyMessageParameters(replyMessage, calledOperation);
617                    setMessageParameters(replyMessage, calledOperation, event,
618                                         useRandomRequestBodies, prefix);
619                    replyMessage.setConnector(connector);
620                    replyMessage.setSendEvent(replySendFragment);
621                    replyMessage.setReceiveEvent(replyRecvFragment);
622                    replySendFragment.setMessage(replyMessage);
623                    replyRecvFragment.setMessage(replyMessage);
624                }
625
626                i++;
627            }
628        }
629        return interaction;
630    }
631
632    /**
633     * <p>
634     * Calculates the usage score of an interaction as the logsum of the event probabilities
635     * multiplied with the length of the interaction.
636     * </p>
637     *
638     * @param interaction
639     *            interaction for which the score is calculated
640     * @param usageProfile
641     *            usage profile used for the calculation
642     * @return calculated usage score
643     */
644    public static double calculateUsageScore(Interaction interaction,
645                                             IStochasticProcess usageProfile)
646    {
647        double usageScore = 0.0d;
648        EList<InteractionFragment> interactionFragments = interaction.getFragments();
649        List<Event> eventSequence = new LinkedList<>();
650        eventSequence.add(Event.STARTEVENT);
651        for (InteractionFragment interactionFragment : interactionFragments) {
652            if (interactionFragment instanceof MessageOccurrenceSpecification) {
653                Message message =
654                    ((MessageOccurrenceSpecification) interactionFragment).getMessage();
655                // if (message.getReceiveEvent().equals(interactionFragment) &&
656                // isCallMessage(message))
657                if (message.getReceiveEvent().equals(interactionFragment)) {
658                    String clientName;
659                    String serviceName;
660                    String methodName = message.getSignature().getName();
661                    CallType callType;
662                    if (isCallMessage(message)) {
663                        clientName =
664                            ((MessageOccurrenceSpecification) message.getSendEvent()).getCovereds()
665                                .get(0).getName();
666                        serviceName =
667                            ((MessageOccurrenceSpecification) message.getReceiveEvent())
668                                .getCovereds().get(0).getName();
669                        callType = CallType.REQUEST;
670                    }
671                    else {
672                        clientName =
673                            ((MessageOccurrenceSpecification) message.getReceiveEvent())
674                                .getCovereds().get(0).getName();
675                        serviceName =
676                            ((MessageOccurrenceSpecification) message.getSendEvent()).getCovereds()
677                                .get(0).getName();
678                        callType = CallType.RESPONSE;
679                    }
680                    eventSequence.add(new Event(new SimpleSOAPEventType(methodName, serviceName,
681                                                                        clientName, null, null,
682                                                                        callType)));
683                }
684            }
685        }
686        eventSequence.add(Event.ENDEVENT);
687        double prob = usageProfile.getLogSum(eventSequence);
688        usageScore = eventSequence.size() * prob;
689
690        return usageScore;
691    }
692
693    /**
694     * <p>
695     * Extends the given model with an activity for usage-based scheduling of the test cases.
696     * </p>
697     *
698     * @param model
699     *            model to be extended
700     * @param usageProfile
701     *            usage profile used as foundation
702     */
703    public static void createScheduling(Model model,
704                                        IStochasticProcess usageProfile,
705                                        String testContextName)
706    {
707        final Component testContext = fetchTestContext(model, testContextName);
708        if (testContext == null) {
709            throw new RuntimeException("Could not find any test context in the model");
710        }
711
712        Map<Operation, Double> usageScoreMapUnsorted = new HashMap<>();
713
714        // first, we determine all test cases and calculate their usage scores
715        final Stereotype utpTestCase = UTPUtils.getTestCaseStereotype(model);
716        for (Operation operation : testContext.getAllOperations()) {
717            if (operation.getAppliedStereotypes().contains(utpTestCase) &&
718                !operation.getMethods().isEmpty())
719            {
720                Interaction interaction = (Interaction) operation.getMethods().get(0);
721                usageScoreMapUnsorted
722                    .put(operation, calculateUsageScore(interaction, usageProfile));
723            }
724        }
725        Map<Operation, Double> usageScoreMapSorted = sortByValue(usageScoreMapUnsorted);
726
727        // now we create the scheduling
728        Activity schedulingActivity =
729            (Activity) testContext.createOwnedBehavior("UsageBasedScheduling",
730                                                       UMLPackage.Literals.ACTIVITY);
731        testContext.setClassifierBehavior(schedulingActivity);
732
733        ActivityNode startNode =
734            schedulingActivity.createOwnedNode("final", UMLPackage.Literals.INITIAL_NODE);
735        ActivityNode finalNode =
736            schedulingActivity.createOwnedNode("final", UMLPackage.Literals.ACTIVITY_FINAL_NODE);
737
738        ActivityNode currentOperationNode = startNode;
739
740        for (Entry<Operation, Double> entry : usageScoreMapSorted.entrySet()) {
741            Operation operation = entry.getKey();
742            CallOperationAction nextOperationNode =
743                (CallOperationAction) schedulingActivity
744                    .createOwnedNode(operation.getName(), UMLPackage.Literals.CALL_OPERATION_ACTION);
745            nextOperationNode.setOperation(operation);
746
747            ActivityEdge edge =
748                schedulingActivity.createEdge(currentOperationNode.getName() + "_to_" +
749                    nextOperationNode.getName(), UMLPackage.Literals.CONTROL_FLOW);
750            edge.setSource(currentOperationNode);
751            edge.setTarget(nextOperationNode);
752
753            currentOperationNode = nextOperationNode;
754        }
755
756        ActivityEdge edge =
757            schedulingActivity
758                .createEdge(currentOperationNode.getName() + "_to_" + finalNode.getName(),
759                            UMLPackage.Literals.CONTROL_FLOW);
760        edge.setSource(currentOperationNode);
761        edge.setTarget(finalNode);
762    }
763
764    /**
765     * <p>
766     * Fetches an operation using only its name from a list of operations. Returns the first match
767     * found or null if no match is found.
768     * </p>
769     *
770     * @param operations
771     *            list of operations
772     * @param name
773     *            name of the operation
774     * @return first matching operation; null if no match is found
775     */
776    private static Operation getOperationFromName(EList<Operation> operations, String name) {
777        if (name == null) {
778            throw new IllegalArgumentException("name of the operation must not be null");
779        }
780        if (operations != null) {
781            for (Operation operation : operations) {
782                if (operation.getName() != null && operation.getName().equals(name)) {
783                    return operation;
784                }
785            }
786        }
787        return null;
788    }
789
790    /**
791     * <p>
792     * Determines which transitions match a given {@link SOAPEventType}.
793     * </p>
794     *
795     * @param transitions
796     *            the transitions
797     * @param eventType
798     *            the SOAP event
799     * @return matching transitions
800     */
801    private static List<Transition> matchTransitions(List<Transition> transitions, Event event) {
802        String eventService = SOAPUtils.getServiceNameFromEvent(event);
803        String eventMethod = SOAPUtils.getCalledMethodFromEvent(event);
804
805        Map<Interface, String> interfaceServiceMap =
806            createInterfaceServiceMap(transitions.get(0).getModel());
807
808        List<Transition> matching = new LinkedList<>();
809        for (Transition transition : transitions) {
810            EList<Trigger> triggers = transition.getTriggers();
811            if (triggers.size() == 1) {
812                if (triggers.get(0).getEvent() instanceof CallEvent) {
813                    CallEvent callEvent = (CallEvent) triggers.get(0).getEvent();
814                    String transitionMethod = callEvent.getOperation().getName();
815                    String transitionService =
816                        interfaceServiceMap.get(callEvent.getOperation().getInterface());
817
818                    if (eventMethod.equals(transitionMethod) &&
819                        eventService.equals(transitionService))
820                    {
821                        matching.add(transition);
822                    }
823                }
824            }
825            else {
826                throw new RuntimeException(
827                                           "only one trigger of type CallEvent per transition allowed: " +
828                                               transition.getName());
829            }
830
831        }
832        return matching;
833    }
834
835    /**
836     * <p>
837     * Fetches all realized interfaces from the type of a UML {@link Property} (i.e.,
838     * property.getType()). If no interfaces are realized, an empty set is returned.
839     * </p>
840     *
841     * @param property
842     *            property, of the whose realized interfaces of the type are determined
843     * @return realized interfaces
844     */
845    private static Set<Interface> getRealizedInterfacesFromProperty(Property property) {
846        return getRealizedInterfaceFromComponent((Component) property.getType());
847    }
848
849    /**
850     * <p>
851     * Fetches all realized interfaces from a UML {@link Component}. If no interfaces are realized,
852     * an empty set is returned.
853     * </p>
854     *
855     * @param comp
856     *            component whose realized interfaces are determined
857     * @return realized interfaces
858     */
859    private static Set<Interface> getRealizedInterfaceFromComponent(Component component) {
860        Set<Interface> interfaces = new HashSet<>();
861        // Interface myInterface = null;
862        for (Property property : component.getAllAttributes()) {
863            if (property instanceof Port) {
864                Port port = (Port) property;
865                if (!port.isConjugated()) {
866                    interfaces.addAll(port.getProvideds());
867                }
868            }
869        }
870        return interfaces;
871    }
872
873    /**
874     * <p>
875     * Determines searches within a {@link Package} for a component to which the UTP TestContext
876     * stereotype is applied.
877     * <ul>
878     * <li>If no testContextName is provided, the first test context found is returned.</li>
879     * <li>In case no test context is found, null is returned.</li>
880     * </p>
881     *
882     * @param pkg
883     *            package where the test context is being locked for
884     * @param testContextName
885     *            name of the test context; in case no test name is specified, use null and not the
886     *            empty String.
887     * @return {@link Component} to which the TestContext stereotype is applied
888     */
889    private static Component fetchTestContext(final Package pkg, final String testContextName) {
890        List<Component> testContexts = fetchAllTestContexts(pkg);
891        if (testContexts.isEmpty()) {
892            return null;
893        }
894        if (testContextName != null) {
895            for (Component testContext : testContexts) {
896                if (testContextName.equals(testContext.getName())) {
897                    return testContext;
898                }
899            }
900            return null;
901        }
902        else {
903            return testContexts.get(0);
904        }
905    }
906
907    /**
908     * <p>
909     * Retrieves all UML {@link Component}s to which the UTP TestContext stereotype is applied from
910     * a package. This method calls itself recursively to include all components contained in
911     * sub-packages.
912     * </p>
913     * <p>
914     * In case no test context is found, an empty list is returned.
915     * </p>
916     *
917     * @param pkg
918     *            package from which the test contexts are retrieved
919     * @return {@link List} of test contexts
920     */
921    private static List<Component> fetchAllTestContexts(final Package pkg) {
922        final Stereotype utpTestContext = UTPUtils.getTestContextStereotype(pkg.getModel());
923        final List<Component> testContexts = new LinkedList<>();
924        for (Element element : pkg.getOwnedElements()) {
925            if (element instanceof Package) {
926                testContexts.addAll(fetchAllTestContexts((Package) element));
927            }
928            if (element instanceof Component &&
929                element.getAppliedStereotypes().contains(utpTestContext))
930            {
931                testContexts.add((Component) element);
932            }
933        }
934        return testContexts;
935    }
936
937    /**
938     * <p>
939     * Retrieves all properties that represent a UTP TestComponent from a test context.
940     * </p>
941     *
942     * @param testContext
943     *            test context from which the properties are retrieved
944     * @return properties that represent test components
945     */
946    private static Set<Property> fetchAllTestComponentProperties(final Component testContext) {
947        // fetch all SUTs and TestComponents
948        final Stereotype utpTestComponent =
949            UTPUtils.getTestComponentStereotype(testContext.getModel());
950        final Set<Property> properties = new HashSet<>();
951        for (Property property : testContext.getAllAttributes()) {
952            if (property.getType().getAppliedStereotypes().contains(utpTestComponent)) {
953                properties.add(property);
954            }
955        }
956        return properties;
957    }
958
959    /**
960     * <p>
961     * Retrieves all properties that represent a UTP SUT from a test context.
962     * </p>
963     *
964     * @param testContext
965     *            test context from which the properties are retrieved
966     * @return properties that represent the SUTs
967     */
968    private static Set<Property> fetchAllSUTProperties(final Component testContext) {
969        // fetch all SUTs and TestComponents
970        final Stereotype utpSUT = UTPUtils.getSUTStereotype(testContext.getModel());
971        final Set<Property> properties = new HashSet<>();
972        for (Property property : testContext.getAllAttributes()) {
973            if (property.getAppliedStereotypes().contains(utpSUT)) {
974                properties.add(property);
975            }
976        }
977        return properties;
978    }
979
980    /**
981     * <p>
982     * Infers connector between two lifelines.
983     * </p>
984     *
985     * @param msgSourceLifeline
986     *            source lifeline of the message
987     * @param targetAttributes
988     *            target lifeline of the message
989     */
990    private static Connector inferConnector(Lifeline msgSourceLifeline, Lifeline msgTargetLifeline, Interface targetInterface)
991    {
992        EList<Property> userAttributes =
993            ((Component) msgSourceLifeline.getRepresents().getType()).getAllAttributes();
994        EList<Property> targetAttributes =
995            ((Component) msgTargetLifeline.getRepresents().getType()).getAllAttributes();
996        for (Property userAttribute : userAttributes) {
997            if (userAttribute instanceof Port) {
998                EList<ConnectorEnd> userEnds = ((Port) userAttribute).getEnds();
999                for (ConnectorEnd userEnd : userEnds) {
1000                    Connector userConnector = (Connector) userEnd.eContainer();
1001                    for (Property targetAttribute : targetAttributes) {
1002                        if (targetAttribute instanceof Port) {
1003                            if( ((Port) targetAttribute).getProvideds().contains(targetInterface) ) {
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        }
1017        return null;
1018    }
1019
1020    /**
1021     * <p>
1022     * Creates a map that maps the interfaces to the properties, i.e., services that they are
1023     * represented by.
1024     * </p>
1025     * <p>
1026     * TODO: currently assumes that each interfaces is only realized by one property
1027     * </p>
1028     *
1029     * @param model
1030     *            model for which the interface->service map is created
1031     * @return the map
1032     */
1033    private static Map<Interface, String> createInterfaceServiceMap(Model model) {
1034        Map<Interface, String> interfaceServiceMap = new HashMap<>();
1035        List<Component> testContexts = fetchAllTestContexts(model.getModel());
1036        for (Component testContext : testContexts) {
1037            for (Property property : fetchAllSUTProperties(testContext)) {
1038                for (Interface intface : getRealizedInterfacesFromProperty(property)) {
1039                    interfaceServiceMap.put(intface, property.getName());
1040                }
1041            }
1042            for (Property property : fetchAllTestComponentProperties(testContext)) {
1043                for (Interface intface : getRealizedInterfacesFromProperty(property)) {
1044                    interfaceServiceMap.put(intface, property.getName());
1045                }
1046            }
1047        }
1048        return interfaceServiceMap;
1049    }
1050
1051    /**
1052     * <p>
1053     * Sets values for the parameters of a call message. The values are, if possible, inferred from
1054     * the event that is provided.
1055     * </p>
1056     *
1057     * @param message
1058     *            call message for which the parameters are set
1059     * @param calledOperation
1060     *            operation that is called by the message
1061     * @param event
1062     *            event that provides the parameters; in case of null, default values are assumed
1063     * @param useRandomMsgBodies
1064     *            defines is random request bodies are used or the body of the associated event
1065     * @param prefix
1066     *            prefix of the call message; used to create good warnings and debugging information
1067     */
1068    private static void setMessageParameters(Message message,
1069                                             Operation calledOperation,
1070                                             Event event,
1071                                             boolean useRandomMsgBodies,
1072                                             String prefix)
1073    {
1074        org.w3c.dom.Element requestBody;
1075        if (SOAPUtils.isSOAPRequest(event)) {
1076            requestBody =
1077                SOAPUtils.getSoapBodyFromEvent(event, useRandomMsgBodies, CallType.REQUEST);
1078        }
1079        else {
1080            requestBody =
1081                SOAPUtils.getSoapBodyFromEvent(event, useRandomMsgBodies, CallType.RESPONSE);
1082        }
1083        Package instSpecPkg = null;
1084        MutableInt instSpecNumber = new MutableInt(0);
1085
1086        // FOR DEBUGGING
1087        // Console.traceln(Level.FINE, "XML structure of path:" + StringTools.ENDLINE +
1088        // SOAPUtils.getSerialization(requestBody));
1089        // for( Parameter param : calledOperation.getOwnedParameters() ) {
1090        // System.out.println(param.getName());
1091        // if( param.getType() instanceof DataType ) {
1092        // for( Property prop1 : ((DataType) param.getType()).getAllAttributes() ) {
1093        // System.out.println("  " + prop1.getName());
1094        // if( prop1.getType() instanceof DataType ) {
1095        // for( Property prop2 : ((DataType) prop1.getType()).getAllAttributes() ) {
1096        // System.out.println("    " + prop2.getName());
1097        // if( prop2.getType() instanceof DataType ) {
1098        // for( Property prop3 : ((DataType) prop2.getType()).getAllAttributes() ) {
1099        // System.out.println("      " + prop3.getName());
1100        // if( prop3.getType() instanceof DataType ) {
1101        // for( Property prop4 : ((DataType) prop3.getType()).getAllAttributes() ) {
1102        // System.out.println("        " + prop4.getName());
1103        // }
1104        // }
1105        // }
1106        // }
1107        // }
1108        // }
1109        // }
1110        // }
1111        // }
1112
1113        // Set parameters of operation
1114        for (Parameter param : calledOperation.getOwnedParameters()) {
1115            if (instSpecPkg == null) {
1116                instSpecPkg = getOrCreateInstanceSpecificationPackage(message.getModel(), event);
1117            }
1118
1119            // TODO String path = calledOperation.getName() + ":" + param.getName();
1120            String path = calledOperation.getName() + ":" + param.getType().getName();
1121            // create param node
1122            // Expression argument =
1123            // (Expression) callMessage.createArgument(param.getName(), param.getType(),
1124            // UMLPackage.Literals.EXPRESSION);
1125            if ((isInParameter(param) && SOAPUtils.isSOAPRequest(event)) ||
1126                (isOutParameter(param) && SOAPUtils.isSOAPResponse(event)))
1127            {
1128
1129                // create parameters node
1130                if (!(param.getType() instanceof DataType)) {
1131                    throw new RuntimeException("TODO error handling; parameters missing");
1132                }
1133                DataType parametersNode = (DataType) param.getType();
1134                InstanceSpecification instSpecParameters =
1135                    (InstanceSpecification) instSpecPkg.createPackagedElement(prefix + "instspec" + instSpecNumber.intValue() + "_" +
1136                        param.getType().getName(), UMLPackage.Literals.INSTANCE_SPECIFICATION);
1137                instSpecParameters.getClassifiers().add((DataType) param.getType());
1138                instSpecNumber.setValue(instSpecNumber.intValue()+1);
1139                // InstanceValue parametersValue =
1140                // (InstanceValue) argument
1141                // .createOperand(param.getType().getName(), param.getType(),
1142                // UMLPackage.Literals.INSTANCE_VALUE);
1143                // parametersValue.setInstance(instSpecParameters);
1144                InstanceValue instanceValue =
1145                    (InstanceValue) message.createArgument(param.getName(), param.getType(),
1146                                                           UMLPackage.Literals.INSTANCE_VALUE);
1147                instanceValue.setInstance(instSpecParameters);
1148
1149                for (Property internalParameter : parametersNode.getAllAttributes()) {
1150                    if (internalParameter.getType() instanceof DataType) {
1151                        List<org.w3c.dom.Element> paramNodes =
1152                            SOAPUtils.getMatchingChildNode(internalParameter.getType().getName(),
1153                                                           requestBody);
1154                        // TODO the mistake is somewhere around here ... probably
1155                        // List<org.w3c.dom.Element> paramNodes =
1156                        // SOAPUtils.getMatchingChildNode(param.getName(), requestBody);
1157                        int multiplicityChosen = paramNodes.size();
1158
1159                        if (multiplicityChosen == 0 && internalParameter.getLower() > 0) {
1160                            Console
1161                                .traceln(Level.WARNING,
1162                                         "required attribute not found in SOAP message: " + path);
1163                            Console
1164                                .traceln(Level.WARNING,
1165                                         "setting default values for this attribute and all its children");
1166                            Console.traceln(Level.FINE, "XML structure of path:" +
1167                                StringTools.ENDLINE + SOAPUtils.getSerialization(requestBody));
1168                            multiplicityChosen = internalParameter.getLower();
1169                        }
1170                        for (int i = 0; i < multiplicityChosen; i++) {
1171                            org.w3c.dom.Element paramNode = null;
1172                            if (!paramNodes.isEmpty()) {
1173                                paramNode = paramNodes.get(i);
1174                            }
1175
1176                            Slot slot = instSpecParameters.createSlot();
1177                            slot.setDefiningFeature(internalParameter);
1178
1179                            InstanceValue value =
1180                                (InstanceValue) slot
1181                                    .createValue(internalParameter.getName() + "_" + i,
1182                                                 internalParameter.getType(),
1183                                                 UMLPackage.Literals.INSTANCE_VALUE);
1184                            value
1185                                .setInstance(createInstanceSpecification((DataType) internalParameter
1186                                                                             .getType(),
1187                                                                         instSpecPkg, prefix, instSpecNumber,
1188                                                                         paramNode, path));
1189                            /*
1190                             * InstanceValue value = (InstanceValue) argument .createOperand(null,
1191                             * internalParameter.getType(), UMLPackage.Literals.INSTANCE_VALUE);
1192                             * value.setInstance(instSpec);
1193                             */
1194                        }
1195                    }
1196                    else if (internalParameter.getType() instanceof PrimitiveType) {
1197                        createSlotPrimitiveType(instSpecParameters, internalParameter, requestBody,
1198                                                path);
1199                    }
1200                }
1201            }
1202            else {
1203                // set literalNull for out and return parameters
1204                // argument.createOperand(null, param.getType(), UMLPackage.Literals.LITERAL_NULL);
1205                message.createArgument(param.getName(), param.getType(),
1206                                       UMLPackage.Literals.LITERAL_NULL);
1207            }
1208        }
1209    }
1210
1211    /**
1212     * <p>
1213     * Creates an {@link InstanceSpecification} for a data type in the given package. The values are
1214     * inferred, if possible, from the DOM node. The prefix and the path are used for naming the
1215     * instance specification and to provide good warnings and debug information in case of
1216     * problems.
1217     * </p>
1218     *
1219     * @param type
1220     *            DataType for which the {@link InstanceSpecification} is created
1221     * @param pkg
1222     *            package in which the {@link InstanceSpecification} is created
1223     * @param prefix
1224     *            prefix used for naming the {@link InstanceSpecification}
1225     * @param currentNode
1226     *            node of a DOM from which values are inferred
1227     * @param path
1228     *            used for warnings and debug information
1229     * @return {@link InstanceSpecification} for the given type
1230     */
1231    private static InstanceSpecification createInstanceSpecification(DataType type,
1232                                                                     Package pkg,
1233                                                                     String prefix,
1234                                                                     MutableInt instSpecNumber,
1235                                                                     org.w3c.dom.Element currentNode,
1236                                                                     String path)
1237    {
1238        if ("".equals(path)) {
1239            path = type.getName();
1240        }
1241
1242        InstanceSpecification instSpec =
1243            (InstanceSpecification) pkg
1244                .createPackagedElement(prefix + "instspec" + instSpecNumber.intValue() + "_" + type.getName(),
1245                                       UMLPackage.Literals.INSTANCE_SPECIFICATION);
1246        instSpec.getClassifiers().add(type);
1247        instSpecNumber.setValue(instSpecNumber.intValue()+1);
1248        for (Property prop : type.getAllAttributes()) {
1249            if (prop.getType() instanceof PrimitiveType) {
1250                createSlotPrimitiveType(instSpec, prop, currentNode, path);
1251            }
1252            else if (prop.getType() instanceof DataType) {
1253                List<org.w3c.dom.Element> attributeNodes = null;
1254                int multiplicityChosen = 0;
1255                if (currentNode != null) {
1256                    // TODO attributeNodes = SOAPUtils.getMatchingChildNode(prop.getName(),
1257                    // currentNode);
1258                    attributeNodes = SOAPUtils.getMatchingChildNode(prop.getName(), currentNode);
1259                    multiplicityChosen = attributeNodes.size();
1260                }
1261
1262                if (multiplicityChosen == 0 && prop.getLower() > 0) {
1263                    if (currentNode != null) {
1264                        Console.traceln(Level.WARNING,
1265                                        "required attribute not found in SOAP message: " + path +
1266                                            "." + prop.getName());
1267                        Console
1268                            .traceln(Level.WARNING,
1269                                     "setting default values for this attribute and all its children");
1270                        Console.traceln(Level.FINE, "XML structure of path:" + StringTools.ENDLINE +
1271                            SOAPUtils.getSerialization(currentNode));
1272                    }
1273                    multiplicityChosen = prop.getLower();
1274                }
1275                for (int i = 0; i < multiplicityChosen; i++) {
1276                    org.w3c.dom.Element attributeNode = null;
1277                    if (attributeNodes != null && !attributeNodes.isEmpty()) {
1278                        attributeNode = attributeNodes.get(i);
1279                    }
1280
1281                    Slot slot = instSpec.createSlot();
1282                    slot.setDefiningFeature(prop);
1283
1284                    InstanceValue value =
1285                        (InstanceValue) slot.createValue(prop.getName() + "_" + i, prop.getType(),
1286                                                         UMLPackage.Literals.INSTANCE_VALUE);
1287                    value.setInstance(createInstanceSpecification((DataType) prop.getType(), pkg,
1288                                                                  prefix, instSpecNumber, attributeNode, path +
1289                                                                      "." + prop.getName()));
1290                }
1291            }
1292            else {
1293                Console.traceln(Level.SEVERE, "property neither DataType nor PrimitiveType: " +
1294                    prop.getType());
1295                // TODO abort?
1296            }
1297        }
1298        return instSpec;
1299    }
1300
1301    /**
1302     * <p>
1303     * Gets or creates a {@link Package} for {@link InstanceSpecification} created by the
1304     * usage-based testing. Each service gets its own sub-package within a package called
1305     * UBT_InstanceSpecifications. "
1306     * </p>
1307     *
1308     * @param model
1309     *            model in which the package is generated
1310     * @param event
1311     *            event from which the service name is inferred
1312     * @return package for the {@link InstanceSpecification}s
1313     */
1314    private static Package getOrCreateInstanceSpecificationPackage(Model model, Event event) {
1315        String pkgUBTInstSpecs = "UBT_InstanceSpecifications";
1316        Package ubtInstSpecPkg = (Package) model.getOwnedMember(pkgUBTInstSpecs);
1317        if (ubtInstSpecPkg == null) {
1318            ubtInstSpecPkg =
1319                (Package) model.createPackagedElement(pkgUBTInstSpecs, UMLPackage.Literals.PACKAGE);
1320        }
1321        String serviceName = SOAPUtils.getServiceNameFromEvent(event);
1322        Package serviceInstSpecPkg = (Package) ubtInstSpecPkg.getOwnedMember(serviceName);
1323        if (serviceInstSpecPkg == null) {
1324            serviceInstSpecPkg =
1325                (Package) ubtInstSpecPkg.createPackagedElement(serviceName,
1326                                                               UMLPackage.Literals.PACKAGE);
1327        }
1328        return serviceInstSpecPkg;
1329    }
1330
1331    /**
1332     * <p>
1333     * Creates an operand that defines a {@link PrimitiveType}.
1334     * </p>
1335     * <p>
1336     * TODO: Currently does nothing in case of multiplicity 0. I am not sure if, in that case, one
1337     * has to define LiteralNull instead.
1338     * </p>
1339     *
1340     * @param param
1341     *            parameter for which the operand is created
1342     * @param argument
1343     *            argument to which the operand is added
1344     * @param currentNode
1345     *            DOM node from which is value for the operand is inferred
1346     * @param path
1347     *            used for warnings and debug information
1348     */
1349    private static void createOperandPrimitiveType(Parameter param,
1350                                                   Expression argument,
1351                                                   org.w3c.dom.Element currentNode,
1352                                                   String path)
1353    {
1354        List<String> attributeValues = SOAPUtils.getValuesFromElement(param.getName(), currentNode);
1355
1356        if (attributeValues.isEmpty()) {
1357            if (param.getLower() == 0) {
1358                // ignoring optional attribute
1359                return;
1360            }
1361            else {
1362                if (currentNode != null) {
1363                    Console.traceln(Level.WARNING,
1364                                    "required attribute not found in SOAP message: " + path + "." +
1365                                        param.getName());
1366                    Console.traceln(Level.WARNING, "setting default values for this attribute");
1367                    Console.traceln(Level.FINE, "XML structure of path:" + StringTools.ENDLINE +
1368                        SOAPUtils.getSerialization(currentNode));
1369                }
1370                attributeValues.add(null);
1371            }
1372        }
1373        for (String attributeValue : attributeValues) {
1374            if ("String".equals(param.getType().getName())) {
1375                LiteralString spec =
1376                    (LiteralString) argument.createOperand(param.getName(), null,
1377                                                           UMLPackage.Literals.LITERAL_STRING);
1378                if (attributeValue != null) {
1379                    spec.setValue(attributeValue);
1380                }
1381                else {
1382                    spec.setValue("foobar");
1383                }
1384            }
1385            else if ("Integer".equals(param.getType().getName())) {
1386                LiteralInteger spec =
1387                    (LiteralInteger) argument.createOperand(param.getName(), null,
1388                                                            UMLPackage.Literals.LITERAL_INTEGER);
1389                if (attributeValue != null) {
1390                    spec.setValue(Integer.parseInt(attributeValue));
1391                }
1392                else {
1393                    spec.setValue(42);
1394                }
1395            }
1396            else if ("Boolean".equals(param.getType().getName())) {
1397                LiteralBoolean spec =
1398                    (LiteralBoolean) argument.createOperand(param.getName(), null,
1399                                                            UMLPackage.Literals.LITERAL_BOOLEAN);
1400                if (attributeValue != null) {
1401                    spec.setValue(Boolean.parseBoolean(attributeValue));
1402                }
1403                else {
1404                    spec.setValue(true);
1405                }
1406            }
1407            else if ("Real".equals(param.getType().getName())) {
1408                LiteralReal spec =
1409                    (LiteralReal) argument.createOperand(param.getName(), null,
1410                                                         UMLPackage.Literals.LITERAL_REAL);
1411                if (attributeValue != null) {
1412                    spec.setValue(Double.parseDouble(attributeValue));
1413                }
1414                else {
1415                    spec.setValue(3.14);
1416                }
1417            }
1418        }
1419    }
1420
1421    /**
1422     * <p>
1423     * Creates a {@link Slot} in an {@link InstanceSpecification} for a primitive type.
1424     * </p>
1425     *
1426     * @param instSpec
1427     *            instance specification to which the slot is added
1428     * @param prop
1429     *            property that describes the slot
1430     * @param currentNode
1431     *            DOM node from which is value for the slot is inferred
1432     * @param path
1433     *            used for warnings and debug information
1434     */
1435    private static void createSlotPrimitiveType(InstanceSpecification instSpec,
1436                                                Property prop,
1437                                                org.w3c.dom.Element currentNode,
1438                                                String path)
1439    {
1440        List<String> attributeValues = SOAPUtils.getValuesFromElement(prop.getName(), currentNode);
1441
1442        if (attributeValues.isEmpty()) {
1443            if (prop.getLower() == 0) {
1444                // ignoring optional attribute
1445                return;
1446            }
1447            else {
1448                if (currentNode != null) {
1449                    Console.traceln(Level.WARNING,
1450                                    "required attribute not found in SOAP message: " + path + "." +
1451                                        prop.getName());
1452                    Console.traceln(Level.WARNING, "setting default values for this attribute");
1453                    Console.traceln(Level.FINE, "XML structure of path:" + StringTools.ENDLINE +
1454                        SOAPUtils.getSerialization(currentNode));
1455                }
1456                attributeValues.add(null);
1457            }
1458        }
1459        for (String attributeValue : attributeValues) {
1460            Slot slot = instSpec.createSlot();
1461            slot.setDefiningFeature(prop);
1462            if ("String".equals(prop.getType().getName())) {
1463                LiteralString value =
1464                    (LiteralString) slot.createValue(prop.getName(), null,
1465                                                     UMLPackage.Literals.LITERAL_STRING);
1466                if (attributeValue != null) {
1467                    value.setValue(attributeValue);
1468                }
1469                else {
1470                    value.setValue("foobar");
1471                }
1472            }
1473            else if ("Integer".equals(prop.getType().getName())) {
1474                LiteralInteger value =
1475                    (LiteralInteger) slot.createValue(prop.getName(), null,
1476                                                      UMLPackage.Literals.LITERAL_INTEGER);
1477                if (attributeValue != null) {
1478                    value.setValue(Integer.parseInt(attributeValue));
1479                }
1480                else {
1481                    value.setValue(42);
1482                }
1483            }
1484            else if ("Boolean".equals(prop.getType().getName())) {
1485                LiteralBoolean value =
1486                    (LiteralBoolean) slot.createValue(prop.getName(), null,
1487                                                      UMLPackage.Literals.LITERAL_BOOLEAN);
1488                if (attributeValue != null) {
1489                    value.setValue(Boolean.parseBoolean(attributeValue));
1490                }
1491                else {
1492                    value.setValue(true);
1493                }
1494            }
1495            else if ("Real".equals(prop.getType().getName())) {
1496                LiteralReal value =
1497                    (LiteralReal) slot.createValue(prop.getName(), null,
1498                                                   UMLPackage.Literals.LITERAL_REAL);
1499                if (attributeValue != null) {
1500                    value.setValue(Double.parseDouble(attributeValue));
1501                }
1502                else {
1503                    value.setValue(3.14);
1504                }
1505            }
1506            else {
1507                Console.traceln(Level.SEVERE, "could not create literal for primitive type: " +
1508                    prop.getType().getName());
1509                // TODO abort?
1510            }
1511        }
1512    }
1513
1514    /**
1515     * <p>
1516     * Sets values for the parameters of a reply message. The values are, all LiterealNull and to
1517     * the INOUT, OUT and REPLY parameters, the UTP stereotype LiteralAny is applied.
1518     * </p>
1519     *
1520     * @param replyMessage
1521     *            reply message for which the parameters are set
1522     * @param calledOperation
1523     *            operation that is replied for by the message
1524     */
1525    private static void setReplyMessageParameters(Message replyMessage, Operation calledOperation) {
1526        for (Parameter param : calledOperation.getOwnedParameters()) {
1527            LiteralNull argument =
1528                (LiteralNull) replyMessage.createArgument(param.getName(), param.getType(),
1529                                                          UMLPackage.Literals.LITERAL_NULL);
1530
1531            if (isOutParameter(param)) {
1532                argument.applyStereotype(UTPUtils.getLiteralAnyStereotype(replyMessage.getModel()));
1533            }
1534        }
1535    }
1536
1537    /**
1538     * <p>
1539     * Checks if a parameter has the direction IN or INOUT
1540     * </p>
1541     *
1542     * @param parameter
1543     *            parameter that is checked
1544     * @return true if the direction is IN or INOUT; false otherwise
1545     */
1546    private static boolean isInParameter(Parameter parameter) {
1547        return parameter.getDirection() == ParameterDirectionKind.IN_LITERAL ||
1548            parameter.getDirection() == ParameterDirectionKind.INOUT_LITERAL;
1549    }
1550
1551    /**
1552     * <p>
1553     * Checks if a parameter has the direction RETURN, OUT or INOUT
1554     * </p>
1555     *
1556     * @param parameter
1557     *            parameter that is checked
1558     * @return true if the direction is RETURN, OUT, or INOUT; false otherwise
1559     */
1560    private static boolean isOutParameter(Parameter parameter) {
1561        return parameter.getDirection() == ParameterDirectionKind.RETURN_LITERAL ||
1562            parameter.getDirection() == ParameterDirectionKind.OUT_LITERAL ||
1563            parameter.getDirection() == ParameterDirectionKind.INOUT_LITERAL;
1564    }
1565
1566    /**
1567     * <p>
1568     * Checks if the {@link MessageSort} of a message is a call message, i.e., ASYNCH_CALL or
1569     * SYNCH_CALL.
1570     * </p>
1571     *
1572     * @param message
1573     *            message that is checked
1574     * @return true if the message is a call message; false otherwise
1575     */
1576    private static boolean isCallMessage(Message message) {
1577        if (message == null) {
1578            return false;
1579        }
1580        MessageSort msgSort = message.getMessageSort();
1581        return msgSort == MessageSort.ASYNCH_CALL_LITERAL ||
1582            msgSort == MessageSort.SYNCH_CALL_LITERAL;
1583    }
1584
1585    /**
1586     * <p>
1587     * inverse-sorts the values of a map. Has been adapted from <a href=
1588     * "http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java"
1589     * >this</a> StackOverflow post.
1590     * </p>
1591     *
1592     * @param map
1593     *            map whose values are sorted
1594     * @return sorted version of the map
1595     */
1596    private static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
1597        // TODO possibly move to another class
1598        List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
1599        Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
1600            @Override
1601            public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
1602                return -1 * (o1.getValue()).compareTo(o2.getValue());
1603            }
1604        });
1605
1606        Map<K, V> result = new LinkedHashMap<>();
1607        for (Map.Entry<K, V> entry : list) {
1608            result.put(entry.getKey(), entry.getValue());
1609        }
1610        return result;
1611    }
1612}
Note: See TracBrowser for help on using the repository browser.