package ru.yandex.webmaster.common.health;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author aherman
 */
public class PingServantlet extends HttpServlet {
    private static final byte[] RESPONSE_XML_BYTES = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><pong />".getBytes();
    private static final byte[] RESPONSE_JSON_BYTES = "{\"pong\": true}".getBytes();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String format = req.getParameter("format");
        boolean jsonFormat = false;
        if ("json".equals(format)) {
            jsonFormat = true;
        }

        resp.setStatus(HttpServletResponse.SC_OK);

        ServletOutputStream outputStream;
        if (jsonFormat) {
            resp.setContentType("application/json; charset=UTF-8");
            resp.setContentLength(RESPONSE_JSON_BYTES.length);
            outputStream = resp.getOutputStream();
            outputStream.write(RESPONSE_JSON_BYTES);
        } else {
            resp.setContentType("text/xml; charset=UTF-8");
            resp.setContentLength(RESPONSE_XML_BYTES.length);
            outputStream = resp.getOutputStream();
            outputStream.write(RESPONSE_XML_BYTES);
        }
        outputStream.flush();
    }
}
