launcher/src/main/java/org/apidesign/bck2brwsr/dew/Dew.java
author phrebejk
Tue, 15 Jan 2013 15:56:45 +0100
branchdew
changeset 460 c0f1788183dd
child 461 ccc3fd318cb1
permissions -rw-r--r--
Web development server initial prototype.
     1 /*
     2  * To change this template, choose Tools | Templates
     3  * and open the template in the editor.
     4  */
     5 package org.apidesign.bck2brwsr.dew;
     6 
     7 import java.io.IOException;
     8 import java.io.InputStream;
     9 import java.io.OutputStream;
    10 import org.glassfish.grizzly.http.server.HttpHandler;
    11 import org.glassfish.grizzly.http.server.Request;
    12 import org.glassfish.grizzly.http.server.Response;
    13 
    14 /**
    15  *
    16  * @author phrebejk
    17  */
    18 public class Dew extends HttpHandler {
    19 
    20     @Override
    21     public void service(Request request, Response response) throws Exception {
    22         String r = request.getHttpHandlerPath();
    23         if (r == null || r.equals("/")) {
    24             r = "index.html";
    25         }
    26         if (r.startsWith("/")) {
    27             r = r.substring(1);
    28         }
    29         if (r.endsWith(".html") || r.endsWith(".xhtml")) {
    30             response.setContentType("text/html");
    31         }
    32         OutputStream os = response.getOutputStream();
    33         try (InputStream is = Dew.class.getResourceAsStream(r) ) {
    34             copyStream(is, os, request.getRequestURL().toString() );
    35         } catch (IOException ex) {
    36             response.setDetailMessage(ex.getLocalizedMessage());
    37             response.setError();
    38             response.setStatus(404);
    39         }
    40     }
    41     
    42     static void copyStream(InputStream is, OutputStream os, String baseURL) throws IOException {
    43         for (;;) {
    44             int ch = is.read();
    45             if (ch == -1) {
    46                 break;
    47             }
    48             os.write(ch);            
    49         }
    50     }
    51     
    52 }