Tuesday, June 23, 2015

Monday, June 22, 2015

CodeAcademy Javascript

JavaScript Tutorial #9 - The return Statement

Design patterns

http://virajonlinetutor.blogspot.in/2013/12/design-pattern-tutorials.html
http://www.tutorialspoint.com/design_pattern/abstract_factory_pattern.htm
http://www.journaldev.com/1827/java-design-patterns-example-tutorial

UML

UML notations

Hibernate Architecture

http://www.tutorialspoint.com/hibernate/hibernate_architecture.htm

Friday, June 19, 2015

ClassNotFoundException

In this tutorial we will discuss about ClassNotFoundException. This exception is thrown when an application tries to load a class through its string name, but no definition for the specified class name could be found. A class can be loaded using one of the following methods:



This exceptions extends the ReflectiveOperationException, which is defined as the common superclass of exceptions thrown by reflective operations in core reflection. Finally, after the Java 1.4 release, the ClassNotFoundException has been retrofitted to conform to the general purpose exception-chaining mechanism. The raising exception may be accessed via the Throwable.getCause() method.

The ClassNotFoundException in Java

The ClassNotFoundException is thrown when the Java Virtual Machine (JVM) tries to load a particular class and the specified class cannot be found in the classpath. The ClassNotFoundException is a checked exception and thus, must be declared in a method or constructor’s throws clause.
The following example tries to load a class using the forName method. However, the specified class name cannot be found and thus, a ClassNotFoundException is thrown.
ClassNotFoundExceptionExample.java:
01package main.java;
02
03public class ClassNotFoundExceptionExample {
04
05    private static final String CLASS_TO_LOAD = "main.java.Utils";
06
07    public static void main(String[] args) {
08        try {
09            Class loadedClass = Class.forName(CLASS_TO_LOAD);
10            System.out.println("Class " + loadedClass + " found successfully!");
11        }
12        catch (ClassNotFoundException ex) {
13            System.err.println("A ClassNotFoundException was caught: " + ex.getMessage());
14            ex.printStackTrace();
15        }
16    }
17}
A sample execution is shown below:
A ClassNotFoundException was caught: main.java.Utils
java.lang.ClassNotFoundException: main.java.Utils
 at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
 at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
 at java.security.AccessController.doPrivileged(Native Method)
 at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
 at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
 at java.lang.Class.forName0(Native Method)
 at java.lang.Class.forName(Class.java:259)
 at main.java.ClassNotFoundExceptionExample.main(ClassNotFoundExceptionExample.java:9)

How to deal with the ClassNotFoundException

  • Verify that the name of the requested class is correct and that the appropriate .jar file exists in your classpath. If not, you must explicitly add it to your application’s classpath.
  • In case the specified .jar file exists in your classpath then, your application’s classpath is getting overriden and you must find the exact classpath used by your application.
  • In case the exception is caused by a third party class, you must identify the class that throws the exception and then, add the missing .jar files in your classpath.

Quick Notes


  1. Most popular JSP editors such as DreamWeaver and WSAD support Custom Tag syntax and the ability to step through them in a debugger.
The Tags themselves are built using Java, of course. Inserting a Tag only requires embedding an XML-like fragment into a JSP. When a JSP that contains one or more tags is invoked, the servlet produced from JSP compilation calls out to the appropriate Tag handler instance to perform its logic. All invocations of the same Tag invoke the same code. The better application's containers will create a pool of tag instances and not create a new instance of the Java class for every request. This helps to improve performance in a manner similar to how an EJB container can reuse Stateless Session bean instances.

2.  method called automatically by JVM is called calll back method...
ex :private void writeObject (OOS os) throws Exception {

}

Object class does not implement serializable

Generic Servlet implements serilizable

-------------------------------------------------------------------------------------------------------------------------------------------------------------------

I was thinking about that, and I had some doubts.
When I declare an interface, for example:
public interface MyInterface
{
   public void method1();
   public void method2();
}
Could these interface methods be considered abstract? What I mean is that the concept of an abstract method is:
An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon).
So, could these methods be considered abstract? They are not "pure" abstract methods as I'm not using the abstract word, but conceptually, it looks like they are.
What can you tell me about it?


-True,,, interfaces provide just the declarations of method and implicitly these methods are "public abstract". 
Interfaces are useful when some classes implements it, or some other interfaces extends it.
The interface "LayoutManager" is implemented by classes like FlowLayout, GridLayout etc.
BorderLayout, CardLayout classes implements LayoutManager2.
LayoutManager2 extends LayoutManager.
So BorderLayout, CardLayout classes implements LayoutManager, but not directly.
I dun know whether i answered ur question the way u wanted !!.



Abstract classes can have abstract methods.

Interfaces can only have abstract methods.

An interface is like a "purely" abstract class. The class and all of its methods are abstract. An abstract class can have implemented methods but the class itself cannot be instantiated (useful for inheritance and following DRY).
For an interface, since there isn't any implementation at all they are useful for their purpose: a contract. If you implement the Interface then you must  implement the methods in the interface.
So the difference is an abstract class can have implemented methods whereas a interface cannot.
The reason they are separate is so a class can implement several interfaces. Java and C# restrict a class to inherent from a single parent class. Some languages allow you to inherit from multiple classes and you could accomplish the work of an interface via a "purely" abstract class. But multiple inheritance has its problems, namely the dreaded Diamond Problem

Methods in an interface is 
"public abstract" by default.
Some code.
------------------------------------
interface Mine {
// is as good as saying "public abstract", thats the default
// for an method in an interface
void tester(); 

/* Won't compile, must be "public"
private abstract void tester();
*/
/* Won't compile, must be "public"
protected abstract void tester();

*/

}
class Test1 implements Mine {

/*
// Won't compile. coz, ur implementing a method of an 
// interface with a
// weaker access privilege ( default access in this case),
// Mr. compiler donot like this
void tester() {
System.out.println("Oops !!");
}
*/

public void tester() {
System.out.println("Mmmm... good enough !!");
}
}


----------------------------------------------------

Check out this code.
It won't compile, coz, class B is overriding the method with a weaker access privilege ( again, default access in this case),

class A {
public void tester() {
}
}

class B extends A{

void tester() {
}
}


Partial Implementations

If a class includes an interface but does not fully implement the methods defined by that interface, then that class must be declared as abstract.



  • nterfaces support multiple inheritance which is not possible with concrete and abstract classes.
  • "implements" keyword is used in place of "extends". "extends" comes with concrete and abstract classes.
  • Interfaces must contain abstract methods only.
  • As in abstract classes, all the abstract methods of the interfaces should be overridden by the subclass.
  • As with abstract classes, with interfaces also, objects cannot be created but reference variables can be created.
  • Interface reference variable can be assigned with concrete subclass objects. Once assigned, the interface reference variable works like an object. This feature applies to abstract classes also.
  • As all methods must be abstract and public, these two keyword can be omitted in method declaration. If omitted, JVM takes by default.
  • All interface variables must be public, static and final. If omitted, they are taken by default.
  • All interface methods should be overridden with public only as overridden method cannot have a weaker access specifier.
  • - See more at: http://way2java.com/oops-concepts/interfaces-partial-implementatin-of-multiple-inheritance/#sthash.TueDnU3f.dpuf

    Compare and Contrast Abstract classes with Interfaces?
    Even though the interface is a special derivative of abstract class; it differs a lot with abstract class. Following table gives their differences.
    Abstract classInterface
    1. Multiple inheritance is not supportedMultiple inheritance is supported
    2. To inherit "extends" keyword is usedTo inherit "implements" keyword is used
    3. May include concrete methods alsoAll must be abstract methods
    4. Methods may be of any specifier except private. That is, may be
    public, protected or default
    Methods must be public only
    5. Access specifier should be writtenIf omitted, taken by default (as public)
    6. Access modifier abstract should be writtenIf omitted, taken by default (as abstract)
    7. Variables can be any access specifier including privateVariables should be public, static and final. If omitted, taken by default.
    8. Constructors can be included in codeNo constructors
    9. main() can be included in codemain() method cannot be included
    Table: Differences between abstract classes and interfaces
    After knowing the differences, let us see the similarities.
    1. With abstract classes and interfaces, objects cannot be created; but reference variables can be created.
    2. All the abstract methods of the both should be overridden by the inherited class.
    3. "Dynamic polymorphism" is supported by both.
    4. Both works as template (structure of methods) from which new classes can be derived easily.
    - See more at: http://way2java.com/oops-concepts/interfaces-partial-implementatin-of-multiple-inheritance/#sthash.TueDnU3f.dpuf



    -------------------
    -The element load-on-startup indicates that this servlet should be loaded (instantiated and have its init() called) on the startup of the Web application. The element content of this element must be an integer indicating the order in which the servlet should be loaded. If the value is a negative integer, or the element is not present, the container is free to load the servlet whenever it chooses. If the value is a positive integer or 0, the container must load and initialize the servlet as the application is deployed. The container must guarantee that servlets marked with lower integers are loaded before servlets marked with higher integers. The container may choose the order of loading of servlets with the same load-on-startup value.

    ------------------------

    Thursday, June 18, 2015

    Struts logic tag tutorial

    http://www.dzone.com/tutorials/java/struts/struts-example/struts-logic-tag-example-1.html

    nice blog

    http://rakshasingh.weebly.com/blog/archives/08-2013

    Java Memory model


    The Java memory model specifies how the Java virtual machine works with the computer's memory (RAM). The Java virtual machine is a model of a whole computer so this model naturally includes a memory model - AKA the Java memory model.
    It is very important to understand the Java memory model if you want to design correctly behaving concurrent programs. The Java memory model specifies how and when different threads can see values written to shared variables by other threads, and how to synchronize access to shared variables when necessary.
    The original Java memory model was insufficient, so the Java memory model was revised in Java 1.5. This version of the Java memory model is still in use in Java 8.

    The Internal Java Memory Model

    The Java memory model used internally in the JVM divides memory between thread stacks and the heap. This diagram illustrates the Java memory model from a logic perspective:
    The Java Memory Model From a Logic PerspectiveEach thread running in the Java virtual machine has its own thread stack. The thread stack contains information about what methods the thread has called to reach the current point of execution. I will refer to this as the "call stack". As the thread executes its code, the call stack changes.
    The thread stack also contains all local variables for each method being executed (all methods on the call stack). A thread can only access it's own thread stack. Local variables created by a thread are invisible to all other threads than the thread who created it. Even if two threads are executing the exact same code, the two threads will still create the local variables of that code in each their own thread stack. Thus, each thread has its own version of each local variable.
    All local variables of primitive types ( booleanbyteshortcharintlongfloatdouble) are fully stored on the thread stack and are thus not visible to other threads. One thread may pass a copy of a pritimive variable to another thread, but it cannot share the primitive local variable itself.
    The heap contains all objects created in your Java application, regardless of what thread created the object. This includes the object versions of the primitive types (e.g. ByteIntegerLong etc.). It does not matter if an object was created and assigned to a local variable, or created as a member variable of another object, the object is still stored on the heap.
    Here is a diagram illustrating the call stack and local variables stored on the thread stacks, and objects stored on the heap:
    The Java Memory Model showing where local variables and objects are stored in memory.A local variable may be of a primitive type, in which case it is totally kept on the thread stack.
    A local variable may also be a reference to an object. In that case the reference (the local variable) is stored on the thread stack, but the object itself if stored on the heap.
    An object may contain methods and these methods may contain local variables. These local variables are also stored on the thread stack, even if the object the method belongs to is stored on the heap.
    An object's member variables are stored on the heap along with the object itself. That is true both when the member variable is of a primitive type, and if it is a reference to an object.
    Static class variables are also stored on the heap along with the class definition.
    Objects on the heap can be accessed by all threads that have a reference to the object. When a thread has access to an object, it can also get access to that object's member variables. If two threads call a method on the same object at the same time, they will both have access to the object's member variables, but each thread will have its own copy of the local variables.
    Here is a diagram illustrating the points above:
    The Java Memory Model showing references from local variables to objects, and from object to other objects.Two threads have a set of local variables. One of the local variables (Local Variable 2) point to a shared object on the heap (Object 3). The two threads each have a different reference to the same object. Their references are local variables and are thus stored in each thread's thread stack (on each). The two different references point to the same object on the heap, though.
    Notice how the shared object (Object 3) has a reference to Object 2 and Object 4 as member variables (illustrated by the arrows from Object 3 to Object 2 and Object 4). Via these member variable references in Object 3 the two threads can access Object 2 and Object 4.
    The diagram also shows a local variable which point to two different objects on the heap. In this case the references point to two different objects (Object 1 and Object 5), not the same object. In theory both threads could access both Object 1 and Object 5, if both threads had references to both objects. But in the diagram above each thread only has a reference to one of the two objects.
    So, what kind of Java code could lead to the above memory graph? Well, code as simple as the code below:
    public class MyRunnable implements Runnable() {
    
        public void run() {
            methodOne();
        }
    
        public void methodOne() {
            int localVariable1 = 45;
    
            MySharedObject localVariable2 =
                MySharedObject.sharedInstance;
    
            //... do more with local variables.
    
            methodTwo();
        }
    
        public void methodTwo() {
            Integer localVariable1 = new Integer(99);
    
            //... do more with local variable.
        }
    }
    
    
    public class MySharedObject {
    
        //static variable pointing to instance of MySharedObject
    
        public static final MySharedObject sharedInstance =
            new MySharedObject();
    
    
        //member variables pointing to two objects on the heap
    
        public Integer object2 = new Integer(22);
        public Integer object4 = new Integer(44);
    
        public long member1 = 12345;
        public long member1 = 67890;
    }
    
    If two threads were executing the run() method then the diagram shown earlier would be the outcome. Therun() method calls methodOne() and methodOne() calls methodTwo().
    methodOne() declares a primitive local variable (localVariable1 of type int) and an local variable which is an object reference (localVariable2).
    Each thread executing methodOne() will create its own copy of localVariable1 and localVariable2 on their respective thread stacks. The localVariable1 variables will be completely separated from each other, only living on each thread's thread stack. One thread cannot see what changes another thread makes to its copy of localVariable1.
    Each thread executing methodOne() will also create their own copy of localVariable2. However, the two different copies of localVariable2 both end up pointing to the same object on the heap. The code setslocalVariable2 to point to an object referenced by a static variable. There is only one copy of a static variable and this copy is stored on the heap. Thus, both of the two copies of localVariable2 end up pointing to the same instance of MySharedObject which the static variable points to. The MySharedObject instance is also stored on the heap. It corresponds to Object 3 in the diagram above.
    Notice how the MySharedObject class contains two member variables too. The member variables themselves are stored on the heap along with the object. The two member variables point to two other Integer objects. These Integer objects correspond to Object 2 and Object 4 in the diagram above.
    Notice also how methodTwo() creates a local variable named localVariable1. This local variable is an object reference to an Integer object. The method sets the localVariable1 reference to point to a newInteger instance. The localVariable1 reference will be stored in one copy per thread executingmethodTwo(). The two Integer objects instantiated will be stored on the heap, but since the method creates a new Integer object every time the method is executed, two threads executing this method will create separate Integer instances. The Integer objects created inside methodTwo() correspond to Object 1 and Object 5 in the diagram above.
    Notice also the two member variables in the class MySharedObject of type long which is a primitive type. Since these variables are member variables, they are still stored on the heap along with the object. Only local variables are stored on the thread stack.

    Hardware Memory Architecture

    Modern hardware memory architecture is somewhat different from the internal Java memory model. It is important to understand the hardware memory architecture too, to understand how the Java memory model works with it. This section describes the common hardware memory architecture, and a later section will describe how the Java memory model works with it.
    Here is a simplified diagram of modern computer hardware architecture:
    Modern hardware memory architecture.A modern computer often has 2 or more CPUs in it. Some of these CPUs may have multiple cores too. The point is, that on a modern computer with 2 or more CPUs it is possible to have more than one thread running simultaneously. Each CPU is capable of running one thread at any given time. That means that if your Java application is multithreaded, one thread per CPU may be running simultaneously (concurrently) inside your Java application.
    Each CPU contains a set of registers which are essentially in-CPU memory. The CPU can perform operations much faster on these registers than it can perform on variables in main memory. That is because the CPU can access these registers much faster than it can access main memory.
    Each CPU may also have a CPU cache memory layer. In fact, most modern CPUs have a cache memory layer of some size. The CPU can access its cache memory much faster than main memory, but typically not as fast as it can access its internal registers. So, the CPU cache memory is somewhere in between the speed of the internal registers and main memory. Some CPUs may have multiple cache layers (Level 1 and Level 2), but this is not so important to know to understand how the Java memory model interacts with memory. What matters is to know that CPUs can have a cache memory layer of some sort.
    A computer also contains a main memory area (RAM). All CPUs can access the main memory. The main memory area is typically much bigger than the cache memories of the CPUs.
    Typically, when a CPU needs to access main memory it will read part of main memory into its CPU cache. It may even read part of the cache into its internal registers and then perform operations on it. When the CPU needs to write the result back to main memory it will flush the value from its internal register to the cache memory, and at some point flush the value back to main memory.
    The values stored in the cache memory is typically flushed back to main memory when the CPU needs to store something else in the cache memory. The CPU cache can have data written to part of its memory at a time, and flush part of its memory at a time. It does not have to read / write the full cache each time it is updated. Typically the cache is updated in smaller memory blocks called "cache lines". One or more cache lines may be read into the cache memory, and one or mor cache lines may be flushed back to main memory again.

    Bridging The Gap Between The Java Memory Model And The Hardware Memory Architecture

    As already mentioned, the Java memory model and the hardware memory architecture are different. The hardware memory architecture does not distinguish between thread stacks and heap. On the hardware, both the thread stack and the heap are located in main memory. Parts of the thread stacks and heap may sometimes be present in CPU caches and in internal CPU registers. This is illustrated in this diagram:
    The division of thread stack and heap among CPU internal registers, CPU cache and main memory.When objects and variables can be stored in various different memory areas in the computer, certain problems may occur. The two main problems are:
    • Visibility of thread updates (writes) to shared variables.
    • Race conditions when reading, checking and writing shared variables.
    Both of these problems will be explained in the following sections.

    Visibility of Shared Objects

    If two or more threads are sharing an object, without the proper use of either volatile declarations or synchronization, updates to the shared object made by one thread may not be visible to other threads.
    Imagine that the shared object is initially stored in main memory. A thread running on CPU one then reads the shared object into its CPU cache. There it makes a change to the shared object. As long as the CPU cache has not been flushed back to main memory, the changed version of the shared object is not visible to threads running on other CPUs. This way each thread may end up with its own copy of the shared object, each copy sitting in a different CPU cache.
    The following diagram illustrates the sketched situation. One thread running on the left CPU copies the shared object into its CPU cache, and changes its count variable to 2. This change is not visible to other threads running on the right CPU, because the update to count has not been flushed back to main memory yet.
    Visibility Issues in the Java Memory Model.To solve this problem you can use Java's volatile keyword. The volatile keyword can make sure that a given variable is read directly from main memory, and always written back to main memory when updated.

    Race Conditions

    If two or more threads share an object, and more than one thread updates variables in that shared object, race conditions may occur.
    Imagine if thread A reads the variable count of a shared object into its CPU cache. Imagine too, that thread B does the same, but into a different CPU cache. Now thread A adds one to count, and thread B does the same. Now var1 has been incremented two times, once in each CPU cache.
    If these increments had been carried out sequentially, the variable count would be been incremented twice and had the original value + 2 written back to main memory.
    However, the two increments have been carried out concurrently without proper synchronization. Regardless of which of thread A and B that writes its updated version of count back to main memory, the updated value will only be 1 higher than the original value, despite the two increments.
    This diagram illustrates an occurrence of the problem with race conditions as described above:
    Race Condition Issues in the Java Memory Model.To solve this problem you can use a Java synchronized block. A synchronized block guarantees that only one thread can enter a given critical section of the code at any given time. Synchronized blocks also guarantee that all variables accessed inside the synchronized block will be read in from main memory, and when the thread exits the synchronized block, all updated variables will be flushed back to main memory again, regardless of whether the variable is declared volatile or not.


    Monday, June 15, 2015

    factory-design-pattern-using-reflection.html

    http://www.jineshmathew.com/2013/04/factory-design-pattern-using-reflection.html

    factory-design-pattern-using-reflection.html

    Monday, April 1, 2013

    Factory Design Pattern using Reflection

    Here I have given an implementation of Factory design pattern in Java using reflection.Please refer to the below link for a quick presentation about Java Refection APIs.

    www.cs.washington.edu/education/courses/.../reflection.ppt

    I am creating a DB factory which will create an instance of Database manager objects depends on the argument which is passed. Assume that we have an application running in 2 different environment where one environment uses Oracle as a database and another uses Solaris as a database.Upon initialization of the program we have to create a DB manager instance which should return Oracle or Solaris DB manager for the program.

    Here I have used reflection to avoid modification to the Factory class if we need to support a new data base tomorrow.

    I have factory class as below, DBFactory.java

    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.util.HashMap;
    
    
    public class DBFactory {
    
        private static HashMap m_RegisteredDatabases = new HashMap();
    
        public static void registerProduct (String id, Class<?> dbclass)
        {
            m_RegisteredDatabases.put(id, dbclass);
        }
        
        public static DBmanager createDBmanager(String id) throws Exception, NoSuchMethodException
        {
            Class dbclass = (Class) m_RegisteredDatabases.get(id);
            Method m = dbclass.getMethod("getInstance", null);
            DBmanager mgr = (DBmanager) m.invoke(null, null);
            return mgr;
            
        }
    }
    

    here a hashmap is used tyo maintain the list of registered databases as you see and createDBManager() method uses reflection to call getInstance() method of corresponding class. This avoids modifications to DBFactory.java if a new database is introduced.

    An interface is created DBmanager.java
    public interface DBmanager {
        
        public void execute();
        
    }
    

    Two concrete classes OracleDBmanager.java and SolarisDBmanager.java as below

    
    public class OracleDBmanager implements DBmanager {
        private static DBmanager instance;    
        public static DBmanager getInstance()
        {
            if ( instance == null)
            {
                synchronized (OracleDBmanager.class )
                {
                    if ( instance == null)
                    {
                        instance = new OracleDBmanager();
                    }
                }
            }
            return instance;
        }
        
        public void execute()
        {
            System.out.println("inside OracleDBmanager execute");
        }
    }
    

    public class SolarisDBmanager implements DBmanager {
        private static DBmanager instance;    
        public static DBmanager getInstance()
        {
            if ( instance == null)
            {
                synchronized (SolarisDBmanager.class )
                {
                    if ( instance == null)
                    {
                        instance = new SolarisDBmanager();
                    }
                }
            }
            return instance;
        }
        
        public void execute()
        {
            System.out.println("inside SolarisDBmanager execute");
        }
    }
    

    The client side code is shown as below in Reflection.java.

    public class Reflection {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            
            DBFactory.registerProduct("env1", OracleDBmanager.class);
            DBFactory.registerProduct("env2", SolarisDBmanager.class);
            DBmanager instance;
            try {
                instance = DBFactory.createDBmanager("env1");
                instance.execute();
            } catch (NoSuchMethodException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
    
    }

    Here you see that we have registered the databases upon startup and depends on the argument to factory method, it will create Oracle or Solaris DB manager instances.

    Suppose we need to support SQLserver then we need to have a SQLserverDBmanager as below.

    public class SQLserverDBmanager implements DBmanager  {
    
        private static DBmanager instance;    
        public static DBmanager getInstance()
        {
            if ( instance == null)
            {
                synchronized (OracleDBmanager.class )
                {
                    if ( instance == null)
                    {
                        instance = new SQLserverDBmanager();
                    }
                }
            }
            return instance;
        }
        
        public void execute()
        {
            System.out.println("inside SQLServerDBmanager execute");
        }
    }

    We only need to modify the client side code in Reflection.java.

    public class Reflection {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            
            DBFactory.registerProduct("env1", OracleDBmanager.class);
            DBFactory.registerProduct("env2", SolarisDBmanager.class);
            DBFactory.registerProduct("env3", SQLserverDBmanager.class);
            DBmanager instance;
            try {
                instance = DBFactory.createDBmanager("env3");
                instance.execute();
            } catch (NoSuchMethodException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }

    T

    Singleton pattern

    http://www.techgig.com/expert-speak/Advance-Java-Series-Session-3-Java-Design-Patterns-Useful-Variations-in-Singleton-Pattern-83

    Friday, June 12, 2015

    List_of_HTTP_header_fields

    http://en.wikipedia.org/wiki/List_of_HTTP_header_fields

    very very nice article on WebServices

    http://www.drdobbs.com/web-development/restful-web-services-a-tutorial/240169069

    RESTful Web Services: A Tutorial

    More than a decade after its introduction, REST has become one of the most important technologies for Web applications. Its importance is likely to continue growing quickly as all technologies move towards an API orientation. Every major development language now includes frameworks for building RESTful Web services. As such, it is important for Web developers and architects to have a clear understanding of REST and RESTful services. This tutorial explains REST architecturally, then dives into the details of using it for common API-based tasks.
    While REST stands for Representational State Transfer, which is an architectural style for networked hypermedia applications, it is primarily used to build Web services that are lightweight, maintainable, and scalable. A service based on REST is called a RESTful service. REST is not dependent on any protocol, but almost every RESTful service uses HTTP as its underlying protocol. In this article, I examine the creation of RESTful services with HTTP.

    Features of a RESTful Services

    Every system uses resources. These resources can be pictures, video files, Web pages, business information, or anything that can be represented in a computer-based system. The purpose of a service is to provide a window to its clients so that they can access these resources. Service architects and developers want this service to be easy to implement, maintainable, extensible, and scalable. A RESTful design promises that and more. In general, RESTful services should have following properties and features, which I'll describe in detail:
    • Representations
    • Messages
    • URIs
    • Uniform interface
    • Stateless
    • Links between resources
    • Caching

    Representations

    The focus of a RESTful service is on resources and how to provide access to these resources. A resource can easily be thought of as an object as in OOP. A resource can consist of other resources. While designing a system, the first thing to do is identify the resources and determine how they are related to each other. This is similar to the first step of designing a database: Identify entities and relations.
    Once we have identified our resources, the next thing we need is to find a way to represent these resources in our system. You can use any format for representing the resources, as REST does not put a restriction on the format of a representation.
    For example, depending on your requirement, you can decide to use JSON or XML. If you are building Web services that will be used by Web pages for AJAX calls, then JSON is a good choice. XML can be used to represent more complex resources. For example a resource called "Person" can be represented as:
    Listing One: JSON representation of a resource.
    ?
    1
    2
    3
    4
    5
    6
    {
        "ID": "1",
        "Name": "M Vaqqas",
        "Email": "m.vaqqas@gmail.com",
        "Country": "India"
    }
    Listing Two: XML representation of a resource.
    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <Person>
     
    <ID>1</ID>
     
    <Name>M Vaqqas</Name>
     
    <Email>m.vaqqas@gmail.com</Email>
     
    <Country>India</Country>
    </Person>
    In fact, you can use more than one format and decide which one to use for a response depending on the type of client or some request parameters. Whichever format you use, a good representation should have some obvious qualities:
    • Both client and server should be able to comprehend this format of representation.
    • A representation should be able to completely represent a resource. If there is a need to partially represent a resource, then you should think about breaking this resource into child resources. Dividing big resources into smaller ones also allows you to transfer a smaller representation. Smaller representations mean less time required to create and transfer them, which means faster services.
    • The representation should be capable of linking resources to each other. This can be done by placing the URI or unique ID of the related resource in a representation (more on this in the coming sections).

    Messages

    The client and service talk to each other via messages. Clients send a request to the server, and the server replies with a response. Apart from the actual data, these messages also contain some metadata about the message. It is important to have some background about the HTTP 1.1 request and response formats for designing RESTful Web services.
    HTTP Request
    An HTTP request has the format shown in Figure 1:
    REST
    Figure 1: HTTP request format.
    <VERB> is one of the HTTP methods like GETPUTPOSTDELETEOPTIONS, etc
    <URI> is the URI of the resource on which the operation is going to be performed
    <HTTP Version> is the version of HTTP, generally "HTTP v1.1" .
    <Request Header> contains the metadata as a collection of key-value pairs of headers and their values. These settings contain information about the message and its sender like client type, the formats client supports, format type of the message body, cache settings for the response, and a lot more information.
    <Request Body> is the actual message content. In a RESTful service, that's where the representations of resources sit in a message.
    There are no tags or markups to denote the beginning or end of a section in an HTML message.
    Listing Three is a sample POST request message, which is supposed to insert a new resourcePerson.
    Listing Three: A sample POST request.
    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    Host: MyService
    Content-Type: text/xml; charset=utf-8
    Content-Length: 123
    <?xml version="1.0" encoding="utf-8"?>
    <Person>
      <ID>1</ID>
      <Name>M Vaqqas</Name>
      <Email>m.vaqqas@gmail.com</Email>
      <Country>India</Country>
    </Person>
    You can see the POST command, which is followed by the URI and the HTTP version. This request also contains some request headers. Host is the address of the server. Content-Type tells about the type of contents in the message body. Content-Length is the length of the data in message body. Content-Length can be used to verify that the entire message body has been received. Notice there are no start or end tags in this message.
    Listing Four is an actual GET request that was created by my browser when I tried to visit the HTTP 1.1 specifications on w3.org:
    Listing Four: A GET request.
    ?
    1
    2
    3
    4
    5
    6
    Host: www.w3.org
    Accept: text/html,application/xhtml+xml,application/xml; …
    User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 …
    Accept-Encoding: gzip,deflate,sdch
    Accept-Language: en-US,en;q=0.8,hi;q=0.6
    There is no message body in this request. The Accept header tells the server about the various presentation formats this client supports. A server, if it supports more than one representation format, it can decide the representation format for a response at runtime depending on the value of the Accept header. User-Agent contains information about the type of client who made this request. Accept-Encoding/Language tells about the encoding and language this client supports.
    HTTP Response
    Figure 2 shows the format of an HTTP response:
    REST
    Figure 2: HTTP response format.
    The server returns <response code>, which contains the status of the request. This response code is generally the 3-digit HTTP status code.
    <Response Header> contains the metadata and settings about the response message.
    <Response Body> contains the representation if the request was successful.
    Listing Five is the actual response I received for the request cited in Listing Three:
    Listing 5: An actual response to a GET request..
    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    HTTP/1.1 200 OK
    Date: Sat, 23 Aug 2014 18:31:04 GMT
    Server: Apache/2
    Last-Modified: Wed, 01 Sep 2004 13:24:52 GMT
    Accept-Ranges: bytes
    Content-Length: 32859
    Cache-Control: max-age=21600, must-revalidate
    Expires: Sun, 24 Aug 2014 00:31:04 GMT
    Content-Type: text/html; charset=iso-8859-1
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <head><title>Hypertext Transfer Protocol -- HTTP/1.1</title></head>
    <body>
    ...
    The response code 200 OK means that everything went well and the response message body contains a valid representation of the resource I requested. In this case, the representation is an HTML document that is declared by Content-Type header in the response header. The headers in the message are self explanatory, but I will discuss some of them later in this article. There aremany other attributes. You can catch and inspect such HTTP requests and responses using a free tool called Fiddler.
    Addressing Resources
    REST requires each resource to have at least one URI. A RESTful service uses a directory hierarchy like human readable URIs to address its resources. The job of a URI is to identify a resource or a collection of resources. The actual operation is determined by an HTTP verb. The URI should not say anything about the operation or action. This enables us to call the same URI with different HTTP verbs to perform different operations.
    Suppose we have a database of persons and we wish to expose it to the outer world through a service. A resource person can be addressed like this:
    http://MyService/Persons/1
    This URL has following format: Protocol://ServiceName/ResourceType/ResourceID
    Here are some important recommendations for well-structured URIs:
    • Use plural nouns for naming your resources.
    • Avoid using spaces as they create confusion. Use an _ (underscore) or  (hyphen) instead.
    • A URI is case insensitive. I use camel case in my URIs for better clarity. You can use all lower-case URIs.
    • You can have your own conventions, but stay consistent throughout the service. Make sure your clients are aware of this convention. It becomes easier for your clients to construct the URIs programmatically if they are aware of the resource hierarchy and the URI convention you follow.
    • A cool URI never changes; so give some thought before deciding on the URIs for your service. If you need to change the location of a resource, do not discard the old URI. If a request comes for the old URI, use status code 300 and redirect the client to the new location.
    • Avoid verbs for your resource names until your resource is actually an operation or a process. Verbs are more suitable for the names of operations. For example, a RESTful service should not have the URIs http://MyService/FetcthPerson/1 orhttp://MyService/DeletePerson?id=1.

    Query Parameters in URI

    The preceding URI is constructed with the help of a query parameter:
    http://MyService/Persons?id=1
    The query parameter approach works just fine and REST does not stop you from using query parameters. However, this approach has a few disadvantages.
    • Increased complexity and reduced readability, which will increase if you have more parameters
    • Search-engine crawlers and indexers like Google ignore URIs with query parameters. If you are developing for the Web, this would be a great disadvantage as a portion of your Web service will be hidden from the search engines.
    The basic purpose of query parameters is to provide parameters to an operation that needs the data items. For example, if you want the format of the presentation to be decided by the client. You can achieve that through a parameter like this:
    http://MyService/Persons/1?format=xml&encoding=UTF8
    or
    http://MyService/Persons/1?format=json&encoding=UTF8
    Including the parameters format and encoding here in the main URI in a parent-child hierarchy will not be logically correct as they have no such relation:
    http://MyService/Persons/1/json/UTF8
    Query parameters also allow optional parameters. This is not otherwise possible in a URI. You should use query parameters only for the use they are intended for: providing parameter values to a process.