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

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