Posts

Showing posts with the label java

Your own Thread Pool

"Create your own thread pool" - A typical interview question, asked to check if you have a basic understanding of Thread Pool, Runnable, and the disadvantages of creating a new Thread for each Task. ThreadPool is made up of a number of threads, identified by the core thread pool size. Once you start the ThreadPool, all the threads start running, waiting for the task. Each task or Runnable that you submit to the ThreadPool is executed by the existing threads of the ThreadPool. Creating a thread is expensive, so it is advisable to have a ThreadPool which manages the tasks. Here is a program which creates its own ThreadPool - MyThreadPool. import java.util.concurrent.ArrayBlockingQueue ; import java.util.concurrent.BlockingQueue ; class MyThreadPool { private int corePoolSize ; private MyThread tPool []; private BlockingQueue < Runnable > queue = new ArrayBlockingQueue <>(1024); public MyThreadPool ( int corePoolSize ) { thi...

Different ways to create an Object in Java

In this post, we will discuss the different ways to create a new Object Consider we have a class, say CustomClass and we are going to see different ways in which we can create a new object of CustomClass. Using new keyword/the constructor: new CustomClass (); Clone You already have an object and you using Cloning to create a copy of that object CustomClass myObject = new CustomClass (); CustomClassobject = ( CustomClass ) myObject . clone (); Class.forName: The reflection API gives us the ability to create objects without calling the constructor. Spring and Hibernate use reflection to create objects. Class . forname ( CustomClass ); Deserialization is another way of creating the object. First you serialize and then deserialize to get the object.

Filter for your Servlet

Image
Filter is used to perform filtering tasks on the request or the response or both. It is an interface in the javax.servlet package. Filters can be used for the following purposes: 1) Authentication Filters  2) Logging and Auditing Filters  3) Image conversion Filters  4) Data compression Filters  5) Encryption Filters  6) Tokenizing Filters  7) Filters that trigger resource access events  8) XSL/T filters  9) Mime-type chain Filter  Filters have the following three methods: Simple example of using filter for pre and post processing of response. This is how my project looks like: MyFilter will be applied before and after our MyServlet. Here is the code: index.html <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1" > <title> Insert title here </title> </head> <body> Welcome! </body> </html> web.xml <web-app> <serv...

Login Logout and Cookies!

Image
Another example of using Cookies for session management in Servlet. Here let us see how to login, maintain user session and then logout. Our application has the following main pages: 1. Login page 2. Logout page 3. My Profile 4. Index page The only criteria : You should be not able to logout or view my profile when you have not logged in. Let us see the code, you can take a look at the project structure from my previous post on Your own Cookie! . index.html file : Simple html page which displays the login, logout and profile links with Welcome. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <! DOCTYPE html > < html > < head > < meta charset = "ISO-8859-1" > < title > Insert title here </ title > </ head > < body > Welcome ! < a href = "login.html" > Login </ a > < a href = "logoutServlet" > Logout </ a > < a href = "profileServlet" > Prof...

Your own Cookie!

Image
In this post we will see how to create a simple web app which uses cookies to hold the user data (remember, in http ever request is a new request and cookie is a way to store the user data for subsequent requests to the server). Refer  Cookies in Servlet  for information about cookies Setup tomcat on your machine. (I have used apache-tomcat-8.0.15) I am using eclipse for installation. Create a dynamic web project, Cookies My final project structure looks like this: How to deploy our war file in tomcat. Export project -> as WAR file -> save it as Cookies in the webapps folder of tomcat. Start tomcat using startup.bat in bin folder. Access http://localhost:8080/Cookies/ Create an index.html file: <form action="servlet1" method="post"> Name : <input type="text" name="name"> <input type="submit" value="Go"> </form> Create FirstServlet.java class. package ...

Cookies in Servlets

Image
Cookies are small piece of information used for session management. The Http protocol is a stateless protocol, it means that each request is a new request for the Http server. Cookies is one of the ways in which Http server can persist data between multiple client requests. Let me depict it with the help of an image: When the browser sends a Http request for the first time, the servlet associates a cookie with the response and sends it to the browser. Now every subsequent request will be associated with the cookie and the server will use this information to identify the user and process the data accordingly. There are two types of cookies: 1. Persistent Cookie -> It is available for a single session only. Once the user closes the browser the cookie is removed. 2. Non-persistent Cookie -> It is available for multiple sessions. Cookie is removed only when the user logs out. Advantages of using Cookies: 1. The information is stored on the client side. 2. Simple ...

Java 8, Default methods, Diamond Problem and the Solution!

Java 8 has introduced default methods (methods with body) in interfaces. But doesn't this introduce the diamond problem? The very problem with C, that Java solved by not having multiple inheritance. Java has given a solution to this !!!!!! If you have two interfaces with same method signature, and a class implements it.. the class will give you compilation error saying there is ambiguity. It is now the developers responsibility to solve this problem by overriding the method in its body. It can call the super interfaces method by SuperInterface.super.methodName(). Let us see an example: public class MultipleInheritanceEg { public static void main(String[] args) { C c = new C(); c.A(); } } interface A{ public default void A(){ //Some implementation }; } interface B{ public default void A(){ //Some implementation }; } interface D extends A, B{ public default void A(){ A.super.A(); }; } ...

Revise Servlets in 10 mins

Revising Servlets in 10 mins, useful only if you have already read on servlets and just need to some guide points to recollect. Servlet is used to create dynamic web applications. Resides at server side. Implement Servlet interface to make a Servlet. Or you can extend the HTTPServlet class. Capable to serving and responding to requests. Better performance (creates new thread for each request), robust, secure and portable(since in java) Uses the HTTP Protocol to transfer data between the web server and the web browser. Stateless by default. HTTP Request methods: GET POST HEAD PUT DELETE OPTIONS TRACE Container provides runtime environment for j2ee applications Life cycle management Multithreading support object pooling Security Content Types: text/html, text/plain, images/jpeg etc Server types: Web server and application server Servlet Life Cycle: Servlet class is loaded Servlet instance is created  init method is invoked service method is invoked, ev...

Why Java!?

Java is an Object Oriented Programming Language. This means that everything in Java is an Object, whose template is given by the Class. Object Oriented Programming Features in Java: 1. Encapsulation Keep variables private and methods public ie just capsule all the data in java 2. Polymorphism Showing many forms. In java this is achieved by overriding and overloading 3. Abstraction Hide the complex implementation hidden from the user and show only the required information 4. Inheritance In java inheritance can be achieved by either extending a class or implementing an interface Features of Java Purely OOPs based Simple to learn Robust - Exception handling and Garbage collection make life easy for a Java Developer Secure - No pointers and high security as it doesnot allow a web applet to read and write from to a file easily High Performance Multi-threading Platform independent and Architecture neutral - java is compile once and run anywhere
DOMParser - XML Parsing 2 In DOMParser everything is a node. A node has childNodes which might have childNodes. DOM Structure I always find DOMParser a better choice when the whole xml files need to be loaded to a single object. When doing a lot of calculations on the xml use a SAXParser. I will post in an example soon. Use a SAXParser over a DOMParser. Reason: SAXParser gives better performance. SAX is faster! DOMParser reads the whole XML File in the memory, if the file is big.. we might get Memory issues!
XML Parsing - 1 Lets start with the structure of XML first. XML is a way of storing data.. sample xml file: <?xml version="1.0" encoding="UTF-8 " ?> <person> <name>Richa</name> <age>100</age> <lastname>Vaidya</lastname> <address>India</address> </person> the first line gives the version of the xml i.e 1.0 the next line person is the root all the contents of the xml are a part of the root i.e. person the later lines.. these are the elements of the root. So now we have the data, how do we use it in a java program. Read it line by line? No... We have been provided with two excellent parsers : DOMParser and  SAXParser . Difference between DOMParser and SAXParser., DOM reads the complete xml element, so you have the complete file in the memory and you can access the elements of the DOM root at you wish. SAX parser reads the file line by line. DOM parser has a greater memo...