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 
17 package com.android.ahat;
18 
19 import com.sun.net.httpserver.HttpExchange;
20 import com.sun.net.httpserver.HttpHandler;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.OutputStream;
24 import java.io.PrintStream;
25 
26 // Handler that returns a static file included in ahat.jar.
27 class StaticHandler implements HttpHandler {
28   private String mResourceName;
29   private String mContentType;
30 
StaticHandler(String resourceName, String contentType)31   public StaticHandler(String resourceName, String contentType) {
32     mResourceName = resourceName;
33     mContentType = contentType;
34   }
35 
36   @Override
handle(HttpExchange exchange)37   public void handle(HttpExchange exchange) throws IOException {
38     ClassLoader loader = StaticHandler.class.getClassLoader();
39     InputStream is = loader.getResourceAsStream(mResourceName);
40     if (is == null) {
41       exchange.getResponseHeaders().add("Content-Type", "text/html");
42       exchange.sendResponseHeaders(404, 0);
43       PrintStream ps = new PrintStream(exchange.getResponseBody());
44       HtmlDoc doc = new HtmlDoc(ps, DocString.text("ahat"), DocString.uri("style.css"));
45       doc.big(DocString.text("Resource not found."));
46       doc.close();
47     } else {
48       exchange.getResponseHeaders().add("Content-Type", mContentType);
49       exchange.sendResponseHeaders(200, 0);
50       OutputStream os = exchange.getResponseBody();
51       int read;
52       byte[] buf = new byte[4096];
53       while ((read = is.read(buf)) >= 0) {
54         os.write(buf, 0, read);
55       }
56       is.close();
57       os.close();
58     }
59   }
60 }
61