List of usage examples for javax.net.ssl SSLContext getInstance
public static SSLContext getInstance(String protocol) throws NoSuchAlgorithmException
From source file:com.adhi.webserver.WebServer.java
public static void main(String[] args) throws Exception { int port = 9999; // Set up the HTTP protocol processor HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate()) .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl()) .build();/*from w ww .j av a2 s .c o m*/ // Set up request handlers UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); reqistry.register("*", new MessageCommandHandler()); // Set up the HTTP service HttpService httpService = new HttpService(httpproc, reqistry); SSLServerSocketFactory sf = null; if (port == 8443) { // Initialize SSL context ClassLoader cl = WebServer.class.getClassLoader(); URL url = cl.getResource("my.keystore"); if (url == null) { System.out.println("Keystore not found"); System.exit(1); } KeyStore keystore = KeyStore.getInstance("jks"); keystore.load(url.openStream(), "secret".toCharArray()); KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, "secret".toCharArray()); KeyManager[] keymanagers = kmfactory.getKeyManagers(); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(keymanagers, null, null); sf = sslcontext.getServerSocketFactory(); } Thread t = new RequestListenerThread(port, httpService, sf); t.setDaemon(false); t.start(); }
From source file:com.bfd.job.testClient.t04.ElementalHttpServer.java
public static void main(String[] args) throws Exception { /**/*from ww w . j ava 2 s. co m*/ * if (args.length < 1) { * System.err.println("Please specify document root directory"); * System.exit(1); } // Document root directory String docRoot = * args[0]; */ String docRoot = "c:/root"; int port = 8080; if (args.length >= 2) { port = Integer.parseInt(args[1]); } // Set up the HTTP protocol processor HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate()) .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl()) .build(); // Set up request handlers UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); reqistry.register("*", new HttpFileHandler(docRoot)); // Set up the HTTP service HttpService httpService = new HttpService(httpproc, reqistry); SSLServerSocketFactory sf = null; if (port == 8443) { // Initialize SSL context ClassLoader cl = ElementalHttpServer.class.getClassLoader(); URL url = cl.getResource("my.keystore"); if (url == null) { System.out.println("Keystore not found"); System.exit(1); } KeyStore keystore = KeyStore.getInstance("jks"); keystore.load(url.openStream(), "secret".toCharArray()); KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, "secret".toCharArray()); KeyManager[] keymanagers = kmfactory.getKeyManagers(); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(keymanagers, null, null); sf = sslcontext.getServerSocketFactory(); } Thread t = new RequestListenerThread(port, httpService, sf); t.setDaemon(false); t.start(); }
From source file:httpserver.ElementalHttpServer.java
public static void main(String[] args) throws Exception { // Clay code, adding arguments to simulate command line execution args = new String[2]; args[0] = "C://Users/Clay/Documents"; args[1] = "80"; if (args.length < 1) { System.err.println("Please specify document root directory"); System.exit(1);/*from ww w. j a v a 2 s.com*/ } // Document root directory String docRoot = args[0]; // Setting up port, if port was specified, then use that one int port = 8080; if (args.length >= 2) { port = Integer.parseInt(args[1]); } // Set up the HTTP protocol processor HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate()) .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl()) .build(); // Set up request handlers UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); reqistry.register("*", new HttpFileHandler(docRoot)); // Set up the HTTP service HttpService httpService = new HttpService(httpproc, reqistry); SSLServerSocketFactory sf = null; if (port == 8443) { // Initialize SSL context ClassLoader cl = ElementalHttpServer.class.getClassLoader(); URL url = cl.getResource("my.keystore"); if (url == null) { System.out.println("Keystore not found"); System.exit(1); } KeyStore keystore = KeyStore.getInstance("jks"); keystore.load(url.openStream(), "secret".toCharArray()); KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, "secret".toCharArray()); KeyManager[] keymanagers = kmfactory.getKeyManagers(); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(keymanagers, null, null); sf = sslcontext.getServerSocketFactory(); } Thread t = new RequestListenerThread(port, httpService, sf); t.setDaemon(false); t.start(); }
From source file:za.co.taung.httpdotserver.main.HttpDotServer.java
public static void main(String[] args) throws Exception { LOG.info("Initialise server"); // The parameter is the Port to listen on. Default is 8080. int port = 8080; if (args.length >= 1) { port = Integer.parseInt(args[0]); }// w w w.j a v a 2s . c o m // Set up the HTTP protocol processor. HttpProcessor httpProcessor = HttpProcessorBuilder.create().add(new ResponseDate()) .add(new ResponseServer("HttpDotServer/1.1")).add(new ResponseContent()) .add(new ResponseConnControl()).build(); // Set up request handler. This is the method that generates SVG. UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); reqistry.register("*", new Dot2SVGHandler()); // Set up the HTTP service. HttpService httpService = new HttpService(httpProcessor, reqistry); // Set up SSL if listening on 8443 for https. SSLServerSocketFactory serverSocketFactory = null; if (port == 8443) { // Get the location of the keystore secrets. ClassLoader cl = HttpDotServer.class.getClassLoader(); URL url = cl.getResource("my.keystore"); if (url == null) { LOG.error("Keystore not found"); System.exit(1); } // Load the secret into a keystore and manage the key material. KeyStore keystore = KeyStore.getInstance("jks"); keystore.load(url.openStream(), "secret".toCharArray()); KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, "secret".toCharArray()); KeyManager[] keymanagers = kmfactory.getKeyManagers(); // Prepare the socket factory for use by the RequestListenerThread. SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(keymanagers, null, null); serverSocketFactory = sslcontext.getServerSocketFactory(); } LOG.debug("Start the RequestListenerThread"); Thread thread = new RequestListenerThread(port, httpService, serverSocketFactory); thread.setDaemon(false); thread.start(); }
From source file:org.acme.insurance.policyquote.test.WorkServiceMain.java
public static void main(String... args) throws Exception { serverHostname = System.getProperty("serverHostname", serverHostname); Set<String> policies = new HashSet<String>(); for (String arg : args) { arg = Strings.trimToNull(arg);/* w ww. j av a 2s . co m*/ if (arg != null) { if (arg.equals(CONFIDENTIALITY) || arg.equals(CLIENT_AUTHENTICATION) || arg.equals(HELP)) { policies.add(arg); } else { LOGGER.error(MAVEN_USAGE); throw new Exception(MAVEN_USAGE); } } } if (policies.contains(HELP)) { LOGGER.info(MAVEN_USAGE); } else { final String scheme; final int port; if (policies.contains(CONFIDENTIALITY)) { LOGGER.info("Invoking service via SSL..."); scheme = "https"; port = 443; SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, null, null); SSLSocketFactory sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); Scheme https = new Scheme(scheme, port, sf); SchemeRegistry sr = new SchemeRegistry(); sr.register(https); } else { scheme = "http"; port = 8080; } Element assertion = policies.contains(CLIENT_AUTHENTICATION) ? getAssertion() : null; invokeWorkService(scheme, port, assertion); } }
From source file:proxy.NHttpServer.java
public static void main(String[] args) throws Exception { if (args.length < 1) { System.err.println("Please specify document root directory"); System.exit(1);//from www .jav a2 s .c o m } // Document root directory File docRoot = new File(args[0]); int port = 8080; if (args.length >= 2) { port = Integer.parseInt(args[1]); } // Create HTTP protocol processing chain HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate()) .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl()) .build(); // Create request handler registry UriHttpAsyncRequestHandlerMapper reqistry = new UriHttpAsyncRequestHandlerMapper(); // Register the default handler for all URIs reqistry.register("*", new HttpFileHandler(docRoot)); // Create server-side HTTP protocol handler HttpAsyncService protocolHandler = new HttpAsyncService(httpproc, reqistry) { @Override public void connected(final NHttpServerConnection conn) { System.out.println(conn + ": connection open"); super.connected(conn); } @Override public void closed(final NHttpServerConnection conn) { System.out.println(conn + ": connection closed"); super.closed(conn); } }; // Create HTTP connection factory NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory; if (port == 8443) { // Initialize SSL context ClassLoader cl = NHttpServer.class.getClassLoader(); URL url = cl.getResource("my.keystore"); if (url == null) { System.out.println("Keystore not found"); System.exit(1); } KeyStore keystore = KeyStore.getInstance("jks"); keystore.load(url.openStream(), "secret".toCharArray()); KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, "secret".toCharArray()); KeyManager[] keymanagers = kmfactory.getKeyManagers(); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(keymanagers, null, null); connFactory = new SSLNHttpServerConnectionFactory(sslcontext, null, ConnectionConfig.DEFAULT); } else { connFactory = new DefaultNHttpServerConnectionFactory(ConnectionConfig.DEFAULT); } // Create server-side I/O event dispatch IOEventDispatch ioEventDispatch = new DefaultHttpServerIODispatch(protocolHandler, connFactory); // Set I/O reactor defaults IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(1).setSoTimeout(3000) .setConnectTimeout(3000).build(); // Create server-side I/O reactor ListeningIOReactor ioReactor = new DefaultListeningIOReactor(config); try { // Listen of the given port ioReactor.listen(new InetSocketAddress(port)); // Ready to go! ioReactor.execute(ioEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); } System.out.println("Shutdown"); }
From source file:net.sf.jsignpdf.InstallCert.java
/** * The main - whole logic of Install Cert Tool. * /*from w w w .ja v a 2s .c om*/ * @param args * @throws Exception */ public static void main(String[] args) { String host; int port; char[] passphrase; System.out.println("InstallCert - Install CA certificate to Java Keystore"); System.out.println("====================================================="); final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { if ((args.length == 1) || (args.length == 2)) { String[] c = args[0].split(":"); host = c[0]; port = (c.length == 1) ? 443 : Integer.parseInt(c[1]); String p = (args.length == 1) ? "changeit" : args[1]; passphrase = p.toCharArray(); } else { String tmpStr; do { System.out.print("Enter hostname or IP address: "); tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null); } while (tmpStr == null); host = tmpStr; System.out.print("Enter port number [443]: "); tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null); port = tmpStr == null ? 443 : Integer.parseInt(tmpStr); System.out.print("Enter keystore password [changeit]: "); tmpStr = reader.readLine(); String p = "".equals(tmpStr) ? "changeit" : tmpStr; passphrase = p.toCharArray(); } char SEP = File.separatorChar; final File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security"); final File file = new File(dir, "cacerts"); System.out.println("Loading KeyStore " + file + "..."); InputStream in = new FileInputStream(file); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, passphrase); in.close(); SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[] { tm }, null); SSLSocketFactory factory = context.getSocketFactory(); System.out.println("Opening connection to " + host + ":" + port + "..."); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); try { System.out.println("Starting SSL handshake..."); socket.startHandshake(); socket.close(); System.out.println(); System.out.println("No errors, certificate is already trusted"); } catch (SSLException e) { System.out.println(); System.out.println("Certificate is not yet trusted."); // e.printStackTrace(System.out); } X509Certificate[] chain = tm.chain; if (chain == null) { System.out.println("Could not obtain server certificate chain"); return; } System.out.println(); System.out.println("Server sent " + chain.length + " certificate(s):"); System.out.println(); MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN()); System.out.println(" Issuer " + cert.getIssuerDN()); sha1.update(cert.getEncoded()); System.out.println(" sha1 " + toHexString(sha1.digest())); md5.update(cert.getEncoded()); System.out.println(" md5 " + toHexString(md5.digest())); System.out.println(); } System.out.print("Enter certificate to add to trusted keystore or 'q' to quit [1]: "); String line = reader.readLine().trim(); int k = -1; try { k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1; } catch (NumberFormatException e) { } if (k < 0 || k >= chain.length) { System.out.println("KeyStore not changed"); } else { try { System.out.println("Creating keystore backup"); final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); final File backupFile = new File(dir, CACERTS_KEYSTORE + "." + dateFormat.format(new java.util.Date())); final FileInputStream fis = new FileInputStream(file); final FileOutputStream fos = new FileOutputStream(backupFile); IOUtils.copy(fis, fos); fis.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("Installing certificate..."); X509Certificate cert = chain[k]; String alias = host + "-" + (k + 1); ks.setCertificateEntry(alias, cert); OutputStream out = new FileOutputStream(file); ks.store(out, passphrase); out.close(); System.out.println(); System.out.println(cert); System.out.println(); System.out.println("Added certificate to keystore '" + file + "' using alias '" + alias + "'"); } } catch (Exception e) { System.out.println(); System.out.println("----------------------------------------------"); System.out.println("Problem occured during installing certificate:"); e.printStackTrace(); System.out.println("----------------------------------------------"); } System.out.println("Press Enter to finish..."); try { reader.readLine(); } catch (IOException e) { e.printStackTrace(); } }
From source file:at.peppol.smp.client.console.SMPClient.java
public static void main(final String[] args) throws Exception { if (false) {//www. j a v a 2 s. c om // Enable this section in development mode, if you want to trust all HTTPS // certificates final SSLContext aSSLContext = SSLContext.getInstance("SSL"); aSSLContext.init(null, new TrustManager[] { new DoNothingTrustManager() }, VerySecureRandom.getInstance()); HttpsURLConnection.setDefaultSSLSocketFactory(aSSLContext.getSocketFactory()); } final SMPClientOptions aOptions = new SMPClientOptions(); final CommandLine cmd = new PosixParser().parse(aOptions, args); ECommand eAction = null; boolean bGoodCmd = true; String cert = null; if (!cmd.hasOption("h")) { s_aLogger.error("No Host specified use -h to specify Host"); bGoodCmd = false; } if (!cmd.hasOption("u")) { s_aLogger.error("No Username specified use -u to specify username"); bGoodCmd = false; } if (!cmd.hasOption("p")) { s_aLogger.error("No Password specified use -p to specify password"); bGoodCmd = false; } if (!cmd.hasOption("c")) { s_aLogger.error("No Action specified please use -c parameter to specify command(" + ECommand.getAllAsString() + ")"); bGoodCmd = false; } else { final String sCommand = cmd.getOptionValue("c"); eAction = ECommand.getFromNameOrNull(sCommand); if (eAction == null) { s_aLogger.error("Illegal Action specified:" + sCommand + " allowed commands(" + ECommand.getAllAsString() + ")"); bGoodCmd = false; } else switch (eAction) { case ADDGROUP: if (!cmd.hasOption("b")) { s_aLogger.error( "No Business/Participant ID specified use -b to specify Business/Participant ID"); bGoodCmd = false; } break; case DELGROUP: if (!cmd.hasOption("b")) { s_aLogger.error( "No Business/Participant ID specified use -b to specify Business/Participant ID"); bGoodCmd = false; } break; case ADD: if (!cmd.hasOption("a")) { s_aLogger.error("No Accesspoint URL defined use -a to Specifify AP-URL"); bGoodCmd = false; } if (!cmd.hasOption("b")) { s_aLogger.error( "No Business/Participant ID specified use -b to specify Business/Participant ID"); bGoodCmd = false; } if (!cmd.hasOption("d")) { s_aLogger.error("No DocumentType ID specified use -d to specify Document Type ID"); bGoodCmd = false; } if (!cmd.hasOption("r")) { s_aLogger.error("No Process ID specified use -r to specify Process ID"); bGoodCmd = false; } if (!cmd.hasOption("e")) { s_aLogger.error("No Certificate PEM file specified use -e to specify Certificate PEM file"); bGoodCmd = false; } else { cert = SimpleFileIO.readFileAsString(new File(cmd.getOptionValue('e')), CCharset.CHARSET_ISO_8859_1); } break; case DEL: if (!cmd.hasOption("b")) { s_aLogger.error( "No Business/Participant ID specified use -b to specify Business/Participant ID"); bGoodCmd = false; } if (!cmd.hasOption("d")) { s_aLogger.error("No Document Type ID specified use -d to specify Document Type ID"); bGoodCmd = false; } } } if (!bGoodCmd) { final NonBlockingStringWriter aSW = new NonBlockingStringWriter(); new HelpFormatter().printHelp(new PrintWriter(aSW), HelpFormatter.DEFAULT_WIDTH, CGStringHelper.getClassLocalName(SMPClient.class), null, aOptions, HelpFormatter.DEFAULT_LEFT_PAD, HelpFormatter.DEFAULT_DESC_PAD, null); s_aLogger.info(aSW.getAsString()); System.exit(-3); } final SMPClient client = new SMPClient(new URI(cmd.getOptionValue('h')), cmd.getOptionValue('u'), cmd.getOptionValue('p'), cmd.getOptionValue('b'), cmd.getOptionValue('d'), cmd.getOptionValue('r'), cmd.getOptionValue('a'), cert); switch (eAction) { case ADDGROUP: client._createServiceGroup(); break; case DELGROUP: client._deleteServiceGroup(); break; case ADD: client._addDocument(); break; case DEL: client._deleteDocument(); break; case LIST: client._listDocuments(); break; default: throw new IllegalStateException(); } }
From source file:com.vmware.photon.controller.core.Main.java
public static void main(String[] args) throws Throwable { try {//w w w. j av a 2 s. c o m LoggingFactory.bootstrap(); logger.info("args: " + Arrays.toString(args)); ArgumentParser parser = ArgumentParsers.newArgumentParser("PhotonControllerCore").defaultHelp(true) .description("Photon Controller Core"); parser.addArgument("config-file").help("photon controller configuration file"); parser.addArgument("--manual").type(Boolean.class).setDefault(false) .help("If true, create default deployment."); Namespace namespace = parser.parseArgsOrFail(args); PhotonControllerConfig photonControllerConfig = getPhotonControllerConfig(namespace); DeployerConfig deployerConfig = photonControllerConfig.getDeployerConfig(); new LoggingFactory(photonControllerConfig.getLogging(), "photon-controller-core").configure(); SSLContext sslContext; if (deployerConfig.getDeployerContext().isAuthEnabled()) { sslContext = SSLContext.getInstance(KeyStoreUtils.THRIFT_PROTOCOL); TrustManagerFactory tmf = null; tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore keyStore = KeyStore.getInstance("JKS"); InputStream in = FileUtils .openInputStream(new File(deployerConfig.getDeployerContext().getKeyStorePath())); keyStore.load(in, deployerConfig.getDeployerContext().getKeyStorePassword().toCharArray()); tmf.init(keyStore); sslContext.init(null, tmf.getTrustManagers(), null); } else { KeyStoreUtils.generateKeys("/thrift/"); sslContext = KeyStoreUtils.acceptAllCerts(KeyStoreUtils.THRIFT_PROTOCOL); } ThriftModule thriftModule = new ThriftModule(sslContext); PhotonControllerXenonHost xenonHost = startXenonHost(photonControllerConfig, thriftModule, deployerConfig, sslContext); if ((Boolean) namespace.get("manual")) { DefaultDeployment.createDefaultDeployment(photonControllerConfig.getXenonConfig().getPeerNodes(), deployerConfig, xenonHost); } // Creating a temp configuration file for apife with modification to some named sections in photon-controller-config // so that it can match the Configuration class of dropwizard. File apiFeTempConfig = File.createTempFile("apiFeTempConfig", ".tmp"); File source = new File(args[0]); FileInputStream fis = new FileInputStream(source); BufferedReader in = new BufferedReader(new InputStreamReader(fis)); FileWriter fstream = new FileWriter(apiFeTempConfig, true); BufferedWriter out = new BufferedWriter(fstream); String aLine = null; while ((aLine = in.readLine()) != null) { if (aLine.equals("apife:")) { aLine = aLine.replace("apife:", "server:"); } out.write(aLine); out.newLine(); } in.close(); out.close(); // This approach can be simplified once the apife container is gone, but for the time being // it expects the first arg to be the string "server". String[] apiFeArgs = new String[2]; apiFeArgs[0] = "server"; apiFeArgs[1] = apiFeTempConfig.getAbsolutePath(); ApiFeService.setupApiFeConfigurationForServerCommand(apiFeArgs); ApiFeService.addServiceHost(xenonHost); ApiFeService.setSSLContext(sslContext); ApiFeService apiFeService = new ApiFeService(); apiFeService.run(apiFeArgs); apiFeTempConfig.deleteOnExit(); LocalApiClient localApiClient = apiFeService.getInjector().getInstance(LocalApiClient.class); xenonHost.setApiClient(localApiClient); // in the non-auth enabled scenario we need to be able to accept any self-signed certificate if (!deployerConfig.getDeployerContext().isAuthEnabled()) { KeyStoreUtils.acceptAllCerts(KeyStoreUtils.THRIFT_PROTOCOL); } Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { logger.info("Shutting down"); xenonHost.stop(); logger.info("Done"); LoggingFactory.detachAndStop(); } }); } catch (Exception e) { logger.error("Failed to start photon controller ", e); throw e; } }
From source file:yucatan.communication.server.NHttpServer.java
public static void main(String[] args) throws Exception { if (args.length < 1) { System.err.println("Please specify document root directory"); System.exit(1);//from w w w .ja v a 2s . co m } // Document root directory File docRoot = new File(args[0]); int port = 8080; if (args.length >= 2) { port = Integer.parseInt(args[1]); } // HTTP parameters for the server HttpParams params = new SyncBasicHttpParams(); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpTest/1.1"); // Create HTTP protocol processing chain HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { // Use standard server-side protocol interceptors new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); // Create request handler registry HttpAsyncRequestHandlerRegistry reqistry = new HttpAsyncRequestHandlerRegistry(); // Register the default handler for all URIs reqistry.register("*", new HttpFileHandler(docRoot)); // Create server-side HTTP protocol handler HttpAsyncService protocolHandler = new HttpAsyncService(httpproc, new DefaultConnectionReuseStrategy(), reqistry, params) { @Override public void connected(final NHttpServerConnection conn) { System.out.println(conn + ": connection open"); super.connected(conn); } @Override public void closed(final NHttpServerConnection conn) { System.out.println(conn + ": connection closed"); super.closed(conn); } }; // Create HTTP connection factory NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory; if (port == 8443) { // Initialize SSL context ClassLoader cl = NHttpServer.class.getClassLoader(); URL url = cl.getResource("my.keystore"); if (url == null) { System.out.println("Keystore not found"); System.exit(1); } KeyStore keystore = KeyStore.getInstance("jks"); keystore.load(url.openStream(), "secret".toCharArray()); KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, "secret".toCharArray()); KeyManager[] keymanagers = kmfactory.getKeyManagers(); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(keymanagers, null, null); connFactory = new SSLNHttpServerConnectionFactory(sslcontext, null, params); } else { connFactory = new DefaultNHttpServerConnectionFactory(params); } // Create server-side I/O event dispatch IOEventDispatch ioEventDispatch = new DefaultHttpServerIODispatch(protocolHandler, connFactory); // Create server-side I/O reactor ListeningIOReactor ioReactor = new DefaultListeningIOReactor(); try { // Listen of the given port ioReactor.listen(new InetSocketAddress(port)); // Ready to go! ioReactor.execute(ioEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); } System.out.println("Shutdown"); }