me.prokopyl.storagemonitor.httpserver.HTTPResponse.java Source code

Java tutorial

Introduction

Here is the source code for me.prokopyl.storagemonitor.httpserver.HTTPResponse.java

Source

/*
 * Copyright (C) 2014 adrien
 *
 * This program 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 2
 * of the License, or (at your option) any later version.
 *
 * This program 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, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

package me.prokopyl.storagemonitor.httpserver;

import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.io.OutputStream;
import me.prokopyl.storagemonitor.worker.Response;
import org.json.simple.JSONArray;
import org.json.simple.JSONAware;

public class HTTPResponse extends Response {
    private final HttpExchange exchange;

    public HTTPResponse(HttpExchange exchange) {
        this.exchange = exchange;
    }

    @Override
    public void send() {
        try {
            byte[] JSONData = ToJSONString(this.data).getBytes();
            exchange.getResponseHeaders().add("Content-Type", "application/json");
            exchange.sendResponseHeaders(getHTTPStatusCode(), JSONData.length);

            OutputStream stream = exchange.getResponseBody();
            stream.write(JSONData);
            stream.close();
        } catch (IOException ex) {
        }
    }

    public int getHTTPStatusCode() {
        switch (status) {
        case OK:
            return 200;
        case NOT_FOUND:
            return 404;
        case SERVER_ERROR:
            return 500;
        case SERVER_STOPPED:
            return 503;
        default:
            return 200;
        }
    }

    static public String ToJSONString(Object object) {
        if (object instanceof JSONAware) {
            return ((JSONAware) object).toJSONString();
        } else {
            JSONArray array = new JSONArray();
            array.add(object);
            return array.toJSONString();
        }
    }

}