Sunday, 15 April 2018

How to read and write a CSV file using core java?


Hello Buddies.

CSV: CSV is a comma separated values file which allows data to be saved in a table structured format


Let's try to read a CSV file using java, filter out the required rows and create a new CSV per our own requirements.


Input - Provided as a path for the file having below details -


ID NAME AGE GENDER OCCUPATION ADDRESS
1 ABC 22 M SE IN
2 DEF 32 F SE US
3 ABC 12 M SE UK
4 DEF 42 F SE IN
5 ABC 52 M SE US
6 DEF 53 F SE UK
7 ABC 60 M SE IN
8 DEF 67 F SE US
9 ABC 74 M SE UK
10 DEF 81 F SE IN
11 ABC 88 M SE US








We will filter out the people living in India and will have a new CSV only for those people.

Here's a code snippet -

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CSVReader {

 private static String mainPath = "C:\\\\Users\\\\namit.sharma\\\\Downloads\\\\";

 public static void main(String[] args) throws IOException {

  FileReader fileReader = new FileReader(new File(mainPath + "sampleExcel1.csv"));

  BufferedReader bufferedReader = new BufferedReader(fileReader);

  String string;
  do {
   string = bufferedReader.readLine();
   if (null != string) {
    System.out.println(string);
    filterForIndians(string);
   }
  } while (null != string);

  bufferedReader.close();

 }

 private static void filterForIndians(String string) throws IOException {
  File file = new File(mainPath + "fileredCsv.csv");
  if (file.exists()) {
   file.delete();
  }
  FileWriter fileWriter = new FileWriter(new File(mainPath + "fileredCsv.csv"),true);
  if ("IN".equals(string.split(",")[5])) {
   BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
   bufferedWriter.write(string+"\n");
   bufferedWriter.close();
  }
 }

}


Now we can check the generated csv. It will have the desired rows -

1 ABC 22 M SE IN
4 DEF 42 F SE IN
7 ABC 60 M SE IN
10 DEF 81 F SE IN

How to count the number of leaves in a binary tree?


Hello Buddies.


Here's a quick code snippet for finding the number of leaves in a 'Binary Tree', after a node gets deleted!





Have a look-

Input -

5
-1 0 0 1 1
1


Input description -

Line 1: No. of nodes in Binary Tree
Line 2: All the nodes' parents, where -1 means no parent - root, 0 means root as parent.
Line 3: Node at which this value exists, remove it.


Node to remove -



public class TreeProblem {
 private static int count = 0;

 public static void main(String args[]) throws Exception {

  Scanner scanner = new Scanner(System.in);
  int numOfNodes = scanner.nextInt();
  scanner.nextLine();
  String intStr = scanner.nextLine();
  String[] array = intStr.split(" ");
  int[] arr = new int[array.length];
  for (int i = 0; i < numOfNodes; i++) {
   arr[i] = Integer.valueOf(array[i]);
  }
  int nodeToDelete = scanner.nextInt();

  // create a tree
  Node root = null;
  int valueIndex = 0;
  Node current = null;
  for (int i = 0; i < numOfNodes; i++) {
   if (arr[i] == -1) {
    root = new Node(valueIndex++);
    current = root;
   } else {
    if (arr[i] == current.value) {
     if (null == current.left) {
      current.left = new Node(valueIndex++);
     } else if (null == current.right) {
      current.right = new Node(valueIndex++);
      current = current.left;
     }
    }
   }
  }

  // scan the tree for deleting the node
  // it clearly means we have to ignore the leaves at that node, for the remaining
  // keep the count going

  treetraversal(root, nodeToDelete);

  System.out.println("Remaining leaves = " + count);
  scanner.close();
 }

 private static void treetraversal(Node root, int nodeToDelete) {
  if (null == root) {
   return;
  }
  System.out.println("-- " + root.value);
  if (root.value == nodeToDelete) {
   return;
  }
  if (null != root.left) {
   treetraversal(root.left, nodeToDelete);
  }
  if (null != root.right) {
   treetraversal(root.right, nodeToDelete);
  }
  if (null == root.left && null == root.right) {
   count++;
  }
 }

}

class Node {

 int value;
 Node parent, left, right;

 Node(int value) {
  this.value = value;
 }
}

Friday, 30 March 2018

SSH Tutorial - How to access UNIX server from WINDOWS client

Hello Buddies.

Here is a quick tutorial to get hands-on experience in accessing a remote machine.
It can either be a case of a remote machine being used as a server or as a storage location.

In case your remote machine is having Windows platform, things become really straightforward. Just need to use MSTSC – Remote login through your windows machine, enter the credentials, and boom, you are already on the remote machine!

Complications occur when the remote machine is UNIX based.

For the same, this tutorial will be based on the below scenarios –

  • Remote machine: UNIX based – here it’s Fedora
    • Remote machine will be hosting a simple HTML page
    • It will be using Apache HTTPD as the server
    • To enable access, it will use SSH
  • Client machine: Windows-based
    • It will use putty for SSH access
    • It will also update the HTML content of the remote server


Sounds interesting?
 Cool! Let’s begin the discussion.


All About Remote

Using Apache HTTP Server project here.

Install:         sudo dnf install httpd
Start:           sudo systemctl start httpd.service
Check:        using http://localhost.

The root directory of your web server is now situated at /var/www/html/ with root as the owner.

Comment out all the lines in /etc/httpd/conf.d/welcome.conf default page landing. 

Create an index.html file with your content in the /var/www/html/ directory:

<html>
    <head>
        <title>Hello world</title>
    </head>
    <body>
        Hello world!
    </body>
</html>

Now, when you visit http://localhost, you will see your new index page.

Yeah! It looks cool! Changes are picked up nicely and easily!


Can I access this web page from any other machine?


Here comes a tricky part. By default, each OS has restrictions over ports, and firewalls as well.
So, you need to, first of all, find the public IP of your system and allow access to a port that would be exposed.









In a UNIX machine, you can check the iptables, for the status of the ports.

  iptables -L

Also open the port 80, for the apache server.

  iptables -I INPUT -p tcp --dport 80 -j ACCEPT

For the IP address of the machine, use ifconfig.

Boom!

Hit the URL from any machine now – http://192.168.xx.xx:80

And you will see the content !!!





 







What if I want to change the content from my client machine?


Here comes another tricky part, that surely demands at least one hands-on experience.

  • Get openssh-server on your server machine 
    •  sudo dnf install openssh-server






  • Start the ssh service
    • sudo systemctl start sshd.service
  • By default, it will use port 22. Remember this!
  • Also, doing some authentication stuff here.
    • Use keygen command to generate an RSA private key at the server side.
    •  # ssh-keygen -t dsa
  • Save the key, for now, bypass the passphrase as empty.


Use the saved private key in your windows client now. How? 
Check this below!

  • Install putty in your windows client.
  • Open puttyGen.
  • Load the imported private key.
  • Open putty, enter the IP address of the server machine.
  • Remember the default port number? Yes, correct. It should be 22.


Hit it. Boom! You are in the server machine now.

Remember where your HTML content was being picked up from?
Yup, correct!

Update the content at /var/www/html/ 


















Refresh the web pages, and you will have new content with you.




















So, this was a quick one! Keep exploring.

And Happy coding!










Sunday, 25 February 2018

Multi-person chat application : Java Socket Programming and Multi-threading


Hello Buddies.


Core java has 2 great things that are generally ignored these days in day to day coding - Multi-threading and socket programming, by the coders like us.
Since these 2 are not encountered by most of us in projects, let's prepare a small app that can give us the hands on experience on the usage.

The concept:

2 persons or players 
1 server
Chat app that serves the clients in a round robin fashion


1. Let's begin with the server first.

To implement the server in the easiest manner possible I would be using java.net.ServerSocket
Something like this -

static ServerSocket ss = null;
...
      ss = new ServerSocket(6666);
...

Socket s = ss.accept();    
...
new DataInputStream(s.getInputStream());

So the plan is simple, create a socket, dedicate a port, read the input stream striking at the port.


2. Now the next step is to have a client prototype.

It would be using the same socket's port to create an output stream of data. Something like this -
...
Socket s = new Socket("localhost", 6666);
...
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
...
dout.writeUTF(playerInput);


So far, looks good.

Create a main() for server and one for the player. Run both, and you would see the message reaching the server.


Now, what if we are having multiple main() methods invoked for various players.

Do you think the app will run smoothly?

Well it won't!


Every main() has its own thread. As soon as that thread invokes socket connection via server socket's accept(), it acquires the lock over it, leading to other threads starving i.e. non availability of the resource.

So what can be done here?

As a good programmer, you can handle this scenario by identifying the risky code blocks and making them thread safe.

Use synchronized blocks, and run the threads for the server and all the players or clients interacting in a parallel fashion.

Have a look here .

I have put a sample project in this GIT repo which shows the generalized way of using multi-threading and socket programming, and avoids thread starvation.


Following is an extract from the readMe file of the same -


# simpleChatApplicationJava

Here's a brief console flow to understand how the chat application code works. Please note S, P1 and P2 denote the respective console screens for the server (or a common chat viewer), person1 and person2.



S:
<<<<<<<<<<<<<<< SERVER >>>>>>>>>>>>>>



P1:
<<<<<<<<<<<<<<< Player 1 >>>>>>>>>>>>>>

Hey player 1 Please enter your message for server - 



P2:
<<<<<<<<<<<<<<< Player 2 >>>>>>>>>>>>>>

Hey player 2 Please enter your message for server - 



S:
<<<<<<<<<<<<<<< SERVER >>>>>>>>>>>>>>

Player accepted!

Player accepted!



P1:
<<<<<<<<<<<<<<< Player 1 >>>>>>>>>>>>>>

Hey player 1 Please enter your message for server - 

Player1 here

Hey player 1 Please enter your message for server - 



S:
<<<<<<<<<<<<<<< SERVER >>>>>>>>>>>>>>

Player accepted!

Player accepted!

Player Input: Player1 here



P2:
<<<<<<<<<<<<<<< Player 2 >>>>>>>>>>>>>>

Hey player 2 Please enter your message for server - 

Player2 here

Hey player 2 Please enter your message for server - 



S:
<<<<<<<<<<<<<<< SERVER >>>>>>>>>>>>>>

Player accepted!

Player accepted!

Player Input: Player1 here

Player Input: Player2 here



P1:
<<<<<<<<<<<<<<< Player 1 >>>>>>>>>>>>>>

Hey player 1 Please enter your message for server - 

Player1 here

Hey player 1 Please enter your message for server - 

q

Player 1 no longer available!




S:
<<<<<<<<<<<<<<< SERVER >>>>>>>>>>>>>>

Player accepted!

Player accepted!

Player Input: Player1 here

Player Input: Player2 here

Player Input: q

ERROR: No input from player!




P2:
<<<<<<<<<<<<<<< Player 2 >>>>>>>>>>>>>>

Hey player 2 Please enter your message for server - 

Player2 here

Hey player 2 Please enter your message for server - 

q

Player 2 no longer available!




S:
<<<<<<<<<<<<<<< SERVER >>>>>>>>>>>>>>

Player accepted!

Player accepted!

Player Input: Player1 here

Player Input: Player2 here

Player Input: q

ERROR: No input from player!

Player Input: q

ERROR: No input from player!



When a person gives 'q' or 'Q' in the input, the connection breaks off.

You can use this basic functionality to incorporate more persons in the chat room or to create a backend for GUI based chat application.



Why don't you try playing around with this some more, and do let me know the challenges and experiences encountered!!

Happy coding!

Thursday, 9 November 2017

JAVA code to handle versions and the comparisons.

Hello Buddies.

Sharing a small but useful piece of code, that can help you in handling version strings and comparisons in day-to-day coding.

Many a time, we struggle while comparing and transcoding the versions, which might take some time and can be frustrating as well.

So for my reference, I am keeping this snippet handy, and so is for you.

Check out the full project here, OR you may refer to the code shared below.


Happy Coding!




 package versionCheckDemo;  
 /**  
  * @author namit  
  * @version 2.0  
  *   
  * re-checking-in for testing develop branch  
  *   
  * */  
 public class VersionTester {  
  public static void main(String[] args) {  
   System.out.println("Part 1 - Generalize the version numbers to a standard format - a.b.c");  
   String input = "1.1";  
   update(input);  
   input = "1.1.1";  
   update(input);  
   input = "1";  
   update(input);  
   System.out.println("Part 2 - Get the main digit representing the version number ");  
   input = "1.0.1";  
   findVersion(input);  
   input = "54.1";  
   findVersion(input);  
   input = "100";  
   findVersion(input);  
   input = "100.c.c";  
   findVersion(input);  
   input = "100.cc.&@!#$$";  
   findVersion(input);  
   System.out.println("Part 3 - Comparing the versions, under the format a.b.c ");  
   String versionX = "2.3";  
   String minVersion = "2.5.5";  
   checkVersion(versionX, minVersion);  
   versionX = "2.7.9";  
   minVersion = "2.5.5";  
   checkVersion(versionX, minVersion);  
  }  
  /**  
   * Method to update the version numbers to a uniform pattern  
   * */  
  private static void update(String input) {  
   System.out.println("incoming >> " + input);  
   int occurence = countMatches(input, '.');  
   if (occurence == 0)  
    input += ".0.0";  
   else if (occurence == 1)  
    input += ".0";  
   System.out.println("outgoing >> " + input);  
   System.out.println("---------------");  
  }  
  public static int countMatches(final CharSequence str, final char ch) {  
   if (null == str) {  
    return 0;  
   }  
   int count = 0;  
   char[] arr = ((String) str).toCharArray();  
   for (char c : arr) {  
    if (c == ch)  
     count++;  
   }  
   // likewise you can go for  
   // org.apache.commons.lang3.StringUtils.StringUtils.countMatches(str, ch)  
   // for saving time of writing the count logic  
   return count;  
  }  
  /**  
   * Method to find the main version number  
   * */  
  private static void findVersion(String input) {  
   System.out.println("Incoming >> " + input);  
   String inputWithoutDots = input.replace(".", "");  
   if (inputWithoutDots.matches("[0-9]+")) {  
    int version = 0;  
    String[] arr = input.split("\\.");  
    version = Integer.valueOf(arr[0]);  
    System.out.println("Success! outgoing >> " + version);  
   } else {  
    System.out.println("error!");  
   }  
   System.out.println("---------------");  
  }  
  /**  
   * Method to compare the given version with a minimum accepted version  
   * */  
  private static void checkVersion(String versionX, String minVersion) {  
   String minVersionFormatted = String.format("%-4s", minVersion.replace(".", "")).replace(' ', '0');  
   int minVersionNum = Integer.valueOf(minVersionFormatted);  
   String formattedVersion = String.format("%-4s", versionX.replace(".", "")).replace(' ', '0');  
   int versionXNum = Integer.parseInt(formattedVersion);  
   System.out.println("Min Version - "+minVersion);  
   System.out.println("You provided - "+versionX);  
   if (versionXNum >= minVersionNum) {  
    System.out.println("Version Accepted!");  
   } else {  
    System.out.println("Version Rejected!");  
   }  
   System.out.println("---------------");  
  }  
 }  


OUTPUT:

 Part 1 - Generalize the version numbers to a standard format - a.b.c  
 incoming >> 1.1  
 outgoing >> 1.1.0  
 ---------------  
 incoming >> 1.1.1  
 outgoing >> 1.1.1  
 ---------------  
 incoming >> 1  
 outgoing >> 1.0.0  
 ---------------  
 Part 2 - Get the main digit representing the version number   
 Incoming >> 1.0.1  
 Success! outgoing >> 1  
 ---------------  
 Incoming >> 54.1  
 Success! outgoing >> 54  
 ---------------  
 Incoming >> 100  
 Success! outgoing >> 100  
 ---------------  
 Incoming >> 100.c.c  
 error!  
 ---------------  
 Incoming >> 100.cc.&@!#$$  
 error!  
 ---------------  
 Part 3 - Comparing the versions, under the format a.b.c   
 Min Version - 2.5.5  
 You provided - 2.3  
 Version Rejected!  
 ---------------  
 Min Version - 2.5.5  
 You provided - 2.7.9  
 Version Accepted!  
 ---------------  


Featured post

JAVA based project, that can be used to hit DB using JDBC, from WSO2 ESB

Hi Buddies, Here is a small project that will enable you to hit MySQL DB using WSO2 ESB - https://github.com/namitsharma99/customM...

Popular Posts