Saturday, November 15, 2014

Generics

Generic Types & Methods :- 
e.g. Generic Type -- public class List
      Generic Method -- public void add(List elements)

Type-safe - A program is type safe when it compiles without  any errors & warnings & does not raise classcast exception at runtime.

Enum, Inner callse & exception can not be generic types.

Concrete parameterized types -- List<String>
Non - Concrete parameterized types -- List<? extends List>

Array of concrete parameterized type is not allowed.
Rawtype :- Generic type without type argument.

Collection of concrete parameterized type is allowed.

Generic Type


/**
 * Generic version of the Box class.
 * @param  the type of value being boxed
 */
public class Box {

    // T stands for "Type"
    private T t;

    public void add(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }
}

Box integerBox = new Box();
 
The most commonly used type parameter names are:
  • E - Element (used extensively by the Java Collections Framework)
  • K - Key
  • N - Number
  • T - Type
  • V - Value
  • S,U,V etc. - 2nd, 3rd, 4th types

Generic Methods

Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors.
e.g.
     public static  boolean compare(Pair p1, Pair p2) {
        return p1.getKey().equals(p2.getKey()) &&
               p1.getValue().equals(p2.getValue());
     } 

Bounded Type Parameters

There may be times when you want to restrict the types that can be used as type arguments in a parameterized type. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for.
To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound, which in this example is Number. Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces).

    public extends Number
> void inspect(U u){ System.out.println("U: " + u.getClass().getName()); }

Type Inference

Type inference is a Java compiler's ability to look at each method invocation and corresponding declaration to determine the type argument (or arguments) that make the invocation applicable. The inference algorithm determines the types of the arguments and, if available, the type that the result is being assigned, or returned. Finally, the inference algorithm tries to find the most specific type that works with all of the arguments.
To illustrate this last point, in the following example, inference determines that the second argument being passed to the pick method is of type Serializable:
static  T pick(T a1, T a2) { return a2; }
Serializable s = pick("d", new ArrayList());

Wildcards

In generic code, the question mark (?), called the wildcard, represents an unknown type.?  -  unbound wildcard.
? extends Type  - a wildcard with upper bound. It stands for family of all types that are subtypes of Type.
? super Type - a wildcard with lower bound. It stands for family of all types that are supertypes of Type.

Overriding, overloading generic type method take precautions as multiple overload methods of generic sub-type results into only one method after compilation.

Wildcards broaden the set of argument or return types that a method accepts or returns. 

Wildcards and Subtyping

List al = new ArrayList<>();

List nl = al; // COMPILE TIME ERROR

Although Integer is a subtype of Number, List is not a subtype of List and, in fact, these two types are not related. The common parent of List and List is List.

List al = new ArrayList<>();

List nl = al; // NO ERROR

Guidelines for Wildcard Use

For purposes of this discussion, it is helpful to think of variables as providing one of two functions:

An "In" Variable
An "in" variable serves up data to the code. Imagine a copy method with two arguments: copy(src, dest). The src argument provides the data to be copied, so it is the "in" parameter.
An "Out" Variable
An "out" variable holds data for use elsewhere. In the copy example, copy(src, dest), the dest argument accepts data, so it is the "out" parameter.
Of course, some variables are used both for "in" and "out" purposes — this scenario is also addressed in the guidelines.
You can use the "in" and "out" principle when deciding whether to use a wildcard and what type of wildcard is appropriate. The following list provides the guidelines to follow:

Wildcard Guidelines: 
  • An "in" variable is defined with an upper bounded wildcard, using the extends keyword.
  • An "out" variable is defined with a lower bounded wildcard, using the super keyword.
  • In the case where the "in" variable can be accessed using methods defined in the Object class, use an unbounded wildcard.
  • In the case where the code needs to access the variable as both an "in" and an "out" variable, do not use a wildcard.

 

In Java SE 7 and later, you can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can determine, or infer, the type arguments from the context. This pair of angle brackets, <>, is informally called the diamond. For example, you can create an instance of Box with the following statement:
 
Box integerBox = new Box<>();


Type Erasure

When a generic type is instantiated, the compiler translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method. Type erasure enables Java applications that use generics to maintain binary compatibility with Java libraries and applications that were created before generics.

Restrictions on Generics

To use Java generics effectively, you must consider the following restrictions:

Reference
http://docs.oracle.com/javase/tutorial/java/generics/index.html

Friday, June 27, 2014

Angular JS

AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML's syntax to express your application's components clearly and succinctly. It is MVC framework for client side. It avoids DOM manupulation like JQuery.

The ng-app attribute represents an Angular directive named ngApp (Angular uses spinal-case for its custom attributes andcamelCase for the corresponding directives which implement them). This directive is used to flag the html element that Angular should consider to be the root element of our application. This gives application developers the freedom to tell Angular if the entire html page or only a portion of it should be treated as the Angular application.

Angular expression is a JavaScript-like code snippet that is evaluated by Angular in the context of the current model scope, rather than within the scope of the global context (window).


Angular Expressions vs. JavaScript Expressions

Angular expressions are like JavaScript expressions with the following differences:
  • Context: JavaScript expressions are evaluated against the global window. In Angular, expressions are evaluated against a scopeobject.
  • Forgiving: In JavaScript, trying to evaluate undefined properties generates ReferenceError or TypeError. In Angular, expression evaluation is forgiving to undefined and null.
  • No Control Flow Statements: you cannot use the following in an Angular expression: conditionals, loops, or exceptions.
  • Filters: You can use filters within expressions to format data before displaying it.
If you want to run more complex JavaScript code, you should make it a controller method and call the method from your view. If you want toeval() an Angular expression yourself, use the $eval() method.

Bootstrapping AngularJS apps

Angular initializes automatically upon DOMContentLoaded event or when theangular.js script is evaluated if at that time document.readyState is set to'complete'. At this point Angular looks for the ng-app directive which designates your application root. If the ng-app directive is found then Angular will: 
  • load the module associated with the directive.
  • create the application injector
  • compile the DOM treating the ng-app directive as the root of the compilation. This allows you to tell it to treat only a portion of the DOM as an Angular application.

Compiler

Compiler is an Angular service which traverses the DOM looking for attributes. The compilation process happens in two phases.
  1. Compile: traverse the DOM and collect all of the directives. The result is a linking function.
  2. Link: combine the directives with a scope and produce a live view. Any changes in the scope model are reflected in the view, and any user interactions with the view are reflected in the scope model. This makes the scope model the single source of truth.
Directive
A directive is a behavior which should be triggered when specific HTML constructs are encountered during the compilation process. The directives can be placed in element names, attributes, class names, as well as comments. Here are some equivalent examples of invoking the ng-bind directive.
A directive is just a function which executes when the compiler encounters it in the DOM. See directive API for in-depth documentation on how to write directives.

How directives are compiled

It's important to note that Angular operates on DOM nodes rather than strings. Usually, you don't notice this restriction because when a page loads, the web browser parses HTML into the DOM automatically.
HTML compilation happens in three phases:
  1. $compile traverses the DOM and matches directives.
    If the compiler finds that an element matches a directive, then the directive is added to the list of directives that match the DOM element. A single element may match multiple directives.
  2. Once all directives matching a DOM element have been identified, the compiler sorts the directives by their priority.
    Each directive's compile functions are executed. Each compile function has a chance to modify the DOM. Each compilefunction returns a link function. These functions are composed into a "combined" link function, which invokes each directive's returned link function.
  3. $compile links the template with the scope by calling the combined linking function from the previous step. This in turn will call the linking function of the individual directives, registering listeners on the elements and setting up $watchs with the scope as each directive is configured to do.

Module

You can think of a module as a container for the different parts of your app – controllers, services, filters, directives, etc
Most applications have a main method that instantiates and wires together the different parts of the application.
Angular apps don't have a main method. Instead modules declaratively specify how an application should be bootstrapped. There are several advantages to this approach:
  • The declarative process is easier to understand.
  • You can package code as reusable modules.
  • The modules can be loaded in any order (or even in parallel) because modules delay execution.
  • Unit tests only have to load relevant modules, which keeps them fast.
  • End-to-end tests can use modules to override configuration.

Scope

A scope can be seen as the glue which allows the template, model and controller to work together. Angular uses scopes, along with the information contained in the template, data model, and controller, to keep models and views separate, but in sync. Any changes made to the model are reflected in the view; any changes that occur in the view are reflected in the model.
scope is an object that refers to the application model. It is an execution context for expressions. Scopes are arranged in hierarchical structure which mimic the DOM structure of the application. Scopes can watch expressions and propagate events.
  • Scopes provide APIs ($watch) to observe model mutations.
  • Scopes provide APIs ($apply) to propagate any model changes through the system into the view from outside of the "Angular realm" (controllers, services, Angular event handlers).
  • Scope 2 type - child scope, isolated scope
During the template linking phase the directives set up $watch expressions on the scope. The $watch allows the directives to be notified of property changes, which allows the directive to render the updated value to the DOM.

Isolate scope as name suggests will not inherit from parent scope. Useful for directives to have its own value for multiple instances.

Controller


In Angular, a Controller is a JavaScript constructor function that is used to augment the Angular Scope.
When a Controller is attached to the DOM via the ng-controller directive, Angular will instantiate a new Controller object, using the specified Controller's constructor function. A new child scope will be available as an injectable parameter to the Controller's constructor function as $scope.
Use controllers to:
  • Set up the initial state of the $scope object.
  • Add behavior to the $scope object.

Service components in ng

NameDescription
$anchorScroll
When called, it checks current value of $location.hash() and scrolls to the related element, according to rules specified in Html5 spec.
$animate
The $animate service provides rudimentary DOM manipulation functions to insert, remove and move elements within the DOM, as well as adding and removing classes. This service is the core service used by the ngAnimate $animator service which provides high-level animation hooks for CSS and JavaScript.
$cacheFactory
Factory that constructs Cache objects and gives access to them.
$templateCache
The first time a template is used, it is loaded in the template cache for quick retrieval. You can load templates directly into the cache in a script tag, or by consuming the $templateCache service directly.
$compile
Compiles an HTML string or DOM into a template and produces a template function, which can then be used to linkscope and the template together.
$controller
$controller service is responsible for instantiating controllers.
$document
jQuery or jqLite wrapper for the browser's window.document object.
$exceptionHandler
Any uncaught exception in angular expressions is delegated to this service. The default implementation simply delegates to $log.error which logs it into the browser console.
$filter
Filters are used for formatting data displayed to the user.
$http
The $http service is a core Angular service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP.
$httpBackend
HTTP backend used by the service that delegates to XMLHttpRequest object or JSONP and deals with browser incompatibilities.
$interpolate
Compiles a string with markup into an interpolation function. This service is used by the HTML $compile service for data binding. See $interpolateProvider for configuring the interpolation markup.
$interval
Angular's wrapper for window.setInterval. The fn function is executed every delay milliseconds.
$locale
$locale service provides localization rules for various Angular components. As of right now the only public api is:
$location
The $location service parses the URL in the browser address bar (based on the window.location) and makes the URL available to your application. Changes to the URL in the address bar are reflected into $location service and changes to $location are reflected into the browser address bar.
$log
Simple service for logging. Default implementation safely writes the message into the browser's console (if present).
$parse
Converts Angular expression into a function.
$q
A promise/deferred implementation inspired by Kris Kowal's Q.
$rootElement
The root element of Angular application. This is either the element where ngApp was declared or the element passed into angular.bootstrap. The element represent the root element of application. It is also the location where the applications $injector service gets published, it can be retrieved using $rootElement.injector().
$rootScope
Every application has a single root scope. All other scopes are descendant scopes of the root scope. Scopes provide separation between the model and the view, via a mechanism for watching the model for changes. They also provide an event emission/broadcast and subscription facility. See the developer guide on scopes.
$sceDelegate
$sceDelegate is a service that is used by the $sce service to provide Strict Contextual Escaping (SCE) services to AngularJS.
$sce
$sce is a service that provides Strict Contextual Escaping services to AngularJS.
$timeout
Angular's wrapper for window.setTimeout. The fn function is wrapped into a try/catch block and delegates any exceptions to $exceptionHandler service.
$window
A reference to the browser's window object. While window is globally available in JavaScript, it causes testability problems, because it is a global variable. In angular we always refer to it through the $window service, so it may be overridden, removed or mocked for testing.


Saturday, April 12, 2014

JEE 6 NEW FEATURES

Web profile :- Java EE 6 defines the first profile, called the Web Profile. This initial profile is a Java EE platform subset for web application development. 


  • JavaServer Faces (JSF) 2.0
  • JavaServer Pages 2.2 and Expression Language (EL) 1.2
  • A Standard Tag Library for JavaServer Pages 1.2
  • Debugging Support for Other Languages 1.0
  • Contexts and Dependency Injection for the Java EE Platform 1.0
  • Dependency Injection for Java
  • Enterprise JavaBeans 3.1(EJB Lite)
  • Java Persistence API 2.0
  • Common Annotations for the Java Platform 1.1
  • Java Transaction API (JTA) 1.1
  • Bean Validation 1.0



  • Java API for RESTful Web Services (JAX-RS)
  • Contexts and Dependency Injection for the Java EE Platform (CDI) -- CDI unifies and simplifies the EJB and JSF programming models. It allows enterprise beans to act as JSF managed beans in a JSF application, and brings transactional support to the web tier. CDI builds on managed beans, which are designed to unify all of the various types of beans in Java EE 6. In JSF2.2 backing beans are now managed beans & denoted by annotation @ManagedBean, CDI services allow Java EE components, including EJB components, to be bound to lifecycle events using @Model. @Inject, identifies a point at which a dependency on a Java class or interface can be injected. @Interceptors allows interceptors in managed bean
    • @Inject. Identifies injectable constructors, methods, and fields.
    • @Qualifier. Identifies qualifier annotations. Qualifiers are strongly-typed keys that help distinguish different uses of objects of the same type. For example, a @Red Car and a @Blue Car are understood to be different instances of the same type. In this example,@Red and @Blue are qualifiers.
    • @Scope. Identifies scope annotations.
    • @Singleton. Identifies a type that the injector only instantiates once
    • @Named. A String-based qualifier to access methos in Facelets using EL.
  • Bean Validation :- Bean Validation affords a standard framework for validation, in which the same set of validations can be shared by all the layers of an application. Bean Validation includes a number of built-in constraint definitions. You add your own constraints by declaring an annotation type that specifies a validator class.
    • e.g. @ZipCode, @Size, @ConstraintValidator, @NotNull

    • Servlet 3.0 :- Web fragments enable web frameworks to self-register, eliminating the need for you to register them through deployment descriptors. The  element identifies a web fragment. A web fragment must be in a file named web-fragment.xml and can be placed in any location in a web application's classpath. However, it's expected that a web framework will typically place its web fragments in the META-INF directory of the framework's JAR file. 
      • Instead of creating deployment descriptors, you can annotate classes to specify servlet-related deployment information.
      • @WebServlet
      • @WebFilter
      • @WebInitParam
      • @WebListener
      • @MultipartConfig
    • Asynchronous Processing in Servlet 3.0 :- A servlet no longer has to wait for a response from a resource such as a database before its thread can continue processing. To make a servlet asynchronous, you specify asyncSupported=true in a@WebServlet annotation
    • Simplified Page Authoring in JSF 2.0 :- 
      • Facelets :- In JSP, elements in a web page are processed and rendered in a progressive order. However, JSF provides its own processing and rendering order. This can cause unpredictable behavior when web applications are executed. Facelets resolves this mismatch. Facelets also enables code reuse through templating and can significantly reduce the time to develop and deploy UIs.
      • Templating
      • Composite Components
      • Support for Ajax in JSF 2.0 :-  tag can invoke functions in the JavaScript API.
      • Programatically servlet & filter can be added at runtime.
      • JSF2.0 :- All resources like css, js, images, properties file will go under resources folder.
    • EJB 3.1 :-
    • No-interface view. Allows you to specify an enterprise bean using only a bean class without having to write a separate business interface. Local interface is optional.
    • Singletons. Lets you easily share state between multiple instances of an enterprise bean component or between multiple enterprise bean components in an application.
    • Asynchronous session bean invocation. Enables you to invoke session bean methods asynchronously by specifying an annotation @Asynchronous@Startup annotation guarantees that @PostConstruct method will be called on application initialization.
    • Simplified Packaging. Removes the restriction that enterprise bean classes must be packaged in an ejb-jar file. You can now place EJB classes directly in a WAR file.
    • EJB Lite. Is a subset of EJB 3.1 for inclusion in a variety of Java EE profiles.
    • Timer :- Programmatic & calendar based scheduling. Cron like syntax.
    • JPA Enhancements:- 
      • In JPA 2.0, you can map collections of basic data types, such as Strings or Integers, as well as collections of embeddable objects.
      • In query, case statement, nullif, coalesce are supported.
      • Criteria API supports builder pattern to generate queries.
    • Misc Features :-
      • Portable JNDI Name
      1. Bean has a @LocalBean annotation -> bean has a no-interface view
      2. Bean has a @Local annotation -> bean has a local view
      3. Bean has a @Remote annotation -> bean has a remote view
The following table depicts what type of managed classes can inject what objects.
ResourcesStatelessStatefulMDBInterceptors
JDBC DataSourceYesYesYesYes
JMS Destinations, Connection FactoriesYesYesYesYes
Mail ResourcesYesYesYesYes
UserTransactionYesYesYesYes
Environment EntriesYesYesYesYes
EJBContextYesYesYesNo
Timer ServiceYesNoYesNo
Web Service referenceYesYesYesYes
EntityManager, EntityManagerFactoryYesYesYesYes
Java EE 5 introduced several metadata annotations as part of JSR 250. Although primarily geared toward EJB, these annotations also apply to Java EE components such as Servlets, JSF managed beans, and application clients.
The following annotations can be used in a field or a setter method for dependency injection. However, these annotations may also be applied at the class level for defining dependencies and then used with JNDI look up.
AnnotationsUsageComponents that can use
javax.annotation.ResourceDependency injection of resources such as DataSource, and JMS objectsEJB, Web, Application Client
javax.ejb.EJBDependency injection of Session beansEJB, Web, Application Client
javax.xml.ws.WebServiceRefDependency injection of Web servicesEJB, Web, Application Client
javax.persistence.PersistenceContextDependency injection of container-managed EntityManagerEJB, Web
javax.persistence.PersistenceUnitDependency injection of EntityManagerFactoryEJB, Web

JEE 7 New Features

  • CDI 1.1 (JSR 346) :- Can specify package as @Vetoed & classes are retrieved using auto discovery.
  • Bean Validation 1.1 (JSR 349) :- Pre/Post conditions on constructor, methods.
  • Interceptors 1.2 (JSR 318) :- Interceptor associated with constructor. @AroundConstruct
    • @Priority - priorirty can be set for different interceptors
  • Concurrency utilities 1.0 (JSR 236) :- Before JEE7, creating threads were discouraged in EE container. Thread pool of EJBs were managed by container.
    •  User threads in Java EE applications
    •  The ability to support simple and advance concurrency design patterns
    •  And to extend Concurrency Utilities API from Java SE (JSR 166y)
    • New classes ManagedExecutor, ManagedScheduledExecutor, ManagedThreadFactory, DynamicProxy
    • reates dynamic proxy objects, and adds contextual information available for applications running in Java EE environment
    • It supports Classloading, JNDI, Security, 
  • JPA 2.1 (JSR 338) :-
    • Schema generation
    • @Index - define index in JPA mapping. In schema generation index will be created.
    • Calling stored procedure in JPA
  • JTA 1.2 (JSR 907) :-
    • @Transactional - Transaction management on Managed Beans as CDI interceptor binding
  • EJB 3.2 (JSR 345) :- 
    • Disable passivation of stateful ejb
    • Async + non persistent timer
  • JMS 2.0 (JSR 343)
    • Simplified API to consume & produce messages.
    • Autoclosable implemented.
    • Annotation to create JMS factory connection definition, JMS destination definition.

  • Servlet 3.1 (JSR 340)
    • Servlet non blocking I/O - Only for asynchronous servlet. New interface ReadListener, Writelistener.
    • New methods like setReadListener, isReady, isfinished in ServletInputStream interface,
    • New methods like setWriteListener, canWrite in ServletOutputStream interface.
    • Improved security. Now can deny http type request by configuring in web.xml file.
  • Web Socket 1.0 (JSR 356)
    • Annotated server endpoint - enables full duplex bi-directional communication over single TCP connection.
    • LifeCycle callback methods - onOpen, ocClose, on Error
    • Annotated client endpoint
    • Websocket encoder & decoder
  • Expression Language 3.0 (JSR 341)
    • ELProcessor - Evaluate EL expression, GET/SET bean properties, 
  • JSF 2.2 (JSR 344)
    • FlowFaces, FileUpload component, 
  • JAX-RS 2.0 (JSR 339)
    • New API to consume services
    • Async client - Async invocation, Async server -  Async processing
    • Message Filter - Used to process Incoming/Outgoing request response headers
    • Entity interceptors- Marshalling/Un-Marshalling of HTTP message bodies.
  • JSON-P 1.0 (JSR 353)
    • JSON builder
    • JSON parser
  • Batch 1.0 (JSR 352)
    • Chunk style processing, BatchLet style processing, Step processing, batch partition
    • Creating batch workflows
  • JavaMail 1.5 (JSR 919)
  • JCA 1.7 (JSR 322)
  • Java Connector Architecture
  • Default Resources
    • Default JMSConnectionFactory
    • Default concurrency objects - DefaultMangedExecutorService, DefaultMangedScheduledExecutorService,  DefaultMangedThreadFactory, DefaultContextService