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

Last change on this file since 1270 was 1270, checked in by pharms, 11 years ago
  • removed find bugs warnings
File size: 7.0 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                            Console.traceln(Level.FINEST, "no decorator used for " + filename);
129                        }
130                        if (decorator != null) {
131                            writer.write(decorator.getHeader());
132                        }
133                        for (List<Event> actions : sequences) {
134                            writeSession(actions, writer);
135                        }
136                        if (decorator != null) {
137                            writer.write(decorator.getFooter());
138                        }
139                        decorator = null;
140                        writer.close();
141                    }
142                    catch (IOException e) {
143                        Console.printerrln("Unable to write replay file " + filename);
144                    }
145                }
146            }
147
148            /**
149             * <p>
150             * Helper function that opens the replay file for writing.
151             * </p>
152             *
153             * @param filename
154             *            name and path of the replay file
155             * @return {@link OutputStreamWriter} that writes to the replay file
156             */
157            private OutputStreamWriter openReplayFile(String filename) {
158                File file = new File(filename);
159                boolean fileCreated;
160                try {
161                    fileCreated = file.createNewFile();
162                    if (!fileCreated) {
163                        Console.traceln(Level.INFO, "Created logfile " + filename);
164                    }
165                    else {
166                        Console.traceln(Level.INFO, "Overwrote existing logfile " + filename);
167                    }
168                }
169                catch (IOException e) {
170                    Console.printerrln("Unable to create file " + filename);
171                    Console.logException(e);
172                }
173                OutputStreamWriter writer = null;
174                try {
175                    writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-16");
176                }
177                catch (IOException e) {
178                    Console.printerrln("Unable to open file for writing (read-only file):" + filename);
179                    Console.logException(e);
180                }
181                return writer;
182            }
183
184            /**
185             * <p>
186             * Helper function that adds an event sequence to the replay.
187             * </p>
188             *
189             * @param actions
190             *            event sequences to be added
191             * @param writer
192             *            {@link OutputStreamWriter} to which the replay is added
193             * @throws IOException
194             *             thrown if there is a problem writing to writer
195             */
196            private void writeSession(List<Event> actions, OutputStreamWriter writer) throws IOException {
197                if (decorator != null) {
198                    writer.write(decorator.getSessionHeader(sessionId));
199                }
200                for (Event currentAction : actions) {
201
202                    List<? extends IReplayable> replayables = currentAction.getReplayables();
203                    for (IReplayable replayble : replayables) {
204                        writer.write(replayble.getReplay() + StringTools.ENDLINE);
205                        writer.flush();
206                    }
207                }
208                if (decorator != null) {
209                    writer.write(decorator.getSessionFooter(sessionId));
210                }
211                sessionId++;
212            }
213}
Note: See TracBrowser for help on using the repository browser.