Hi, Everybody
I wanted to share with you a link to one useful site I've recently found.
It allows to find the Jar by the class - that's easy! The wildcards in the class name are also supported.
The site address is:
Jar Finder
Sunday, November 21, 2010
Tuesday, July 6, 2010
SSO solution for Java based web application
Hi, This time I'll keep the post simple, I would just like to recommend the open source java based solution for the single-sign on.
Recently I've had a chance to fiddle with SSO related stuff.
I've chose an outstanding piece of software called CAS
This software provides a simple yet powerful solution for the SSO and implements a lot of different methods of performing the authentication.
I would like to mention that they have a very supportive community, they helped me a lot in resolving some technical issues.
In just a couple of days I was able to come with SPNEGO based solution for the web environment that works against kerberos system.
Although this product seems to be more widespread in the academics, it seems to be really mature and up-to-date.
So, I definitely recommend to consider CAS for the sso related stuff.
Recently I've had a chance to fiddle with SSO related stuff.
I've chose an outstanding piece of software called CAS
This software provides a simple yet powerful solution for the SSO and implements a lot of different methods of performing the authentication.
I would like to mention that they have a very supportive community, they helped me a lot in resolving some technical issues.
In just a couple of days I was able to come with SPNEGO based solution for the web environment that works against kerberos system.
Although this product seems to be more widespread in the academics, it seems to be really mature and up-to-date.
So, I definitely recommend to consider CAS for the sso related stuff.
Tuesday, June 15, 2010
Setting up JPA 2.0 Out-Of-Container
Hi, today I would like to explain how to set up the JPA 2.0 Out of container.
I'll use MySQL as a back-end database And hibernate 3.5 as a persistence provider.
First of all some introduction (really short).
JEE 6 brought us a new persistent standard called JPA 2(Java Persistence Architecture) which is a natural evolution of JPA available from JEE(5).
A popular ORM tool Hibernate 3.5.x provides an implementation of the JPA 2 specification.
While JPA 2.0 is mostly efficient in a managed environment (usually inside application server), sometimes we would just like to come up with a simple use case:
we would like to write a class with a "main" method, configure the JPA 2.0 environment and interact with our relational database management server.
Such a configuration is called "out-of-container".
"Out-of-container" (later OOC for the sake of brevity) configuration has some drawbacks when compared to the "standard" (managed) invocation mode.
- we can't use JTA (transaction control)
- we have to define our domain classes explicitly in the file called "persistence.xml" which is a part of JPA/JPA 2 standard
On the other hand we gain simplicity, fast startup, eliminate the dependency on application server. This makes OOC an attractive solution for unit testing, developing the domain model objects, etc.
So how would we set up a working OOC environment?
First of all, we will need a RDBMS - I'll use MySQL for that.
Next, I'll download Hibernate. The latest stable version at this moment is 3.5.2, so I'll download it from the official Hibernate site
Installing MySQL should not be a problem so I won't cover this here.
I assume that the data base is running and proceed with java related stuff.
First of all we'll create the simple java project in the IDE and put the following list of dependent jars:
- antlr-2.7.6.jar
- commons-collections-3.1.jar
- dom4j-1.6.1.jar
- hibernate-jpa-2.0-api-1.0.0.Final.jar
- hibernate3.jar
- javaassist-3.9.0.GA.jar
- jta-1.1.jar
All of them can be found in the downloaded hibernate distribution archive
I also added the latest versions of the slf4j - logging system:
- slf4j-api-1.6.0.jar
- slf4j-simple-1.6.0.jar
These jars I've downloaded manually here
The last jar we will need is the MySQL jdbc driver. The connector-j can be downloaded from the manufacturer's site here
So we add the
- mysql-connector-java-5.1.12-bin.jar
to the list of our dependencies
Now when all the dependent jars are present we will create a special file called persistence.xml and put there all the information about connection configuration.
According to the JPA standards it should be placed into the META-INF folder of your project like this:
META-INF/persistence.xml
Here is the sample file:
The xml contains definitions of persistence unit, we call it 'testPersistenceUnit' (remember this name, we will use it later) and various configuration stuff (see the comment in the xml file)
Now we'll create a sample domain-object. This is a fairly simple POJO with JPA annotations. The class "User" will have id, first name and last name. Hence the code:
Please, notice that the annotations declared in the 'imports' section are from javax.persistence (JPA 2 annotations ) and not Hibernate specific.
Another important thing is the mapping itself, each property will be mapped to the corresponding column in the database. And the entity itself will be mapped to the table "USERS" (we will create everything we need in the data base later)
Also note, that this class has been listed in the persistence.xml file
And now we will create the last part of the puzzle - the class responsible for initialization of OOC and running the sample JPA code.
Again, I've tried to provide short explanations in the code.
Now this code can be run for the first time. Assuming that the database doesn't have a table "USERS" and in the persistence.xml database/username/password properties are set and the property hibernate.hbm2ddl.auto is defined to be "create":
we will run the program for the first time:
The output will be a lot of configuration related stuff as well as the important line:
Hibernate: insert into USERS (FIRST_NAME, LAST_NAME, id) values (?, ?, ?)
Now the table "Users" has been created and the new row has been inserted into the db
Each time you run the program, the table will be dropped at the very beginning, created from scratch and filled with the sample data.
I hope it was a helpful tutorial, comments are welcome :)
Thanks a lot for attention
Mark Bramnik
I'll use MySQL as a back-end database And hibernate 3.5 as a persistence provider.
First of all some introduction (really short).
JEE 6 brought us a new persistent standard called JPA 2(Java Persistence Architecture) which is a natural evolution of JPA available from JEE(5).
A popular ORM tool Hibernate 3.5.x provides an implementation of the JPA 2 specification.
While JPA 2.0 is mostly efficient in a managed environment (usually inside application server), sometimes we would just like to come up with a simple use case:
we would like to write a class with a "main" method, configure the JPA 2.0 environment and interact with our relational database management server.
Such a configuration is called "out-of-container".
"Out-of-container" (later OOC for the sake of brevity) configuration has some drawbacks when compared to the "standard" (managed) invocation mode.
- we can't use JTA (transaction control)
- we have to define our domain classes explicitly in the file called "persistence.xml" which is a part of JPA/JPA 2 standard
On the other hand we gain simplicity, fast startup, eliminate the dependency on application server. This makes OOC an attractive solution for unit testing, developing the domain model objects, etc.
So how would we set up a working OOC environment?
First of all, we will need a RDBMS - I'll use MySQL for that.
Next, I'll download Hibernate. The latest stable version at this moment is 3.5.2, so I'll download it from the official Hibernate site
Installing MySQL should not be a problem so I won't cover this here.
I assume that the data base is running and proceed with java related stuff.
First of all we'll create the simple java project in the IDE and put the following list of dependent jars:
- antlr-2.7.6.jar
- commons-collections-3.1.jar
- dom4j-1.6.1.jar
- hibernate-jpa-2.0-api-1.0.0.Final.jar
- hibernate3.jar
- javaassist-3.9.0.GA.jar
- jta-1.1.jar
All of them can be found in the downloaded hibernate distribution archive
I also added the latest versions of the slf4j - logging system:
- slf4j-api-1.6.0.jar
- slf4j-simple-1.6.0.jar
These jars I've downloaded manually here
The last jar we will need is the MySQL jdbc driver. The connector-j can be downloaded from the manufacturer's site here
So we add the
- mysql-connector-java-5.1.12-bin.jar
to the list of our dependencies
Now when all the dependent jars are present we will create a special file called persistence.xml and put there all the information about connection configuration.
According to the JPA standards it should be placed into the META-INF folder of your project like this:
META-INF/persistence.xml
Here is the sample file:
The xml contains definitions of persistence unit, we call it 'testPersistenceUnit' (remember this name, we will use it later) and various configuration stuff (see the comment in the xml file)
Now we'll create a sample domain-object. This is a fairly simple POJO with JPA annotations. The class "User" will have id, first name and last name. Hence the code:
Please, notice that the annotations declared in the 'imports' section are from javax.persistence (JPA 2 annotations ) and not Hibernate specific.
Another important thing is the mapping itself, each property will be mapped to the corresponding column in the database. And the entity itself will be mapped to the table "USERS" (we will create everything we need in the data base later)
Also note, that this class has been listed in the persistence.xml file
And now we will create the last part of the puzzle - the class responsible for initialization of OOC and running the sample JPA code.
Again, I've tried to provide short explanations in the code.
Now this code can be run for the first time. Assuming that the database doesn't have a table "USERS" and in the persistence.xml database/username/password properties are set and the property hibernate.hbm2ddl.auto is defined to be "create":
we will run the program for the first time:
The output will be a lot of configuration related stuff as well as the important line:
Hibernate: insert into USERS (FIRST_NAME, LAST_NAME, id) values (?, ?, ?)
Now the table "Users" has been created and the new row has been inserted into the db
Each time you run the program, the table will be dropped at the very beginning, created from scratch and filled with the sample data.
I hope it was a helpful tutorial, comments are welcome :)
Thanks a lot for attention
Mark Bramnik
Friday, April 9, 2010
Data Validation - using the Hibernate Validator
Hi, Recently I've started to fiddle with a Data Validation problem.
Given a data model represented as an object graph of POJO-s, we should validate it.
The data model should contain some declarative validation rules and the validation infrastructure should get the object graph as an input, traverse it and produce the series of validation errors (if any)
I've figured out that the data validation problem has been addressed by JSR 303
The project Hibernate Validator 4.x is a reference implementation of this spec. So I've decided to investigate ;)
This project contains a fairly good tutorial here
So I've started to use this framework in my project. One thing that I've noticed is that the default message resolution wasn't flexible enough for my needs. Obviously after reading the tutorial, I've come to conclusion that I should define a custom "message interpolator". In this article I want to provide an example of how to use it.
My requirements are:
- I would like to override the default message bundle
- I would like define different messages for the same validated entity. For instance, if I have 2 (or more) different usages for the same data model, then theoretically I would like to show the different messages when validating the same data.
I've created the new project by running maven as the tutorial suggests:
mvn archetype:generate -DarchetypeCatalog=http://repository.jboss.com/maven2/archetype-catalog.xml -DgroupId=mark.test -DartifactId=beanvalidation-test -Dversion=1.0-SNAPSHOT -Dpackage=mark.test
This command generated the project with the following list of dependencies:
Now I'm ready to start my tests.
We will need six classes:
Class DataObject will represent our domain data and this class will have the validation annotation defined on it's getters:
Just pay attention to the annotations. The field 'foo' can't be null and The field 'bar' can't be less than 10
Another class we will need is the ResourceBundle storage.
This class is a message bundle container it contains a matrix of strings. There are two columns in this matrix: the column 0 is a key, the column 1 is a message itself.
In this example I've implemented the resouce bundle that can be created from the given stream (in our case it could be a properties file). One can think about the better design, but its just a simple examlpe...
The loaded bundles should be stored in a library and supplied with the unique identifier that will be accessible from the application. This can be done by the class that represents the bundle library and the enum that represents a unique ID:
And now the most interesting parts - The message interpolator itself and the code that actually makes a validation.
The Main class looks like this:
In the main method I:
- build the resource bundles library
- create the validator (see the 'Bootstraping' chapter of the aforementioned tutorial for addition information)
- create a data object
- validate the data object
- reconfigure the message interpolator so that it will take the messages from another source
- validate the data object again
- once more reconfigure the message interpolator
- validate the data object again
Note that I supplied two property files during the library creation.
Each property file contains the various messages that can be used in the framework.
The keys are predefined and can be found in the hibernate-validator-4.0.2.GA.jar
in the file named ValidationMessages.properties
I've redefined the message I need (obviously for the NotNull and for the Size).
If the message is not found in the message bundle, automatically the default bundle will be used...
So, for example, my main_app_bundle.properties file contains the single line:
javax.validation.constraints.NotNull.message=In my application this value may not be null
(I intentionally don't touch the Size message to keep it default here, In real application I would probably redefine them all)
My my_custom_bundle.properties files contains two lines (again to handle NotNull error in my own way):
javax.validation.constraints.NotNull.message=Yet another 'not null' message example
Now the output:
may not be null
must be greater than or equal to 10
=====================
In my application this value may not be null
must be greater than or equal to 10
=====================
Yet another 'not null' message example
In my application this value must be greater than or equal to 10
=====================
The first section as expected shows message that can be found in the default bundle supplied with the framework.
The second section is produced by the second validation invocation on the same object.
This time you can see that the 'not-null' error has been changed to one found in my properties file but the second message remained unchanged
The third section is the result of the third validation call. Here you can see that both of the messages have been redefined
Since the messages appear in the set, we can't do any assumptions about their order.
I would also like to provide the full list of the available keys and default values (in english):
=====================================================================================
javax.validation.constraints.AssertFalse.message=must be false
javax.validation.constraints.AssertTrue.message=must be true
javax.validation.constraints.DecimalMax.message=must be less than or equal to {value}
javax.validation.constraints.DecimalMin.message=must be greater than or equal to {value}
javax.validation.constraints.Digits.message=numeric value out of bounds (<{integer} digits>.<{fraction} digits> expected)
javax.validation.constraints.Future.message=must be in the future
javax.validation.constraints.Max.message=must be less than or equal to {value}
javax.validation.constraints.Min.message=must be greater than or equal to {value}
javax.validation.constraints.NotNull.message=may not be null
javax.validation.constraints.Null.message=must be null
javax.validation.constraints.Past.message=must be in the past
javax.validation.constraints.Pattern.message=must match "{regexp}"
javax.validation.constraints.Size.message=size must be between {min} and {max}
org.hibernate.validator.constraints.Email.message=not a well-formed email address
org.hibernate.validator.constraints.Length.message=length must be between {min} and {max}
org.hibernate.validator.constraints.NotEmpty.message=may not be empty
org.hibernate.validator.constraints.Range.message=must be between {min} and {max}
=====================================================================================
I hope this post was helpful, feel free to comment
Best regards, Mark Bramnik
Given a data model represented as an object graph of POJO-s, we should validate it.
The data model should contain some declarative validation rules and the validation infrastructure should get the object graph as an input, traverse it and produce the series of validation errors (if any)
I've figured out that the data validation problem has been addressed by JSR 303
The project Hibernate Validator 4.x is a reference implementation of this spec. So I've decided to investigate ;)
This project contains a fairly good tutorial here
So I've started to use this framework in my project. One thing that I've noticed is that the default message resolution wasn't flexible enough for my needs. Obviously after reading the tutorial, I've come to conclusion that I should define a custom "message interpolator". In this article I want to provide an example of how to use it.
My requirements are:
- I would like to override the default message bundle
- I would like define different messages for the same validated entity. For instance, if I have 2 (or more) different usages for the same data model, then theoretically I would like to show the different messages when validating the same data.
I've created the new project by running maven as the tutorial suggests:
mvn archetype:generate -DarchetypeCatalog=http://repository.jboss.com/maven2/archetype-catalog.xml -DgroupId=mark.test -DartifactId=beanvalidation-test -Dversion=1.0-SNAPSHOT -Dpackage=mark.test
This command generated the project with the following list of dependencies:
Now I'm ready to start my tests.
We will need six classes:
Class DataObject will represent our domain data and this class will have the validation annotation defined on it's getters:
Just pay attention to the annotations. The field 'foo' can't be null and The field 'bar' can't be less than 10
Another class we will need is the ResourceBundle storage.
This class is a message bundle container it contains a matrix of strings. There are two columns in this matrix: the column 0 is a key, the column 1 is a message itself.
In this example I've implemented the resouce bundle that can be created from the given stream (in our case it could be a properties file). One can think about the better design, but its just a simple examlpe...
The loaded bundles should be stored in a library and supplied with the unique identifier that will be accessible from the application. This can be done by the class that represents the bundle library and the enum that represents a unique ID:
And now the most interesting parts - The message interpolator itself and the code that actually makes a validation.
The Main class looks like this:
In the main method I:
- build the resource bundles library
- create the validator (see the 'Bootstraping' chapter of the aforementioned tutorial for addition information)
- create a data object
- validate the data object
- reconfigure the message interpolator so that it will take the messages from another source
- validate the data object again
- once more reconfigure the message interpolator
- validate the data object again
Note that I supplied two property files during the library creation.
Each property file contains the various messages that can be used in the framework.
The keys are predefined and can be found in the hibernate-validator-4.0.2.GA.jar
in the file named ValidationMessages.properties
I've redefined the message I need (obviously for the NotNull and for the Size).
If the message is not found in the message bundle, automatically the default bundle will be used...
So, for example, my main_app_bundle.properties file contains the single line:
javax.validation.constraints.NotNull.message=In my application this value may not be null
(I intentionally don't touch the Size message to keep it default here, In real application I would probably redefine them all)
My my_custom_bundle.properties files contains two lines (again to handle NotNull error in my own way):
javax.validation.constraints.NotNull.message=Yet another 'not null' message example
Now the output:
may not be null
must be greater than or equal to 10
=====================
In my application this value may not be null
must be greater than or equal to 10
=====================
Yet another 'not null' message example
In my application this value must be greater than or equal to 10
=====================
The first section as expected shows message that can be found in the default bundle supplied with the framework.
The second section is produced by the second validation invocation on the same object.
This time you can see that the 'not-null' error has been changed to one found in my properties file but the second message remained unchanged
The third section is the result of the third validation call. Here you can see that both of the messages have been redefined
Since the messages appear in the set, we can't do any assumptions about their order.
I would also like to provide the full list of the available keys and default values (in english):
=====================================================================================
javax.validation.constraints.AssertFalse.message=must be false
javax.validation.constraints.AssertTrue.message=must be true
javax.validation.constraints.DecimalMax.message=must be less than or equal to {value}
javax.validation.constraints.DecimalMin.message=must be greater than or equal to {value}
javax.validation.constraints.Digits.message=numeric value out of bounds (<{integer} digits>.<{fraction} digits> expected)
javax.validation.constraints.Future.message=must be in the future
javax.validation.constraints.Max.message=must be less than or equal to {value}
javax.validation.constraints.Min.message=must be greater than or equal to {value}
javax.validation.constraints.NotNull.message=may not be null
javax.validation.constraints.Null.message=must be null
javax.validation.constraints.Past.message=must be in the past
javax.validation.constraints.Pattern.message=must match "{regexp}"
javax.validation.constraints.Size.message=size must be between {min} and {max}
org.hibernate.validator.constraints.Email.message=not a well-formed email address
org.hibernate.validator.constraints.Length.message=length must be between {min} and {max}
org.hibernate.validator.constraints.NotEmpty.message=may not be empty
org.hibernate.validator.constraints.Range.message=must be between {min} and {max}
=====================================================================================
I hope this post was helpful, feel free to comment
Best regards, Mark Bramnik
Friday, April 2, 2010
Some tricks with reflection
Hi, everyone!
Today I would like to talk a little about reflection api and some interesting tricks we can do with it.
Basically, reflection allows us to introspect the object's structure during the runtime.
With the help of reflection we can:
- obtain the information about the methods/fields of the object
- obtain the information about superclass/interfaces that the object implements
- obtain the value of the data fields
- invoke the methods of the object dynamically
While in general I believe that the reflection shouldn't be vastly used in a properly designed Object Oriented program, sometimes we just can't live without this very powerful feature. From my experience the reflection based APIs are extensively used in different frameworks when we just don't have any information about the classes that will be used...
In this post I'll try to show some less known usages of the reflection API.
So, here we go :)
1. Instanceof with reflection
We will mimic the well known instanceof operator's behavior with the help of reflection:
The Class java.lang.Number is the common ancestor for Integer, Float, Double and other so-called wrapper classes
So we expect that the following code will produce 'true' twice:
Ok, but we knew that i is castable to Number, so it's not a big deal...
Now how about checking the String:
One could expect that this code would print 'false'. But in fact we can't even compile this code. The error is :
Inconvertible types; can't cast java.lang.String to java.lang.Number
So we can't fool the java compile with obviously false expression.
We can however upcast our String to Object and this code will run as expected.
The output is 'false'
Now lets see how the things can be done with the help of reflection:
Class "java.lang.Class" contains meta information about the object, this is our key to reflection APIs.
We will use its "isAssignableFrom" method that behaves exactly like 'instanceof' operator but makes it regardless the called classes. The method called on the class A will return true iff the parameter (which is also a java.lang.Class) is a successor of class A (or class A itself).
Example:
>>true - because Integer is a subclass of Number
>>false - because String is not a subclass of Number
>>true - because Number can be assigned to Number (upcasted).
>> false - because String is not a subclass of Number
As we see we the same result could be achieved with 'instanceof'.
But this time we don't need the casting (!); and since any object has a getClass() method, we don't need any information about the object we're going to check. This is impossible if we would chose the 'instanceof' approach:
Example:
2. Accessing the private data of the object.
OK, this sounds like a dirty trick, since it seems to break the encapsulation. But sometimes we need to know what is an internal structure of the class.
So how we can do that?
Imagine we have a fairly simple class A defined like this:
Using the traditional object oriented approach we just don't have a way to modify or even read the value of the field foo outside the class A!
So what should we do?
Let's use reflection :)
The problem is that the field is private therefore the program produces an exception during the runtime:
java.lang.IllegalAccessException: Class Test can not access a member of class A with modifiers "private"
So we have to slightly modify the program. We will say to the java runtime environment: "Its ok, I know that I can access this variable"
The program will look like this:
Now the program will run perfectly and print out the value of "foo" field as expected.
Of course its possible to modify the property:
Now the output would be:
5
10
Thats all, hope you found this short article interesting!
Today I would like to talk a little about reflection api and some interesting tricks we can do with it.
Basically, reflection allows us to introspect the object's structure during the runtime.
With the help of reflection we can:
- obtain the information about the methods/fields of the object
- obtain the information about superclass/interfaces that the object implements
- obtain the value of the data fields
- invoke the methods of the object dynamically
While in general I believe that the reflection shouldn't be vastly used in a properly designed Object Oriented program, sometimes we just can't live without this very powerful feature. From my experience the reflection based APIs are extensively used in different frameworks when we just don't have any information about the classes that will be used...
In this post I'll try to show some less known usages of the reflection API.
So, here we go :)
1. Instanceof with reflection
We will mimic the well known instanceof operator's behavior with the help of reflection:
The Class java.lang.Number is the common ancestor for Integer, Float, Double and other so-called wrapper classes
So we expect that the following code will produce 'true' twice:
Ok, but we knew that i is castable to Number, so it's not a big deal...
Now how about checking the String:
One could expect that this code would print 'false'. But in fact we can't even compile this code. The error is :
Inconvertible types; can't cast java.lang.String to java.lang.Number
So we can't fool the java compile with obviously false expression.
We can however upcast our String to Object and this code will run as expected.
The output is 'false'
Now lets see how the things can be done with the help of reflection:
Class "java.lang.Class" contains meta information about the object, this is our key to reflection APIs.
We will use its "isAssignableFrom" method that behaves exactly like 'instanceof' operator but makes it regardless the called classes. The method called on the class A will return true iff the parameter (which is also a java.lang.Class) is a successor of class A (or class A itself).
Example:
>>true - because Integer is a subclass of Number
>>false - because String is not a subclass of Number
>>true - because Number can be assigned to Number (upcasted).
>> false - because String is not a subclass of Number
As we see we the same result could be achieved with 'instanceof'.
But this time we don't need the casting (!); and since any object has a getClass() method, we don't need any information about the object we're going to check. This is impossible if we would chose the 'instanceof' approach:
Example:
2. Accessing the private data of the object.
OK, this sounds like a dirty trick, since it seems to break the encapsulation. But sometimes we need to know what is an internal structure of the class.
So how we can do that?
Imagine we have a fairly simple class A defined like this:
Using the traditional object oriented approach we just don't have a way to modify or even read the value of the field foo outside the class A!
So what should we do?
Let's use reflection :)
The problem is that the field is private therefore the program produces an exception during the runtime:
java.lang.IllegalAccessException: Class Test can not access a member of class A with modifiers "private"
So we have to slightly modify the program. We will say to the java runtime environment: "Its ok, I know that I can access this variable"
The program will look like this:
Now the program will run perfectly and print out the value of "foo" field as expected.
Of course its possible to modify the property:
Now the output would be:
5
10
Thats all, hope you found this short article interesting!
Thursday, April 1, 2010
CGLIB introduction
Today I would like to briefly discuss the bytecode generation framework, CGLIB.
There are a lot of these frameworks, each one works at the different level of abstraction.
Recently I was looking for a high-level framework that would let me to dynamically change my classes providing its proxy and substituting the functionality of some methods.
While the most obvious jdk proxies can do the job (java.lang.reflect.Proxy), I've figured out, that when I don't have both an interface and implementation of my to-be-proxified class, it just doesn't work. So I've found another solution, a library called CGLIB
The only significant drawback for me was a lack of comprehensive documentation, in fact I've found only one decent tutorial here (It could be great if someone could point me on more tutorials about this tool).
Anyway, I think that a beginner's level introduction can't harm so I fill the gap and share the experience :)
So CGLIB is a bytecode generation library, that relies on low-level
ASM framework.
So in order to create a working example we'll need to open a regular java project and add two jars as a dependency (the latest versions available at the moment):
- cglib-2.2.jar
- asm-all-3.2.jar
We will 'proxify' the mock Algorithm class which is supposed to implement some long-running algorithm. We would like to measure its execution time.
So we create our algorithm like this:
Now the most interesting part of the program:
We'll create a class that adds the 'measurements'. This class will be used by CGLIB to proxify our algorithm, so it should implement net.sf.cglib.proxy.MethodInterceptor
The class looks like this:
The last class is the main class. Here we will actually create the proxy so here we'll see some CGLIB related code:
The output of this program is predictable :)
Before
running the algorithm
After
Took: 500 ms
Thats all, thanks for your attention
Mark Bramnik
There are a lot of these frameworks, each one works at the different level of abstraction.
Recently I was looking for a high-level framework that would let me to dynamically change my classes providing its proxy and substituting the functionality of some methods.
While the most obvious jdk proxies can do the job (java.lang.reflect.Proxy), I've figured out, that when I don't have both an interface and implementation of my to-be-proxified class, it just doesn't work. So I've found another solution, a library called CGLIB
The only significant drawback for me was a lack of comprehensive documentation, in fact I've found only one decent tutorial here (It could be great if someone could point me on more tutorials about this tool).
Anyway, I think that a beginner's level introduction can't harm so I fill the gap and share the experience :)
So CGLIB is a bytecode generation library, that relies on low-level
ASM framework.
So in order to create a working example we'll need to open a regular java project and add two jars as a dependency (the latest versions available at the moment):
- cglib-2.2.jar
- asm-all-3.2.jar
We will 'proxify' the mock Algorithm class which is supposed to implement some long-running algorithm. We would like to measure its execution time.
So we create our algorithm like this:
Now the most interesting part of the program:
We'll create a class that adds the 'measurements'. This class will be used by CGLIB to proxify our algorithm, so it should implement net.sf.cglib.proxy.MethodInterceptor
The class looks like this:
The last class is the main class. Here we will actually create the proxy so here we'll see some CGLIB related code:
The output of this program is predictable :)
Before
running the algorithm
After
Took: 500 ms
Thats all, thanks for your attention
Mark Bramnik
Wednesday, March 31, 2010
Connecting Groovy to the Derby DB
Hi, today was reading a great book 'Groovy in action', a chapter about the Data Base programming.
Authors use hsql db, so I've asked myself how to connect to Apache Derby
Here I've found the way to do that,but they connect via the driver manager which is the less preferable way to use the jdbc. AFAIK java.sql.DataSource is much better.
So, I've come up with the following solution:
- Create a groovy project in your favorite way.
- Ensure you have a jar derby.jar in your classpath.
You can find the needed jar inside the derby distribution(the latest one available for a moment) in the lib directory.
Now lets create a groovy script that looks as follows:
That's all, very easy!
Hope you've found this post useful!
Thanks a lot for attention
Authors use hsql db, so I've asked myself how to connect to Apache Derby
Here I've found the way to do that,but they connect via the driver manager which is the less preferable way to use the jdbc. AFAIK java.sql.DataSource is much better.
So, I've come up with the following solution:
- Create a groovy project in your favorite way.
- Ensure you have a jar derby.jar in your classpath.
You can find the needed jar inside the derby distribution(the latest one available for a moment) in the lib directory.
Now lets create a groovy script that looks as follows:
That's all, very easy!
Hope you've found this post useful!
Thanks a lot for attention
Tuesday, March 30, 2010
Java Dates
Hi everybody.
In this post I've decided to discuss the java date's related possible issues.
We will talk about java timezones, dates, switching to the daylight saving time, etc. Recently I had a chance to explore this theme, so here are my thoughts and conclusions. Hope you'll find it useful.
Here we go.
Basically the date as we see it in our computers is comprised of
- The base (GMT == UTC)
- The offset (in hours) that denotes our timezone.
For example Asia/Jerusalem timezone = GMT (base) + 2 (2 hours offset).
The 'base' time is usually taken from the underlying Operating System, but the offset is a tricky part here.
The timezone differs in the different geographical locations in the world, and this is a kind of "static" information. We can always know which timezone we belong to just by our geografical location and its always the same timezone.
The "dynamic" part adds a lot of headache when it comes to switching to the Daylight Saving Time (DST). In different countries governments decide when to switch to the DST (in some countries there is no such a thing at all).
The are two such a switches. Usually on spring we add one hour to our offsets. Somewhere during the autumn we switch back (cancel the DST).
For example (I'll continue with Asia/Jerusalem timezone here):
During the DST period, we'll get
GMT + 3 (3 hours offset)
When the DST is switched off we'll get GMT + 2
So the main question here is when do we switch to the DST back and forth.
And here come some bad news: its not constantly the same time, but rather changes each year (well, at least it can be so). In general case the switch can't be predicted since it can be fulfilled as a result of the government decisions which can be theoretically taken each year. AFAIK in most of the countries its not so, but still we can't refer to this piece of information as a static content.
Ok, now, after some theoretical insights let's get down to the java implementation.
Java has been designed portable language so it should work in the same way on different OSes.
Unix and Linux have a "predefined" table for all the timezones.
Windows on the other hand is aware only of a change within the next year (as far as I understand Windows 7 fixed this behavior and now it more resembles Linux implementation but for those of us who don't have yet Windows 7 on their machines its still relevant :) ).
Java language has a very solid support of dates and times but its implemented in a very specific manner.
So JRE developers come with the following solution:
- The base time is really taken from the underlying OS.
- The offset part is determined from the custom tables that are a part of the JRE distribution.
This (to some extent) resembles Linux implementation. But its important to understand that Java doesn't deal with the Linux Tables/information from the windows registry but decides by itself about the offset and DST on & off periods.
Of course such a design, while provides portability, has its own drawbacks:
- We said that the information about the DST can become obsolete theoretically each year (when the new, unpredictible-beforehands decision comes).
- JRE developers should maintain the information about the timezones and DST switches all over the world and always be up-to-date!
When we're connected to the internet Java can check for the update and offer to download the latest JRE (well, it depends on the JRE installation options, but this is not our main focus here).
However for organizations running the JRE in LAN and those who don't have a direct internet connection it can be a tedious task to update the JRE.
Each version of JRE comes with the up-to-date table of timezones and DST periods (of course which is relevant when the version is published).
It can be found in %{JRE_INSTALLATION_HOME}/lib/zi folder and physically its just a set of binary files (a file for each timezone).
Linux also has such a binary table. Lets see what information can really be found there:
For the current year:
>> zdump -v Asia/Jerusalem | grep 2010
Asia/Jerusalem Thu Mar 25 23:59:59 2010 UTC = Fri Mar 26 01:59:59 2010 IST isdst=0 gmtoff=7200
Asia/Jerusalem Fri Mar 26 00:00:00 2010 UTC = Fri Mar 26 03:00:00 2010 IDT isdst=1 gmtoff=10800
Asia/Jerusalem Sat Sep 11 22:59:59 2010 UTC = Sun Sep 12 01:59:59 2010 IDT isdst=1 gmtoff=10800
Asia/Jerusalem Sat Sep 11 23:00:00 2010 UTC = Sun Sep 12 01:00:00 2010 IST isdst=0 gmtoff=7200
Here by convention UTC means the 'base' time,
IST = Israel Standard Time (the base + offset with the DST switched off)
IDT = Israel Daylight saving Time ( the base + offset with the DST switched on)
The output is 4 lines. The first two lines denote switching the DST on and the last two line show when the DST period will end.
Unlike Linux, Java doesn't allow to directly see the information in the zi directory (no third-party utility is available as far as I know). Moreover Linux allows to extend the table by our own rules (zic - zone info compiler will do that), but Java doesn't.
So how we can influence this information in Java?
- First of all consider to use tzupdater a utility provided my the jre maintainer. I know that Oracle (Sun) provide such a utility for their jre distribution.
This utility is a jar that updates the zi folder with the recent information.
Some Caveats:
- This still doesn't allow to see the current state of the tables
- If you run the old jre version (1.0 - 1.3) you can't use tzupdater. So this solution is applicable only for those of us running the jre 1.4+
- If you're running java on platforms that are not directly supported by Oracle (Sun), for example HP-UX or jrockit, you should consider to download the tzupdater from the site of HP and not from Oracle, the Oracle's tzupdater just won't work.
- Figure out whether your current java distribution is ready for the next DST switch.
There are some methods of doing that:
The output is as follows:
Tue Mar 30 08:27:52 IDT 2010
It shows that now I have the DST switched on.
The program that prints the current timezone is also fairly simple:
The output (again, I'll stick to Asia/Jerusalem timezone) is as follows:
sun.util.calendar.ZoneInfo[id="Asia/Jerusalem",offset=7200000,dstSavings=3600000,
useDaylight=true,transitions=143,
lastRule=java.util.SimpleTimeZone[id=Asia/Jerusalem,
offset=7200000,dstSavings=3600000,
useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=26,
startDayOfWeek=6,startTime=7200000,startTimeMode=0,
endMode=1,endMonth=8,endDay=13,endDayOfWeek=0,endTime=7200000,
endTimeMode=0]]
One can see the similar information as in the linux zoneinfo table but in the different format.
Any java program can be run with special JVM parameter: -Duser.timezone=_THE_TIMEZONE_
* this works also when using web-start of course.
We should consider using this parameter in the situations when:
- Java is unable to determine the current timezone for some reason (I believe It should get down to wrongPC/Server configurations)
- We have an old jre in our legacy system and don't want to touch it :)
- We want to decide by ourselves what is the needed offset.
The parameter can have one of the possible values:
Conclusions:
- Java has a portable but quite complicated architecture for the date/time/timezones.
- Java maintains its own timezone table (the set of rules) in a proprietary binary format
- tzupdater should be used in order to provide our jre/jdk distribution with the most up-to-date information
- there is still a way to "force" java to ignore its internal timezone table by means of running the program with -Duser.timezone option
I hope you've found this post helpful.
Thanks a lot for attention
Mark Bramnik
In this post I've decided to discuss the java date's related possible issues.
We will talk about java timezones, dates, switching to the daylight saving time, etc. Recently I had a chance to explore this theme, so here are my thoughts and conclusions. Hope you'll find it useful.
Here we go.
Basically the date as we see it in our computers is comprised of
- The base (GMT == UTC)
- The offset (in hours) that denotes our timezone.
For example Asia/Jerusalem timezone = GMT (base) + 2 (2 hours offset).
The 'base' time is usually taken from the underlying Operating System, but the offset is a tricky part here.
The timezone differs in the different geographical locations in the world, and this is a kind of "static" information. We can always know which timezone we belong to just by our geografical location and its always the same timezone.
The "dynamic" part adds a lot of headache when it comes to switching to the Daylight Saving Time (DST). In different countries governments decide when to switch to the DST (in some countries there is no such a thing at all).
The are two such a switches. Usually on spring we add one hour to our offsets. Somewhere during the autumn we switch back (cancel the DST).
For example (I'll continue with Asia/Jerusalem timezone here):
During the DST period, we'll get
GMT + 3 (3 hours offset)
When the DST is switched off we'll get GMT + 2
So the main question here is when do we switch to the DST back and forth.
And here come some bad news: its not constantly the same time, but rather changes each year (well, at least it can be so). In general case the switch can't be predicted since it can be fulfilled as a result of the government decisions which can be theoretically taken each year. AFAIK in most of the countries its not so, but still we can't refer to this piece of information as a static content.
Ok, now, after some theoretical insights let's get down to the java implementation.
Java has been designed portable language so it should work in the same way on different OSes.
Unix and Linux have a "predefined" table for all the timezones.
Windows on the other hand is aware only of a change within the next year (as far as I understand Windows 7 fixed this behavior and now it more resembles Linux implementation but for those of us who don't have yet Windows 7 on their machines its still relevant :) ).
Java language has a very solid support of dates and times but its implemented in a very specific manner.
So JRE developers come with the following solution:
- The base time is really taken from the underlying OS.
- The offset part is determined from the custom tables that are a part of the JRE distribution.
This (to some extent) resembles Linux implementation. But its important to understand that Java doesn't deal with the Linux Tables/information from the windows registry but decides by itself about the offset and DST on & off periods.
Of course such a design, while provides portability, has its own drawbacks:
- We said that the information about the DST can become obsolete theoretically each year (when the new, unpredictible-beforehands decision comes).
- JRE developers should maintain the information about the timezones and DST switches all over the world and always be up-to-date!
When we're connected to the internet Java can check for the update and offer to download the latest JRE (well, it depends on the JRE installation options, but this is not our main focus here).
However for organizations running the JRE in LAN and those who don't have a direct internet connection it can be a tedious task to update the JRE.
Each version of JRE comes with the up-to-date table of timezones and DST periods (of course which is relevant when the version is published).
It can be found in %{JRE_INSTALLATION_HOME}/lib/zi folder and physically its just a set of binary files (a file for each timezone).
Linux also has such a binary table. Lets see what information can really be found there:
For the current year:
>> zdump -v Asia/Jerusalem | grep 2010
Asia/Jerusalem Thu Mar 25 23:59:59 2010 UTC = Fri Mar 26 01:59:59 2010 IST isdst=0 gmtoff=7200
Asia/Jerusalem Fri Mar 26 00:00:00 2010 UTC = Fri Mar 26 03:00:00 2010 IDT isdst=1 gmtoff=10800
Asia/Jerusalem Sat Sep 11 22:59:59 2010 UTC = Sun Sep 12 01:59:59 2010 IDT isdst=1 gmtoff=10800
Asia/Jerusalem Sat Sep 11 23:00:00 2010 UTC = Sun Sep 12 01:00:00 2010 IST isdst=0 gmtoff=7200
Here by convention UTC means the 'base' time,
IST = Israel Standard Time (the base + offset with the DST switched off)
IDT = Israel Daylight saving Time ( the base + offset with the DST switched on)
The output is 4 lines. The first two lines denote switching the DST on and the last two line show when the DST period will end.
Unlike Linux, Java doesn't allow to directly see the information in the zi directory (no third-party utility is available as far as I know). Moreover Linux allows to extend the table by our own rules (zic - zone info compiler will do that), but Java doesn't.
So how we can influence this information in Java?
- First of all consider to use tzupdater a utility provided my the jre maintainer. I know that Oracle (Sun) provide such a utility for their jre distribution.
This utility is a jar that updates the zi folder with the recent information.
Some Caveats:
- This still doesn't allow to see the current state of the tables
- If you run the old jre version (1.0 - 1.3) you can't use tzupdater. So this solution is applicable only for those of us running the jre 1.4+
- If you're running java on platforms that are not directly supported by Oracle (Sun), for example HP-UX or jrockit, you should consider to download the tzupdater from the site of HP and not from Oracle, the Oracle's tzupdater just won't work.
- Figure out whether your current java distribution is ready for the next DST switch.
There are some methods of doing that:
- Just change the base time on your machine and see how java reacts.
- Write a simple java program that prints a date before and after the DST switch.
- Write a simple java program that prints the current TimeZone and see when the java is supposed to apply the DST switch
The output is as follows:
Tue Mar 30 08:27:52 IDT 2010
It shows that now I have the DST switched on.
The program that prints the current timezone is also fairly simple:
The output (again, I'll stick to Asia/Jerusalem timezone) is as follows:
sun.util.calendar.ZoneInfo[id="Asia/Jerusalem",offset=7200000,dstSavings=3600000,
useDaylight=true,transitions=143,
lastRule=java.util.SimpleTimeZone[id=Asia/Jerusalem,
offset=7200000,dstSavings=3600000,
useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=26,
startDayOfWeek=6,startTime=7200000,startTimeMode=0,
endMode=1,endMonth=8,endDay=13,endDayOfWeek=0,endTime=7200000,
endTimeMode=0]]
One can see the similar information as in the linux zoneinfo table but in the different format.
Any java program can be run with special JVM parameter: -Duser.timezone=_THE_TIMEZONE_
* this works also when using web-start of course.
We should consider using this parameter in the situations when:
- Java is unable to determine the current timezone for some reason (I believe It should get down to wrongPC/Server configurations)
- We have an old jre in our legacy system and don't want to touch it :)
- We want to decide by ourselves what is the needed offset.
The parameter can have one of the possible values:
- ID of the entry in the java internal time zone table (which is nothing more than the set of rules when to switch to DST on and of and what is the current offset). Example: >>java -Duser.timezone=Asia/Jerusalem MyProg
- The "Hard-coded" offset value. Example: >>java -Duser.timezone=GMT+2 MyProg
Conclusions:
- Java has a portable but quite complicated architecture for the date/time/timezones.
- Java maintains its own timezone table (the set of rules) in a proprietary binary format
- tzupdater should be used in order to provide our jre/jdk distribution with the most up-to-date information
- there is still a way to "force" java to ignore its internal timezone table by means of running the program with -Duser.timezone option
I hope you've found this post helpful.
Thanks a lot for attention
Mark Bramnik
Subscribe to:
Posts (Atom)