de.instantouch.model.io.SnakeJSONWriter.java Source code

Java tutorial

Introduction

Here is the source code for de.instantouch.model.io.SnakeJSONWriter.java

Source

/*******************************************************************************
 * Copyright (c) 2014 Joachim Tessmer.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     Joachim Tessmer - initial API and implementation
 ******************************************************************************/
package de.instantouch.model.io;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.StringTokenizer;

import org.json.simple.JSONValue;

import de.instantouch.model.base.SnakeBoolean;
import de.instantouch.model.base.SnakeDate;
import de.instantouch.model.base.SnakeDouble;
import de.instantouch.model.base.SnakeInteger;
import de.instantouch.model.base.SnakeLong;
import de.instantouch.model.base.SnakeString;
import de.instantouch.model.base.SnakeType;
import de.instantouch.model.base.ref.SnakeReference;
import de.instantouch.model.collections.SnakeEntity;
import de.instantouch.model.collections.SnakeList;
import de.instantouch.model.collections.SnakeMap;
import de.instantouch.model.exception.SnakeModelException;
import de.instantouch.model.exception.SnakeNotInitializedException;
import de.instantouch.model.exception.SnakeWrongTypeException;
import de.instantouch.model.log.SnakeLog;
import de.instantouch.model.util.SnakeContainerTools;
import de.instantouch.model.util.SnakeContainerTools.ClassInfo;
import de.instanttouch.api.model.ISnakeMap;

public class SnakeJSONWriter {
    protected Writer writer = null;
    protected PrintWriter printWriter = null;

    public SnakeJSONWriter() {
        writer = new StringWriter();
        printWriter = new PrintWriter(writer);
    }

    public SnakeJSONWriter(OutputStream output) {
        writer = new OutputStreamWriter(output);
        printWriter = new PrintWriter(writer);
    }

    public void write(SnakeEntity entity) throws SnakeModelException, IOException {

        ClassInfo classInfo = SnakeContainerTools.determineClassInfo(entity.getClass());

        printWriter.println("{");

        int i = 0;

        printWriter.print(createElementName("entityClass") + " : ");
        printWriter.print(createElementName(classInfo.getClassName()));
        i++;

        printWriter.println(",");
        printWriter.print(createElementName("bundle") + " : ");
        printWriter.print(createElementName(classInfo.getBundle()));

        for (SnakeType element : entity.getChildren()) {
            if (i > 0)
                printWriter.println(",");
            printWriter.print(createElementName(element.getName()) + " : ");
            write(element);
            i++;
        }
        printWriter.println();
        printWriter.println("}");
    }

    public void write(SnakeList<SnakeType> list) throws SnakeModelException, IOException {

        printWriter.println("[");

        int i = 0;
        for (SnakeType element : list.getChildren()) {
            if (i > 0)
                printWriter.println(",");
            write(element);
            i++;
        }

        printWriter.println();
        printWriter.println("]");
    }

    public void write(ISnakeMap<SnakeType, SnakeType> map) throws SnakeModelException, IOException {

        printWriter.println("[");

        int i = 0;
        for (SnakeType key : map.keySet()) {
            printWriter.println("{");

            printWriter.print("\"key\" : ");
            write(key);
            printWriter.println(",\n");

            printWriter.print("\"value\" : ");
            write(map.get(key));
            printWriter.println("\n");

            i++;
            printWriter.println("}");
            if (i < map.keySet().size())
                printWriter.println(",");
        }

        printWriter.println();
        printWriter.println("]");
    }

    public void write(SnakeType type) throws SnakeModelException, IOException {

        if (type.hasReference()) {
            SnakeReference ref = type.getReference();
            write(ref.getKey());
        } else {

            if (type instanceof SnakeEntity) {
                SnakeEntity entity = (SnakeEntity) type;
                write(entity);
            } else if (type instanceof SnakeList<?>) {
                SnakeList<SnakeType> list = (SnakeList<SnakeType>) type;
                write(list);
            } else if (type instanceof SnakeMap<?, ?>) {
                ISnakeMap<SnakeType, SnakeType> map = (ISnakeMap<SnakeType, SnakeType>) type;
                write(map);
            } else {
                String str = createValueString(type);
                printWriter.print(str);
            }
        }
    }

    public static String beautify(String jsonString, boolean appendNewline) {

        String beautyString = appendNewline ? newliner(jsonString) : jsonString;

        String delim = String.valueOf("\r\n");
        StringTokenizer tokenizer = new StringTokenizer(beautyString, delim);

        StringWriter beautyWriter = new StringWriter();
        PrintWriter beautyPrinter = new PrintWriter(beautyWriter);

        int tabs = 0;
        while (tokenizer.hasMoreTokens()) {
            String token = tokenizer.nextToken();
            if (token.contains("}") || token.contains("]")) {
                tabs--;
            }

            beautyPrinter.println(printtabs(beautyPrinter, tabs) + token);
            if (token.contains("{") || token.contains("[")) {
                tabs++;
            }
        }

        return beautyWriter.toString();
    }

    private static String newliner(String jsonString) {
        String beauty = jsonString.replace("{", "\n{\n");
        beauty = beauty.replace("}", "\n}\n");
        beauty = beauty.replace("[", "\n[\n");
        beauty = beauty.replace("]", "\n]\n");
        beauty = beauty.replace(",", ",\n");
        beauty = beauty.replace("\\", "");

        return beauty;
    }

    public String beautify() {
        String jsonStr = writer.toString();
        String beauty = beautify(jsonStr, false);

        return beauty;
    }

    public String getContent() {
        String content = writer.toString();
        close();
        return content;
    }

    private static String printtabs(PrintWriter beautyPrinter, int tabs) {
        String tabStr = "";
        for (int i = 0; i < tabs; i++) {
            beautyPrinter.print("   ");
        }
        return tabStr;
    }

    private String createElementName(String name) {
        return "\"" + name + "\"";
    }

    private String createValueString(Object obj) throws SnakeWrongTypeException, SnakeNotInitializedException {
        String jsonString = null;

        if (obj instanceof SnakeType) {
            SnakeType type = (SnakeType) obj;

            if (type instanceof SnakeDate) {
                jsonString = JSONValue.toJSONString(type.toString());
            } else if (!type.handleAsBasic()) {
                throw new SnakeWrongTypeException("not supported type: " + type.getClass().getName());
            } else if (type instanceof SnakeBoolean) {
                jsonString = JSONValue.toJSONString(type.toString());
            } else if (type instanceof SnakeInteger) {
                jsonString = JSONValue.toJSONString(type.toString());
            } else if (type instanceof SnakeLong) {
                jsonString = JSONValue.toJSONString(type.toString());
            } else if (type instanceof SnakeDouble) {
                jsonString = JSONValue.toJSONString(type.toString());
            } else if (type instanceof SnakeString) {
                jsonString = JSONValue.toJSONString(type.toString());
            }
        } else {
            jsonString = JSONValue.toJSONString(obj);
        }

        return jsonString;
    }

    public void close() {
        if (printWriter != null) {
            printWriter.close();
        }

        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                SnakeLog.log(e);
            }
        }
        printWriter = null;
        writer = null;
    }

}