1/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.ahat;
18
19import com.android.tools.perflib.heap.Instance;
20import com.sun.net.httpserver.HttpExchange;
21import com.sun.net.httpserver.HttpHandler;
22import java.awt.image.BufferedImage;
23import java.io.IOException;
24import java.io.OutputStream;
25import java.io.PrintStream;
26import javax.imageio.ImageIO;
27
28class BitmapHandler implements HttpHandler {
29  private AhatSnapshot mSnapshot;
30
31  public BitmapHandler(AhatSnapshot snapshot) {
32    mSnapshot = snapshot;
33  }
34
35  @Override
36  public void handle(HttpExchange exchange) throws IOException {
37    try {
38      Query query = new Query(exchange.getRequestURI());
39      long id = query.getLong("id", 0);
40      BufferedImage bitmap = null;
41      Instance inst = mSnapshot.findInstance(id);
42      if (inst != null) {
43        bitmap = InstanceUtils.asBitmap(inst);
44      }
45
46      if (bitmap != null) {
47        exchange.getResponseHeaders().add("Content-Type", "image/png");
48        exchange.sendResponseHeaders(200, 0);
49        OutputStream os = exchange.getResponseBody();
50        ImageIO.write(bitmap, "png", os);
51        os.close();
52      } else {
53        exchange.getResponseHeaders().add("Content-Type", "text/html");
54        exchange.sendResponseHeaders(404, 0);
55        PrintStream ps = new PrintStream(exchange.getResponseBody());
56        HtmlDoc doc = new HtmlDoc(ps, DocString.text("ahat"), DocString.uri("style.css"));
57        doc.big(DocString.text("No bitmap found for the given request."));
58        doc.close();
59      }
60    } catch (RuntimeException e) {
61      // Print runtime exceptions to standard error for debugging purposes,
62      // because otherwise they are swallowed and not reported.
63      System.err.println("Exception when handling " + exchange.getRequestURI() + ": ");
64      e.printStackTrace();
65      throw e;
66    }
67  }
68}
69