Wednesday, December 7, 2011

Association, Aggregation & Composition

Association : An association is  the relation between two objects. In other words its connectivity between two objects. Aggregation and compositions are form of association. 
Aggregation: This is a part of a whole relationship where a part can exist without a whole.
Aggregation is a weak association.  Also called “has a” relationship.
Composition : This is a part of a whole relationship where a part cannot exist without a whole. If a whole is deleted then all parts are deleted.
Composition is a Strong association.
Example:
A House contains Room and TV. Relationship between House and TV is aggregation and relation between House and Room is composition.
A TV can exist without a House-> Weak association (Aggregation)
A Room cannot exist without a House -> Strong association (Composition).

Java Example :
Aggregation

Class LPG{
}

Class Car{
Car(LPG objLPG) //Object is passed from outside   - weak relationship –LPG can exist without a car
{
}
}

Composition
Class Engine{}
Class Car{
                Car(){
                Engine objEng = new Engine();  //lives within car object   - Strong relationship: Engine cannot exist without car.
}
}








Tuesday, December 6, 2011

Class File (binary file)

We all(Java Developers) know, in the java programming language java source files (.java) are compiled into machine readable (.class) files and the .class files have byte code.


In this section  we will look into the class file structure (class file format) .

The ClassFile Structure (As per The Java Virtual Machine)

ClassFile {
                 u4 magic;
                 u2 minor_version;
                 u2 major_version;
                 u2 constant_pool_count;
                 cp_info constant_pool[constant_pool_count-1];
                 u2 access_flags;
                 u2 this_class;
                 u2 super_class;
                 u2 interfaces_count;
                 u2 interfaces[interfaces_count];
                 u2 fields_count;
                 field_info fields[fields_count];
                 u2 methods_count;
                 method_info methods[methods_count];
                 u2 attributes_count;
                 attribute_info attributes[attributes_count];
}
Magic Number: Identifying the class file format; it has the value 0xCAFEBABE.
Version of Class file :  The values of the minor_version and major_version items are the minor and major version numbers of this class file.
Constant pool : The constant pool table is where most of the literal constant values are stored. This includes values such as numbers of all sorts, strings, identifier names, references to classes and methods, and type descriptors. 
Access Flag : denote access permissions to class or interface.
This class : The value of the this_class item must be a valid index into the constant_pool. The constant pool entry at that index must be a Constant_claa_info structure representing the class or interface defined by this class file.
Super Class : Identify the superclass of this class.
Interfaces : Identify any interfaces in the class. (interfaces_count, interfaces)
Fields : Fields in the class.( fields_count, field_info fields)
Methods : Methods in the class (method_count, method_info)
Attributes : Attributes in the class  (attributes_count, attribute_info)


Simple example with binary code

Compiled with J2SE 6 and opened the class file with Binary viewer (Hexadecimal).
Some of the file Structure sections with respect to above example
Magic number : CAFEBABE
Minor version: 0000
Major Version : J2SE 6.0 = 50 (0x32 hex) – 0032
Access flag : 0001– public access




Sunday, December 4, 2011

Eclipse Shortcuts

CTRL + D
Delete row. No need to grab the mouse and select the line. simple press ctrl + d to delete the row.
ALT + SHIFT + N
Open the dailog box, which allow to create new package/class/Project ... etc.


ALT + UP/Down arrow
Very useful at the time of rearranging the code. move up/down the selected row(code).

ALT + Left/Right arrow
Move the last location you edited. Imagine you just created a class Test1, and now you are working on a class Test2. Now, if you need to look at the Test1 class, just press Alt+Left arrow. Alt + Right arrow brings you back to Test2.


CTRL + SHIFT + R
This shortcut opens a dialog box that accepts the name of the file you're looking for. It accepts wildcard characters. Typing *.java will give you the list of all files that ends with .java.

CTRL + SHIFT + T
This will give the list of files(a class, an interface) which are present in packages ( don't have the source files in workspace, only have the class files ).


CTRL + O
which gives you a list of methods in file that match what you've typed


CTRL + E
Go to the open editors.

CTRL + T
Get the dialog box, which toggles between supertypes and subtypes.

CTRL + L : Go to Line


CTRL + SHIFT + O
It resolves the import issues

F3 : Jump to definition of methods

CTRL + 3 (Most useful shortcut )
Quick Access (Ctrl + 3) is your window to anything. perspectives, views, open editors, commands, menus ... just press ctrl + 3 and start typing, and it will show you the possible matches.




Friday, December 2, 2011

Oracle XE 11g Installation - "Oracle XE service instance failed"

If you get the error "Oracle XE service instance failed" while installing the oracle xe..

check the OracleXEService in services (Start->Run (type services.msc) enter)

Remove the OracleServiceXE by using below sc command

sc delete OracleServiceXE

now try the Oracle XE 11 g installation. :-)





Thursday, December 1, 2011

New useful class (java.util.Objects) in java 7

                In JAVA 7 API, we'll find a new class: java.util.Objects. This class consists of static utility 9 methods for operating on objects. These methods provide null-safe or null-tolerant operations on objects.
Methods in Objects class :
static <T> int compare(T a, T b, Comparator<? super T> c) 
                       Returns 0 if the arguments are identical and c.compare(a, b) otherwise
static boolean deepEquals(Object a, Object b)
                     Returns true if the arguments are deeply equal to each other and false otherwise
static boolean equals(Object a, Object b)
Returns true if the arguments are equal to each other and false otherwise
static int hash(Object... values)
Generates a hash code for a sequence of input values.
static int hashCode(Object o)
Returns the hash code of a non-null argument and 0 for a null argument
static <T> T requireNonNull(T obj)
Checks that the specified object reference is not null
static <T> T requireNonNull(T obj, String message)
                   Checks that the specified object reference is not null and throws a customized  NullPointerException if it is
static String toString(Object o)
Returns the result of calling toString for a non-null argument and "null" for a null argument
static String toString(Object o, String nullDefault)
                  Returns the result of calling toString on the first argument if the first argument is not null and returns the second

The following Examples demonstrates how to use some of these methods.

import java.util.Objects;

class Employee {

public String empName, empNo;

public Employee(String empName, String empNo){
this.empName = Objects.requireNonNull(empName, "Empolyee Name not be null"); // if first argument null, will throw null pointer exception with customized message
this.empNo = empNo;
}

@Override
public boolean equals(Object obj) {
final Employee employee = (Employee)obj;
return this.empName.equals(employee.empName) && this.empNo.equals(employee.empNo);
}

@Override
public int hashCode() {
return super.hashCode();
}

public void empDetails(){
System.out.println(empName);
System.out.println(Objects.toString(empNo, "Default value"));  // if first argument null, will return the default value
}
}


public class ObjectsDemo{

public static void main(String[] args) {

System.out.println(Objects.hashCode(null)); // display  0 

//Case1
Employee emp1 = new Employee("Employee1","1");
emp1.empDetails();

//Case2
Employee emp2 = new Employee("Employee2", null);
emp2.empDetails();

//Case3
System.out.println(Objects.equals(emp2, null));

//Case4
Employee emp3 = new Employee (null, "4");
emp3.empDetails();


}
}

output will be

0
Employee1
1
Employee2
Default value
Exception in thread "main" java.lang.NullPointerException
at test.Employee.equals(ObjectsDemo.java:18)
at java.util.Objects.equals(Objects.java:57)
at test.ObjectsDemo.main(ObjectsDemo.java:48)

Friday, November 25, 2011

Cool features in Java 7

Java 7 : Type Inference for Generic Instance Creation

Previously when using generics you had to specify the type twice, in the declaration and the constructor;
List<String> strings = new ArrayList<String>();


In Java 7, you just use the diamond operator without the type;
List<String> strings = new ArrayList<>();  



If the compiler can infer the type arguments from the context, it does all the work for you. Note that you have always been able do a “new ArrayList()” without the type, but this results in an unchecked conversion warning.
Type inference becomes even more useful for more complex cases;
Before Java 7
Map<String, Map<String,int>> mS = new HashMap<String, Map<String,int>>();
Java 7
Map<String, Map<String, int> mS = new HashMap();
Java SE 7 supports limited type inference for generic instance creation; you can only use type inference if the parameterized type of the constructor is obvious from the context. For example, the following example does not compile:
List<String> list = new ArrayList<>();
list.add("A");

  // The following statement should fail since addAll expects
  // Collection<? extends String>

list.addAll(new ArrayList<>());
Note that the diamond often works in method calls; however, it is suggested that you use the diamond primarily for variable declarations.
In comparison, the following example compiles:
// The following statements compile:

List<? extends String> list2 = new ArrayList<>();
list.addAll(list2);


Java 7 : Rethrowing Exceptions with More Inclusive Type Checking


The Java SE 7 compiler performs more precise analysis of rethrown exceptions than earlier releases of Java SE. This enables you to specify more specific exception types in the throws clause of a method declaration.
Consider the following example:
  static class FirstException extends Exception { }
  static class SecondException extends Exception { }

  public void rethrowException(String exceptionName) throws Exception {
    try {
      if (exceptionName.equals("First")) {
        throw new FirstException();
      } else {
        throw new SecondException();
      }
    } catch (Exception e) {
      throw e;
    }
  }
This examples's try block could throw either FirstException or SecondException. Suppose you want to specify these exception types in the throws clause of the rethrowException method declaration. In releases prior to Java SE 7, you cannot do so. Because the exception parameter of the catch clause, e, is type Exception, and the catch block rethrows the exception parameter e, you can only specify the exception type Exception in the throws clause of the rethrowException method declaration.
However, in Java SE 7, you can specify the exception types FirstException and SecondException in the throws clause in the rethrowException method declaration. The Java SE 7 compiler can determine that the exception thrown by the statementthrow e must have come from the try block, and the only exceptions thrown by the try block can be FirstException and SecondException. Even though the exception parameter of the catch clause, e, is type Exception, the compiler can determine that it is an instance of either FirstException or SecondException:
  public void rethrowException(String exceptionName)
  throws FirstException, SecondException {
    try {
      // ...
    }
    catch (Exception e) {
      throw e;
    }
  }
This analysis is disabled if the catch parameter is assigned to another value in the catch block. However, if the catch parameter is assigned to another value, you must specify the exception type Exception in the throws clause of the method declaration.
In detail, in Java SE 7 and later, when you declare one or more exception types in a catch clause, and rethrow the exception handled by this catch block, the compiler verifies that the type of the rethrown exception meets the following conditions:
  • The try block is able to throw it.
  • There are no other preceding catch blocks that can handle it.
  • It is a subtype or supertype of one of the catch clause's exception parameters.
The Java SE 7 compiler allows you to specify the exception types FirstException and SecondException in the throws clause in the rethrowException method declaration because you can rethrow an exception that is a supertype of any of the types declared in the throws.
In releases prior to Java SE 7, you cannot throw an exception that is a supertype of one of the catch clause's exception parameters. A compiler from a release prior to Java SE 7 generates the error, "unreported exception Exception; must be caught or declared to be thrown" at the statement throw e. The compiler checks if the type of the exception thrown is assignable to any of the types declared in the throws clause of the rethrowException method declaration. However, the type of the catch parametere is Exception, which is a supertype, not a subtype, of FirstException andSecondException.

Java 7 : Handling More Than One Type of Exception


A single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.
Consider the following example, which contains duplicate code in each of the catch blocks:
catch (IOException ex) {
     logger.log(ex);
     throw ex;
catch (SQLException ex) {
     logger.log(ex);
     throw ex;
}
In releases prior to Java SE 7, it is difficult to create a common method to eliminate the duplicated code because the variable ex has different types.
The following example, which is valid in Java SE 7 and later, eliminates the duplicated code:
catch (IOException|SQLException ex) {
    logger.log(ex);
    throw ex;
}
The catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar (|).
Note: If a catch block handles more than one exception type, then the catch parameter is implicitly final. In this example, the catch parameter ex is final and therefore you cannot assign any values to it within the catch block.

Java 7 : Binary Literals


In Java SE 7, the integral types (byteshortint, and long) can also be expressed using the binary number system. To specify a binary literal, add the prefix 0b or 0B to the number. The following examples show binary literals:
// An 8-bit 'byte' value:
byte aByte = (byte)0b00100001;

// A 16-bit 'short' value:
short aShort = (short)0b1010000101000101;

// Some 32-bit 'int' values:
int anInt1 = 0b10100001010001011010000101000101;
int anInt2 = 0b101;
int anInt3 = 0B101; // The B can be upper or lower case.

// A 64-bit 'long' value. Note the "L" suffix:
long aLong = 0b1010000101000101101000010100010110100001010001011010000101000101L;

Java 7 : Strings in switch Statements


Currently you can only use char, byte, short, int,Character, Byte, Short, Integer, or an enum type (spec).Now Java 7 adds Strings making the switch instruction much friendlier to String inputs.

public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
     String typeOfDay;
     switch (dayOfWeekArg) {
         case "Monday":
             typeOfDay = "Start of work week";
             break;
         case "Tuesday":
         case "Wednesday":
         case "Thursday":
             typeOfDay = "Midweek";
             break;
         case "Friday":
             typeOfDay = "End of work week";
             break;
         case "Saturday":
         case "Sunday":
             typeOfDay = "Weekend";
             break;
         default:
             throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
     }
     return typeOfDay;
}

The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String.equals method; consequently, the comparison of String objects in switch statements is case sensitive. The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.

try-with-resource / AMD ( automatic resource management)


A *resource* is as an object that must be closed manually,
such as a java.io.InputStream, OutputStream, Reader, Writer, Formatter;
java.nio.Channel;java.net.socket; java.sql.Connection, Statement, ResultSet,
or java.awt.Graphics.

The *automatic resource management statement* is a form of the try statement
that declares one or more resources. The scope of these resource
declarations is limited to the statement. When the statement completes,
whether normally or abruptly, all of its resources are closed automatically.

*EXAMPLES*

SIMPLE EXAMPLE: Here is a static method to read the first line of a file,
demonstrating the minimal (nearly) correct code to release a single resource
today.
    static String readFirstLineFromFile(String path) throws IOException {

        BufferedReader br = new BufferedReader(new FileReader(path));

        try {

            return br.readLine();

        } finally {

            br.close();

        }
    }

Unfortunately, if the readLine and close invocations both throw exceptions,
the latter exception supplants the former.  The only practical way around
this today would to be to ignore any exception thrown by the close invocation.
While this might be reasonable in the case of a Reader or InputStream, it
would be disastrous for a Writer or OutputStream.

Here’s how it would look with an automatic resource management statement:

    static String readFirstLineFromFile2(String path) throws IOException {

      try (BufferedReader br = new BufferedReader(new FileReader(path)) {

            return br.readLine();

         }

      }

You may declare one or more resources in a try-with-resources statement.
like
    try (
       java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);
       java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
      )

The following example uses a try-with-resources statement to automatically close a java.sql.Statement object:
  public static void viewTable(Connection con) throws SQLException {

    String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES";

  try (Statement stmt = con.createStatement()){

      ResultSet rs = stmt.executeQuery(query);

      while (rs.next()) {
        String coffeeName = rs.getString("COF_NAME");
        int supplierID = rs.getInt("SUP_ID");
        float price = rs.getFloat("PRICE");
        int sales = rs.getInt("SALES");
        int total = rs.getInt("TOTAL");
        System.out.println(coffeeName + ", " + supplierID + ", " + price +
                           ", " + sales + ", " + total);
      }

    } catch (SQLException e) {
      JDBCTutorialUtilities.printSQLException(e);
    }
  }
The resource java.sql.Statement used in this example is part of the JDBC 4.1 and later API.
Note: A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.

Advantage : The automatic resource management statement obviates the need for manual resource termination, which has proven ugly and error prone.
It could emit the code to suppress the uninteresting(second) exception in favor of the interesting(first) one with no effort on the part of the programmer, and no loss to the clarity of the program.
Like the for-each statement(introduced in java 1.5), the automatic resource management statement is a small piece of syntactic sugar with a very high power-to-weight ratio.


Disadvantage: Like all syntactic sugar, this construct removes a bit of java's "what you see is what you get" character ("transparency").

Thursday, November 17, 2011

Adding Ajax Behavior for Generate PDF in Apache wicket framework



Step 1: Override the AbstractAjaxBehavior class functionality as below.

public abstract class ClassName extends AbstractAjaxBehavior {

    private static final long serialVersionUID = 1L;
 
    /**
     * initiate to call the java script file open dialog
     * @param target
     */
    public void initiate(AjaxRequestTarget target) {
        target.appendJavascript("window.open('" + getCallbackUrl()
            + "', '', 'scrollbars=yes,location=no,menuBar=no,resizable=yes,status=no,toolbar=no')");
    }

    /**
     * Called when a request to a behavior is received.
     * @see org.apache.wicket.behavior.IBehaviorListener#onRequest()
     */
    @Override
    public void onRequest() {

        RequestCycle rc = getComponent().getRequestCycle();
        final WebResponse webResponse = (WebResponse) getComponent().getRequestCycle().getResponse();
        webResponse.setLastModifiedTime(Time.now());
        webResponse.setContentType("application/pdf");
        webResponse.setHeader("Content-Disposition", "inline; filename=\"" + getFileName() + "\"");

        rc.setRequestTarget(new IRequestTarget() {

            public void respond(RequestCycle requestCycle) {
                OutputStreamWriter writer = null;
                try {
                    OutputStream stream = webResponse.getOutputStream();
                    writer = new OutputStreamWriter(stream, "ISO-8859-1");
                    writer.write(getStringToWriteonPDF());
                    writer.flush();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                } finally {
                    try {
                        writer.close();
                    } catch (IOException ioException) {
                    }
                }
            }

            public void detach(RequestCycle requestCycle) {

            }

        });

    }

    /**
     * get the File Name
     * @see ResourceStreamRequestTarget#getFileName()
     */
    protected abstract String getFileName();

    protected abstract String getStringToWriteonPDF();

}

Step 2: Use the override behavior in Component class

public void onClick(AjaxRequestTarget target) {

  ClassName  behavior =  new ClassName () {
             private static final long serialVersionUID = 1L;

             @Override
             protected String getStringToWriteonPDF() {
                  return "out put of PDF-it may get from Source (Database/webservices)";
             }

             @Override
             protected String getFileName() {
                  return "File Name of PDF";
             }
          };
                  add(behavior);
             behavior.initiate(target);
}

Learn This: When to use an Abstract Class and an Interface

Learn This: When to use an Abstract Class and an Interface

Configure Java environment on Windows

Configure Java environment on Windows

Wednesday, November 16, 2011

Singleton


The Singleton is a useful Design Pattern for allowing only one instance of your class.

The Singleton's purpose is to control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields.

Below are the example for singleton..

Case 1:

public class Singleton {

private static Singleton singleton;

private Singleton(){
}

public static synchronized Singleton getInstance(){
if(singleton==null)
singleton = new Singleton();
return singleton;
}

}

Case 2:

public class Singleton {


private static Singleton singleton = new Singleton();

private Singleton(){
}

public static synchronized Singleton getInstance(){
return singleton;
}
}


The difference between Case 1 and Case 2 is that in Case 2 singleton is instantiated when the class is loaded, while in the Case 1, it is not instantiated until it is actually needed.

J2EE Video tutorial.

Java Brains: J2EE video tutorial :  JSP/Servlet, Maven, Hibernat and Spring framework video tutorial.

Thursday, October 20, 2011

Sharing HTTP session across web-apps in Oracle Weblogic 10.3



If you’re an experienced J2EE programmer, you probably already heard of the chance to use session sharing between two or more webapps. This feature is not part of the J2EE spec but has been implemented in several application servers like WebLogic, WebSphere or JBoss for example.
Although sharing session data is a Servlet 2.4 spec violation, and a potential security issue under some rare circumstances, there are some understable business cases to use it :
  • You may want to broke up a large application into multiple web-apps, so that new functionality can be pushed out in a more modularized way.
  • If you buy software to a company and that you want to integrate it seamlessly to your web application and make the two act as if you are facing a single application, this is the fastest & easiest way. It saves you from the pain of writing complex code to synchronize the sessions between the web-apps or even to exchange data between these web-apps.
Remember that the following will not apply directly to other application servers but may guide you towards the solution for these servers too.
Here’s how i made it work under WebLogic 10.3 :
My first guess was that i simply had to declare the web-app to use the shared session ability and that only the web-apps using this declaration would participate in this shared memory area. But this is not exactly how it works.
In fact, you need to build an EAR (Enterprise ARchive) out of your two web-apps, and declare in an additionnal configuration file that session sharing is enabled inside this entreprise application.
Let’s say that you have two web-apps which context paths are /poc1 and /poc2. First thing you have to do is reorganize your project to fit to the model of EAR’s. Here’s the final structure of our new EAR :
ear_schema
As you can see, there is a new meta-inf/application.xml file which purpose is to describe the application structure :
01.xml version="1.0" encoding="ISO-8859-1"?>
02.<application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
06.id="Application_ID" version="5">
07. 
08.<display-name>Test ear appdisplay-name>
09. 
10.<module>
11.<web>
12.<web-uri>poc1web-uri>
13.<context-root>poc1context-root>
14.web>
15.module>
16.<module>
17.<web>
18.<web-uri>poc2web-uri>
19.<context-root>poc2context-root>
20.web>
21.module>
22.application>
You may already have noticed the weblogic-application.xml, this is the Weblogic specific file that contains the sharing session directive.
01.xml version="1.0" encoding="ISO-8859-1"?>
02.<wls:weblogic-applicationxmlns:wls="http://www.bea.com/ns/weblogic/weblogic-application"
05. 
06.<wls:session-descriptor>
07.<wls:persistent-store-type>memorywls:persistent-store-type>
08.<wls:sharing-enabled>truewls:sharing-enabled>
09.wls:session-descriptor>
10.wls:weblogic-application>
Now deploy this application using weblogic console. You can test that everything is running ok by using the read.jsp and set.jsp which allow to set a variable in the session in one web-app and read it from the other web-app just by accessing these in your browser. A typical test would be to open the following urls in two different browser’s windows :
Don’t forget to replace [serverhost:port] by your server name and port which should typically be localhost:7001
http://[serverhost:port]/poc1/set.jsp
http://[serverhost:port]/poc2/read.jsp
The second url should display the following page content :
Session attribute “myvar” is set to : toto1
Everything is working as intented, just don’t forget that you are using shared sessions. This could result in looooooooooooong debugging sessions because of variable names collisions between the web-apps which can be simply solved by prefixing the key of these session attributes with web-app related prefixes.
You can download an archive of the exploded demo EAR, if you want to test it by yourself.