Tuesday, November 16, 2010

GWT Basics

Question : What is GWT ?
Answer : Google Web Tool Kit(GWT) is a open source Java Development Framework,
 use to develop Ajax(Asynchronous JavaScript and XML)  Web applications those looks
 like the desktop applications.


Question: What are the other Frameworks which can compete the GWT framework ?
Answer:  1) Ruby on rails
               2) JQuery.
               3) Flex.
               4) Echo2.


Question :  What are the advantages of GWT Framework ?
Answer:
1) True Interaction: with lots of code executed on client side, reduce server-side 
    interaction minimum.
2) Easy to Develop : Using Java Language.
3) Excellent IDE Support :  With Excellent Debugging Skills.
4) Easy Integration of JavaScript: using the JSNI(Javascript Native Interface) we can 
    easily integrate the Javascript, we can integrate easily whenever we required the 
    JavaScript in GWt.
5) Easy Integration with Hibernate.
6) Excellent News Group  facilities.
7) Widget Support : Ready to use excellent Widgets.
8) Easy Integration with Server : GWT enables to integrate with server written in any    
     language.
9) using Ajax framework : rich web application look using the AJAX framework.
10) Good webserver Support : GWT has java-to-javascript compiler which is to distill 
     your web application into HTML and Javascript that you can server with any webserver.
11) Great Browser Compatibility : using the above feature.
12) Debugging in Hosted Mode.


Question: Hurdles in GWT Framework ?
Answer:
1) Slow Compilation.
2) No Support for multi-core : Compilation Process does not support the multiple Cpu's.
3) inconvenient to use arbitrary HTML with GWT: solved by using the powerful CSS.


Question: What is Host Mode in GWT ?
Answer : This is enables you to run your GWT application as Java in JVM.without
compilling to Javascript to First.This is called Host mode.


Question: How hostmode is accomplished?
Answer : by using SWT browser(Standard Web Tool Kit) this has hooks into JVM.
When you run your application in hostmode, the browser which u see u'r application is
nothing but the SWT browser.


Question : What is Web Mode ?
Answer : You use the GWT compiler to compile your GWT applications to JavaScript. The application can then be deployed to a web container. This is referred to as running in web mode. When you click on the Compile/Browse button, the Java code for the KitchenSink project is compiled by the Java-to-JavaScript compiler into pure HTML and JavaScript.


Explain the four main Components of GWT?
Answer : 
               1) GWT java - javascript compiler.
               2) GWT hosted web browser.
               3) JRE emulation library.
               4) GWT web User interface Library.


1) GWT java - javascript compiler : 
      The Java code for the GWT application project is compiled by the Java-to-JavaScript 
      compiler into pure HTML and JavaScript.
2) GWT hosted web browser :
    This enables you to run and execute your GWT applications as Java in the Java Virtual   
     Machine (JVM) without compiling to JavaScript first.
3) JRE emulation library :
    This contains JavaScript implementations of most of the widely used classes of the     
     java.lang and java.util packages from the Java standard class library.
     of course free to use the entire Java class library for the server-side implementation. 
4) GWT Web UI class library: 
     This provides a set of custom interfaces and classes that enable you to create various 
     widgets such as buttons, text boxes, images, and text.


Question: What is Asynchronous server call and Synchronous server call ?
Answer : Synchronous : Wait until server responds with the reply.
                Asynchronous : Allow the page to continue to processed and process the reply 
                                             from server when it is arrived.
Question : is GWT server calls are synchronous or Asynchronous ?
Answer : Asynchronous.
Reason : Most browser java script engines are single threaded.
Question : is AJAX server calls are synchronous or Asynchronous?
Answer : Asynchronous.
Question: In GWT how to handle the server Response?
Answer : by Implementing the interface "AsyncCallback" interface.
if RPC is successful then onSuccess(Object) is called otherwise the in failure
 onFailure(Throwable) is called.
Question :Write an Example implementation of interface AysnCallback Interface?
Answer :
                     Shapes.getShapes(dbname,new AsyncCallback() {
                      public void onSuccess(Shapes[] result) {
                 //Process the result 
              }
               public void onFailure(Throwable caught) {
               try
                  { throw caught } catch(Excpetion e) { // }
Question: What is the latest Version of GWT ?
Answer : Version 2.1.

Question : Explain about GWT RPC ?
Answer: GWT provides simple, Asynchronous RPC and Object Serialization that allows client and server to talk.GWT includes a GWT RPC package for enabling communication with server resources.
That Package includes:
               1) Two interfaces 
            2) Service implementation.
Two interfaces are :
              a) Synchronous interface.
              b)Asynchronous Interface.


 Synchronous Interface:
        A Synchronous interface extends RemoteService interface and defines the methods
        your service exposes.
Example  Program :
             package com.example.Employee.client;
             import com.google.gwt.user.client.rpc.RemoteService;
            public interface HelloService extends RemoteService {
                       String sayHello(Person p);
            }
Asynchronous Interface:
    a) Same name as Synchronous interface, but with Async Suffix.
    b) Does not extends Remote service Interface.
    c) Should have all the methods of the synchronous interface.
    d) All methods should have return type of void.
     e)Throw no Exceptions.
     f)Additional final Reference parameter of type AsyncCallback.
Example Program :
        package com.example.Employee.client;
        import com.google.gwt.user.client.rpc.AsyncCallback;
        public interface HelloServiceAsync {
                 void sayHello(Person p,AsyncCallback callback);
          }
Note : Above two interfaces or in client Side.
Service implementation :
must create a server-side implementation of your client side synchronous RemoteService interface.
this must extends the GWT RemoteServiceServlet class.
Example Program : 
             package com.example.Employee.server;
             import com.example.Employee.client.HelloService;
             import com.example.Employee.client.Person;
               public class HelloServiceImpl implements HelloService {
                    public String sayHello(Person p) {
        return "Hello "+p.name+" How is the Weather at "+p.address+ " ?";
}
}

Note : above total 3 parts called as .
 1) Synchronous client service interface.
 2) Asynchronous client service interface.
3) server implementation service servlet.

Note: And the last part in RPC is Servlet, through which the client side class communicates.It is
an actual Implementation of RemoteServiceServlet.
Example Program : 

package com.example.Employee.server;
import com.example.Employee.client.HelloService;
import com.example.Employee.client.Person;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class HelloServlet extends RemoteServiceServlet implements HelloService {
private HelloService impl = new HelloServiceImpl();
public HelloServlet(){
super();
}
public String sayHello(Person p) {
//Pass through from servlet to Implementation.
return impl.sayHello(p);
}
}

Note : Actually Speaking the server side RemoteService  implementation  and RemoteServiceServlet    
          implementation,can be combined by doing like this .
Combination program:
 RemoteService  implementation  and RemoteServiceServlet implementation

package com.example.Employee.server;
import com.example.Employee.client.HelloService;
import com.example.Employee.client.Person;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class HelloServiceImpl extends RemoteServiceServlet implements HelloService {
public String sayHello(Person p) {
// TODO Auto-generated method stub
return "Hello "+p.name+" How is the Weather at "+p.address+ " ?";
}
}


Question : Why you want separate the RemoteService implementation and RemoteServletService
                 implementation ?
Answer :  Because in larger projects we are like to use the RemoteService outside of remoteServlet
  Service implementation.
Question : What is the use of Asynchronous interface?
Answer : Service side implementation of client side synchronous interface can be accessible in the 
               client side through the Asynchronous interface only.
Question: How to call server from the client?
Answer : Get the Asynchronous service interface from the static method GWT.create()
             and bind it to relative URL for our HelloServlet.
  Example Code : 
          //Obtain Async service for interface.
           HelloServiceAsync service = (HelloServiceAsync) GWT.create(HelloService.class);
          bind it to relative URL for our HelloServlet.
          ServiceDefTarget endpoint = (ServiceDefTarget) service;
          // Bind service  to HTTP path
         endpoint.setServiceEntryPoint(GWT.getModuleBaseURL() +"/HelloService");
Question : What is the Job of RemoteServiceServlet?
Answer : 1) Deserializes the object and pass it to service implementation .
              2) Serializes the object and pass it back to service interface.
 Question : What is GWT stub ?
 Answer : 1)Sits at service interface, serializes the object pass it to RemoteServiceServlet.
               2) Deserializes the object (result from RemoteServiceServlet) pass it to Asyncallback.
Question : What is JSNI ?
Answer : JSNI is required any time you want to call into native JavaScript from java , or ViceVersa.
              There are two sides to JSNI : JAVA and JavaScript.
Question : How to Write Javascript methods in java ?
Answer : Using native keyword and special comments  /*-{ alert(message);}-*/.
Question : How to access the java methods and java fields from within Javascript?
Answer : classes with @ symbol and methods or fields names with ::
 Example :  [Optional .] @class-name:: field-name
                  [Optional .]@class-name::method-name(parm-signature)(arguments)
Question : How to call java method from within the javascript ?
Answer : GWT JSNI uses set of character tokens to indicate the type information for the method
               your calling.
Example :  A java Method a signature like this in Java.
                 public String myMethod(String[] string,int POint,boolean Flag);
                you would invoke it from JSNI with a statement such as this.
              x.@com.my.classname::mymethod([Ljava/lang/StringIZ)(array,2,false);
NOTE : Mapping of Java types to JSNI type signature tokens.
             long : J
             int    : I
            Any Java Class :  L(fully-qualified class path); example : Ljava/lang/String;
            Arrays : [followed by the JSNI token for the contained type.

Question : What is JavaScriptObject class?
Answer :  It allows deep intervine between javascript and Java Objects.In otherwords we want javascript
objects looks like java Objects. A marker that GWT uses to denote the Javascript Objects.

Question : In Gwt how will you cancel the server request ?
   http://code.google.com/webtoolkit/doc/latest/DevGuideServerCommunication.html#DevGuideRemoteProcedureCalls

Question : In GW how will you handle the time out request?
Answer : 


Question: What is default time out interval for  GWT RPC call ?


Answer : RPC Services do have timeouts, its just that by default they are set to 0, which 
effectively means no timeout.


Good Article :
http://blog.johnhite.com/2010/09/02/gwtgxt-and-session-timeouts/




Question : In GWT how will you handle the Logging ?
 Answer : 


Question : In GWT how will you display an arrayList response in a Webpage?
Hint: There is some component in gwt.


Question :  What is Entry Point in GWT?
 Answer : 


Question : What are the Event Handlers in GWT ?
Answer : See my another Post ..


Question : what is *.gwt.xml ? what is   tag in that?
Answer :  The  *.gwt.xml file called as XML module descriptor. The line ““. tells your  
                 GWT  module to inherit the  GWT Log module.
                 Inherits uses only the fully qualified name of the GWT LOG module.


Question : What is *.index.js file how will you add some div tags into that?
Answer :


Question : What are the different panels in GWT ?
Answer : Dock-panel, vertical Panel, Flow-panel,Horizontal Panel, Absolute panel.


Question : What is the default request time out interval for a RPC call?
Answer   : It is zero.If you want to set the request time interval you can set using the 
                   RequestBuilder.


Question : Will you handle the request timed out exception in server or in client side?
Answer :


Question : where the server side classes will diploy in GWT ?
 Answer : Diploy in websever.


Question : Where the client side classes diploy in GWT ?
Answer : Delpoy in GWT ..


Question : Example of using third part GWT Module ?
Answer :  Gwt Module name : GWT log module .


            Advantages of this mudule :
             1)  Able to display the error,debug,info and warning messages as your app runs.
             2) Set log level globally .
             3) Even turnoff logging locally.



Saturday, November 6, 2010

Object Copying in Java

What are the possible ways to copy an Object in java?
Ans: Possibility 1 : Using the shallow Copy
        Possibility 2 : Using the Deep Copy


What is Shallow Copy?
Ans: In Shallow Copy, both the original and copied or duplicate objects share the same 
references.Example: if the original object have an vector, then the duplicate object will 
point to the vector. That means it does not make any new copy of vector.
BUT,we can add a new elements to duplicate object, if required, and that elements are 
only visible to the duplicate objects.


Simply, Shallow copy is something, where original and duplicate are just the elements in
the  original object.


What is Deep Copy?
Ans: In this the Original and duplicate will have the distinct variable set which are used
by the  original set.So modifying one of the variable in the original Object, does not affect
the duplicate Object.


Sounds Good, Then How to Implement the Deep Copy?
Ans: Using Java Object Serialization [ JOS ].
The idea is simple: Write the object to an array using JOS’s ObjectOutputStream and 
then use ObjectInputStream to reconsistute a copy of the object. The result will be a completely distinct object, with completely distinct referenced objects.



Sample Program:
public class UnoptimizedDeepCopy {

    /**
     * Returns a copy of the object, or null if the object cannot
     * be serialized.
     */
    public static Object copy(Object orig) {
        Object obj = null;
        try {
            // Write the object out to a byte array
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(bos);
            out.writeObject(orig);
            out.flush();
            out.close();

            // Make an input stream from the byte array and read
            // a copy of the object back in.
            ObjectInputStream in = new ObjectInputStream(
                new ByteArrayInputStream(bos.toByteArray()));
            obj = in.readObject();
        }
        catch(IOException e) {
            e.printStackTrace();
        }
        catch(ClassNotFoundException cnfe) {
            cnfe.printStackTrace();
        }
        return obj;
    }

}


Wednesday, November 3, 2010

Design Patterns in Java

 Creational Pattern 
Question : What is singleton Pattern in java?
Answer : The Singleton pattern, for example, is used to encapsulate the creation
of an object in order to maintain control over it. This not only ensures that 
only one is created, but also allows lazy instantiation; that is, the instantiation
of the object can be delayed until it is actually needed.
This is especially beneficial if the constructor needs to perform a costly
 operation, such as accessing a remote database.
Example of Singleton Class:

10 :public class SingletonObject
{
20 :private SingletonObject()
  {
    // no code req'd
  }
30:public static synchronized SingletonObject getSingletonObject()
  {
40:   if (ref == null)
        // it's ok, we can call this constructor
50:      ref = new SingletonObject();  
60:    return ref;
  }

70: public Object clone()
80: throws CloneNotSupportedException
  {
90:    throw new CloneNotSupportedException(); 
    // that'll teach 'em
  }

100: private static SingletonObject ref;
}

Observation : 
line 70: Creating method clone(), throw an exception, if any class trying 
to clone the singleton object.
line 30 - 60 :
Creates only one instance of the singleton class if not created early,and this
can access only one thread at a time.
line 20: Private constructor. so that so that other classes can't create a new instance.


What is Factory Pattern in Creational Pattern ?
Definition : Factory of what? Of classes. In simple words, if we have a super class 
and n sub-classes, and based on data provided, we have to return the object of
 one of the sub-classes, we use a factory pattern.


When to use a Factory Pattern?
The Factory patterns can be used in following cases:
1. When a class does not know which class of objects it must create.
2. A class specifies its sub-classes to specify which objects to create.
3. In programmer’s language (very raw form), you can use factory pattern

 where you have to create an object of any one of sub-classes depending on the
 data provided.


Example of Factory Pattern :

Example: Let’s suppose an application asks for entering the name and sex
 of a person. If the sex is Male (M), it displays welcome message saying Hello
 Mr. and if the sex is Female (F), it displays message saying
 Hello Ms .

The skeleton of the code can be given here.

public class Person {
// name string
public String name;
// gender : M or F
private String gender;
public String getName() {
return name;
}

public String getGender() {
return gender;
}
}// End of class

This is a simple class Person having methods for name and gender. Now, 
we will have two sub-classes, Male and Female which will print the welcome
message on the screen.
public class Male extends Person {
public Male(String fullName) {
System.out.println("Hello Mr. "+fullName);
}
}// End of class

Also, the class Female
public class Female extends Person {
public Female(String fullNname) {
System.out.println("Hello Ms. "+fullNname);
}
}// End of class
Now, we have to create a client, or a SalutationFactory which will return
the welcome message depending on the data provided.
public class SalutationFactory {
public static void main(String args[]) {
SalutationFactory factory = new SalutationFactory();
factory.getPerson(args[0], args[1]);
}
public Person getPerson(String name, String gender) {
if (gender.equals("M"))
return new Male(name);
else if(gender.equals("F"))
return new Female(name);
else
return null;
}
}// End of class
This class accepts two arguments from the system at runtime and prints the 
names.
Running the program:
After compiling and running the code on my computer with the arguments 
Prashant and M:
javac> java Prashant M
The result returned is: “Hello Mr. Prashant”.


What is Abstract Factory Pattern?
Ans : This pattern is one level of abstraction higher than factory pattern. This means 
that the abstract factory returns the factory of classes. Like Factory pattern returned
one of the several sub-classes, this returns such factory which later will return one of 
the sub-classes.

Creational Patterns - Builder Pattern
Builder, as the name suggests builds complex objects from simple ones 
step-by-step. It separates the construction of complex objects from their representation.
Question : Define design Patterns ?
Answer : Design patterns are recurring solutions to designing problems.
Question : How many Design-patterns and sub classes?
Answer : 23 design patterns under 3 sub classes.
            1) Creational Patterns.
            2)Behavioral Patterns.
            3)Structural Patterns.
Question : What is abstract factory pattern ?
Answer: it is one among the Creational pattern.returns the factory of classes.
Advantage : It isolates the names of concrete classes. the names of the actual implementing
classes not needed to be known on client side.because of this we can change the imple-
mentation from one factory to another.


Explain in layman Words:
Suppose i have to get the specification of one of the 3 computers (server,PC,Mainframe)
 the client really need not to know the name of that class(here suppose say Mainframe).
he can simply pass the name of the computer to a computer which will return exact
specification of that computer.
Example : 
public class ComputerType {
 private Computer comp;public static void main(String[] args) {
  ComputerType type = new ComputerType();Computer computer = type.getComputer("Server");
System.out.println("Monitor: "+computer.getMonitor().getSpecification());
System.out.println("RAM: "+computer.getRAM().getSpecification());
System.out.println("Processor: "+computer.getProcessor().getSpecification());
 }  
  /**
* Returns a computer for a type
*
* @param computerType String, PC / Workstation / Server
* @return Computer
*/
 public Computer getComputer(String computerType) {
  if (computerType.equals("PC"))
comp = new PC();
else if(computerType.equals("Workstation"))
comp = new Workstation();
else if(computerType.equals("Server"))
comp = new Server();
return comp;
 } 
}// End of class

Here where the user does not really need to the names of the server class.

Design Patterns in Java

 Creational Pattern 
What is singleton Pattern in java?
Ans : The Singleton pattern, for example, is used to encapsulate the creation
of an object in order to maintain control over it. This not only ensures that 
only one is created, but also allows lazy instantiation; that is, the instantiation
of the object can be delayed until it is actually needed.
This is especially beneficial if the constructor needs to perform a costly
 operation, such as accessing a remote database.
Example of Singleton Class:



10 :public class SingletonObject
{
20 :private SingletonObject()
  {
    // no code req'd
  }
30:public static synchronized SingletonObject getSingletonObject()
  {
40:   if (ref == null)
        // it's ok, we can call this constructor
50:      ref = new SingletonObject();  
60:    return ref;
  }

70: public Object clone()
80: throws CloneNotSupportedException
  {
90:    throw new CloneNotSupportedException(); 
    // that'll teach 'em
  }

100: private static SingletonObject ref;
}

Observation : 
line 70: Creating method clone(), throw an exception, if any class trying 
to clone the singleton object.
line 30 - 60 :
Creates only one instance of the singleton class if not created early,and this
can access only one thread at a time.
line 20: Private constructor. so that so that other classes can't create a new instance.


What is Factory Pattern in Creational Pattern ?
Definition : Factory of what? Of classes. In simple words, if we have a super class 
and n sub-classes, and based on data provided, we have to return the object of
 one of the sub-classes, we use a factory pattern.


When to use a Factory Pattern?
The Factory patterns can be used in following cases:
1. When a class does not know which class of objects it must create.
2. A class specifies its sub-classes to specify which objects to create.
3. In programmer’s language (very raw form), you can use factory pattern

 where you have to create an object of any one of sub-classes depending on the
 data provided.


Example of Factory Pattern :

Example: Let’s suppose an application asks for entering the name and sex
 of a person. If the sex is Male (M), it displays welcome message saying Hello
 Mr. and if the sex is Female (F), it displays message saying
 Hello Ms .

The skeleton of the code can be given here.

public class Person {
 // name string
public String name;
// gender : M or F
private String gender;
public String getName() {
return name;
}

public String getGender() {
return gender;
}
}// End of class

This is a simple class Person having methods for name and gender. Now, 
we will have two sub-classes, Male and Female which will print the welcome
message on the screen.
public class Male extends Person {
 public Male(String fullName) {
System.out.println("Hello Mr. "+fullName);
}
}// End of class

Also, the class Female
public class Female extends Person {
 public Female(String fullNname) {
System.out.println("Hello Ms. "+fullNname);
}
}// End of class
Now, we have to create a client, or a SalutationFactory which will return
the welcome message depending on the data provided.
public class SalutationFactory {
 public static void main(String args[]) {
SalutationFactory factory = new SalutationFactory();
factory.getPerson(args[0], args[1]);
}
public Person getPerson(String name, String gender) {
if (gender.equals("M"))
return new Male(name);
else if(gender.equals("F"))
return new Female(name);
else
return null;
}
}// End of class
This class accepts two arguments from the system at runtime and prints the 
names.
Running the program:
After compiling and running the code on my computer with the arguments 
Prashant and M:


javac> java Prashant M
The result returned is: “Hello Mr. Prashant”.



Monday, November 1, 2010

ThreadPool in Java

Question : What is Thread-Pool?
Ans :Thread Pool allows you to maintain fixed number of threads running 
assigned tasks to each thread.


Question : Advantages of Thread-Pool?
Ans : 1) It saves the machine work of creating new Threads.
         2) Thread can be recycled again and again.
         3) Thread pool size can be increased based on requirement.
         4) Response time can be quick.


Disadvantages of Thread Pool ?
Ans :
         1) Once a task is rejected because no thread is free from Thread-pool.
            then it leads to high degree of rejection rate.
         2) Chances of occurring the Deadlock.
         3) If a task is on waiting state then that waiting time can be too long.           

Reference Count in Garbage Collection

What is Reference Count ?
Ans : 
As a garbage collection algorithm, reference counting tracks for each object 
a count of the number of references to it held by other objects. If an object's
reference count reaches zero, the object has become inaccessible, and
 can be destroyed.


Advantages : 
In real-time applications or systems with limited memory,Programs cannot
 be interrupted. 
Disadvantages : 
1) Reference counting requires every memory-managed object to reserve
 space for  a reference count.
2) The naive algorithm described above can't handle reference cycles, an 
object which refers directly or indirectly to itself.

AWS certification question

AWS AWS Hi! this is for questions related to AWS questions. EC2 instances EC2 storage types cold HDD : 1. Defines performance in terms...