001/*
002 * Copyright 2013 Prometheus Team Licensed under the Apache License, Version 2.0
003 * (the "License"); you may not use this file except in compliance with the
004 * License. You may obtain a copy of the License at
005 *
006 * http://www.apache.org/licenses/LICENSE-2.0
007 *
008 * Unless required by applicable law or agreed to in writing, software
009 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
010 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
011 * License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package io.prometheus.client.utility.servlet;
016
017import com.matttproud.accepts.Accept;
018import com.matttproud.accepts.Parser;
019import io.prometheus.client.Prometheus;
020
021import javax.servlet.ServletException;
022import javax.servlet.http.HttpServlet;
023import javax.servlet.http.HttpServletRequest;
024import javax.servlet.http.HttpServletResponse;
025import java.io.BufferedOutputStream;
026import java.io.IOException;
027import java.util.Map;
028
029/**
030 * @author matt.proud@gmail.com (Matt T. Proud)
031 */
032public class MetricsServlet extends HttpServlet {
033  private void dumpJson(final HttpServletResponse resp) throws IOException {
034    resp.setContentType("application/json; schema=\"prometheus/telemetry\"; version=0.0.2");
035    Prometheus.defaultDumpJson(resp.getWriter());
036  }
037
038  private void dumpProto(final HttpServletResponse resp) throws IOException {
039    resp.setContentType("application/vnd.google.protobuf; proto=\"io.prometheus.client.MetricFamily\"; encoding=\"delimited\"");
040    final BufferedOutputStream buf = new BufferedOutputStream(resp.getOutputStream());
041    Prometheus.defaultDumpProto(buf);
042    buf.close();
043  }
044
045  @Override
046  protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
047      throws ServletException, IOException {
048    resp.setStatus(HttpServletResponse.SC_OK);
049    boolean dispensed = false;
050    try {
051      for (final Accept spec : Parser.parse(req)) {
052        if ("application".equals(spec.getType()) && "vnd.google.protobuf".equals(spec.getSubtype())) {
053          final Map<String, String> params = spec.getParams();
054          if ("io.prometheus.client.MetricFamily".equals(params.get("proto"))
055              && "delimited".equals(params.get("encoding"))) {
056            dumpProto(resp);
057            dispensed = true;
058            break;
059          }
060        }
061      }
062    } catch (final IllegalArgumentException e) {
063    } finally {
064      if (!dispensed) {
065        dumpJson(resp);
066      }
067    }
068  }
069}