1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.example.echoserver.ssl;
21
22 import java.io.IOException;
23 import java.net.InetAddress;
24 import java.net.Socket;
25 import java.net.UnknownHostException;
26 import java.security.GeneralSecurityException;
27
28 import javax.net.SocketFactory;
29
30
31
32
33
34
35
36 public class SslSocketFactory extends SocketFactory {
37 private static boolean sslEnabled = false;
38
39 private static javax.net.ssl.SSLSocketFactory sslFactory = null;
40
41 private static javax.net.SocketFactory factory = null;
42
43 public SslSocketFactory() {
44 super();
45 }
46
47 @Override
48 public Socket createSocket(String arg1, int arg2) throws IOException,
49 UnknownHostException {
50 if (isSslEnabled()) {
51 return getSSLFactory().createSocket(arg1, arg2);
52 } else {
53 return new Socket(arg1, arg2);
54 }
55 }
56
57 @Override
58 public Socket createSocket(String arg1, int arg2, InetAddress arg3, int arg4)
59 throws IOException, UnknownHostException {
60 if (isSslEnabled()) {
61 return getSSLFactory().createSocket(arg1, arg2, arg3, arg4);
62 } else {
63 return new Socket(arg1, arg2, arg3, arg4);
64 }
65 }
66
67 @Override
68 public Socket createSocket(InetAddress arg1, int arg2) throws IOException {
69 if (isSslEnabled()) {
70 return getSSLFactory().createSocket(arg1, arg2);
71 } else {
72 return new Socket(arg1, arg2);
73 }
74 }
75
76 @Override
77 public Socket createSocket(InetAddress arg1, int arg2, InetAddress arg3,
78 int arg4) throws IOException {
79 if (isSslEnabled()) {
80 return getSSLFactory().createSocket(arg1, arg2, arg3, arg4);
81 } else {
82 return new Socket(arg1, arg2, arg3, arg4);
83 }
84 }
85
86 public static javax.net.SocketFactory getSocketFactory() {
87 if (factory == null) {
88 factory = new SslSocketFactory();
89 }
90 return factory;
91 }
92
93 private javax.net.ssl.SSLSocketFactory getSSLFactory() {
94 if (sslFactory == null) {
95 try {
96 sslFactory = BogusSslContextFactory.getInstance(false)
97 .getSocketFactory();
98 } catch (GeneralSecurityException e) {
99 throw new RuntimeException("could not create SSL socket", e);
100 }
101 }
102 return sslFactory;
103 }
104
105 public static boolean isSslEnabled() {
106 return sslEnabled;
107 }
108
109 public static void setSslEnabled(boolean newSslEnabled) {
110 sslEnabled = newSslEnabled;
111 }
112
113 }