blob: fb7049dcd4d352bbe95bedcde3d123aed1b938c1 [file] [log] [blame]
Richard Uhlerb730b782015-07-15 16:01:58 -07001/*
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.google.common.io.ByteStreams;
20import com.sun.net.httpserver.HttpHandler;
21import com.sun.net.httpserver.HttpExchange;
22import java.io.InputStream;
23import java.io.IOException;
24import java.io.OutputStream;
25import java.io.PrintStream;
26
27// Handler that returns a static file included in ahat.jar.
28class StaticHandler implements HttpHandler {
29 private String mResourceName;
30 private String mContentType;
31
32 public StaticHandler(String resourceName, String contentType) {
33 mResourceName = resourceName;
34 mContentType = contentType;
35 }
36
37 @Override
38 public void handle(HttpExchange exchange) throws IOException {
39 ClassLoader loader = StaticHandler.class.getClassLoader();
40 InputStream is = loader.getResourceAsStream(mResourceName);
41 if (is == null) {
42 exchange.getResponseHeaders().add("Content-Type", "text/html");
43 exchange.sendResponseHeaders(404, 0);
44 PrintStream ps = new PrintStream(exchange.getResponseBody());
45 HtmlDoc doc = new HtmlDoc(ps, DocString.text("ahat"), DocString.uri("style.css"));
46 doc.big(DocString.text("Resource not found."));
47 doc.close();
48 } else {
49 exchange.getResponseHeaders().add("Content-Type", mContentType);
50 exchange.sendResponseHeaders(200, 0);
51 OutputStream os = exchange.getResponseBody();
52 ByteStreams.copy(is, os);
53 os.close();
54 }
55 }
56}