Wednesday, January 5, 2011

Default vs Protected access modifier


Default and protected access modifier rules are somewhat strange I will try to clarify them.

Class:

We cannot declare a top level class as protected; we can only declare it as , if it is default it is only visible and inheritable by other classes in the same package.

Members:

, member are visible to all class in the same package. But not visible to classes outside the package even if the class is sub classed by other class. So default visibility is strictly within the package.

Protected is same as default with one extra liberty. “Sub classes outside the package can inherit the protected members “.

Thursday, October 28, 2010

One reason for equals and compareTo methods to have same symantic

Suppose you have Class which is comparable, then symantics of equal and comapreTo methods should same.
i.e If o1.equals(o2) is true , then o1. comareTo(o2) should be 0 and vice verse.

What happens when above condition is not maintained, I wrote below peace code to test that.
public class Main1 {
public static void main(String[] args) {

MyData[] darray = {new MyData(1, "siva"), new MyData(2, "siva"), new MyData(3, "siva3"), new MyData(4, "siva4")};
System.out.println(darray[0].equals(darray[1]));
System.out.println(darray[0].compareTo((darray[1])));
TreeSet set = new TreeSet();
System.out.println("**********TreeSet*****************");
System.out.println(set.add(darray[0]));
System.out.println(set.add(darray[1]));

TreeMap map = new TreeMap();
System.out.println("**********TreeMap*****************");
System.out.println(map.put(darray[0], "1"));
System.out.println(map.put(darray[1], "2"));

HashMap map2 = new HashMap();
System.out.println("**********HashMap*****************");
System.out.println(map2.put(darray[0], "1"));
System.out.println(map2.put(darray[1], "2"));

HashSet set2 = new HashSet();
System.out.println("**********HashSet*****************");
System.out.println(set2.add(darray[0]));
System.out.println(set2.add(darray[1]));
}
}

public class MyData implements Comparable {
public MyData(int value, String name) {
super();
this.value = value;
this.name = name;
}
private int value;
private String name;
@Override
public int compareTo(MyData o) {
//Comparison based on name
return name.compareTo(o.name);
}
public int getValue() {
return value;
}
public String getName() {
return name;
}

@Override
public boolean equals(Object o){
if(o instanceof MyData){
//Equals behavior is based on int value
return this.value == ((MyData)o).value;
}
return false;
}
}

//------output is----------//
false
0
**********TreeSet*****************
Added
Already Exist
**********TreeMap*****************
Added
Already Exist
**********HashMap*****************
Added
Added
**********HashSet*****************
Added
Added
-------------------------------------------------------------------
There is a difference behavior of different Set and Map based on their implementation.
Is there a way to enforce compareTo and equals have same behavior ? Well its upto the java programmer to guarantee this semantics.

Define equals when ever compareTo is defined.

Tuesday, September 21, 2010

Disable host name verification in webservices

While developing secured http clients, host name verification failure is one of the common issue.

In this blog I will try to explain about:

What is host name verification ?
If you observe SSL hand shake process, during new TCP connection, server sends a trust certificate to client. This certificate will have servers public key and host name(common name (CN)) among many other properties.
In the subsequent communication between client and server in the same ssl session, the request host name should be same as host name in certificate. This check is necessary to prevent URL spoofing.

Why it is problematic ?
If host name in certificate is 'myhost', you can only access the sever with that specific name we can not even access it with local IP address.

In application that directly deal with HttpConnection host name verification can be done as below:
HostnameVerifier hv = new javax.net.ssl.HostnameVerifier() {
public boolean verify(String urlHostName,SSLSession session) {
return true;
}

Either set the default HV
javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(hv);

or Set hv to specific connection :
URLConnection uc = u.openConnection();
HttpsURLConnection connection = (HttpsURLConnection)uc;
connection.setHostnameVerifier(hv);
connection.connect();

When it comes to JAX-WS web service how can we disable HV ?
We don't have access to any protocol handler, and we may not know if custom connection handler are used.

Below code can used to disable host name verification: JAX-WS RI
Map ctxt = ((BindingProvider)portType ).getRequestContext();
ctxt.put(com.sun.xml.ws.developer.JAXWSProperties.HOSTNAME_VERIFIER, hv);
Or
ctxt.put(weblogic.wsee.jaxws.JAXWSProperties.HOSTNAME_VERIFIER, hv);


Related Info:
* Dummy certificates can be created using 'openssl'
* http://download.oracle.com/javase/1.5.0/docs/guide/security/jsse/JSSERefGuide.html#SSLOverview

Monday, August 16, 2010

Number format exception with eclipse link JPQL IN clause

Eclipse link jpql IN clause can throw Number format exception even when number is valid.

JPQL:
"Select e from Entity e where e.id IN (4562859281)". This can throw number format exception, this is because of a limitation with JPQL. workaround is to use bind parameters.

Wednesday, August 4, 2010

SQL Trace

Learn how to use SQL trace
http://www.orafaq.com/wiki/SQL_Trace

To know the file where trace will be logged.
Login as sys (sqlplus sys/oracle@:1521/orcl AS SYSDBA)

UDUMP is the database's USER DUMP DIRECTORY.
SQL> SHOW PARAMETERS user_dump_dest

NAME TYPE VALUE
------------------------------------ ----------- ------------------------------
user_dump_dest string /app/oracle/admin/o102/udump

Sunday, July 25, 2010

EntityManager vs EntityManagerFactory vs PersistenceContext

Clear understanding of Persistence unit, EntityManager, EntityManagerFactory and PersistenceContext are very impotent to work with JPA.
Persistence unit: Set of entity types(classes) that are grouped under a name.
Persistence context: A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance. Within the persistence context, the entity instances and their lifecycle is managed by a particular entity manager. The scope of this context can either be the transaction, or an extended unit of work.
EntityManagerFactory: An entity manager factory provides entity manager instances, all instances are configured to connect to the same database. You can prepare several entity manager factories to access several data stores.
EntityManager provides API to create and remove persistent entity instances, to find entities by their primary key identity, and to query over all entities.
An Entity Manager whose lifecycle is managed by the container is Container-managed entity manager.
An Entity Manager whose lifecycle is managed by the application is Application-managed entity manager.
Entity manager involved in a JTA transaction is JTA entity manager, generally its also container-managed entity manager.
Entity manager using a resource transaction (not a JTA transaction) is
Resource-local entity manager. Generally its Application-managed entty manager.

The most common and widely used entity manager in a Java EE environment is the container-managed entity manager. In this mode, the container is responsible for the opening and closing of the entity manager (this is transparent to the application). . A container-managed entity manager is obtained in an application through dependency injection or through JNDI lookup, A container-managed entity manger requires the use of a JTA transaction.

An application-managed entity manager allows you to control the entity manager in application code. This entity manager is retrieved through the EntityManagerFactory API. An application managed entity manager can be either involved in the current JTA transaction (using EntityManager.joinTransaction) , or the transaction may be controlled through the EntityTransaction API (a resource-local entity manager). The resource-local entity manager transaction maps to a direct resource transaction (i. e. JDBC transaction). The entity manager type (JTA or resource-local) is defined at configuration time, when setting up the entity manager factory.

Persistence context scope and Propagation
Persistence context scope can be bounded to a transaction or can be bounded to several transactions(extended transaction scope).

The most common case is to bind the persistence context scope to the current transaction scope. This is only doable when JTA transactions are used. The persistence context is associated with the JTA transaction life cycle. When an entity manager is invoked, the persistence context is also opened, if there is no persistence context associated with the current JTA transaction. Otherwise, the associated persistence context is used. The persistence context ends when the JTA transaction completes.

You can also use an extended persistence context. This can be combined with stateful session beans, if you use a container-managed entity manager: the persistence context is created when an entity manager is retrieved from dependency injection or JNDI lookup , and is kept until the container closes it after the completion of the Remove stateful session bean method. This is a perfect mechanism for implementing a "long" unit of work pattern.

A resource-local entity manager or an entity manager created with EntityManagerFactory.createEntityManager() (application-managed) has a one-to-one relationship with a persistence context and is always (in J2Se mode) extended persistence context.

Friday, July 16, 2010

Finding top N rows

oracle supports specifying order by clause in select statement.
Suppose we what get top n rows by a specific value.

table Run(startTime, ID, priority). To get top N priority items

SELECT p,
startTime, ID
FROM (
SELECT row_number() OVER (ORDER BY priority DESC) p,
startTime, ID
FROM Run
WHERE r > N;