source: trunk/autoquest-ui-core/src/main/java/de/ugoe/cs/autoquest/commands/sequences/CMDgenerateReplayfile.java @ 927

Last change on this file since 927 was 927, checked in by sherbold, 12 years ago
  • added copyright under the Apache License, Version 2.0
File size: 6.9 KB
Line 
1//   Copyright 2012 Georg-August-Universität Göttingen, Germany
2//
3//   Licensed under the Apache License, Version 2.0 (the "License");
4//   you may not use this file except in compliance with the License.
5//   You may obtain a copy of the License at
6//
7//       http://www.apache.org/licenses/LICENSE-2.0
8//
9//   Unless required by applicable law or agreed to in writing, software
10//   distributed under the License is distributed on an "AS IS" BASIS,
11//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//   See the License for the specific language governing permissions and
13//   limitations under the License.
14
15package de.ugoe.cs.autoquest.commands.sequences;
16
17import java.io.File;
18import java.io.FileOutputStream;
19import java.io.IOException;
20import java.io.OutputStreamWriter;
21import java.util.Collection;
22import java.util.List;
23import java.util.logging.Level;
24
25import de.ugoe.cs.autoquest.CommandHelpers;
26import de.ugoe.cs.autoquest.IReplayDecorator;
27import de.ugoe.cs.autoquest.SequenceInstanceOf;
28import de.ugoe.cs.autoquest.eventcore.Event;
29import de.ugoe.cs.autoquest.eventcore.IReplayable;
30import de.ugoe.cs.util.StringTools;
31import de.ugoe.cs.util.console.Command;
32import de.ugoe.cs.util.console.Console;
33import de.ugoe.cs.util.console.GlobalDataContainer;
34
35/**
36 * <p>
37 * Command to create a replay file from stored sessions.
38 * </p>
39 *
40 * TODO: Add appropriate checks if Events are replayable
41 *
42 * @author Steffen Herbold
43 * @version 1.0
44 */
45public class CMDgenerateReplayfile implements Command {
46
47        /*
48         * (non-Javadoc)
49         *
50         * @see de.ugoe.cs.util.console.Command#help()
51         */
52        @Override
53        public String help() {
54                return "generateReplayfile <filename> <sequences>";
55        }
56
57        /*
58         * (non-Javadoc)
59         *
60         * @see de.ugoe.cs.util.console.Command#run(java.util.List)
61         */
62        @SuppressWarnings("unchecked")
63        @Override
64        public void run(List<Object> parameters) {
65                String filename;
66                String sequencesName;
67                try {
68                        filename = (String) parameters.get(0);
69                        sequencesName = (String) parameters.get(1);
70                } catch (Exception e) {
71                        throw new IllegalArgumentException();
72                }
73
74                Collection<List<Event>> sequences = null;
75                Object dataObject = GlobalDataContainer.getInstance().getData(
76                                sequencesName);
77                if (dataObject == null) {
78                        CommandHelpers.objectNotFoundMessage(sequencesName);
79                        return;
80                }
81                if (!SequenceInstanceOf.isCollectionOfSequences(dataObject)) {
82                        CommandHelpers.objectNotType(sequencesName,
83                                        "Collection<List<Event<?>>>");
84                        return;
85                }
86
87                sequences = (Collection<List<Event>>) dataObject;
88                createLogfileMultipleSessions(sequences, filename);
89        }
90       
91            /**
92             * <p>
93             * {@link IReplayDecorator} to be used. If this field is {@code null}, no decorator is used.
94             * Default: {@code null}
95             * </p>
96             */
97            private IReplayDecorator decorator = null;
98
99            /**
100             * <p>
101             * Id of the current session. The starting id is 1.
102             * </p>
103             */
104            int sessionId = 1;
105
106            /**
107             * <p>
108             * Creates a replay file that contains multiple event sequences.
109             * </p>
110             *
111             * @param sequences
112             *            collection of event sequences from which the sessions are generated
113             * @param filename
114             *            name and path of the replay file
115             */
116            private void createLogfileMultipleSessions(Collection<List<Event>> sequences, String filename) {
117                OutputStreamWriter writer = openReplayFile(filename);
118                if (writer != null) {
119                    try {
120                        try {
121                            decorator =
122                                sequences.iterator().next().get(0).getReplayables().get(0).getDecorator();
123                        }
124                        catch (Exception e) {
125                            // in the above line, many things can go wrong: emtpy sequences, null
126                            // references, etc. However, all failures just indicate that no replay decorator
127                            // should be used, hence, we ignore the exception
128                        }
129                        if (decorator != null) {
130                            writer.write(decorator.getHeader());
131                        }
132                        for (List<Event> actions : sequences) {
133                            writeSession(actions, writer);
134                        }
135                        if (decorator != null) {
136                            writer.write(decorator.getFooter());
137                        }
138                        decorator = null;
139                        writer.close();
140                    }
141                    catch (IOException e) {
142                        Console.printerrln("Unable to write replay file " + filename);
143                    }
144                }
145            }
146
147            /**
148             * <p>
149             * Helper function that opens the replay file for writing.
150             * </p>
151             *
152             * @param filename
153             *            name and path of the replay file
154             * @return {@link OutputStreamWriter} that writes to the replay file
155             */
156            private OutputStreamWriter openReplayFile(String filename) {
157                File file = new File(filename);
158                boolean fileCreated;
159                try {
160                    fileCreated = file.createNewFile();
161                    if (!fileCreated) {
162                        Console.traceln(Level.INFO, "Created logfile " + filename);
163                    }
164                    else {
165                        Console.traceln(Level.INFO, "Overwrote existing logfile " + filename);
166                    }
167                }
168                catch (IOException e) {
169                    Console.printerrln("Unable to create file " + filename);
170                    Console.logException(e);
171                }
172                OutputStreamWriter writer = null;
173                try {
174                    writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-16");
175                }
176                catch (IOException e) {
177                    Console.printerrln("Unable to open file for writing (read-only file):" + filename);
178                    Console.logException(e);
179                }
180                return writer;
181            }
182
183            /**
184             * <p>
185             * Helper function that adds an event sequence to the replay.
186             * </p>
187             *
188             * @param actions
189             *            event sequences to be added
190             * @param writer
191             *            {@link OutputStreamWriter} to which the replay is added
192             * @throws IOException
193             *             thrown if there is a problem writing to writer
194             */
195            private void writeSession(List<Event> actions, OutputStreamWriter writer) throws IOException {
196                if (decorator != null) {
197                    writer.write(decorator.getSessionHeader(sessionId));
198                }
199                for (Event currentAction : actions) {
200
201                    List<? extends IReplayable> replayables = currentAction.getReplayables();
202                    for (IReplayable replayble : replayables) {
203                        writer.write(replayble.getReplay() + StringTools.ENDLINE);
204                        writer.flush();
205                    }
206                }
207                if (decorator != null) {
208                    writer.write(decorator.getSessionFooter(sessionId));
209                }
210                sessionId++;
211            }
212}
Note: See TracBrowser for help on using the repository browser.