Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
javaによる複数の特定ディレクトリ以下の静的リソースを返すHttpサーバー(やっつけ実装)
package server;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashMap;
import java.util.Map;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
/**
* HttpServer of static resources.
*
* configure paths and port in main method.
* paths's key is context. It maps http://localhost:8080/this
* paths's values is file system path.
* http://localhost:8080/this/xxx is maps in file system.
*
*/
public class StaticResourceHttpServer {
public static void main(String[] args) throws IOException {
final Map<String, String> paths = new HashMap<String, String>(){{
put("example1", "WebContent/example");
put("example2", "c:/temp/example2");
}};
int port = 8080;
new StaticResourceHttpServer().runSeaver(paths, port);
}
private Map<String, String> paths;
public void runSeaver(Map<String, String> staticPaths, int port) throws IOException {
this.paths = staticPaths;
final HttpServer server = HttpServer.create(
new InetSocketAddress(port), 0);
for (Map.Entry<String, String> entry : paths.entrySet()) {
final String context = entry.getKey();
String fsPath = entry.getValue();
FileSystem fs = FileSystems.getDefault();
final Path root = fs.getPath(fsPath);
Files.walkFileTree(root,
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) throws IOException {
Path p = root.relativize(file);
server.createContext(toUrl(context, p.toString()),
fileHander);
return super.visitFile(file, attrs);
}
});
}
server.setExecutor(null);
server.start();
}
private String toUrl(String context, String filePath) {
String res = "/" + context + "/" + filePath.replace('\\', '/');
System.out.println(res);
return res;
}
private final HttpHandler fileHander = new HttpHandler() {
private Map<String, String> ct = new HashMap<String, String>() {
{
put("html", "text/html;charset=utf-8");
put("xml", "text/xml");
put("css", "text/css;charset=utf-8");
put("js", "text/javascript;charset=utf-8");
put("json", "application/json");
}
};
@Override
public void handle(HttpExchange ex) throws IOException {
String path = ex.getRequestURI().getPath();
String context = path.substring(1, path.indexOf("/", 1));
String realPath = paths.get(context) + path.substring(path.indexOf("/", 1));
System.out.println(realPath);
String suffix = realPath.substring(realPath.lastIndexOf(".") + 1);
if (ct.containsKey(suffix)) {
ex.getResponseHeaders().add("Content-Type", ct.get(suffix));
}
byte[] res = read(realPath);
ex.sendResponseHeaders(200, res.length);
OutputStream os = ex.getResponseBody();
os.write(res);
os.close();
ex.close();
}
};
private static byte[] read(String path) throws IOException {
return Files.readAllBytes(new File(path).toPath());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment