Eclipse and Eclipse RCP


Eclipse and Eclipse RCP

Eclipse RCP is a platform for building and deploying rich client desktop applications. The rich means "rich" user experience, It provides high-quality end-user experience, native user interfaces, high-speed local processing, rich UIs support such as drag-and-drop, system clipboard, navigation, and customization.

An RCP application is a collection of plug-ins and a Runtime on which they run. An RCP developer assembles a collection of plug-ins from the Eclipse base and elsewhere and adds in the plug-ins he has written.

Eclipse RCP consists of the following components:
    * Core platform, runtime, lifecycle manager
    * Equinox OSGi – a standard OSGI bundling framework   
    * Standard Widget Toolkit (SWT) – a portable widget toolkit
    * JFace – viewer classes to bring model view controller programming to SWT, file buffers, text handling, and text editors
    * Eclipse Workbench – views, editors, perspectives, wizards
    * An update manager
Advantages of Eclipse RCP
Native look and feel - SWT
SWT uses native widgets as much as possible; this makes the look and feel of SWT-based applications match that of the host window system.
Eclipse plugin mechanism and Extensibility - OSGI
       Eclipse RCP applications are composed of a collection of existing plug-ins and plug-ins we developed, and applications can evolve over time by adding and replacing components.
Many available Eclipse components/Plugins for reuse
There are many other Eclipse components or plugins available for reuse (e.g. Help UI, Update Manager, Cheat Sheets, Intro, etc.), also many third-parties components.
Intelligent install and update
Due to OSGI, you can install, uninstall, start, and stop different modules of your application dynamically without restarting the container.
Disconnected operation
Development tooling support


Some History
For traditional desktop application, deploying and upgrading clients is a manual task, and need much time and money.
Then along came the Internet and Web-based applications, or thin clients.
Thin clients solved many of the deployment and management problems related to rich clients. Since applications were on servers, updates were made centrally. User machines required only a Web browser. This reduced the cost of deploying and maintaining enterprise applications at the expense of the user experience thin clients did not provide the UI features and high-speed interactions users had come to expect.
Thin client applications, using the request-and-response model, required more networking capability to ensure optimal interaction performance.

Standard Widget Toolkit (SWT)
SWT is a low-level graphics library that provides standard UI controls such as lists, menus, fonts, and colors. To display GUI elements, the SWT implementation accesses the native GUI libraries of the operating system using JNI
Pros and cons of SWT
Native look and feel
The real trick of SWT is to use native widgets as much as possible. This makes the look and feel of SWT-based applications match that of the host window system.

And to avoid the least-common-denominator approach that doomed AWT to mediocrity, SWT implements widgets in Java if no native counterpart exists on the target platform
Better Performance
Cons:
Swing is distributed with the JRE, to use SWT, application must add additional SWT libraries.

SWT is not available on all Java-supported platforms, though SWT has already supported almost all mainstream platforms.
There is also some evidence that the performance of SWT on platforms other than Windows is noticeably less efficient.
Since SWT uses a different native library for each platform, SWT developers may be exposed to platform specific bugs.
JFace
JFace is built on top of SWT, and provides classes for handling common UI programming tasks. It brings MVC programming to the SWT, and includes a whole range of UI toolkit components, from image, standard dialogs and wizards etc.

Whereas SWT provides access to the widgets as defined by the window system, JFace adds structure and facilities for common UI notions.
UI Workbench
As JFace adds structure to SWT, the Workbench adds presentation and coordination to JFace. To the user, the Workbench consists of views and editors arranged in a particular layout. In particular, the Workbench:
* Provides contribution-based UI extensibility
* Defines a powerful UI paradigm with windows, perspectives, views, editors, and actions

OSGI
The Eclipse plug-in component model is based on an implementation of the OSGi framework, OSGI defines architecture for modular application development, OSGi specification forms a framework for defining, composing, and executing components or bundles.
OSGi offers the following advantages:
    * Dynamic Updates, you can install, uninstall, start, and stop different modules of your application dynamically without restarting the container.
    * Your application can have more than one version of a particular module running at the same time, you can enable the version you want.
    * Reuse - The OSGi component model makes it very easy to use many third party components in an application. An increasing number of open source projects provide their JARs ready made for OSGi.
    * OSGi provides very good infrastructure for developing service-oriented applications, as well as embedded, mobile, and rich internet apps.

OSGi container implementations include Eclipse Equinox, Knopflerfish, and Apache Felix. Many web servers such as Apache geronimo, SpringSource dm Server, also in IBM WAS are built on OSGI.
Eclipse
Eclipse is a multi-language software development environment comprising an IDE and an extensible plug-in system. It also can be used to develop C, C++, COBOL, Python, Perl, PHP, and others.

Users can extend its capabilities by installing plug-ins written for the Eclipse software framework, such as development toolkits for other programming languages, and can write and contribute their own plug-in modules.

Resources:
Eclipse Rich Client Platform: Designing, Coding, and Packaging Java(TM) Applications
http://www.ibm.com/developerworks/websphere/techjournal/0608_xu/0608_xu.html
Hello, OSGi, Part 1: Bundles for beginners
http://www.osgi.org/About/WhyOSGi
http://en.wikipedia.org/wiki/Rich_Client_Platform

Java Web Services


Java Web Services

Web services are typically application programming interfaces (API) or web APIs that is executed on a remote system and can be accessed over a network.

Web services can be divided roughly into two groups, SOAP-based and REST-style.

Advantages of Web Services
Language transparency and Interoperability
Web services and their clients can interoperate even if written in different programming languages. Language transparency is the key to web service interoperability that is the ability of web services and requesters to interact seamlessly despite differences in programming languages, support libraries, and platforms.

Standard and Open infrastructure
Web services are deployed using industry-standard, vendor-independent protocols such as HTTP and XML, SOAP, WSDL, which are ubiquitous and well understood.

Modular design
Web services are meant to be modular in design so that new services can be generated through the integration and layering of existing services, this is the basic concepts of SOA.

Main components in web services include XML, SOAP, and WSAL.
WSDL
The Web Services Description Language is an XML-based language that provides a model for describing Web services.

A WSDL document is a contract between a service and its consumers. The contract provides such critical information as the service endpoint, the service operations, and the data types required for these operations.

SOAP
SOAP stands for as Simple Object Access Protocol, is a protocol specification for exchanging structured information in the implementation of Web Services in computer networks.

It relies on XML as its message format, and usually relies on other Application Layer protocols (most notably HTTP and Remote Procedure Call (RPC)) for message negotiation and transmission.

In SOAP-based web services, the SOAP is mostly unseen infrastructure.

Web Services in Java
Java defines some APIs to support web services development such as JAX-WS, JAXP, and JAXB.

It is very easy to develop web services in Java EE5. After write web services interface, and implementation - POJO or EJB, we can just add annotation, @WebService, @WebMethod, @WebResult, @SOAPBinding, @WebServiceProvider(for Restful Web Service) to expose these operations as web services.

The Service Endpoint Interface and Service Implementation Bean
In A SOAP-based web service, there should be an interface that declares the methods, the interface is called the SEI: Service Endpoint Interface and an implementation, which implements the methods declared in the interface, the implementation is called the SIB: Service Implementation Bean.
The SIB can be either a POJO or a Stateless Session EJB.

Restful Web Service
REST stands for REpresentational State Transfer. Roy Fielding coined the acronym in his Ph.D. dissertation to describe an architectural style in the design of web services.

Jersey is reference implementation for building RESTful Web services.
WADL
WADL stands for Web Application Description Language.

WADL can be thought of as the REST equivalent of Web Services Description Language version 1.1. Version 2.0 of WSDL can be used to describe REST Web services, thus competing with WADL.

Resources:
Java Web Services: Up and Running
http://en.wikipedia.org/wiki/Web_service
http://en.wikipedia.org/wiki/SOAP

OOP in JavaScript


Object Oriented Programming in JavaScript

There are no classes in JavaScript. Functions can be used to somewhat simulate classes.
We can define instance properties, instance methods, and class properties, class methods, we can also use prototype to define inheritance.
In JavaScript, it's important to understand concept of execution context, search order, prototype.
Creating Objects
The simplest way to create a custom object is to create a new instance of Object and add properties and methods to it:
var person = new Object();
person.name = "Nicholas";
person.sayName = function(){ alert(this.name); };
The downside to this approach is that creating multiple objects with the same interface requires a lot of code duplication.
The Constructor Pattern
function Person(name, age, job){
    this.name = name; …
    this.sayName = function(){ alert(this.name);};   
}
Problems with Constructors
The major downside to constructors is that methods are created once for each instance and those instances' methods are not the same instance of Function.
The Prototype Pattern
The benefit of using the prototype is that all of its properties and methods are shared among object instances.
function Person(){}
Person.prototype.name = "Nicholas";
Person.prototype.sayName = function(){ alert(this.name); };
Alternate Prototype Syntax
Instead of adding to the prototype object, another way to achieve the above result is to overwrite the prototype completely.
Person.prototype = {
    constructor: Person,
    name : "Nicholas", …
    sayName : function () { alert(this.name); }
};
Problems with Prototypes
Prototype negates the ability to pass initialization arguments into the constructor. All properties on the prototype are shared among instances, this is ideal for functions, but problem occurs when a property contains a reference value.
Combination Constructor/Prototype Pattern
The most common way of defining custom types is to combine the constructor and prototype patterns. The constructor pattern defines instance properties, whereas the prototype pattern defines methods and shared property.
function Person(name, age, job){ this.name = name; }
Person.prototype = {
    constructor: Person,
    sayName : function () { alert(this.name); }
};
We can also enhance built-in objects, such as arrays or strings
Inheritance
Prototype Chaining
The basic idea is to use the concept of prototypes to inherit properties and methods between two reference types.
function SuperType(){}
function SubType(){}
SubType.prototype = new SuperType();//inherit from SuperType
SubType.prototype.getSubValue = function (){}; //new method
SubType.prototype.getSuperValue = function (){};  //override existing method
Problems with Prototype Chaining
The major issue revolves around prototypes that contain reference values. When implementing inheritance using prototypes, the prototype actually becomes an instance of another type, meaning that what once were instance properties are now prototype properties.
A second issue with prototype chaining is that you cannot pass arguments into the supertype constructor when the subtype instance is being created.
Constructor Stealing
The basic idea is quite simple: call the supertype constructor from within the subtype constructor.
function SuperType(name){ this.name = name;}
function SubType(){     
SuperType.call(this, “Nicholas”);
this.age = 29; //instance property
}
By using the call () method (or alternately, apply ()), the SuperType constructor is called in the context of the newly created instance of SubType. Doing this effectively runs all of the object-initialization code in the SuperType() function on the new SubType object. The result is that each instance has its own copy of the colors property.
Problems with Constructor Stealing
The downside to using constructor stealing is that:  methods must be defined inside the constructor, so there’s no function reuse.
Combination Prototype Chaining and Constructor Stealing
The basic idea is to use prototype chaining to inherit properties and methods on the prototype, and to use constructor stealing to inherit instance properties. This allows function reuse by defining methods on the prototype and allows each instance to have its own properties.
function SuperType(name){ this.name = name; }
function SubType(name, age){ 
    SuperType.call(this, name); //inherit properties
    this.age = age;
}
SubType.prototype = new SuperType();//inherit methods
SubType.prototype.sayAge = function(){};
Problems with Combination Inheritance
The most inefficient part of the pattern is that the supertype constructor is always called twice: once to create the subtype’s prototype, and once inside the subtype constructor.
Browser Object Model
The Browser Object Model (BOM) provides objects that expose browser functionality independent of any web page content, and provides objects, such as window, location, navigator, screen, and history.
Document Object Model
The DOM represents a document as a hierarchical tree of nodes, allowing        developers to add, remove, and modify individual parts of the page.

Resources:

SQL join


SQL join

A SQL JOIN clause is a means for combining records from two or more tables in a database by using values common to each.
ANSI standard SQL specifies several types of Joins: INNER, OUTER, LEFT, and RIGHT, full join.
There are also some derivations, such as self-join, cross join.
Inner Join
Inner join is the default join-type, it only return rows with matching values from both joined tables excluding all other rows.
Outer joins
An outer join does not require each record in the two joined tables to have a matching record. The joined table retains each record—even if no other matching record exists. Outer joins subdivide further into left outer joins, right outer joins, and full outer joins, depending on which table(s) one retains the rows from (left, right, or both).
The whole idea behind an outer join is to retrieve all rows from table A (left) or table B (right), even though there are no matching columns in the counterpart table. A left (or right) outer join also returns nulls for all unmatched columns from the joined table.
Left outer join
The result of a left outer join (or simply left join) for table A and B always contains all records of the "left" table (A), even if the join-condition does not find any matching record in the "right" table (B).
This means that if the ON clause matches 0 (zero) records in B, the join will still return a row in the result—but with NULL in each column from B.
This means that a left outer join returns all the values from the left table, plus matched values from the right table (or NULL in case of no matching join predicate).
If the left table returns one row and the right table returns more than one matching row for it, the values in the left table will be repeated for each distinct row on the right table.
Right outer joins
A right outer join (or right join) closely resembles a left outer join, except with the treatment of the tables reversed. Every row from the "right" table (B) will appear in the joined table at least once. If no matching row from the "left" table (A) exists, NULL will appear in columns from A for those records that have no match in B.
A right outer join returns all the values from the right table and matched values from the left table (NULL in case of no matching join predicate).
The only difference between left and right outer joins is the order in which the tables are joined in the query, and they can always be replaced with left outer joins.
Full outer join
A full outer join combines the results of both left and right outer joins. It returns all rows from both "left" and "right" tables, no matter if the counterpart table has matching rows or not, and fill in Nulls for missing matches on either side.
Other kinds of Join
Natural join
Natural-join joins tables by column(s) with identical names. we don't have to specify the columns explicitly in the ON subclause of the SELECT statement's FROM clause. The ON subclause is omitted completely.
Self-join
A self-join is joining a table to itself.
One important thing to understand is that despite the fact that we are joining the table with itself, we are still dealing with two instances of the same table, or with two identical tables rather than with just one table.
Cross join (Cartesian product)
A cross join combines every row in B with every row in A. The number of rows in the result set will be the number of rows in A times the number of rows in B. Thus, if A and B are two sets, then the cross join is written as A × B.

Example
Employee and Department Table

Resources:
Join (SQL)
SQL Bible

JSON and XML


JSON and XML

JSON
JSON, short for JavaScript Object Notation, is an open standard, lightweight, text-based, human-readable data interchange format derived from the JavaScript programming language for representing simple data structures and associative arrays (called objects). Despite its close connection to JavaScript, it is language-independent, with parsers available for virtually every programming language in existence.
The JSON format is often used for serializing and transmitting structured data between a server and web application, serving as an alternative to XML.
Many browsers now support native JSON, which is generally faster.
JSON vs XML
http://stackoverflow.com/questions/1579269/any-particular-advantage-to-using-json-over-xml-with-flash
http://stackoverflow.com/questions/584985/what-are-the-advantages-and-disadvantages-of-json-vs-xml-for-ajax-requests
Advantages of JSON
   1. JSON is typically a more efficient data encoding method than XML; it’s much smaller than XML. XML is verbose, and cumbersome, 90% hypertext and 10% data.   JSON can save bandwidth and get much better response times, excellent for AJAX.
   2. JSON can be parsed more efficiently, it is a subset of JavaScript, we can easily parse it in JavaScript, such as call eval.
Advantages of XML
XML has been around for quite a while, and has lots of tool support.
XML has schema, we can use schema to validate the data.
Disadvantages
Using XML in JavaScript is quite verbose and cumbersome.
JSONP
JSONP or "JSON with padding" is a complement to the base JSON data format, a usage pattern that allows a page to request and more meaningfully use JSON from a server other than the primary server.
HTML <script> tags can retrieve data from other sites.
<script type="text/javascript" src="http://domain1.com/getjson?jsonp=parseResponse"></script>
The server wraps its JSON response with this prefix, or "padding", before sending it to the browser. When the browser receives the wrapped response from the server it is now a script, rather than simply a data declaration.
Same origin policy
The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites.

RESTful Web Services


Urls
- Short, Meaningful, Predictable, Readable urls
- Nouns, not verbs
- Lower case
- Use hypens rather than spaces or underlines
- Use a plural path for collections
- Put individual resources under the plural collection path.
- Favor hackable urls over direct urls.

Idempotent
stateless
versioned
PATCH - to update parts of a resource, update one or more fields as opposed to all fields.
Define SLA

actions
POST /transactions
from=1&to=2&amount=500.00

REST is a term coined by Roy Fielding in his Ph.D. dissertation to describe an architecture style of networked systems.
REST is an acronym standing for Representational State Transfer, REST defines a set of architectural principles by which you can design Web services that focus on a system's resources, including how resource states are addressed and transferred over HTTP by a wide range of clients written in different languages.
REST is a key design idiom that embraces a stateless client-server architecture in which the web services are viewed as resources and can be identified by their URLs.
Web service clients use a small globally defined set of remote methods, such as GET, Put, POST, and DELETE to access and manipulate the resource. REST is an analytical description of the existing web architecture, and thus the interplay with HTTP protocol appears seamlessly.
REST isn’t protocol-specific, but they usually mean REST over HTTP.
The HTTP methods such as GET, PUT, POST, DELETE are the verbs that the developer can use to describe the necessary create, read, update, and delete (CRUD) actions to be performed.
REST has had such a large impact on the Web that it has mostly displaced SOAP- and WSDL-based interface design because it's a considerably simpler style to use.
Motivation for REST
The motivation for REST was to capture the characteristics of the Web which has made the Web successful. 
REST is an Architectural Style, not a standard.
REST Web Services Characteristics
Here are the characteristics of REST:
  • REST is a pull-based interaction style client-server model.
  • Named and addressable resources
         The key abstraction of information and data in REST is a resource, and the system is comprised of resources which are named using a URI. (Uniform Resource Identifier)
  • A uniform, constrained interface
         All resources are manipulated with a generic interface (e.g., HTTP GET, POST, PUT, DELETE).
         Advantages:

    1. Familiarity
    2. Interoperability
    HTTP is a very ubiquitous protocol. Most programming languages have an HTTP
    1. client library available to them.
  • Communicate stateless
        Stateless applications are easier to scale to meet increasingly high performance demands; each request from client to server must contain  all the information necessary to understand the request.
        Stateless services are less complicated to design, write, and distribute across load-balanced servers. A stateless service performs better and shifts most of the responsibility of maintaining state to the client application. 
        Advantages:
    1. Scalability
                  We can reuse the rich and configurable caching semantics defined in HTTP, such as client browser cache, procy etc.
  • Hypermedia As The Engine Of Application State (HATEOAS)
    Let your data formats drive state transitions in your applications.
One of the uses of hypermedia and hyperlinks is composing complex sets of information from disparate sources. Hyperlinks allow us to reference and aggregate additional data without bloating our responses.
with each request returned from a server it tells you what new interactions you can do next, as well as where to go to transition the state of your applications.
     Miscs 
  • Cache: A caching infrastructure can be leveraged for performance; GET method can normally be cacheable.
  • Use HTTP methods explicitly, RESTful Web service uses Put, GET, POST, and DELETE to create, retrieve, change and delete a resource.
  • Expose directory structure-like URIs, REST Web services normally use directory structure-like URIs,
http://www.myservice.org/discussion/topics/{topic}
http://www.myservice.org/discussion/{year}/{day}/{month}/{topic}
This kind of URI is straightforward, predictable, and easily understood.
    * Interconnected resource representations - the representations of the resources are interconnected using URLs, thereby enabling a client to progress from one state to another. We can put hyperlinks within resource representations to enable clients to drill down for more information, and/or to obtain related information
    * Layered components - intermediaries, such as proxy servers, cache servers, gateways, etc, can be inserted between clients and resources to support performance, security, etc.
Principles of REST Web Service Design
1. The key to creating Web Services in a REST network (i.e., the Web) is to identify all of the conceptual entities that you wish to expose as services.
2. Create a URL to each resource. The resources should be nouns, not verbs.
3. Categorize your resources according to whether clients can just receive a representation of the resource, or whether clients can modify (add to) the resource. For the former, make those resources accessible using an HTTP GET. For the later, make those resources accessible using HTTP POST, PUT, and/or DELETE.
4. All resources accessible via HTTP GET should be side-effect free. That is, the resource should just return a representation of the resource. Invoking the resource should not result in modifying the resource.
5. No representation should be an island, put hyperlinks within resource representations to enable clients to drill down for more information, and/or to obtain related information.
6. Design to reveal data gradually. Don't reveal everything in a single response document. Provide hyperlinks to obtain more details.
7. Specify the format of response data using a schema. For those services that require a POST or PUT to it, also provide a schema to specify the format of the response.
8. Describe how your services are to be invoked using either a WADL document, or simply an HTML document.
RESTful Support in JAX-WS
The Java API for XML Web Services (JAX-WS) provides full support for building and deploying RESTful web services, The API was developed through JSR 224, JSR-311.


Resources:
RESTful Java with Jax-RS (Animal Guide)
RESTful Web services: The basics
RESTful Web Services
Representational State Transfer (REST) - Roy Fielding

Out of Memory - TimerTask.cancel and GC


Out of Memory Defect - TimerTask.cancel and GC

TimerTask.cancel() simply marks the task as cancelled, doesn’t cause it to be garbage collected. The Timer only releases TimerTask objects when they reach the head of the queue.
In fact, the TimerTask Object is actually only removed from the queue when the TimerTask is already cancelled at the point of time when the TimerTask is being checked by the Timer. See code extracted from Timer class
java.util.TimerThread.mainLoop()
while (true) {
    if (task.state == TimerTask.CANCELLED) {
        queue.removeMin();
        continue// No action required, poll queue again
    }
                     
It is possible to fill memory with cancelled timeouts if the timeouts are sufficiently long and there are valid timeouts ahead of them in the queue.

So when we cancel TimerTask, we should also free all references hold by the TimerTask when it is cancelled, otherwise the objects in the already cancelled TimerTask still use memory and may finally cause OOM.

This problem can be verified by the following simple test program.
import java.util.*;

class Chatter extends TimerTask {
    private int[] randomA, randomB, randomC;
    public Chatter(int[] randomA, int[] randomB, int[] randomC) {
       this.randomA = randomA;
       this.randomB = randomB;
       this.randomC = randomC;
    }
    public void run() {
       System.out.println("Timer run.");
    }
    @Override
    public boolean cancel() {
       System.out.println("Timer is cancelled");
       // we should overwrite TimerTask.cancel method, and null out all references
//     randomA = null;
//     randomB = null;
//     randomC = null;
       return super.cancel();
    }
}

public class TryThread {
    public static void main(String[] argv) throws InterruptedException {
       Timer t = new Timer(false);
       long timeout = 6000000; //6000 seconds
       Chatter chatter;
       int size = 100000;
       while (true) {
           int[] randomA = new int[size], randomB = new int[size] , randomC = new int[size];
           chatter = new Chatter(randomA, randomB, randomC);
           t.schedule(chatter, timeout);
           // after 10 seconds, cancel the timerTask
           Thread.sleep(10000);
           chatter.cancel();
            System.out.println(new Date() + " before GC call, free mem: " + Runtime.getRuntime().freeMemory());
            System.gc();
            System.out.println(new Date() +  " after GC call, free mem: " + Runtime.getRuntime().freeMemory());
       }
    }
}

At first, when TimerTask is cancelled, the program doesn't null out all TimerTask's references.

Run 'java -Xmx50m TryThread', After about 7 mins, the program hits OOM.
Timer is cancelled
Tue Apr 06 22:17:17 CST 2010 before GC call, free mem: 6173440
Tue Apr 06 22:17:17 CST 2010 after GC call, free mem: 6412104
...
Timer is cancelled
Tue Apr 06 22:23:58 CST 2010 before GC call, free mem: 1153672
Tue Apr 06 22:23:58 CST 2010 after GC call, free mem: 1184120
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
        at TryThread.main(TryThread.java:30)

After add the logic to null out all references in TimerTask.cancel method, the program runs smoothly, the free memory is stable.
Timer is cancelled
Tue Apr 06 22:18:18 CST 2010 before GC call, free mem: 6173416
Tue Apr 06 22:18:18 CST 2010 after GC call, free mem: 6349088

Timer is cancelled
Wed Apr 07 00:20:38 CST 2010 before GC call, free mem: 5275920
Wed Apr 07 00:20:38 CST 2010 after GC call, free mem: 6475912

Resources:
http://forums.sun.com/thread.jspa?threadID=239011

J2EE interview -- Spring


J2EE interview -- Spring

Spring Overview Spring is a lightweight, complete solution that makes building enterprise Java applications much easier.

Modularity is its key feature, which allows enterprise application developers to use only the modules they require from the stack. IoC container

Inversion of Control is also known as dependency injection (DI). It is a process whereby objects define their dependencies via constructor, or setter method. The container then injects those dependencies when it creates the bean. AOP Second AOP, Aspect-Oriented Programming complements Object-Oriented Programming (OOP) by providing another way of thinking about program structure. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Aspects enable the abstraction and modularization of crosscutting concern such as transaction management, logging, validation, authentication, authorization. Traditional object-oriented approach would cause two problems.

1. Code tangling: methods would include core logic and other crosscutting concerns; this will lead to poor code maintainability and reusability.

2. Code scattering: we have to repeat same statements and logics multiple times in multiple modules to fulfill a single requirement, if later we need to change the logic; we have to change all places.

AOP provides another way to implement crosscutting concerns. We implement the crosscutting concerns as aspects, and then through XML or Annotation, we weave aspects into various objects, in this way, we place the crosscutting concern in only one place. Spring has its own AOP framework, which successfully addresses the 80%s of AOP requirements. Also Spring provides integration with AspectJ, which is the richest and certainly most mature AOP implementation in the Java enterprise space. AOP is used in the Spring Framework to... • ... Provide declarative enterprise services. • ... Allow users to implement custom aspects. Data Access layer

Spring provides a comprehensive and consistent abstraction for transaction management. Spring provides consistent exception hierarchy, Spring wraps JDBC exceptions, Hibernate JDO and JPA specific exceptions, converts them from proprietary, checked exceptions to a set of runtime, unchecked exceptions, inherited from DataAccessException. This allows one to handle most persistence exceptions, which are non-recoverable, only in the appropriate layers, without having annoying boilerplate catch-and-throw blocks and exception declarations in one's DAOs. We can still trap and handle exceptions anywhere one needs to though. Spring JDBC abstraction simplifies the use of JDBC, by providing APIs that move tedious and error-prone exception handling out of application code into the framework. The framework takes care of all exception handling, Open the connection, Handle transactions, Close the connection, statement and resultset, application code can concentrate on issuing the appropriate SQL and extracting results. Spring supports integration with Hibernate, JPA, JDO and iBATIS. Spring also provides support for Object/XML Mapping, that is to convert an XML document to and from an object. Spring MVC Fourthly, In Web Layer, Spring provides Spring MVC, Spring's MVC model is most similar to that of Struts, But Spring MVC has some significant advantages over Struts.

Spring provides a very clean division between controllers, JavaBean models, and views.

Reusable business code, no need for duplication. we can use existing business objects as command or form objects instead of mirroring them and create a similar DTO object, such as formbean in struts1.

Spring, like WebWork, provides interceptors as well as controllers, making it easy to factor out behavior common to the handling of many requests.

Spring MVC is truly view-agnostic. You can choose to use nay view technologies like JSP, Velocity, XLST, iText, or POI, you can even write your custom view mechanism.

Spring Controllers are configured via IoC like any other objects. This makes them easy to test, and beautifully integrated with other objects managed by Spring.

Spring also provides a JSP form tag library, that makes writing forms in JSP pages much easier.

Spring MVC web tiers are typically easier to test than Struts web tiers, due to the avoidance of forced concrete inheritance and explicit dependence of controllers on the dispatcher servlet.

Also we can choose other web frameworks, and Srping provide integration with most of popular third party web frameworks such as struts1/2, JSF. Spring also makes it much easier to access, use EJBs and implement EJBs. Integration Spring provides a consistent integration and abstraction framework for many Java EE related technologies, such as JMS, JMX, Email, task scheduling, and integrate with other dynamic languages. Spring simplifies the use of these API remarkably. Spring also provides Security framework, Spring Security, previously call Acegi. The IoC container IoC(Inversion of Control ) is also known as dependency injection (DI). It is a process whereby objects define their dependencies, that is, the other objects they work with, only through constructor, or setter method. The container then injects those dependencies when it creates the bean. This process is fundamentally the inverse of the bean itself controlling the instantiation or location of its dependencies by using direct construction of classes, or a mechanism such as the Service Locator pattern. Spring provides BeanFactory and ApplicationContext. The BeanFactory provides the configuration framework and basic functionality, and the ApplicationContext is a sub-interface of BeanFactory, and adds more enterprise-specific functionality. Spring supports XML-based and annotation-based configuration. Are annotations better then XML for configuring Spring? Due to the way they are defined, annotations provide a lot of context in their declaration leading to shorter, more concise configurations. However XML excels at wiring up components without touching their source code or recompile them. Some prefer having the wiring close to the source while others argue that annotated classes are no longer POJOs and further more that the configuration becomes decentralized and harder to control. Annotation-based container configuration Spring provides @Resource, @PostConstruct, and @PreDestroy, @Inject, @Required etc... Classpath scanning and managed components @Component and further stereotype annotations @Component is a generic stereotype for any Spring-managed component. @Repository, @Service, and @Controller are specializations of @Component for more specific use cases, for example, in the persistence, service, and presentation layers, respectively. Aspect-Oriented Programming (AOP) AOP concepts • Aspect: a modularization of a concern that cuts across multiple classes. Transaction management is a good example of a crosscutting concern in Java EE applications. • Join point: a point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution. • Advice: action taken by an aspect at a particular joins point. Different types of advice include "around," "before" and "after" advice. Many AOP frameworks, including Spring, model an advice as an interceptor, maintaining a chain of interceptors around the join point. • Pointcut: a predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut (for example, the execution of a method with a certain name). The concept of join points as matched by pointcut expressions is central to AOP, and Spring uses the AspectJ pointcut expression language by default. Types of advice: Before advice, After returning advice, After throwing advice, After (finally) advice, Around advice. Data Access Layer In Data Access layer, Spring provides a comprehensive and consistent abstraction for transaction management, that delivers the following benefits: • Consistent programming model across different transaction APIs such as Java Transaction API (JTA), JDBC, Hibernate, Java Persistence API (JPA), and Java Data Objects (JDO). • Support for declarative transaction management and Programmatic transaction management. Also Spring's DAO support aims at making it easy to work with data access technologies like JDBC, Hibernate, JPA or JDO in a consistent way. This allows one to switch between these persistence technologies fairly easily. Consistent exception hierarchy Spring provides consistent exception hierarchy. Spring provides a convenient translation from technology-specific exceptions like SQLException to its own exception class hierarchy with the DataAccessException as the root exception.

Spring wraps JDBC exceptions, Hibernate JDO and JPA specific exceptions, converts them from proprietary, checked exceptions to a set of runtime, unchecked exceptions, inherited from DataAccessException. This allows one to handle most persistence exceptions, which are non-recoverable, only in the appropriate layers, without having annoying boilerplate catch-and-throw blocks and exception declarations in one's DAOs. We can still trap and handle exceptions anywhere one needs to though. Spring JDBC abstraction JDBC offers fairly good abstraction from the underlying database, but is a painful API to use. Some of the problems include: The need for verbose error handling to ensure that ResultSets, Statements and (most importantly) Connections are closed after use. This means that correct use of JDBC can quickly result in a lot of code. It's also a common source of errors. Connection leaks can quickly bring applications down under load. The relatively uninformative SQLException. JDBC does not offer an exception hierarchy, but throws SQLException in response to all errors. Finding out what actually went wrong involves examining the SQLState value and error code. The meaning of these values varies between databases. Spring addresses these problems in two ways: By providing APIs that move tedious and error-prone exception handling out of application code into the framework. The framework takes care of all exception handling, Open the connection, Handle transactions, Close the connection, statement and resultset, application code can concentrate on issuing the appropriate SQL and extracting results. By providing a meaningful exception hierarchy for your application code to work with in place of SQLException. Spring ORM Support Spring supports integration with Hibernate, Java Persistence API (JPA), Java Data Objects (JDO) and iBATIS for resource management, data access object (DAO) implementations, and transaction strategies. Benefits of Spring ORM Support include: Common data access exceptions. Spring can wrap exceptions from your ORM tool, converting them from proprietary (potentially checked) exceptions to a common runtime DataAccessException hierarchy. This feature allows you to handle most persistence exceptions, which are non-recoverable, only in the appropriate layers, without annoying boilerplate catches, throws, and exception declarations. You can still trap and handle exceptions as necessary. Spring's Object/XML Mapping support Spring also provides support for Object/XML Mapping, that is to convert an XML document to and from an object. The Web Layer Spring MVC is designed around a DispatcherServlet that dispatches requests to handlers, with configurable handler mappings, view resolution, locale and theme resolution. A Controller implementation can even write directly to the response stream. Typically, a ModelAndView instance consists of a view name and a model Map, which contains bean names and corresponding objects such as a command or form, which contain reference data. Also we can choose other web frameworks, and Srping provide integration with most of popular third party web frameworks such as struts1/2, JSF.

This allows one to continue to leverage any and all of the skills one may have acquired in a particular web framework such as Struts, while at the same time being able to enjoy the benefits afforded by Spring in other areas such as data access, declarative transaction management, and flexible configuration and application assembly.

Other features

Spring Expression Language(SpEL)

Object/XML Mapping (OXM) module

Resources Introducing the Spring Framework spring-framework-reference-3.0.pdf

Labels

adsense (5) Algorithm (69) Algorithm Series (35) Android (7) ANT (6) bat (8) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) Java (186) JavaScript (27) JSON (7) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) regex (5) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) xml (5)