001/*-------------------------------------------------------------------------+
002|                                                                          |
003| Copyright 2005-2011 The ConQAT Project                                   |
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+-------------------------------------------------------------------------*/
017package org.conqat.lib.commons.net;
018
019import java.io.IOException;
020import java.net.ServerSocket;
021import java.net.Socket;
022import java.rmi.server.RMISocketFactory;
023
024/**
025 * A {@link RMISocketFactory} that adjusts flags on the sockets used. One is
026 * that for the server socket the reuse flag is set, which allows fast
027 * reopening. Second, an optional timeout can be set.
028 * 
029 * @author hummelb
030 */
031public class SmartRMISocketFactory extends RMISocketFactory {
032
033        /** Timeout in seconds. */
034        private final int timeoutSeconds;
035
036        /** Constructor. No timeout is set. */
037        public SmartRMISocketFactory() {
038                this(-1);
039        }
040
041        /** Constructor */
042        public SmartRMISocketFactory(int timeoutSeconds) {
043                this.timeoutSeconds = timeoutSeconds;
044        }
045
046        /** {@inheritDoc} */
047        @Override
048        public Socket createSocket(String host, int port) throws IOException {
049                Socket socket = getDefaultSocketFactory().createSocket(host, port);
050                if (timeoutSeconds > 0) {
051                        socket.setSoTimeout(timeoutSeconds * 1000);
052                }
053                return socket;
054        }
055
056        /** {@inheritDoc} */
057        @Override
058        public ServerSocket createServerSocket(int port) throws IOException {
059                ServerSocket socket = getDefaultSocketFactory().createServerSocket(port);
060                socket.setReuseAddress(true);
061                return socket;
062        }
063}