Sunday, April 1, 2012

Struts1 vs Struts2

Feature Struts 1 Struts 2
Action classes Struts 1 requires Action classes to extend an abstract base class. A common problem in Struts 1 is programming to abstract classes instead of interfaces. An Struts 2 Action may implement an Action interface, along with other interfaces to enable optional and custom services. Struts 2 provides a base ActionSupport class to implement commonly used interfaces. Albeit, the Action interface is not required. Any POJO object with a execute signature can be used as an Struts 2 Action object.
Threading Model Struts 1 Actions are singletons and must be thread-safe since there will only be one instance of a class to handle all requests for that Action. The singleton strategy places restrictions on what can be done with Struts 1 Actions and requires extra care to develop. Action resources must be thread-safe or synchronized. Struts 2 Action objects are instantiated for each request, so there are no thread-safety issues. (In practice, servlet containers generate many throw-away objects per request, and one more object does not impose a performance penalty or impact garbage collection.)
Servlet Dependency Struts 1 Actions have dependencies on the servlet API since the HttpServletRequest and HttpServletResponse is passed to the execute method when an Action is invoked. Struts 2 Actions are not coupled to a container. Most often the servlet contexts are represented as simple Maps, allowing Actions to be tested in isolation. Struts 2 Actions can still access the original request and response, if required. However, other architectural elements reduce or eliminate the need to access the HttpServetRequest or HttpServletResponse directly.
Testability A major hurdle to testing Struts 1 Actions is that the execute method exposes the Servlet API. A third-party extension, Struts TestCase, offers a set of mock object for Struts 1. Struts 2 Actions can be tested by instantiating the Action, setting properties, and invoking methods. Dependency Injection support also makes testing simpler.
Harvesting Input Struts 1 uses an ActionForm object to capture input. Like Actions, all ActionForms must extend a base class. Since  other JavaBeans cannot be used as ActionForms, developers often create redundant classes to capture input. DynaBeans can used as an alternative to creating conventional ActionForm classes, but, here too, developers may be redescribing existing JavaBeans.
Struts 2 uses Action properties as input properties, eliminating the need for a second input object. Input properties may be rich object types which may have their own properties. The Action properties can be accessed from the web page via the taglibs. Struts 2 also supports the ActionForm pattern, as well as POJO form objects and POJO Actions. Rich object types, including business or domain objects, can be used as input/output objects. The ModelDriven feature simplifies taglb references to POJO input objects.
Expression Language Struts 1 integrates with JSTL, so it uses the JSTL EL. The EL has basic object graph traversal, but relatively weak collection and indexed property support. Struts 2 can use JSTL, but the framework also supports a more powerful and flexible expression language called "Object Graph Notation Language" (OGNL).
Binding values into views Struts 1 uses the standard JSP mechanism for binding objects into the page context for access. Struts 2 uses a "ValueStack" technology so that the taglibs can access values without coupling your view to the object type it is rendering. The ValueStack strategy allows reuse of views across a range of types which may have the same property name but different property types.
Type Conversion Struts 1 ActionForm properties are usually all Strings. Struts 1 uses Commons-Beanutils for type conversion. Converters are per-class, and not configurable per instance. Struts 2 uses OGNL for type conversion. The framework includes converters for basic and common object types and primitives.
Validation Struts 1 supports manual validation via a validate method on the ActionForm, or through an extension to the Commons Validator. Classes can have different validation contexts for the same class, but cannot chain to validations on sub-objects. Struts 2 supports manual validation via the validate method and the XWork Validation framework. The Xwork Validation Framework supports chaining validation into sub-properties using the validations defined for the properties class type and the validation context.
Control Of Action Execution Struts 1 supports separate Request Processors (lifecycles) for each module, but all the Actions in the module must share the same lifecycle. Struts 2 supports creating different lifecycles on a per Action basis via Interceptor Stacks. Custom stacks can be created and used with different Actions, as needed.

MVC nice article with Observable pattern

4 down vote accepted
First, you need to understand the Observer pattern.
The basic idea is that you define an object that notifies interested parties when it changes. (Note that the Observer pattern is a bit more general - Observables notify Observers about "some event". For MVC, that event is "something changed")
First you define a contract between the OBSERVABLE and OBSERVER
package aaa;
// AN OBSERVER INTERFACE
// This is a contract between an interested party (the OBSERVER) and
//   the thing it would like to know has changed (the OBSERVABLE)
// The OBSERVABLE will call this method whenever its data changes
public interface SomethingChangedListener {
    void somethingChanged(String name, Object newValue);
}
Then you define the OBSERVABLE
package aaa;
import java.util.ArrayList;
import java.util.List;
// An OBSERVABLE class
public class Person {
    // STEP 1: keep track of "who cares"
    //         outsiders with interest implement the observer interface
    //         and register with the person to indicate that they care
    private List<SomethingChangedListener> listeners = new ArrayList<SomethingChangedListener>();
    public void addSomethingChangedListener(SomethingChangedListener scl) {
        listeners.add(scl);
    }
    public void removeSomethingChangedListener(SomethingChangedListener scl) {
        listeners.remove(scl);
    }

    // STEP 2: be able to notify those observers by calling a method in the observer interface
    protected void fireSomethingChanged(String name, Object newValue) {
        for (SomethingChangedListener scl : listeners) {
            scl.somethingChanged(name, newValue);
        }
    }

    // STEP 3: whenever the data changes, notify the observers
    private String name;
    private int age;

    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
        fireSomethingChanged("age", name);
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
        fireSomethingChanged("name", name);
    }
}
This allows any other object to "listen" for changes on the thing it's interested in, as long as it implements that observer interface.
For example:
package aaa;
public class Test1 {
    private static class TestObserver implements SomethingChangedListener {
        @Override public void somethingChanged(String name, Object newValue) {
            System.out.println("Property '" + name + "' changed to '" + newValue + "'");
        }
    }
    public static void main(String[] args) {
        Person p = new Person();
        p.addSomethingChangedListener(new TestObserver());
        p.setName("Scott");
        p.setAge(43);
    }
}
Creates an instance of the observable (the Person), registers an observer (TestObserver), and then interacts with the Observable. When run, we see
Property 'name' changed to 'Scott'
Property 'age' changed to 'Scott'
So far so good.
Now let's call the Person our MODEL. The MODEL represents the data that we want to manipulate and view.
We can do this in a "user interface". The user interface can be, but is not limited to:
  • A Graphical User Interface (GUI)
  • A Command-Line Interface (CLI)
  • A Web Application (HTML, JSP, ASP, etc)
  • A Web Service (SOAP, REST, etc)
The code for each of these types of user interfaces (UIs) can be drastically different, but the concepts are the same.
The user interface (UI) allows a user (a person or another computer for example) to see information about the model and make changes to that information.
The "View" is the part of the UI that displays the information for the user. It reads data from the model and formats it in some way to present it.
If the model changes, the View must be updated. To accomplish this, it registers observers with the model. Those observers simply refresh the relevant parts of the presentation in the View.
Now what happens if the user wants to make a change?
We define a "Controller" in the UI as code that interprets user interaction with that UI. For example, if the user types in the "name" field, the controller may interpret that as "change the value of 'name' to the text the user has typed. The controller makes a
person.setName(textFromField);
call to update the model.
Remember what that setName() method does? It notifies the observers of the change. This will cause the UI to update its view.
Note that "view" and "controller" do not need to be separate classes; they're often combined. It's really the roles of "view" (the part of the UI that displays model data) and "controller" (the part of the UI that interprets user interaction and updates the model) that are important to understand.
In some settings, such as Web Applications, the view and controller are very separate. The controller interprets the HTTP requests that are made to the server and updates the mode. The view renders HTML responses to the user. (If you're doing an AJAX application, the design is a bit more similar to a GUI)
The cool thing about the MVC separation (Model vs UI) is that you can add or remove UIs from the Model at any time, and can have multiple UIs on the same model. If data is changed in one UI, all other UIs are updated to reflect the change.
Cool, eh?

Saturday, March 31, 2012

CSS : Containing block definition

The position and size of an element's box(es) are sometimes calculated relative to a certain rectangle, called the containing block of the element. The containing block of an element is defined as follows:
  1. The containing block in which the root element lives is a rectangle called the initial containing block. For continuous media, it has the dimensions of the viewport and is anchored at the canvas origin; it is the page area for paged media. The 'direction' property of the initial containing block is the same as for the root element.
  2. For other elements, if the element's position is 'relative' or 'static', the containing block is formed by the content edge of the nearest block container ancestor box.
  3. If the element has 'position: fixed', the containing block is established by the viewport in the case of continuous media or the page area in the case of paged media.
  4. If the element has 'position: absolute', the containing block is established by the nearest ancestor with a 'position' of 'absolute', 'relative' or 'fixed', in the following way:
    1. In the case that the ancestor is an inline element, the containing block is the bounding box around the padding boxes of the first and the last inline boxes generated for that element. In CSS 2.1, if the inline element is split across multiple lines, the containing block is undefined.
    2. Otherwise, the containing block is formed by the padding edge of the ancestor.
    If there is no such ancestor, the containing block is the initial containing block.
In paged media, an absolutely positioned element is positioned relative to its containing block ignoring any page breaks (as if the document were continuous). The element may subsequently be broken over several pages.
For absolutely positioned content that resolves to a position on a page other than the page being laid out (the current page), or resolves to a position on the current page which has already been rendered for printing, printers may place the content
  • on another location on the current page,
  • on a subsequent page, or
  • may omit it.
Note that a block-level element that is split over several pages may have a different width on each page and that there may be device-specific limits.
With no positioning, the containing blocks (C.B.) in the following document:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<HTML>
   <HEAD>
      <TITLE>Illustration of containing blocks</TITLE>
   </HEAD>
   <BODY id="body">
      <DIV id="div1">
      <P id="p1">This is text in the first paragraph...</P>
      <P id="p2">This is text <EM id="em1"> in the 
      <STRONG id="strong1">second</STRONG> paragraph.</EM></P>
      </DIV>
   </BODY>
</HTML>
are established as follows:
For box generated by C.B. is established by
htmlinitial C.B. (UA-dependent)
bodyhtml
div1body
p1div1
p2div1
em1p2
strong1p2
If we position "div1":
#div1 { position: absolute; left: 50px; top: 50px }
its containing block is no longer "body"; it becomes the initial containing block (since there are no other positioned ancestor boxes).
If we position "em1" as well:
#div1 { position: absolute; left: 50px; top: 50px }
   #em1  { position: absolute; left: 100px; top: 100px }
the table of containing blocks becomes:
For box generated by C.B. is established by
htmlinitial C.B. (UA-dependent)
bodyhtml
div1initial C.B.
p1div1
p2div1
em1div1
strong1em1
By positioning "em1", its containing block becomes the nearest positioned ancestor box (i.e., that generated by "div1").

Wednesday, March 28, 2012

CSS Selector Syntax

http://www.w3.org/TR/CSS2/selector.html#type-selectors
PatternMeaningDescribed in section
*Matches any element.Universal selector
EMatches any E element (i.e., an element of type E).Type selectors
E FMatches any F element that is a descendant of an E element.Descendant selectors
E > FMatches any F element that is a child of an element E.Child selectors
E:first-childMatches element E when E is the first child of its parent. The :first-child pseudo-class
E:link
E:visited
Matches element E if E is the source anchor of a hyperlink of which the target is not yet visited (:link) or already visited (:visited). The link pseudo-classes
E:active
E:hover
E:focus
Matches E during certain user actions. The dynamic pseudo-classes
E:lang(c) Matches element of type E if it is in (human) language c (the document language specifies how language is determined). The :lang() pseudo-class
E + FMatches any F element immediately preceded by a sibling element E.Adjacent selectors
E[foo]Matches any E element with the "foo" attribute set (whatever the value). Attribute selectors
E[foo="warning"]Matches any E element whose "foo" attribute value is exactly equal to "warning". Attribute selectors
E[foo~="warning"]Matches any E element whose "foo" attribute value is a list of space-separated values, one of which is exactly equal to "warning". Attribute selectors
E[lang|="en"]Matches any E element whose "lang" attribute has a hyphen-separated list of values beginning (from the left) with "en". Attribute selectors
DIV.warningLanguage specific. (In HTML, the same as DIV[class~="warning"].) Class selectors
E#myidMatches any E element with ID equal to "myid".ID selectors

Tuesday, March 20, 2012

Multipart/form-data

Excerpt from http://www.ietf.org/rfc/rfc2388.txt

In many applications, it is possible for a user to be presented with
   a form. The user will fill out the form, including information that
   is typed, generated by user input, or included from files that the
   user has selected. When the form is filled out, the data from the
   form is sent from the user to the receiving application.
 
multipart/form-data" contains a series of parts. Each part is
   expected to contain a content-disposition header [RFC 2183] where the
   disposition type is "form-data", and where the disposition contains
   an (additional) parameter of "name", where the value of that
   parameter is the original field name in the form. For example, a part
   might contain a header:

        Content-Disposition: form-data; name="user"

   with the value corresponding to the entry of the "user" field. 
 
As with all multipart MIME types, each part has an optional
   "Content-Type", which defaults to text/plain.  If the contents of a
   file are returned via filling out a form, then the file input is
   identified as the appropriate media type, if known, or
   "application/octet-stream".  If multiple files are to be returned as
   the result of a single form entry, they should be represented as a
   "multipart/mixed" part embedded within the "multipart/form-data".

   Each part may be encoded and the "content-transfer-encoding" header
   supplied if the value of that part does not conform to the default
   encoding. 
As with other multipart types, a boundary is selected that does not
   occur in any of the data. Each field of the form is sent, in the
   order defined by the sending appliction and form, as a part of the
   multipart stream.  Each part identifies the INPUT name within the
   original form. Each part should be labelled with an appropriate
   content-type if the media type is known (e.g., inferred from the file
   extension or operating system typing information) or as
   "application/octet-stream".
 
 
If the value of a form field is a set of files rather than a single
   file, that value can be transferred together using the
   "multipart/mixed" format.
 
 
Forms may request file inputs from the user; the form software may
   include the file name and other file attributes, as specified in [RFC
   2184].

   The original local file name may be supplied as well, either as a
   "filename" parameter either of the "content-disposition: form-data"
   header or, in the case of multiple files, in a "content-disposition:
   file" header of the subpart. The sending application MAY supply a
   file name; if the file name of the sender's operating system is not
   in US-ASCII, the file name might be approximated, or encoded using
   the method of RFC 2231.

   This is a convenience for those cases where the files supplied by the
   form might contain references to each other, e.g., a TeX file and its
   .sty auxiliary style description. 
 

Friday, March 2, 2012

How to track index in 'for' loops when we have callback inside it

A typical problem faced while working with javascript code involving "for" loop with callbacks created in each run of the loop is that when the callback is actually executed the value of loop index is different than the one when the callback is created.

For Example

<script>
for(var i=0;i<10;i++){
 setTimeout(function(){alert(i);}.1000);
}
</script>

In each run of the loop a function object is created with its scope set to "global object".This global object contains variable i, the index of for loop.
All the 10 function objects will be referencing this 'i'  in the global object;
By the time call backs are run ,for loop exits and the value of i is 10.So when the call back are actually run, the value of i , which is now '10' is printed.

Simple  solution --- Anonymous function.
This works because as the scope of each function object created inside for loop now contains activation record of anonymous function (this record contains param index with value of  'i' in the current run of the loop).When the function are actually executed they refer to value of index in its scope.
 <script>
for(var i=0;i<10;i++){
 (function(index){
  setTimeout(function(){alert(index);}.1000);

 } )(i); 
}
</script>

Saturday, February 25, 2012

jQuery noconflict decrypted

What is jQuery noconflict ?
Its basically a way to tell jQuery to relinquish its control on $ or jQuery.

During its initialization it saves the existing values of $ / jQuery in current Window Scope.

var _jQuery = window.jQuery;
var _$ = window.$,

if $ / jQuery already in use prior to inclusing of jQuery script, _jQuery / _$ will  now store the existing values.Otherwise these variables are undefined.

In case of already in use if noconflict is not called, $/jQuery will point to jQuery object, thus losing the values of $/jQuery prior to inclusion of jQuery js file.

If you want jQuery not to interfere with old values of $ then call noConflict.