001 /** 002 * Copyright (C) 2012 FuseSource, Inc. 003 * http://fusesource.com 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); 006 * you may not use this file except in compliance with the License. 007 * You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 018 package org.fusesource.hawtdispatch.transport; 019 020 import org.fusesource.hawtdispatch.Task; 021 022 import javax.net.ssl.KeyManager; 023 import javax.net.ssl.SSLContext; 024 import javax.net.ssl.TrustManager; 025 import java.net.URI; 026 import java.net.UnknownHostException; 027 import java.util.concurrent.Executor; 028 import java.security.NoSuchAlgorithmException; 029 030 /** 031 * @author <a href="http://hiramchirino.com">Hiram Chirino</a> 032 */ 033 034 public class SslTransportServer extends TcpTransportServer { 035 036 public static SslTransportServer createTransportServer(URI uri) throws Exception { 037 return new SslTransportServer(uri); 038 } 039 040 protected KeyManager[] keyManagers; 041 private TrustManager[] trustManagers; 042 protected String protocol = "TLS"; 043 protected SSLContext sslContext; 044 private String clientAuth = "want"; 045 046 public SslTransportServer(URI location) throws Exception { 047 super(location); 048 setSSLContext(SSLContext.getInstance(SslTransport.protocol(location.getScheme()))); 049 } 050 051 public void setKeyManagers(KeyManager[] keyManagers) { 052 this.keyManagers = keyManagers; 053 } 054 public void setTrustManagers(TrustManager[] trustManagers) { 055 this.trustManagers = trustManagers; 056 } 057 058 public void start(Task onCompleted) throws Exception { 059 if( keyManagers!=null ) { 060 sslContext.init(keyManagers, trustManagers, null); 061 } else { 062 sslContext = SSLContext.getDefault(); 063 } 064 super.start(onCompleted); 065 } 066 067 protected TcpTransport createTransport() { 068 SslTransport rc = new SslTransport(); 069 rc.setDispatchQueue(dispatchQueue); 070 rc.setBlockingExecutor(blockingExecutor); 071 rc.setSSLContext(sslContext); 072 rc.setClientAuth(clientAuth); 073 return rc; 074 } 075 076 public SslTransportServer protocol(String value) throws NoSuchAlgorithmException { 077 this.protocol = value; 078 sslContext = SSLContext.getInstance(protocol); 079 return this; 080 } 081 082 public SSLContext getSSLContext() { 083 return sslContext; 084 } 085 086 public void setSSLContext(SSLContext sslContext) { 087 this.sslContext = sslContext; 088 } 089 090 public String getClientAuth() { 091 return clientAuth; 092 } 093 094 public void setClientAuth(String clientAuth) { 095 this.clientAuth = clientAuth; 096 } 097 098 }