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

Last change on this file since 1672 was 1672, checked in by dmay, 10 years ago

fully revert the changes to generateReplayfile

File size: 7.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.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        }
71        catch (Exception e) {
72            throw new IllegalArgumentException();
73        }
74
75        Collection<List<Event>> sequences = null;
76        Object dataObject = GlobalDataContainer.getInstance().getData(sequencesName);
77        if (dataObject == null) {
78            CommandHelpers.objectNotFoundMessage(sequencesName);
79            return;
80        }
81        if (!SequenceInstanceOf.isCollectionOfSequences(dataObject)) {
82            CommandHelpers.objectNotType(sequencesName, "Collection<List<Event<?>>>");
83            return;
84        }
85
86        sequences = (Collection<List<Event>>) dataObject;
87        createLogfileMultipleSessions(sequences, filename);
88    }
89
90    /**
91     * <p>
92     * {@link IReplayDecorator} to be used. If this field is {@code null}, no decorator is used.
93     * Default: {@code null}
94     * </p>
95     */
96    private IReplayDecorator decorator = null;
97
98    /**
99     * <p>
100     * Id of the current session. The starting id is 1.
101     * </p>
102     */
103    int sessionId = 1;
104
105    /**
106     * <p>
107     * Creates a replay file that contains multiple event sequences.
108     * </p>
109     *
110     * @param sequences
111     *            collection of event sequences from which the sessions are generated
112     * @param filename
113     *            name and path of the replay file
114     */
115    private void createLogfileMultipleSessions(Collection<List<Event>> sequences, String filename) {
116        OutputStreamWriter writer = openReplayFile(filename);
117        if (writer != null) {
118            try {
119                try {
120                    decorator =
121                        sequences.iterator().next().get(0).getReplayables().get(0).getDecorator();
122                }
123                catch (Exception e) {
124                    // in the above line, many things can go wrong: emtpy sequences, null
125                    // references, etc. However, all failures just indicate that no replay decorator
126                    // should be used, hence, we ignore the exception
127                    Console.traceln(Level.FINEST, "no decorator used for " + filename);
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     * @param encoding
155     *            file encoding, empty string for platform default
156     * @return {@link OutputStreamWriter} that writes to the replay file
157     */
158    private OutputStreamWriter openReplayFile(String filename) {
159        File file = new File(filename);
160        boolean fileCreated;
161        try {
162            fileCreated = file.createNewFile();
163            if (!fileCreated) {
164                Console.traceln(Level.INFO, "Created logfile " + filename);
165            }
166            else {
167                Console.traceln(Level.INFO, "Overwrote existing logfile " + filename);
168            }
169        }
170        catch (IOException e) {
171            Console.printerrln("Unable to create file " + filename);
172            Console.logException(e);
173        }
174        OutputStreamWriter writer = null;
175        try {
176            writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-16");
177        }
178        catch (IOException e) {
179            Console.printerrln("Unable to open file for writing (read-only file):" + filename);
180            Console.logException(e);
181        }
182        return writer;
183    }
184
185    /**
186     * <p>
187     * Helper function that adds an event sequence to the replay.
188     * </p>
189     *
190     * @param actions
191     *            event sequences to be added
192     * @param writer
193     *            {@link OutputStreamWriter} to which the replay is added
194     * @throws IOException
195     *             thrown if there is a problem writing to writer
196     */
197    private void writeSession(List<Event> actions, OutputStreamWriter writer) throws IOException {
198        if (decorator != null) {
199            writer.write(decorator.getSessionHeader(sessionId));
200        }
201        for (Event currentAction : actions) {
202
203            List<? extends IReplayable> replayables = currentAction.getReplayables();
204            for (IReplayable replayble : replayables) {
205                writer.write(replayble.getReplay() + StringTools.ENDLINE);
206                writer.flush();
207            }
208        }
209        if (decorator != null) {
210            writer.write(decorator.getSessionFooter(sessionId));
211        }
212        sessionId++;
213    }
214}
Note: See TracBrowser for help on using the repository browser.