Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Tuesday, May 26, 2020

JAXB Examples in official "The Java EE 5 Tutorial"

I was trying to brush up on JAXB for a work-related project from the official "The Java EE 5 Tutorial". In the past, working with the provided examples has been useful. It helps me internalize better. Finding these examples has become difficult recently with most routes ending up in dead ends.
Here are the steps to quickly find these examples (if you don't want to chase the rabbit hole, download my cached version here for gz and here for zip):

  1. On the left sidebar, search for "Using the Tutorial Examples" link and click it.
  2. Click on "To Obtain the Tutorial Bundle".
  3. Click on "javaeetutorial.java.net".
  4. Search for "tutorial" and click on "javaeetutorial".
  5. Search for "Download" on the right sidebar.
  6. The links to the download are seen. Enjoy!!!


Monday, December 31, 2012

Difference between @Autowire and @Resource

1. @Resource is part of JSR-250. @Autowire is part of Spring framework.
2. @Resource can inject by name only(to inject into a field named "xyz" look for a bean named "xyz"). @Autowire can inject by name, type(to inject into a field/parameter of type "Abc", look for a unique bean of type "Abc") and many more.
3. @Resource can inject into a field only. @Autowire can inject into field, constructor and method parameters.
3. @Resource can inject List, Map and other Collection types. @Autowire cannot.

Sources: [1] [2]

Thursday, February 02, 2012

Strong, Weak, Soft and Phantom references in Java

The following code instantiates an instance of Student class in the heap and references the created instance from the stack variable s.

Student s = new Student();

The instantiated Student object remains in the heap until it is reachable by at least one reference to it. When the garbage collector runs after the last object reference has been removed, the object is deleted from heap. 

In the above example, s is a strong reference to the Student object. The garbage collector will not remove objects that have a strong reference.

When strong references fall short
There are times when a object should be marked as garbage collectible even when there are active references to it. For example, consider a large image object held in a in-memory cache. This image object should remain in the heap as long as the caching API's clients have reference to the image object. But if the caching API uses strong references, the image object will never get garbage collected as there will always be a strong reference to the image object from the cache itself. Enter weak references.

In the above caching example, the caching API should use a WeakReference. A weak reference "is a reference that isn't strong enough to force the object to remain in memory".

WeakReference weakStudent = new WeakStudent(new Student());

weakStudent.get(); // Returns actual Student object

The weakStudent.get() call could potentially return null if there are no strong references to the Student object.

A WeakHashMap is similar to HashMap except that the keys (not values) are referred to using weak references. So when there are no other Strong references to a key, it will be removed from the map.

Once WeakReference.get() starts returning null, the reference has become garbage collectible and the WeakReference is of no good. The ReferenceQueue class helps keep track of such garbage collectible references and should be passed as argument to WeakReference's constructor. When a object becomes garbage collectable, it will be placed in the ReferenceQueue. The application can read this queue from time to time and perform clean up on its end.

Degrees of weakness
A WeakReference is only one flavor of weakness. There are 2 more flavors:
1. SoftReference - This is less weak than a WeakReference. In a WeakReference, the referenced object is garbage collected the next time garbage collector runs, irrespective of whether memory is in shortage or not. A SoftReference is garbage collected only when memory is in short supply.
2. PhantomReference - This is stronger than a WeakReference. Its get() method always returns null. Its only use is to figure out when the object is enqueued into ReferenceQueues. For a WeakReference, the object is queued as soon as its only weakly reachable. Even before finalization and actual garbage collection. For PhanthomReference, the object is queued only after the object is physically removed from memory.

Saturday, October 08, 2011

3 ways to initialize and destroy Spring beans

There are 3 ways to initialize (and destroy) spring beans
1. Using init-method and destroy-method attributes
2. Implementing InitializingBean and DisposableBean interfaces
3. Using @PostConstruct and @PreDestroy Annotations (available only in Spring >=2.5)


1. Using init-method and destroy-method attributes
Certain bean methods can designated as initializing and destroying methods using the init-method and destroy-method attributes. Like so:



<bean
    id="studentService"
    class="initMethod.StudentServiceImpl"
    init-method="subscribe"
    destroy-method="unsubscribe"/>



2. Implementing InitializingBean and DisposableBean interfaces
The bean can implement these methods InitializingBean.afterPropertiesSet() and DisposableBean.destroy(). Like so:

public class StudentServiceImpl implements StudentService, InitializingBean, DisposableBean {
    @Override
    public boolean isExists(long studentId) {
        // A fake implementation
        if ( studentId % 2 == 0 )
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception 
    {
        // subscribe logic goes here
    }

    @Override
    public void destroy() throws Exception 
    {
       // unsubscribe logic goes here
    }
}



3. Using @PostConstruct and @PreDestroy Annotations
Note that both of these are JSR-250 annotations (here is a nice introduction to JSR-250 support introduced in spring 2.5).

@PostConstruct
public void subscribe()
{
  // subscribe logic goes here
}


@PreDestroy
public void unsubscribe()
{
  // unsubscribe logic goes here
}

Friday, September 02, 2011

Monday, February 07, 2011

Iterable interface and "for each" loop

Since Java SE 5.0, the new "for each" loop is supported.

To iterate a Collection, one had to go through the long way as follows:

import java.util.Collection;
import java.util.ArrayList;
import java.util.Iterator;

class IterationUsingIterator
{
    public static void main(String[] args)
    {
        Collection<String> names = new ArrayList<String>();
        names.add( "Jack" );
        names.add( "Jill" );

        Iterator<String> nameIterator = names.iterator();
        while( nameIterator.hasNext() )
        {
            System.out.println( nameIterator.next() );
        }
    }
}

The same loop using "for each" syntax:

import java.util.Collection;
import java.util.ArrayList;

class IterationUsingForEach
{
    public static void main(String[] args)
    {
        Collection<String> names = new ArrayList<String>();
        names.add( "Jack" );
        names.add( "Jill" );

        for( String name : names)
        {
            System.out.println( name );
        }
    }
}


Question: When can a collection (Collection, Array etc...) participate in "for each" syntax?
Answer: When the collection implements Iterable (with a single method Iterator<T> interator()). These includes Collection, List, Set, SortedSet, Queue and a few more collection sub-interfaces (refer to the javadocs). Arrays also support "for each" syntax. But they do not have a "Is A" relationship with Iterable.

Categorized list of Collection interface methods

Collection interface methods categorized:

Boolean

add(E o)

Methods to add elements to collection

Boolean

addAll(Collection<? Extends E> c)

Void

Clear()

Methods to remove elements from collection

Boolean

remove(Object o)

Boolean

removeAll(Collection<?> c)

Boolean

retainAll(Collection<?> c)

Boolean

contains(Object o)

Methods to check if specific element(s) exist in collection.

Boolean

containsAll(Collection<?> c)

Boolean

IsEmpty()

Methods to check collection at a higher level

Int

Size()

Iterator<E>

Iterator()

Methods to transform the whole collection to other representations

Object[]

ToArray()

<T> T[]

toArray(T[] a)


Saturday, February 05, 2011

Eclipse versions and release years

Helios - 3.6.0 - Released 2010

Galileo - 3.5.2 - 2009

Ganymede - 3.4.2 - 2008

Europa - 3.3.2 - 2007

Thursday, January 27, 2011

Abstraction & Encapsulation

Abstraction is the process of coining an interface that specifies all the
essential external behavior of an Object for a given client. This
interface is the external contract upon which the object's client depend
on. Abstraction focuses on the external view of an object and serves to
separate an object's behavior from its implementation.

Abstraction is based on concept of invariance - a boolean condition that
should be true at all times. Each method defines pre-conditions
(invariants the method assumes) and post-conditions (invariants that the
method satisfies).

Encapsulation is hiding of the implementation details of an object. An
object's client is not interested in the implementation details as long
as the implementation complies to the external contract.

Abstraction and Encapsulation are complementary concepts. Abstraction
focuses on the external behavior and encapsulation focuses on the
implementation that gives rise to the external behavior.

Monday, September 13, 2010

Java Generics - Part 4

Wildcards:

 

Consider the a method that prints all the elements of a collection (pre 1.5 code):

 

private static void printCollection(Collection objectCollection)

{

      for (Object element: objectCollection)

      {

            System.out.println( element );

      }

}

 

The above code when invoked as follows:

 

 

printCollection( Arrays.asList( new String[] {"test", "another test"} ) );

 

 

gives the following output:

 

 

test

another test

 

 

Lets write the same method using generics:

 

private static void printCollection(Collection<Object> objectCollection)

{

      for (Object element: objectCollection)

      {

            System.out.println( element );

      }

}

 

But now the same invocation ( printCollection( Arrays.asList( new String[] {"test", "another test"} ) ); ) will lead to a compile time error! :

 

PrintCollection.java:8: printCollection2(java.util.Collection<java.lang.Object>) in PrintCollection cannot be applied to (java.util.List<java.lang.String>)

                 printCollection2( Arrays.asList( new String[] { "test", "another test" }) );

                 ^

1 error

 

This is because when the String[] is converted to a List, it returns a List<String>. And a List<String> is not a List<Object> (although String is a Object. Why? Read this)

 

To resolve this issue, we could use…wildcards as follows:

 

private static void printCollection2(Collection<?> objectCollection)

{

      for (Object element: objectCollection) // compiler error will result for objectCollection.add(anything). Because Collection<?> specifies an unknown element type<terminology>. And the compiler has no way to check the type of “anything” against the unknown type. Null is exception.

      {

            System.out.println( element );

      }

}

 

 

Saturday, September 11, 2010

Java Generics - Part 3

List<Student> is NOT a List<Person>.

Isa relationships do not apply for generics. Why? Check the following listing:


 

1        List<String> nameList = new ArrayList<String>();

2        List<Object> objectList = nameList; // Now objectList is an alias for nameList

3     obecjtList.add( new Student() ); // a Student would have been added to a List<String>


 

Assuming the above code snippet would compile (it will not), it has introduced a Student object into a List of Strings. This violates one of the very basic reasons for having generics (type checking).  So Isa relationships do not work with generics.

BTB, the above code will fail compilation with the following compiler error:


 

NoIsaInGenerics.java:8: incompatible types

found   : java.util.List<java.lang.String>

required: java.util.List<java.lang.Object>

               List<Object> objectList = nameList; // Now objectList is an alias for nameList

                                         ^

NoIsaInGenerics.java:9: cannot find symbol

symbol  : variable obecjtList

location: class NoIsaInGenerics

               obecjtList.add( new Student() ); // a Student would have been added to a List<String>

               ^

2 errors


 

Java Generics - Part 2

A custom parametrized type:

Consider the following oversimplified DAO interfaces:


 

public interface StudentDAO

{

   Student getStudent( Long studentId );

}

 

class Student

{

        private Long id;

        private String name;

        // accessors and mutators

}


 

The above interface is specific for Student. But the same interfaces will hold good for other entities too, like Professor, Course etc... If the interfaces like the above are to be implemented, then there would be a Professor getProfessor( Long professorId ), Course getCourse( Long courseId). This is redundant, violates the DRY (Do not Repeat Yourself) principle. Since there is a getEntity() method is all the cases, the above interface can be written using generics as follows:

 


 

public interface DataAccessInterface<T> // 1 Parameterized type 2 T is formal type paramter

{

        T getEntity( Long EntityKey ); // 3 T can be used where ordinary types can be used

}


The above DAO interface will be used as follows:


 

        DataAccessInterface<Student> studentDAO; // 4 Student is actual type argument


 

Now, DataAccessInterface<T> is a parameterized type, T is the name of the formal type paramter. After T has been declared in the interface declaration, it can be used instead of normal types throughout the interface declaration.

When a reference to a parameterized type is declared (at 4 above), the actual type to be passed to the formal types is also specified. At this time, all occurrences of the formal type (T) will be replaced by the actual type (Student).

Wednesday, August 04, 2010

Java Generics - Part 1

Generics were introduced in JDK 5.0. Generics help write re-usable code without losing type safety. Type safety helps write robust programs. The most common usage of generics is in the collections API.

 

Prior to generics, a Collection could theoretically hold values of various types. Like so:

 

import java.util.Collection;

import java.util.LinkedList;

class Generics1

{

       public static void main(String[] args)

       {

              Collection nameList = new LinkedList();              

              nameList.add( new Integer(0) ); // 1 Integer added to collection

              nameList.add( "test" );         // 2 String added to collection

              System.out.println( nameList );

       }

}

 

Compiling the above code with JDK 5.0 and above will result in a “warning”. But the class file does get generated. Like so:

 

$ javac Generics1.java

Note: Generics1.java uses unchecked or unsafe operations.

Note: Recompile with -Xlint:unchecked for details.

 

Running the class file does give the following output:

 

$ java Generics1

[0, test]

 

But now we have a Collection with a Integer and a String. Its highly un-likely that a programmer would expect to see a Integer in a nameList.

 

To enforce type safety that the nameList can only hold String instances, change the declaration of nameList like so:

 

import java.util.Collection;

import java.util.LinkedList;

class Generics1

{

       public static void main(String[] args)

       {

              Collection<String> nameList = new LinkedList<String>();

              nameList.add( new Integer(0) ); // Violation (Integer added to String collection) caught by compiler.

              nameList.add( "test" );        

              System.out.println( nameList );

       }

}

 

 

Now, the compiler checks each operation on the Collection and ensures that only Strings find place in the Collection (type correctness). Compilation fails if there are violations (like above):

 

$ javac Generics1.java

Generics1.java:8: add(java.lang.String) in java.util.Collection<java.lang.String> cannot be applied to (java.lang.Integer)

                nameList.add( new Integer(0) );

                        ^

1 error

 

Since all Collection elements are held as java.lang.Object in a non-generic Collection, all fetches must be cast to the appropriate type. Failing to do so will result in a compilation failure. Like so:

 

import java.util.List;

import java.util.LinkedList;

class Generics1

{

       public static void main(String[] args)

       {

              List nameList = new LinkedList();

              nameList.add( "test" );

              String firstName = nameList.get(0);

System.out.println( firstName );

       }

}

 

$ javac Generics1.java

Generics1.java:9: incompatible types

found   : java.lang.Object

required: java.lang.String

                String firstName = nameList.get(0);

                                               ^

Note: Generics1.java uses unchecked or unsafe operations.

Note: Recompile with -Xlint:unchecked for details.

1 error

 

This issue can be resolved by explicitly casting the assignment or typing the collection with generics like so:

 

              List<String> nameList = new LinkedList<String>();

 

$ java Generics1

Test

 

In the above case, List is a generic interface with a type parameter.

Tuesday, July 06, 2010

String.split() trivia

The String.split() method converts a given string to an array based on a regular expression.

Examples:


System.out.println( Arrays.toString( "0:1::::".split( "[:]" ) ) );     // Output: [0, 1]

System.out.println( Arrays.toString( "::::4:5".split( "[:]" ) ) );     // Output: [, , , , 4, 5]

System.out.println( Arrays.toString( "0:1::::".split( "[:]", -1 ) ) ); // Output: [0, 1, , , , ]


As the documentation notes, “blah”.split(“:”) is the same as “blah”.split(“:”, 0) which does not include trailing empty strings.

Wednesday, December 09, 2009

Debugging exceptions with no known cause

There are times when you call a third party method in your code which throws an exception. Your line that invokes the third party code is not seen in the exception stack trace. In these cases, it is useful to wrap the call to the third party code in try catch block, catch Exception and log the resulting exception. The stack trace from the exception you log will have your code that is making the third party call, calls made by the third party code and likely a more detailed message of what went wrong.

 

e.g.:

 

class MyClass

{

    public void myMethod()

    {

        try

        {

            new ThirdPartyClass().thirdPartyMethod();

        }

        catch (Exception e)

        {

            e.printStackTrace();

        }

    }

}

Tuesday, December 01, 2009

Looking at java stack traces

While looking at stack traces,

  1. Read from the bottom of the trace
  2. Read the Message of the last stack trace (usually there are many with “caused by”)
  3. Look for a line in the stack trace that indicate a call to your package in the stack trace. This way, you will know how your code is getting called and what your code is doing.

Tuesday, September 08, 2009

Simple Logging Facade 4 Java (SLF4J)

A peer of commons logging. Both are logging interfaces that applications have dependencies to. The calls to SLF4J or commons logging APIs is finally implemented by log4j or jdk logging.

Thursday, September 03, 2009

Logic that needs to be executed only in the JSF Render Response Phase

if (FacesContext.getCurrentInstance().getRenderResponse()) {
    // Logic that needs to be executed only in the JSF Render Response Phase
}
 
Source - balusc

 

Thursday, August 27, 2009

Building a massive system is like building a simple API - Eric

In response to Steve indicating that Eric is pretty good at building big systems from the scratch