1 /*
2 * Copyright 2009 the original author or authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.openehealth.ipf.platform.camel.ihe.mllp.core;
17
18
19 import org.apache.mina.core.filterchain.IoFilter;
20 import org.apache.mina.core.session.IoSession;
21 import org.apache.mina.filter.ssl.SslFilter;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
24
25 import javax.net.ssl.SSLContext;
26 import javax.net.ssl.SSLException;
27 import javax.net.ssl.SSLHandshakeException;
28
29 /**
30 * {@link IoFilter} similar to an {@link SslFilter} that provides a
31 * callbacks to handle a handshake exception.
32 */
33 public class HandshakeCallbackSSLFilter extends SslFilter {
34
35 private static final Logger LOGGER = LoggerFactory.getLogger(HandshakeCallbackSSLFilter.class);
36
37 /**
38 * Callback interface for dealing with handshake failures.
39 */
40 public interface Callback {
41 /**
42 * Runs the callback.
43 * @param session
44 * the session in which the handshake failure occurred.
45 */
46 void run(IoSession session, String message);
47 }
48
49 private Callback handshakeExceptionCallback;
50
51 /** Creates a new SSL filter using the specified {@link SSLContext}.
52 * @param sslContext
53 * the context.
54 */
55 public HandshakeCallbackSSLFilter(SSLContext sslContext) {
56 super(sslContext);
57 }
58
59 /**
60 * Sets the callback used if a failure occurred while receiving a handshake.
61 * @param handshakeExceptionCallback
62 * the callback to use.
63 */
64 public void setHandshakeExceptionCallback(Callback handshakeExceptionCallback) {
65 this.handshakeExceptionCallback = handshakeExceptionCallback;
66 }
67
68 @Override
69 public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws SSLException {
70 try {
71 super.messageReceived(nextFilter, session, message);
72 } catch (SSLHandshakeException e) {
73 handshakeExceptionCallback.run(session, e.getMessage());
74 try {
75 exceptionCaught(nextFilter, session, e.getCause());
76 } catch (Exception e1) {
77 LOGGER.warn("SSLHandshakeException {} on Session: {}", e, session);
78 }
79 }
80 }
81 }