source: trunk/autoquest-plugin-uml-test/src/test/java/de/ugoe/cs/autoquest/plugin/uml/UMLUtilsTest.java @ 1752

Last change on this file since 1752 was 1752, checked in by sherbold, 10 years ago
  • updated UMLUtils.createInteractionFromEventSequence to be compatible with the MIDAS DSL
  • Property svn:mime-type set to text/plain
File size: 13.2 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.io.File;
18import java.io.FileInputStream;
19import java.io.FileOutputStream;
20import java.io.IOException;
21import java.io.InputStream;
22import java.util.Collection;
23import java.util.Iterator;
24import java.util.LinkedList;
25import java.util.List;
26import java.util.Map;
27import java.util.Random;
28
29import org.eclipse.core.runtime.IStatus;
30import org.eclipse.emf.common.util.URI;
31import org.eclipse.emf.ecore.EPackage;
32import org.eclipse.emf.ecore.EcorePackage;
33import org.eclipse.emf.ecore.resource.Resource;
34import org.eclipse.emf.ecore.resource.ResourceSet;
35import org.eclipse.emf.ecore.resource.Resource.Factory.Registry;
36import org.eclipse.emf.ecore.resource.impl.ResourceFactoryImpl;
37import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
38import org.eclipse.emf.ecore.util.EcoreUtil;
39import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
40import org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl;
41import org.eclipse.uml2.uml.Interaction;
42import org.eclipse.uml2.uml.Model;
43import org.eclipse.uml2.uml.StateMachine;
44import org.eclipse.uml2.uml.Transition;
45import org.eclipse.uml2.uml.UMLPackage;
46import org.eclipse.uml2.uml.resource.UMLResource;
47import org.eclipse.uml2.uml.resources.util.UMLResourcesUtil;
48import org.junit.After;
49import org.junit.Test;
50
51import de.ugoe.cs.autoquest.eventcore.Event;
52import de.ugoe.cs.autoquest.plugin.http.HTTPLogParser;
53import de.ugoe.cs.autoquest.plugin.http.HTTPUtils;
54import de.ugoe.cs.autoquest.plugin.http.eventcore.SOAPEventType;
55import de.ugoe.cs.autoquest.plugin.uml.eventcore.UMLTransitionType;
56import de.ugoe.cs.autoquest.testgeneration.RandomWalkGenerator;
57import de.ugoe.cs.autoquest.usageprofiles.FirstOrderMarkovModel;
58import eu.midas.dsl.validation.util.ConstraintValidator;
59
60/**
61 * <p>
62 * Tests for AutoQUESTs UMLUtils
63 * </p>
64 *
65 * @author Steffen Herbold
66 */
67public class UMLUtilsTest {
68
69    private final static String OUTPUT_DIR = "target/tmp/test-outputs/";
70
71    /**
72    *
73    */
74    @After
75    public void tearDown() throws Exception {
76        deleteFiles(new File(OUTPUT_DIR));
77    }
78
79    @Test(expected = java.lang.RuntimeException.class)
80    public void testCreateUMLTransitionSequence_1() throws Exception {
81        // parse log file
82        HTTPLogParser parser = new HTTPLogParser();
83        parser.parseFile(new File(ClassLoader.getSystemResource("createSequence_1_usagedata.log")
84            .getFile()));
85        Collection<List<Event>> httpSequences = parser.getSequences();
86        Model model =
87            loadModelFromInputStream(ClassLoader
88                .getSystemResourceAsStream("createSequence_1_model.uml"));
89
90        StateMachine stateMachine =
91            (StateMachine) model.getPackagedElement("PatientIDBehavior", true,
92                                                    UMLPackage.Literals.STATE_MACHINE, true);
93
94        Collection<List<Event>> umlSequences = new LinkedList<>();
95        for (List<Event> httpSequence : httpSequences) {
96            for (Iterator<Event> eventIter = httpSequence.iterator(); eventIter.hasNext();) {
97                Event event = eventIter.next();
98                if (!(event.getType() instanceof SOAPEventType)) {
99                    eventIter.remove();
100                }
101                else {
102                    if (!event.getType().toString().contains("ixsmq")) {
103                        eventIter.remove();
104                    }
105                }
106            }
107
108            umlSequences.add(UMLUtils.createUMLTransitionSequence(httpSequence, stateMachine));
109        }
110    }
111
112    @Test
113    public void testConvertStateMachineToUsageProfile_1() throws Exception {
114        // parse log file
115        HTTPLogParser parser = new HTTPLogParser();
116        parser.parseFile(new File(ClassLoader.getSystemResource("createSequence_1_usagedata.log")
117            .getFile()));
118        Collection<List<Event>> httpSequences = parser.getSequences();
119        Model model =
120            loadModelFromInputStream(ClassLoader
121                .getSystemResourceAsStream("createSequence_1_model.uml"));
122
123        StateMachine stateMachine =
124            (StateMachine) model.getPackagedElement("PatientIDBehavior", true,
125                                                    UMLPackage.Literals.STATE_MACHINE, true);
126
127        Collection<List<Event>> umlSequences = new LinkedList<>();
128        for (List<Event> httpSequence : httpSequences) {
129            for (Iterator<Event> eventIter = httpSequence.iterator(); eventIter.hasNext();) {
130                Event event = eventIter.next();
131                if (!(event.getType() instanceof SOAPEventType)) {
132                    eventIter.remove();
133                }
134                else {
135                    if (!event.getType().toString().contains("ixsmq")) {
136                        eventIter.remove();
137                    }
138                }
139            }
140
141            List<List<Transition>> matchingSequences =
142                UMLUtils.determineMatchingTransitionSequences(httpSequence, stateMachine);
143            if (matchingSequences.size() >= 1) {
144                List<Event> umlEventSequence = new LinkedList<>();
145                for (Transition transition : matchingSequences.get(0)) {
146                    umlEventSequence.add(new Event(new UMLTransitionType(transition)));
147                }
148                umlSequences.add(umlEventSequence);
149            }
150        }
151        UMLUtils.convertStateMachineToUsageProfile(umlSequences, stateMachine);
152
153        writeModelToFile(model, OUTPUT_DIR + "convertStateMachineToUsageProfile_1.uml");
154    }
155
156    @Test
157    public void testCreateInteractionFromEventSequence_1() throws Exception {
158        // parse log file
159        HTTPLogParser parser =
160            new HTTPLogParser(new File(ClassLoader
161                .getSystemResource("testCreateInteractionFromEventSequence_1_properties.txt")
162                .getFile()));
163        parser
164            .parseFile(new File(ClassLoader
165                .getSystemResource("testCreateInteractionFromEventSequence_1_usagedata.log")
166                .getFile()));
167        Collection<List<Event>> httpSequences = parser.getSequences();
168        Model model =
169            loadModelFromInputStream(ClassLoader
170                .getSystemResourceAsStream("testCreateInteractionFromEventSequence_1_model.uml"));
171
172        for (List<Event> httpSequence : httpSequences) {
173            for (Iterator<Event> eventIter = httpSequence.iterator(); eventIter.hasNext();) {
174                Event event = eventIter.next();
175                if (!(event.getType() instanceof SOAPEventType)) {
176                    eventIter.remove();
177                }
178            }
179
180            UMLUtils.createInteractionFromEventSequence(httpSequence, model, "testSequence");
181        }
182
183        ConstraintValidator validator = new ConstraintValidator();
184        IStatus validationStatus = validator.validate(model);
185        if (validationStatus.getSeverity() == IStatus.OK) {
186            System.out.println("success");
187        }
188        else {
189            System.out.println("Errors during the model validation: ");
190            for (IStatus status : validationStatus.getChildren()) {
191                System.out.println("\t" + status.getMessage());
192            }
193        }
194
195        writeModelToFile(model, OUTPUT_DIR + "testCreateInteractionFromEventSequence_1_result.uml");
196        loadModelFromInputStream(new FileInputStream(OUTPUT_DIR +
197            "testCreateInteractionFromEventSequence_1_result.uml"));
198    }
199
200    @Test
201    public void testCalculateUsageScore_1() throws Exception {
202        // parse log file
203        HTTPLogParser parser =
204            new HTTPLogParser(new File(ClassLoader
205                .getSystemResource("testCalculateUsageScore_1_properties.txt").getFile()));
206        parser.parseFile(new File(ClassLoader
207            .getSystemResource("testCalculateUsageScore_1_usagedata.log").getFile()));
208        Collection<List<Event>> httpSequences = parser.getSequences();
209        Model model =
210            loadModelFromInputStream(ClassLoader
211                .getSystemResourceAsStream("testCalculateUsageScore_1_model.uml"));
212
213        Collection<List<Event>> simpleSOAPSequences = new LinkedList<>();
214        for (List<Event> httpSequence : httpSequences) {
215            for (Iterator<Event> eventIter = httpSequence.iterator(); eventIter.hasNext();) {
216                Event event = eventIter.next();
217                if (!(event.getType() instanceof SOAPEventType)) {
218                    eventIter.remove();
219                }
220            }
221            simpleSOAPSequences.add(HTTPUtils.convertToSimpleSOAPEvent(httpSequence));
222            // simpleSOAPSequences.add(httpSequence);
223        }
224
225        FirstOrderMarkovModel usageProfile = new FirstOrderMarkovModel(new Random(1));
226        usageProfile.train(simpleSOAPSequences);
227
228        Collection<List<Event>> genSeqs =
229            (new RandomWalkGenerator(10, 1, 100, true, 500)).generateTestSuite(usageProfile);
230
231        int i = 1;
232        int[] lengths = new int[genSeqs.size()];
233        for (List<Event> seq : genSeqs) {
234            UMLUtils.createInteractionFromEventSequence(seq, model, "seq_" + i);
235            lengths[i - 1] = seq.size();
236            i++;
237        }
238        for (int j = 0; j < genSeqs.size(); j++) {
239            Interaction interaction =
240                (Interaction) model.getPackagedElement("seq_" + j, true,
241                                                       UMLPackage.Literals.INTERACTION, true);
242            double usageScore = UMLUtils.calculateUsageScore(interaction, usageProfile);
243            System.out.format("usage score %02d: %.2f \t %d\n", j + 1, usageScore, lengths[j]);
244        }
245    }
246
247    private static void writeModelToFile(Model model, String filename) throws IOException {
248        final ResourceSet resourceSet = new ResourceSetImpl();
249        UMLResourcesUtil.init(resourceSet);
250        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap()
251            .put(Resource.Factory.Registry.DEFAULT_EXTENSION, new ResourceFactoryImpl() {
252                @Override
253                public Resource createResource(URI uri) {
254                    return new XMIResourceImpl(uri) {
255                        @Override
256                        public boolean useUUIDs() {
257                            return true;
258                        }
259                    };
260                }
261            });
262
263        Resource resource = resourceSet.createResource(URI.createURI("binresource"));
264
265        resource.getContents().add(model);
266        FileOutputStream fos;
267        File file = new File(filename);
268        if (file.getParent() != null) {
269            file.getParentFile().mkdirs();
270        }
271        fos = new FileOutputStream(file);
272        resource.save(fos, null);
273    }
274
275    private static Model loadModelFromInputStream(InputStream inputStream) {
276        ResourceSet resourceSet = new ResourceSetImpl();
277        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap()
278            .put(UMLResource.FILE_EXTENSION, UMLResource.Factory.INSTANCE);
279        resourceSet.getPackageRegistry().put(UMLPackage.eNS_URI, UMLPackage.eINSTANCE);
280        resourceSet.getPackageRegistry().put(EcorePackage.eNS_URI, EcorePackage.eINSTANCE);
281        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap()
282            .put(Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl());
283        Map<URI, URI> uriMap = resourceSet.getURIConverter().getURIMap();
284
285        UMLResourcesUtil.init(resourceSet);
286
287        uriMap.put(URI.createURI("pathmap://Papyrus.profile.uml"),
288                   URI.createURI("file:/D:/.../Papyrus.profile.uml/"));
289
290        EPackage.Registry.INSTANCE.put(UMLPackage.eNS_URI, UMLPackage.eINSTANCE);
291
292        Resource resource = new XMIResourceImpl();
293
294        try {
295            // resource.load(inputStream, options);
296            resource.load(inputStream, null);
297        }
298        catch (IOException e) {
299            // TODO Auto-generated catch block
300            e.printStackTrace();
301        }
302
303        return (Model) EcoreUtil.getObjectByType(resource.getContents(), UMLPackage.Literals.MODEL);
304    }
305
306    private void deleteFiles(File file) {
307        if (file.exists()) {
308            if (file.isDirectory()) {
309                for (File child : file.listFiles()) {
310                    deleteFiles(child);
311                }
312            }
313
314            try {
315                file.delete();
316            }
317            catch (Exception e) {
318                // ignore and delete as much as possible
319            }
320        }
321    }
322
323}
Note: See TracBrowser for help on using the repository browser.