1 package com.jetbrains.edu.learning;
3 import com.google.gson.*;
4 import com.intellij.openapi.editor.Document;
5 import com.intellij.openapi.editor.EditorFactory;
6 import com.intellij.openapi.fileEditor.FileDocumentManager;
7 import com.intellij.openapi.project.Project;
8 import com.intellij.openapi.util.io.FileUtil;
9 import com.intellij.openapi.vfs.LocalFileSystem;
10 import com.intellij.openapi.vfs.VirtualFile;
11 import com.intellij.util.containers.hash.HashMap;
12 import com.jetbrains.edu.learning.core.EduNames;
13 import com.jetbrains.edu.learning.courseFormat.AnswerPlaceholder;
14 import com.jetbrains.edu.learning.courseFormat.Course;
15 import com.jetbrains.edu.learning.courseFormat.StudyStatus;
16 import com.jetbrains.edu.learning.courseFormat.TaskFile;
17 import org.jdom.Attribute;
18 import org.jdom.Element;
19 import org.jdom.output.XMLOutputter;
20 import org.jetbrains.annotations.NotNull;
23 import java.lang.reflect.Type;
24 import java.util.Collections;
25 import java.util.List;
28 public class StudySerializationUtils {
30 public static final String PLACEHOLDERS = "placeholders";
31 public static final String LINE = "line";
32 public static final String START = "start";
33 public static final String LENGTH = "length";
34 public static final String POSSIBLE_ANSWER = "possible_answer";
35 public static final String HINT = "hint";
36 public static final String HINTS = "hints";
37 public static final String OFFSET = "offset";
38 public static final String TEXT = "text";
39 public static final String LESSONS = "lessons";
40 public static final String COURSE = "course";
41 public static final String COURSE_TITLED = "Course";
42 public static final String STATUS = "status";
43 public static final String AUTHOR = "author";
44 public static final String AUTHORS = "authors";
45 public static final String MY_INITIAL_START = "myInitialStart";
47 private StudySerializationUtils() {
50 public static class StudyUnrecognizedFormatException extends Exception {}
52 public static class Xml {
53 public final static String COURSE_ELEMENT = "courseElement";
54 public final static String MAIN_ELEMENT = "StudyTaskManager";
55 public static final String MAP = "map";
56 public static final String KEY = "key";
57 public static final String VALUE = "value";
58 public static final String NAME = "name";
59 public static final String LIST = "list";
60 public static final String OPTION = "option";
61 public static final String INDEX = "index";
62 public static final String STUDY_STATUS_MAP = "myStudyStatusMap";
63 public static final String TASK_STATUS_MAP = "myTaskStatusMap";
64 public static final String LENGTH = "length";
65 public static final String ANSWER_PLACEHOLDERS = "answerPlaceholders";
66 public static final String TASK_LIST = "taskList";
67 public static final String TASK_FILES = "taskFiles";
68 public static final String INITIAL_STATE = "initialState";
69 public static final String MY_INITIAL_STATE = "MyInitialState";
70 public static final String MY_LINE = "myLine";
71 public static final String MY_START = "myStart";
72 public static final String MY_LENGTH = "myLength";
73 public static final String HINTS = "hints";
74 public static final String HINT = "hint";
75 public static final String AUTHOR_TITLED = "Author";
76 public static final String FIRST_NAME = "first_name";
77 public static final String SECOND_NAME = "second_name";
78 public static final String MY_INITIAL_LINE = "myInitialLine";
79 public static final String MY_INITIAL_LENGTH = "myInitialLength";
80 public static final String ANSWER_PLACEHOLDER = "AnswerPlaceholder";
81 public static final String TASK_WINDOWS = "taskWindows";
82 public static final String RESOURCE_PATH = "resourcePath";
83 public static final String COURSE_DIRECTORY = "courseDirectory";
88 public static int getVersion(Element element) throws StudyUnrecognizedFormatException {
89 if (element.getChild(COURSE_ELEMENT) != null) {
93 final Element taskManager = element.getChild(MAIN_ELEMENT);
95 Element versionElement = getChildWithName(taskManager, "VERSION");
96 if (versionElement == null) {
100 return Integer.valueOf(versionElement.getAttributeValue(VALUE));
103 public static Element convertToSecondVersion(Element element) throws StudyUnrecognizedFormatException {
104 final Element oldCourseElement = element.getChild(COURSE_ELEMENT);
105 Element state = new Element(MAIN_ELEMENT);
107 Element course = addChildWithName(state, COURSE, oldCourseElement.clone());
108 course.setName(COURSE_TITLED);
110 Element author = getChildWithName(course, AUTHOR);
111 String authorString = author.getAttributeValue(VALUE);
112 course.removeContent(author);
114 String[] names = authorString.split(" ", 2);
115 Element authorElement = new Element(AUTHOR_TITLED);
116 addChildWithName(authorElement, FIRST_NAME, names[0]);
117 addChildWithName(authorElement, SECOND_NAME, names.length == 1 ? "" : names[1]);
119 addChildList(course, AUTHORS, Collections.singletonList(authorElement));
121 Element courseDirectoryElement = getChildWithName(course, RESOURCE_PATH);
122 renameElement(courseDirectoryElement, COURSE_DIRECTORY);
124 for (Element lesson : getChildList(course, LESSONS)) {
125 incrementIndex(lesson);
126 for (Element task : getChildList(lesson, TASK_LIST)) {
127 incrementIndex(task);
128 Map<String, Element> taskFiles = getChildMap(task, TASK_FILES);
129 for (Element taskFile : taskFiles.values()) {
130 renameElement(getChildWithName(taskFile, TASK_WINDOWS), ANSWER_PLACEHOLDERS);
131 for (Element placeholder : getChildList(taskFile, ANSWER_PLACEHOLDERS)) {
132 placeholder.setName(ANSWER_PLACEHOLDER);
134 Element initialState = new Element(MY_INITIAL_STATE);
135 addChildWithName(placeholder, INITIAL_STATE, initialState);
136 addChildWithName(initialState, MY_LINE, getChildWithName(placeholder, MY_INITIAL_LINE).getAttributeValue(VALUE));
137 addChildWithName(initialState, MY_START, getChildWithName(placeholder, MY_INITIAL_START).getAttributeValue(VALUE));
138 addChildWithName(initialState, MY_LENGTH, getChildWithName(placeholder, MY_INITIAL_LENGTH).getAttributeValue(VALUE));
144 element.removeContent();
145 element.addContent(state);
149 public static Map<String, String> fillStatusMap(Element taskManagerElement, String mapName, XMLOutputter outputter)
150 throws StudyUnrecognizedFormatException {
151 Map<Element, String> sourceMap = getChildMap(taskManagerElement, mapName);
152 Map<String, String> destMap = new HashMap<>();
153 for (Map.Entry<Element, String> entry : sourceMap.entrySet()) {
154 String status = entry.getValue();
155 if (status.equals(StudyStatus.Unchecked.toString())) {
158 destMap.put(outputter.outputString(entry.getKey()), status);
163 public static Element convertToThirdVersion(Element state, Project project) throws StudyUnrecognizedFormatException {
164 Element taskManagerElement = state.getChild(MAIN_ELEMENT);
165 XMLOutputter outputter = new XMLOutputter();
167 Map<String, String> placeholderTextToStatus = fillStatusMap(taskManagerElement, STUDY_STATUS_MAP, outputter);
168 Map<String, String> taskFileToStatusMap = fillStatusMap(taskManagerElement, TASK_STATUS_MAP, outputter);
170 Element courseElement = getChildWithName(taskManagerElement, COURSE).getChild(COURSE_TITLED);
171 for (Element lesson : getChildList(courseElement, LESSONS)) {
172 int lessonIndex = getAsInt(lesson, INDEX);
173 for (Element task : getChildList(lesson, TASK_LIST)) {
174 String taskStatus = null;
175 int taskIndex = getAsInt(task, INDEX);
176 Map<String, Element> taskFiles = getChildMap(task, TASK_FILES);
177 for (Map.Entry<String, Element> entry : taskFiles.entrySet()) {
178 Element taskFileElement = entry.getValue();
179 String taskFileText = outputter.outputString(taskFileElement);
180 String taskFileStatus = taskFileToStatusMap.get(taskFileText);
181 if (taskFileStatus != null && (taskStatus == null || taskFileStatus.equals(StudyStatus.Failed.toString()))) {
182 taskStatus = taskFileStatus;
184 Document document = StudyUtils.getDocument(project.getBasePath(), lessonIndex, taskIndex, entry.getKey());
185 if (document == null) {
188 for (Element placeholder : getChildList(taskFileElement, ANSWER_PLACEHOLDERS)) {
189 taskStatus = addStatus(outputter, placeholderTextToStatus, taskStatus, placeholder);
190 addOffset(document, placeholder);
191 addInitialState(document, placeholder);
192 addHints(placeholder);
195 if (taskStatus != null) {
196 addChildWithName(task, STATUS, taskStatus);
203 public static String addStatus(XMLOutputter outputter,
204 Map<String, String> placeholderTextToStatus,
206 Element placeholder) {
207 String placeholderText = outputter.outputString(placeholder);
208 String status = placeholderTextToStatus.get(placeholderText);
209 if (status != null) {
210 addChildWithName(placeholder, STATUS, status);
211 if (taskStatus == null || status.equals(StudyStatus.Failed.toString())) {
218 public static void addInitialState(Document document, Element placeholder) throws StudyUnrecognizedFormatException {
219 Element initialState = getChildWithName(placeholder, INITIAL_STATE).getChild(MY_INITIAL_STATE);
220 int initialLine = getAsInt(initialState, MY_LINE);
221 int initialStart = getAsInt(initialState, MY_START);
222 int initialOffset = document.getLineStartOffset(initialLine) + initialStart;
223 addChildWithName(initialState, OFFSET, initialOffset);
224 renameElement(getChildWithName(initialState, MY_LENGTH), LENGTH);
227 public static void addOffset(Document document, Element placeholder) throws StudyUnrecognizedFormatException {
228 int line = getAsInt(placeholder, LINE);
229 int start = getAsInt(placeholder, START);
230 int offset = document.getLineStartOffset(line) + start;
231 addChildWithName(placeholder, OFFSET, offset);
234 public static void addHints(@NotNull Element placeholder) throws StudyUnrecognizedFormatException {
235 final String hint = getChildWithName(placeholder, HINT).getAttribute(VALUE).getValue();
236 Element listElement = new Element(LIST);
237 final Element hintElement = new Element(OPTION);
238 hintElement.setAttribute(VALUE, hint);
239 listElement.setContent(hintElement);
240 addChildWithName(placeholder, HINTS, listElement);
243 public static int getAsInt(Element element, String name) throws StudyUnrecognizedFormatException {
244 return Integer.valueOf(getChildWithName(element, name).getAttributeValue(VALUE));
247 public static void incrementIndex(Element element) throws StudyUnrecognizedFormatException {
248 Element index = getChildWithName(element, INDEX);
249 int indexValue = Integer.parseInt(index.getAttributeValue(VALUE));
250 changeValue(index, indexValue + 1);
253 public static void renameElement(Element element, String newName) {
254 element.setAttribute(NAME, newName);
257 public static void changeValue(Element element, Object newValue) {
258 element.setAttribute(VALUE, newValue.toString());
261 public static Element addChildWithName(Element parent, String name, Element value) {
262 Element child = new Element(OPTION);
263 child.setAttribute(NAME, name);
264 child.addContent(value);
265 parent.addContent(child);
269 public static Element addChildWithName(Element parent, String name, Object value) {
270 Element child = new Element(OPTION);
271 child.setAttribute(NAME, name);
272 child.setAttribute(VALUE, value.toString());
273 parent.addContent(child);
277 public static Element addChildList(Element parent, String name, List<Element> elements) {
278 Element listElement = new Element(LIST);
279 for (Element element : elements) {
280 listElement.addContent(element);
282 return addChildWithName(parent, name, listElement);
285 public static List<Element> getChildList(Element parent, String name) throws StudyUnrecognizedFormatException {
286 Element listParent = getChildWithName(parent, name);
287 if (listParent != null) {
288 Element list = listParent.getChild(LIST);
290 return list.getChildren();
293 return Collections.emptyList();
296 public static Element getChildWithName(Element parent, String name) throws StudyUnrecognizedFormatException {
297 for (Element child : parent.getChildren()) {
298 Attribute attribute = child.getAttribute(NAME);
299 if (attribute == null) {
302 if (name.equals(attribute.getValue())) {
306 throw new StudyUnrecognizedFormatException();
309 public static <K, V> Map<K, V> getChildMap(Element element, String name) throws StudyUnrecognizedFormatException {
310 Element mapParent = getChildWithName(element, name);
311 if (mapParent != null) {
312 Element map = mapParent.getChild(MAP);
314 HashMap result = new HashMap();
315 for (Element entry : map.getChildren()) {
316 Object key = entry.getAttribute(KEY) == null ? entry.getChild(KEY).getChildren().get(0) : entry.getAttributeValue(KEY);
317 Object value = entry.getAttribute(VALUE) == null ? entry.getChild(VALUE).getChildren().get(0) : entry.getAttributeValue(VALUE);
318 result.put(key, value);
323 return Collections.emptyMap();
327 public static class Json {
329 public static final String TASK_LIST = "task_list";
330 public static final String TASK_FILES = "task_files";
335 public static class CourseTypeAdapter implements JsonDeserializer<Course> {
337 private final File myCourseFile;
339 public CourseTypeAdapter(File courseFile) {
340 myCourseFile = courseFile;
344 public Course deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
345 JsonObject courseObject = json.getAsJsonObject();
346 JsonArray lessons = courseObject.getAsJsonArray(LESSONS);
347 for (int lessonIndex = 1; lessonIndex <= lessons.size(); lessonIndex++) {
348 JsonObject lessonObject = lessons.get(lessonIndex - 1).getAsJsonObject();
349 JsonArray tasks = lessonObject.getAsJsonArray(TASK_LIST);
350 for (int taskIndex = 1; taskIndex <= tasks.size(); taskIndex++) {
351 JsonObject taskObject = tasks.get(taskIndex - 1).getAsJsonObject();
352 for (Map.Entry<String, JsonElement> taskFile : taskObject.getAsJsonObject(TASK_FILES).entrySet()) {
353 String name = taskFile.getKey();
354 String filePath = FileUtil.join(myCourseFile.getParent(), EduNames.LESSON + lessonIndex, EduNames.TASK + taskIndex, name);
355 VirtualFile resourceFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(filePath));
356 if (resourceFile == null) {
359 Document document = FileDocumentManager.getInstance().getDocument(resourceFile);
360 if (document == null) {
363 JsonObject taskFileObject = taskFile.getValue().getAsJsonObject();
364 JsonArray placeholders = taskFileObject.getAsJsonArray(PLACEHOLDERS);
365 for (JsonElement placeholder : placeholders) {
366 JsonObject placeholderObject = placeholder.getAsJsonObject();
367 if (placeholderObject.getAsJsonPrimitive(OFFSET) != null) {
370 int line = placeholderObject.getAsJsonPrimitive(LINE).getAsInt();
371 int start = placeholderObject.getAsJsonPrimitive(START).getAsInt();
372 int offset = document.getLineStartOffset(line) + start;
373 placeholderObject.addProperty(OFFSET, offset);
378 return new GsonBuilder().create().fromJson(json, Course.class);
382 public static class StepicTaskFileAdapter implements JsonDeserializer<TaskFile> {
385 public TaskFile deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
386 final Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
387 JsonObject taskFileObject = json.getAsJsonObject();
388 JsonArray placeholders = taskFileObject.getAsJsonArray(PLACEHOLDERS);
389 for (JsonElement placeholder : placeholders) {
390 JsonObject placeholderObject = placeholder.getAsJsonObject();
391 int line = placeholderObject.getAsJsonPrimitive(LINE).getAsInt();
392 int start = placeholderObject.getAsJsonPrimitive(START).getAsInt();
394 placeholderObject.addProperty(OFFSET, start);
396 Document document = EditorFactory.getInstance().createDocument(taskFileObject.getAsJsonPrimitive(TEXT).getAsString());
397 placeholderObject.addProperty(OFFSET, document.getLineStartOffset(line) + start);
399 final String hintString = placeholderObject.getAsJsonPrimitive(HINT).getAsString();
400 final JsonArray hintsArray = new JsonArray();
403 final List<String> hints = gson.fromJson(hintString, List.class);
404 for (String hint : hints) {
405 hintsArray.add(hint);
408 catch (JsonParseException e) {
409 hintsArray.add(hintString);
411 placeholderObject.add(HINTS, hintsArray);
414 return gson.fromJson(json, TaskFile.class);
418 public static class StepicAnswerPlaceholderAdapter implements JsonSerializer<AnswerPlaceholder> {
420 public JsonElement serialize(AnswerPlaceholder src, Type typeOfSrc, JsonSerializationContext context) {
421 final List<String> hints = src.getHints();
423 final int length = src.getLength();
424 final int start = src.getOffset();
425 final String possibleAnswer = src.getPossibleAnswer();
427 final Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
428 final JsonObject answerPlaceholder = new JsonObject();
429 answerPlaceholder.addProperty(OFFSET, start);
430 answerPlaceholder.addProperty(LENGTH, length);
431 answerPlaceholder.addProperty(POSSIBLE_ANSWER, possibleAnswer);
433 final String jsonHints = gson.toJson(hints);
434 answerPlaceholder.addProperty(HINT, jsonHints);
436 return answerPlaceholder;