cc.pinel.mangue.storage.StateStorage.java Source code

Java tutorial

Introduction

Here is the source code for cc.pinel.mangue.storage.StateStorage.java

Source

/*
 * Copyright 2014 Roque Pinel
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cc.pinel.mangue.storage;

import java.io.IOException;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import com.amazon.kindle.kindlet.KindletContext;

public class StateStorage extends AbstractStorage {
    public StateStorage(KindletContext context) {
        super(context, "state.json");
    }

    public String getChapter(String mangaId) {
        String chapterNumber = null;

        JSONArray jsonMangas = null;

        try {
            jsonMangas = (JSONArray) readJSON().get("mangas");
        } catch (Exception e) {
            // ignored
        }
        if (jsonMangas == null)
            jsonMangas = new JSONArray();

        JSONObject jsonManga = findManga(jsonMangas, mangaId);
        if (jsonManga != null)
            chapterNumber = jsonManga.get("chapterNumber").toString();

        return chapterNumber;
    }

    public void setChapter(String mangaId, String chapterNumber) throws IOException {
        JSONObject json = null;

        try {
            json = readJSON();
        } catch (Exception e) {
            // ignored
        }
        if (json == null)
            json = new JSONObject();

        JSONArray jsonMangas = (JSONArray) json.get("mangas");
        if (jsonMangas == null) {
            jsonMangas = new JSONArray();
            json.put("mangas", jsonMangas);
        }

        JSONObject jsonManga = findManga(jsonMangas, mangaId);
        if (jsonManga == null) {
            jsonManga = new JSONObject();
            jsonManga.put("id", mangaId);
            jsonMangas.add(jsonManga);
        }
        jsonManga.put("chapterNumber", chapterNumber);

        writeJSON(json);
    }
}