Tag Archives: java

Designing a basic chat system using Java Socket programming

“A socket is one end-point of a two-way communication link between two programs running on the network. Socket classes are used to represent the connection between a client program and a server program. “  – Oracle Docs.

So,

Server Socket  listens to  port    ==>     <XX>    <==     Client Socket connect to port

Lets build a basic chat system using socket programming.

Server Socket : It listens to port 2200 and responds to client

package com.language.sockets;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

// This is Server Socket which listens to and responds to client
public class ServerSocketImpl {

    public static void main(String args[])
    {
        ServerSocket server = null;
        Socket  client = null;
        InputStream instream = null;
        Scanner scanner = null;
       OutputStream oos= null;
        try {
            server = new ServerSocket(2200, 10, InetAddress.getByName("localhost"));
            System.out.println("Listening to port 2200");
            client = server.accept();
            scanner = new Scanner(System.in);
            while(true)
            {
                instream = client.getInputStream();
                oos = client.getOutputStream();
                byte b[] = new byte[1024];
                int read = 0;
                if((read = instream.read(b)) > 0)
                {
                    System.out.println("New Chat : " + new String(b));
                }

                if(scanner.hasNext())
                {
                    oos.write(scanner.nextLine().getBytes());
                }

            }
        }
        catch(UnknownHostException e)
        {
            e.printStackTrace();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        finally {
            if(server != null)
            {
                try
                {
                    server.close();
                }
                catch(IOException e)
                {}
            }
            if(client!=null)
            {
                try
                {
                    client.close();
                }
                catch(IOException e)
                {

                }
            }
            if(instream!=null)
            {
                try
                {
                    instream.close();
                }
                catch(IOException e)
                {

                }
            }
        }
    }
}

Client Socket : It connects to port 2200 and responds to server

package com.language.sockets;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class ServerClientImpl {
    public static void main(String args[])
    {
        OutputStream oos = null;
        Socket client = null;
        Scanner scanner = null;
        InputStream is = null;
        try {
            client = new Socket(InetAddress.getByName("localhost"), 2200);
            oos = client.getOutputStream();
            scanner = new Scanner(System.in);
            is =   client.getInputStream();
            while(true)
            {
                if(scanner.hasNext())
                {
                    oos.write(scanner.nextLine().getBytes());
                    oos.flush();
                }
                int read = 0;
                byte b[] = new byte[1024];
                if((read = is.read(b)) > 0)
                {
                    System.out.println(new String(b));
                }
            }
        }
        catch(UnknownHostException e)
        {
            e.printStackTrace();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        finally {
            if(oos != null)
            {
                try
                {
                    oos.close();
                }
               catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(client!=null)
            {
                try {
                    client.close();
                }
                catch(IOException e)
                {}
            }
            if(scanner !=null)
            {
                scanner.close();
            }
        }
    }
}

Now compile the classes and open two command prompts one for the Server and another for client and exchange the message (Communication should start from the Client) :

Window 1 : 

C:\Test>java com.language.sockets.ServerSocketImpl

Listening to port 2200

sHello Server
Hi ClientProgram

Window 2 : 

C:\Test>java com.language.sockets.ServerClientImpl

Hello Server
Hi ClientProgram

 

Happy Coding 🙂

Consecutive character removal algorithm

Recently I came across a question in one of the coding practices quiz – Remove consecutive characters from a string and they say it as String Bomber Algorithm. I was given half an hour of time to complete the task. Looks simple at first but while writing I came across certain scenarios which proved me that the algorithm requires more thinking than anticipated. However, I  managed to complete the task in which a few test cases passed while one failed. Let us take some examples.

Examples:

Input Output
abbcd acd
abbcccd ad
abbcccad d
abbcccadag dag

Still looks simple , huh ? 🙂

The difficulty of the problem lies in re eliminating the characters which become consecutive in the output if all the characters in between them has been dropped.

Say, in example above exmple ‘abbcccad’ input should give the output as ‘d’.

Input : abbcccad

Pass 1: acccad ==> bb is consecutive so elliminated

Pass 2: aad ==> ccc is consecutive so eliminated

Pass 3: d ==> aa is consecutive so eliminated.

Hence output is ‘d’.

I wrote an algorithm which would do the above task:

package com.ds;

/**
 * Created by devashish on 2/13/2017.
 */
public class StringBomber {
    public static void main(String args[])
    {
        String input  = "abbcccadag";
        String output = "";
        char prevchar = input.charAt(0);
        for(int i  = 0 ; i < input.length()   ; )
        {

            char outputlastchar = ' ';
            if(output.length() > 0)
            {
             outputlastchar =  output.charAt(output.length()-1);
            }

            if( i == input.length() -1 )
            {
                if(outputlastchar != input.charAt(i))
                {
                    output +=input.charAt(i);
                }
                else
                {
                    if(output.length() > 0)
                    {
                        output = output.substring(0,output.length()-1);
                    }
                }
                break;
            }

            if((input.charAt(i) == input.charAt(i+1)) )
            {
                int j = i;

                while(j< input.length() && input.charAt(j) == input.charAt(i))
                {
                    j++;
                }
                i=j;
                prevchar = input.charAt(j-1);
            }
            else if(   input.charAt(i) == outputlastchar )
            {

                if(output.length() > 0)
                {
                     output = output.substring(0,output.length()-1);
                }

                prevchar = input.charAt(i);
                i++;
               
            }
            else
            {
                output +=input.charAt(i);
                prevchar = input.charAt(i);
                i++;

            }

        }

        System.out.println("output:"+output);
    }
}

 

Complexity of the above problem is O(n).

Try it and comment in case you see any issues with the algorithm.

Stay well and happy coding 🙂

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Insertion Sort

Insertion sort : Pick an element in the array and position it in its appropriate place in the natural ordering.

e.g. Array 5,4,3,2,1

Pass 1:

Input : 5,4,3,2,1

4 is lesser than 5, so re-position 4.

Output: 4,5,3,2,1

Pass 2:

Input :4,5,3,2,1

3 is lesser than 4, so re-position 3.

Output: 3,4,5,2,1

 

Pass 3:

Input :3,4,5,2,1

2 is lesser than 3, so re-position 3.

Output: 2,3,4,5,1

 

Pass 4:

Input :2,3,4,5,1

1 is lesser than 2, so re-position 2.

Output: 1,2,3,4,5

Array is now sorted.

So, the complexity of the sorting lies in re positioning the array elements.

  • Worst case: O(n^2).
  • Best case: O(n).
  • Average case for a random array: O(n^2).

I have written a small program to compare the elements using insertion sort algorithm.

 

public class InsertionSort 
{
 public static void main(String[] args) 
 {
 int arr[] = {28,26,1,7,13,12,9,-1,6,6,6,6,5,6,4,3,2,1};
 
 for(int i = 1 ; i < arr.length ; i++)
 {
 if(arr[i] < arr[i-1])
 {
 boolean shift = false;
 int temp = -100;
 for(int j = 0 ; j <= i ; j++)
 {
 
 if(shift)
 {
 int temp1 = arr[j];
 arr[j] = temp;
 temp = temp1;
 continue;
 }
 
 if(arr[j] > arr[i])
 {
 temp = arr[j];
 arr[j] = arr[i];
 shift = true;
 }
 }
 }
 }
 
 for(int i : arr)
 {
 System.out.println(i);
 }
 }
}


 

Stay well and happy coding 🙂

Arranging scores in a Game Board.

Problem Statement: Let us say a scenario where player’s scores are displayed in a Game Board. As and when the player scores, it should be inserted in the proper position in the Game Board.

Assumptions:

  1. We assume maximum number of scorecards to be inserted in the Game Board to be fifty.
  2. The player names must be unique in a Game Board.

Solution: A simple approach is:

  1. When we get a scorecard, we iterate through the existing Game Board as insert it in the proper position.
  2. When we have inserted it in the proper position, all the next scorecards has to be shifted right and score card length will be incremented by 1.
  3. If we want to remove a score card from the Game Board, we search it by name and remove it. Also, we shift the array left by one position.

Code:

 

public class GameBoard {
 ScoreCard[] scorecards;
 static int scorecardlength;

public GameBoard() {
 this.scorecards = new ScoreCard[50] ;
 scorecardlength = 0;
 }

public GameBoard(ScoreCard[] scorecards) 
 {
 this.scorecards = scorecards ;
 }

public int insertScoreCard(ScoreCard myscorecard)
 {
 int i = 0;
 try {
 do
 {
 
 if(i == scorecardlength)
 {
 scorecards[i] = myscorecard;
 scorecardlength++;
 break;
 }
 
 if(scorecards[i].playerName.equals(myscorecard.playerName))
 {
 System.out.println("Player "+myscorecard.playerName+" already mentioned in GameBoard. This will be skipped. ");
 break;
 }
 
 if(scorecardlength > 0)
 {
 if(myscorecard.score > scorecards[i].score)
 {
 scorecardlength++;
 ScoreCard temp = scorecards[i];
 scorecards[i] = myscorecard;

int iterator = i+1;
 while(iterator <= scorecardlength)
 {
 ScoreCard tempnext = scorecards[iterator];
 scorecards[iterator] = temp;
 temp = tempnext;
 iterator++;
 }
 break;
 } 
 }
 else
 {
 scorecards[i] = myscorecard;
 scorecardlength++;
 break;
 }

i++;
 }
 while( i <= scorecardlength);
 } catch (Exception e) {
 e.printStackTrace();
 }
 return scorecardlength;

}
 
 
 public void removeScoreCard(String playerName)
 {
 for(int i=0; i <scorecardlength ; i++)
 {
 if(scorecards[i].playerName.equals(playerName))
 {
 int iterator = i;
 while(iterator < scorecardlength-1 )
 {
 scorecards[iterator] = scorecards[iterator+1];
 iterator++;
 }
 scorecardlength--; 
 break;
 }
 }
 }
 
 public int getScoreCards()
 {
 return scorecardlength;
 }
 public void displayGameBoard()
 {
 for(int i=0;i<scorecardlength;i++)
 {
 if(scorecardlength >0 )
 {
 System.out.println("Player "+scorecards[i].playerName+" scored "+scorecards[i].score+" score. You are on "+(i+1)+" position.");
 }
 else
 {
 System.out.println("No scorecards in the Game Board.");
 }
 }
 }
 
 
 public static void main(String[] args) {
 GameBoard gameboard = new GameBoard();
 
 
 gameboard.insertScoreCard(new ScoreCard("player1", 10));
 gameboard.insertScoreCard(new ScoreCard("player2", 20));
 gameboard.insertScoreCard(new ScoreCard("player3", 5));
 gameboard.insertScoreCard(new ScoreCard("player4", 10));
 gameboard.insertScoreCard(new ScoreCard("player5", 10));
 gameboard.insertScoreCard(new ScoreCard("player6", 10));
 gameboard.insertScoreCard(new ScoreCard("player7", 10));
 gameboard.insertScoreCard(new ScoreCard("player8", 10));
 gameboard.insertScoreCard(new ScoreCard("player1", 10));
 gameboard.insertScoreCard(new ScoreCard("player2", 20));
 gameboard.insertScoreCard(new ScoreCard("player3", 5));
 gameboard.insertScoreCard(new ScoreCard("player4", 10));
 gameboard.insertScoreCard(new ScoreCard("player5", 10));
 gameboard.insertScoreCard(new ScoreCard("player6", 10));
 gameboard.insertScoreCard(new ScoreCard("player7", 10));
 gameboard.insertScoreCard(new ScoreCard("player8", 10));
 
 gameboard.displayGameBoard();
 }
}

class ScoreCard
{
 String playerName ; 
 int score;
 public ScoreCard() {

}

ScoreCard(String playerName, int score)
 {
 this.playerName = playerName ;
 this.score = score ;
 }

}

Keep Safe and Happy Coding 🙂

 

 

 

ActiveMQ – My First Example

Hello and welcome after a very long time !!

There are lots of things that I want to post but as of now, would post my first example code with active mq.

Active MQ – This is a open source message broker with full JMS implementation.

You can please read more details from : http://activemq.apache.org/

First step : Download and unzip apache-activemq-5.11.1-bin binary files to a drive.

Second step: Installation
————–
Run the ActiveMQ batch inside the win32 folder.
http://localhost:8161/
Testing the installation
————————
Active MQ default port is 61616

From cmd prompt

netstat -an|find “61616”

Monitoring ActiveMQ
——————-
The default username and password is admin/admin.
You can configure this in the conf/jetty-real.properties file.
Stopping ActiveMQ
——————
Type Ctrl-C at the cmd prompt.

Now open Eclipse and create a Message Producer, Message consumer and a main class. Complete codes are posted here. These are taken from the active mq website and can be modified accordingly.

Add activemq-all-5.4.3.jar in the class path.

HelloProducer.java

========================================================================================================================================================

package com.Active_MQ;

import java.awt.font.TextMeasurer;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class HelloProducer implements Runnable{

@Override
public void run() {
// TODO Auto-generated method stub
try {
//Creating connection factory
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(“tcp://localhost:61616”);

//ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_BROKER_URL);

//Create connection
Connection connection = connectionFactory.createConnection();
connection.start();

//Create session
Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);

//Create destination
Destination destination = session.createQueue(“TEST.FOO”);

MessageProducer producer = session.createProducer(destination);

producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

//Create a message

String text = “Hello world from ” + Thread.currentThread().getName()+” : ” + this.hashCode();
TextMessage message = session.createTextMessage(text);

//Tell the producer to send the message

System.out.println(“Sent message ” + message.hashCode() + ” : ” + Thread.currentThread().getName());

producer.send(message);

//Clean up

session.close();
connection.close();

} catch (Exception e) {
e.printStackTrace();
}
}

}

============================================================================
============================================================================

HelloConsumer.java

========================================================================================================================================================

package com.Active_MQ;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
public class HelloConsumer implements Runnable{
public void run()
{
try {
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(“tcp://localhost:61616”);

Connection connection = connectionFactory.createConnection();

connection.start();
//connection.setExceptionListener((ExceptionListener) this);

Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);

Destination destination = session.createQueue(“TEST.FOO”);

MessageConsumer consumer = session.createConsumer(destination);

Message message = consumer.receive(1000);

if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
String text = textMessage.getText();
System.out.println(“Received “+text);

}
else
{
System.out.println(“Received “+message);
}

consumer.close();
session.close();
connection.close();

} catch (Exception e) {
e.printStackTrace();
}
}

}

========================================================================================================================================================

App.java

========================================================================================================================================================

package com.Active_MQ;

public class App {
public static void main(String[] args) {
try {
thread(new HelloProducer(),false);
thread(new HelloProducer(),false);
thread(new HelloConsumer(),false);
Thread.sleep(1000);
thread(new HelloConsumer(), false);
thread(new HelloProducer(), false);
thread(new HelloConsumer(), false);
thread(new HelloProducer(), false);
Thread.sleep(1000);
thread(new HelloConsumer(), false);
thread(new HelloProducer(), false);
thread(new HelloConsumer(), false);
thread(new HelloConsumer(), false);
thread(new HelloProducer(), false);
thread(new HelloProducer(), false);
Thread.sleep(1000);
thread(new HelloProducer(), false);
thread(new HelloConsumer(), false);
thread(new HelloConsumer(), false);
thread(new HelloProducer(), false);
thread(new HelloConsumer(), false);
thread(new HelloProducer(), false);
thread(new HelloConsumer(), false);
thread(new HelloProducer(), false);
thread(new HelloConsumer(), false);
thread(new HelloConsumer(), false);
thread(new HelloProducer(), false);
} catch (Exception e) {
e.printStackTrace();
}

}

public static void thread(Runnable runnable,boolean deamon)
{
Thread brokerThread = new Thread(runnable);
brokerThread.setDaemon(deamon);
brokerThread.start();
}

}

========================================================================================================================================================

Now when we run the main class output shows as :

========================================================================================================================================================

Sent message 700549 : Thread-1
Sent message 7702079 : Thread-0
Received Hello world from Thread-0 : 10859927
Sent message 14397555 : Thread-10
Received Hello world from Thread-1 : 18709978
Sent message 12968500 : Thread-12
Received Hello world from Thread-10 : 28432383
Sent message 12606869 : Thread-20
Sent message 29596937 : Thread-24
Sent message 32819228 : Thread-25
Received Hello world from Thread-12 : 19520119
Received Hello world from Thread-20 : 17982827
Received Hello world from Thread-25 : 24829876
Sent message 10565194 : Thread-43
Sent message 32734483 : Thread-33
Received Hello world from Thread-24 : 23815485
Sent message 25663554 : Thread-40
Sent message 19368064 : Thread-46
Sent message 26051994 : Thread-36
Received Hello world from Thread-33 : 32729846
Received Hello world from Thread-46 : 3333237
Received Hello world from Thread-43 : 3117096
Received Hello world from Thread-40 : 11203640
Received Hello world from Thread-36 : 7522198

========================================================================================================================================================

When I open my web console then I can see queue TEST.FOO is created and messages are enqueued and dequeued.

I am trying to test some more examples with Active MQ and will keep posting the same.

Till then, Happy coding !! 🙂

Setting up a JDBC connection to Oracle 11g from java class

For setting up a JDBC connection , we need to have the following data primarily:

JDBC_DRIVER=”oracle.jdbc.driver.OracleDriver”;
DB_URL = “jdbc:oracle:thin:@localhost:1521:xe”;

This is for setting up connection to oracle 11g. For any other databases the DB_URL and the DRIVER may vary. Also  the URL pattern depends on the port and the database that we are trying to connect to and the details may be obtained in tnsnames.ora file in  <drive:\>oracleexe\app\oracle\product\11.2.0\server\network\ADMIN path


XE =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = Devashish-PC)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = XE)
)
)


Now comes the database username and password. If you already have a user created then you can skip this step else do the following:

1. In start menu in the oracle11g folder click on get started.
2. When prompted to enter the username type ‘system’ and password type ‘tiger’.
3. Localhost appears.
4. Click on application express.
5. Create the database user.

Suppose my user is created with credentials :

USER = “dev”;
PASS = “june”;

Now when the following steps has been performed. Go to eclipse and create a new project. Download ojdbc14 , configure buildpath and add as external jar.

Then the the code for connecting is :


final String JDBC_DRIVER="oracle.jdbc.driver.OracleDriver";
final String DB_URL = "jdbc:oracle:thin:@localhost:1521:xe";
// Database credentials
final String USER = "dev";
final String PASS = "june";
Connection con=null;
Statement stmt=null;
try {
Class.forName(JDBC_DRIVER);
con=DriverManager.getConnection(DB_URL,USER,PASS);
stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from tab");
System.out.println(rs.getFetchSize());
} catch (Exception e) {
e.printStackTrace();
}

It should return the no of tables fetched e.g. in my case it showed 10.

Happy coding  🙂

Threads Pools and Executor Service

In order to maintain the performance in a distributed system, we might require to limit the number of threads in a thread pool. We have two approaches:

Executor Service & Thread Pools .

I feel executor service is the easier approach whereas Thread Pools is required when we need customization.

Executor Service:

Executor Service is the child interface of Executor. Basically, we can create the following types if executor service as:

FixedThreadPool  :  To create a fixed number of threads, if more tasks are submitted then the idle threads in the thread pools the tasks will wait.

ScheduledThreadPool

CachedThreadPool : Threads will execute the task and are killed.

SingleThreadPool : Only one thread in the entire thread pool.

We just require to create an object of the Runnable/Thread type and submit it in the threadpool.

A sample code snippet is as follows:

ExecutorService executor= Executors.newScheduledThreadPool(5);

for(int i=0;i<10;i++)

{

Runnable worker=new WorkerThread(i);

executor.execute(worker);

}

executor.shutdown();

if (executor.isTerminated()) {

System.out.println(“Completed..”);

}

}

class WorkerThread implements Runnable

{

private int i;

public WorkerThread(int i) {

this.i=i;

}

@Override

public void run() {

System.out.println(Thread.currentThread().getName()+” Start= “+i);

System.out.println(Thread.currentThread().getName()+” End.”);

}

}

ThreadPoolExecutor:

Thread Pool Executor is perhaps a better approach where we have a lot of options.

ExecutorService threadPoolExecutor =        new ThreadPoolExecutor(corePoolSize,            maxPoolSize,keepAliveTime,TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(),                   threadFactory,rejectionHandler);

Let us see what the above parameters mean:

Core and maximum pool sizes :

When a new task is submitted in method , and fewer than corePoolSize threads are running, a new thread is created to handle the request, even if other worker threads are idle.

If there are more than corePoolSize but less than maximumPoolSize threads running, a new thread will be created only if the queue is full.

Keep-alive times :

If the pool currently has more than corePbeoolSize threads, excess threads will be terminated if they have been idle for more than the keepAliveTime.

Queuing:

Any blocking queue can be used to transfer and hold the submitted task such as a Synchronous Queue, a LinkedBlockingQueue or an ArrayBlockingQueue.

Thread Factory: A default thread factory can be used as

ThreadFactory threadFactory = Executors.defaultThreadFactory();

RejectedExecutionHandler : Implementation to handle the jobs that can’t fit in the worker queue.

For that we need to create a class which implements the RejectedExecutionHandler.

class RejectedExecutionHandlerImpl implements RejectedExecutionHandler

{

@Override

public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {

System.out.println(r.toString()+” is rejected”);

}

}

So we create the executor pool as:

ThreadPoolExecutor executorPool=new ThreadPoolExecutor(2, 4, 10,TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(2),threadFactory,rejectionHandler);

And then we add a new task in the thread pool as

executorPool.execute(new WorkerThread(3));

After all the tasks has been executed by the thread pool we should terminate the thread pool as executorPool.shutdown();