Example usage for java.net Socket getLocalPort

List of usage examples for java.net Socket getLocalPort

Introduction

In this page you can find the example usage for java.net Socket getLocalPort.

Prototype

public int getLocalPort() 

Source Link

Document

Returns the local port number to which this socket is bound.

Usage

From source file:com.packetsender.android.PacketListenerService.java

@Override
protected void onHandleIntent(Intent intent) {

    dataStore = new DataStorage(getSharedPreferences(DataStorage.PREFS_SETTINGS_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_SAVEDPACKETS_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_SERVICELOG_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_MAINTRAFFICLOG_NAME, 0));

    listenportTCP = dataStore.getTCPPort();
    listenportUDP = dataStore.getUDPPort();
    Log.i("service", DataStorage.FILE_LINE("TCP: " + listenportTCP + " / UDP: " + listenportUDP));

    Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);

    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);

    startNotification();/*from   w  w  w  . j  a v  a  2s . c  o m*/

    CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder();
    ByteBuffer response = null;
    try {
        response = encoder.encode(CharBuffer.wrap("response"));
    } catch (CharacterCodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {

        SocketAddress localportTCP = new InetSocketAddress(listenportTCP);
        SocketAddress localportUDP = new InetSocketAddress(listenportUDP);

        tcpserver = ServerSocketChannel.open();
        tcpserver.socket().bind(localportTCP);

        udpserver = DatagramChannel.open();
        udpserver.socket().bind(localportUDP);

        tcpserver.configureBlocking(false);
        udpserver.configureBlocking(false);

        Selector selector = Selector.open();

        tcpserver.register(selector, SelectionKey.OP_ACCEPT);
        udpserver.register(selector, SelectionKey.OP_READ);

        ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);
        receiveBuffer.clear();

        shutdownListener = new Runnable() {
            public void run() {

                if (false) {

                    try {
                        tcpserver.close();
                    } catch (IOException e) {
                    }
                    try {
                        udpserver.close();
                    } catch (IOException e) {
                    }
                    stopSelf();
                } else {
                    mHandler.postDelayed(shutdownListener, 2000);

                }

            }
        };

        sendListener = new Runnable() {
            public void run() {

                //Packet fetchedPacket = mDbHelper.needSendPacket();
                Packet[] fetchedPackets = dataStore.fetchAllServicePackets();

                if (fetchedPackets.length > 0) {
                    dataStore.clearServicePackets();
                    Log.d("service",
                            DataStorage.FILE_LINE("sendListener found " + fetchedPackets.length + " packets"));

                    for (int i = 0; i < fetchedPackets.length; i++) {
                        Packet fetchedPacket = fetchedPackets[i];
                        Log.d("service", DataStorage.FILE_LINE("send packet " + fetchedPacket.toString()));

                    }

                    new SendPacketsTask().execute(fetchedPackets);
                }

                mHandler.postDelayed(sendListener, 2000);

            }
        };

        //start shutdown listener
        mHandler.postDelayed(shutdownListener, 2000);

        //start send listener
        mHandler.postDelayed(sendListener, 5000);

        while (true) {
            try { // Handle per-connection problems below
                  // Wait for a client to connect
                Log.d("service", DataStorage.FILE_LINE("waiting for connection"));
                selector.select();
                Log.d("service", DataStorage.FILE_LINE("client connection"));

                Set keys = selector.selectedKeys();

                for (Iterator i = keys.iterator(); i.hasNext();) {

                    SelectionKey key = (SelectionKey) i.next();
                    i.remove();

                    Channel c = (Channel) key.channel();

                    if (key.isAcceptable() && c == tcpserver) {

                        SocketChannel client = tcpserver.accept();

                        if (client != null) {

                            Socket tcpSocket = client.socket();
                            packetCounter++;

                            DataInputStream in = new DataInputStream(tcpSocket.getInputStream());

                            byte[] buffer = new byte[1024];
                            int received = in.read(buffer);
                            byte[] bufferConvert = new byte[received];
                            System.arraycopy(buffer, 0, bufferConvert, 0, bufferConvert.length);

                            Packet storepacket = new Packet();
                            storepacket.tcpOrUdp = "TCP";
                            storepacket.fromIP = tcpSocket.getInetAddress().getHostAddress();

                            storepacket.toIP = "You";
                            storepacket.fromPort = tcpSocket.getPort();
                            storepacket.port = tcpSocket.getLocalPort();
                            storepacket.data = bufferConvert;

                            UpdateNotification("TCP:" + storepacket.toAscii(), "From " + storepacket.fromIP);

                            Log.i("service", DataStorage.FILE_LINE("Got TCP"));
                            //dataStore.SavePacket(storepacket);

                            /*
                            Intent tcpIntent = new Intent();
                            tcpIntent.setAction(ResponseReceiver.ACTION_RESP);
                            tcpIntent.addCategory(Intent.CATEGORY_DEFAULT);
                            tcpIntent.putExtra(PARAM_OUT_MSG, storepacket.name);
                            sendBroadcast(tcpIntent);
                            */

                            storepacket.nowMe();
                            dataStore.saveTrafficPacket(storepacket);
                            Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            if (false) //mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).equalsIgnoreCase("Yes"))
                            {
                                storepacket = new Packet();
                                storepacket.name = dataStore.currentTimeStamp();
                                ;
                                storepacket.tcpOrUdp = "TCP";
                                storepacket.fromIP = "You";
                                storepacket.toIP = tcpSocket.getInetAddress().getHostAddress();
                                storepacket.fromPort = tcpSocket.getLocalPort();
                                storepacket.port = tcpSocket.getPort();
                                // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT));

                                storepacket.nowMe();
                                dataStore.saveTrafficPacket(storepacket);
                                Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                                client.write(response); // send response
                            }

                            client.close(); // close connection
                        }
                    } else if (key.isReadable() && c == udpserver) {

                        DatagramSocket udpSocket;
                        DatagramPacket udpPacket;

                        byte[] buffer = new byte[2048];
                        // Create a packet to receive data into the buffer
                        udpPacket = new DatagramPacket(buffer, buffer.length);

                        udpSocket = udpserver.socket();

                        receiveBuffer.clear();

                        InetSocketAddress clientAddress = (InetSocketAddress) udpserver.receive(receiveBuffer);

                        if (clientAddress != null) {

                            String fromAddress = clientAddress.getAddress().getHostAddress();

                            packetCounter++;

                            int received = receiveBuffer.position();
                            byte[] bufferConvert = new byte[received];

                            System.arraycopy(receiveBuffer.array(), 0, bufferConvert, 0, bufferConvert.length);

                            Packet storepacket = new Packet();
                            storepacket.tcpOrUdp = "UDP";
                            storepacket.fromIP = clientAddress.getAddress().getHostAddress();

                            storepacket.toIP = "You";
                            storepacket.fromPort = clientAddress.getPort();
                            storepacket.port = udpSocket.getLocalPort();
                            storepacket.data = bufferConvert;

                            UpdateNotification("UDP:" + storepacket.toAscii(), "From " + storepacket.fromIP);

                            //dataStore.SavePacket(storepacket);
                            storepacket.nowMe();
                            dataStore.saveTrafficPacket(storepacket);
                            Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            if (false)//mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).trim().equalsIgnoreCase("Yes"))
                            {
                                storepacket = new Packet();
                                storepacket.name = dataStore.currentTimeStamp();
                                ;
                                storepacket.tcpOrUdp = "UDP";
                                storepacket.fromIP = "You";
                                storepacket.toIP = clientAddress.getAddress().getHostAddress();
                                storepacket.fromPort = udpSocket.getLocalPort();
                                storepacket.port = clientAddress.getPort();
                                // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT));

                                //dataStore.SavePacket(storepacket);
                                udpserver.send(response, clientAddress);
                                storepacket.nowMe();
                                dataStore.saveTrafficPacket(storepacket);
                                Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            }
                        }
                    }
                }
            } catch (java.io.IOException e) {
                Log.i("service", DataStorage.FILE_LINE("IOException "));
            } catch (Exception e) {
                Log.w("service", DataStorage.FILE_LINE("Fatal Error: " + Log.getStackTraceString(e)));
            }
        }
    } catch (BindException e) {

        //mDbHelper.putServiceError("Error binding to port");
        dataStore.putToast("Port already in use.");
        Log.w("service", DataStorage.FILE_LINE("Bind Exception: " + Log.getStackTraceString(e)));

    } catch (Exception e) {
        //mDbHelper.putServiceError("Fatal Error starting service");
        Log.w("service", DataStorage.FILE_LINE("Startup error: " + Log.getStackTraceString(e)));
    }

    stopNotification();

}

From source file:org.echocat.jomon.net.dns.DnsServer.java

public void TCPclient(Socket s) {
    try {/*  w w w .  j  a va2  s. c o  m*/
        final int inLength;
        final DataInputStream dataIn;
        final DataOutputStream dataOut;
        final byte[] in;

        final InputStream is = s.getInputStream();
        dataIn = new DataInputStream(is);
        inLength = dataIn.readUnsignedShort();
        in = new byte[inLength];
        dataIn.readFully(in);

        final Message query;
        byte[] response;
        try {
            query = new Message(in);
            response = generateReply(query, in, in.length, s);
            if (response == null) {
                return;
            }
        } catch (final IOException ignored) {
            response = formerrMessage(in);
        }
        dataOut = new DataOutputStream(s.getOutputStream());
        dataOut.writeShort(response.length);
        dataOut.write(response);
    } catch (final IOException e) {
        LOG.warn("TCPclient(" + addrport(s.getLocalAddress(), s.getLocalPort()) + ").", e);
    } finally {
        try {
            s.close();
        } catch (final IOException ignored) {
        }
    }
}

From source file:Server.java

/**
 * This is the method that Listener objects call when they accept a
 * connection from a client. It either creates a Connection object for the
 * connection and adds it to the list of current connections, or, if the
 * limit on connections has been reached, it closes the connection.
 *///from  w  ww . j a v  a 2  s.co  m
protected synchronized void addConnection(Socket s, Service service) {
    // If the connection limit has been reached
    if (connections.size() >= maxConnections) {
        try {
            // Then tell the client it is being rejected.
            PrintWriter out = new PrintWriter(s.getOutputStream());
            out.print("Connection refused; " + "the server is busy; please try again later.\n");
            out.flush();
            // And close the connection to the rejected client.
            s.close();
            // And log it, of course
            log("Connection refused to " + s.getInetAddress().getHostAddress() + ":" + s.getPort()
                    + ": max connections reached.");
        } catch (IOException e) {
            log(e);
        }
    } else { // Otherwise, if the limit has not been reached
        // Create a Connection thread to handle this connection
        Connection c = new Connection(s, service);
        // Add it to the list of current connections
        connections.add(c);
        // Log this new connection
        log("Connected to " + s.getInetAddress().getHostAddress() + ":" + s.getPort() + " on port "
                + s.getLocalPort() + " for service " + service.getClass().getName());
        // And start the Connection thread to provide the service
        c.start();
    }
}

From source file:com.devoteam.srit.xmlloader.http.bio.BIOChannelHttp.java

/** Open a connexion to each Stack */
public boolean open() throws Exception {
    if (this.secure) {
        StatPool.beginStatisticProtocol(StatPool.CHANNEL_KEY, StatPool.BIO_KEY, StackFactory.PROTOCOL_TLS,
                StackFactory.PROTOCOL_HTTP);
    } else {//w w  w  .ja v  a  2s.  com
        StatPool.beginStatisticProtocol(StatPool.CHANNEL_KEY, StatPool.BIO_KEY, StackFactory.PROTOCOL_TCP,
                StackFactory.PROTOCOL_HTTP);
    }

    this.startTimestamp = System.currentTimeMillis();

    if (null != this.socketServerHttp) {
        ThreadPool.reserve().start((BIOSocketServerHttp) socketServerHttp);
    } else {

        String host = this.getRemoteHost();
        int port = this.getRemotePort();

        DefaultHttpClientConnection defaultHttpClientConnection = new DefaultHttpClientConnection();

        Socket socket;

        if (this.secure) {
            // Create a trust manager that does not validate certificate chains like the default TrustManager
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    //No need to implement.
                }

                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    //No need to implement.
                }
            } };

            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, null);

            socket = sslContext.getSocketFactory().createSocket();
            // read all properties for the TCP socket 
            Config.getConfigForTCPSocket(socket, true);
        } else {
            //
            // Create a TCP non secure socket
            //                
            socket = new Socket();
            // read all properties for the TCP socket 
            Config.getConfigForTCPSocket(socket, false);
        }

        //
        // Bind the socket to the local address
        //
        String localHost = this.getLocalHost();
        int localPort = initialLocalport;

        if (null != localHost) {
            socket.bind(new InetSocketAddress(localHost, localPort));
        } else {
            socket.bind(new InetSocketAddress(localPort));
        }

        socket.setReceiveBufferSize(65536);
        socket.connect(new InetSocketAddress(host, port));

        this.setLocalPort(socket.getLocalPort());

        HttpParams params = new BasicHttpParams();
        defaultHttpClientConnection.bind(socket, params);

        this.socketClientHttp = new BIOSocketClientHttp(defaultHttpClientConnection, this);

        ThreadPool.reserve().start((BIOSocketClientHttp) socketClientHttp);
    }
    return true;
}

From source file:ca.uhn.hunit.example.MllpHl7v2MessageSwapper.java

@Override
public void run() {
    Socket socket = null;//from   w w  w.  j a  va  2  s.c om

    try {
        if (myPrintOutput) {
            System.out.println("Opening server socket on port " + 10201);
        }

        ServerSocket serverSocket = new ServerSocket(10201);

        socket = serverSocket.accept();

        InputStream inputStream = socket.getInputStream();
        inputStream = new BufferedInputStream(inputStream);

        MinLLPReader minLLPReader = new MinLLPReader(inputStream);

        Socket outSocket = null;

        if (myPrintOutput) {
            System.out.println("Accepting connection from " + socket.getInetAddress().getHostAddress());
        }

        for (int i = 0; i < myIterations; i++) {
            String messageText;

            do {
                messageText = minLLPReader.getMessage();
                Thread.sleep(250);
            } while (messageText == null);

            if (myPrintOutput) {
                System.out.println("Received message:\r\n" + messageText + "\r\n");
            }

            MSH inboundHeader = (MSH) myParser.parse(messageText).get("MSH");
            String controlId = inboundHeader.getMessageControlID().encode();
            if (StringUtils.isNotBlank(controlId) && myControlIdsToIgnore.indexOf(controlId) > -1) {
                Message replyAck = DefaultApplication.makeACK(inboundHeader);
                new MinLLPWriter(socket.getOutputStream()).writeMessage(myParser.encode(replyAck));
            } else {
                System.out.println("Ignoring message with control ID " + controlId);
            }

            for (Map.Entry<String, String> next : mySubstitutions.entrySet()) {
                messageText = messageText.replace(next.getKey(), next.getValue());
            }

            if ((outSocket != null) && myAlwaysCreateNewOutboundConnection) {
                outSocket.close();
                outSocket = null;
            }

            if (outSocket == null) {
                if (myPrintOutput) {
                    System.out.println("Opening outbound connection to port " + 10200);
                }

                outSocket = new Socket();
                outSocket.connect(new InetSocketAddress("localhost", 10200));
            }

            if (myPrintOutput) {
                System.out.println("Sending message from port " + outSocket.getLocalPort() + ":\r\n"
                        + messageText + "\r\n");
            }

            new MinLLPWriter(outSocket.getOutputStream()).writeMessage(messageText);
            new MinLLPReader(outSocket.getInputStream()).getMessage();
        }

        serverSocket.close();
        socket.close();

        myStopped = true;

    } catch (Exception e) {
        myStopped = true;
        e.printStackTrace();
    }
}

From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java

/**
 * Client-side handshake with a Server//from w w  w.  j  av a 2  s.com
 */
public ServerQueueStatus handshakeWithServer(Connection conn, ServerLocation location,
        CommunicationMode communicationMode) throws IOException, AuthenticationRequiredException,
        AuthenticationFailedException, ServerRefusedConnectionException {
    try {
        ServerQueueStatus serverQStatus = null;
        Socket sock = conn.getSocket();
        DataOutputStream dos = new DataOutputStream(sock.getOutputStream());
        final InputStream in = sock.getInputStream();
        DataInputStream dis = new DataInputStream(in);
        DistributedMember member = getIDForSocket(sock);
        // if running in a loner system, use the new port number in the ID to
        // help differentiate from other clients
        DM dm = ((InternalDistributedSystem) this.system).getDistributionManager();
        InternalDistributedMember idm = dm.getDistributionManagerId();
        synchronized (idm) {
            if (idm.getPort() == 0 && dm instanceof LonerDistributionManager) {
                int port = sock.getLocalPort();
                ((LonerDistributionManager) dm).updateLonerPort(port);
                updateProxyID(dm.getDistributionManagerId());
            }
        }
        if (communicationMode.isWAN()) {
            this.credentials = getCredentials(member);
        }
        byte intermediateAcceptanceCode = write(dos, dis, communicationMode, REPLY_OK, this.clientReadTimeout,
                null, this.credentials, member, false);

        String authInit = this.system.getProperties().getProperty(SECURITY_CLIENT_AUTH_INIT);
        if (!communicationMode.isWAN() && intermediateAcceptanceCode != REPLY_AUTH_NOT_REQUIRED
                && (authInit != null && authInit.length() != 0)) {
            location.compareAndSetRequiresCredentials(true);
        }
        // Read the acceptance code
        byte acceptanceCode = dis.readByte();
        if (acceptanceCode == (byte) 21 && !(sock instanceof SSLSocket)) {
            // This is likely the case of server setup with SSL and client not using
            // SSL
            throw new AuthenticationRequiredException(
                    LocalizedStrings.HandShake_SERVER_EXPECTING_SSL_CONNECTION.toLocalizedString());
        }
        if (acceptanceCode == REPLY_SERVER_IS_LOCATOR) {
            throw new GemFireConfigException("Improperly configured client detected.  " + "Server at "
                    + location + " is actually a locator.  Use addPoolLocator to configure locators.");
        }

        // Successful handshake for GATEWAY_TO_GATEWAY mode sets the peer version in connection
        if (communicationMode.isWAN() && !(acceptanceCode == REPLY_EXCEPTION_AUTHENTICATION_REQUIRED
                || acceptanceCode == REPLY_EXCEPTION_AUTHENTICATION_FAILED)) {
            short wanSiteVersion = Version.readOrdinal(dis);
            conn.setWanSiteVersion(wanSiteVersion);
            // establish a versioned stream for the other site, if necessary
            if (wanSiteVersion < Version.CURRENT_ORDINAL) {
                dis = new VersionedDataInputStream(dis, Version.fromOrdinalOrCurrent(wanSiteVersion));
            }
        }

        // No need to check for return value since DataInputStream already throws
        // EOFException in case of EOF
        byte epType = dis.readByte();
        int qSize = dis.readInt();

        // Read the server member
        member = readServerMember(dis);
        serverQStatus = new ServerQueueStatus(epType, qSize, member);

        // Read the message (if any)
        readMessage(dis, dos, acceptanceCode, member);

        // Read delta-propagation property value from server.
        // [sumedh] Static variable below? Client can connect to different
        // DSes with different values of this. It shoule be a member variable.
        if (!communicationMode.isWAN() && currentClientVersion.compareTo(Version.GFE_61) >= 0) {
            deltaEnabledOnServer = dis.readBoolean();
        }

        // validate that the remote side has a different distributed system id.
        if (communicationMode.isWAN() && Version.GFE_66.compareTo(conn.getWanSiteVersion()) <= 0
                && currentClientVersion.compareTo(Version.GFE_66) >= 0) {
            int remoteDistributedSystemId = in.read();
            int localDistributedSystemId = ((InternalDistributedSystem) system).getDistributionManager()
                    .getDistributedSystemId();
            if (localDistributedSystemId >= 0 && localDistributedSystemId == remoteDistributedSystemId) {
                throw new GatewayConfigurationException(
                        "Remote WAN site's distributed system id " + remoteDistributedSystemId
                                + " matches this sites distributed system id " + localDistributedSystemId);
            }
        }
        // Read the PDX registry size from the remote size
        if (communicationMode.isWAN() && Version.GFE_80.compareTo(conn.getWanSiteVersion()) <= 0
                && currentClientVersion.compareTo(Version.GFE_80) >= 0) {
            int remotePdxSize = dis.readInt();
            serverQStatus.setPdxSize(remotePdxSize);
        }

        return serverQStatus;
    } catch (IOException ex) {
        CancelCriterion stopper = this.system.getCancelCriterion();
        stopper.checkCancelInProgress(null);
        throw ex;
    }
}

From source file:com.mirth.connect.plugins.dashboardstatus.DashboardConnectorStatusMonitor.java

public void updateStatus(String connectorId, ConnectorType type, Event event, Socket socket) {
    String stateImage = COLOR_BLACK;
    String stateText = STATE_UNKNOWN;
    boolean updateStatus = true;

    switch (event) {
    case INITIALIZED:
        switch (type) {
        case LISTENER:
            stateImage = COLOR_YELLOW;/*from  w w w  .ja v a 2 s.  co  m*/
            stateText = STATE_WAITING;
            break;
        case READER:
            stateImage = COLOR_YELLOW;
            stateText = STATE_IDLE;
            break;
        }
        break;
    case CONNECTED:
        switch (type) {
        case LISTENER:
            if (socket != null) {
                addConnectionToSocketSet(socket, connectorId);
                stateImage = COLOR_GREEN;
                stateText = STATE_CONNECTED + " (" + getSocketSetCount(connectorId) + ")";
            } else {
                stateImage = COLOR_GREEN;
                stateText = STATE_CONNECTED;
            }
            break;
        case READER:
            stateImage = COLOR_GREEN;
            stateText = STATE_POLLING;
            break;
        }
        break;
    case DISCONNECTED:
        switch (type) {
        case LISTENER:
            if (socket != null) {
                removeConnectionInSocketSet(socket, connectorId);
                int connectedSockets = getSocketSetCount(connectorId);
                if (connectedSockets == 0) {
                    stateImage = COLOR_YELLOW;
                    stateText = STATE_WAITING;
                } else {
                    stateImage = COLOR_GREEN;
                    stateText = STATE_CONNECTED + " (" + connectedSockets + ")";
                }
            } else {
                clearSocketSet(connectorId);
                stateImage = COLOR_RED;
                stateText = STATE_DISCONNECTED;
            }
            break;
        case READER:
            stateImage = COLOR_RED;
            stateText = STATE_NOT_POLLING;
            break;
        case WRITER:
            stateImage = COLOR_RED;
            stateText = STATE_DISCONNECTED;
            break;
        case SENDER:
            stateImage = COLOR_RED;
            stateText = STATE_DISCONNECTED;
            break;
        }
        break;
    case BUSY:
        switch (type) {
        case READER:
            stateImage = COLOR_GREEN;
            stateText = STATE_READING;
            break;
        case LISTENER:
            stateImage = COLOR_GREEN;
            stateText = STATE_RECEIVING;
            break;
        case WRITER:
            stateImage = COLOR_YELLOW;
            stateText = STATE_WRITING;
            break;
        case SENDER:
            stateImage = COLOR_YELLOW;
            stateText = STATE_SENDING;
            break;
        }
        break;
    case DONE:
        switch (type) {
        case READER:
            stateImage = COLOR_YELLOW;
            stateText = STATE_IDLE;
            break;
        case LISTENER:
            if (socket != null) {
                stateImage = COLOR_GREEN;
                stateText = STATE_CONNECTED + " (" + getSocketSetCount(connectorId) + ")";
            } else {
                stateImage = COLOR_YELLOW;
                stateText = STATE_WAITING;
            }
            break;
        }
        break;
    case ATTEMPTING:
        switch (type) {
        case WRITER:
            stateImage = COLOR_YELLOW;
            stateText = STATE_ATTEMPTING;
            break;
        case SENDER:
            stateImage = COLOR_YELLOW;
            stateText = STATE_ATTEMPTING;
            break;
        }
        break;
    default:
        updateStatus = false;
        break;
    }

    if (updateStatus) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");

        String channelName = "";
        // this will be overwritten down below. If not, something's wrong.
        String connectorType = type.toString();
        String information = "";

        /*
         * check 'connectorId' - contains destination_1_connector, etc.
         * connectorId consists of id_source_connector for sources, and
         * id_destination_x_connector for destinations. i.e. tokenCount will
         * be 3 for sources and 4 for destinations. Note that READER and
         * LISTENER are sources, and WRITER and SENDER are destinations.
         */
        StringTokenizer tokenizer = new StringTokenizer(connectorId, "_");
        String channelId = tokenizer.nextToken();
        int destinationIndex;
        LinkedList<String[]> channelLog = null;

        Channel channel = ControllerFactory.getFactory().createChannelController()
                .getDeployedChannelById(channelId);

        if (channel != null) {
            channelName = channel.getName();
            // grab the channel's log from the HashMap, if not exist, create
            // one.
            if (connectorInfoLogs.containsKey(channelName)) {
                channelLog = connectorInfoLogs.get(channelName);
            } else {
                channelLog = new LinkedList<String[]>();
            }

            Connector connector = null;

            switch (type) {
            case READER:
                connectorType = "Source: " + channel.getSourceConnector().getTransportName() + "  ("
                        + channel.getSourceConnector().getTransformer().getInboundProtocol().toString() + " -> "
                        + channel.getSourceConnector().getTransformer().getOutboundProtocol().toString() + ")";
                break;
            case LISTENER:
                connectorType = "Source: " + channel.getSourceConnector().getTransportName() + "  ("
                        + channel.getSourceConnector().getTransformer().getInboundProtocol().toString() + " -> "
                        + channel.getSourceConnector().getTransformer().getOutboundProtocol().toString() + ")";
                break;
            case WRITER:
                tokenizer.nextToken();
                // destinationId begins from 1, so subtract by 1 for the
                // arrayIndex.
                destinationIndex = Integer.valueOf(tokenizer.nextToken()) - 1;
                connector = channel.getDestinationConnectors().get(destinationIndex);
                connectorType = "Destination: " + connector.getTransportName() + " - " + connector.getName();

                if (connector.getTransportName().equals(FileWriterProperties.name)) {
                    // Destination - File Writer.
                    switch (event) {
                    case BUSY:
                        information = FileWriterProperties.getInformation(connector.getProperties());
                        break;
                    }
                } else if (connector.getTransportName().equals(DatabaseWriterProperties.name)) {
                    // Destination - Database Writer.
                    information = DatabaseWriterProperties.getInformation(connector.getProperties());
                } else if (connector.getTransportName().equals(JMSWriterProperties.name)) {
                    // Destination - JMS Writer.
                    information = JMSWriterProperties.getInformation(connector.getProperties());
                } else if (connector.getTransportName().equals(DocumentWriterProperties.name)) {
                    // Destination - Document Writer.
                    information = DocumentWriterProperties.getInformation(connector.getProperties());
                }
                break;
            case SENDER:
                tokenizer.nextToken();
                // destinationId begins from 1, so subtract by 1 for the
                // arrayIndex.
                destinationIndex = Integer.valueOf(tokenizer.nextToken()) - 1;
                connector = channel.getDestinationConnectors().get(destinationIndex);
                connectorType = "Destination: " + connector.getTransportName() + " - " + connector.getName();

                if (connector.getTransportName().equals(HttpSenderProperties.name)) {
                    // Destination - HTTP Sender.
                    information = HttpSenderProperties.getInformation(connector.getProperties());
                } else if (connector.getTransportName().equals(ChannelWriterProperties.name)) {
                    // Destination - Channel Writer.
                    Channel targetChannel = ControllerFactory.getFactory().createChannelController()
                            .getDeployedChannelById(
                                    ChannelWriterProperties.getInformation(connector.getProperties()));

                    if (targetChannel == null) {
                        information = "Target Channel: None";
                    } else {
                        information = "Target Channel: " + targetChannel.getName();
                    }
                } else if (connector.getTransportName().equals(SmtpSenderProperties.name)) {
                    // Destination - SMTP Sender.
                    information = SmtpSenderProperties.getInformation(connector.getProperties());
                } else if (connector.getTransportName().equals(TCPSenderProperties.name)) {
                    // Destination - TCP Sender.
                    // The useful info for TCP Sender - host:port will
                    // be taken care of by the socket below.
                } else if (connector.getTransportName().equals(LLPSenderProperties.name)) {
                    // Destination - LLP Sender.
                    // The useful info for LLP Sender - host:port will
                    // be taken care of by the socket below.
                } else if (connector.getTransportName().equals(WebServiceSenderProperties.name)) {
                    // Destination - Web Service Sender.
                    // information = "";
                }
                break;
            }
        }

        if (socket != null) {
            String sendingAddress = socket.getLocalAddress().toString() + ":" + socket.getLocalPort();
            String receivingAddress = socket.getInetAddress().toString() + ":" + socket.getPort();

            // If addresses begin with a slash "/", remove it.
            if (sendingAddress.startsWith("/")) {
                sendingAddress = sendingAddress.substring(1);
            }

            if (receivingAddress.startsWith("/")) {
                receivingAddress = receivingAddress.substring(1);
            }

            information += "Sender: " + sendingAddress + "  Receiver: " + receivingAddress;
        }

        if (channelLog != null) {
            synchronized (this) {
                if (channelLog.size() == MAX_LOG_SIZE) {
                    channelLog.removeLast();
                }
                channelLog.addFirst(new String[] { String.valueOf(logId), channelName,
                        dateFormat.format(timestamp), connectorType, event.toString(), information });

                if (entireConnectorInfoLogs.size() == MAX_LOG_SIZE) {
                    entireConnectorInfoLogs.removeLast();
                }
                entireConnectorInfoLogs.addFirst(new String[] { String.valueOf(logId), channelName,
                        dateFormat.format(timestamp), connectorType, event.toString(), information });

                logId++;

                // put the channel log into the HashMap.
                connectorInfoLogs.put(channelName, channelLog);
            }
        }

        connectorStateMap.put(connectorId, new String[] { stateImage, stateText });
    }
}