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

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