001/*
002 * Stallion Core: A Modern Web Framework
003 *
004 * Copyright (C) 2015 - 2016 Stallion Software LLC.
005 *
006 * This program is free software: you can redistribute it and/or modify it under the terms of the
007 * GNU General Public License as published by the Free Software Foundation, either version 2 of
008 * the License, or (at your option) any later version. This program is distributed in the hope that
009 * it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
010 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
011 * License for more details. You should have received a copy of the GNU General Public License
012 * along with this program.  If not, see <http://www.gnu.org/licenses/gpl-2.0.html>.
013 *
014 *
015 *
016 */
017
018package io.stallion.dataAccess.file;
019
020import com.fasterxml.jackson.databind.ObjectMapper;
021
022import com.fasterxml.jackson.databind.SerializationFeature;
023import io.stallion.dataAccess.DataAccessRegistry;
024import io.stallion.dataAccess.Model;
025
026import static io.stallion.utils.Literals.*;
027
028import io.stallion.utils.json.JSON;
029import org.apache.commons.io.FileUtils;
030
031import java.io.File;
032import java.io.IOException;
033import java.util.HashSet;
034import java.util.Set;
035
036public class JsonFilePersister<T extends Model> extends FilePersisterBase<T> {
037
038    private static final Set<String> extensions = new HashSet<>(list("json"));
039
040    @Override
041    public Set<String> getFileExtensions() {
042        return extensions;
043    }
044
045    public T doFetchOne(File file) {
046        T o = null;
047        try {
048            String json = FileUtils.readFileToString(file, UTF8);
049            o = JSON.parse(json, this.getModelClass());
050        } catch (IOException e) {
051            throw new RuntimeException(e);
052        }
053
054        return o;
055    }
056
057
058    @Override
059    public void persist(T obj) {
060        if (obj.getId() == null) {
061            obj.setId(DataAccessRegistry.instance().getTickets().nextId());
062        }
063        String filePath = fullFilePathForObj(obj);
064        File file = new File(filePath);
065        File directory = new File(file.getParent());
066        if (!directory.isDirectory()) {
067            directory.mkdirs();
068        }
069
070        try {
071            FileUtils.write(file, JSON.stringify(obj), UTF8);
072        } catch (IOException e) {
073            throw new RuntimeException(e);
074        }
075        //ObjectMapper mapper = new ObjectMapper();
076        //mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
077        //try {
078            //mapper.writerWithDefaultPrettyPrinter().writeValue(file, obj);
079        //} catch (IOException e) {
080        //    throw new RuntimeException(e);
081        //}
082
083    }
084
085
086
087
088
089}