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