Pages

Friday, 20 September 2013

GWTModuleBase URL and HostPageBase URL

http://stackoverflow.com/q/12615663

Say I'm hosting a project at http://example.com/foo. I put all of the GWT files (which are generated in the /war/ directory after compiling) in http://example.com/foo/GwtModule directory.
Then on my host page, which is http://example.com/foo/bar, I put the following in the HTML:
<script type="text/javascript" src="http://example.com/foo/GwtModule/GwtModule.noCache.js"></script>.
My questions are:
  • Will GWT know to fetch its resources (e.g css files) from foo/GwtModule folder rather than trying to get them from foo/bar folder?
  • If I wanted to send a HTTP request to foo/signup, would GWT.getModuleBaseUrl() + "signup" work or will I have to parse the base url, remove "/bar" from it and replace it with "/signup"?
  • If I run the code locally as well as on a web server, will GWT automatically determine if the base url is http://localhost/foo/bar or http://example.com/foo/bar , or do I need to hard-code the base urls somewhere?
 http://stackoverflow.com/a/12618532
Will GWT know to fetch its resources (e.g css files) from foo/GwtModule folder rather than trying to get them from foo/bar folder?
Yes.
GWT always resolves the module base from the script URL (or a special <meta name='gwt:property'>)
If I wanted to send a HTTP request to foo/signup, would GWT.getModuleBaseUrl() + "signup" work or will I have to parse the base url, remove "/bar" from it and replace it with "/signup"?
GWT.getModuleBaseURL() will be /foo/GwtModule/.
You can either use GWT.getModuleBaseURL() + "/../signup" or "GWT.getHostPageBaseURL() + "/signup", in your case they'll both resolve to the same /foo/signup URL.
If I run the code locally as well as on a web server, will GWT automatically determine if the base url is http://localhost/foo/bar or http://example.com/foo/bar, or do I need to hard-code the base urls somewhere?
See answer to first question.
That means you'll have to use <script src="GwtModule/GwtModule.nocache.js"> or <script src="/foo/GwtModule/GwtModule.nocache.js"> in your host page.

Friday, 6 September 2013

JVM Class loader and java class initialization

JVM Class Loader

http://javarevisited.blogspot.sg/2012/07/when-class-loading-initialization-java-example.html 

What is ClassLoader in Java

In short here is the location from which Bootstrap, Extension and Application ClassLoader load Class files.

1) Bootstrap ClassLoader - JRE/lib/rt.jar
2) Extension ClassLoader - JRE/lib/ext or any directory denoted by java.ext.dirs
3) Application ClassLoader - CLASSPATH environment variable, -classpath or -cp option, Class-Path attribute of Manifest inside JAR file.

How ClassLoader works in Java

As I explained earlier Java ClassLoader works in three principles : delegation, visibility and uniqueness.


Delegation principles
As discussed on when a class is loaded and initialized in Java, a class is loaded in Java, when its needed. Suppose you have an application specific class called Abc.class, first request of loading this class will come to Application ClassLoader which will delegate to its parent Extension ClassLoader which further delegates to Primordial or Bootstrap class loader. Primordial will look for that class in rt.jar and since that class is not there, request comes to Extension class loader which looks on jre/lib/ext directory and tries to locate this class there, if class is found there than Extension class loader will load that class and Application class loader will never load that class but if its not loaded by extension class-loader than Application class loader loads it from Classpath in Java. Remember Classpath is used to load class files while PATH is used to locate executable like javac or java command.
Visibility Principle
According to visibility principle, Child ClassLoader can see class loaded by Parent ClassLoader but vice-versa is not true. Which mean if class Abc is loaded by Application class loader than trying to load class ABC explicitly using extension ClassLoader will throw either java.lang.ClassNotFoundException. as shown in below Example

package test;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Java program to demonstrate How ClassLoader works in Java,
 * in particular about visibility principle of ClassLoader.
 *
 * @author Javin Paul
 */


public class ClassLoaderTest {
 
    public static void main(String args[]) {
        try {         
            //printing ClassLoader of this class
            System.out.println("ClassLoaderTest.getClass().getClassLoader() : "

                                 + ClassLoaderTest.class.getClassLoader());

         
            //trying to explicitly load this class again using Extension class loader
            Class.forName("test.ClassLoaderTest", true 

                            ,  ClassLoaderTest.class.getClassLoader().getParent());
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ClassLoaderTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

Output:
ClassLoaderTest.getClass().getClassLoader() : sun.misc.Launcher$AppClassLoader@601bb1
16/08/2012 2:43:48 AM test.ClassLoaderTest main
SEVERE: null
java.lang.ClassNotFoundException: test.ClassLoaderTest
        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at sun.misc.Launcher$ExtClassLoader.findClass(Launcher.java:229)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:247)
        at test.ClassLoaderTest.main(ClassLoaderTest.java:29)
Uniqueness Principle
According to this principle a class loaded by Parent should not be loaded by Child ClassLoader again. Though its completely possible to write class loader which violates Delegation and Uniqueness principles and loads class by itself, its not something which is beneficial. You should follow all  class loader principle while writing your own ClassLoader.


Class loading and Initialization

http://javarevisited.blogspot.sg/2012/07/when-class-loading-initialization-java-example.html

When a Class is initialized in Java

After class loading, initialization of class takes place which means initializing all static members of class. A Class is initialized in Java when :

1) an Instance of class is created using either new() keyword or using reflection using class.forName(), which may throw ClassNotFoundException in Java.
2) an static method of Class is invoked.
3) an static field of Class is assigned.
4) an static field of class is used which is not a constant variable.
5) if Class is a top level class and an assert statement lexically nested within class is executed.



How Class is initialized in Java

Here are some of the rules of class initialization in Java:

1) Classes are initialized from top to bottom so field declared on top initialized before field declared in bottom
2) Super Class is initialized before Sub Class or derived class in Java
3) If Class initialization is triggered due to access of static field, only Class which has declared static field is initialized and it doesn't trigger initialization of super class or sub class even if static field is referenced by Type  of Sub Class, Sub Interface or by implementation class of interface.

4) interface initialization in Java doesn't cause super interfaces to be initialized.
5) static fields are initialized during static initialization of class while non static fields are initialized when instance of class is created. It means static fields are initialized before non static fields in Java.

6)non static fields are initialized by constructors in Java. sub class constructor implicitly call super class constructor before doing any initialization, which guarantees that non static or instance variables of super class is initialized before sub class.

Wednesday, 4 September 2013

URL, URI, Context Path, path info

Consider following servlet conf 
 <servlet>
        <servlet-name>NewServlet</servlet-name>
        <servlet-class>NewServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>NewServlet</servlet-name>
        <url-pattern>/NewServlet/*</url-pattern>
    </servlet-mapping>
Now When I hit url http://localhost:8084/JSPTemp1/NewServlet/jhi it will invoke NewServlet as it is mapped with pattern.
here
getRequestURI() =  /JSPTemp1/NewServlet/jhi
getPathInfo() = /jhi
getPathInfo()
returns
a String, decoded by the web container, specifying extra path information that comes after the servlet path but before the query string in the request URL; or null if the URL does not have any extra path information
getRequestURI()
returns
a String containing the part of the URL from the protocol name up to the query string



Its very important to know how container picks a servlet from which web app .(means how it identify the correct web app and then correct servlet)

Since the request uri consist of three main parts
Context Path- this helps container to choose the correct web app
ServletPath-this helps container to identify correct servlet into the from the requested web app.
PathInfo-in case of directory match

So if the request uri is
http://server.com/MyApp/servlet/xyz ,the container will first look for a web app named MyApp if it exists then it will look for the resource(here servlet) mapped to /servlet/xyz.

In case if there is no web app named MyApp then it (Tomcat)will look into the default web app (ROOT) for the servlet mapped to the uri /MyApp/servlet/xyz and proceed acc to that.

Web application and Servlets notes

Servlet Context and Session Listeners

• Servlet context listeners.
– These listeners are notified when the servlet context (i.e., the Web application) is initialized and destroyed.
• Servlet context attribute listeners.
– These listeners are notified when attributes are added to, removed from, or replaced in the servlet context.
• Session listeners.
– These listeners are notified when session objects are created, invalidated, or timed out.
• Session attribute listeners.
– These listeners are notified when attributes are added to, removed from, or replaced in any session.

Implement the appropriate interface.
– Use ServletContextListener, ServletContextAttributeListener,
HttpSessionListener, or HttpSessionAttributeListener

Use these objects.
– This process is application specific, but there are some common
themes. For example, with the servlet context, you are most likely
to read initialization parameters (getInitParameter), store data for
later access (setAttribute), and read previously stored data
(getAttribute).

Declare the listener.
– You do this with the listener and listener-class
elements of the general Web application deployment descriptor
(web.xml) or of a tag library descriptor file.

Provide any needed initialization parameters.
– Servlet context listeners commonly read context initialization
parameters to use as the basis of data that is made available to all
servlets and JSP pages. You use the context-param web.xml
element to provide the names and values of these initialization
parameters.

How to pass parameters to whole web application – ServletContext

Here’s a serlvet code example to demonstrate how to pass a parameter to whole web application by using ServletContext “init-param” in web.xml.

In the deployment descriptor (web.xml)

Put your parameter value in “init-param” and make sure outside the “servlet” element
        <servlet>
  <servlet-name>ServletName</servlet-name>
  <servlet-class>com.mkyong.ServletDemo</servlet-class>
 </servlet>
 
 <context-param>
   <param-name>email</param-name>
   <param-value>admin@email.com</param-value>
 </context-param>

Servlet code

public void doGet(HttpServletRequest request, HttpServletResponse response)
 throws IOException{
 
  PrintWriter pw = response.getWriter();
  pw.println(getServletContext().getInitParameter("email"));
 
 }
The “getServletContext().getInitParameter(“email”)” method is use to get the ServletContext parameter value in web.xml. In addition , this parameter is accessible by the whole web application.

How to pass parameters to a servlet – ServletConfig

Here’s a serlvet code example to demonstrate how to pass a parameter to a servlet by using ServletConfig “init-param” in web.xml

In the deployment descriptor (web.xml)

Put your parameter value in “init-param” and make sure inside the “servlet” element
        <servlet>
  <servlet-name>ServletName</servlet-name>
  <servlet-class>com.mkyong.ServletDemo</servlet-class>
 
  <init-param>
   <param-name>email</param-name>
   <param-value>admin@email.com</param-value>
  </init-param>
 </servlet>
 
 <servlet-mapping>
  <servlet-name>ServletName</servlet-name>
  <url-pattern>/Demo</url-pattern>
 </servlet-mapping>

Servlet code

public void doGet(HttpServletRequest request, HttpServletResponse response)
 throws IOException{
 
  PrintWriter pw = response.getWriter();
  pw.println(getServletConfig().getInitParameter("email"));
 
 }
The “getServletConfig().getInitParameter(“email”)” method is use to get the ServletConfig parameter value in web.xml. Btw, this parameter only available for this servlet only. If you want a parameter which allow globally access by whole web application, you need put the parameter in servlet context element.
Here’s an example to pass parameter to whole web application.