org.ESLM.Parser.JSONLessonParser.java Source code

Java tutorial

Introduction

Here is the source code for org.ESLM.Parser.JSONLessonParser.java

Source

package org.ESLM.Parser;

/*
Copyright (C) 2015 Rmi Even, Eric Perlinski
<remi.even@telecomnancy.net>
<eric.perlinski@telecomnancy.net>
    
This file is part of ESLM.
    
ESLM is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
    
ESLM is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
    
You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

import java.io.Reader;

import org.ESLM.Model.Exercise;
import org.ESLM.Model.Lesson;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

public class JSONLessonParser {

    private Reader reader;
    private Lesson parsedLesson;

    public JSONLessonParser(Reader reader) {
        this.reader = reader;
    }

    public Lesson getParsedLesson() throws BadFormedJSONExerciseException {
        if (parsedLesson == null)
            parseLesson();
        return parsedLesson;
    }

    private void parseLesson() throws BadFormedJSONExerciseException {
        JSONTokener tokener = new JSONTokener(reader);
        JSONObject jsonLesson = new JSONObject(tokener);
        String title = jsonLesson.optString("title", "Untitled Lesson");
        JSONArray jsonExercises = jsonLesson.optJSONArray("exercises");
        Exercise[] exercises = parseExercises(jsonExercises);
        parsedLesson = new Lesson(title, exercises);
    }

    private Exercise[] parseExercises(JSONArray jsonExercises) throws BadFormedJSONExerciseException {
        int numberOfExercises = jsonExercises.length();
        Exercise[] exercises = new Exercise[numberOfExercises];
        for (int i = 0; i < numberOfExercises; i++) {
            JSONObject jsonExercise = jsonExercises.getJSONObject(i);
            exercises[i] = ExerciseFactory.createExercise(jsonExercise);
        }
        return exercises;
    }

}