Monday 20 October 2014

Installing SSL Certificate on Linux Tomcat Server

SSL (Secure Sockets Layer) is the standard security technology for establishing an encrypted link between a web server and a browser. This link ensures that all data passed between the web server and browsers remain private and integral. With a secure web server, clients can connect to your server secure in the knowledge both that it is who it claims to be and that the transaction is well-encrypted so their data is safe.

  • Here are the few steps to install SSL Certificate.

1. First create a keystore file using below command.
keytool -genkey -alias domainname.com -keyalg RSA -keystore keystore.jks -keysize 2048

2.Generate an CSR(Certificate Signing Request).
keytool -certreq -alias domainname.com -keystore keystore.jks -file domainname.csr

3.Import root certificate.
keytool -import -alias root -keystore keystore.jks -trustcacerts -file root.crt

4. Import intermidiate certificate.
keytool -import -alias intermed -keystore keystore.jks -trustcacerts -file intermediate.crt

5. Install your certificate.
keytool -import -alias domainname.com -keystore keystore.jks -trustcacerts -file keystore.crt


  • Configuration of connector in Apache - In tomcat server.xml file, you have to add some parameters to the connector tag like SSLEnabled, Address, Keystore file, Password of keystore file etc.

<Connector port="443" protocol="HTTP/1.1" address="192.168.2.111" SSLEnabled="true"
maxThreads="500" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS"
keystoreFile="/home/user/keystore_yuspeed.jks"
keystorePass="password" />

Saturday 12 July 2014

Direct Memory Access Java

Does Java Allow Direct Memory Access

Well, there is a sun.misc.Unsafe class. It allows direct memory access, so you can implement some magic like reinterpret casts and so on. The thing is you need to use hacky reflection approach to get the instance and this class is not realy well documented. In general you need a very good reason to use this kind of tool in production code.
Here's an example how to get it:

Field f = Unsafe.class.getDeclaredField("theUnsafe");
f
.setAccessible(true);
Unsafe unsafe = (Unsafe) f.get(null);
 
 
There are 105 methods, allowing different low-level stuff. These methods are devoted to direct memory access:
  • allocateMemory
  • copyMemory
  • freeMemory
  • getAddress
  • getInt - Gets you a value from the memory whose

 

Wednesday 9 July 2014

Method Overidding vs Method Overloading

Difference between overloaded methods and overidden methods in Java



Overloaded Method Overridden Method
Arguments Must change Must not change
Return type Can change Can’t change except for co-variant returns
Exceptions Can change Can reduce or eliminate. Must not throw new or broader checked exceptions
Access Can change Must not make more restrictive (can be less restrictive)
Invocation Reference type determines which overloaded version is selected. Happens at compile time. Object type determines which method is selected. Happens at run-time.

Abstraction Vs Encapsulation

 Difference  between Abstraction and encapsulation 

  • Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation (information hiding) prevents clients from seeing it’s inside view, where the behavior of the abstraction is implemented.
  • Abstraction solves the problem in the design side while Encapsulation is the Implementation.
  • Encapsulation is the deliverable of Abstraction. Encapsulation barely talks about grouping up your abstraction to suit the developer needs. 
eg . Interface and the class implementing the interface 

eg . public interface ABC {
             void display();
}

Here abstraction is provided by the interface meaning it will be the face of the class implementing the interface ABC

Encapsulation can be done as 

public class DEF implements ABC{
             void display(){
                    System.out.println("DEF");
             }
}

In the above example 

Inteface ABC provides abstraction , while class DEF provides encapsulation i.e. binding the data and the code together.

What happens when a static method is invoked using a null object reference

No we can't.

It will throw NullPointerException because null is not an object in java. If method is static it will run & if method is non static it will through an NPEnull does not represent some "base" object, it represents a reference which does not point to any object at all.

For Example:-
class TestClass {
    static void myMethod() {
        System.out.println("Hello World...");
    }
}

class Test {
    public static void main(String[] args) {
        TestClass tc = null;        tc.myMethod();    }
}

Above code will print "Hello World..." as myMethod() is static method.

Sunday 6 July 2014

JVM parameters in Java

On the basis of how we specify JVM option it can be divided into two parts, JVM Options which starts with –X and those which starts with -XX:

1) JVM Options that begin with -X are non-standard (thy are not guaranteed to be supported on all JVM implementations), and are subject to change without notice in subsequent releases of the JDK.

2) JVM Options or parameters which are specified with -XX are not stable and are not recommended for casual use. These options are subject to change without notice also.



Key Points about JVM Options:

1) Boolean JVM options can be turned on with -XX:+ and can be turned off with -XX:-.
2) Numeric JVM Options can be set with -XX:=. Numbers can include 'm' or 'M' for megabytes, 'k' or 'K' for kilobytes, and 'g' or 'G' for gigabytes (for example, 32k is the same as 32768).
3) String JVM options can be set by using -XX:=, and usually used to specify a file, a path, or a list of commands.

The command java -help lists the standard options (standard across different JVM implementations) for the Java application launcher. The command java -X can be used to see the Java application launcher's non-standard (X for extension specific to that JVM) arguments.The -X options are non-standard and subject to change without notice. If you wish to detect which JVM arguments your currently running Java application is using, you can try below code.

Read JVM Parameters Runtime

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.util.List;

public void runtimeParameters() {
          RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
          List<String> aList = bean.getInputArguments();
          for (int i = 0; i < aList.size(); i++) {
                    System.out.println( aList.get( i ) );
          }
}


Brief Introduction to OOP

Object Oriented Programming or OOP is the technique to create programs based on the real world. Unlike procedural programming, here in the OOP programming model programs are organized around objects and data rather than actions and logic. Objects represent some concepts or things and like any other objects in the real Objects in programming language have certain behavior, properties, type, and identity. In OOP based language the principal aim is to find out the objects to manipulate and their relation between each other. OOP offers greater flexibility and compatibility and is popular in developing larger application. Another important work in OOP is to classify objects into different types according to their properties and behavior. So OOP based software application development includes the analysis of the problem, preparing a solution, coding and finally its maintenance.

Java is a object oriented programming and to understand the functionality of OOP in Java, we first need to understand several fundamentals related to objects. These include class, method, inheritance, encapsulation, abstraction, polymorphism etc. 

Class - It is the central point of OOP and that contains data and codes with behavior. In Java everything happens within class and it describes a set of objects with common behavior. The class definition describes all the properties, behavior, and identity of objects present within that class. As far as types of classes are concerned, there are predefined classes in languages like C++ and Pascal. But in Java one can define his/her own types with data and code. 

Object - Objects are the basic unit of object orientation with behavior, identity. As we mentioned above, these are part of a class but are not the same. An object is expressed by the variable and methods within the objects. Again these variables and methods are distinguished from each other as instant variables, instant methods and class variable and class methods. 

Methods - We know that a class can define both attributes and behaviors. Again attributes are defined by variables and behaviors are represented by methods. In other words, methods define the abilities of an object. 

Inheritance - This is the mechanism of organizing and structuring software program. Though objects are distinguished from each other by some additional features but there are objects that share certain things common. In object oriented programming classes can inherit some common behavior and state from others. Inheritance in OOP allows to define a general class and later to organize some other classes simply adding some details with the old class definition. This saves work as the special class inherits all the properties of the old general class and as a programmer you only require the new features. This helps in a better data analysis, accurate coding and reduces development time. 

Abstraction - The process of abstraction in Java is used to hide certain details and only show the essential features of the object. In other words, it deals with the outside view of an object. Know more about Abstract Class

Encapsulation - This is an important programming concept that assists in separating an object's state from its behavior. This helps in hiding an object's data describing its state from any further modification by external component. In Java there are four different terms used for hiding data constructs and these are public, private, protected and package. As we know an object can associated with data with predefined classes and in any application an object can know about the data it needs to know about. So any unnecessary data are not required by an object can be hidden by this process. It can also be termed as information hiding that prohibits outsiders in seeing the inside of an object in which abstraction is implemented. 

Polymorphism - It describes the ability of the object in belonging to different types with specific behavior of each type. So by using this, one object can be treated like another and in this way it can create and define multiple level of interface. Here the programmers need not have to know the exact type of object in advance and this is being implemented at runtime. 


Thanks to Prashant for adding contribution to this post.

How to add BASIC Authentication into HttpURLConnection?

Here is one sample.

...
try {
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
...
BASE64Encoder enc = new sun.misc.BASE64Encoder();
String userpassword = username + ":" + password;
String encodedAuthorization = enc.encode( userpassword.getBytes() );
connection.setRequestProperty("Authorization", "Basic "+
encodedAuthorization);
...
//Send post data
...

} catch (Exception e) {
...
} finally {

if(connection != null) {
connection.disconnect();
}
}
}

Thursday 3 July 2014

Hibernate session.get() and session.load()

Actually, both functions are use to retrieve an object with different mechanism, of course.

1. session.load()
It will always return a “proxy” (Hibernate term) without hitting the database. In Hibernate, proxy is an object with the given identifier value, its properties are not initialized yet, it just look like a temporary fake object.
If no row found , it will throws an ObjectNotFoundException.


2. session.get()
It always hit the database and return the real object, an object that represent the database row, not proxy.
If no row found , it return null.
It’s about performance

Hibernate create anything for some reasons, when you do the association, it’s normal to obtain retrieve an object (persistent instance) from database and assign it as a reference to another object, just to maintain the relationship.

Tuesday 1 July 2014

Abstract Class

An abstract class is a class that is declared abstract & it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract. All other functionality of the class still exists like with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods and all accessed in the same manner.

Ex-

public abstract class GraphicObject {
            // declare fields 
            // declare nonabstract methods
            abstract void draw(); 
    }


Can an abstract class be final?
No a class cannot be marked "abstract" as well as "final". Marking a class "abstract" means it contains partial implementation of methods and hence depends on its subclasses to provide concrete implementation. Marking the class "final" means that no other class can
extend it and hence abstract classes cannot be marked final.


Can abstract class have constructors in Java?
Yes, abstract class can declare and define constructor in Java. Since you can not create instance of abstract class, constructor can only be called during constructor chaining, i.e. when you create instance of concrete implementation class. Also even if you don’t provide any constructor, compiler will add default no argument constructor in abstract class, without that your subclass will not compile, since first statement in any constructor implicitly calls super(), default super class constructor in Java.


Can you create instance of abstract class?
No, you can not create instance of abstract class in Java, they are incomplete. Even though, if your abstract class don’t contain any abstract method, you can not create instance of it. By making a class abstract, you told compiler that, it’s incomplete and should not be instantiated. Java compiler will throw error, when a code tries to instantiate abstract class.


What is abstract method in Java?
An abstract method is a method without body. You just declare method, without defining it and use abstract keyword in method declaration. All method declared inside Java Interface are by default abstract. Here is an example of abstract method in Java

public void abstract sampleMethod();

Can abstract class contains main method in Java ?
Yes, abstract class can contain main method, it just another static method and you can execute Abstract class with main method, until you don’t create any instance.


Is it necessary for abstract class to have abstract method?
No, It’s not mandatory for an abstract class to have any abstract method. You can make a class abstract in Java, by just using abstract keyword in class declaration. Compiler will enforce all structural restriction, applied to abstract class.



Thursday 26 June 2014

How to config Tomcat to retrieve images from an external folder outside webapps(outside the context of tomcat)?

You should add following line in server.xml file

<Context path="/DataRepository" docBase="D:/DataRepository/" />

You must put this context tag inside of HOST tag.

Now you can just access the image present inside your path "D:/DataRepository/".

For Example if your DataRepository folder is having an image image 'sanket.jpg' then you can access it as ,

http://localhost:8080/DataRepository/sanket.jpg

Wednesday 25 June 2014

HashSet & HashMap

HashSet:

  • HashSet is implementation of Set Interface and extends AbstractSet class
  • Uses Hash table to store the elements.
  • In Hash set the main thing is that objects which are going to be stored in HashSet must override equals() and hashCode() method so that no duplicate value are stored in our set.
  • Contains unique elements only.
  • HashSet is slower than HashMap.
  • Add method is used to add element in Set. public boolean add(Object o)
  • Example : In the HashSet, there must be no duplicate elements.
       HashSet is a set, e.g. {10,20,30}


HashMap:


  • HashMap is a implementation of Map Interface and extends AbstractMap class, which maps a key to value.
  • It contains only unique elements.
  • It may have one null key and multiple null values.
  • Basically map Interface has two implementation classes HashMap and TreeMap the main difference is TreeMap maintains order of the objects but HashMap will not.
  • HashMap is not synchronized, but collection framework provide methods so that we can make them synchronized if multiple threads are going to access our HashMap and one thread is structurally change our map.
  • HashMap is faster than HashSet because unique key is used to access object.
  • Put method is used to add element in map. public Object put(Object Key,Object value)
  • Example : HashMap there must not be duplicate keys, but it may have duplicate values.
        HashMap is a key -> value (key to value) map, e.g. {a -> 10, b -> 20, c -> 20}


Differences between HashSet and HashMap in Java
HashSet internally uses HashMap to store objects. When add(String) method called it calls HahsMap put(key,value) method where key=String object & value=new Object(Dummy). So it maintain no duplicates because keys are nothing but Value Object. Keys which are used to access/store value objects in HashMap should declared as Final because when it is modified Value object can't be located & returns null.

Why add() Method of HashSet return boolean & put() method of HashMap return values?

HashMap put method: Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

Return:- the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)



HashSet add method: Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.

Returns:- true if this set did not already contain the specified element.

Tuesday 24 June 2014

Daemon Thread

There are two types of threads user thread and daemon thread. The daemon thread is a service provider thread which runs in background to provide services to the user thread and mostly created by JVM for performing background task like Garbage collection and other house keeping tasks. Its life depends on the user threads i.e. when all the user threads dies, JVM terminates this thread automatically.

Points to remember for Daemon Thread:

  • It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads.
  • Thread.setDaemon(true) makes a Thread daemon but it can only be called before starting Thread in Java. It will throw IllegalThreadStateException if corresponding Thread is already started and running.
  • Its life depends on user threads.
  • It is a low priority thread.

Why JVM terminates the daemon thread if there is no user thread remaining?
The sole purpose of the daemon thread is that it provides services to user thread for background supporting task. If there is no user thread, why should JVM keep running this thread. That is why JVM terminates the daemon thread if there is no user thread.

Difference between Daemon and Non Daemon thread in Java
1) JVM doesn't wait for any daemon thread to finish before existing.
2) Daemon Thread are treated differently than User Thread when JVM terminates, finally blocks are not called, Stacks are not unwounded and JVM just exits.