001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.core.net.server;
015
016import java.io.IOException;
017import java.net.ServerSocket;
018import java.net.Socket;
019import java.net.SocketAddress;
020
021import ch.qos.logback.core.util.CloseUtil;
022
023/**
024 * A {@link ServerListener} that accepts connections on a {@link ServerSocket}.
025 *
026 * @author Carl Harris
027 */
028public abstract class ServerSocketListener<T extends Client> implements ServerListener<T> {
029
030    private final ServerSocket serverSocket;
031
032    /**
033     * Constructs a new listener.
034     * 
035     * @param serverSocket server socket delegate
036     */
037    public ServerSocketListener(ServerSocket serverSocket) {
038        this.serverSocket = serverSocket;
039    }
040
041    /**
042     * {@inheritDoc}
043     */
044    public T acceptClient() throws IOException {
045        Socket socket = serverSocket.accept();
046        return createClient(socketAddressToString(socket.getRemoteSocketAddress()), socket);
047    }
048
049    /**
050     * Creates the client object for a new socket connection
051     * 
052     * @param id     identifier string for the client
053     * @param socket client's socket connection
054     * @return client object
055     * @throws IOException
056     */
057    protected abstract T createClient(String id, Socket socket) throws IOException;
058
059    /**
060     * {@inheritDoc}
061     */
062    public void close() {
063        CloseUtil.closeQuietly(serverSocket);
064    }
065
066    /**
067     * {@inheritDoc}
068     */
069    @Override
070    public String toString() {
071        return socketAddressToString(serverSocket.getLocalSocketAddress());
072    }
073
074    /**
075     * Converts a socket address to a reasonable display string.
076     * 
077     * @param address the subject socket address
078     * @return display string
079     */
080    private String socketAddressToString(SocketAddress address) {
081        String addr = address.toString();
082        int i = addr.indexOf("/");
083        if (i >= 0) {
084            addr = addr.substring(i + 1);
085        }
086        return addr;
087    }
088
089}