Complete Ajax Tutorial Step by Step

AJAX is a buzzword these days. What really is AJAX ? Is it a new technology ? New framework ?
AJAX ( Asynchronous Javascript And XML ) is mainly used for manipulating the part of the web page and transfering some computation to the client system. Using this technology the page need not be reloaded when a part of the page changes because of user actions. This can be achieved by dynamically getting the data from the server when user interaction happens using the XMLHTTPRequest object. This is the new approach of developing rich client application.
AJAX is the mix of :
  • XML and DOM
  • Javascript
  • XMLHttpRequest Object.
  • HTML ( or XHTML )
  • CSS

    The traditional problem we have is, a lack of interactiveness for web applications like Desktop applications. When we submit a form or request some data from the server from the client side, the client has to wait till the request is processed and response is sent back to the client. If the server side request handler is taking long time to process the request, the client has to wait till the response comes back, probably with "working-in-background" mouse pointer or "Busy" mouse pointer. This is really annoying to the users and if user clicks many times on the windows that’s working on the request, OS may report that window as "Not Responding" and shows a blank white screen with just the title bar appearing (referring to IE on Windows). And users like me will definitely go to the taskbar and try to end the process. What if we can do this request processing work in the background asynchronously not disturbing the front-end screen and display a proper and relevant message "Processing Request" or "Waiting for reply" and allow the user to continue with some other tasks in the same window.
  • A Simple usecase:
    In the web application I am working on has user selection field, which can be used to select any corporate user. (This is used to select users in a HTML form). Once the user selects "user selection" field and selects the particular corporate user, then the information regarding the selected user , like phone number, mailstop, mail address, manager, will be displayed in other fields of the form. The present solution developed waits till the request is processed and user can’t do any other task, like filling up other fields of the form in the same page. And sometimes, it takes nearly 30 seconds to 1 min for the response. If the user tries to click the window two or three times during this period then a blank window will appear and nothing works. And as I told you before, users like me will definitely kill the window using Task Manger and I have done that many times. This is a real annoying situation for the end user. This can be quite enough for a user to stop using the application altogether. So, what if we process that request of getting user information in the background asynchronously and still allowing the user to work on other fields of the form and process the information once we get the response from the back-end server ?
    This kind of situations can be very well handled using AJAX, which has A ( Asynchronous ) at it’s core. Let’s get to the code and see how we can use AJAX in an application.
    XMLHttpRequest Object:
    One of the core component in AJAX framework is XMLHttpRequest object which allows asynchronous processing. XMLHttpRequest object also supports events. So, we can take actions whenever that’s necessary instead of continously checking for the status of the request. For example, we can just set a event handler to execute when the request is completed and response is received and continue with other tasks in the page and or wait for user input. This object also supports XML content. If the response is XML content then we can directly get a XML DOM object instead of taking the string and constructing the XML DOM object explicitly. Let’s look at the features of this object.

    Object Methods (Most commonly used ):
    open( method, URL, [isAsynchronous]) : This method is used to tell XMLHTTPRequest object which url to be considered to open the connection, what’s the method to use (GET/POST/PUT) and whether to process this request (accessing the specified URL) asynchronously or synchronously. The third parameter is option and by default it’s true, meaning that the request is processed asynchronously. The other optional parameters include username and password.
    Example:
    var xmlHttpRequest; //XMLHTTPRequest object
    ...... ( object construction goes here...will look into this later)
    xmlHttpReuqest.open("GET","http://www.geocities.com/keelypavan/test.xml",true) // This method tells the object to get
    using GET method asynchronously. This is a dummy URL I used for demonstration purpose.
    Note: This open doesn’t really open the connection to the server. We should call send(..) method for the request to be actually sent.
    send( parameters as string ) : This method is used to actually send the request to the server for processing. Parameters if any specified will be sent to the server. Typically if the method id GET then the parameter will be null or an empty string or call the method without any parameters. If the method is POST then the parameter string would be the POST parameters in query string format, i.e. name=value pairs delimited by "&".
    Example:
    var xmlHttpRequest; //XMLHTTPRequest object
    xmlHttpRequest.send( null ); //for GET
    xmlHttpRequest.send( "name1=value1&name2=value2....");

    Note: Make sure to set the onreadystatechange event handler before using the send method on the object.
    abort():This Method aborts the request operation.
    setRequestHeader( headerName, headerValue): Sets the request headers that will be sent to the server with the request.
    Example:
    var xmlHttpRequest; //XMLHTTPRequest object
    xmlHttpRequest.setRequestHeader("IF-MODIFIED-SINCE","Sat, 04 Feb 2006 17:47:00 PST");

    getResponseHeader( headerName ): Gets the specified response header sent by the server. Example response header are, content-type, content-length etc.
    getAllResponseHeaders():Gets all the response header with header name and value as a string.

    Properties:
    readystate: Returns the ready state of the http request, which represents the internal state of the obejct. Values are listed below.

    0Unintialized
    1Loading
    2Loaded
    3Interactive
    4Completed


    onreadystatechange: Sets the event handler function which will be called everytime there is a state change (readystate value change).This method is useful as we are requesting the resource from server asynchronously not waiting for the response. So, applications can use this method to come back and perform the necessary action when the request is completed.
    status: Returns the status sent by the server. This status is HTTP status code. At the high level these codes mean:
    1xxInformational
    2xxSuccessful
    3xxRedirection
    4xxClient Error
    5xxServer Error


    statusText:Returns the text message (string) associated with the status code returned by the server.
    For Example: Server send "OK" with the status code 200.
    responseText: Returns the content of the response as a string returned by the server. Using this properly when the object is not is completed "readystate" will give an error.
    reponseXML: Returns the XML DOM Document object if the response content is XML. For this to work, the server should send the XML content with content-type set as "text/xml" otherwise the responseXML will be empty. This is an important thing for developers as sometimes everything would be fine, the response will be XML content and XML will be well-formed but the responseXML method will not return DOM Document object.
    If the response content is not well-formed XML, then the responseXML will return DOM Document with the parseError properly set so that applications can be aware of the problem.
    Example:
    Now let’s take an example and see how AJAX works.
    Note: The sample application I developed works in IE, will try to develop a cross-browser app soon.
    The sample application gets the RSS feeds from http://www.traffic.com/ site and displays them in the page.

    Note: As this application tries to get the RSS feeds from traffic.com site, the security option allowing access to other domain resources should be enabled.
    Object Creation:First let’s look at the object creation.
    Object creation code:
    if( window.XMLHttpRequest )
    {
    try{
    xmlHTTPObj = new XMLHttpRequest();
    }catch(e)
    {
    xmlHTTPObj = null;
    }
    }
    else if( window.ActiveXObject )
    {
    try{
    xmlHTTPObj = new ActiveXObject("MSXML2.XMLHTTP");
    }catch( e )
    {
    xmlHTTPObj = null;
    }
    if( xmlHTTPObj == null )
    {
    try{
    xmlHTTPObj = new ActiveXObject("Microsoft.XMLHTTP");
    }catch(e)
    {
    xmlHTTPObj = null;
    }
    }
    }

    This code uses the object detection technique to find out whether the object is defined in the browser environment. If yes, then this code creates that particular object and returns it. The other way of creating this object is using browser detection technique, meaning, check which browser is executing this piece of code and create the object accordingly. If it can't create the object, it would return a null value.

    Sending Request:
    Piece of code used for sending request:

    document.getElementById("trafficDetails").innerHTML = "Loading Data ...";
    var selectedCity = obj.options[ obj.selectedIndex ].value;
    if( selectedCity != "" )
    {
    xmlhttp.open("GET",rssXMLBaseURL+trafficRSSXMLs.get( selectedCity ),true );
    xmlhttp.setRequestHeader("If-Modified-Since","Thu, 26 Jan 2006 00:00:00 GMT");
    xmlhttp.onreadystatechange = processRequest;
    xmlhttp.send( "" );
    }
    else
    {
    document.getElementById("trafficDetails").innerHTML = "Select a city";
    }


    it uses, open(...), setRequestHeader(...), onreadystatechange, send() with the XMLHttpRequest object.
    The first method used with XMLHttpRequest object is open(...). This method assigns the HTTP method to use to get the resource, URL and asynchronous flag.
    setRequestHeader method is used in this case to check to see if the server resource has changed after the specified date and time. This has been set to a past date to get the content everytime.
    onreadystatechange(..) method is used to set the event handler method.
    At this point, the request is not yet sent but all other parameters are set. The next method send() transmits the HTTP request to the server. Be sure to set event handler method, onreadystatechange, before using send() method on the object.
    Event Handler Method ( i.e. processRequest ): This method will be called every time there is a change in the readystate of the object. This method checks the readystate value and if it’s in completed state ( value 4 ) then it tries to see what’s the status code returned by the server. If status is 200 (successful) then it tries to get the content with responseXML and transforms using XSLT. You can get the XSLT source. If the status code is not 200, then it reports an error string statusText.
    The piece code is:
    if( xmlhttp.readystate == 4 )
    {
    var divObj = document.getElementById("trafficDetails");
    if( xmlhttp.status == 200 )
    {
    divObj.innerHTML = xmlhttp.responseXML.transformNode( xsltDoc );
    }
    else
    {
    divObj.innerHTML = "Could not load data";
    alert( "Error:"+xmlhttp.statusText );
    }
    }

    End of example:
    Conclusion:
    AJAX is very much useful to get the dynamic content from the server. This can be used to get the content of from the server even after the page load, in better terms, lazy loading and create very rich and interactive applications.

    Data Interchange formats for Ajax based applications using XML and JSON

    With the introduction of Ajax, the classic web-applications are moving towards sending data instead of content to the web browser (in most of the cases). The emphasis on data interchange formats is more than before. This article points out available data interchange formats.

    If you consider a normal web-application (non-Ajax), server sends some content (normally, HTML content) and like a faithful servant, web browser displays it and it may have Javascript working but to a limited level. But when we talk about richness of the application, we need something more than this. Most part of how we display the content should be left to the application running in browser, so that it can change the content or even look and feel dynamically, i.e. Ajax app, especially Javascript.

    As we all know, the XMLHttpRequest is the core component of Ajax and it communicates with the server to get data to display in the browser without any reload of the page. Different applications use different data formats based on their application needs.

    Following types of data interchange I can think of in the industry now.

    - XML (eXtensible Markup Language)
    - JSON (Javascript Object Notation)
    - String with delimiters
    - Script-centric approach
    - Classic way of sending content.


    Well, first three formats together can be considered data-centric approaches. But for clarity I am separating them. Let’s discuss each of the formats individually.

    XML:

    XML is a web standard for data interchange formats. It’s been around for quite sometime now. The support for XML in Javascript is very good as most of the browser implemented XML DOM specifications. The main usage of XML is that structured and hierarchical data can be represented very well and it’s readable by human beings. This comes with a cost of including meta-data, which describes what that data represents. Of course, I have seen many XML documents, which you can’t make out anything from but let’s keep that aside for now. One good thing about this is its pure data representation, which lacks in HTML. (HTML represents data intermingled with styles and formatting.)

    Once you get the XML content as a response to the client-side you can use XSLT to transform the data into HTML content or you can use XML DOM API to parse and access XML and form HTML content, may be using innerHTML or standard DOM API.

    Let’s take an example and see how we can represent the same data/content in all the formats. The example I am going to take is folder contents’ information. The XML is self-explanatory, so I am not spending much time explaining what it represents.

    <?xml version="1.0"?>
    <items>
    <item>
    <name>Test Document</name>
    <type>document</type>
    <creator>Test creator</creator>
    </item>
    <item>
    <name>Test Folder</name>
    <type>folder</type>
    <creator>Test Creator 2</creator>
    </item>
    <item>
    <name>Test Shortcut</name>
    <type>shortcut</type>
    <creator>Test Creator 3</creator>
    </item>
    </items>
    JSON:

    JSON is a light-weight data interchange format. It’s a text (string) representation of Javascript objects. An object in Javascript is represented in key, value pairs. A key is a string enclosed in double-quotes whereas the value can be number, string, boolean (true or false), object, array or null. Following paragraph explains JSON format in brief.

  • An object is a set of name, value pairs and it’s enclosed in "{" and "}". Name and value is separated by " : " and Name, value pairs are separated by " , ".

  • An array is ordered collection of values and is enclosed in "[" and "]" and values are separated by " , ".

  • Name is a string enclosed in double-quotes.

  • Value can be anyone of the following. String, Number, Boolean (true or false), Object, Array, null.


  • The advantage of JSON is that it’s more compact than XML format and parsing JSON is a lot simpler than XML. You just need to pass JSON string to eval of Javascript or you can also download JSON parsers for different programming languages from http://www.json.org/. As we have parsers for most of the famous programming languages, it makes JSON a good data interchange format. I know that a lot of people think that eval is very evil but doing eval once to evaluate the JSON string will not cause any big performance impact. But if the data grows larger then definitely JSON will not be a good option.

    Example: Let’s take the same example I represented in XML and write that in JSON format.

    {items:[
    {"name": "Test Document", "type": "document", "creator": "Test creator"},
    {"name": "Test Folder", "type": "folder", "creator": "Test Creator 2"},
    {"name": "Test Shortcut", "type": "shortcut", "creator": "Test Creator 3"}
    ]}

    String with delimiters:
    Though it’s not a standard to use a plain string with delimiters as the response format, it has some advantages. We can use regular expressions or split the string into pieces using the delimiter and use the data as an array. Not much of processing is required for parsing the string.

    The problem with this approach is that we need to rely on the position of the elements. And if there is any change in the positions of the elements (data) then it requires a change in the client side code. And representing deep hierarchical data is very difficult and error-prone in this approach.

    Example:The data represented in two examples above could be represented in this approach as:

    Test Document#document#Test creator$$Test Folder#folder#Test Creator 2$$Test Shortcut#shortcut#Test Creator 3

    As you see this format is very compact because it doesn’t contain any meta-data but as the nested ness of data increases, like corporate taxonomy, representing that data is this fashion would definitely be a problem.

    Script-centric approach:
    In this approach a piece of script will sent from the server like assigning values to variables, function calls, which will be dynamically evaluated at the client side to perform the necessary actions.

    The disadvantage of this approach is that it assumes some Javascript environment (like some functions defined in the page) at the client side. This means more coupling with the response with the page that’s requesting the resource.

    Example: As we can’t represent data as-is and there will be piece of Javascript code as a response in this approach, there could be multiple ways you can represent this.

    Response:
    var matchingItems = {items:[
    {"name": "Test Document", "type": "document", "creator": "Test creator"},
    {"name": "Test Folder", "type": "folder", "creator": "Test Creator 2"},
    {"name": "Test Shortcut", "type": "shortcut", "creator": "Test Creator 3"}
    ]} //new lines are just for clarity.

    someMethod( matchingitems,… )


    Content-Centric Approaches:

    In the content-centric approach, the response from the server contains HTML content. So, the client side application (Javascript) has to take the content as is and place the content in any container using innerHTML or related methods. The advantage of this approach is that there is no explicit parsing of the data required. I used “explicit”, because internally when you use HTML content, the data has to parsed and shown in the web page. But the disadvantage is that it’s data with formatting tags. If you want to reuse the data of a response in this approach then we have to rely on DOM methods to retrieve the data, which is cumbersome.

    Example:

    As the response would be in HTML format, we can represent this in many ways depending on the need. Here is a way:

    Response:

    <div><span>Test Document</span><span>document</span><span>Test Creator</span></div>
    <div><span>Test Folder</span><span>folder</span><span>Test Creator2</span></div>
    <div><span>Test Shortcut</span><span>shortcut</span><span>Test Creator3</span></div>

    We can take this content as-is and insert as HTML content in any of the allowed elements using innerHTML (or related) method. There’s not much processing required at the client side.

    Sites/Apps using these formats:

    XML:
  • Netflix

  • Dell

  • Google suggestions toolbar (new beta)
  • Script-centric approach:
  • Google Suggest

  • JSON format:
  • Yahoo provides JSON for its web services.
  • Conclusion: Depending on application needs, appropriate data interchange format has to be chosen. This article just describes the options available and the decision is yours.

    Interview First Question : Introduce yourself / Tell something about yourself / Describe yourself

    It’s probably the most common question. It’s very simple to answer this question, but a decent answer requires you to keep few things in mind before coming up with your version of the answer. Answer to this question should be concise and precise. Normally this is the first question in any interview and an effective answer to this question will boost your confidence for the entire interview. As we all know that first impression is of utmost importance, so it may be better for you to work on the answer to this question in advance instead of giving an instant reply. All the interviewers know that the candidates already know this question, so the answer you give in the interview is normally supposed to be the best you can give. Beware of it :-)

    Try to cover your name, place you’re from, the highest degree you hold, years of experience (if applicable) in one-two lines. After that, you should present your qualification in the best possible way to align the acquired skills with those needed for the job you’re applying for. Don’t let the panel know that you’re not even aware of the major skills required for the job. If you feel that only a subset of skills required can be aligned with the skills you’ve acquired by your qualification, work exp, etc. then try to present yourself well aware of the gap and do mention the path you’ll follow the imbibe rest of the skills not only to make yourself fit into the profile, but to excel in that. Your learning skills, analytical skills, problem solving skills, and most importantly your attitude will come handy in such a situation. Figure out the instances in your life where you really proved something similar by using any of these (or may be some other skill). The interviewers may ask an example. You should be ready with that. But, don’t rush into the example straightaway. You may prefer to take a pause (few seconds) before explaining that example. Always keep in mind that the more interactive the session is, the better it may be for you. If you’re about to speak at length about something, present only the gist first and then seek their approval before explaining the whole idea. In the end, don’t forget to ask them if you really answered everything they wanted. For example, you may ask “Is there anything specific you wanted to know and I didn’t cover so far?”

    Avoid including your percentage, CPI, honors/awards, etc., which you’ve already mentioned in your resume. You may lose their attention by doing so. They already know, so no point repeating the same. They’ll anyway ask you to elaborate on something they really want.

    If you’re applying for a profile, you’ve already been into somewhere (or maybe in current employment) then try to include a reference to that in your answer. They’ll probably ask you to explain or elaborate on that. The point I’m trying to make here is that every sentence you speak while answering this question should either reflect or give you a chance to present one or more of the reasons why they should consider you a better candidate for the profile.


    Sample answer:- (As I've already said that the complete answer to this question will result from the interaction you would have with the panel. This sample answer is just a starter. They may intervene in the middle. You’ll anyway end your answer by asking them if they want you to cover anything else.)


    “My name is <…> (this is also there in your resume, but it’s normally included :-)). I’m from <place … city and state should suffice>, have completed my schooling from <place>, from <institute> (prefer using the name of the university only, if you think your college/institute is not among the very well known colleges/institutes). I’m currently working (if applicable) with <company> for <years> as a <profile>. I’m handling/managing/doing <mention whatever you do>. I’m quite friendly with my friends/colleagues and like to work in a team. I’m looking for <the position you're looking for> and I believe my skills and abilities are rightly suitable for that. I like to play <the sports you like>... Anything specific you wanted me to cover and I didn’t do so far?”

    Tricky Overloading in Core java | Method overloading concept in java

    Choosing the Most Specific Method - Tricky Method Overloading

    Let's start with looking at a code-segment and try to think of the output/error, it would produce when compiled/executed and subsequently we'll discuss the behavior of code.

    
    public class NullTest {
    
       public static void method(Object obj){
         System.out.println("method with param type - Object");
       }
     
       public static void method(String obj){
         System.out.println("method with param type - String");
       }
     
       public static void main(String [] args){
         method(null);
       }
    }

    So, what do you expect as the output here? Before thinking about the output, do you really expect the code to compile successfully? Well... yeah, the code will compile and run fine as opposed to anyone who might have sensed an ambiguity here - we'll see the reason soon.

    Since the methods are overloaded, the resolution will be done at compile-time only. Which method do you see being bind here - the one with parameter type 'Object' or the one with parameter type 'String' and why? Of course, the compiler can't bind two methods with one call, so on what basis would it pick the most suitable? Which method would be picked, is evident from the output given below:-

    
    method with param type - String

    Any guesses for why a special treatment is being given to 'String' here? Well... it's not actually for 'String' class specifically, but any sub-class would get a preference over the super class in such a situation. But, why? Because JLS (Section: 15.12.2.5) allows this. It clearly says:

    "If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen."

    As you easily deduce that the compiler should be able to pick 'the most specific', failing which it will throw a compile-time error. Let's understand it with the below code-segment which doesn't compile because the compiler can't pick 'the most specific' here.

    
    public class NullTest {
    
       public static void method(Object obj){
         System.out.println("method with param type - Object");
       }
     
       public static void method(String str){
         System.out.println("method with param type - String");
       }
     
       public static void method(StringBuffer strBuf){
         System.out.println("method with param type - StringBuffer");
       }
     
       public static void main(String [] args){
         method(null); //... compile-time error!
       }
    }

    Why is the compiler not able to pick 'the most specific' here - because both String and StringBuffer are are sub-classes of the Object class, but without being in the same inheritance hierarchy. For finding 'the most specific' method, the compiler needs to find a method having the parameter type, which is a sub-class of the parameter types of all other overloaded methods.

    This holds true for overloaded methods having more than one parameters as well. The compiler would pick 'the most specific' by looking which method is having at least one of its parameter types as a clear sub-class of the corresponding parameter type and other parameter types being either the same or clear sub-classes, in all other overloaded methods. If it can find one, good, otherwise it will throw a compile-time error. For example:

    
    public class NullTest {
    
     public static void method(Object obj, Object obj1){
       System.out.println("method with param types - Object, Object");
     }
    
     public static void method(String str, Object obj){
       System.out.println("method with param types - String, Object");
     }
    
     public static void main(String [] args){
       method(null, null);
     }
    }
    
    Output
    
    method with param types - String, Object

    In this case the compiler can easily pick 'the most specific' as the method having parameter types (String, Object) as the other overloaded method is having its parameter types as (Object, Object) - clearly 'String' is a subclass of 'Object' and the other parameter is of same type, so the method with parameter types (String, Object) can be picked with ease. But, the below code would throw a compile-time error as none of the methods satisfy the condition for being picked as 'the most specific' method.

    
    public class NullTest {
    
     public static void method(Object obj, String obj1){
       System.out.println("method with param types - Object, String");
     }
    
     public static void method(String str, Object str1){
       System.out.println("method with param types - String, Object");
     }
    
     public static void main(String [] args){
       method(null, null); //... compile-time error!
     }
    }


    Difference between getRequestDispatcher method of the ServletRequest interface and that of the ServletContext interface?

    RequestDispatcher getRequestDispatcher(String path) - the same method belongs to both the ServletRequest interface and the ServletContext interface. This method returns a RequestDispatcher object for the resource (dynamic or static) located at the given path. We can use this RequestDispatcher object to forward a request to the resource or to include the resource in a response.

    Difference between the two getRequestDispatcher methods

    The difference between ServletRequest.getRequestDispatcher(String path) and ServletContext.getRequestDispatcher(String path) is that the former can accept a relative path as well whereas the latter can accept paths relative to the current context root only.

    If the path starts with a '/' in the getRequestDispatcher(String path) of the ServletRequest interface then it's interpreted as being relative to the current context root otherwise it'll be a relative to the request of the calling servlet. Whereas, the path of the getRequestDispatcher(String path) of the ServletContext interface must start with '/' only - being relative to the current context root.

    Another difference between the two is that path of the getRequestDispatche(String path) of the ServletRequest interface cannot extend outside the current servlet context whereas getRequestDispatcher(String path) of the ServletContext can use the getContext(String uripath) method
    to obtain RequestDispatcher for resources in foreign contexts.

    Java Web service : Ways of combining Web Services. Orchestration vs Choreography


    As we know that Web Services are actually application components each of which normally performs one discrete functionality of the overall application. So, we definitely need some way of combining these individual components to make the entire application work. There are two popular ways of combining Web Services, which are:-

    • Orchestration - we have a central controller in this case and it can be executed
    • Choreography - we don't have any controller here and it can't be executed directly
    Orchestration

    In this case we have a central controller process which controls and co-ordinates all the Web Services involved in the application. This central process can be a Web Service a well. The point to note in this case is that all other Web Services don't really know that they are participating in a higher-level business process. How the participating Web Services will be called, what will be the control flow, what all transformation will take place, ... these all things are known only to the central controller process. The other Web Services simply honor the requests whenever called. The below diagram makes it quite easier to understand the overall process.


    Since Orchestration provides a controlled environment hence alternative scenarios can be used in case a fault occurs in the normal flow. For example, suppose we need to call a Web Service which may result into fault and in such a case we may need to either call another Web Service OR to simply use a default value. IN case of Orchestration it's very easy to achieve - maybe by just having a switch activity to transfer the control either to the alternative Web Service OR to compute the required Default Value.

    Choreography

    Here we don't have any central controller process and hence all the participating Web Services know when to call, whom to interact, when to execute operations, etc. We can visualize choreography just like a collaborative effort of many participating Web Services and since we don't have any controller hence all the Web Services need to know the actual business process and things involved in it like message exchanges, time of call, etc. Find below a diagram depicting a typical Choreography process.


    Orchestration vs Choregraphy

    Easy to fugure out, right? Orchestration has a central controller process and all other participating Web Services don't know about the actual business process. They are called only by the controller process and they don't know anything about other Web Services involved in the application. Whereas Choreography doesn't have any controller process/service and all the participating Web Services know the actual business process and they are well aware of which all Web Services they need to interact with, when to execute the operations, etc.

    So, we can say that Orchestration is a controlled and co-ordinated way of utilizing the services of all the participating Web Services whereas Choreography is just a collaborative effort of utilizing the services of the participating Web Services.

    Falut handling is easier in Orchestration as the execution is controlled which is not the case with Choreography. Web Services can be easily and transparently replaced in case of Orchestration as the involved Web Services don't know the actual business process whereas it'll be difficult in case of Choreography.

    Thus, we see that Orchestration is having quite a few advantages over Choreography and hence Orchestrtaion is normally preferred for business process implementations, but Choreography may certainly have its own usage in some selected scenarios.

    Xml tutorial : XML Schema and its anatomy, Applications of XML Schemas, Namespaces

    XML Schema was approved as an official recommendation by the WOrld Wide Web Consortium (W3C) in 2001. W3C defines XML Schema as "XML Schemas express shared vocabularies and allow machines to carry out rules made by people. They provide a means for defining the structure, content, and semantics of XML documents."

    As it's clear from the definition that XML Schema is a mechanism of defining basically the
    structure, content and semantics of XML Documents which conform to the Schema under consideration. But, DTD (Document Type Definition) also serves a similar purpose. So, why a need for something different was felt?

    Well... the short answer is that XML Schema just evolved from DTDs in the wake of getting a
    more powerful and flexible mechanism as compared to what DTD supported. XML Schemas are XML documents themselves and hence all the benefits of XML - parsing, programmatically accessing, validating, and extending automatically apply to XML Schemas as well. These all benefits make Schemas a far better alternative to DTDs.

    Do we still need DTDs?


    Yeah, we need them, but probably only for the legacy applications where they have been in
    use since long. Almost all the newer applications now use Schemas only for the simple reason that XML Schemas are much more powerful & flexible and therefore offer many advantages over DTDs. However, DTDs are still supported and they can be used in tandem with XML Schemas as well.

    Anatomy of XML Schemas


    An XML Schema is made up of the following declarations and definitions. Few of these might
    be optional as well.

    • Document Type Declaration: Since an XML Schema is also an XML Document which obviously conforms to the W3C XML recommendations and hence they may contain the particular document type declaration, but this is not a mandatory requirement. If present, it's inferred by the root element named <Schema>
    • Namespace Declaration: Again an optional declaration which is used to provide a context for element names and attribute names used within an XML Document (which conforms to this Schema). This helps in avoiding ambiguity in name resolution and thereby helps building and extending XML Documents using URIs ensuring unique names for elements and attributes. Namespaces can either be defined inline (called inline xml namespace which are defined inline with element and atribute in the XML) or as Expanded names where the namespace name is combined with the local name to uniquely identify the particular name. Both the namespace and the local name are separated with a colon (e.g., NamespaceName:LocalName).
    • Type Definitions: These definitions are used to define Simple or Complex data types or structures, which are later re-used by all the client content models.
    • Element/Attribute Declarations: This section of an XML Schema defines the elements and their respective attributes which are used for tags in the XML instances using the Schema. Various constraints like id, type, max/minOccurs, substitutionGroup, etc. can also be defined in this section of an XML Schema.
    • Sequence Definition: As the name might suggest this section is used to enforce the order in which the child elements of the XML instances (using the XML Schema in consideration) are required to appear.

    XML Schema applications/uses

    • Data Validation: XML Schema is used to define the structure of the elements and the attributes within the elements and this definition helps the XML parsers to validate the XML Document Syntax, Datatypes used by the XML Document/Instance, and/or the Inclusion of mandatory elements or attributes. This obviously helps the application designers to delegate some of the basic data validation (and data sufficiency) tasks to the XML Schema rather than doing all of them programmatically.
    • Content Model Definition: XML Schema supports both simple and complex data types definitions which ultimately provides flexibility of using concepts like inheritance to the data syntax. This consequently helps building the XML Schema defining extensible models highly suitable for large and complex applications.
    • Data Exchange/Integration: Since XML Schemas are themselves XML documents and hence they can be parsed and accessed similar to other XML instances by variety of XML companion tools for various purposes. For example: an XSD when used in conjunction with an appropriate XSLT and an XML-enabled database can support the changes made to the global elements defined by the XSD to be processed consistently. In addition, the output can simultaneously be produced in various formats like PDF, Doc, RTF, HTML, etc. using the single source publishing methodology. The data-oriented datatypes provided in XML Schema 1.1, in addition to the document-oriented datatypes as supported in the previous versions, facilitate complex document exchange and data integration scenarios. Namespaces supported by XML Schema can be used to have more than one vocabulary at a time in an XML instance as the namespaces enable the XML documents to contain unique identifiers. Namespaces facilitate ample opportunities for data exchange and integration by enabling the entire XML frameworks to co-exist within the same architecture. This feature is extremely helpful in mergers and acquisitions, and supply chain requirements, where we generally have a plethora of heterogeneous data constructs.
    • Industry XML Standards: These standards aim to streamline and provide a basis for industry-wide data integration by implementing common XML vocabularies which enable the business partners to seamlessly exchange data across different systems and architectures. Several new industry standards are strongly being followed and they are paving way for a seamless data integration and inter-operability. Some of these standards are DITA, DocBook, SCORM, ACORD, CXML, FIXML, and XBRL.

    An interesting try-catch-finally scenario | Java exception

    If not very comfortable with finally block and its execution then you may probably like to go through this article It covers some pretty interesting scenarios covering various possible scenarios of try, catch, and finally blocks followed by the precise explanation of their execution in each of these scenarios. Come back to this article once you finish that as this article is more like a logical extension of that article. If already comfortable with try-catch-finally then you may proceed straightaway with this one.

    One of our visitors has asked another interesting scenario involving nested try blocks in response to the above mentioned article. I have created two possible cases taking reference of that scenario and have tried to explain the execution of each of these cases below:

    Case #1: nested 'try' with a 'finally' block associated with the inner 'try' and a 'catch' with the outer
    
    public class TestFinally {
    
       public static void main(String[] args) {
            
             try{
                   try{
                         throw new NullPointerException ("e1");
                   }
                   finally{
                         System.out.println("e2");
                   }
             }
             catch(Exception e){
                         e.printStackTrace();
             }
       }
    }

    Output: what do you expect as the output here? As we all know that 'finally' will always get executed irrespective of 'try' finishes its execution with or without exception. In our case the inner 'try' throws an exception which has no matching 'catch' associated with the corresponding (inner) 'try' block. As per the Exception Mechanism in Java, the uncaught exception will be propagated until it's either executed by some matching 'catch' block on its way back or it'll be handled by the default JVM handler which simply terminates the program after printing a stack trace.

    But, before the control leaves the inner 'try' block, the entire inner block should complete its execution and hence the associated 'finally' block will get executed before the control leaves the inner block for the simple reason that 'finally' in any case has to be executed and the control won't go back to the inner block once it comes out of it.

    The 'catch' block associated with the outer 'try' block expects an exception of type 'Exception' and hence a 'NullPointerException' (a subclass of the the Exception class) thrown from the inner 'try' block (which has been propagated) can be handled by this 'catch' handler and hence this 'catch' block will be executed. Do I still need to tell you the output of this code-snippet. Here is it for your reference:
    
    e2
    
    java.lang.NullPointerException: e1
    
         at TestFinally.main(TestFinally.java:8)

    Case #2: nested 'try' with 'catch' block associated with the inner 'try' and 'finally' with the outer
    
    public class TestFinally2 {
    
       public static void main(String[] args) {
    
             try{
                   try{
                         throw new NullPointerException ("e1");
                   }
                   catch(Exception e){
                         e.printStackTrace();
                   }
             }
             finally{
                         System.out.println("e2");
             }
       }
    }

    Output: This is pretty straightforward I think. Since an exception is being thrown from the inner 'try' block and we have an associated matching 'catch' handler for this exception so obviously it will be handled there. Now the control leaves the inner block and hence the outer 'finally' gets executed as 'finally' block in any case has to be executed. All right? Please find below the output for your reference:
    
    java.lang.NullPointerException: e1
    
         at TestFinally2.main(TestFinally2.java:8)
    
    e2

    Java error: java.lang.UnsupportedClassVersionError: when is it thrown by a JVM & how to resolve it?

    UnsupportedClassVersionError is (evidently a descendant of the Error class in Java) which subclasses java.lang.ClassFormatError which in turn subclasses java.lang.LinkageError (which is a direct subclass of java.lang.Error). This error is thrown in the cases when the JVM (Java Virtual Machine) attempts to read a class file and finds that the major and minor version numbers in the particular class file are not supported. This happens in the cases when a higher version of Java Compiler is used to generate the class file than the JVM version which is used to execute that class file. Please do notice that this is not true vice-versa which means you can comfortably use a higher version of JVM to run a class file compiled using an earlier version of Java Compiler. Let’s understand why? We'll see below a valid Java program and subsequently an alert and a stack trace of the error which are thrown as a result of the above explained situation which causes UnsupportedClassVersionError. FYI:
    
    public class TestFinally {
    
          public static void main(String[] args) {
                  
                try{
                      try{
                            throw new NullPointerException ("e1");
                      }
                      finally{
                            System.out.println("e2");
                      }
                }
                catch(Exception e){
                            e.printStackTrace();
                }
          }
    }
    
    

    The error alert and the stack trace if the right JVM is not used


    
    java.lang.UnsupportedClassVersionError: TestFinally (Unsupported major.minor version 49.0)
          at java.lang.ClassLoader.defineClass0(Native Method)
          at java.lang.ClassLoader.defineClass(ClassLoader.java:539)
          at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:123)
          at java.net.URLClassLoader.defineClass(URLClassLoader.java:251)
          at java.net.URLClassLoader.access$100(URLClassLoader.java:55)
          at java.net.URLClassLoader$1.run(URLClassLoader.java:194)
          at java.security.AccessController.doPrivileged(Native Method)
          at java.net.URLClassLoader.findClass(URLClassLoader.java:187)
          at java.lang.ClassLoader.loadClass(ClassLoader.java:289)
          at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:274)
          at java.lang.ClassLoader.loadClass(ClassLoader.java:235)
          at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:302)
    
    

    The minor and major version numbers are represented by the major_version and minor_version items respectively in a Java Class File structure. A combination of these two unsigned integers (both of length 2 bytes each) determines the particular version of the class file format. If a class file has major version number M and minor version number m, we denote the version of its class file format as M.m.

    As per Java VM Spec, “A Java virtual machine implementation can support a class file format of version v if and only if v lies in some contiguous range Mi.0 v Mj.m. Only Sun can specify what range of versions a Java virtual machine implementation conforming to a certain release level of the Java platform may support.” For example: Implementations of version 1.2 of the Java 2 platform can support class file formats of versions in the range 45.0 through 46.0 inclusive.

    Major version number of the class file formats of the popular Java versions are: J2SE 6.0 = 50, J2SE 5.0 = 49, JDK 1.4 = 48, JDK 1.3 = 47, JDK 1.2 = 46, JDK 1.1 = 45. Now you understand what in our example “major.minor version 49.0” signifies? It simply means we have used J2SE 5.0 for compiling the source code as the class file format is 49.0 where major_version is ‘49’ and minor_version is ‘0’.

    Errors are never detected at compile time. This is quite easier to understand in this case – how can the compiler have the information at the time of compilation about which version of JVM would be used execute the compiled class file? It can't, right? So is the case with other errors as well. This is the reason why all the Errors are unchecked. The error alert also rightly shows that it's a JVM Launcher error.

    How to resolve UnsupportedClassVersionError?

    Whenever you encounter this error, do check if you’re using an earlier version of JVM to execute the class file than the corresponding version of compiler you used to compile the source code. The example shown here was compiled using Java 5.0 compiler, but when I tried to run using JVM 1.4, I got the above error. I just needed to switch either to a JVM version 5.0 or above OR needed to switch to a Java Compiler of JDK 1.4 or below (you of course need to make sure the source code is compatible with the corresponding version of the compiler otherwise you’ll start getting other compiler errors).

    A higher JVM version doesn’t cause a problem in most of cases unless the class file format is quite old (and hence doesn’t lie in the supported range as specified by Sun for that particular JVM version ... as discussed above). But, it’s always a good practice to have both the Compiler and the JVM of the same version.

    Usage of ThreadLocal: per-thread Singleton and per-thread Logging | Java Thread

    Should you require a refresh of what ThreadLocals in Java are and how they work, refer to  first. You can then proceed with the current article for understanding two of the most common uses of ThreadLocals in Java.

    per-thread Singleton impl using ThreadLocal


    Suppose you have a need of having a JDBC Connection objects per thread of your application. The moment you hear the term 'per-thread', ThreadLocal automatically comes into mind as that's what it's primarily meant for. Below is a sample implementation of how easily can you actually use ThreadLocal for a per-thread JDBC Connection object in Java.


    
    public class ConnectionDispenser {
    
     private static class ThreadLocalConnection extends ThreadLocal {
    
       public Object initialValue() {
    
         return DriverManager.getConnection(ConfigurationSingleton.getDbUrl());
    
       }
    
     }
    
     private static ThreadLocalConnection conn = new ThreadLocalConnection();
    
     public static Connection getConnection() {
    
       return (Connection) conn.get();
    
     }
    
    }

    Most of the code is self-explanatory and you can easily see how overriding the 'initialValue()' method of ThreadLocal is doing the trick of getting a Connection object by calling 'getConnection' method of the 'DriverManager' class. As you know the 'initialValue()' method is called only once for a ThreadLocal object and hence the Connection object will be obtained only once per thread (as a ThreadLocal object is created per thread only). From then on, whenever the particular thread requires the Connection object it simply calls the static 'getConnection' method of the your 'ConnectionDispenser' class, which in turn calls the 'get()' method of ThreadLocal to fetch the Connection object associated with that particular thread.

    per-thread Debug Logging impl using ThreadLocal


    Ever thought of having a per-thread DEBUG logging for any of your applications? Few multi-threading applications do get trickier at times and having per-thread DEBUG logs might be of great help in such situations as you probably can't visualize the actual order in which the threads might have executed and changed the shared objects. Here goes a sample implementation of per-thread DEBUG logging in Java using ThreadLocal.


    
    public class DebugLogger {
    
     private static class ThreadLocalList extends ThreadLocal {
    
       public Object initialValue() {
    
         return new ArrayList();
    
       }
    
       public List getList() {
    
         return (List) super.get();
    
       }
    
     }
    
    
     private ThreadLocalList list = new ThreadLocalList();
    
     private static String[] stringArray = new String[0];
    
    
     public void clear() {
    
       list.getList().clear();
    
     }
    
    
     public void put(String text) {
    
       list.getList().add(text);
    
     }
    
    
     public String[] get() {
    
       return list.getList().toArray(stringArray);
    
     }
    
    }

    As you can identify we are using an ArrayList object to store the logging info for a thread. 'initialValue' has been overridden to initialize every thread with a new ArrayList object. Whenever your multi-threaded application calls the 'put' method of your 'DebugLogger' class then all that method does is that it adds the logging info (passed as an String parameter to the 'put' call) to the corresponding ArrayList object of the current thread. Similarly a 'get' call of your 'DebugLogger' class simply returns the associated ArrayList object of the current thread in form of an String array. Evidently the 'clear' method of your 'DebugLogger' class is for clearing the logging info captured so far for the current thread - it'll simply clear the ArrayList object holding logging info for the current thread. This might help you getting rid of the non-essential logging info, maybe based on some condition, when you know for sure that all that you need for your debugging is what you are going to capture next and now what has already been captured so far.


    Source: a nice article on ThreadLocals in Java, which I thoroughly enjoyed.

    Step by Step to create product carousel in Hybris e-commerce suit



    Create Product Carousel
    1.       Login into CMSCOCKPIT with admin rights
    2.       After select carousel section click on +  button in corner
    3.       Click on Banner
    4.       Click on create a new Item
    5.       Click on Media

    6.       Here we will add new media item

    7.       Click on create a new item

    8.       Go to the desire folder  where all file (image file dimension should in 947 * 501)

    9.       Click on choose file

    10.   Click on Done button
    11.   Click on Done

    12.   Now it will show in Content Component Editor

    13.   We will Add URL for that image
    14.   Finally it will show in Website