Thursday, September 1, 2011

Spring Key Points

What is BeanNameUrlHandlerMapping in Spring MVC

I have taken these nots from few of the eBooks.
=================================
What are the advantages of spring framework?
What is the purpose of each module in spring framework?
=================================

  1. Spring provides a light-weight solution for building enterprise-ready applications, declarative transaction management
  2. remote access to your logic using RMI or web services
  3. various options for persisting your data to a database
  4. Spring provides a full-featured
  5. Spring is modular, allowing you to use just those parts of it that you need, without having to bring in the rest.
  6. Spring could potentially be a one-stop-shop for all your enterprise applications
    1. AOP into your software.
  7. Transparent ways of integrating
        1. BeanFactory, which provides a sophisticated implementation of the factory pattern which removes the need for programmatic singletons and allows you to decouple the configuration and specification of dependencies from your actual program logic.
      8) Spring has been (and continues to be) designed to be non-intrusive, meaning dependencies on the framework itself are generally none (or absolutely minimal, depending on the area of use).
    9) IoC and Dependency Injection features whch provide The basic concept here is the
            Context package à and adds support for internationalization (I18N) (using for exampleresource bundles), event-propagation, resource-loading, and the transparent creation of contexts
    11) The DAO package à removes the need to do tedious JDBC coding provides a way to do programmatic as well as declarative transaction management
        12) The ORM package ' provides integration layers for popular object-relational mapping APIs, including JPA, JDO, Hibernate, and iBatis.
            13) Spring's Web package ' provides basic web-oriented integration features, such as multipart file-upload Functionality
            14)Spring's MVC package ' provides a Model-View-Controller (MVC) implementation for web-applications.
            15) you can use Spring in all sorts of scenarios, from applets up to fully-fledged enterprise applications
            16) The Spring Framework also provides an access- and abstraction- layer for Enterprise JavaBeans, enabling you to reuse your existing POJOs and wrap them in Stateless Session Beans
            17) The Spring team have found that the correct use of IoC certainly does make both unit and integration testing easier
        MVC frameworkTransparent ways of integrating AOP into your software.
            ================================

            When to use BeanFactory and when ApplicationContext?

            =======================================
             is best suited for use in a particular situation. A BeanFactory pretty much just instantiates and configures beans. An ApplicationContext also does that, and it provides the supporting infrastructure to enable lots of enterprise-specific features such as transactions and AOP.
            The ApplicationContext interface super set of the BeanFactory (it is a sub-interface)
            It has functionality such as
            1) easier integration with Spring's AOP
            2) message resource handling (for use in internationalization)
            3) event propagation
            4) application-layer specific contexts such as the WebApplicationContext for use in web applications.
            In short, favor the use of an ApplicationContext.
            ================================
             Every bean has one or more ids (also called identifiers, or names; these terms refer to the same thing). These ids must be unique within the container the bean is hosted in. A bean will almost always have only one id, but if a bean has more than one id, the extra ones can essentially be considered aliases.
            ======================
            you are not required to supply a name for a bean. If no name is supplied explicitly, the container will generate a unique name for that bean.


            ======================

            Injecting dependencies
            ==================
            When to use Constructor injection and when Setter-based DI?
            Disadvantages of constructor DI
            ==================
            The Spring team generally advocates the usage of setter injection
            1) It may be difficult, since a large number of constructor arguments cannot be managed easily.
            2) Sometimes arguments may be optional, may not required at all, then you canot use cosntructor DI
            3) Sometimes the objects in an argument may be heavy and may consume lots of space.
            4) Once configured object is not eligible for reIjection.
            Advantage of Constructor DI :
            1) Object will never be uninitialized at any moment of time, it will always get injected to calling method.
            2)In third pary classes, if you are suing readealy available jar file and you don’t have source code, then you don’t have other choice to use constructor DI as they may not provide you setter method for some particular reason.
            The presence of setter methods also makes objects of that class manageable to being re-configured (or re-injected) at some later Time.
            In case of JMX MBeans it is a particularly compelling use case

            The basic principle behind Dependency Injection (DI) is that objects define their dependencies (that is to say the other objects they work with) through
            1)  constructor arguments
            2)  arguments to a factory method
            3)  properties which are set on the object instance after it has been constructed

            it is the job of the container to actually inject those dependencies when it creates the bean. This is fundamentally the inverse, hence the name Inversion of Control (IoC)

            ================================

            What are Advantages of Dependency Injection
            ================================
            1. code gets much cleaner when the DI principle is applied
            2. code gets a higher grade of decoupling is much easier when objects do not look up their dependencies, but are provided with them
            3. bean do not even know where the dependencies are located and of what concrete class they are.

          Tuesday, July 26, 2011

          JMeter Tutorial


          JMeter Tutorial

           

          Apache JMeter
          Apache JMeter is open source software, a 100% pure Java desktop applicationdesigned to load test functional behavior and measure performance.
           

          Advantage 

          1) Apache JMeter may be used to test performance both on static and dynamic resources like
          1) files
          2) Servlets
          3) Perl scripts
          4) Java Objects
          5) Data Bases and Queries
          6) FTP Servers .

          2) JMeter can be used to simulate a heavy load on a server, network or object to test its strength or to analyze overall performance under different load types.
           
           3) Can load and performance test many different server types:
          • 1) Web - HTTP, HTTPS
          • 2) SOAP
          • 3) Database via JDBC
          • 4) LDAP
          • 5) JMS
          • 6) Mail - POP3(S) and IMAP(S)
          4) Complete portability and 100% Java purity .
          5) Full multithreading framework allows concurrent sampling by many threads
          6) Careful GUI design allows faster operation and more precise timings.
          7) Highly Extensible:
          • Pluggable Samplers allow unlimited testing capabilities.
          • Several load statistics may be choosen with pluggable timers .
          • Data analysis and visualization plugins allow great extendibility as well as personalization.
          8) JMeter can help you regression test your application by letting you create test scripts with assertionsto validate that your application is returning the results you expect. For maximum flexibility, JMeter lets you create these assertions using regular expressions.
           
           

          Thursday, June 9, 2011

          UML Tutorial


          UML Tutorial

          UML key Points / Notes
           
          1) Inheritance is indicated by a solid line with a closed, unfilled arrowhead pointing at the
          super class
          2) Abstract class is indicated by italic notation.
          3) By default all the assotiations are bidirectional this means that both classes are aware of each other and their relationship. A bi-directional association is indicated by a solid line between the two classes.
          4) A uni-directional association is drawn as a solid line with an open arrowhead (not the closed arrowhead, triangle, used to indicate inheritance) pointing to the known class.
           5) dotted line with a closed, unfilled arrow means realization (or implementation)
           
          A very important concept in object-oriented design, inheritance, refers to the ability of one class (child class) to inherit the identical functionality of another class (super class),
          Inheritance is indicated by a solid line with a closed, unfilled arrowhead pointing at the
          super class
           
          Below both the diagram shows the same concept of inheritance in UML. If you look care fully BankAccount class in the diagram is shown with ITALIC format. It implies that this class is an abstract class and withdrawl(int amount) method is abstract method.
           
           
           
          An example of inheritance using tree notation
           There are five types of associations. 1) bidirectional associations
          2)uni-directional associations
           
          1) bidirectional associations
                       By default all the assotiations are bidirectional this means that both classes are aware of each other and their relationship. A bi-directional association is indicated by a solid line between the two classes.  At either end of the line, you place a role name and a multiplicity value.  The multiplicity value next to the Plane class of 0..1 means that when an instance of a Flight exists, it can either have one instance of a Plane associated with it or no Planes associated with it (i.e., maybe a plane has not yet been assigned).
           
           
           
           
           
           
           
           
           
           
           
           
           
           
           
           
           
           
           
           
           
           Indicator Meaning
          1) 0..1  (Zero or one)
          2) 1 (One only)
          3) 0..* (Zero or more)
          4) * (Zero or more)
          5) 1..* (One or more)
          6) 3 (Three only)
          7) 0..5 (Zero to Five)
          8) 5..15 (Five to Fifteen)
           
          2) Uni-directional association
          In a uni-directional association, two classes are related, but only one class knows that the relationship exists. 
          An example of a uni-directional association: The OverdrawnAccountsReport class knows about the BankAccount class, but the BankAccount class does not know about the association
           
           
          In java term, An instance of report class can exist which can use AccountClass object, but vice versa is not true, i.e. If AccountClass object is created it may not user report class object.
                          A uni-directional association is drawn as a solid line with an open arrowhead (not the closed arrowhead, or triangle, used to indicate inheritance) pointing to the known class. Like standard associations, the unidirectional association includes a role name and a multiplicity value, but unlike the standard bi-directional association, the uni-directional association only contains the role name and multiplicity value for the known class. In our example , the OverdrawnAccountsReport knows about the BankAccount class, and the BankAccount class plays the role of "overdrawnAccounts." However, unlike a standard association, the BankAccount class has no idea that it is associated with the OverdrawnAccountsReport.
           
          ==========================
          What is realization in UML 
          ========================== 
          In the diagram shown , both the Professor and Student classes implement the Person interface and do not inherit from it. We know this for two reasons: 1) The Person object is defined as an interface — it has the "«interface»" text in the object's name area.
          2) We know inheritance is not being shown here, because the line with the arrow is dotted and not solid. As shown dotted line with a closed, unfilled arrow means realization (or implementation),
           
           
          Ralization ==> The String class does not implement any thing for sortable interface.
           
           
          =================================================
           Composition Relationships== IS MADE UP OF
          =================================================
          Case 1) Each instance of type Circle seems to contain an instance of type Point. Composition is shown by Dark Arrohead at parent class. If Objects of Circle class get deleted, then all the objects of Point will also get deleated.
           
          Case 2)  Address book is made up of / contains contacts, and contact group. You can have contact to be part of many groups. In case if AddressBook object get deleted then ALL contact and ContactGroup objects will be deleted. But if only ContactGroup object is deleted then as Contact can be part of many ContactGrups , it will not be deleted.
          Here we can see Strong Composition between AddressBook and Contact, ContactGroup objects, but at the same time ContactGroup is made up of Contact, but they have weak composition which is been shown with hollow white arrowHead marked toward parent class.
          Composition can be recursive. i.e. ContactGroup is madeup of Contacts as well as other ContactGroup.There is weak composition between contactGroup with itSelf.
           
           

          Friday, June 3, 2011

          Code Coverage

          ==============================================
          What is EMMA Code coverage.
          What do you understand by code coverage report?
          ==============================================
                          Code coverage is a measure used in software testing. It describes the degree to which the source code of a program has been tested. To measure how well the program is exercised by a test suite, one or more coverage criteria are used. There are following types of criteria in general.
           
          1) Function coverage - Has each function (or subroutine) in the program been called?
          2) Statement coverage - Has each node in the program been executed?
          3) Decision coverage  - Has every IF and CASE statements been met as well as not met?
          4) Condition coverage - Has each boolean sub-expression evaluated both to true and false?
                   Attached is Emma-codeCoverage Text report snap shot.
           
           

          SingleTon Pattern Nots / Key Points

          Some of the key points which I feel one should know.


          1) Constructor must be private as nobody should able to create object.

          2) getInstance method must be static

          3) getInstance method must take care of multiple threads

          4) if you make getInstance method as synchronized then it will hamper the performance, Use synchronized block

          5) Class should not support serialization, as serialization can create multiple object

          6) Class should not be clonable, as cloning can create multiple objects

          7) Even if you do synchroniz the piece of code in getInstance() then, still you will have to do double check looking.

           

          in the below code that getInstance method ensures that only one instance of the class is created. The constructor is not accessible from the outside of the class , only way of instantiating the class would be only through the getInstance method.


          Implementation

          The implementation involves a static member in the "Singleton" class, a private constructor and a static public method that returns a reference to the static member.


          class MySingleton
          {
          private static MySingleton instance;
          private MySingleton()
          {
          // Empty constructor which is private
          }

          public static synchronized MySingleton getInstance()
          {
          if (instance == null)
          instance = new MySingleton();

          return instance;
          }
          }

          Where can you use Singleton pattern

           1 - Logger Classes

          The Singleton pattern is used in the design of logger classes. This classes are ussualy implemented as a singletons, and provides a global logging access point in all the application components without being necessary to create an object each time a logging operations is performed.

          2 - Configuration Classes

          The Singleton pattern is used to design the classes which provides the configuration settings for an application.  

          3 - Accesing resources in shared mode

          It can be used in the design of an application that needs to work with the serial port.  In this case a singleton with synchronized methods could be used to be used to manage all the operations on the serial port.

          4 - Factories implemented as Singletons

          Let's assume that we design an application with a factory to generate new objects(Acount, Customer, Site, Address objects) with their ids, in an multithreading environment. If the factory is instantiated twice in 2 different threads then is possible to have 2 overlapping ids for 2 different objects. If we implement the Factory as a singleton we avoid this problem. Combining Abstract Factory or Factory Method and Singleton design patterns is a common practice.

           

          There are two ways to create singleton classes




          Lazy instantiation using double locking mechanism.

                          The standard implementation shown in the above code is a thread safe implementation, but it's not the best thread-safe implementation beacuse synchronization is very expensive when we are talking about the performance. We can see that the synchronized method getInstance does not need to be checked for syncronization after the object is initialized. If we see that the singleton object is already created we just have to return it without using any syncronized block. This optimization consist in checking in an unsynchronized block if the object is null and if not to check again and create it in an syncronized block. This is called double locking mechanism.

          Early instantiation using implementation with static field

                          In the following implementattion the singleton object is instantiated when the class is loaded and not when it is first used, due to the fact that the instance member is declared static. This is why in we don't need to synchronize any portion of the code in this case. The class is loaded once this guarantee the uniquity of the object.

          Singleton - A simple example (java)

          //Early instantiation using implementation with static field.
          class Singleton
          {
          private static Singleton instance = new Singleton();

          private Singleton()
          {
          System.out.println("Singleton(): Initializing Instance");
          }

          public static Singleton getInstance()
          {
          return instance;
          }

          public void doSomething()
          {
          System.out.println("doSomething(): Singleton does something!");
          }
          }
          ================================================
          What are disadvantages of Singleton Pattern
          ================================================
          Disadvantages:


          • 1) Multithreading - A special care should be taken when singleton has to be used in a multithreading application.
          • 2) Serialization - When Singletons are implementing Serializable interface they have to implement readResolve method in order to avoid having 2 different objects.
          • 3) Classloaders - If the Singleton class is loaded by 2 different class loaders we'll have 2 different classes, one for each class loader.
          • 4) Global Access Point represented by the class name - The singleton instance is obtained using the class name. At the first view this is an easy way to access it, but it is not very flexible. If we need to replace the Sigleton class, all the references in the code should be changed accordinglly.
           
           
          Fact about SingleTon


          1) if your singleTOn class implements the java.io.Serializable interface, the class's instances can be serialized and deserialized. However, if you serialize a singleton object and subsequently deserialize that object more than once, you will have multiple singleton instances.


          2)SingleTon Class is not thread safe


          if(instance == null) {
              instance = new Singleton();
          }


          3) if you clone singleTon class, it will create a clone and there will be two different object  will be created. You can print hashCode of each instance, it will be different


          4) if you create synchronized method, it will always hit the performance whenever you
          you create object.


          public synchronized static Singleton getInstance() {
             if(singleton == null) {
                synchronized(Singleton.class) {
                   singleton = new Singleton();
                }
                System.out.println("Object created");
             }
             return singleton;
          }


          5) if you creat synchronized block, its not thread safe. Suppose control comes to
          System.out.println("Object created"); statement and before returning 2nd thread come
          here thread1 is out of synchornized block and again thread2 can enter block


          public static Singleton getInstance() {
             if(singleton == null) {
                synchronized(Singleton.class) {
                   singleton = new Singleton();
                }
                System.out.println("Object created");
             }
             return singleton;
          }

          Core Java Notes / Key Points

                      HashMap provides constant-time performance for the basic operations (get and put). Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important. An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs.

           
          ===============================
          What is the capacity of HashMap
          ===============================
          The capacity is the number of buckets in the hash table

           
          ===============================
          What is loadFactor in HashMap
          ===============================
          The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased

           
          ===============================
          I want to store certain objects in a HashMap. Say object Emp. Emp has age, name, and dept as its attribute. Can I add this object as a key? If yes, how can I make sure that key is unique.?


          What is extra thing that object need to be do, to be as key for Hashmap.

          ===============================
          yes, you can add an object as a key.

          Your key object must implement/ override the hashCode() and equals(). If it is a SortedMap, it must also implements the Comparable interface


           
          ===============================
          How to make a HashMap as Synchronized.

          ===============================
          1) HashMap is not synchronized.it must be synchronized externally.

          2) the map should be "wrapped" using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:
           Map m = Collections.synchronizedMap(new HashMap(...));

          Key Points or Facts or Best Practices in java

          1.      System.out.println is expensive. These calls are synchronized for the duration of disk I/O, which significantly slows throughput. 

           2. Catch an exception as close as possible to its source.

          3. Never throw unchecked exceptions in your methods


          ===============================
          When to throw CheckedException and When to throw RuntimeException
          ===============================
          bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

           

          The cost of exception handling

                          Exceptions are expensive and should be used exceptionally. The JVM maintains a method invocation stack containing all the methods that have been invoked by the current thread in the reverse order of invocation. Actually it is not the actual method that is present in the stack. Instead a stack frame representing the method is added to the stack. The stack frame contains the method’s parameters, return value, local variables and JVM specific information. When the exception is thrown in a method at the top of the stack, code execution stops and the JVM takes over. The JVM searches the current method for a catch clause for the exception thrown or one of the parent classes of the thrown exception. If one is not found, then the JVM pops the current stack frame and inspects the calling method (the next method in the stack), for the catch clause for the exception or its parents. The process continues until the bottom of the stack is reached. In summary, it requires a lot of time and effort on the part of JVM.


          ===============================
          What is the difference == and .equals() method
          ===============================
          1) equals() method is present in the java.lang.Object class

          1) '==' operator
           
          2) equals() check for the equivalence of the state of objects! That means, the contents of the objects.

          2) == check the actual object instances are same or not.
           
          If you have two object say emp1 and emp2.  Both of them have empName and empAddress same.
          emp1 stored at momory location 3x00794 and emp2 at 3x00794. Both of them are on heap memory of JVM
          Now if you say (emp1 == emp2) will give you FALSE, as == checks at reference lavel and not at object content
          but .equals () method will return TRUE.
           
          For String also
          if you have two strings s1 = new String("xyz"); and s2 = new String("xyz"); if you use == method , it will return
          FALSE but .equals() method will return TRUE. Again same principal. As for Strings when you use new operator it will get saperate space for saperate object.
           
          If you use String s1 ="xyz";
          String s2 ="xyz"; Here both the method == and .equals() will return TRUE

           ===============================
          Can I add millions of object in ArrayList
          ===============================
          Yes,
          Definately You can. You can write a loop which will iterate for million time and try this in local program.
          But it is directly dependent on
          1)Heap size of JVM
          2) A type of object you are trying to add to collection. i.e. if it is an Integer then its ok, but if its object of say type Emp
          which has say 10 attributs in it, they definately its a matter of heap memory. There are chances that system will give
          OUT of MEMORY error.

          XML-DOM

           ======================================
          What is the Document Object Model?

           ======================================

          The foundation of Extensible Markup Language, or XML, is the DOM. XML documents have a hierarchy of informational units called nodes; DOM is a way of describing those nodes and the relationships between them.
          A DOM Document is a collection of nodes,the DOM is said to be tree-based, or object-based.
          provides an API that allows a developer to add, edit, move, or remove nodes at any point on the tree in order to create an application.

          DOM Level 1 included support for XML 1.0 and HTML

          Namespace support was added to the DOM Level 2. new modules supporting Cascading Style Sheets, events, and enhanced tree manipulations.

          DOM Level 3, currently in Last Call, includes better support for creating a Document object  XSL Transformations and other XML technologies.


          CDATA: Short for Character Data, this is a node that contains information that should not be analyzed by the parser. Instead, it should just be passed on as plain text. For example, HTML might be stored for a specific purpose. Under normal circumstances, the processor might try to create elements for each of the stored tags, which might not even be well-formed. These problems can be avoided by using CDATA sections. These sections are written with a special notation:


           <[CDATA[ <b>
          Important:  Please keep head and hands inside ride at <i>all times</i>.
          </b> ]]>
          

          JSP Short Notes for interview

           
            -------------------------------------------------------------------------------------------------------------------------
          When isThreadSafe is set to true, multiple requests will go to JSP page. This is the default setting. If using true, you must ensure that you properly synchronize access to any shared objects defined at the page level. This includes

          1) objects created within declarations

          2) JavaBeans components with page scope

          3) attributes of the page scope object.



          If isThreadSafe is set to false, requests are dispatched one at a time. However, you still must ensure that access to attributes of the

          1) application or session scope objects

          2) JavaBeans components with application or session scope must be properly synchronized.
           
            ---------------------------------------------------------------------------------------------------

          What are implicit object in jsp

          1) request

          2) response

          3) page

          4) session

          5) application

          6) pageContext

          7) exception

          8) config

          9) out
           
          ------------------------------------------------------------------------------------------------------

          Variables declared in <%! %> are instance variable of servlet class and can be accessible multiple thread.
          ------------------------------------------------------------------------------------------------------
          Variables declared in  scriptlets and expressions are Local variables of the JSP page's servlet class.
          in Page import directive <%@ page import="java.util.*, cart.*, com.sss.*" %> multiple imports are saperated by comma, and not by semicolon.
          semicolon is not allowed within a JSP expression <%= %>
          ------------------------------------------------------------------------------------------------------
          Can you define methods in declaratin tag

          YES,

          <%!

             private BookDBEJB bookDBEJB;
             public void jspInit() {

                ...

             }

             public void jspDestroy() {

                ...

             }

          %>

           
          =============================
          How to handle exceptions in jsp
          =============================
          ----------------------------------------------------------------------------------------------------- 
          Case 1
          -----------------------------------------------------------------------------------------------------
          We can handle the exceptions in jsp by specifying errorPage in the page directive, <%@ page errorPage = "myErrorPage.jsp">

          Here at the first line of jsp, we are intimating container that if any exception comes in this jsp, then control must go to myErrorPaeg.jsp
           
          Funciton.jsp

          <%@ page errorPage="="/WEB-INF/templates/myErrorPage.jsp" %>

          <html>

          <body><%
           int fno;

           int sno;  
             fno = Integer.parseInt(request.getParameter("fno")); 
              sno = Integer.parseInt(request.getParameter("sno"));

              int div=fno/sno;%>

          <p>Division is : <%= div %></p><p><a href="form.html">Back</a>.</p></body>

          </html>

          Below is the source for myErrorPage.jsp. Here we have to declare isErrorPage="true" property, so that container will come to know that this jsp is capable of handling error

          <%@ page isErrorPage="true" import="java.io.*" %>

          </head><body<%= exception.toString() %><br></head>


                  When we specify errorPage=true, we get access to variable exception. This exception variable will not be avaiable in other pages.
          ----------------------------------------------------------------------------------------------------- 
          Case 2
          -----------------------------------------------------------------------------------------------------

          But the disadvantage of this method is you have to specify errorPage attribute of page directive for evey jsp that is repeatation of coding. To avoid this you can specify tag in web.xml

           <error-page>

              <exception-type>java.lang.Throwable</exception-type>

              <location>/WEB-INF/templates/errorPage.jsp</location>

            </error-page>

          You can also assign error page jsp for HTTP error codes
          <error-page>
                                         <error-code>404</error-code>
                                        <location>exceptions/Page404.jsp</location>
          </error-page>
           
          Many times we write custom tags in jsp, like struts-tag library, velocity templates, scriplet. These libraries throws JspException in their tag callback methods


           Home

          XML-StAX


          =======================================================
          What are advantages of StAX over SAX and DOM
          =======================================================

          1) StAX-enabled clients are generally easier to code than SAX clients. StAX parser code can be smaller and the code necessary for the client to interact with the parser simpler.

          2) StAX is a bidirectional API, meaning that it can both read and write XML documents. SAX is read only, so another API is needed if you want to write XML documents.

          3) SAX is a push API, whereas StAX is pull.

          =======================================================
          What is StAX
          =======================================================

                          The StAX project was initiated by BEA . The goal of the StAX API is to give "parsing control to the programmer by exposing a simple iterator based API. StAX was created to address limitations in the SAX and DOM.
           
           



          Streaming Versus DOM 

                          Generally speaking, there are two programming models for working with XML infosets: document streaming and the document object model (DOM).
          The DOM model involves creating in-memory objects representing an entire document tree and the complete infoset state for an XML document. Once in memory, DOM trees can be navigated freely and parsed arbitrarily, and as such provide maximum flexibility for developers. However the cost of this flexibility is a potentially large memory footprint and significant processor requirements, as the entire representation of the document must be held in memory as objects for the duration of the document processing. This may not be an issue when working with small documents, but memory and processor requirements can escalate quickly with document size.

                          Streaming refers to a programming model in which XML infosets are transmitted and parsed serially at application runtime, often in real time, and from dynamic sources. Moreover, stream-based parsers can start generating output immediately, and infoset elements can be discarded and garbage collected immediately after they are used. While providing a smaller memory footprint, reduced processor requirements, and higher performance in certain situations.
                          Streaming models for XML processing are particularly useful
          1) when your application has strict memory limitations, as with a cellphone running J2ME,
          2) or when your application needs to simultaneously process several requests, as with an application server.
           


          Pull Parsing Versus Push Parsing


          =======================================================
          What is Pull Parsing
          What is Push Parsing
          =======================================================

                          Streaming pull parsing refers to a programming model in which a client application calls methods on an XML parsing library when it needs to interact with an XML infoset--that is, the client only gets (pulls) XML data when it explicitly asks for it.


                          Streaming push parsing refers to a programming model in which an XML parser sends (pushes) XML data to the client as the parser encounters elements in an XML infoset--that is, the parser sends the data whether or not the client is ready to use it at that time.


          Pull parsing provides several advantages over push parsing when working with XML streams:

          • With pull parsing, the client controls the application thread, and can call methods on the parser when needed. By contrast, with push processing, the parser controls the application thread, and the client can only accept invocations from the parser.
          • Pull parsing libraries can be much smaller and the client code to interact with those libraries much simpler than with push libraries, even for more complex documents.
          • Pull clients can read multiple documents at one time with a single thread.
          • A StAX pull parser can filter XML documents such that elements unnecessary to the client can be ignored, and it can support XML views of non-XML data. 

          Tuesday, May 31, 2011

          XML-SAX

          ================== ===================================
          When to Use SAX
          SAX key points 
          ===================================================== 

          SAX event model is used when you want to convert existing data to XML.
          ITs an event-driven, serial-access mechanism for accessing XML documents. This protocol is frequently used by servlets and network-oriented programs that need to send and receive XML documents, because it's the fastest and least memory-intensive mechanism that is currently available for dealing with XML documents.


          SAX is fast and efficient, and its event model makes it most useful for such state-independent filtering. For example, a SAX parser calls one method in your application when an element tag is encountered and calls a different method when text is found. If the processing you're doing is state-independent (meaning that it does not depend on the elements have come before), then SAX works fine.

          SAX requires much less memory than DOM, because SAX does not construct an internal representation (tree structure) of the XML data, as a DOM does. Instead, SAX simply sends data to the application as it is read.

          SAX API act like a serial I/O stream. You see the data as it streams in, but you can't go back to an earlier position or leap ahead to a different position. In general, SAX parsers work well when you simply want to read data and have the application act on it.

          SAX was developed by the members of the XML-DEV mailing list, and the Java version is now a SourceForge project

          SAX has no official standards body; it is not maintained by the World Wide Web Consortium (W3C) or any other official body


          Disadvantages:

          1) Setting up a program to use SAX requires a bit more work than setting up to use the Document Object Model (DOM).
          2) SAX is an event-driven model and that makes it harder to visualize
          3) Finally, you can't "back up" to an earlier part of the document, or rearrange it. For those reasons, developers who are writing a user-oriented application that displays an XML document and possibly modifies it will want to use the DOM mechanism

          Saturday, May 21, 2011

          Java Interview Questions

          SQL Injection in java


          SQL Interview Questions

          ======================================
          What is sql inject attack
          What is sql injeciton
          ======================================

           This is the way you can pass INVALID or VUNARABLE input parameters to query and retrive information more than expected. This is the way to break the Security of Database lavel. for eg.
           
          Suppose you have sql query like statement 
           
           "SELECT * FROM `users` WHERE `name` = '" + userName + "';"
           
              This SQL code is designed to pull up the records of the specified username from its table of users.
          You can see here that query is taking parameter dynamically. Here you may use prepared statement. At the run time value of userName variable will be added to query.
          If you pass the userName=' or '1'='1 the actual statement will look like
           SELECT * FROM `users` WHERE `name` = '' OR '1'='1';

          If this code were to be used in an authentication procedure then this example could be used to force the selection of a valid username because the evaluation of '1'='1' is always true.
          The following value of "userName" in the statement below would cause the deletion of the "users" table as well as the selection of all data from the "userinfo" table using an API that allows multiple statements:
           
          a';DROP TABLE `users`; SELECT * FROM `userinfo` WHERE 't' = 't

          The above scenario which I explained is comes under Incorrectly filtered escape characters scenario
          There are following way you can do query injection
          1)Incorrectly filtered escape characters
          2) Incorrect type handling
          3) Conditional responses
          4) Parameterized statements etc.

          Memory Management in java

          Memory management is the process of recognizing when allocated objects are no longer needed, deallocating (freeing) the memory used by such objects, and making it available for subsequent allocations. Garbage collection solves many, but not all, memory allocation problems. You could, for example, create objects indefinitely and continue referencing them until there is no more memory available. Garbage collection is also a complex task taking time and resources of its own.



          ===========================
          When does GarbageCollector will run
          What will happen if garbage collector is not able to free memory
          ===========================
          Consider the possibility that the garbage collector may never even run during an application's lifetime. There is no guarantee as to when or if the JVM will invoke the garbage collector -- even if a program explicitly callsSystem.gc(). Typically, the garbage collector won't be automatically run until a program needs more memory than is currently available. At this point, the JVM will first attempt to make more memory available by invoking the garbage collector. If this attempt still doesn't free enough resources, then the JVM will obtain more memory from the operating system until it finally reaches the maximum allowed.
           Garbage Collection Algorithms
          1 – Reference Counting:
          2 – Tracing Collectors:
          3 – Mark-Sweep collectors:
          4 – Copying Collectors:
          5 – Heap Compaction:
          6 – Mark-compact collectors:
          JDK uses all of the algorithms in some sense. Early JDK used mark-sweep and mark-compact while version 1.2 and later employed a hybrid approach.
           
          An object is created in the heap and is garbage-collected after there are no more references to it. 
          The sequence of the garbage collection process is as follows:

          1. Root set tracing and figure out objects that are not referenced at all.
          2. Put the garbage objects from above in finalizer Q
          3. Run finalize() of each of these instances
          4. Free memory

          The JavaHeap is separated into three regions
          1. New Generation objects
          2. Old Generation objects
          3. Permenent Generation objects
          The New Object Regions is subdivided into three smaller regions:
           1. Eden , where objects are allocated
           2. Survivor semi-spaces:  From
          3. Survivor semi-spaces:  To
          When the Eden area is full, the GC does a reachability test and then copies all the live objects from Eden to the To region. objects get created in New generation and then move to survivor Spaces at every GC run, and if they survive for long to be considered old, they get moved to the Tenured generation
          By default, Java has 2 separate  threads for GC, one each for young(minor GC) and old generation(major GC). When ever there is requirment for memory then, first minor GC will runs if it could not release memory, then major Gc thread will run, even it could not release memory then JVM increase heap memory. This cycle run untill current memory reaches the MaxMemory for the JVM (default is 64MB for client JVM), after which JVM throws OutOfMemory Error.

          Permanent Generation
          Class information is stored in the perm generation. Also constant strings are stored there. Strings created dynamically in your application with String.intern() will also be stored in the perm generation.Reflective objects (classes, methods, etc.) are stored in perm. It holds all of the reflective data for the JVM