Into the Web – Part 2

When we look into the code we write, we always go through an indefinite thought process and it stops at simple question in the end “How I can make it Better?”. The word “Better” will stay with you and it will give you some kind of superpower to analyze and breakdown the things you did and you will eventually find an even “Better” way to write the same code.

Now think the the scenario mentioned in the previous part where a server returns some content when client access the web application. Here we had only one static HTML file called “index.html” which always displays the “Hello World!” text.

Now apply the thought process. “How I can make it Better?”

Yes – It would be nice if the server responds with different content every time client sent a request to server. Say user should see a different greetings whenever client send the request –Sounds Good 🙂

Now we have a problem and we have to find a solution.We will see how to do this with the help of Servlets.

Understanding the Deployment Descriptor
As the name says, It describes how a web application should be deployed. Since we use Java language for writing the web application, the deployment descriptor is written using XML syntax and we name it as “web.xml” and store it in “WEB-INF” directory.

Our next step is adding a servlet information in the “web.xml” file. To do this we have two XML elements: servlet and servlet-mapping. We declare the servlet using the servlet element and specify the URL mapping using servlet-mapping element.

<servlet>
    <servlet-name>welcome_greeting</servlet-name>
    <servlet-class>GreetingServlet</servlet-class>
</servlet>

servlet-name element is used to give our servlet a meaningful name and servlet-class element is used to specify the actual servlet Java class (Without extension).

<servlet-mapping>
    <servlet-name>welcome_greeting</servlet-name>
    <url-pattern>/greetings</url-pattern>
</servlet-mapping>

servlet-name element is used specify the name of the servlet to which we can map the URL pattern which is specified using element url-pattern. The URL pattern we give here is used to resolve the URLs. Here we have used pattern “/greetings”. So if we apply URL “localhost:8080/helloword/greetings” we will see the response from our GreetingServlet. The complete “web.xml” file is given below.

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
 <!-- To save as "tomcat_home\webapps\helloworld\WEB-INF\web.xml" --> 
 <!-- Note: All <servlet> elements MUST be grouped together and placed IN FRONT of the <servlet-mapping> elements --> 
<servlet>
    <servlet-name>welcome_greeting</servlet-name>
    <servlet-class>GreetingServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>welcome_greeting</servlet-name>
    <url-pattern>/greetings</url-pattern>
</servlet-mapping>
</web-app>

That is all for today and we will see how to write the GreetingServlet class in the coming part using Java language and servlet API 🙂

Advertisements

Into the Web – Part 1

It all started a few months back that I was trying to create a java application to track my daily activities and to learn some of the interesting java libraries and frameworks. But during the process I realized that instead of focusing on desktop based applications, it would be nice if I develop a small web application for that. And the best part is I never explored web development too much and it was challenging, because web development is something big “The technologies used in web development”. All I knew was a set of HTML tags and basic JavaScript and some other areas.

As a first step I started searching in the internet and some of the books about the web application development. Meanwhile during the searching process I came across Servlets “It is basically an executable which runs on the server side”. I learned about the basics of servlets, the related java classes and finally the request response programming model. Like every beginner I started with the “Hello World” program. So here I would like to tell you about my first experience “A servlet which return some HTML content on request.

Setting up the Server
Every web application require a server and to setup a server in my local I used the Appache Tomcat. Tomcat is simply an open source Java servlet container. Download the latest version of the Tomcat server from http://tomcat.apache.org/.

  1. Install the latest stable version of tomcat server
  2. Create a project folder “C:\projects\” and extract the downloaded file here
  3. Rename the folder “apache-tomcat-8.5.**” to “tomcat”
  4. Now we have our tomcat home ready and we will refer directory “C:\projects\tomcat” as tomcat_home

Starting and Stopping the Server
Starting and stopping the tomcat server is easy. We do have two executable files under “tomcat_home\bin\” directory. To start we do use “startup.bat” and to stop we do use “shutdown.bat”
After starting the server we can test this by opening a browser session and typing in “localhost:8080/”. If we are getting a tomcat home page then you are done, the server is up and running. 🙂

Getting started with Web Application Development
Our web application require a root directory and we have to place this root directory under “tomcat_home\webapps\” directory. Let me tell you the steps one by one.

  1. Create a root directory called “helloworld” under “tomcat_home\webapps\” directory.
  2. Now create a new directory called “WEB-INF” under this root directory. We will store the web descriptor file under this directory
  3. Create a new directory called “classes” under the “WEB-INF” directory to store our servlet classes

Now create a new web deployment descriptor file named “web.xml”. The deployment descriptor works like a configuration file and it describe how the application or components should be deployed. The default content of the “web.xml” is given below.<!– Note: All elements MUST be grouped together and placed IN FRONT of the elements –>

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
 <!-- To save as "tomcat_home\webapps\helloworld\WEB-INF\web.xml" --> 
 <!-- Note: All <servlet> elements MUST be grouped together and placed IN FRONT of the <servlet-mapping> elements --> 
</web-app>

Okay, now we need to see if the setup is correct or not by restarting the server. If we are getting the below given messages in the console then we are good and our application is deployed successfully 🙂

29-Sep-2017 21:26:43.902 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [C:\Projects\tomcat\webapps\helloworld]
29-Sep-2017 21:26:43.933 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [C:\Projects\tomcat\webapps\helloworld] has finished in [30] ms

Accessing our Web Application
Once the server is up and running we can access the web application by issuing URL “localhost:8080/helloword/” where “8080” is the default port number. We can change this default port number by editing the “server.xml” file available under “tomcat_home\conf\” directory.

Now create a new HTML file “index.html” and save it under “tomcat_home\webapps\helloworld\” directory. In this HTML file we will write HTML tags that are required to display “Hello World” message. The structure of “index.html” is given below.

<html>
    <body>
        <h1>Hello World!</h1>
    </body>
</html>

After saving this file under application root directory which is “tomcat_home\webapps\helloworld”, open a new browser session and issue the below given URL

localhost:8080/helloworld/

Actually this one is a directory request and if out root directory have “index.html”, the server will redirect the request to “index.html” and the browser will display “Hello World!” message. 🙂 You can use the below given URL too.

localhost:8080/helloworld/index.html

That is all for today. We will see how to write a servlet class and use it to process a request and send a response in the next part of “Into the Web”.

Developing a Mini Calculator Part -4

Hello, this is the final part of article on Developing a Mini Calculator. Here we will see how different modules interact with each other and the importance of central module called “Core” in detail.

About Core module in detail

As I mentioned in the previous topics this module is most important part of our calculator application, because it maintain the application state and do connect other modules with each other using messaging system. Input service, output service, calculation logic and history recorder send message to and receive message from core module. Core module do the state change using the messages received from input service and calculation logic.

How Core and other modules work together ?

Input Service generate message based on the key pressed by the user and send the message to core module. The message will have identifier to identify the message, key details. Core will process the message, do some state change and send required messages based on the state change to other modules. Below I will give you a example simple scenario.c

Example: “65+56=”

So once user press “=” operator key calculator should display result “121”.

  1. User enter key 6: This will send message to core module. It will be store as first operand
  2. User enter key 5: Since no operator is entered, core will append “5” to previously entered number “6” and make “65” the first operand
  3. User enter “+” operator key: When processing this key press, core will do a state  that tell operator is entered now it will accept the second operand. If user press any other operator key to change the operation, this will be taken care by core module using the previous state change.
  4. The same way “56” will be accepted
  5. Now core have first operand, operator and second operand. If user press the next operator key (-,+,*,/), core will send a message to calculation logic including this details. Calculation logic do the required calculation and send back the result to core.
  6. The result given by calculation logic will be the new first operand. The same can be treated as final result as well based on the past input.
  7. In the above steps, core will send the state changes to output service. Output service will display the state changes received to screen.

THE END

Hope you liked the final part 🙂 .

Please access the previous topics here
Developing a Mini Calculator Part – 1
Developing a Mini Calculator Part – 2
Developing a Mini Calculator Part – 3

Developing a Mini Calculator Part-3

Hello, this is third part of Developing a Mini Calculator. Today’s topic will cover Input Service and Output service module. Please read Developing a Mini Calculator Part-2 for understanding about Calculation logic.

Input Service

Like I said in the first section, input service is responsible for two things and they are accepting right input and preventing user from entering an input that may cause application behavior inconsistent. Input service alone can take some decisions for preventing user inputs. But sometimes it is not possible and that decision making require application state.

Consider an example scenario “user pressing period or dot key”. I will explain how the decision making works

How input service alone take decisions?

  • When application start input service will unlock period key
  • If user press period key input service will lock the period key
  • When user press period key it will send a message to core module saying user pressed period key

How input service take decision with the help of core module

  • When user press backspace key after pressing period key, input service will send a message to core module. Core module will understand that user pressed backspace key and so do a state change and send back a message to input service. So by identifying this message from core, input service can enable or unlock the period key.

Output Service

Output service is responsible for managing the screen and doing this by showing allowed application state to the screen. Output service will do this with the help of core, because core manage the application state.

Consider an example scenario “user entering number ‘6.’ and press backspace key to delete the dot character”

Hitting backspace key will initiate a message from input service to core. Core do the necessary state change and send a message to input service. After this core will send a message to output service  to delete the dot character from screen.

Advantages

  • Once messages are defined we can use it uniquely across all modules
  • Each module can be managed independently
  • Since communication across modules are achieved using messages, so maintenance is easy

 

Here ends the third session on mini calculator development. Hope you liked it 🙂 . In next topic I will explain about core module and communication between different modules using messages 🙂

Creating Slide Show using Java

Today i was doing some search in my personal computer prior to formatting the hard disk and to take backup of important files and I came across a small java source code file. I wrote this code during my collage days and did it as part of the technical exhibition conducted by my college. As part of it I got a chance to prepare some presentation on game development basics and created some slides. All I wanted was to run this slides (images) in an equal interval of time, so it will run continuously in circular fashion without any user intervention. The program will load the predefined images using the file name and display it for three seconds and move it to next image. After reaching the the last image, it will start again from the first image. I would like to share the code here 🙂

Source Code

import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

class JavaSlider extends JPanel implements Runnable {
	
	private Thread sliderThread;
	private boolean active;
	private JFrame parent;
	
	public JavaSlider(JFrame parent) {
		super();
		sliderThread = new Thread(this);
		active = false;
		println("Panel created...");
		this.parent = parent;
	}
	
	public void setActive(boolean status) {
		println("Thread activated/deactivated...");
		active = true;
	}
	
	public Thread getThread() {
		return sliderThread;
	}
	
	public void start() {
		setActive(true);
		println("Thread started...");
		sliderThread.start();
	}
	
	@Override
	public void run() {
		int counter = 1;
		String name = "";
		while (active) {
			try {
				name = "slide" + counter + ".png";
				println("Loading file " + name + "...");
				BufferedImage image = ImageIO.read(getClass().getResource(name));
				println("Loaded file " + name + "...");
				parent.setSize(image.getWidth() + 4, image.getHeight() + 32);
				getGraphics().drawImage(image, 0, 0, image.getWidth(), image.getHeight(), this);
				if (++counter > 23) {
					println("Reseting counter...");
					counter = 1;
				}
				Thread.sleep(3000);
			} catch (IOException | InterruptedException ex) {
				println("Interrupted...");
			}
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		JFrame frame = new JFrame("Java Slider");
		JavaSlider panel = new JavaSlider(frame);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(960, 720);
		frame.setContentPane(panel);
		frame.setResizable(false);
		frame.setVisible(true);
		frame.setLocation(0, 0);
		frame.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent we) {
				panel.setActive(false);
			};
		});
		panel.start();
		panel.getThread().join();
	}
	
	public static void println(String message) {
		System.out.println(message);
	}
}

Game Development Season 1

Hello, today I am going to show you how to develop a computer game where character run continuously along a straight road collecting points and avoiding obstacles.

What are the things required while developing this type of game?

Character development

The game have a main character. We have to give a proper behavior.

  • Character can jump left or right, jump over the obstacles, slide under obstacles.
  • Character will die when hit the obstacles and so game will end.
  • Character can collect points from the road by hitting them.

World

World is where we have everything in picture. The road, points, obstacles and main character. The obstacles are vehicles and hurdles. The main character have to jump over vehicles and slide under the hurdles. Or simply jump left or right. The road will have three lines. Where vehicles move towards main character.

If you look close to such games you will see the main character is not moving forward or backward. That is the magic. The other things are actually moving. Got it?

Getting in to the Picture

The objects are created and placed in the world continuously in equal time interval in different patterns. This includes points or coins and obstacles. If you look at any such game you will find this pattern and the same pattern can come more than once.

Each time interval a pattern generator create patterns and based on the pattern objects will be placed in the world. At first the pattern is created for obstacles. Secondly the pattern is created for coins or points. While generating the second pattern we have to consider the pattern of obstacles. Got it?

The reason we are doing this is simple. When coins are placed in the world, ten or less coins can be placed in the line in an interval. We place coins continuously one by one. Say if the next position is occupied by an obstacle, we can place coin over the obstacle if it is a vehicle or do like this for hurdles by placing coins under hurdles. You got the picture right?

Once we finalize the patterns for the current time interval we can use the pattern to place the objects in the world and they will move towards main character 🙂 . In these type of games pattern generation is important. Patterns must be created without continuously repetition. If we generate same pattern continuously, it will be boring. We can customize the patterns on demand by giving behaviors and look and feel.

Hope this tutorial gave you a small idea about running games 🙂

Developing a Mini Calculator Part-2

Hello, this is a continuation of article on Developing a Mini Calculator Part-1. In the first part I have explained about the components required for this application. Today we will see the implementation of Calculation Logic.

Note: I will be using Java programming language to demonstrate the examples

Calculation Logic

Since our calculator only support four operations and each of them take two operands and one operator it will be easy for us to write one single procedure or method which do all the necessary operation and return the result

public static double doCalculate(double operand1, char operator, double operand2) {
    double result = 0.0;
    switch (operator) {
        case '+': result = operand1 + operand2; break;
        case '-': result = operand1 - operand2; break;
        case '/': result = operand1 / opernad2; break;
        case '*': result = operand1 * operand2; break;
    }
    return result;
}

The above given method is seems good but what will happen if you divide a number with zero. Yes of course division by zero is not possible. In that case what we will do. One way is to insert an error handling code that do the required when such and error comes. Again think of other scenario where the result is infinity or not a number. What we will do again insert some logic to handle that scenario.

Instead of keeping all calculations in one method we can separate them, like one method for addition, one four subtraction etc. Each of them will take three arguments and return the expected result.

public static double doCalculate(double operand1, char operator, double operand2) {
    double result = 0.0;
    switch (operator) {
       case '+': result = doAddition(operand1, operand2); break;
       case '-': result = doSubtraction(operand1, operand2); break;
       case '/': result = doDivision(operand1, operand2); break;
       case '*': result = doMultiplication(operand1 * operand2); break;
    }
    return result;
}

private static double doAddition(double operand1, double operand2) {
    return (operand1) + (operand2);
}

private static double doSubtraction(double operand1, double operand2) {
    return (operand1) - (operand2);
}

private static double doDivision(double operand1, double operand2) {
    return (operand1) / (operand2);
}

private static double doMultiplication(double operand1, double operand2) {
    return (operand1) * (operand2);
}

Now we can manage each operation logic separately, say for division we can add extra error handling code

private static double doDivision(double operand1, double operand2) {
    double result = 0.0;
    try {
        result = operand1 / operand2;
    catch (ArithmeticException ex) {
        // set some flag to indicate this error
    }
    if (new Double(result).isNaN()) {
        // set some flag to indicate this
        result = 0.0;
    } else if (!Double.isFinite(result)) {
        // set some flag to indicate this
        result = 0.0;
    }
    return result;
}

If we look at the above program we will see two things. If the division leads to error we will set some flag and return zero. If the result is not a number or infinite we do the same. The flag might be some where else in the program. We have to introduce a state change some where out side the calculation logic. This is okay! because it doesn’t harm anything.

Instead of changing the state out side the calculation logic we can simply return the entire result out side the calculation logic. Say, the result, is it valid?, is it infinite?, is it an error. How we will do this?

public class Result {
    private double value;
    private boolean error;
    private boolean finite;
    private boolean nan;
    
    public Result() {
        // initialize to default
    }
    // get and set methods will come here
}

We can create a new Result object to do this. This object will keep all the information related to the operation carried out. The Calculation Logic simply return the final result with necessary information to process the result. So an external module say Core can process the result as required without worrying about the calculations 🙂

Calculation Logic: Do the required calculations and return the result
Core: Process the result and take the necessary actions

private static Result doDivision(double operand1, double operand2) {
    Result result = new Result();
    double value = 0.0;
    try {
        value = operand1 / operand2;
    catch (ArithmeticException ex) {
        result.setError(true);
    }
    result.setValue(value);
    if (new Double(value).isNaN()) {
        result.setNaN(true);
    } else if (!Double.isFinite(result)) {
        result.setFinite(false);
    }
    return result;
}

Here ends the second part. Hope you like it 🙂

In the next part we will see the implementation of other modules.