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

Last change on this file since 1930 was 1930, checked in by sherbold, 9 years ago
  • removed deprecated debugging outputs
  • Property svn:mime-type set to text/plain
File size: 65.7 KB
Line 
1//   Copyright 2012 Georg-August-Universität Göttingen, Germany
2//
3//   Licensed under the Apache License, Version 2.0 (the "License");
4//   you may not use this file except in compliance with the License.
5//   You may obtain a copy of the License at
6//
7//       http://www.apache.org/licenses/LICENSE-2.0
8//
9//   Unless required by applicable law or agreed to in writing, software
10//   distributed under the License is distributed on an "AS IS" BASIS,
11//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//   See the License for the specific language governing permissions and
13//   limitations under the License.
14
15package de.ugoe.cs.autoquest.plugin.uml;
16
17import java.util.Collection;
18import java.util.Collections;
19import java.util.Comparator;
20import java.util.HashMap;
21import java.util.HashSet;
22import java.util.Iterator;
23import java.util.LinkedHashMap;
24import java.util.LinkedList;
25import java.util.List;
26import java.util.Map;
27import java.util.Map.Entry;
28import java.util.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        // Set parameters of operation
1039        for (Parameter param : calledOperation.getOwnedParameters()) {
1040            if (instSpecPkg == null) {
1041                instSpecPkg = getOrCreateInstanceSpecificationPackage(param.getModel(), event);
1042            }
1043
1044            String path = calledOperation.getName() + ":" + param.getName();
1045            Expression argument =
1046                (Expression) callMessage.createArgument(param.getName(), param.getType(),
1047                                                        UMLPackage.Literals.EXPRESSION);
1048
1049            if (isInParameter(param)) {
1050                if (param.getType() instanceof DataType) {
1051                    List<org.w3c.dom.Element> paramNodes =
1052                        SOAPUtils.getMatchingChildNode(param.getType().getName(), requestBody);
1053                    int multiplicityChosen = paramNodes.size();
1054
1055                    if (multiplicityChosen == 0 && param.getLower() > 0) {
1056                        Console.traceln(Level.WARNING,
1057                                        "required attribute not found in SOAP message: " + path);
1058                        Console
1059                            .traceln(Level.WARNING,
1060                                     "setting default values for this attribute and all its children");
1061                        Console.traceln(Level.FINE, "XML structure of path:" + StringTools.ENDLINE +
1062                            SOAPUtils.getSerialization(requestBody));
1063                        multiplicityChosen = param.getLower();
1064                    }
1065                    for (int i = 0; i < multiplicityChosen; i++) {
1066                        org.w3c.dom.Element paramNode = null;
1067                        if (!paramNodes.isEmpty()) {
1068                            paramNode = paramNodes.get(i);
1069                        }
1070                        InstanceSpecification instSpec =
1071                            createInstanceSpecification((DataType) param.getType(), instSpecPkg,
1072                                                        prefix, paramNode, path);
1073
1074                        InstanceValue value =
1075                            (InstanceValue) argument
1076                                .createOperand(null, param.getType(),
1077                                               UMLPackage.Literals.INSTANCE_VALUE);
1078                        value.setInstance(instSpec);
1079                    }
1080                }
1081                else if (param.getType() instanceof PrimitiveType) {
1082                    createOperandPrimitiveType(param, argument, requestBody, path);
1083                }
1084            }
1085            else {
1086                // set literalNull for out and return parameters
1087                argument.createOperand(null, param.getType(), UMLPackage.Literals.LITERAL_NULL);
1088            }
1089        }
1090    }
1091
1092    /**
1093     * <p>
1094     * Creates an {@link InstanceSpecification} for a data type in the given package. The values are
1095     * inferred, if possible, from the DOM node. The prefix and the path are used for naming the
1096     * instance specification and to provide good warnings and debug information in case of
1097     * problems.
1098     * </p>
1099     *
1100     * @param type
1101     *            DataType for which the {@link InstanceSpecification} is created
1102     * @param pkg
1103     *            package in which the {@link InstanceSpecification} is created
1104     * @param prefix
1105     *            prefix used for naming the {@link InstanceSpecification}
1106     * @param currentNode
1107     *            node of a DOM from which values are inferred
1108     * @param path
1109     *            used for warnings and debug information
1110     * @return {@link InstanceSpecification} for the given type
1111     */
1112    private static InstanceSpecification createInstanceSpecification(DataType type,
1113                                                                     Package pkg,
1114                                                                     String prefix,
1115                                                                     org.w3c.dom.Element currentNode,
1116                                                                     String path)
1117    {
1118        if ("".equals(path)) {
1119            path = type.getName();
1120        }
1121
1122        InstanceSpecification instSpec =
1123            (InstanceSpecification) pkg
1124                .createPackagedElement(prefix + "instspec_" + type.getName(),
1125                                       UMLPackage.Literals.INSTANCE_SPECIFICATION);
1126        instSpec.getClassifiers().add(type);
1127        for (Property prop : type.getAllAttributes()) {
1128            if (prop.getType() instanceof PrimitiveType) {
1129                createSlotPrimitiveType(instSpec, prop, currentNode, path);
1130            }
1131            else if (prop.getType() instanceof DataType) {
1132                List<org.w3c.dom.Element> attributeNodes = null;
1133                int multiplicityChosen = 0;
1134                if (currentNode != null) {
1135                    attributeNodes = SOAPUtils.getMatchingChildNode(prop.getName(), currentNode);
1136                    multiplicityChosen = attributeNodes.size();
1137                }
1138
1139                if (multiplicityChosen == 0 && prop.getLower() > 0) {
1140                    if (currentNode != null) {
1141                        Console.traceln(Level.WARNING,
1142                                        "required attribute not found in SOAP message: " + path +
1143                                            "." + prop.getName());
1144                        Console
1145                            .traceln(Level.WARNING,
1146                                     "setting default values for this attribute and all its children");
1147                        Console.traceln(Level.FINE, "XML structure of path:" + StringTools.ENDLINE +
1148                            SOAPUtils.getSerialization(currentNode));
1149                    }
1150                    multiplicityChosen = prop.getLower();
1151                }
1152                for (int i = 0; i < multiplicityChosen; i++) {
1153                    org.w3c.dom.Element attributeNode = null;
1154                    if (attributeNodes != null && !attributeNodes.isEmpty()) {
1155                        attributeNode = attributeNodes.get(i);
1156                    }
1157
1158                    Slot slot = instSpec.createSlot();
1159                    slot.setDefiningFeature(prop);
1160
1161                    InstanceValue value =
1162                        (InstanceValue) slot.createValue(prop.getName() + "_" + i, prop.getType(),
1163                                                         UMLPackage.Literals.INSTANCE_VALUE);
1164                    value.setInstance(createInstanceSpecification((DataType) prop.getType(), pkg,
1165                                                                  prefix, attributeNode, path +
1166                                                                      "." + prop.getName()));
1167                }
1168            }
1169            else {
1170                Console.traceln(Level.SEVERE, "property neither DataType nor PrimitiveType: " +
1171                    prop.getType());
1172                // TODO abort?
1173            }
1174        }
1175        return instSpec;
1176    }
1177
1178    /**
1179     * <p>
1180     * Gets or creates a {@link Package} for {@link InstanceSpecification} created by the
1181     * usage-based testing. Each service gets its own sub-package within a package called
1182     * UBT_InstanceSpecifications. "
1183     * </p>
1184     *
1185     * @param model
1186     *            model in which the package is generated
1187     * @param event
1188     *            event from which the service name is inferred
1189     * @return package for the {@link InstanceSpecification}s
1190     */
1191    private static Package getOrCreateInstanceSpecificationPackage(Model model, Event event) {
1192        String pkgUBTInstSpecs = "UBT_InstanceSpecifications";
1193        Package ubtInstSpecPkg = (Package) model.getOwnedMember(pkgUBTInstSpecs);
1194        if (ubtInstSpecPkg == null) {
1195            ubtInstSpecPkg =
1196                (Package) model.createPackagedElement(pkgUBTInstSpecs, UMLPackage.Literals.PACKAGE);
1197        }
1198        String serviceName = SOAPUtils.getServiceNameFromEvent(event);
1199        Package serviceInstSpecPkg = (Package) ubtInstSpecPkg.getOwnedMember(serviceName);
1200        if (serviceInstSpecPkg == null) {
1201            serviceInstSpecPkg =
1202                (Package) ubtInstSpecPkg.createPackagedElement(serviceName,
1203                                                               UMLPackage.Literals.PACKAGE);
1204        }
1205        return serviceInstSpecPkg;
1206    }
1207
1208    /**
1209     * <p>
1210     * Creates an operand that defines a {@link PrimitiveType}.
1211     * </p>
1212     * <p>
1213     * TODO: Currently does nothing in case of multiplicity 0. I am not sure if, in that case, one
1214     * has to define LiteralNull instead.
1215     * </p>
1216     *
1217     * @param param
1218     *            parameter for which the operand is created
1219     * @param argument
1220     *            argument to which the operand is added
1221     * @param currentNode
1222     *            DOM node from which is value for the operand is inferred
1223     * @param path
1224     *            used for warnings and debug information
1225     */
1226    private static void createOperandPrimitiveType(Parameter param,
1227                                                   Expression argument,
1228                                                   org.w3c.dom.Element currentNode,
1229                                                   String path)
1230    {
1231        List<String> attributeValues = SOAPUtils.getValuesFromElement(param.getName(), currentNode);
1232
1233        if (attributeValues.isEmpty()) {
1234            if (param.getLower() == 0) {
1235                // ignoring optional attribute
1236                return;
1237            }
1238            else {
1239                if (currentNode != null) {
1240                    Console.traceln(Level.WARNING,
1241                                    "required attribute not found in SOAP message: " + path + "." +
1242                                        param.getName());
1243                    Console.traceln(Level.WARNING, "setting default values for this attribute");
1244                    Console.traceln(Level.FINE, "XML structure of path:" + StringTools.ENDLINE +
1245                        SOAPUtils.getSerialization(currentNode));
1246                }
1247                attributeValues.add(null);
1248            }
1249        }
1250        for (String attributeValue : attributeValues) {
1251            if ("String".equals(param.getType().getName())) {
1252                LiteralString spec =
1253                    (LiteralString) argument.createOperand(param.getName(), null,
1254                                                           UMLPackage.Literals.LITERAL_STRING);
1255                if (attributeValue != null) {
1256                    spec.setValue(attributeValue);
1257                }
1258                else {
1259                    spec.setValue("foobar");
1260                }
1261            }
1262            else if ("Integer".equals(param.getType().getName())) {
1263                LiteralInteger spec =
1264                    (LiteralInteger) argument.createOperand(param.getName(), null,
1265                                                            UMLPackage.Literals.LITERAL_INTEGER);
1266                if (attributeValue != null) {
1267                    spec.setValue(Integer.parseInt(attributeValue));
1268                }
1269                else {
1270                    spec.setValue(42);
1271                }
1272            }
1273            else if ("Boolean".equals(param.getType().getName())) {
1274                LiteralBoolean spec =
1275                    (LiteralBoolean) argument.createOperand(param.getName(), null,
1276                                                            UMLPackage.Literals.LITERAL_BOOLEAN);
1277                if (attributeValue != null) {
1278                    spec.setValue(Boolean.parseBoolean(attributeValue));
1279                }
1280                else {
1281                    spec.setValue(true);
1282                }
1283            }
1284            else if ("Real".equals(param.getType().getName())) {
1285                LiteralReal spec =
1286                    (LiteralReal) argument.createOperand(param.getName(), null,
1287                                                         UMLPackage.Literals.LITERAL_REAL);
1288                if (attributeValue != null) {
1289                    spec.setValue(Double.parseDouble(attributeValue));
1290                }
1291                else {
1292                    spec.setValue(3.14);
1293                }
1294            }
1295        }
1296    }
1297
1298    /**
1299     * <p>
1300     * Creates a {@link Slot} in an {@link InstanceSpecification} for a primitive type.
1301     * </p>
1302     *
1303     * @param instSpec
1304     *            instance specification to which the slot is added
1305     * @param prop
1306     *            property that describes the slot
1307     * @param currentNode
1308     *            DOM node from which is value for the slot is inferred
1309     * @param path
1310     *            used for warnings and debug information
1311     */
1312    private static void createSlotPrimitiveType(InstanceSpecification instSpec,
1313                                                Property prop,
1314                                                org.w3c.dom.Element currentNode,
1315                                                String path)
1316    {
1317        List<String> attributeValues = SOAPUtils.getValuesFromElement(prop.getName(), currentNode);
1318
1319        if (attributeValues.isEmpty()) {
1320            if (prop.getLower() == 0) {
1321                // ignoring optional attribute
1322                return;
1323            }
1324            else {
1325                if (currentNode != null) {
1326                    Console.traceln(Level.WARNING,
1327                                    "required attribute not found in SOAP message: " + path + "." +
1328                                        prop.getName());
1329                    Console.traceln(Level.WARNING, "setting default values for this attribute");
1330                    Console.traceln(Level.FINE, "XML structure of path:" + StringTools.ENDLINE +
1331                        SOAPUtils.getSerialization(currentNode));
1332                }
1333                attributeValues.add(null);
1334            }
1335        }
1336        for (String attributeValue : attributeValues) {
1337            Slot slot = instSpec.createSlot();
1338            slot.setDefiningFeature(prop);
1339            if ("String".equals(prop.getType().getName())) {
1340                LiteralString value =
1341                    (LiteralString) slot.createValue(prop.getName(), null,
1342                                                     UMLPackage.Literals.LITERAL_STRING);
1343                if (attributeValue != null) {
1344                    value.setValue(attributeValue);
1345                }
1346                else {
1347                    value.setValue("foobar");
1348                }
1349            }
1350            else if ("Integer".equals(prop.getType().getName())) {
1351                LiteralInteger value =
1352                    (LiteralInteger) slot.createValue(prop.getName(), null,
1353                                                      UMLPackage.Literals.LITERAL_INTEGER);
1354                if (attributeValue != null) {
1355                    value.setValue(Integer.parseInt(attributeValue));
1356                }
1357                else {
1358                    value.setValue(42);
1359                }
1360            }
1361            else if ("Boolean".equals(prop.getType().getName())) {
1362                LiteralBoolean value =
1363                    (LiteralBoolean) slot.createValue(prop.getName(), null,
1364                                                      UMLPackage.Literals.LITERAL_BOOLEAN);
1365                if (attributeValue != null) {
1366                    value.setValue(Boolean.parseBoolean(attributeValue));
1367                }
1368                else {
1369                    value.setValue(true);
1370                }
1371            }
1372            else if ("Real".equals(prop.getType().getName())) {
1373                LiteralReal value =
1374                    (LiteralReal) slot.createValue(prop.getName(), null,
1375                                                   UMLPackage.Literals.LITERAL_REAL);
1376                if (attributeValue != null) {
1377                    value.setValue(Double.parseDouble(attributeValue));
1378                }
1379                else {
1380                    value.setValue(3.14);
1381                }
1382            }
1383            else {
1384                Console.traceln(Level.SEVERE, "could not create literal for primitive type: " +
1385                    prop.getType().getName());
1386                // TODO abort?
1387            }
1388        }
1389    }
1390
1391    /**
1392     * <p>
1393     * Sets values for the parameters of a reply message. The values are, all LiterealNull and to
1394     * the INOUT, OUT and REPLY parameters, the UTP stereotype LiteralAny is applied.
1395     * </p>
1396     *
1397     * @param replyMessage
1398     *            reply message for which the parameters are set
1399     * @param calledOperation
1400     *            operation that is replied for by the message
1401     */
1402    private static void setReplyMessageParameters(Message replyMessage, Operation calledOperation) {
1403        for (Parameter param : calledOperation.getOwnedParameters()) {
1404            Expression argument =
1405                (Expression) replyMessage.createArgument(param.getName(), param.getType(),
1406                                                         UMLPackage.Literals.EXPRESSION);
1407            if (isOutParameter(param)) {
1408                ValueSpecification operand =
1409                    argument.createOperand(null, param.getType(), UMLPackage.Literals.LITERAL_NULL);
1410                operand.applyStereotype(UTPUtils.getLiteralAnyStereotype(param.getModel()));
1411            }
1412            else {
1413                argument.createOperand(null, param.getType(), UMLPackage.Literals.LITERAL_NULL);
1414            }
1415        }
1416    }
1417
1418    /**
1419     * <p>
1420     * Checks if a parameter has the direction IN or INOUT
1421     * </p>
1422     *
1423     * @param parameter
1424     *            parameter that is checked
1425     * @return true if the direction is IN or INOUT; false otherwise
1426     */
1427    private static boolean isInParameter(Parameter parameter) {
1428        return parameter.getDirection() == ParameterDirectionKind.IN_LITERAL ||
1429            parameter.getDirection() == ParameterDirectionKind.INOUT_LITERAL;
1430    }
1431
1432    /**
1433     * <p>
1434     * Checks if a parameter has the direction RETURN, OUT or INOUT
1435     * </p>
1436     *
1437     * @param parameter
1438     *            parameter that is checked
1439     * @return true if the direction is RETURN, OUT, or INOUT; false otherwise
1440     */
1441    private static boolean isOutParameter(Parameter parameter) {
1442        return parameter.getDirection() == ParameterDirectionKind.RETURN_LITERAL ||
1443            parameter.getDirection() == ParameterDirectionKind.OUT_LITERAL ||
1444            parameter.getDirection() == ParameterDirectionKind.INOUT_LITERAL;
1445    }
1446
1447    /**
1448     * <p>
1449     * Checks if the {@link MessageSort} of a message is a call message, i.e., ASYNCH_CALL or
1450     * SYNCH_CALL.
1451     * </p>
1452     *
1453     * @param message
1454     *            message that is checked
1455     * @return true if the message is a call message; false otherwise
1456     */
1457    private static boolean isCallMessage(Message message) {
1458        if (message == null) {
1459            return false;
1460        }
1461        MessageSort msgSort = message.getMessageSort();
1462        return msgSort == MessageSort.ASYNCH_CALL_LITERAL ||
1463            msgSort == MessageSort.SYNCH_CALL_LITERAL;
1464    }
1465
1466    /**
1467     * <p>
1468     * inverse-sorts the values of a map. Has been adapted from <a href=
1469     * "http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java"
1470     * >this</a> StackOverflow post.
1471     * </p>
1472     *
1473     * @param map
1474     *            map whose values are sorted
1475     * @return sorted version of the map
1476     */
1477    private static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
1478        // TODO possibly move to another class
1479        List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
1480        Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
1481            @Override
1482            public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
1483                return -1 * (o1.getValue()).compareTo(o2.getValue());
1484            }
1485        });
1486
1487        Map<K, V> result = new LinkedHashMap<>();
1488        for (Map.Entry<K, V> entry : list) {
1489            result.put(entry.getKey(), entry.getValue());
1490        }
1491        return result;
1492    }
1493}
Note: See TracBrowser for help on using the repository browser.