b1ab9e68f83df8abbc8d859e715f7007921c5029
[idea/community.git] / python / educational-core / student / src / com / jetbrains / edu / learning / StudySerializationUtils.java
1 package com.jetbrains.edu.learning;
2
3 import com.google.gson.*;
4 import com.google.gson.reflect.TypeToken;
5 import com.intellij.openapi.editor.Document;
6 import com.intellij.openapi.editor.EditorFactory;
7 import com.intellij.openapi.fileEditor.FileDocumentManager;
8 import com.intellij.openapi.project.Project;
9 import com.intellij.openapi.util.io.FileUtil;
10 import com.intellij.openapi.vfs.LocalFileSystem;
11 import com.intellij.openapi.vfs.VirtualFile;
12 import com.intellij.util.containers.ContainerUtil;
13 import com.intellij.util.containers.hash.HashMap;
14 import com.jetbrains.edu.learning.core.EduNames;
15 import com.jetbrains.edu.learning.courseFormat.AnswerPlaceholder;
16 import com.jetbrains.edu.learning.courseFormat.Course;
17 import com.jetbrains.edu.learning.courseFormat.StudyStatus;
18 import com.jetbrains.edu.learning.courseFormat.TaskFile;
19 import org.jdom.Attribute;
20 import org.jdom.Element;
21 import org.jdom.output.XMLOutputter;
22
23 import java.io.File;
24 import java.lang.reflect.Type;
25 import java.util.Collections;
26 import java.util.List;
27 import java.util.Map;
28
29 public class StudySerializationUtils {
30
31   public static final String PLACEHOLDERS = "placeholders";
32   public static final String LINE = "line";
33   public static final String START = "start";
34   public static final String LENGTH = "length";
35   public static final String POSSIBLE_ANSWER = "possible_answer";
36   public static final String HINT = "hint";
37   public static final String ADDITIONAL_HINTS = "additional_hints";
38   public static final String OFFSET = "offset";
39   public static final String TEXT = "text";
40   public static final String LESSONS = "lessons";
41   public static final String COURSE = "course";
42   public static final String COURSE_TITLED = "Course";
43   public static final String STATUS = "status";
44   public static final String AUTHOR = "author";
45   public static final String AUTHORS = "authors";
46   public static final String MY_INITIAL_START = "myInitialStart";
47
48   private StudySerializationUtils() {
49   }
50
51   public static class StudyUnrecognizedFormatException extends Exception {
52   }
53
54   public static class Xml {
55     public final static String COURSE_ELEMENT = "courseElement";
56     public final static String MAIN_ELEMENT = "StudyTaskManager";
57     public static final String MAP = "map";
58     public static final String KEY = "key";
59     public static final String VALUE = "value";
60     public static final String NAME = "name";
61     public static final String LIST = "list";
62     public static final String OPTION = "option";
63     public static final String INDEX = "index";
64     public static final String STUDY_STATUS_MAP = "myStudyStatusMap";
65     public static final String TASK_STATUS_MAP = "myTaskStatusMap";
66     public static final String LENGTH = "length";
67     public static final String ANSWER_PLACEHOLDERS = "answerPlaceholders";
68     public static final String TASK_LIST = "taskList";
69     public static final String TASK_FILES = "taskFiles";
70     public static final String INITIAL_STATE = "initialState";
71     public static final String MY_INITIAL_STATE = "MyInitialState";
72     public static final String MY_LINE = "myLine";
73     public static final String MY_START = "myStart";
74     public static final String MY_LENGTH = "myLength";
75     public static final String HINT = "hint";
76     public static final String AUTHOR_TITLED = "Author";
77     public static final String FIRST_NAME = "first_name";
78     public static final String SECOND_NAME = "second_name";
79     public static final String MY_INITIAL_LINE = "myInitialLine";
80     public static final String MY_INITIAL_LENGTH = "myInitialLength";
81     public static final String ANSWER_PLACEHOLDER = "AnswerPlaceholder";
82     public static final String TASK_WINDOWS = "taskWindows";
83     public static final String RESOURCE_PATH = "resourcePath";
84     public static final String COURSE_DIRECTORY = "courseDirectory";
85     public static final String SUBTASK_INFO = "AnswerPlaceholderSubtaskInfo";
86     public static final String SUBTASK_INFOS = "subtaskInfos";
87     public static final String ADDITIONAL_HINTS = "additionalHints";
88     public static final String POSSIBLE_ANSWER = "possibleAnswer";
89     public static final String SELECTED = "selected";
90     public static final String TASK_TEXT = "taskText";
91     public static final String PLACEHOLDER_TEXT = "placeholderText";
92
93     private Xml() {
94     }
95
96     public static int getVersion(Element element) throws StudyUnrecognizedFormatException {
97       if (element.getChild(COURSE_ELEMENT) != null) {
98         return 1;
99       }
100
101       final Element taskManager = element.getChild(MAIN_ELEMENT);
102
103       Element versionElement = getChildWithName(taskManager, "VERSION");
104       if (versionElement == null) {
105         return -1;
106       }
107
108       return Integer.valueOf(versionElement.getAttributeValue(VALUE));
109     }
110
111     public static Element convertToSecondVersion(Element element) throws StudyUnrecognizedFormatException {
112       final Element oldCourseElement = element.getChild(COURSE_ELEMENT);
113       Element state = new Element(MAIN_ELEMENT);
114
115       Element course = addChildWithName(state, COURSE, oldCourseElement.clone());
116       course.setName(COURSE_TITLED);
117
118       Element author = getChildWithName(course, AUTHOR);
119       String authorString = author.getAttributeValue(VALUE);
120       course.removeContent(author);
121
122       String[] names = authorString.split(" ", 2);
123       Element authorElement = new Element(AUTHOR_TITLED);
124       addChildWithName(authorElement, FIRST_NAME, names[0]);
125       addChildWithName(authorElement, SECOND_NAME, names.length == 1 ? "" : names[1]);
126
127       addChildList(course, AUTHORS, Collections.singletonList(authorElement));
128
129       Element courseDirectoryElement = getChildWithName(course, RESOURCE_PATH);
130       renameElement(courseDirectoryElement, COURSE_DIRECTORY);
131
132       for (Element lesson : getChildList(course, LESSONS)) {
133         incrementIndex(lesson);
134         for (Element task : getChildList(lesson, TASK_LIST)) {
135           incrementIndex(task);
136           Map<String, Element> taskFiles = getChildMap(task, TASK_FILES);
137           for (Element taskFile : taskFiles.values()) {
138             renameElement(getChildWithName(taskFile, TASK_WINDOWS), ANSWER_PLACEHOLDERS);
139             for (Element placeholder : getChildList(taskFile, ANSWER_PLACEHOLDERS)) {
140               placeholder.setName(ANSWER_PLACEHOLDER);
141
142               Element initialState = new Element(MY_INITIAL_STATE);
143               addChildWithName(placeholder, INITIAL_STATE, initialState);
144               addChildWithName(initialState, MY_LINE, getChildWithName(placeholder, MY_INITIAL_LINE).getAttributeValue(VALUE));
145               addChildWithName(initialState, MY_START, getChildWithName(placeholder, MY_INITIAL_START).getAttributeValue(VALUE));
146               addChildWithName(initialState, MY_LENGTH, getChildWithName(placeholder, MY_INITIAL_LENGTH).getAttributeValue(VALUE));
147             }
148           }
149         }
150       }
151       element.removeContent();
152       element.addContent(state);
153       return element;
154     }
155
156     public static Map<String, String> fillStatusMap(Element taskManagerElement, String mapName, XMLOutputter outputter)
157       throws StudyUnrecognizedFormatException {
158       Map<Element, String> sourceMap = getChildMap(taskManagerElement, mapName);
159       Map<String, String> destMap = new HashMap<>();
160       for (Map.Entry<Element, String> entry : sourceMap.entrySet()) {
161         String status = entry.getValue();
162         if (status.equals(StudyStatus.Unchecked.toString())) {
163           continue;
164         }
165         destMap.put(outputter.outputString(entry.getKey()), status);
166       }
167       return destMap;
168     }
169
170     public static Element convertToThirdVersion(Element state, Project project) throws StudyUnrecognizedFormatException {
171       Element taskManagerElement = state.getChild(MAIN_ELEMENT);
172       XMLOutputter outputter = new XMLOutputter();
173
174       Map<String, String> placeholderTextToStatus = fillStatusMap(taskManagerElement, STUDY_STATUS_MAP, outputter);
175       Map<String, String> taskFileToStatusMap = fillStatusMap(taskManagerElement, TASK_STATUS_MAP, outputter);
176
177       Element courseElement = getChildWithName(taskManagerElement, COURSE).getChild(COURSE_TITLED);
178       for (Element lesson : getChildList(courseElement, LESSONS)) {
179         int lessonIndex = getAsInt(lesson, INDEX);
180         for (Element task : getChildList(lesson, TASK_LIST)) {
181           String taskStatus = null;
182           int taskIndex = getAsInt(task, INDEX);
183           Map<String, Element> taskFiles = getChildMap(task, TASK_FILES);
184           for (Map.Entry<String, Element> entry : taskFiles.entrySet()) {
185             Element taskFileElement = entry.getValue();
186             String taskFileText = outputter.outputString(taskFileElement);
187             String taskFileStatus = taskFileToStatusMap.get(taskFileText);
188             if (taskFileStatus != null && (taskStatus == null || taskFileStatus.equals(StudyStatus.Failed.toString()))) {
189               taskStatus = taskFileStatus;
190             }
191             Document document = StudyUtils.getDocument(project.getBasePath(), lessonIndex, taskIndex, entry.getKey());
192             if (document == null) {
193               continue;
194             }
195             for (Element placeholder : getChildList(taskFileElement, ANSWER_PLACEHOLDERS)) {
196               taskStatus = addStatus(outputter, placeholderTextToStatus, taskStatus, placeholder);
197               addOffset(document, placeholder);
198               addInitialState(document, placeholder);
199             }
200           }
201           if (taskStatus != null) {
202             addChildWithName(task, STATUS, taskStatus);
203           }
204         }
205       }
206       return state;
207     }
208
209     public static Element convertToForthVersion(Element state) throws StudyUnrecognizedFormatException {
210       Element taskManagerElement = state.getChild(MAIN_ELEMENT);
211       Element courseElement = getChildWithName(taskManagerElement, COURSE).getChild(COURSE_TITLED);
212       for (Element lesson : getChildList(courseElement, LESSONS)) {
213         for (Element task : getChildList(lesson, TASK_LIST)) {
214           Map<String, Element> taskFiles = getChildMap(task, TASK_FILES);
215           for (Map.Entry<String, Element> entry : taskFiles.entrySet()) {
216             Element taskFileElement = entry.getValue();
217             for (Element placeholder : getChildList(taskFileElement, ANSWER_PLACEHOLDERS)) {
218               Element valueElement = new Element(SUBTASK_INFO);
219               addChildMap(placeholder, SUBTASK_INFOS, Collections.singletonMap(String.valueOf(0), valueElement));
220               for (String childName : ContainerUtil
221                 .list(HINT, ADDITIONAL_HINTS, POSSIBLE_ANSWER, SELECTED, STATUS, TASK_TEXT)) {
222                 Element child = getChildWithName(placeholder, childName);
223                 valueElement.addContent(child.clone());
224               }
225               renameElement(getChildWithName(valueElement, TASK_TEXT), PLACEHOLDER_TEXT);
226             }
227           }
228         }
229       }
230
231       return state;
232     }
233
234     public static String addStatus(XMLOutputter outputter,
235                                    Map<String, String> placeholderTextToStatus,
236                                    String taskStatus,
237                                    Element placeholder) {
238       String placeholderText = outputter.outputString(placeholder);
239       String status = placeholderTextToStatus.get(placeholderText);
240       if (status != null) {
241         addChildWithName(placeholder, STATUS, status);
242         if (taskStatus == null || status.equals(StudyStatus.Failed.toString())) {
243           taskStatus = status;
244         }
245       }
246       return taskStatus;
247     }
248
249     public static void addInitialState(Document document, Element placeholder) throws StudyUnrecognizedFormatException {
250       Element initialState = getChildWithName(placeholder, INITIAL_STATE).getChild(MY_INITIAL_STATE);
251       int initialLine = getAsInt(initialState, MY_LINE);
252       int initialStart = getAsInt(initialState, MY_START);
253       int initialOffset = document.getLineStartOffset(initialLine) + initialStart;
254       addChildWithName(initialState, OFFSET, initialOffset);
255       renameElement(getChildWithName(initialState, MY_LENGTH), LENGTH);
256     }
257
258     public static void addOffset(Document document, Element placeholder) throws StudyUnrecognizedFormatException {
259       int line = getAsInt(placeholder, LINE);
260       int start = getAsInt(placeholder, START);
261       int offset = document.getLineStartOffset(line) + start;
262       addChildWithName(placeholder, OFFSET, offset);
263     }
264
265     public static int getAsInt(Element element, String name) throws StudyUnrecognizedFormatException {
266       return Integer.valueOf(getChildWithName(element, name).getAttributeValue(VALUE));
267     }
268
269     public static void incrementIndex(Element element) throws StudyUnrecognizedFormatException {
270       Element index = getChildWithName(element, INDEX);
271       int indexValue = Integer.parseInt(index.getAttributeValue(VALUE));
272       changeValue(index, indexValue + 1);
273     }
274
275     public static void renameElement(Element element, String newName) {
276       element.setAttribute(NAME, newName);
277     }
278
279     public static void changeValue(Element element, Object newValue) {
280       element.setAttribute(VALUE, newValue.toString());
281     }
282
283     public static Element addChildWithName(Element parent, String name, Element value) {
284       Element child = new Element(OPTION);
285       child.setAttribute(NAME, name);
286       child.addContent(value);
287       parent.addContent(child);
288       return value;
289     }
290
291     public static Element addChildWithName(Element parent, String name, Object value) {
292       Element child = new Element(OPTION);
293       child.setAttribute(NAME, name);
294       child.setAttribute(VALUE, value.toString());
295       parent.addContent(child);
296       return child;
297     }
298
299     public static Element addChildList(Element parent, String name, List<Element> elements) {
300       Element listElement = new Element(LIST);
301       for (Element element : elements) {
302         listElement.addContent(element);
303       }
304       return addChildWithName(parent, name, listElement);
305     }
306
307     public static Element addChildMap(Element parent, String name, Map<String, Element> value) {
308       Element mapElement = new Element(MAP);
309       for (Map.Entry<String, Element> entry : value.entrySet()) {
310         Element entryElement = new Element("entry");
311         mapElement.addContent(entryElement);
312         String key = entry.getKey();
313         entryElement.setAttribute("key", key);
314         Element valueElement = new Element("value");
315         valueElement.addContent(entry.getValue());
316         entryElement.addContent(valueElement);
317       }
318       return addChildWithName(parent, name, mapElement);
319     }
320
321     public static List<Element> getChildList(Element parent, String name) throws StudyUnrecognizedFormatException {
322       return getChildList(parent, name, false);
323     }
324
325     public static List<Element> getChildList(Element parent, String name, boolean optional) throws StudyUnrecognizedFormatException {
326       Element listParent = getChildWithName(parent, name, optional);
327       if (listParent != null) {
328         Element list = listParent.getChild(LIST);
329         if (list != null) {
330           return list.getChildren();
331         }
332       }
333       return Collections.emptyList();
334     }
335
336     public static Element getChildWithName(Element parent, String name) throws StudyUnrecognizedFormatException {
337       return getChildWithName(parent, name, false);
338     }
339
340     public static Element getChildWithName(Element parent, String name, boolean optional) throws StudyUnrecognizedFormatException {
341       for (Element child : parent.getChildren()) {
342         Attribute attribute = child.getAttribute(NAME);
343         if (attribute == null) {
344           continue;
345         }
346         if (name.equals(attribute.getValue())) {
347           return child;
348         }
349       }
350       if (optional) {
351         return null;
352       }
353       throw new StudyUnrecognizedFormatException();
354     }
355
356     public static <K, V> Map<K, V> getChildMap(Element element, String name) throws StudyUnrecognizedFormatException {
357       return getChildMap(element, name, false);
358     }
359
360     public static <K, V> Map<K, V> getChildMap(Element element, String name, boolean optional) throws StudyUnrecognizedFormatException {
361       Element mapParent = getChildWithName(element, name, optional);
362       if (mapParent != null) {
363         Element map = mapParent.getChild(MAP);
364         if (map != null) {
365           HashMap result = new HashMap();
366           for (Element entry : map.getChildren()) {
367             Object key = entry.getAttribute(KEY) == null ? entry.getChild(KEY).getChildren().get(0) : entry.getAttributeValue(KEY);
368             Object value = entry.getAttribute(VALUE) == null ? entry.getChild(VALUE).getChildren().get(0) : entry.getAttributeValue(VALUE);
369             result.put(key, value);
370           }
371           return result;
372         }
373       }
374       return Collections.emptyMap();
375     }
376   }
377
378   public static class Json {
379
380     public static final String TASK_LIST = "task_list";
381     public static final String TASK_FILES = "task_files";
382
383     private Json() {
384     }
385
386     public static class CourseTypeAdapter implements JsonDeserializer<Course> {
387
388       private final File myCourseFile;
389
390       public CourseTypeAdapter(File courseFile) {
391         myCourseFile = courseFile;
392       }
393
394       @Override
395       public Course deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
396         JsonObject courseObject = json.getAsJsonObject();
397         JsonArray lessons = courseObject.getAsJsonArray(LESSONS);
398         for (int lessonIndex = 1; lessonIndex <= lessons.size(); lessonIndex++) {
399           JsonObject lessonObject = lessons.get(lessonIndex - 1).getAsJsonObject();
400           JsonArray tasks = lessonObject.getAsJsonArray(TASK_LIST);
401           for (int taskIndex = 1; taskIndex <= tasks.size(); taskIndex++) {
402             JsonObject taskObject = tasks.get(taskIndex - 1).getAsJsonObject();
403             for (Map.Entry<String, JsonElement> taskFile : taskObject.getAsJsonObject(TASK_FILES).entrySet()) {
404               String name = taskFile.getKey();
405               String filePath = FileUtil.join(myCourseFile.getParent(), EduNames.LESSON + lessonIndex, EduNames.TASK + taskIndex, name);
406               VirtualFile resourceFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(filePath));
407               if (resourceFile == null) {
408                 continue;
409               }
410               Document document = FileDocumentManager.getInstance().getDocument(resourceFile);
411               if (document == null) {
412                 continue;
413               }
414               JsonObject taskFileObject = taskFile.getValue().getAsJsonObject();
415               JsonArray placeholders = taskFileObject.getAsJsonArray(PLACEHOLDERS);
416               for (JsonElement placeholder : placeholders) {
417                 JsonObject placeholderObject = placeholder.getAsJsonObject();
418                 if (placeholderObject.getAsJsonPrimitive(OFFSET) != null) {
419                   break;
420                 }
421                 int line = placeholderObject.getAsJsonPrimitive(LINE).getAsInt();
422                 int start = placeholderObject.getAsJsonPrimitive(START).getAsInt();
423                 int offset = document.getLineStartOffset(line) + start;
424                 placeholderObject.addProperty(OFFSET, offset);
425               }
426             }
427           }
428         }
429         return new GsonBuilder().create().fromJson(json, Course.class);
430       }
431     }
432
433     public static class StepicTaskFileAdapter implements JsonDeserializer<TaskFile> {
434
435       @Override
436       public TaskFile deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
437         final Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
438         JsonObject taskFileObject = json.getAsJsonObject();
439         JsonArray placeholders = taskFileObject.getAsJsonArray(PLACEHOLDERS);
440         for (JsonElement placeholder : placeholders) {
441           JsonObject placeholderObject = placeholder.getAsJsonObject();
442           int line = placeholderObject.getAsJsonPrimitive(LINE).getAsInt();
443           int start = placeholderObject.getAsJsonPrimitive(START).getAsInt();
444           if (line == -1) {
445             placeholderObject.addProperty(OFFSET, start);
446           }
447           else {
448             Document document = EditorFactory.getInstance().createDocument(taskFileObject.getAsJsonPrimitive(TEXT).getAsString());
449             placeholderObject.addProperty(OFFSET, document.getLineStartOffset(line) + start);
450           }
451           final String hintString = placeholderObject.getAsJsonPrimitive(HINT).getAsString();
452           final JsonArray hintsArray = new JsonArray();
453
454           try {
455             final Type listType = new TypeToken<List<String>>() {}.getType();
456             final List<String> hints = gson.fromJson(hintString, listType);
457             if (hints != null && !hints.isEmpty()) {
458               for (int i = 0; i < hints.size(); i++) {
459                 if (i == 0) {
460                   placeholderObject.addProperty(HINT, hints.get(0));
461                   continue;
462                 }
463                 hintsArray.add(hints.get(i));
464               }
465               placeholderObject.add(ADDITIONAL_HINTS, hintsArray);
466             }
467             else {
468               placeholderObject.addProperty(HINT, "");
469             }
470           }
471           catch (JsonParseException e) {
472             hintsArray.add(hintString);
473           }
474         }
475
476         return gson.fromJson(json, TaskFile.class);
477       }
478     }
479
480     public static class StepicAnswerPlaceholderAdapter implements JsonSerializer<AnswerPlaceholder> {
481       @Override
482       public JsonElement serialize(AnswerPlaceholder src, Type typeOfSrc, JsonSerializationContext context) {
483         final List<String> hints = src.getHints();
484
485         final int length = src.getLength();
486         final int start = src.getOffset();
487         final String possibleAnswer = src.getPossibleAnswer();
488         int line = -1;
489
490         final Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
491         final JsonObject answerPlaceholder = new JsonObject();
492         answerPlaceholder.addProperty(LINE, line);
493         answerPlaceholder.addProperty(START, start);
494         answerPlaceholder.addProperty(LENGTH, length);
495         answerPlaceholder.addProperty(POSSIBLE_ANSWER, possibleAnswer);
496
497         final String jsonHints = gson.toJson(hints);
498         answerPlaceholder.addProperty(HINT, jsonHints);
499
500         return answerPlaceholder;
501       }
502     }
503   }
504 }