1/* 2 * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24import java.util.*; 25import java.util.concurrent.*; 26import java.util.logging.*; 27import java.io.*; 28import java.net.*; 29import java.security.*; 30import javax.net.ssl.*; 31import com.sun.net.httpserver.*; 32 33/** 34 * Implements a basic static content HTTP server 35 * which understands text/html, text/plain content types 36 * 37 * Must be given an abs pathname to the document root. 38 * Directory listings together with text + html files 39 * can be served. 40 * 41 * File Server created on files sub-path 42 * 43 * Echo server created on echo sub-path 44 */ 45public class SimpleFileServer { 46 47 public static void main (String[] args) throws Exception { 48 if (args.length != 3) { 49 System.out.println ("usage: java FileServerHandler rootDir port logfilename"); 50 System.exit(1); 51 } 52 Logger logger = Logger.getLogger("com.sun.net.httpserver"); 53 ConsoleHandler ch = new ConsoleHandler(); 54 logger.setLevel(Level.ALL); 55 ch.setLevel(Level.ALL); 56 logger.addHandler(ch); 57 58 String rootDir = args[0]; 59 int port = Integer.parseInt (args[1]); 60 String logfile = args[2]; 61 HttpServer server = HttpServer.create (new InetSocketAddress (port), 0); 62 HttpHandler h = new FileServerHandler (rootDir); 63 HttpHandler h1 = new EchoHandler (); 64 65 HttpContext c = server.createContext ("/files", h); 66 c.getFilters().add (new LogFilter (new File (logfile))); 67 HttpContext c1 = server.createContext ("/echo", h1); 68 c.getFilters().add (new LogFilter (new File (logfile))); 69 c1.getFilters().add (new LogFilter (new File (logfile))); 70 server.setExecutor (Executors.newCachedThreadPool()); 71 server.start (); 72 } 73} 74