Example usage for java.net Socket getPort

List of usage examples for java.net Socket getPort

Introduction

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

Prototype

public int getPort() 

Source Link

Document

Returns the remote port number to which this socket is connected.

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();/* w  w  w.j av 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:gov.hhs.fha.nhinc.lift.proxy.client.ClientConnector.java

@Override
public void run() {
    /*/*from w ww. j a v  a 2s . com*/
     * Accept a connection and tunnel messages through the proxy system.
     */
    Socket socket = null;
    try {
        Thread toProxyThread;
        Thread fromProxyThread;

        socket = server.accept();
        log.debug("Server accepting to socket " + socket.getInetAddress());
        Connector toProxy = new Connector(socket.getInputStream(), proxyConnection.getOutStream(), bufferSize);
        Connector fromProxy = new Connector(proxyConnection.getInStream(), socket.getOutputStream(),
                bufferSize);

        toProxyThread = new Thread(toProxy, "Client To Proxy");
        fromProxyThread = new Thread(fromProxy, "Client From Proxy");

        toProxyThread.start();
        fromProxyThread.start();

        log.debug("Waiting to finish " + toProxyThread.getName());
        toProxyThread.join();

    } catch (IOException e) {
        String errorMsg = "Problem in creating client to proxy connectors: " + e.getMessage();
        log.error(errorMsg);
        controller.reportFailure(proxyConnection.getToken().getRequest(), errorMsg);
    } catch (InterruptedException e) {
        String errorMsg = "Client to proxy communication thread interrupted: " + e.getMessage();
        log.error(errorMsg);
        controller.reportFailure(proxyConnection.getToken().getRequest(), errorMsg);
    } finally {
        if (socket != null) {
            try {
                log.debug("Closing socket " + socket.getInetAddress() + ": " + socket.getPort());
                // Also closes associated streams
                socket.close();
            } catch (IOException ex) {
                log.warn("Unable to close client to proxy socket: " + ex.getMessage());
            }
        }
        if (proxyConnection != null) {
            try {
                log.debug("Closing proxy connection " + proxyConnection.getSocket().getInetAddress() + ": "
                        + proxyConnection.getSocket().getPort());
                proxyConnection.close();
            } catch (IOException ex) {
                log.warn("Unable to close proxy connection: " + ex.getMessage());
            }
        }
        if (server != null) {
            try {
                log.debug("Closing client connection server" + server.getInetAddress() + ": "
                        + server.getLocalPort());
                server.close();
            } catch (IOException ex) {
                log.warn("Unable to close proxy connection: " + ex.getMessage());
            }
        }
    }
}

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

/**
 * Return fake, temporary DistributedMember to represent the other vm this vm is connecting to
 * //from  ww  w. ja  v a 2s .c o  m
 * @param sock the socket this handshake is operating on
 * @return temporary id to reprent the other vm
 */
private DistributedMember getIDForSocket(Socket sock) {
    return new InternalDistributedMember(sock.getInetAddress(), sock.getPort(), false);
}

From source file:org.apache.hadoop.hive.service.HSSessionItem.java

public HSSessionItem(HSAuth auth, String sessionName, TTransport trans) throws FileNotFoundException {

    this.jobid = 0;
    this.auth = auth;
    this.sessionName = sessionName;
    this.home = ".";
    this.runable = null;
    this.jr = null;
    this.config = new SessionConfig(jobType.ONESHOT);
    this.jobStatus = HSSessionItem.JobStatus.INIT;
    this.date = new Date();
    this.opdate = this.date;
    if (SessionState.get() != null) {
        this.to = SessionState.get().getConf().getIntVar(HiveConf.ConfVars.HIVESESSIONTIMEOUT);
        if (this.to > 7200 || this.to < 0) {
            this.to = 60;
        }/*w  w w  . j a  v a 2s  .  co  m*/
    } else {
        this.to = 7200;
    }

    this.transSet = new HashSet();
    if (trans != null)
        transSet.add(trans);
    l4j.debug("HSSessionItem created");
    status = SessionItemStatus.NEW;

    l4j.debug("Wait for NEW->READY transition");
    l4j.debug("NEW->READY transition complete");

    queryInfo = new HashMap<Integer, GregorianCalendar>();
    this.current_query_count = 0;

    InetAddress localhost = null;
    try {
        localhost = InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    if (localhost != null)
        hostip = localhost.getHostAddress();

    try {
        TSocket tSocket = (TSocket) trans;
        Socket socket = tSocket.getSocket();
        InetAddress addr = socket.getInetAddress();
        this.clientip = addr.getHostAddress();
        l4j.debug("client address: " + addr.getHostAddress() + " client port: " + socket.getPort());
    } catch (Exception e) {
        l4j.debug("get IP, PORT failed in create session");
    }

    if ((conf_file_loc == null) || conf_file_loc.length() == 0) {
        return;
    }

    File f = new File(conf_file_loc);
    if (!f.exists()) {
        if (!f.mkdir()) {
            return;
        }
    }

    try {
        sessionFileName = conf_file_loc + "/" + sessionName + ".txt";
        File thefile = new File(sessionFileName);
        if (!thefile.exists()) {
            dayLogStream = new PrintWriter(new FileWriter(sessionFileName, true));
        } else {
            dayLogStream = new PrintWriter(new FileWriter(sessionFileName, true));
            dayLogStream.print("+++++++++++++++++++++++++++++++++++++++++++++++++++");
            dayLogStream.print('\n');
            dayLogStream.print("A new session is appended here!  ");
            dayLogStream.print('\n');
            Calendar rightNow = Calendar.getInstance();
            Date time = rightNow.getTime();
            dayLogStream.print(time.toString());
            dayLogStream.print('\n');
            dayLogStream.print("+++++++++++++++++++++++++++++++++++++++++++++++++++");
            dayLogStream.print('\n');
        }
    } catch (Exception ex) {
    }
}

From source file:org.apache.geode.internal.net.SocketCreator.java

/**
 * Will be a server socket... this one simply registers the listeners.
 *///from   w ww  .j a  v a  2s . c  om
public void configureServerSSLSocket(Socket socket) throws IOException {
    if (socket instanceof SSLSocket) {
        SSLSocket sslSocket = (SSLSocket) socket;
        try {
            sslSocket.startHandshake();
            SSLSession session = sslSocket.getSession();
            Certificate[] peer = session.getPeerCertificates();
            if (logger.isDebugEnabled()) {
                logger.debug(LocalizedMessage.create(LocalizedStrings.SocketCreator_SSL_CONNECTION_FROM_PEER_0,
                        ((X509Certificate) peer[0]).getSubjectDN()));
            }
        } catch (SSLPeerUnverifiedException ex) {
            if (this.sslConfig.isRequireAuth()) {
                logger.fatal(
                        LocalizedMessage.create(
                                LocalizedStrings.SocketCreator_SSL_ERROR_IN_AUTHENTICATING_PEER_0_1,
                                new Object[] { socket.getInetAddress(), Integer.valueOf(socket.getPort()) }),
                        ex);
                throw ex;
            }
        } catch (SSLException ex) {
            logger.fatal(
                    LocalizedMessage.create(LocalizedStrings.SocketCreator_SSL_ERROR_IN_CONNECTING_TO_PEER_0_1,
                            new Object[] { socket.getInetAddress(), Integer.valueOf(socket.getPort()) }),
                    ex);
            throw ex;
        }
    }
}

From source file:org.apache.geode.internal.net.SocketCreator.java

/**
 * When a socket is accepted from a server socket, it should be passed to this method for SSL
 * configuration./*from  ww w .ja  v  a2  s  . c  o m*/
 */
private void configureClientSSLSocket(Socket socket, int timeout) throws IOException {
    if (socket instanceof SSLSocket) {
        SSLSocket sslSocket = (SSLSocket) socket;

        sslSocket.setUseClientMode(true);
        sslSocket.setEnableSessionCreation(true);

        String[] protocols = this.sslConfig.getProtocolsAsStringArray();

        // restrict cyphers
        if (protocols != null && !"any".equalsIgnoreCase(protocols[0])) {
            sslSocket.setEnabledProtocols(protocols);
        }
        String[] ciphers = this.sslConfig.getCiphersAsStringArray();
        if (ciphers != null && !"any".equalsIgnoreCase(ciphers[0])) {
            sslSocket.setEnabledCipherSuites(ciphers);
        }

        try {
            if (timeout > 0) {
                sslSocket.setSoTimeout(timeout);
            }
            sslSocket.startHandshake();
            SSLSession session = sslSocket.getSession();
            Certificate[] peer = session.getPeerCertificates();
            if (logger.isDebugEnabled()) {
                logger.debug(LocalizedMessage.create(LocalizedStrings.SocketCreator_SSL_CONNECTION_FROM_PEER_0,
                        ((X509Certificate) peer[0]).getSubjectDN()));
            }
        } catch (SSLHandshakeException ex) {
            logger.fatal(
                    LocalizedMessage.create(LocalizedStrings.SocketCreator_SSL_ERROR_IN_CONNECTING_TO_PEER_0_1,
                            new Object[] { socket.getInetAddress(), Integer.valueOf(socket.getPort()) }),
                    ex);
            throw ex;
        } catch (SSLPeerUnverifiedException ex) {
            if (this.sslConfig.isRequireAuth()) {
                logger.fatal(LocalizedMessage
                        .create(LocalizedStrings.SocketCreator_SSL_ERROR_IN_AUTHENTICATING_PEER), ex);
                throw ex;
            }
        } catch (SSLException ex) {
            logger.fatal(
                    LocalizedMessage.create(LocalizedStrings.SocketCreator_SSL_ERROR_IN_CONNECTING_TO_PEER_0_1,
                            new Object[] { socket.getInetAddress(), Integer.valueOf(socket.getPort()) }),
                    ex);
            throw ex;
        }

    }
}

From source file:slash.navigation.mapview.browser.BrowserMapView.java

private void processStream(Socket socket) throws IOException {
    List<String> lines = new ArrayList<>();
    boolean processingPost = false, processingBody = false;
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()),
            64 * 1024)) {/* w  w w.j  av  a2 s. com*/
        while (true) {
            try {
                String line = trim(reader.readLine());
                if (line == null) {
                    if (processingPost && !processingBody) {
                        processingBody = true;
                        continue;
                    } else
                        break;
                }
                if (line.startsWith("POST"))
                    processingPost = true;
                lines.add(line);
            } catch (IOException e) {
                log.severe("Cannot read line from callback listener port:" + e);
                break;
            }
        }

        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))) {
            writer.write("HTTP/1.1 200 OK\n");
            writer.write("Content-Type: text/plain\n");
        }
    }

    StringBuilder buffer = new StringBuilder();
    for (String line : lines) {
        buffer.append("  ").append(line).append("\n");
    }
    log.fine("Processing callback @" + currentTimeMillis() + " from port " + socket.getPort() + ": \n"
            + buffer.toString());

    if (!isAuthenticated(lines))
        return;

    processLines(lines, socket.getPort());
}

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;/*ww w  .  j a  v a2s . 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 });
    }
}