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

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