Tuesday, December 8, 2015

ANDROID layout with fix header footer and center area

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
       android:layout_width="match_parent"
   android:layout_height="match_parent"
   xmlns:ads="http://schemas.android.com/apk/res-auto">
   <RelativeLayout
           android:id="@+id/rl_fixHeader"
   android:layout_width="match_parent"
   android:layout_height="30dp"
   android:layout_alignParentTop="true"
   android:background="#123456"
   android:gravity="center"      
                    android:layout_gravity="center">
   <TextView
       android:id="@+id/fix_header_text"
       android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
       android:text="@string/fix_header_msg"        
       android:textSize="25sp"/>
   </RelativeLayout>
   <RelativeLayout
           android:id="@+id/rl_fix_footer"
   android:layout_width="match_parent"
   android:layout_height="30dp"
   android:layout_alignParentBottom="true"
   android:background="#654321"
   android:gravity="center"      
                    android:layout_gravity="center">
   <TextView
       android:id="@+id/fix_footer_text"
       android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
       android:text="@string/footer_msg"
       android:textColor="#FFFFFF"
       android:gravity="center"
       android:textSize="25sp"/>
   </RelativeLayout>
   <ScrollView
   android:id="@+id/sv_scroll_view"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:layout_above="@+id/rl_fix_footer"
   android:layout_below="@+id/rl_fixHeader"
   android:fillViewport="true">  
<LinearLayout
   android:id="@+id/ll_myScrollLayout"
   android:orientation="vertical"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:background="#FFFFFF"
   android:fillViewport="true">
   <TextView
       android:id="@+id/tvBodytext"
       android:layout_width="wrap_content"
               android:layout_height="wrap_content"
       android:text="@string/body_msg"      
       android:gravity="center"
       android:textSize="25sp"/>
</LinearLayout>
   </ScrollView>
</RelativeLayout>  

Monday, December 7, 2015

What is Wildcard Capture , Get and Put Principle and wildcard restrictions?

What is Wildcard Capture ?
When a generic method is called then the type parameter is choosen to replace the unknow type represented by the wildcard.
this is called wildcapture. in short when any type replace the wildcard in the method or any collection then it is called wildcard capture.

What is Get and Put Principle ?
In generics use extends with wildcard ( ? extends AnyType) when you just want to GET values from the collection and
use super with wildcard ( ? super AnyType) whenever you want to put values in to collection.

What are the restrictions on wildcard ??

1) wildcards cannot be used with the instance creation(new)
List<?>  dataList = new ArrayList<?>(); // INVALID , it will show compile time error
Map<String, ? extends Number> dataMap = new HashMap<String, ? extends Number>(); // this will show compile time error

the reason behind this restriction is the GET and PUT principle because when you want to do both then it requires a precise type.
so it requires precise type at the instance creation.

But yes this is allowed
List<List<?>> lists = new ArrayList<List<?>>(); 
because here each individual list will have specific type related data.
here the wildcard type prohibits us from extracting elements from the inner lists as any type
other than Object.

2) Wildcard cannot be used in the explicit type parameter in generic method call
when a generic method includes a explicit type parameter then that method call cannot contain a wildcard as a type parameteer.
example
public static <T> List<T> dataList() { return new ArrayList<T>(); }

above method cannot be called as List<?> list = Lists.<?>factory();  it will give compile time error.
but it can be called as List<List<?>> = Lists.<List<?>>factory(); as explained above witt the nested list example.

and yes whatever restrictions are applied with the instance creations all that are applied with the supertype.
any superclass or superinterface has the type parameter then that cannot be wild card

class AnyList extends ArrayList<?> { } //  this will give compile-time error

class MyList implements List<?> { } // this will give  compile-time error

What is array subtyping is covariant means ?

It means array DOVE[] is considered to be subtype of BIRD[] if DOVE is a subclass of BIRD.
example
Integer[] ints = new Integer[]{9,99};
Number[] nums =  ints;
nums[1] = 1.9; // here it will throw array store exception
According to the substitution principle the assignment on the second line is legal
but the exception will be throws at the run time on the third line.
Because whenever an array is created then it tagged with its reified type. here it is integer.
eventhough it is assigned to the Number (super type)  type here internally it points to it
Integer type so it throws exception at run time when it detects a float value assigned.

While in contrats for generics the subtype relation is invariant, means
List<DOVE> is not considered to be subtype of List<BIRD>.

example
List<Integer> intList =  Arrays.asList(1,2,3,4,5,6,7,8,9);
List<Number>  numList = intList; // here it will show compile time error


But here with wild card we can achieve the covariant
in that case here List<DOVE> is considered to be subtype of List<? extends BIRD>.

Sunday, December 6, 2015

How the JVM Locates, Loads, and Runs Libraries


Classes are the building blocks of Java’s type system, but
they also serve another fundamental purpose: a class
is a compilation unit, the smallest piece of code that can be
individually loaded and run a JVM process. The class-loading
mechanism was set from the beginning of Java time, back in
JDK 1.0, and it immensely affected Java’s popularity as a crossplatform
solution. Compiled Java code—in the form of class
files and packaged JAR files—can be loaded into a running
JVM process on any of many supported operating systems.
It’s this ability that has allowed developers to easily distribute
compiled binaries of libraries. Because it is so much easier to
distribute JAR files than source code or platform-dependent
binaries, this ability has made Java popular, particularly in
open source projects.
In this article, I explain the Java class-loading mechanism
in detail and how it works. I also explain how classes are
found in the classpath and how are they loaded into memory
and initialized for use.
The Mechanics of Loading Classes into the JVM
Imagine you have a simple Java program such as the one
below:
public class A {
public static void main(String[] args) {
         B b = new B();
           int i = b.inc(0);
            System.out.println(i);
 }
}

When you compile this piece of code and run it, the JVM
correctly determines the entry point into the program and
starts running the main method of class A. However, the JVM
doesn’t load all imported classes or even referred-to classes
eagerly—that is, right away. In particular, this means that
only when the JVM encounters the bytecode instructions for
the new B() statement will it try to locate and load class B.
Besides calling a constructor of a class, there are other ways
to initiate the process of loading a class, such as accessing
a static member of the class or accessing it through the
Reflection API.
In order to actually load a class, the JVM uses classloader
objects. Every already loaded class contains a reference
to its class loader, and that class loader is used to
load all the classes referenced from that class. In the preceding
example, this means that loading class B can be
approximately translated into the following Java statement:
A.class.getClassLoader().loadClass("B").
Here comes a paradox: every class loader is itself an object of the java.lang.Classloader type that developers
can use to locate and load the classes by name. If
you’re confused by this chicken-and-egg problem
and wonder how the first class loader that
loads all the JDK classes (for example, java.lang
.String) is created, you’re thinking along the right
lines. Indeed, the primordial class loader, called
the bootstrap class loader, comes from the core
of the JVM and is written in native platformdependent
code. It loads the classes necessary
for the JVM itself, such as those of the java.lang
package, classes for Java primitives, and so forth.
Application classes are loaded using the regular,
user-defined class loaders written in Java—so, if
needed, the developer can influence the processing
of these loaders.
The Class-Loader Hierarchy
The class loaders in the JVM are organized into
a tree hierarchy, in which every class loader
has a parent. Prior to trying to locate and load a
class, a good practice for a class loader is to check
whether the class’s parent in the hierarchy can
load—or already has loaded—the required class. This helps
avoid doing double work and loading classes repeatedly. As a
rule, the classes of the parent class loader are visible to the
children but are not visible otherwise. This structure, which
is based on delegation and visibility of the classes, allows for
separation of the responsibilities of the class loaders in the
hierarchy and makes the class loaders responsible for loading
classes from a specific location only.
Let’s look at this hierarchy of class loaders in a Java application
and explore what classes they typically load. At the
root of the hierarchy, Java is the bootstrap class loader. It
loads the system classes required to run the JVM itself. You
can expect all the classes that were provided with the JDK
distribution to be loaded by this class loader.
(A developer can expand the set of classes that
the bootstrap class loader will be able to load by
using the -Xbootclasspath JVM option.)
Note that even though the library might be
put on the boot classpath, it won’t be automatically
loaded and initialized. Classes are loaded
into the JVM only on demand, so even though
classes might be available for the bootstrap class
loader, the application needs to access them to
trigger their actual loading. (A curious aspect of
this loading process is that you can override JDK
classes if your JAR file is prepended to the boot
classpath. While this is almost always a poor
idea, it does open a door to potentially morepowerful
tools.)
A sort of child of the bootstrap class loader is
the extension class loader, which loads the classes
from the extension directories (explained in a
moment). These classes may be used to specify
machine-specific configuration such as locales,
security providers, and such. The locations of
the extension directories are specified via the
java.ext.dirs system property, which on my machine is
set to the following:
/Users/shelajev/Library/Java/Extensions:/Library/
Java/JavaVirtualMachines/jdk1.8.0_40.jdk/Contents/
Home/jre/lib/ext:/Library/Java/Extensions:/Network/
Library/Java/Extensions:/System/Library/Java/
Extensions:/usr/lib/java
By changing the value of this property, you can change
which additional libraries are loaded into the JVM process.
Next comes the system class loader, which loads the
application classes and the classes available on the class-
path. Users can specify the classpath using the
-cp property.
Both the extension class loader and the system
class loader are of the URLClassloader type and
behave in the same way: delegating to the parent
first, and only then finding and resolving the
required classes themselves, if need dictates.
The class-loader hierarchy of web applications
is a bit more complicated. Because multiple
applications can be deployed simultaneously to an application
server, they need to be able to distinguish their classes
from each other. So, every web application uses its own class
loader, which is responsible for loading its libraries. Such
isolation ensures that different web applications deployed to
a single server can have different versions of the same library
without conflicts. So the application server automatically
provides every web application with its own class loader,
which is responsible for loading the application’s libraries.
This arrangement works because the web application class
loader will try to locate the classes packaged in the application’s
WAR file first, rather than first delegating the search to
the parent class loader.
Finding the Right Class
In general, if multiple classes with the same fully qualified
name are available to the JVM, the conflict resolution strategy
is simple and straightforward: the first appropriate class
wins. The URLClassloader, which most of the class loaders
extend from, will traverse the directories in the order they
are given on the classpath and load the first class it finds
that has requested the class name.
The same goes for JAR files that share the same name. The
JAR files will be scanned in the order in which they appear in
the classpath, not according to their names. If the first JAR
file contains an entry for the required class, the class will be
loaded. If not, the classpath scan will continue and reach the
second JAR file. Naturally, if the class isn’t
found anywhere on the classpath, the
ClassNotFound exception will be thrown.
Usually, relying on the order of directories
in the classpath is a fragile practice, so
instead the developer can add the classes to
-Xbootclasspath to ensure that they will be
loaded first. There’s nothing in particular wrong
with this approach, but maintaining a project
that relies on a polluted boot classpath requires work.
Intuition about where the classes are loaded from will be
broken, and everyone will be confused. A better practice is
to resolve the confusion at its root and figure out why there
are multiple classes with the same name on the classpath.
Maybe upgrading some dependency version, cleaning the
caches, or running a clean build will be enough to get rid of
the duplicates.
Resolution, Linking, and Verification
After a class is located and its initial in-memory representation
created in the JVM process, it is verified, prepared,
resolved, and initialized.
■■ Verification makes sure that the class is not corrupted and
is structurally correct: its runtime constant pool is valid,
the types of variables are correct, and the variables are
initialized prior to being accessed. Verification can be
turned off by supplying the -noverify option. If the JVM
process does not run potentially malicious code, strict
verification might not be required. Turning off the verification
can speed up the startup of the JVM. Another
benefit is that some classes, especially those generated
on the fly by various tools, can be valid and safe for the
JVM but unable to pass the strict verification process. In
order to use such tools, the developer should disable this
verification, which is often acceptable to do in a development
environment.
■■ Preparation of a class involves initializing its static fields to
the default values for their respective types. (After preparation,
fields of type int contain 0, references are null, and
so forth.)
■■ Resolution of a class means checking that the symbolic
references in the runtime constant pool actually point
to valid classes of the required types. The resolution of a
symbolic reference triggers loading of the referenced
class. According to the JVM specification, this resolution
process can be performed lazily, so it is deferred until the
class is used.
■■ Initialization expects a prepared and verified class. It runs
the class’s initializer. During initialization, the static fields
are initialized to whatever values are specified in the code.
The static initializer method that combines the code from
all the static initialization blocks is also run. The initialization
process should be run only once for every loaded class,
so it is synchronized, especially because the initialization
of the class can trigger the initialization of other classes
and should be performed with care to avoid deadlocks.
More detail on how the JVM performs the loading, linking,
and initializing of classes is explained in Chapter 5 of the Java
Virtual Machine Specification.
Other Considerations About Class Loaders
The class-loading model is the central piece of the dynamic
operations of the Java platform. Not only does it allow for
dynamic location and linking of classes at runtime, but
it also provides an interface for various tools to hook into
the application.
In addition, many security features rely on the class-loader
hierarchy for permission checks. For example, the famous
method sun.misc.Unsafe.getUnsafe() successfully
returns an instance of the Unsafe class if it is called from a
class that was loaded by the bootstrap class loader. Because
only system classes are returned by this loader, every library
that uses the Unsafe API must rely on the Reflection API to
read the reference from a private field.
Conclusion
When you’re developing a library or a framework, as a rule,
you don’t have to worry about any issues with class loading.
It is a dynamic process that happens at runtime, so you
rarely need to influence it. Also, modifying the class-loading
scheme rarely benefits a typical Java library.
However, if you create a system of modules or plugins that
are intended to be isolated from each other, enhancing the
class-loading scheme might be a good idea. Just remember
that custom class loaders, being a fundamental force influencing
all the classes, can introduce hard-to-spot bugs into
literally any part of your application. So take extra care when
designing your own class-loading functionality.
In this article, we looked at how the JVM loads classes into
the runtime, at the hierarchical model of class loaders Java
uses, and the hierarchy model of a typical Java application.
All in all, even if you don’t fight class-loading issues or
create plugin architectures every day, understanding class
loading helps you to understand what is happening in your
application. It also provides insight into how several Java
tools work. And it really demonstrates the benefits of keeping
your classpath clean and up to date. </article>

Source : JAVA MAGAZINE 20151112

Monday, November 23, 2015

Sunday, November 22, 2015

DATATABLE : how to remove pagination if no record found from the database

Add following line of code into your datatable definition 

"fnDrawCallback":function(oSettings){
var totalFoundRecords = oSettings._iRecordsDisplay;
if((totalFoundRecords!=null && totalFoundRecords>0) == false){
$(oSettings.nTableWrapper).find('.dataTables_paginate').hide();
}
},

Thursday, October 22, 2015

boost your smartphone or tablet's battery life

Boost your smartphone or tablet's battery life

Protect your Phone's Battery From Overcharging.

Keep your phone battery Healthy.

How to take care for my Phone's Battery? 

Battery Alarm, Battery alarm at any Level., Battery Doctor, Battery full alarm, Battery Health protector, Battery Information, Battery protector,
Battery Peotector

Battery Alarm, Battery alarm at any Level., Battery Doctor, Battery full alarm, Battery Health protector, Battery Information, Battery protector,
Battery Alarm, Battery alarm at any Level., Battery Doctor, Battery full alarm, Battery Health protector, Battery Information, Battery protector, 



Why Battery Full Alarm (Battery Protector & Battery Alarm) is a MUST-HAVE app?
★ Protect Over Charging
Instantly play the alarm tone when charging is Full. You can set Alarm at your choice battery level;
Shows Graphical Battery Level with Percentage.


★ Battery Alarms
App has features to play alarm in Silent, Vibrate mode.
Also it has a Speech Alarm unique feature.


★ Battery Complete Information
It provides all Information related to Battery Health and Battery Temperature


★ Battery Plug (IN/OUT) Sound and Plug Types
There are sounds for Plug in and Plug Out. So you will come to know about whether your phone is actually charging or not.
Graphical Images shows your the Plug Types.


★ App Automatically Start ON/OFF
Configurable auto start feature.


★ Battery Fast Charging
Provides settings for Fast Charging.


★ Battery Saver Modes
There are difference modes available which will help you to save your battery power and will keep the battery health better.


★ Battery Percentage in Notification Area
Battery Full Alarm provides the Current battery percentage into notification area. Also on the lock screen it shows the Battery Information.


Display charge status in real time, accurately shows the battery percentage.

Battery Full Alarm & Battery Monitor or Battery Alarm is the simplest and easiest way to keep your Android phone Battery Health Better and Protect It from Overcharging.

Wednesday, October 21, 2015

STRUTS 2 ATCHITECTURE


ECLIPSE SHORTCUTS

Eclipse Shortcuts

CTRL SHIFT R Open a resource
CTRL E Open a file (editor) from within the list of all open files
CTRL PAGE UP or PAGE DOWN Navigate to previous or next file from within the list of all open files
ALT <- or ALT -> Go to previous or next edit positions from editor history list
Java Editing
CTRL SPACE Type assist
CTRL SHIFT F Format code
CTRL O List all methods of the class
CTRL SHIFT O Organize imports
CTRL SHIFT U Find reference in file
CTRL / Comment a line
F3 Go to the declaration of the variable
F4 Show type hierarchy of on a class
CTRL T Show inheritance tree of current token
SHIFT F2 Show Javadoc for current element
ALT SHIFT Z Enclose block in try-catch
General Editing
F12 Focus on current editor
CTRL L Go to line number
CTRL D Delete a line
CTRL <- or -> Move one element left or right
CTRL M Maximize editor
CTRL SHIFT P Go to the matching parenthesis
Debug, Run
CTRL . or , Navigate to next or previous error
F5 Step into
F6 Step over
F8 Resume
CTRL Q Inspect
CTRL F11 Run last run program
CTRL 1 Quick fix code
Search
CTRL SHIFT G Search for current cursor positioned word reference in workspace
CTRL H Java search in workspace

Hibernate annotations Introduction

Friends Happy point for you:- Annotations are replacement for “xyz.hbm.xml” files

Let us learn few points regarding annotations in hibernate

Annotations are introduced in java along with JDK 1.5, annotations are used to
provide META data to the classes, variables, and methods of java

Annotations are given by SUN as replacement to the use of xml files in java

In hibernate annotations are given to replace hibernate mapping [ xml ] files

While working with annotations in hibernate, we do not require any mapping files, but
hibernate xml configuration file is must required

Hibernate borrowed annotations from java persistence API but hibernate it self doesn’t
contain its own annotations

Every annotation is internally an Interface, and the keywords starts with @ symbol

Hibernate Transient + Persistent + Detached Objects

Transient Object :
One newly created object of POJO class without having any relation with the database, means
never persistent, not associated with any Session object.

Persistent Object:
An object of a POJO class having relation with the database, associated with a unique Session
object

Detached Object:
An object of a POJO class Previously having relation with the database [persistent ], now not
associated with any Session object

Hibernate Object's Transient & Persistent states


Whenever an object of a POJO class is created then it will be in the Transient state
An object in a Transient state doesn’t represent any row of the database,

Means it is not associated with any Session object, No relation with the database, it is just a
normal object

 If we modify the data of a POJO class object, when it is in transient state then it doesn’t effect
on the database table

When the object is in persistent state, then it represent one row of the database,

In persistent state object is having associated with the unique Session

If we want to move an object from persistent to detached state, then we need to do either
close that session or need to clear the cache of the session

If we want to move an object from persistent state into transient state then we need to delete
that object permanently from the database

Tuesday, October 20, 2015

Criteria Query + Conditions To Criteria + criterion

Criteria Query is only for selecting the data from the database

Using Criteria query we can select complete objects only not partial objects

In fact by combining criteria and projections concept we can select partial objects too

We cannot perform non-select operations using this criteria.

Criteria is suitable for executing dynamic queries too,

Friend lets take a flight of how to use this criteria queries in the hibernate
Syntax:
Criteria criteria = session.createCriteria(“Class Name”.class);
How to use ?
Criteria criteria = session.createCriteria(Entity.class);
List list = criteria.list()
Iterator iterator = list.iterator();
while(iterator.hasNext())
{
Object obj = iterator.next();
Entity entity = (Entity)obj;
/*------ Further code ----- */
}

Adding Conditions To Criteria
If we want to put conditions to load data from database, using criteria then we need to create
one Criterion Interface object and we need to add this object to Criteria Class object

Criterion is an interface given in “org.hibernate.criterion” package

In order to get Criterion object, we need to use Restrictions class

Restrictions is the factory for producing Criterion objects, but friends there is no explicit
relation between Criterion interface and Restrictions class, it means Restrictions class is not
implemented from Criterion Interface

Restrictions class, we have all static methods and each method of this class returns
Criterion object

Restrictions class is also given in “org.hibernate.criterion” package

How to use criterion ?
Criteria criteria = session.createCriteria(Entity.class);
Criterion criterion =Restrictions.gt("id", new Integer(11));
// .gt() : means greater than
// id is a variable of our POJO class Entity.java
criteria.add(criterion); // adding criterion object to criteria class object
List l = criteria.list(); // executing criteria query
In our above example we are fetching the data by comparing id greater than (>) 11
If we want to put more conditions on the data (multiple conditions) then we can use
.and() method ,. or() method , .eq() method using the Restrictions class
How to use Restrictions?
Criteria criteria = session.createCriteria(Entity.class);
criteria.add(Restrictions.and(Restrictions.like("name","%M%"),Restrictions.eq("category",ne
w String(“bird”))));
List list = criteria.list();
Iterator it = list.iterator();
Buddy, like this we can add required number of conditions

Conditions to Criteria
If we want to add some sorting order for the objects, before the objects are going to store
in list object then we need to add an Order class object to the Criteria class object by
calling addOrder() method

Order is a class given in “org.hibernate.Criterion” package

In Order class, we have 2 static methods, asc()[ascending order] and dsc()[descending
order] for getting an objects in required order

Internal concept is, hibernate will select the records (rows) from ENTITIES_DATA table
and stores them into a ResultSet and then converts each row data of resultset into a POJO
class object basing on our field type, then add all these objects into a list according to the
order we have given

Monday, October 19, 2015

JAVA ROBOT CODE TO DO SOME PREDEFINE ACTIVITY

THIS CODE WILL TAKE UPDATE IN YOUR PARTICULAR FOLDER FOR THE CONFIGURED WORKSPACE.

IT WILL OPEN YOUR PREDEFINE SOFTWARE (i.e. Eclipse, ThunderBird etc)

IT WILL OPEN YOUR SOME ROUTINE SITES (i.e Gmail, Hotmail etc etc)

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;

/*Author : RAJ*/

class MyRobot {

Robot robot = new Robot();

public static void main(String[] args) {

try {

Desktop desktop = Desktop.getDesktop();
File dirToOpen = new File("D:\\Data\\My_Branch");
desktop.open(dirToOpen);

MyRobot r = new MyRobot();

// Creates the delay of 5 sec so that you can open notepad before
// Robot start writting
/*
* robot.delay(5000); robot.keyPress(KeyEvent.VK_H);
* robot.keyPress(KeyEvent.VK_I); robot.keyPress(KeyEvent.VK_SPACE);
* robot.keyPress(KeyEvent.VK_B); robot.keyPress(KeyEvent.VK_U);
* robot.keyPress(KeyEvent.VK_D); robot.keyPress(KeyEvent.VK_Y);
*/

} catch (Exception e) {
e.printStackTrace();
}
}

public MyRobot() throws AWTException {
startTheBattle();
}

private void leftClick() {
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.delay(200);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
robot.delay(200);
}

private void startTheBattle(){
rightClick();
leftClick();
robot.delay(1000);

openChrome();
robot.delay(1000);

openEclipse();
robot.delay(1000);

openThunder();
exitNow();
}

private void exitNow() {
System.out.println("Exiting Now.. Good Bye..");
System.exit(0);
}

private void rightClick() {
robot.mouseMove(640, 630);
robot.delay(500);

robot.mousePress(InputEvent.BUTTON3_MASK);
robot.delay(200);
robot.mouseRelease(InputEvent.BUTTON3_MASK);
robot.delay(200);

robot.mouseMove(660, 500);
robot.delay(500);
}

private void openChrome(){
try{
java.awt.Desktop.getDesktop().browse(java.net.URI.create("http://gmail.com"));
java.awt.Desktop.getDesktop().browse(java.net.URI.create("http://yahoomail.com"));
java.awt.Desktop.getDesktop().browse(java.net.URI.create("http://hotmail.com"));
java.awt.Desktop.getDesktop().browse(java.net.URI.create("http://google.com"));
}catch(Exception ex){}
}


private void openEclipse(){
try{
String path = "D:\\Data\\Software\\eclipse-jee-indigo-SR2-win32-x86_64 - Branch-660\\eclipse\\eclipse.exe";
File file = new File(path);
if (! file.exists()) {
throw new IllegalArgumentException("The file " + path + " does not exist");
}
Process p = Runtime.getRuntime().exec(file.getAbsolutePath());
}catch(Exception ex){}
}

private void openThunder(){
try{
String path = "D:\\Data\\Software\\ThunderbirdPortable\\ThunderbirdPortable.exe";
File file = new File(path);
if (! file.exists()) {
throw new IllegalArgumentException("The file " + path + " does not exist");
}
Process p = Runtime.getRuntime().exec(file.getAbsolutePath());
}catch(Exception ex){}
}

private void type(int i) {
robot.delay(40);
robot.keyPress(i);
robot.keyRelease(i);
}

private void type(String s) {
byte[] bytes = s.getBytes();
for (byte b : bytes) {
int code = b;
// keycode only handles [A-Z] (which is ASCII decimal [65-90])
if (code > 96 && code < 123)
code = code - 32;
robot.delay(40);
robot.keyPress(code);
robot.keyRelease(code);
}
}
}

what is difference between < ? super T > and < ? extends T >

what is difference between < ? super T> and <? extends T> ?

<? super T> :
Here the ? is a wildcard which represents the parameter type. (i.e List<Integer> here Integer is a parameter type), T is a generic Type and super is a keyword which represents the put principle.
If it is List<? super T> then one can put all the types objects into this list which comes int the range of ? and T.
because of the usage of super one cannot get the values from this list.

<? extends T>:
Here the ? is a wildcard which represents the parameter type. (i.e List<Character> here Character is a parameter type).
T is a generic type (i.e public static <T> void getList(T[] arr);  here T is a generic type)
and extends is keyword. and the pattern <? extends T> represets the get principle of generic.
means if it is List<? extends T> then one can get the values from this list. and the value object will be ranging between the ?(TYPE) and T(type).

 

how the Servlet Container Works

Creating a request object and populate it with information that may be used by the invoked servlet, such as parameters, headers, cookies, query string, URI, etc. A request object is an instance of the javax.servlet.ServletRequest interface or the javax.servlet.http.ServletRequest interface.

Creating a response object that the invoked servlet uses to send the response to the web client. A response object is an instance of the javax.servlet.ServletResponse interface or the javax.servlet.http.ServletResponse interface.

Invoking the service method of the servlet, passing the request and response objects. Here the servlet reads the values from the request object and writes to the response object.

JAVA COLLECTIONS UTILITY


import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * A set of commonly used utilities for {@link Collection}s. Named as Collectionz to avoid
 * conflict with {@link java.util.Collections}
 *
 *
 */
public class Collectionz {

/**
* Checks whether the collection is null or empty.
*
* @param collection collection to be checked
* @return true if the collection is null or empty, false otherwise
*/
public static boolean isNullOrEmpty(Collection<?> collection) {
return collection == null ? true : collection.isEmpty();
}

/**
* Before JDK 7, constructing new generic collections requires unpleasant code duplication:
* {@code List<TypeThatsTooLongForItsOwnGood> list = new ArrayList<TypeThatsTooLongForItsOwnGood>();}
*
* <p>But using these static factory methods, the type on the right side is automatically inferred:
* {@code List<TypeThatsTooLongForItsOwnGood> list = Collectionz.newArrayList();}
* @return a new empty {@code ArrayList}
*/
public static <T> ArrayList<T> newArrayList() {
return new ArrayList<T>();
}

/**
* Before JDK 7, constructing new generic collections requires unpleasant code duplication:
* {@code List<TypeThatsTooLongForItsOwnGood> list = new LinkedList<TypeThatsTooLongForItsOwnGood>();}
*
* <p>But using these static factory methods, the type on the right side is automatically inferred:
* {@code List<TypeThatsTooLongForItsOwnGood> list = Collectionz.newLinkedList();}
* @return a new empty {@code LinkedList}
*/
public static <T> LinkedList<T> newLinkedList() {
return new LinkedList<T>();
}

/**
* Before JDK 7, constructing new generic collections requires unpleasant code duplication:
* {@code Set<TypeThatsTooLongForItsOwnGood> set = new HashSet<TypeThatsTooLongForItsOwnGood>();}
*
* <p>But using these static factory methods, the type on the right side is automatically inferred:
* {@code Set<TypeThatsTooLongForItsOwnGood> set = Collectionz.newHashSet();}
* @return a new empty {@code HashSet}
*/
public static <T> HashSet<T> newHashSet() {
return new HashSet<T>();
}

/**
* Before JDK 7, constructing new generic collections requires unpleasant code duplication:
* {@code Set<TypeThatsTooLongForItsOwnGood> set = new LinkedHashSet<TypeThatsTooLongForItsOwnGood>();}
*
* <p>But using these static factory methods, the type on the right side is automatically inferred:
* {@code Set<TypeThatsTooLongForItsOwnGood> set = Collectionz.newLinkedHashSet();}
* @return a new empty {@code LinkedHashSet}
*/
public static <T> LinkedHashSet<T> newLinkedHashSet() {
return new LinkedHashSet<T>();
}

/**
* Transforms the collection to map using the type of collection {@code V} as value type in map
* and uses the {@code keyFormationFunction} to form keys of type {@code K} for each entry in collection.
*
* @param <K> the type of key in map
* @param <V> the type of value in map, same as type of value in collection
* @param collection a non-null collection which will be transformed to map
* @param valueToKeyFunction a non-null function that will form key based on value
* @return map created using all elements in collection
*/
public static <K,V> Map<K, V> asHashMap(Collection<V> collection, Function<V, K> valueToKeyFunction) {
checkNotNull(collection, "collection is null");
checkNotNull(valueToKeyFunction, "valueToKeyFunction is null");

Map<K,V> map = new HashMap<K, V>();
for(V element : collection){
map.put(valueToKeyFunction.apply(element),element);
}
return map;
}

/**
* From the given collections returns the first collection that is non-null and non-empty
* wrapped in optional.
* If no suitable collection is found then returns an {@link Optional#absent()}. Before
* getting the collection check to see if it is present using {@link Optional#isPresent()}.
*
* @param <T> any sub-type of collection
* @param collections a non-null collection array
* @return optional instance containing collection if a non-null and non-empty collection
* is found, {@code Optional.absent()} otherwise
*/
public static <T extends Collection<?>> Optional<T> firstNonEmpty(T... collections) {
for(T collection : collections) {
if(Collectionz.isNullOrEmpty(collection) == false) {
return Optional.of(collection);
}
}
return Optional.absent();
}

/**
* Returns a list as a resultant of applying function {@code mapper} to each element
* of the collection {@code coll}. Returns an empty mutable list if {@code coll} is
* {@code null} or if the collection is empty.
*
* @param <X> type of elements in source collection
* @param <Y> type of elements in mapped collection
* @param coll source collection on which mapping will be applied
* @param mapper a non-null function
* @return resultant list obtained by applying function {@code mapper} on collection,
* empty mutable list if {@code coll} is null or empty
* @throws NullPointerException is mapper function is null
*/
public static <X, Y> List<Y> map(Collection<X> coll, Function<X, Y> mapper) {
checkNotNull(mapper, "mapper function is null");

if (isNullOrEmpty(coll)) {
return new ArrayList<Y>(0);
}

List<Y> result = new ArrayList<Y>();
for (X element : coll) {
result.add(mapper.apply(element));
}
return result;
}

/**
* Filters the elements from the collection that don't satisfy the predicate passed.
* <p>This method eagerly evaluates the filter and removes the elements from the passed
* {@code unfiltered} collection. Uses {@link Iterator#remove()} method to remove elements
* that don't satisfy the filter, so remove method MUST be supported for this method
* to work.
*
* <p><b>NOTE:</b> This method eagerly evaluates the filter giving O(n) complexity.
*
* <p>Usage:
* <pre><code>
* Collection&lt;String&gt; unfiltered = ...
* Collectionz.filter(unfiltered, Predicates.nonNull());
* </code></pre>
*
* @param <T> type of elements in the collection
* @param unfiltered a non-null collection to be filtered
* @param predicate a non-null filter which will be applied to all elements in the collection
* @throws NullPointerException if any parameter passed is null
*/
public static <T> void filter(Collection<T> unfiltered,
Predicate<? super T> predicate) {
checkNotNull(unfiltered, "collection is null");
checkNotNull(predicate, "predicate is null");

Iterator<? extends T> iterator = unfiltered.iterator();
while (iterator.hasNext()) {
if (predicate.apply(iterator.next()) == false) {
iterator.remove();
}
}
}
}

JAVA FILES UTILITY


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Files {

/**
* Read full bytes of the given file.
*
* @param file a non-null file whose bytes will be read
* @return full bytes of the given file
* @throws FileNotFoundException if file does not exist
* @throws IOException if some issue occurs while reading from file
* @throws IllegalArgumentException if file is a directory
*/
public static byte[] readFully(File file) throws FileNotFoundException, IOException, IllegalArgumentException {
checkNotNull(file, "file is null");
checkArgument(file.isFile(), file.getPath() + " is not a file");

return ByteStreams.readFully(new FileInputStream(file));
}

/**
* Read full bytes of the file at given path.
*
* @param filePath non-null path of the file whose bytes will be read
* @return full bytes of file at given path
* @throws FileNotFoundException if file at given path does not exist
* @throws IOException if some issue occurs while reading from file
* @throws IllegalArgumentException if filePath points to a directory
*/
public static byte[] readFully(String filePath) throws FileNotFoundException, IOException, IllegalArgumentException {
checkNotNull(filePath, "filePath is null");

return readFully(new File(filePath));
}
}

JAVA MAPS UTILITY

public class Maps {

/**
* Checks whether the map is {@code null} or empty
* @param map a nullable map
* @return true if map is either {@code null} or empty, false otherwise
*/
public static boolean isNullOrEmpty(Map<?, ?> map) {
return map == null || map.isEmpty();
}

/**
* Before JDK 7, constructing new generic collections requires unpleasant code duplication:
* {@code Map<TypeThatsTooLongForItsOwnGood, AnotherTypeThatsTooLong> map =
* new HashMap<TypeThatsTooLongForItsOwnGood, AnotherTypeThatsTooLong>();}
*
* <p>But using these static factory methods, the type on the right side is automatically inferred:
* {@code Map<TypeThatsTooLongForItsOwnGood, AnotherTypeThatsTooLong> map = Maps.newHashMap();}
* @return a new empty {@code HashMap}
*/
public static <K, V> HashMap<K, V> newHashMap() {
return new HashMap<K, V>();
}

/**
* Before JDK 7, constructing new generic collections requires unpleasant code duplication:
* {@code Map<TypeThatsTooLongForItsOwnGood, AnotherTypeThatsTooLong> map =
* new LinkedHashMap<TypeThatsTooLongForItsOwnGood, AnotherTypeThatsTooLong>();}
*
* <p>But using these static factory methods, the type on the right side is automatically inferred:
* {@code Map<TypeThatsTooLongForItsOwnGood, AnotherTypeThatsTooLong> map = Maps.newLinkedHashMap();}
* @return a new empty {@code LinkedHashMap}
*/
public static <K, V> HashMap<K, V> newLinkedHashMap() {
return new LinkedHashMap<K, V>();
}
}

JAVA NUMBERS UTILITY


public class Numbers {

/**
* A predicate for positive integers. Evaluates to false if the Integer is null.
*/
public static final Predicate<Integer> POSITIVE_INT = new PositiveIntPredicate();
/**
* A predicate for positive long value. Evaluates to false if the Long is null or zero.
*/
public static final Predicate<Long> POSITIVE_LONG = new PositiveLongPredicate();

/**
* Returns a big-endian representation of {@code value} as an n byte array, where
* n is the {@code noOfBytes}.
*
* <p>Returns an empty array if {@code noOfBytes} is {@code 0}
*
* <p> Example: {@code Numbers.toByteArray(0x1213,3)} will return a byte array
* {@code {0x00, 0x12, 0x13}}.
*
* @param value any integer value
* @param noOfBytes non-negative number of bytes
* @return a big-endian representation of value as a byte array.
* @throws IllegalArgumentException if {@code noOfBytes} is negative
*/
public static byte[] toByteArray(int value, int noOfBytes) {
checkArgument(noOfBytes >= 0, "noOfBytes cannot be negative");

if (noOfBytes == 0) {
return new byte[] {};
}

byte[] intBytes = new byte[noOfBytes];
for (int i = noOfBytes-1; i >= 0; i--, value >>>= 8) {
intBytes[i] = (byte)value;
}
return intBytes;
}

/**
* Returns a big-endian representation of {@code value} as an n byte array, where
* n is the {@code noOfBytes}.
*
* <p>Returns an empty array if {@code noOfBytes} is {@code 0}
*
* <p> Example: {@code Numbers.toByteArray(0x12131415,4)} will return a byte array
* {@code {0x12, 0x13, 0x14, 0x15}}.
*
* @param value any long value
* @param noOfBytes non-negative number of bytes
* @return a big-endian representation of value as a byte array.
* @throws IllegalArgumentException if {@code noOfBytes} is negative
*/
public static byte[] toByteArray(long value, int noOfBytes) {
checkArgument(noOfBytes >= 0, "noOfBytes cannot be negative");

if (noOfBytes == 0) {
return new byte[] {};
}

byte[] longBytes = new byte[noOfBytes];
for (int i = noOfBytes-1; i >= 0; i--, value >>>= 8) {
longBytes[i] = (byte)value;
}
return longBytes;
}

/**
* Parses the string {@code value} using {@link Integer#parseInt(String)} and returns
* the parsed value if parsing was successful or returns {@code otherwise} instead.
*
* @param value string containing integer representation to be parsed
* @param otherwise value to be returned if parsing causes {@code NumberFormatException}
* @return parsed integer value on successful parsing or otherwise instead
*/
public static int parseInt(String value, int otherwise) {
return parseInt(value, Predicates.<Integer>alwaysTrue(), otherwise);
}

/**
* Parses the string {@code value} using {@link Integer#parseInt(String)} and returns
* the parsed value if parsing was successful or returns {@code otherwise} instead.
*
* @param value string containing integer representation to be parsed
* @param otherwise value to be returned if parsing causes {@code NumberFormatException}
* @return parsed integer value on successful parsing or otherwise instead
*/
public static Integer parseInt(String value, Integer otherwise) {
return parseInt(value, Predicates.<Integer>alwaysTrue(), otherwise);
}

/**
* Parses the string {@code value} using {@link Long#parseLong(String)} and returns
* the parsed value if parsing was successful or returns {@code otherwise} instead.
*
* @param value string containing long representation to be parsed
* @param otherwise value to be returned if parsing causes {@code NumberFormatException}
* @return parsed long value on successful parsing or otherwise instead
*/
public static long parseLong(String value, long otherwise) {
long result = otherwise;
try {
result = Long.parseLong(value);
} catch (NumberFormatException nfe) {
LogManager.getLogger().trace(nfe);
}
return result;
}

/**
* Parses the string {@code value} using {@link Integer#parseInt(String)} and returns
* the parsed value if parsing was successful and the parsed value satisfies the
* predicate else returns {@code otherwise}.
*
* <p>
* Usage: Parse a string which should be a positive integer
* <pre>
*  int parsedPositiveValue = Numbers.parseInt("100", Numbers.POSITIVE_INT, DEFAULT_VALUE);
* </pre>
* @param value string containing integer representation to be parsed
* @param predicate a non-null predicate that the parsed value must satisfy
* @param otherwise value to be returned if parsing causes {@code NumberFormatException}
* or the parsed value does not satisfy the predicate
* @return parsed integer value on successful parsing or otherwise instead
*/
public static int parseInt(String value, Predicate<Integer> predicate, int otherwise) {
int result = otherwise;
try {
result = Integer.parseInt(value);
result = predicate.apply(result) ? result : otherwise;
} catch (NumberFormatException nfe) {
LogManager.getLogger().trace(nfe);
}
return result;
}

/**
* Parses the string {@code value} using {@link Integer#parseInt(String)} and returns
* the parsed value if parsing was successful and the parsed value satisfies the
* predicate else returns {@code otherwise}.
*
* <p>
* Usage: Parse a string which should be a positive integer
* <pre>
*  Integer parsedPositiveValue = Numbers.parseInt("100", Numbers.POSITIVE_INT, DEFAULT_VALUE);
* </pre>
* @param value string containing integer representation to be parsed
* @param predicate a non-null predicate that the parsed value must satisfy
* @param otherwise value to be returned if parsing causes {@code NumberFormatException}
* or the parsed value does not satisfy the predicate
* @return parsed integer value on successful parsing or otherwise instead
*/
public static Integer parseInt(String value, Predicate<Integer> predicate, Integer valueOtherwise) {
Integer result = valueOtherwise;
try {
result = Integer.parseInt(value);
result = predicate.apply(result) ? result : valueOtherwise;
} catch (NumberFormatException nfe) {
LogManager.getLogger().trace(nfe);
}
return result;
}

private static class PositiveIntPredicate implements Predicate<Integer> {
@Override
public boolean apply(Integer input) {
return input != null ? input > 0 : false;
}
}

private static class PositiveLongPredicate implements Predicate<Long> {
@Override
public boolean apply(Long input) {
return input != null ? input.longValue() > 0 : false;
}
}
}

Scrum and Scrum master

Scrum  Scrum is a framework which helps a team to work together.  It is like a rugby team (the scrum name comes from rugby game). Scrum enco...