com.facebook.tsdb.tsdash.server.PlotImageEndpoint.java Source code

Java tutorial

Introduction

Here is the source code for com.facebook.tsdb.tsdash.server.PlotImageEndpoint.java

Source

/*
 * Copyright 2011 Facebook, Inc.
 *
 * 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 com.facebook.tsdb.tsdash.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

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

import com.google.common.io.Closeables;

/**
 * @author James Royalty (jroyalty) <i>[May 29, 2013]</i>
 */
public class PlotImageEndpoint extends TsdbServlet {
    private static final long serialVersionUID = 4695826656621742442L;

    private static int BUFFER_SIZE = 1024;

    @Override
    protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("image/png");

        final String filename = new File(req.getPathInfo()).getName();

        File file = new File(TsdbServlet.plotsDir, filename);
        FileInputStream in = new FileInputStream(file);

        resp.setBufferSize(BUFFER_SIZE);

        final ServletOutputStream out = resp.getOutputStream();

        try {
            byte[] buffer = new byte[1024];
            while ((in.read(buffer)) != -1) {
                out.write(buffer);
            }
        } finally {
            Closeables.closeQuietly(in);
        }

        out.flush();
        resp.flushBuffer();
    }
}