blob: e3a9686a8652019c956d2aab2704bcbf135ceb80 [file] [log] [blame]
chrismair00dc7bd2014-05-11 21:21:28 +00001/*
2 * Copyright 2007 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 */
16package org.mockftpserver.core.socket;
17
18import java.io.IOException;
19import java.net.ServerSocket;
20import java.net.Socket;
21import java.net.SocketTimeoutException;
22
23/**
24 * Test (fake) subclass of ServerSocket that performs no network access and allows setting the
25 * Socket returned by accept(), and the local port for the ServerSocket.
26 *
27 * @version $Revision$ - $Date$
28 *
29 * @author Chris Mair
30 */
31public class StubServerSocket extends ServerSocket {
32 private int localPort;
33 private Socket socket;
34
35 /**
36 * Construct a new instance with the specified local port.
37 * @param localPort - the local port to be returned from getLocalPort()
38 * @throws IOException
39 */
40 public StubServerSocket(int localPort) throws IOException {
41 this(localPort, null);
42 }
43
44 /**
45 * Construct a new instance with specified local port and accept() socket.
46 * @param localPort - the local port to be returned from getLocalPort()
47 * @param socket - the socket to be returned from accept(); if null, then accept() throws SocketTimeoutException.
48 * @throws IOException
49 */
50 public StubServerSocket(int localPort, Socket socket) throws IOException {
51 super(0);
52 this.localPort = localPort;
53 this.socket = socket;
54 }
55
56 /**
57 * Return the predefined local port
58 * @see java.net.ServerSocket#getLocalPort()
59 */
60 public int getLocalPort() {
61 return localPort;
62 }
63
64 /**
65 * If a socket was specified on the constructor, then return that; otherwise, throw a SocketTimeoutException.
66 * @see java.net.ServerSocket#accept()
67 */
68 public Socket accept() throws IOException {
69 if (socket != null) {
70 return socket;
71 }
72 throw new SocketTimeoutException();
73 }
74}