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

Last change on this file since 1977 was 1977, checked in by sherbold, 9 years ago
  • updated UMLUtils to work correctly with imported UML models
  • Property svn:mime-type set to text/plain
File size: 69.4 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
1078            if (isInParameter(param)) {
1079               
1080                // create parameters node
1081                if (!(param.getType() instanceof DataType) ) {
1082                    throw new RuntimeException("TODO error handling; parameters missing");
1083                }
1084                DataType parametersNode = (DataType) param.getType();
1085                InstanceSpecification instSpecParameters = (InstanceSpecification)
1086                        instSpecPkg.createPackagedElement(prefix + "instspec_" + param.getType().getName(),
1087                                                          UMLPackage.Literals.INSTANCE_SPECIFICATION);
1088                instSpecParameters.getClassifiers().add((DataType) param.getType());
1089                InstanceValue parametersValue =
1090                        (InstanceValue) argument
1091                            .createOperand(param.getType().getName(), param.getType(),
1092                                           UMLPackage.Literals.INSTANCE_VALUE);
1093                parametersValue.setInstance(instSpecParameters);
1094               
1095                for( Property internalParameter : parametersNode.getAllAttributes() ) {
1096                    if (internalParameter.getType() instanceof DataType) {
1097                        List<org.w3c.dom.Element> paramNodes =
1098                            SOAPUtils.getMatchingChildNode(internalParameter.getType().getName(), requestBody);
1099                        // TODO the mistake is somewhere around here ... probably
1100                        //List<org.w3c.dom.Element> paramNodes =
1101                        //    SOAPUtils.getMatchingChildNode(param.getName(), requestBody);
1102                        int multiplicityChosen = paramNodes.size();
1103   
1104                        if (multiplicityChosen == 0 && internalParameter.getLower() > 0) {
1105                            Console.traceln(Level.WARNING,
1106                                            "required attribute not found in SOAP message: " + path);
1107                            Console
1108                                .traceln(Level.WARNING,
1109                                         "setting default values for this attribute and all its children");
1110                            Console.traceln(Level.FINE, "XML structure of path:" + StringTools.ENDLINE +
1111                                SOAPUtils.getSerialization(requestBody));
1112                            multiplicityChosen = internalParameter.getLower();
1113                        }
1114                        for (int i = 0; i < multiplicityChosen; i++) {
1115                            org.w3c.dom.Element paramNode = null;
1116                            if (!paramNodes.isEmpty()) {
1117                                paramNode = paramNodes.get(i);
1118                            }
1119                           
1120                            Slot slot = instSpecParameters.createSlot();
1121                            slot.setDefiningFeature(internalParameter);
1122
1123                            InstanceValue value =
1124                                (InstanceValue) slot.createValue(internalParameter.getName() + "_" + i, internalParameter.getType(),
1125                                                                 UMLPackage.Literals.INSTANCE_VALUE);
1126                            value.setInstance(createInstanceSpecification((DataType) internalParameter.getType(), instSpecPkg,
1127                                                                          prefix, paramNode, path));
1128                            /*
1129                            InstanceValue value =
1130                                (InstanceValue) argument
1131                                    .createOperand(null, internalParameter.getType(),
1132                                                   UMLPackage.Literals.INSTANCE_VALUE);
1133                            value.setInstance(instSpec);*/
1134                        }
1135                    }
1136                    else if (internalParameter.getType() instanceof PrimitiveType) {
1137                        createSlotPrimitiveType(instSpecParameters, internalParameter, requestBody, path);
1138                    }
1139                }
1140            }
1141            else {
1142                // set literalNull for out and return parameters
1143                argument.createOperand(null, param.getType(), UMLPackage.Literals.LITERAL_NULL);
1144            }
1145        }
1146    }
1147
1148    /**
1149     * <p>
1150     * Creates an {@link InstanceSpecification} for a data type in the given package. The values are
1151     * inferred, if possible, from the DOM node. The prefix and the path are used for naming the
1152     * instance specification and to provide good warnings and debug information in case of
1153     * problems.
1154     * </p>
1155     *
1156     * @param type
1157     *            DataType for which the {@link InstanceSpecification} is created
1158     * @param pkg
1159     *            package in which the {@link InstanceSpecification} is created
1160     * @param prefix
1161     *            prefix used for naming the {@link InstanceSpecification}
1162     * @param currentNode
1163     *            node of a DOM from which values are inferred
1164     * @param path
1165     *            used for warnings and debug information
1166     * @return {@link InstanceSpecification} for the given type
1167     */
1168    private static InstanceSpecification createInstanceSpecification(DataType type,
1169                                                                     Package pkg,
1170                                                                     String prefix,
1171                                                                     org.w3c.dom.Element currentNode,
1172                                                                     String path)
1173    {
1174        if ("".equals(path)) {
1175            path = type.getName();
1176        }
1177
1178        InstanceSpecification instSpec =
1179            (InstanceSpecification) pkg
1180                .createPackagedElement(prefix + "instspec_" + type.getName(),
1181                                       UMLPackage.Literals.INSTANCE_SPECIFICATION);
1182        instSpec.getClassifiers().add(type);
1183        for (Property prop : type.getAllAttributes()) {
1184            if (prop.getType() instanceof PrimitiveType) {
1185                createSlotPrimitiveType(instSpec, prop, currentNode, path);
1186            }
1187            else if (prop.getType() instanceof DataType) {
1188                List<org.w3c.dom.Element> attributeNodes = null;
1189                int multiplicityChosen = 0;
1190                if (currentNode != null) {
1191                    // TODO attributeNodes = SOAPUtils.getMatchingChildNode(prop.getName(), currentNode);
1192                    attributeNodes = SOAPUtils.getMatchingChildNode(prop.getName(), currentNode);
1193                    multiplicityChosen = attributeNodes.size();
1194                }
1195
1196                if (multiplicityChosen == 0 && prop.getLower() > 0) {
1197                    if (currentNode != null) {
1198                        Console.traceln(Level.WARNING,
1199                                        "required attribute not found in SOAP message: " + path +
1200                                            "." + prop.getName());
1201                        Console
1202                            .traceln(Level.WARNING,
1203                                     "setting default values for this attribute and all its children");
1204                        Console.traceln(Level.FINE, "XML structure of path:" + StringTools.ENDLINE +
1205                            SOAPUtils.getSerialization(currentNode));
1206                    }
1207                    multiplicityChosen = prop.getLower();
1208                }
1209                for (int i = 0; i < multiplicityChosen; i++) {
1210                    org.w3c.dom.Element attributeNode = null;
1211                    if (attributeNodes != null && !attributeNodes.isEmpty()) {
1212                        attributeNode = attributeNodes.get(i);
1213                    }
1214
1215                    Slot slot = instSpec.createSlot();
1216                    slot.setDefiningFeature(prop);
1217
1218                    InstanceValue value =
1219                        (InstanceValue) slot.createValue(prop.getName() + "_" + i, prop.getType(),
1220                                                         UMLPackage.Literals.INSTANCE_VALUE);
1221                    value.setInstance(createInstanceSpecification((DataType) prop.getType(), pkg,
1222                                                                  prefix, attributeNode, path +
1223                                                                      "." + prop.getName()));
1224                }
1225            }
1226            else {
1227                Console.traceln(Level.SEVERE, "property neither DataType nor PrimitiveType: " +
1228                    prop.getType());
1229                // TODO abort?
1230            }
1231        }
1232        return instSpec;
1233    }
1234
1235    /**
1236     * <p>
1237     * Gets or creates a {@link Package} for {@link InstanceSpecification} created by the
1238     * usage-based testing. Each service gets its own sub-package within a package called
1239     * UBT_InstanceSpecifications. "
1240     * </p>
1241     *
1242     * @param model
1243     *            model in which the package is generated
1244     * @param event
1245     *            event from which the service name is inferred
1246     * @return package for the {@link InstanceSpecification}s
1247     */
1248    private static Package getOrCreateInstanceSpecificationPackage(Model model, Event event) {
1249        String pkgUBTInstSpecs = "UBT_InstanceSpecifications";
1250        Package ubtInstSpecPkg = (Package) model.getOwnedMember(pkgUBTInstSpecs);
1251        if (ubtInstSpecPkg == null) {
1252            ubtInstSpecPkg =
1253                (Package) model.createPackagedElement(pkgUBTInstSpecs, UMLPackage.Literals.PACKAGE);
1254        }
1255        String serviceName = SOAPUtils.getServiceNameFromEvent(event);
1256        Package serviceInstSpecPkg = (Package) ubtInstSpecPkg.getOwnedMember(serviceName);
1257        if (serviceInstSpecPkg == null) {
1258            serviceInstSpecPkg =
1259                (Package) ubtInstSpecPkg.createPackagedElement(serviceName,
1260                                                               UMLPackage.Literals.PACKAGE);
1261        }
1262        return serviceInstSpecPkg;
1263    }
1264
1265    /**
1266     * <p>
1267     * Creates an operand that defines a {@link PrimitiveType}.
1268     * </p>
1269     * <p>
1270     * TODO: Currently does nothing in case of multiplicity 0. I am not sure if, in that case, one
1271     * has to define LiteralNull instead.
1272     * </p>
1273     *
1274     * @param param
1275     *            parameter for which the operand is created
1276     * @param argument
1277     *            argument to which the operand is added
1278     * @param currentNode
1279     *            DOM node from which is value for the operand is inferred
1280     * @param path
1281     *            used for warnings and debug information
1282     */
1283    private static void createOperandPrimitiveType(Parameter param,
1284                                                   Expression argument,
1285                                                   org.w3c.dom.Element currentNode,
1286                                                   String path)
1287    {
1288        List<String> attributeValues = SOAPUtils.getValuesFromElement(param.getName(), currentNode);
1289
1290        if (attributeValues.isEmpty()) {
1291            if (param.getLower() == 0) {
1292                // ignoring optional attribute
1293                return;
1294            }
1295            else {
1296                if (currentNode != null) {
1297                    Console.traceln(Level.WARNING,
1298                                    "required attribute not found in SOAP message: " + path + "." +
1299                                        param.getName());
1300                    Console.traceln(Level.WARNING, "setting default values for this attribute");
1301                    Console.traceln(Level.FINE, "XML structure of path:" + StringTools.ENDLINE +
1302                        SOAPUtils.getSerialization(currentNode));
1303                }
1304                attributeValues.add(null);
1305            }
1306        }
1307        for (String attributeValue : attributeValues) {
1308            if ("String".equals(param.getType().getName())) {
1309                LiteralString spec =
1310                    (LiteralString) argument.createOperand(param.getName(), null,
1311                                                           UMLPackage.Literals.LITERAL_STRING);
1312                if (attributeValue != null) {
1313                    spec.setValue(attributeValue);
1314                }
1315                else {
1316                    spec.setValue("foobar");
1317                }
1318            }
1319            else if ("Integer".equals(param.getType().getName())) {
1320                LiteralInteger spec =
1321                    (LiteralInteger) argument.createOperand(param.getName(), null,
1322                                                            UMLPackage.Literals.LITERAL_INTEGER);
1323                if (attributeValue != null) {
1324                    spec.setValue(Integer.parseInt(attributeValue));
1325                }
1326                else {
1327                    spec.setValue(42);
1328                }
1329            }
1330            else if ("Boolean".equals(param.getType().getName())) {
1331                LiteralBoolean spec =
1332                    (LiteralBoolean) argument.createOperand(param.getName(), null,
1333                                                            UMLPackage.Literals.LITERAL_BOOLEAN);
1334                if (attributeValue != null) {
1335                    spec.setValue(Boolean.parseBoolean(attributeValue));
1336                }
1337                else {
1338                    spec.setValue(true);
1339                }
1340            }
1341            else if ("Real".equals(param.getType().getName())) {
1342                LiteralReal spec =
1343                    (LiteralReal) argument.createOperand(param.getName(), null,
1344                                                         UMLPackage.Literals.LITERAL_REAL);
1345                if (attributeValue != null) {
1346                    spec.setValue(Double.parseDouble(attributeValue));
1347                }
1348                else {
1349                    spec.setValue(3.14);
1350                }
1351            }
1352        }
1353    }
1354
1355    /**
1356     * <p>
1357     * Creates a {@link Slot} in an {@link InstanceSpecification} for a primitive type.
1358     * </p>
1359     *
1360     * @param instSpec
1361     *            instance specification to which the slot is added
1362     * @param prop
1363     *            property that describes the slot
1364     * @param currentNode
1365     *            DOM node from which is value for the slot is inferred
1366     * @param path
1367     *            used for warnings and debug information
1368     */
1369    private static void createSlotPrimitiveType(InstanceSpecification instSpec,
1370                                                Property prop,
1371                                                org.w3c.dom.Element currentNode,
1372                                                String path)
1373    {
1374        List<String> attributeValues = SOAPUtils.getValuesFromElement(prop.getName(), currentNode);
1375
1376        if (attributeValues.isEmpty()) {
1377            if (prop.getLower() == 0) {
1378                // ignoring optional attribute
1379                return;
1380            }
1381            else {
1382                if (currentNode != null) {
1383                    Console.traceln(Level.WARNING,
1384                                    "required attribute not found in SOAP message: " + path + "." +
1385                                        prop.getName());
1386                    Console.traceln(Level.WARNING, "setting default values for this attribute");
1387                    Console.traceln(Level.FINE, "XML structure of path:" + StringTools.ENDLINE +
1388                        SOAPUtils.getSerialization(currentNode));
1389                }
1390                attributeValues.add(null);
1391            }
1392        }
1393        for (String attributeValue : attributeValues) {
1394            Slot slot = instSpec.createSlot();
1395            slot.setDefiningFeature(prop);
1396            if ("String".equals(prop.getType().getName())) {
1397                LiteralString value =
1398                    (LiteralString) slot.createValue(prop.getName(), null,
1399                                                     UMLPackage.Literals.LITERAL_STRING);
1400                if (attributeValue != null) {
1401                    value.setValue(attributeValue);
1402                }
1403                else {
1404                    value.setValue("foobar");
1405                }
1406            }
1407            else if ("Integer".equals(prop.getType().getName())) {
1408                LiteralInteger value =
1409                    (LiteralInteger) slot.createValue(prop.getName(), null,
1410                                                      UMLPackage.Literals.LITERAL_INTEGER);
1411                if (attributeValue != null) {
1412                    value.setValue(Integer.parseInt(attributeValue));
1413                }
1414                else {
1415                    value.setValue(42);
1416                }
1417            }
1418            else if ("Boolean".equals(prop.getType().getName())) {
1419                LiteralBoolean value =
1420                    (LiteralBoolean) slot.createValue(prop.getName(), null,
1421                                                      UMLPackage.Literals.LITERAL_BOOLEAN);
1422                if (attributeValue != null) {
1423                    value.setValue(Boolean.parseBoolean(attributeValue));
1424                }
1425                else {
1426                    value.setValue(true);
1427                }
1428            }
1429            else if ("Real".equals(prop.getType().getName())) {
1430                LiteralReal value =
1431                    (LiteralReal) slot.createValue(prop.getName(), null,
1432                                                   UMLPackage.Literals.LITERAL_REAL);
1433                if (attributeValue != null) {
1434                    value.setValue(Double.parseDouble(attributeValue));
1435                }
1436                else {
1437                    value.setValue(3.14);
1438                }
1439            }
1440            else {
1441                Console.traceln(Level.SEVERE, "could not create literal for primitive type: " +
1442                    prop.getType().getName());
1443                // TODO abort?
1444            }
1445        }
1446    }
1447
1448    /**
1449     * <p>
1450     * Sets values for the parameters of a reply message. The values are, all LiterealNull and to
1451     * the INOUT, OUT and REPLY parameters, the UTP stereotype LiteralAny is applied.
1452     * </p>
1453     *
1454     * @param replyMessage
1455     *            reply message for which the parameters are set
1456     * @param calledOperation
1457     *            operation that is replied for by the message
1458     */
1459    private static void setReplyMessageParameters(Message replyMessage, Operation calledOperation) {
1460        for (Parameter param : calledOperation.getOwnedParameters()) {
1461            Expression argument =
1462                (Expression) replyMessage.createArgument(param.getName(), param.getType(),
1463                                                         UMLPackage.Literals.EXPRESSION);
1464            ValueSpecification operand =
1465                    argument.createOperand(null, param.getType(), UMLPackage.Literals.LITERAL_NULL);
1466            if (isOutParameter(param)) {
1467                operand.applyStereotype(UTPUtils.getLiteralAnyStereotype(replyMessage.getModel()));
1468            }
1469        }
1470    }
1471
1472    /**
1473     * <p>
1474     * Checks if a parameter has the direction IN or INOUT
1475     * </p>
1476     *
1477     * @param parameter
1478     *            parameter that is checked
1479     * @return true if the direction is IN or INOUT; false otherwise
1480     */
1481    private static boolean isInParameter(Parameter parameter) {
1482        return parameter.getDirection() == ParameterDirectionKind.IN_LITERAL ||
1483            parameter.getDirection() == ParameterDirectionKind.INOUT_LITERAL;
1484    }
1485
1486    /**
1487     * <p>
1488     * Checks if a parameter has the direction RETURN, OUT or INOUT
1489     * </p>
1490     *
1491     * @param parameter
1492     *            parameter that is checked
1493     * @return true if the direction is RETURN, OUT, or INOUT; false otherwise
1494     */
1495    private static boolean isOutParameter(Parameter parameter) {
1496        return parameter.getDirection() == ParameterDirectionKind.RETURN_LITERAL ||
1497            parameter.getDirection() == ParameterDirectionKind.OUT_LITERAL ||
1498            parameter.getDirection() == ParameterDirectionKind.INOUT_LITERAL;
1499    }
1500
1501    /**
1502     * <p>
1503     * Checks if the {@link MessageSort} of a message is a call message, i.e., ASYNCH_CALL or
1504     * SYNCH_CALL.
1505     * </p>
1506     *
1507     * @param message
1508     *            message that is checked
1509     * @return true if the message is a call message; false otherwise
1510     */
1511    private static boolean isCallMessage(Message message) {
1512        if (message == null) {
1513            return false;
1514        }
1515        MessageSort msgSort = message.getMessageSort();
1516        return msgSort == MessageSort.ASYNCH_CALL_LITERAL ||
1517            msgSort == MessageSort.SYNCH_CALL_LITERAL;
1518    }
1519
1520    /**
1521     * <p>
1522     * inverse-sorts the values of a map. Has been adapted from <a href=
1523     * "http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java"
1524     * >this</a> StackOverflow post.
1525     * </p>
1526     *
1527     * @param map
1528     *            map whose values are sorted
1529     * @return sorted version of the map
1530     */
1531    private static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
1532        // TODO possibly move to another class
1533        List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
1534        Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
1535            @Override
1536            public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
1537                return -1 * (o1.getValue()).compareTo(o2.getValue());
1538            }
1539        });
1540
1541        Map<K, V> result = new LinkedHashMap<>();
1542        for (Map.Entry<K, V> entry : list) {
1543            result.put(entry.getKey(), entry.getValue());
1544        }
1545        return result;
1546    }
1547}
Note: See TracBrowser for help on using the repository browser.