Dependency Injection with Java Spring IoC, A Complete Example


Here i am going to describe a simple example of Dependency Injection which uses Spring IoC framework.
You may refer to my earlier"Understanding Dependency Injection and Its Importance" for understanding the concepts.
This example uses Implementation of  Operation, Reader and Writer Interfaces.
We simply perform a one of the arithmentic Operation by taking values from Reader and write the values using Writer Class.

Reader Interface:
public interface Reader {
    Operands readValues(String promptMsg);
}

Its implementations can be:
ConsoleReader:
public class ConsoleReader implements Reader{
    Operands oprnds;
    Scanner sc;
    public ConsoleReader (){
        oprnds=new Operands();
        sc=new Scanner(System.in);
    }
    public Operands readValues(String promptMsg) {
        System.out.println(promptMsg);
        oprnds.setOp1(sc.nextLong());
        oprnds.setOp2(sc.nextLong());
        return oprnds;
    }
}


The Operation Interface
public interface Operation {
    Result operate(long op1,long op2);
    String getOperationName();
}


The Operation Interface can have implementations such as
Multiply
public class Multiply implements Operation {
    Result res;
    public Multiply(){
          res=new Result();
    }
    public Result operate(long op1, long op2) {
        res.setRes(op1*op2);
        return res;
    }
    public String getOperationName() {
        return "Multiply";
    }
}

Addition
public class Add implements Operation {
    Result res;
    public Add(){
        res=new Result();
    }
    public Result operate(long op1, long op2) {
        res.setRes(op1+op2);
        return res;
    }
    public String getOperationName() {
        return "Add";
    }
}


The  writer Interface
public interface Writer {
    void write(Result res);
}

Its ConsoleWriter Implementation
public class ConsoleWriter implements Writer{
 public void write(Result res){
    System.out.println("The result after operation : "+res.getRes());
  }
}

Its TXTFileWriter Implementation
public class TXTFileWriter implements Writer{
    File file;
    PrintWriter fwriter;
    public TXTFileWriter(){
        try {
           file = new File("output.txt");
           fwriter = new PrintWriter( new BufferedWriter( new FileWriter(file)));
       } catch (Exception ex) {
           System.err.println(ex);
        }
    }
    public void write(Result res)
  {
     fwriter.println(res.getRes());
     fwriter.close();
    }
}


The Model Classes
Operands
public class Operands {
    private long op1;
    private long op2;
//setters and getters
}

The Result Class
public class Result {
    private long res;
    //setters and getters
}


Now create a configuration file in class path i.e, src folder of project directory - confBean.xml.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="operation" class="com.gt.spring.operation.Add"/>
<bean id="reader" class="com.gt.spring.reader.ConsoleReader"/>
<bean id="writer" class="com.gt.spring.writer.ConsoleWriter"/>
<beans>

The dependency injection will help you to inject the implementations of an object at runtime.
In the Main Class: read the xml file and inject the dependent beans…
public class Main {
    public static void main(String[] args) {
    ApplicationContext ctx = 
new ClassPathXmlApplicationContext("confBean.xml");
        //get beans from ctx
        Reader rdr = (Reader) ctx.getBean("reader");
        Operation opr = (Operation)ctx.getBean("operation");
        Writer wrt = (Writer) ctx.getBean("writer");//
        //read operands
        Operands opnds = rdr.readValues("Enter the Values :");
        //do operation
        Result res =opr.operate(opnds.getOp1(), opnds.getOp2());
        //write result
        wrt.write(res);
    }
}


Dependency Injection in Java without Spring IoC Framework........ How it is possible... A Simple way

You can first read Understanding Dependency Injection and its Importance, before this post for clearing Funda of Dependency Injection.
How can we this do programmatically.
  • Create a interface Wheel.
    Interface Wheel(){
         rotate();
         applyBreak();
    }
  • Create implementations
    class ChineseRubberWheel implements Wheel{
         //override and define
    }
    class NepaleseRubberWheel implements Wheel{
         //override and define
    }
  • Create a txt file, where you write the valid name(say NepaleseRubberWheel ) of a Implementation of Wheel
  • Read the txt file
  • And finally, to Dynamically load the NepaleseRubberWheel as instance of Wheel;
    String wheeltoInject = ReadFromTXTFile();
    // Create Wheel object
    Wheel wheelToRun =(Wheel)     (Class.forName(wheelToInject).newInstance());
    // Execute methods of the wheel object.
    wheelToRun.rotate();
    wheelToRun.applyBreak();


This works for any implementation of Wheel. To change the Wheel on the Car just change name of Implementation on the txt file.

Understanding Dependency Injection and its Importance, A tutorial

Understanding Dependency Injection and its Importance

Any application is composed of many objects that collaborate with each other to perform some useful stuff. Traditionally each object is responsible for obtaining its own references to the dependent objects (dependencies) it collaborate with. This leads to highly coupled classes and hard-to-test code.

For example, consider a `Car` object.

A `Car` depends on wheels, engine, fuel, battery, etc. to run. Traditionally we define the brand of such dependent objects along with the definition of the `Car` object.

Without Dependency Injection (DI):

  class Car{  
    private Wheel wh = new NepaliRubberWheel();  
    private Battery bt = new ExcideBattery();  
    //The rest  
   }  

Here, the `Car` object *is responsible for creating the dependent objects.*

What if we want to change the type of its dependent object - say `Wheel` - after the initial `NepaliRubberWheel()` punctures?
We need to recreate the Car object with its new dependency say `ChineseRubberWheel()`, but only the `Car` manufacturer can do that.

 Then what does the `Dependency Injection` do for us...?


When using dependency injection, objects are given their dependencies *at run time rather than compile time (car manufacturing time)*.
So that we can now change the `Wheel` whenever we want. Here, the `dependency` (`wheel`) can be injected into `Car` at run time.

After using dependency injection:

Here, we are **injecting** the **dependencies** (Wheel and Battery) at runtime. Hence the term : *Dependency Injection.* We normally rely on DI frameworks such as Spring, Guice, Weld to create the dependencies and inject where needed.

   class Car{  
    private Wheel wh; // Inject an Instance of Wheel (dependency of car) at runtime  
    private Battery bt; // Inject an Instance of Battery (dependency of car) at runtime  
    Car(Wheel wh,Battery bt) {  
      this.wh = wh;  
      this.bt = bt;  
    }  
    //Or we can have setters  
    void setWheel(Wheel wh) {  
      this.wh = wh;  
    }  
   }  

The advantages/benefits of dependency injection are:

  • decoupling the creation of an object (in another word, separate usage from the creation of object)
  • ability to replace dependencies (eg: Wheel, Battery) without changing the class that uses it(Car)
  • promotes "Code to interface not to an implementation" principle
  • ability to create and use mock dependency during a test (if we want to use a Mock of Wheel during test instead of a real instance.. we can create Mock Wheel object and let DI framework inject to Car)

Understanding Importance of Interface, Inheritance...... OOP concepts in a different way !

Lets talk about some fundamentals of Object Oriented Design concepts in a different way...
1.IS A - Inheritance
A super class for Animal

class Animal {
int legs;
String name;
public Animal(int legs, String name) {
  this.legs = legs;
  this.name = name;
}
public void walk() {}
}

Creating Cow class, a type of Animal

class Cow extends Animal {
public Cow(int legs, String name) {
  super(legs, name);
}
}

In the example above,
Cow is a subclass of Animal because Cow inherits from Animal. So inheritance is ISA relationship. You see the walk() methods is already defined for Animal and we don't need to defined them again and again.
2. Has A - Member Field
Lets create Brain...

class Memory {
 int size;
 public void loadIntoMemory(Object anything) {}
 public boolean isInMemory(Object suspect) {
  return true;
}
}

Adding brain to Dogs' head.
class Dog extends Animal{
  Memory dogMemory;
}

Dog is obvioulsy an Animal and a Dog has some Memory called dogMemory. Hence, HAS-A relation is defined by a member field.
3. Performs - Interface
Lets introduce a interface IHelp.

interface IHelp {
  void doHelp();
}

Creating A Dog
class Dog extends Animal implements IHelp {
  private Memory dogMemory;
  public Dog(int legs, String name) {
  super(legs, name);
}
@Override
public void doHelp() {
  if (dogMemory.isInMemory(new Object())) {
  walk();
  findSuspect();
 }
}
private void findSuspect() {}
}

Here Dog is an Animal, it has Memory and it can Help. We can ensure a Dog can help by implementing IHelp interface.

Something More
The benefit of IHelp interface is that we can get help from all Animals by using same interface methods.
For example , lets create a Horse Class

class Horse extends Animal implements IHelp{
public Horse(int legs, String name){
  super(legs,name);
}
@Override
public void doHelp() {
  carryHuman();
}
private void carryHuman();
}



Getting help from Horse
Horse aHorse= new Horse(4,"Acorn");
horse.doHelp();


and for getting help from Dog
Dog aDog= new Dog(4,"Puppy");
aDog.doHelp();


You see we can get help from these Animals from same method doHelp();.
Its the fun of Object Oriented Design.......
Enjoy !!!!!

Some Popular, Interesting, Impressing, Funny...... Quotes


  • Diplomacy is the art of saying "nice doggy" ... until you can find a rock. 
  • It's not a bug, it's a feature. >> Support 
  • As far as I can tell, calling something philosophical is like greasing a pig to make it hard to catch. 
  • It’s always known that one horse can run faster than another. But which one? 
  • Some people will believe anything if you whisper it to them. 
  • If you want to make peace, you don’t talk to your friends. You talk to your enemies. 
  • We could never learn to be brave and patient If there were only joy in the world. 
  • War does not determine who is right - only who is left. 
  • Gratitude is expensive. Revenge is profitable. 
  • A synonym is a word you use when you can’t spell the word you first thought of. 
  • The greatest weariness comes from work not done. 
  • It may be that your whole purpose in life is simply to serve as a warning to others. 
  • Anything is possible, but only a few things actually happen. 
  • No matter how big or soft or warm your bed is, you still have to get out of it. 
  • I went on a diet, swore off drinking and heavy eating, and in fourteen days I lost two weeks. 
  • We make a living by what we get, we make a life by what we give. 
  • I slept, and dreamed that life was beauty;I woke, and found that life was duty. 
Visit http://ganeshtiwaridotcomdotnp.blogspot.com/2011/06/some-intelligent-humorous-quotes-about.html for some intelligent/ humorous quotes

Java Image - read image and separate RGB array values

Reading image and getting values of Red Green Blue and Alpha values in separate 2d arrays :

public class TestImagesss {
    public static void main(String[] args) {
        int value[][]=getRGB(getImage("test.jpg"));
        int valueR[][]=getR(getImage("test.jpg"));
    }
    //.... code below :

maven - pom.xml define properties constants

Define :
    <properties>
        <my_Constant_String>com.gt.App</my_Constant_String>
    </properties>
Use :

 <some_property_tag>${my_Constant_String}</some_property_tag>

screen logger - capture screen periodically and save to folder - java

Screen Capture Logger Java Application : Capture screen in fixed interval and save jpeg image to a folder.
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

public class ScreenLogger {
    private static final String saveLocation = "c:\\logs\\";
    private static final int timeInterval = 1000 * 30;
    private static Rectangle rect;
    private static Robot robot;

    public static void main(String[] args) throws Exception {
        init();
        new Thread(new CaptureThread()).start();
    }

J2ME Bluetooth discover connect send read message

Bluetooth communication - discover (by both server and client), connect to ad hoc network, send, receive message in J2ME java code.
This working java source code was used in our project  BlueChess- two player chess game over bluetooth adhoc connection
Code:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;

public class BtCommunication {

    private StreamConnectionNotifier scn=null;
    private DiscoveryAgent mDiscoveryAgent=null;
    private StreamConnection conn = null;
    private InputStream inputStream=null;

Java:opening a folder in windows explorer

opening a directory using start utility in windows

String cmd = "cmd.exe /c start ";
String file = "c:\\";
Runtime.getRuntime().exec(cmd + file);

Creating DSL / PPPOE Connection in UBUNTU

I have internet connection (worldlink-512kbps, cable net) shared with landowner and flatmates through wireless router. I recently created a PPPOE (Point to Point Protocol Over Ethernet) dial-up connection on my laptop to use whole bandwidth during load-shedding.

Creating DSL connection in Ubuntu is extremely easy.

Create, configure maven project in eclipse - example tutorial

In this post, the followings are covered :
  • Download and Install maven in windows:
  • Add M2_REPO classpath variable in eclipse 
  • Generate Java/Web Project  with maven and import in eclipse
  • Add another dependency from web repository
  • Add custom or 3rd party library manually into repository:
  • Benefits of using MAVEN :

Reading contents of unix ext partitions from windows

How to read / browse / copy files from linux ext partitions from windows?

Do you ever want to copy files from your unix ext partition from windows?
Ext2Explore is solution.
It supports ext2, ext3, ext4 partitions. and easy to use as it provides GUI like an file explorer.
This software is compatible with windows XP SP3 and higher.
Download it from SourceForge.net
You need to run this program as an Administer option.

Most Popular English Movies


Here is the list of best and popular movies that I have watched.
They are definitely good : inspiring and entertaining.
  1. A beautiful mind
  2. The Pursuit of Happiness
  3. Atonement
  4. The Notebook
  5. Casablanca
  6. Hill has eyes
  7. Stuck
  8. 8 belows
  9. Alive
  10. Awakenings
  11. Basketball diaries
  12. The Motorcycle Diaries (2004)
  13. Before Sunrise (1995)
  14. Before Sunset (2004)

Drawing Chess Game Board in Java - Source Code

Source code for Chess Game Board in Java :


public class ChessGUI extends JFrame {
    private Board board;
    private ChessGUI() {
        board = new Board();
        setLayout(new FlowLayout());
        add(board);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
        pack();
    }

java read content of web page

The following example use easier method to read String from InputStream in Java. It uses java.util.Scanner. It will be easy/efficient to read shorter content by using this method.
Reading content of web URL:
System.out.println("Google\n" + new Scanner(new URL("http://google.com").openStream())
                                                    .useDelimiter("\\A").next());
Reading a text file :
System.out.println("TextFile\n"+new Scanner(new File("inputFile.txt"))
                                                    .useDelimiter("\\A").next());
The regex "\\A" here matches the beginning of input source. Scanner can work not only with an InputStream source, but with  anything that implements the new (JDK version >= 1.5) java.lang.Readable interface.

Deploying .war file to Apache Tomcat Server : Working way

Here i am going to describe the [MANUAL]working way to deploy your .war(web application archive) file to the Apache Tomcat Server.
Suppose you have your web application's war file ,say MyProject.war exported from Eclipse Netbeans or similar IDE.
Steps:
1.Copy this .war file to webapps folder TOMCAT_HOME directory e.g, C:\apache-tomcat\webapps\
2.Restart the server, >> run the startup.bat in folder C:\apache-tomcat\bin
3.If the error message such as
     JAVA_HOME not defined or CATALINA_HOME not defined
     Then follow these steps to setup these environment variables:
  • Right-click the My Computer icon on your desktop and select 'Properties'.
  • Click the 'Advanced' tab (Windows XP), click on Advance System Settings on Windows7.
  • Click the 'Environment Variables' button.
  • Under 'System Variables', click 'New'.
  • Enter the variable name as JAVA_HOME.
  • Enter the variable value as the installation path for the Java Development Kit. eg. C:\Program Files (x86)\Java\jdk1.6.0_20
  • Repeat the process for CATALINA_HOME variable and enter installation path for Tomcat Server, eg. C:\apache-tomcat\webapps\
  • Click 'OK'.
  • Click 'Apply Changes'.
  • Restart the Server >> run the startup.bat in folder C:\apache-tomcat\bin
4.Launch http://localhost:[PORT]/MyProject/ on the browser, (port number might be 8080 or 8400). And Make sure the work offline option is not checked.
5.If everything is ok, the Home page of your app will be loaded into browser
6.Enjoy :)

hibernate show sql & parameter to console


You need to configure it 2 places :
1) Configuration in log4j logger : add following lines in - log4j.properties file  :
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE
The first is equivalent to hibernate.show_sql=true, the second prints the bound parameters among other things.
2)Configuration in hibernate.cfg.xml :

<property name="show_sql">true</property>
TO Show Formatted SQL :<property name="format_sql">true</property>

java escape html string - code

1) StringEscapeUtils from Apache Commons Lang:

import static org.apache.commons.lang.StringEscapeUtils.escapeHtml;
// ...
String source = "The less than sign (<) and ampersand (&) must be escaped before using them in HTML";
String escaped = escapeHtml(source);


OR 

2) Use Spring's HtmlUtils.htmlEscape(String input) method.

Selection sort C C++ source code

Selection sort C C++ source code
//selection sort
#include <iostream.h>
void selectionSort(int *array,int length)//selection sort function 
{
    int i,j,min,minat;
    for(i=0;i<(length-1);i++)
    {
        minat=i;
        min=array[i];

      for(j=i+1;j<(length);j++) //select the min of the rest of array
      {
          if(min>array[j])   //ascending order for descending reverse
          {
              minat=j;  //the position of the min element 
              min=array[j];
          }
      }
      int temp=array[i] ;
      array[i]=array[minat];  //swap 
      array[minat]=temp;      
    }
}

void printElements(int *array,int length) //print array elements
{
    int i=0;
    for(i=0;i<10;i++)
        cout<<array[i]<<endl;
}
void main()
{

    int a[]={9,6,5,23,2,6,2,7,1,8};   // array to sort 
    selectionSort(a,10);                 //call to selection sort  
    printElements(a,10);               // print elements 
}

Java iterate through map, hashmap - working source code

Iterating through Map in Java - working efficient source code 

Map<String, Object> map = ...;

The solution uses map.keySet(), map.values(), and map.entrySet().

Text Prompted Remote Speaker Authentication : Joint Speech and Speaker Recognition/Verification System :: Major Project ::: Introduction

Biometrics is, in the simplest definition, something you are. It is a physical characteristic unique to each individual such as fingerprint, retina, iris, speech. Biometrics has a very useful application in security; it can be used to authenticate a person’s identity and control access to a restricted area, based on the premise that the set of these physical characteristics can be used to uniquely identify individuals.

Speech signal conveys two important types of information, the primarily the speech content and on the secondary level, the speaker identity. Speech recognizers aim to extract the lexical information from the speech signal independently of the speaker by reducing the inter-speaker variability. On the other hand, speaker recognition is concerned with extracting the identity of the person speaking the utterance. So both speech recognition and speaker recognition system is possible from same voice input.

Desired Output of the Combined System
Text Prompted Remote Speaker Authentication is a voice biometric system that authenticates a user before permitting the user to log into a system on the basis of the user’s input voice. It is a web application. Voice signal acquisition and feature extraction is done on the client. Training and Authentication task based on the voice feature obtained from client side is done on Server. The authentication task is based on text-prompted version of speaker recognition, which incorporates both speaker recognition and speech recognition. This joint implementation of speech and speaker recognition includes text-independent speaker recognition and speaker-independent speech recognition. Speaker Recognition verifies whether the speaker is claimed one or not while Speech Recognition verifies whether or not spoken word matches the prompted word.

java calculate method run time


long startTime = System.currentTimeMillis();

doReallyLongThing(); // call your method here
long endTime = System.currentTimeMillis();
// calculate the difference - that the method just took to executeSystem.out.println("That took " + (endTime - startTime) + " milliseconds");

SQL basics- complete reference guide - part8 SQL System Commands

Part8: SQL System Commands Reference guide

TOPICTEXTSYNTAXExample
ARRAY_GETReturns one element of an array.ARRAY_GET(arrayExpression, indexExpression)
ARRAY_LENGTHReturns the length of an array.ARRAY_GET(arrayExpression)
AUTOCOMMITReturns true if auto commit is switched on for this session.AUTOCOMMIT()
CANCEL_SESSIONCancels the currently executing statement of another session.CANCEL_SESSION(sessionInt)
CASEWHEN FunctionReturns 'a' if the boolean expression is true, otherwise 'b'.CASEWHEN(boolean, aValue, bValue)
CASTConverts a value to another data type.CAST(value AS dataType)
COALESCEReturns the first value that is not null.COALESCE(aValue, bValue [,...])
CONVERTConverts a value to another data type.CONVERT(value, dataType)
CURRVALReturns the current (last) value of the sequence, independent of the session.CURRVAL( [ schemaName, ] sequenceString )
CSVREADReturns the result set of reading the CSV (comma separated values) file.CSVREAD(fileNameString [, columnsString [, csvOptions ] ] )
CSVWRITEWrites a CSV (comma separated values).CSVWRITE ( fileNameString, queryString [, csvOptions [, lineSepString] ] )
DATABASEReturns the name of the database.DATABASE()
DATABASE_PATHReturns the directory of the database files and the database name, if it is file
based.
DATABASE_PATH()
FILE_READReturns the contents of a file.FILE_READ(fileNameString [,encodingString])
GREATESTReturns the largest value that is not NULL, or NULL if all values are NULL.GREATEST(aValue, bValue [,...])
IDENTITYReturns the last inserted identity value for this session.IDENTITY()
IFNULLReturns the value of 'a' if it is not null, otherwise 'b'.IFNULL(aValue, bValue)
LEASTReturns the smallest value that is not NULL, or NULL if all values are NULL.LEAST(aValue, bValue [,...])
LOCK_MODEReturns the current lock mode.LOCK_MODE()
LOCK_TIMEOUTReturns the lock timeout of the current session (in milliseconds).LOCK_TIMEOUT()
LINK_SCHEMACreates table links for all tables in a schema.LINK_SCHEMA(targetSchemaString, driverString, urlString,
userString, passwordString, sourceSchemaString)
MEMORY_FREEReturns the free memory in KB (where 1024 bytes is a KB).MEMORY_FREE()
MEMORY_USEDReturns the used memory in KB (where 1024 bytes is a KB).MEMORY_USED()
NEXTVALReturns the next value of the sequence.NEXTVAL ( [ schemaName, ] sequenceString )
NULLIFReturns NULL if 'a' is equals to 'b', otherwise 'a'.NULLIF(aValue, bValue)
READONLYReturns true if the database is read-only.READONLY()
ROWNUMReturns the number of the current row.ROWNUM()
SCHEMAReturns the name of the default  schema for this session.SCHEMA()
SCOPE_IDENTITYReturns the last inserted identity value for this session for the current scope.SCOPE_IDENTITY()
SESSION_IDReturns the unique session id number for the current database connection.SESSION_ID()
SETUpdates a variable with the given value.SET(@variableName, value)
TABLEReturns the result set.{ TABLE | TABLE_DISTINCT } ( { name dataType = expression } [,...] )
TRANSACTION_IDReturns the current transaction id for this session.TRANSACTION_ID()
USERReturns the name of the current user of this session.{ USER | CURRENT_USER } ()Select User();

SQL basics- complete reference guide - part7 - Date Time Functions

Part7: SQL Date Time Functions Reference

TOPICTEXTSYNTAXExample
CURRENT_DATEReturns the current date.{ CURRENT_DATE [ () ] | CURDATE() | SYSDATE | TODAY }
CURRENT_TIMEReturns the current time.{ CURRENT_TIME [ () ] | CURTIME() }
CURRENT_TIMESTAMPReturns the current timestamp.{ CURRENT_TIMESTAMP [ ( [ int ] ) ] | NOW( [ int ] ) }
DATEADDAdds units to a timestamp.DATEADD(unitString, addInt, timestamp)
DATEDIFFReturns the the number of crossed unit boundaries between two timestamps.{ DATEDIFF | TIMESTAMPDIFF } (unitString, aTimestamp, bTimestamp)
DAYNAMEReturns the name of the day (in English).DAYNAME(date)
DAY_OF_MONTHReturns the day of the month (1-31).DAY_OF_MONTH(date)
DAY_OF_WEEKReturns the day of the week (1 means Sunday).DAY_OF_WEEK(date)
DAY_OF_YEARReturns the day of the year (1-366).DAY_OF_YEAR(date)
EXTRACTReturns a specific value from a timestamps.EXTRACT ( { YEAR | YY | MONTH | MM | DAY | DD | DAY_OF_YEAR
    | DOY | HOUR | HH | MINUTE | MI | SECOND | SS | MILLISECOND | MS }
    FROM timestamp )
FORMATDATETIMEFormats a date, time or timestamp as a string.FORMATDATETIME ( timestamp, formatString
[ , localeString [ , timeZoneString ] ] )
HOURReturns the hour (0-23) from a timestamp.HOUR(timestamp)
MINUTEReturns the minute (0-59) from a timestamp.MINUTE(timestamp)
MONTHReturns the month (1-12) from a timestamp.MONTH(timestamp)
MONTHNAMEReturns the name of the month (in English).MONTHNAME(date)
PARSEDATETIMEParses a string and returns a timestamp.PARSEDATETIME(string, formatString
[, localeString [, timeZoneString]])
QUARTERReturns the quarter (1-4) from a timestamp.QUARTER(timestamp)
SECONDReturns the second (0-59) from a timestamp.SECOND(timestamp)
WEEKReturns the week (1-53) from a timestamp.WEEK(timestamp)
YEARReturns the year from a timestamp.YEAR(timestamp)

Java Capture/save image from swing Component eg : JFrame JPanel ..

Capture image from any swing Component and save to file.
Capture  :
BufferedImage image = new BufferedImage(component.getWidth(),
                                     component.getHeight(), BufferedImage.TYPE_INT_RGB);
// paints into image's Graphics
component.paint(image.getGraphics());
Save Image :