Monday, December 16, 2019

How to create HTTP Server in Java - ServerSocket Example


How to create HTTP Server in Java - ServerSocket Example
Java has a very good networking support, allows you to write client server application by using TCP Sockets. In this tutorial, we will learn how to create a simple HTTP Server in Java, which can listen HTTP request on a port let's say 80 and can send response to client. Being an HTTP Server, you can connect to it using your browser e.g. Chrome, Firefox or Internet Explorer. Though HTTP is ubiquitous and present everywhere, Java doesn't have a dedicated API to create and parse HTTP request, there is no in built HTTP client library in JDK. Though there is no short of good open source library e.g. you can use Jsoup to parse HTML and can use Apache HttpClient library for sending GET and POST request right from your Java program. By the way, for those who wants to master network programming in Java, I suggest to read Java Network Programming, 4th Addition by Harold, Elliotte Rusty, its very comprehensive and not only covers both TCP/IP and UDP protocols, which are backbone of internet but also dive deep into the HTTP protocol, including REST, HTTP headers, and cookies. Book is very focused on practical and you will find lot of interesting example related to common networking task e.g. writing multi-threaded servers, using non blocking IO and using low level socket classes.

How to make HTTP Server in Java
First step to create a web server is to create a network socket which can accept connection on certain TCP port. HTTP server usually listen on port 80 but we will use a different port 8080 for testing purpose. You can use ServerSocket class in Java to create a Server which can accept requests, as shown below


import java.net.ServerSocket;
public class SimpleHTTPServer {

  public static void main(String[] args) throws Exception {
    final ServerSocket server = new ServerSocket(8080);
    System.out.println("Listening for connection on port 8080 ....");
    while (true){
      // spin forever
    }
  }

}

That's enough to create a web server in Java. Now our server is ready and listening for incoming connection on port 8080. If you connect to http://localhost:8080 from your browser, the connection will be established and browser will wait forever. Don't believe? compile and try it now.
If your browser is smart and giving up after waiting for sometime then try telnet command. You should be able to connect to server and as soon as you stop your server telnet will show that "could not open connection to the host, on port 8080: connect failed" as shown in following screenshot.



So now we have a server which is listening for connection on port 8080 but we are not doing anything with incoming connection but we are not rejecting them either. All of them are waiting to be served and stored inside server object. Do you see the while(true) loop? Any guess why we have that? This allows us to keep our program running, without this infinite loop our program will finish execution and server will be shutdown.

Now let's write code to start accepting connections. In Java, you can accept incoming connection by blocking call to accept() method, as shown below :

final Socket client = server.accept();

This is a blocking method and blocks until a client connects to the server. As soon as a client connect it returns the Socket object which can be used to read client request and send response to client. Once you are done with client you should close this socket and get ready to accept new incoming connection by calling accept() again. So basically, our HTTP server should work like this:


import java.net.ServerSocket;
import java.net.Socket;
public class SimpleHTTPServer {

  public static void main(String args[] ) throws Exception {
    final ServerSocket server = new ServerSocket(8080);
    System.out.println("Listening for connection on port 8080 ....");
    while (true) {
      final Socket client = server.accept();
      // 1. Read HTTP request from the client socket
      // 2. Prepare an HTTP response
      // 3. Send HTTP response to the client
      // 4. Close the socket
    }
  }
}

This is the standard HTTP Server, its simple because HTTP is stateless, which means it doesn't need to remember previous connection, all it care for new incoming connections. This is endless cycle until server is stopped. Now let's see what is coming from browser in form of HTTP request. When you connect to http://localhost:8080,your browser will send a GET HTTP request to the server. You can read the content of request using InputStream opened from the client socket. It's better to use BufferedReader because browser will send multiple line. Here is the code to read request in your HTTP Server :


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleHTTPServer {

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

        ServerSocket server = new ServerSocket(8080);
        System.out.println("Listening for connection on port 8080 ....");
        while (true) {
            Socket clientSocket = server.accept();
            InputStreamReader isr =  new InputStreamReader(clientSocket.getInputStream());
            BufferedReader reader = new BufferedReader(isr);
            String line = reader.readLine();           
            while (!line.isEmpty()) {
                System.out.println(line);
                line = reader.readLine();
            }
        }
    }

}

When you connect to this server using Firefox it will spin endlessly but on server side you will see following lines on your console :


Listening for connection on port 8080 ....
GET / HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:36.0) Gecko/20100101 Firefox/36.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive

Our HTTP client (the Firefox browser) passes this text to our HTTP server written in Java. You can see that request type is GET and protocol used here is HTTP/1.1.

So now our server is not only listening for connection, but accepting it and also reading HTTP request. Now only thing remaining is to send HTTP response back to the client. To keep our server simple, we will just send today's date to the client. Let's see how we can do that. In order to send response, we need to get the output stream from socket and then we will write HTTP response code OK and today's date into stream.


import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

/**
 * Java program to create a simple HTTP Server to demonstrate how to use
 * ServerSocket and Socket class.
 *
 * @author Javin Paul
 */
public class SimpleHTTPServer {

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

        ServerSocket server = new ServerSocket(8080);
        System.out.println("Listening for connection on port 8080 ....");
        while (true) {
            try (Socket socket = server.accept()) {
                Date today = new Date();
                String httpResponse = "HTTP/1.1 200 OK\r\n\r\n" + today;
                socket.getOutputStream().write(httpResponse.getBytes("UTF-8"));
            }
        }
    }

}

When you run the above program in Eclipse or from command line and connect to the http://localhost:8080 from Firefox,
you will see following response :
Sun Mar 29 13:32:26 GMT+08:00 2015

Which is today's date. It means our HTTP Server is working properly, it is listening on port 8080, accepting connection, reading request and sending response. By using try-with-resource statement of Java 7, we have also simplified our code, because socket will automatically closed by Java once you are done with response. Only limitation of this server is that it can serve one client at a time. If request processing takes longer time, which is not in our case, the other connection has to wait. This problem can be solved by using threads or Java NIO non blocking selectors and channels.



That's all about how to create HTTP server in Java. This is a good example to learn network programming in Java. You have learned how to use ServerSocket and Socket class from this example. Remember, ServerSocket is used to receive connections in Server application and Socket is used to send and receive data from individual client.



Friday, November 15, 2019

File Changes WatchService - When a file is updated in java


import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.stream.Collectors;

public class DirectoryWatchDemo {
public static void main(String[] args) {
try {
WatchService watcher = FileSystems.getDefault().newWatchService();
Path dir = Paths.get("D:\\WatchService");
dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
System.out.println("Watch Service registered for dir: " + dir.getFileName());
long initialCount = 0;
while (true) {
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException ex) {
return;
}

for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();

@SuppressWarnings("unchecked")
WatchEvent<Path> ev = (WatchEvent<Path>) event;
Path fileName = ev.context();

String filePath = dir.toString() + "\\" + fileName;

BufferedReader br1 = new BufferedReader(new FileReader(filePath));
long thisCount = br1.lines().count();
if (thisCount != 0) {

BufferedReader br2 = new BufferedReader(new FileReader(filePath));
System.out.println(br2.lines().skip(initialCount).collect(Collectors.toList()));
br2.close();
initialCount = thisCount;
}
br1.close();
/*
* if (kind == ENTRY_MODIFY &&
* fileName.toString().equals("DirectoryWatchDemo.java")) {
* System.out.println("My source file has changed!!!"); }
*/
}

boolean valid = key.reset();
if (!valid) {
break;
}
}

} catch (IOException ex) {
System.err.println(ex);
}
}
}

Output:
File in the Directory: D:\\WatchService\\ExampleText.txt

Watch Service registered for dir: WatchService
[Good Morning, How are you ?, Where are you going ?, When will you come?, GGood, Check, Good , Check, Show, Love You, Told you, Tuuu]
[]
[]
[Good]

Sunday, October 6, 2019

Login to MySQL Server in Ubuntu 18.0 .

Login to MySQL Server in Ubuntu 18.0 .

In the latest versions of the MySQL Server in Ubunte 18.0 .
Login to MySQL Server process is changed .
So, first we have to find the password  in the following way and then need to login to the MySQL Server.


nagaraju@nagaraju:~$ sudo cat /etc/mysql/debian.cnf
# Automatically generated for Debian scripts. DO NOT TOUCH!
[client]
host     = localhost
user     = debian-sys-maint
password = LnW2fO2BdFpjj62L
socket   = /var/run/mysqld/mysqld.sock
[mysql_upgrade]
host     = localhost
user     = debian-sys-maint
password = GoodMan
socket   = /var/run/mysqld/mysqld.sock

nagaraju@nagaraju:~$ mysql -u debian-sys-maint -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.27-0ubuntu0.18.04.1 (Ubuntu)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.


mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

mysql>

Friday, July 26, 2019

Rest API Response Types and Required Keys and Optional Keys


When setting up a JSON API, you'll have all kinds of different types of calls and responses. Send separates responses into some basic types, and defines required and optional keys for each type:
Type
Description
Required Keys
Optional Keys
success
All went well, and (usually) some data was returned.
status, data
fail
There was a problem with the data submitted, or some pre-condition of the API call wasn't satisfied
status, data
error
An error occurred in processing the request, i.e. an exception was thrown
status, message
code, data

Thursday, July 4, 2019

Eclipse Shortcut for Ubuntu Unity

Eclipse Shortcut for Ubuntu Unity

a shortcut to run Eclipse on Ubuntu Unity and to register Eclipse with the left Launcher

Installation

In your terminal,
cd ~/.local/share/applications
wget https://gist.github.com/raw/2922285/eclipse.desktop
chmod u+x eclipse.desktop
vim eclipse.desktop
# edit eclipse.desktop to replace "<ECLIPSE_DIR>" with your eclipse directory

Register Eclipse with Unity Launcher

  1. In your terminal, xdg-open ~/.local/share/applications to open the directory with the file browser
  2. Drag and drop the eclipse.desktop on Unity Launcher
# Eclipse Shortcut
# https://gist.github.com/2922285
[Desktop Entry]
Type=Application
Name=Eclipse
Comment=Eclipse Integrated Development Environment
Icon=<ECLIPSE_DIR>/icon.xpm
Exec=<ECLIPSE_DIR>/eclipse
Terminal=false
Categories=Development;IDE;Java;
StartupWMClass=Eclipse

Reference:

Friday, June 21, 2019

Example Remote Java Application Debugging

Step 1:

Create a Runnuable Jar file.

Step 2:

Run the Jar file as following:

java -Xdebug -Xrunjdwp:transport=dt_socket,address=0.0.0.0:8000,server=y,suspend=y -jar jar file

Example:



Step 3 : Eclipse Configurations and running.

Note : we should check the IP Address , Port Number is same .. Otherwise Debug will not work.
When you click on debug then the Jar fill will start running.
When we keep debug point then the Application will stop at the point.



Saturday, May 11, 2019

Having doubt and continuing a work

Experience : 

  • One day, I have given my bike for service in the morning . 
  • They have completed the service and i have started to servicing center to bring my bike.
  • When I started , There is raining and I have reached to servicing center by bus with helmet.
  • I have taken bike and started to come to home.
  • There is heavy raining and even though i am come to home . 
  • My mind have a doubt that I have mobile and it may be damaged because of the rain. 
  • But, i did not listen because of the mobile pouch. 
  • I have reached home and checked the mobile then i came to know that my mobile's sound is coming differently compared to previous sound.

Lesson :  Whenever , we have doubt on that we have to get clarity and that doubt and then go ahead. 

Effect of Postpone in Life

Experience : 

  • One day I came from Office and being ready to go to my home town.
  • On that day in my home water is going empty in the cans. 
  • So, my mind suggest me to bring the new water cans.
  • But , I did not listen to that and wasted my time and left home to home town.
  • I have completed some work at home town and come back to Bangalore on Sunday night .
  • I have went  to Office and come back in the evening.
  • Started preparing dinner then I came to know that cans are empty. So, I have called immediately to  cans to supplier . He told that there is raining so that it will take some time to deliver.
  • At this time, it take 3 hours to the cans supplier to come to my home and deliver the water.
  • I have realized at that moment , that because of postponement of water bringing before going to hometown, this happens.
Lesson:  we should not postpone of any work , if possible. if we do not do the work at that time , then when we have to do that work when we are busy.        

Monday, April 1, 2019

JsUnit is a Unit Testing framework for client-side (in-browser) JavaScript

JsUnit is a Unit Testing framework for client-side (in-browser) JavaScript. It is essentially a port of JUnitto JavaScript. Also included is a platform for automating the execution of tests on multiple browsers and mutiple machines running different OSs. Its development began in January 2001.

Download the jsunit
http://www.jsunit.net/

Test Procedure

Step 1 : run(double click) testRunner.html which is located in the  jsunit/testRunner.html.




Step 2 : Need to add the test case html page (already this frame work has some test html files in the location : jsunit/tests/*)and click on the run button from the opened testRunner. (in my case, Google Chrome is not showing me Run, Stop buttons. So, I have tested with FireFox Browser and Internet Explorer).





Documenting your javascript code like a pro, setting up JSdoc

Please find the following link ,
Explains clearly about the documentation of javascript code.

https://www.youtube.com/watch?v=Yl6WARA3IhQ

https://github.com/JSCasts-episodes/ep1-jsdoc


Saturday, February 23, 2019

Why are prime numbers important in real life? What practical use are prime numbers?

Primes have properties of uniqueness such that multiplying primes together produce unique results, for example multiply 3*7=21 which is a unique method for creating 21.
Uniqueness is a confusing term in mathematics. To me, uniqueness describes a unique path or vector to reach a specific point.
You can exploit that concept using small primes for creating an efficient database. In fact the first program I ever wrote back in the early eighties had used such a method in a phone book program.
I was trying to create a phone book program that could filter records into multiple different groups or multiple different phone books such as coworkers, friends, clients, church group, poker players, etc. One record could exist in multiple groups, but each record should only be stored once such that if the number was to change for that person, it would only require changing the number once in a master database that contained every record.
How this worked was to assign a prime number to each phone book. Records would be assigned to each phone book by taking the factors of those primes.
For example, let’s say that Bob is a friend, a coworker, and a poker player. The phone book for friends had the prime number 2 assigned to it, coworkers was assigned the prime number 3, and poker players had the prime 7 assigned to it. Then Bobs record would have the number 2x3x7 = 42 linked to it’s record.
Then when I decide to have a poker game and look up poker players to invite to the game, it would search the factors linked to all records for numbers evenly divisible by 7 to display only the records of poker players.
I guess the same concept was later used for digital security only applied in a kind of inside out way where only 2 large primes were used and the idea was to create semiprime index that was so large that they became prohibitively unsolvable for finding their primes based on using math due to computers being so dumb at doing arithmetic for large numbers.
They call it a complexity issue, I would call it something else because its not really that complex. It’s just doing something simple lots and lots of times.

Friday, February 8, 2019

git stash - How to Save Your Changes Temporarily

git stash - How to Save Your Changes Temporarily

There are lots of situations where a clean working copy is recommended or even required: when merging branches, when pulling from a remote, or simply when checking out a different branch.
The "git stash" command can help you to (temporarily but safely) store your uncommitted local changes - and leave you with a clean working copy.

git stash: a Clipboard for Your Changes

if you have to switch context - e.g. because you need to work on an urgent bug - you need to get these changes out of the way. You shouldn't just commit them, of course, because it's unfinished work.
This is where "git stash" comes in handy:
our working copy is now clean: all uncommitted local changes have been saved on this kind of "clipboard" that Git's Stash represents. You're ready to start your new task (for example by pulling changes from remote or simply switching branches).

Continuing Where You Left Off

As already mentioned, Git's Stash is meant as a temporary storage. When you're ready to continue where you left off, you can restore the saved state easily:
The "pop" flag will reapply the last saved state and, at the same time, delete its representation on the Stash (in other words: it does the clean-up for you).

Recent Post

Databricks Delta table merge Example

here's some sample code that demonstrates a merge operation on a Delta table using PySpark:   from pyspark.sql import SparkSession # cre...