|
| 1 | +package org.jooby; |
| 2 | + |
| 3 | +import org.jooby.Request; |
| 4 | +import org.jooby.Response; |
| 5 | +import org.jooby.Route; |
| 6 | + |
| 7 | +import java.io.*; |
| 8 | +import java.nio.charset.Charset; |
| 9 | +import java.util.Arrays; |
| 10 | + |
| 11 | +public class SSIHandler implements Route.Handler { |
| 12 | + |
| 13 | + private final String file; |
| 14 | + private final String type; |
| 15 | + |
| 16 | + public SSIHandler(String file, String type) { |
| 17 | + this.file = file; |
| 18 | + this.type = type; |
| 19 | + } |
| 20 | + |
| 21 | + @Override |
| 22 | + public void handle(Request req, Response rsp) throws Throwable { |
| 23 | + StringBuilder op = new StringBuilder(); |
| 24 | + process(op, file); |
| 25 | + Charset charset = Charset.forName("UTF-8"); |
| 26 | + byte[] output = op.toString().getBytes(charset); |
| 27 | + rsp.charset(charset); |
| 28 | + rsp.length(output.length); |
| 29 | + rsp.type(type); |
| 30 | + rsp.status(200); |
| 31 | + rsp.send(output); |
| 32 | + } |
| 33 | + |
| 34 | + private void process(StringBuilder op, String file) throws IOException { |
| 35 | + InputStream stream = this.getClass().getResourceAsStream(file); |
| 36 | + if (stream == null) { |
| 37 | + stream = findResource(file, "/target/test-classes", "/target/classes"); |
| 38 | + } |
| 39 | + LineNumberReader lnr = new LineNumberReader(new InputStreamReader(stream)); |
| 40 | + String line = lnr.readLine(); |
| 41 | + while (line != null) { |
| 42 | + if (line.contains("JOOBY-INCLUDE")) { |
| 43 | + process(op, toInclude(line)); |
| 44 | + } else { |
| 45 | + op.append(line).append("\n"); |
| 46 | + } |
| 47 | + line = lnr.readLine(); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + private InputStream findResource(String file, String... paths) throws IOException { |
| 52 | + final String canonicalPath = new File(".").getCanonicalPath(); |
| 53 | + for (String path : paths) { |
| 54 | + final String filePath = (canonicalPath + path) + file; |
| 55 | + System.err.println("--> " + filePath); |
| 56 | + if(new File(filePath).exists()) { |
| 57 | + return new FileInputStream(filePath); |
| 58 | + } |
| 59 | + } |
| 60 | + throw new UnsupportedOperationException(file + " not found in " + Arrays.toString(paths)); |
| 61 | + } |
| 62 | + |
| 63 | + private String toInclude(String line) { |
| 64 | + int str = line.indexOf("JOOBY-INCLUDE ") + "JOOBY-INCLUDE ".length(); |
| 65 | + return line.substring(str, line.indexOf(" ", str + 1)); |
| 66 | + } |
| 67 | +} |
0 commit comments