1 package fi.iki.elonen; 2 3 import org.pegdown.PegDownProcessor; 4 5 import java.io.*; 6 import java.util.Map; 7 8 import static fi.iki.elonen.NanoHTTPD.MIME_HTML; 9 import static fi.iki.elonen.NanoHTTPD.Response.Status.OK; 10 11 /** 12 * @author Paul S. Hawke (paul.hawke (at) gmail.com) 13 * On: 9/13/13 at 4:03 AM 14 */ 15 public class MarkdownWebServerPlugin implements WebServerPlugin { 16 17 private final PegDownProcessor processor; 18 19 public MarkdownWebServerPlugin() { 20 processor = new PegDownProcessor(); 21 } 22 23 @Override public void initialize(Map<String, String> commandLineOptions) { 24 } 25 26 @Override public boolean canServeUri(String uri, File rootDir) { 27 File f = new File(rootDir, uri); 28 return f.exists(); 29 } 30 31 @Override 32 public NanoHTTPD.Response serveFile(String uri, Map<String, String> headers, NanoHTTPD.IHTTPSession session, File file, String mimeType) { 33 String markdownSource = readSource(file); 34 return markdownSource == null ? null : 35 new NanoHTTPD.Response(OK, MIME_HTML, processor.markdownToHtml(markdownSource)); 36 } 37 38 private String readSource(File file) { 39 FileReader fileReader = null; 40 BufferedReader reader = null; 41 try { 42 fileReader = new FileReader(file); 43 reader = new BufferedReader(fileReader); 44 String line = null; 45 StringBuilder sb = new StringBuilder(); 46 do { 47 line = reader.readLine(); 48 if (line != null) { 49 sb.append(line).append("\n"); 50 } 51 } while (line != null); 52 reader.close(); 53 return sb.toString(); 54 } catch (Exception e) { 55 e.printStackTrace(); 56 return null; 57 } finally { 58 try { 59 if (fileReader != null) { 60 fileReader.close(); 61 } 62 if (reader != null) { 63 reader.close(); 64 } 65 } catch (IOException ignored) {} 66 } 67 } 68 } 69