Showing posts with label TechPosts. Show all posts
Showing posts with label TechPosts. Show all posts

Friday, 4 March 2016

Creating and Deploying Servlet without using Eclipse

This tutorial will guide you how to create and deploy Servlet without using Eclipse IDE.

Step 1. Download Tomcat : Tomcat is an application server from the Apache Software Foundation that executes Java servlets and renders Web pages that include Java Server Page coding.
Download latest release of Tomcat https://tomcat.apache.org/download-80.cgi
Step 2. Configure Tomcat : Unzip the tomcat package to C (or other) drive in my case it is D:\software\apache-tomcat-7.0.65-windows-x64\apache-tomcat-7.0.65

Now setup the JAVA_HOME, CATALINA_HOME, PATH environment variable:

Creating JAVA_HOME :
Click on -> Control Panel -> System -> Advanced->Environment Variable in User variables tab add new variable name:  JAVA_HOME and variable value :  C:\ "top level directory of your java install"
eg: variable name JAVA_HOME
      variable value :  C:\Program Files\Java\jdk1.8.0_40
      Note: Separate variable values by semicolon, if other value already exists(;)

Creating CATALINA_HOME :
Click on -> Control Panel -> System -> Advanced->Environment Variable in User variables tab add new variable name:  CATALINA_HOME and variable value :  C:\ "top level directory of your Tomcat install"
eg: variable name CATALINA_HOME :
      variable value :  D:\software\apache-tomcat-7.0.65-windows-x64\apache-tomcat-7.0.65
      Note: Separate variable values by semicolon, if other value already exists(;)

Appendng PATH :
Click on -> Control Panel -> System -> Advanced->Environment Variable in User variables tab select path variable and click on edit button. In variable value section give a semicolon and at the end paste the following text : %PATH%;%JAVA_HOME%\bin;%CATALINA_HOME%\bin

Step 3. Starting Tomcat: Go to the location of startup.bat D:\software\apache-tomcat-7.0.65-windows-x64\apache-tomcat-7.0.65\bin and double click on startup.bat
Now go to the browser and give url as localhost:8080 it should bring the apache tomcat home page.


Step 4. Creating Directory structure;
Step 5. Creating Servlet:

import javax.servlet.http.*;  
import javax.servlet.*;  
import java.io.*; 

public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
pw.println("<html><body>");
pw.println("Welcome to servlet");
pw.println("</body></html>");
pw.close();
}
}

Step 6. Compiling Servlet:
Go the directory containing DemoServlet and compile DemoServlet using servlet-api.jar.
eg: javac -classpath "D:\software\apache-tomcat-7.0.65-windows-x64\apache-tomcat-7.0.65\lib\servlet-api.jar" "DemoServlet.java"
Copy the DemoServlet.class file to the classes directory.

Step 7. Creating Deployment Descriptor:

<web-app>
  
<servlet>
     <welcome-file-list>
    <welcome-file>index.html</welcome-file>
   <welcome-file>default.html</welcome-file>
    </welcome-file-list>  
    <servlet-name>demo</servlet-name>  
    <servlet-class>DemoServlet</servlet-class>  
</servlet>  
  
<servlet-mapping>  
    <servlet-name>demo</servlet-name>  
    <url-pattern>/demoPage</url-pattern>  
</servlet-mapping>  
  
</web-app> 


Step 8. Deploying application to server:

Method 1-> Copy the application folder (here it is context root) to the apache tomcat's webapps directory for example I copied inside D:\software\apache-tomcat-7.0.65-windows-x64\apache-tomcat-7.0.65\webapps

Method 2->  Create WAR of your application and deploy it to tomcat through browser.
eg: Creating WAR, in cmd do  D:\myPrograms\servlets\web-app>jar -cvf myProject.war *
      Upload myProject.war and deploy in Tomcat server.

Step 9. Access the Servlet through URL: http://localhost:8084/myProject/demoPage



Sunday, 28 February 2016

Understanding hashCode and equals contract

When it comes to storing objects in a hashMap, we must follow the contract between hashCode() and equals(). The contract says:

  1. If two objects are equal, then they must have the same hash code.
  2. If two objects have the same hash code, they may or may not be equal.
or in other words
If equal, then same hash codes too.
Same hash codes no guarantee of being equal.

Lets see the scenarios what happens when we deal with object in hashMap:
import java.util.HashMap;

// Scenario 1 : Neither of  equals() or hashCode() is overridden 
import java.util.*;
 class Apple {
private String color;
public Apple(String color) {
this.color = color;
}
  public static void main(String[] args) {
Apple a1 = new Apple("green");
Apple a2 = new Apple("red");
//hashMap stores apple type and its quantity
HashMap<Apple, Integer> m = new HashMap<Apple, Integer>();
m.put(a1, 10);
m.put(a2, 20);
System.out.println(m.get(new Apple("green")));
}
}

The out put is simply "null" (of course which is not expected)
The reason is when we are calling m.get(new Apple("green")), the hash created by hashCode() would be different as its will hold a different memory location. So it will not be available in the hash table bucket.

// Scenario 2 : Overriding equals() 
import java.util.*;
 class Apple {
private String color;
public Apple(String color) {
this.color = color;
}
      //overriding equals
public boolean equals(Object obj) {
if(obj==null) return false;
if (!(obj instanceof Apple))
return false;
if (obj == this)
return true;
return this.color.equals(((Apple) obj).color);
}

  public static void main(String[] args) {
Apple a1 = new Apple("green");
Apple a2 = new Apple("red");
//hashMap stores apple type and its quantity
HashMap<Apple, Integer> m = new HashMap<Apple, Integer>();
m.put(a1, 10);
m.put(a2, 20);
System.out.println(m.get(new Apple("green")));
}
}

Still the out put is  "null" (again which is not expected)
Reason: Here we broke the contract of hashCode() and equals(). We must override hashCode() when we override equals(). Because the default behavior of equals() is to compare memory of the objects. When we are overriding the behavior of equals this will change the default behaviour..which leads to breaking the contract between hashCode() and equals(){If two objects are equal, then they must have the same hash code.}

// Scenario 3 : Overriding both equals() and hashCode() {Correct scenario}

import java.util.*;
 class Apple {
private String color;
public Apple(String color) {
this.color = color;
}
      //overriding equals
public boolean equals(Object obj) {
if(obj==null) return false;
if (!(obj instanceof Apple))
return false;
if (obj == this)
return true;
return this.color.equals(((Apple) obj).color);
}
     //overriding hashCode
public int hashCode(){
return this.color.hashCode();
}

  public static void main(String[] args) {
Apple a1 = new Apple("green");
Apple a2 = new Apple("red");
//hashMap stores apple type and its quantity
HashMap<Apple, Integer> m = new HashMap<Apple, Integer>();
m.put(a1, 10);
m.put(a2, 20);
System.out.println(m.get(new Apple("green")));
}
}

Now hope you hape a better understanding why we should override hashCode() and equals() while dealing with hashMap and objects.
References:

Saturday, 19 December 2015

Understanding virtual function in CPP

A function declared with keyword virtual is called virtual function. Virtual functions are handy when classes are Polymorphic i.e when child class and parent classes have functions with same name.
Let's understand the problem when we don't use virtual function.

#include<iostream>
using namespace std;
class Parent{
public:
void showMe(){
cout<<"\nParent is showing!";
}
};

class Child: public Parent{
public:
void showMe(){
cout<<"\nChild is showing!";
}
};

int main(){
Parent *parentPointer;
parentPointer = new Parent();
parentPointer->showMe();//its calling Parent->showMe()//

parentPointer = new Child();
parentPointer->showMe(); //it is also calling Parent->showMe()//
return 0;
}

Output:
Parent is showing!
Parent is showing!

When we don't declare Parent class function as a virtual, compiler does early binding which means for all the direct function references compiler will replace the reference with actual address of the method.
Now let's declare the Parent class function as a virtual

#include<iostream>
using namespace std;
class Parent{
public:
virtual void showMe(){
cout<<"\nParent is showing!";
}
};

class Child: public Parent{
public:
void showMe(){
cout<<"\nChild is showing!";
}
};

int main(){
Parent *parentPointer;
parentPointer = new Parent();
parentPointer->showMe();//it is calling Parent->showMe()//

parentPointer = new Child();
parentPointer->showMe(); //Now it is calling Child->showMe()//
return 0;
}

Output:
Parent is showing!
Child is showing!

When we declare the base class function as virtual, the function call using a Parent reference, as in shown in second example, compiler does not know which method will get called at run time. In this case compiler will replace the reference with code to get the address of function at run-time.

Why do we need to use Parent class pointer, cant we just declare Child class pointer itself and call the respective function instead declaring  virtual function?

Valid question, but consider a scenario when we have a Parent class Animal and Children classes Dog, Cat, Rat, Fox etc, each one has one common function says():
Now we have a function which demonstrates how individual animal sounds which will accept Parent class point because it has to access each of it's child class function;

void animalSound(Animal *pointer){
    pointer->says();
}

If we want animalSound function to call the child class function, we need delay the binding of early binding by declaring Animal class says() function as virtual.




Saturday, 26 September 2015

How to clear interview in core IT companies

Hellow there, want to get into the flex muscle companies. Tight your waist, take deeeep breadth, kill the procrastination, listen carefully what I'm gonna say next. Because if the follow that up, within four months, definitely you are gonna land into your dream company..

First 15 days:

Try to do these in the prescribed order and hopefully you wont feel any difficulty.
Algorithm Lectures from MIT:(15 Days).
Do coding as well which clears concept in better way.

https://www.youtube.com/watch?v=JPyuH4qXLZ0&list=PL8B24C31197EC371C

https://www.youtube.com/watch?v=HtSuA80QTyo&list=PLUl4u3cNGP61Oq3tWYp6V_F-5jb5L2iHb

After completion of this you will have confidence and sense of completeness of the syllabus. Solving just questions will leave a doubt that there might be something I didn't cover.

Next 15 Days:

Data Structures from UC Berkley:(15 Days)

https://www.youtube.com/watch?v=QMV45tHCYNI&list=PL4BBB74C7D2A1049C

Next 30 Days:

Now you have a better understanding data structure and algorithm, now lets do some hands on with text books of prestigious writes.

Text Books(Use when required, no need to read cover to cover)

Algorithm Design Manual By Steven Skiena

Data Structures and Algorithms by Roberto Tamassia(optional)

Books for Interview Practice:(Keep solving 5-10 questions every day, don't get stuck for more than one hour, make a target to finish in 1 month)

Elements of Programming Interviews: Adnan Aziz, Amit Prakash(Must)

Cracking the Coding Interview: Gayle Laakman McDowell(easy)

Data Structure and Algorithm Made Easy : Narsimha Karumanchi(optional, but good)

It's time to practice:

Two Must Links for Data-Structure  and Algorithm: Write code on paper as well as system. Interviews are on paper.

http://www.geeksforgeeks.org/fundamentals-of-algorithms/

http://www.geeksforgeeks.org/data-structures/

Try to do all of the questions in the above links which are not in EPI (Elements of Programming Interviews).

Believe me or not, there are no questions for Data-Structure and Algorithm outside this. At least in India. Nobody asks beyond these.

Use an excel sheet to monitor goal and progress. Setting hard targets and finishing them.

Let me know if you find anything erroneous.

Now you are confident enough, let's rock the interviews.

Friday, 14 August 2015

How to rename blog title

If you have created a block with a weird name or just you want to change the title of your blog..(This happened to me :P), here is the solution how can you rename your blog title:

1. Go to your blog
2. Click on the design, on right top corner (as mentioned in the below  image):


3. In the next page click on the My blogs:



4. In the next page click on the down-arrow (mentioned below) and select Settings from drop-down list:


5. In next next page click on Edit next to the title of the blog and there you are..enjoy :)