Read more on WittyReader.com
Thursday, July 3, 2014
WittyReader: More than a speed reading tool
WittyReader is a reading tool and provide the possibility to you to read web pages, blogs, twitter feeds, text books, rss feeds on your smartphone while traveling. Forget the zooming, scrolling, positioning, With WittyReader it’s just a single tip and you can enjoy reading.
Labels:
gails,
ios,
reader,
reading,
reading tool,
speed reading
Saturday, November 9, 2013
Follow me on Tumblr
Follow me on Tumblr and read about Groovy and Grails, SmartBiobank and view my photos: szpetip.tumblr.com.
Developing in Groovy and Grails
In the last two years, I abandoned the pure Java EE as primary developing framework, this is the main reason, why this blog doesn't have new posts.
We had to face with new challenges and the pure Java EE technology was not flexible enough to support our development processes. We thought, we should try one of the new dynamic web application framework. The Groovy on Grails was the chosen one.
It was a big decision. Migration to a new technology in a country, where nobody knows nothing except .NET and Java was not an easy task. Our developer team was really enthusiastic, we made some pilot projects and drawn the consequences: Let's do it!
Our first live project with Groovy and Grails was the SmartBiobank (http://smartbiobank.com).
SmartBiobank's development is continuous, but I'm absolutely sure:
I can tell you our experiences about Groovy and Grails:
But of course, there are some disadvantages:
If you are curious, try out Groovy and Grails and check out SmartBiobank!
We had to face with new challenges and the pure Java EE technology was not flexible enough to support our development processes. We thought, we should try one of the new dynamic web application framework. The Groovy on Grails was the chosen one.
It was a big decision. Migration to a new technology in a country, where nobody knows nothing except .NET and Java was not an easy task. Our developer team was really enthusiastic, we made some pilot projects and drawn the consequences: Let's do it!
Our first live project with Groovy and Grails was the SmartBiobank (http://smartbiobank.com).
SmartBiobank is a free, online biobank software designed to help clinicians, lab biologists and researchers to integrate translational research elements into one single system. SmartBiobank can store, manage and analyze biospecimen data, clinical data as well as experimental data. SmartBiobank is fully customizable. Users can choose from several types of questions and then build forms freely from these questions. Forms are then linked to patients or samples creating the basic structure of the project.
SmartBiobank's development is continuous, but I'm absolutely sure:
Changing to Groovy and Grails was a brilliant idea!
I can tell you our experiences about Groovy and Grails:
- Our development process is five-six times as fast! Just imagine, you can work as fast as a complete team.
- Source code is more transparent and no sucks with jar files, application layouts, rigid EE design patterns.
But of course, there are some disadvantages:
- Only experienced developers should use Groovy and Grails and other dynamic languages: No compiler errors, less code competition, typeless objects, closures.
- We posted a job advertisement and got a call from the advertising company, what a hell is this "Groovy on Grails developer", this is a fake position or a kind of Java or .NET developer.
- Of course, nobody applied the job.
If you are curious, try out Groovy and Grails and check out SmartBiobank!
Sunday, July 4, 2010
Last post
Unfortunately I'm closing my blog this week. I can't spend time with posting and moderating out Chinese people who write junk comments all the time.
I have had ~9000 visitor from 111 country all over the world in the last two year, thanks for it!
Bye,
...szpetip
I have had ~9000 visitor from 111 country all over the world in the last two year, thanks for it!
Bye,
...szpetip
Saturday, July 4, 2009
String puzzle
A short, but interesting puzzle.
Question
What does the following program print:
Answer
When you run the code, you get the answer: 2.
Why?
The compiler translates Unicode escapes into the characters they represent before it parses the program into tokens, such as strings literals. As you see, NetBeans IDE doesn't know it, it present the code like a string with a length() method.
Question
What does the following program print:
Answer
When you run the code, you get the answer: 2.
Why?
The compiler translates Unicode escapes into the characters they represent before it parses the program into tokens, such as strings literals. As you see, NetBeans IDE doesn't know it, it present the code like a string with a length() method.
Saturday, May 16, 2009
NetBeans 6.5.1 generates invalid web.xml
If you use NetBeans 6.5.1 and you want to add a new servlet to the project, the IDE generate an invalid web.xml file and you will be not able to deploy the application.
The problem
If you try to deploy the web application into an application container, then you get an exception like this:
The solution
Solving this problem is very easy:
The problem
If you try to deploy the web application into an application container, then you get an exception like this:
org.apache.catalina.startup.ContextConfig applicationWebConfig
SEVERE: Parse error in application web.xml file at jndi:/localhost/XXXXXX/WEB-INF/web.xml
java.lang.IllegalArgumentException: Servlet mapping specifies an unknown servlet name XXXXXX
The solution
Solving this problem is very easy:
- Open your web.xml file and choose the XML view to see the xml code.
- Cut all <servlet-mapping> tags and put them back after the <servlet> tags.
Friday, May 15, 2009
Solve MySQL server drops and close connections in connection pool
If you get "Last packet sent to the server was XX ms ago." error in your application that want to access MySQL database or you want to know, how to create a connection pool using Tomcat server and DataSource then this is your post.
Connection pooling with MySQL
Using connection pool is a good way to increase your web application speed. If you create a connection pool in your application, using a MySQl server, in the first morning you will see, the database server drops all of the connections in the pool.
This is because MySQL drops connections after 8 hours idle period. There are many solution in the web, some are working, some aren't working, but the most of them are hacking.
I present an elegant solution to this typically problem, caused by MySQL server.
The best solution - Commons DBCP
Download Commons DBCP
The Apache Commons project has a very useful connection pool implementation, called Commons DBCP.
To use Commons DBCP,
Configuring datasource - Tomcat server, server.xml
In my solution, the datasource is defined as a global resource in the server.xml of the Tomcat. To do this, edit the server.xml file in the conf directory in your Tomcat server and add some code line like this between the <GlobalNamingResources> </GlobalNamingResources> tags:
Parameters descriptions are availables here, in nutshell:
name - The datasource will be registred with this name in the naming context.
auth - The authentication type of the resource. Set to Container.
type - The resource type. Set to javax.sql.DataSource to create a datasource.
maxAcive - The maximum number of active connections that can be allocated from this pool at the same time, or negative for no limit.
maxIdele - The maximum number of connections that can remain idle in the pool, without extra ones being released, or negative for no limit.
maxWait - The maximum number of milliseconds that the pool will wait (when there are no available connections) for a connection to be returned before throwing an exception, or -1 to wait indefinitely.
timeBetweenEvictionRunsMillis - The number of milliseconds to sleep between runs of the idle object evictor thread. When non-positive, no idle object evictor thread will be run.
minEvictableIdleTimeMillis - The minimum amount of time an object may sit idle in the pool before it is eligable for eviction by the idle object evictor (if any).
factory - The factory, that provide the connections, to use Commons DBCP, use org.apache.commons.dbcp.BasicDataSourceFactory.
userName - The user name to access your database.
password - The password to access your database.
driverClassName - The driver class to access the database, in this case com.mysql.jdbc.Driver. The driver file must be copied into the lib directory of the Tomcat server.
url - The database url.
testOnBorrow - The indication of whether objects will be validated before being borrowed from the pool. If the object fails to validate, it will be dropped from the pool, and we will attempt to borrow another. Set to true.
testOnReturn - The indication of whether objects will be validated before being returned to the pool. Set to true.
validationQuery - The SQL query that will be used to validate connections from this pool before returning them to the caller. If specified, this query must be an SQL SELECT statement that returns at least one row.
Configuring datasource - Web application, context.xml
To access the defined global resource, modify the context.xml file in your web application. Open the context.xml with your favorite editor and put the following code between the <Context> </Context> tags:
The global parameter is the global name of the defined resource in the server.xml, the name parameter is the name of the resource in our context, type is like in server.xml, the type of the resource, in this case javax.sql.DataSource.
Getting a connection from the pool
We're ready to get a connection from the pool and use it in a Hibernate transaction. The code:
Tips
You must restart your Tomcat server after you copy something into lib directory or edit the server.xml file.
Connection pooling with MySQL
Using connection pool is a good way to increase your web application speed. If you create a connection pool in your application, using a MySQl server, in the first morning you will see, the database server drops all of the connections in the pool.
This is because MySQL drops connections after 8 hours idle period. There are many solution in the web, some are working, some aren't working, but the most of them are hacking.
I present an elegant solution to this typically problem, caused by MySQL server.
The best solution - Commons DBCP
Download Commons DBCP
The Apache Commons project has a very useful connection pool implementation, called Commons DBCP.
To use Commons DBCP,
- download the required jar file from the project page (DBCP Download),
- copy it into the lib directory in your Tomcat server and add to your project, where you want to use the connection pool.
Configuring datasource - Tomcat server, server.xml
In my solution, the datasource is defined as a global resource in the server.xml of the Tomcat. To do this, edit the server.xml file in the conf directory in your Tomcat server and add some code line like this between the <GlobalNamingResources> </GlobalNamingResources> tags:
<resource name="jdbc/sampleDB" auth="Container" type="javax.sql.DataSource" maxActive="15" maxidle="10" maxwait="10000" timeBetweenEvictionRunsMillis="10000" minEvictableIdleTimeMillis="60000" factory="org.apache.commons.dbcp.BasicDataSourceFactory" username="XXXXXXXX" password="XXXXXXX" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/sampledatabase" testOnBorrow="true" testOnReturn="true" validationQuery="select count(*) from TABLENAME" />
Parameters descriptions are availables here, in nutshell:
name - The datasource will be registred with this name in the naming context.
auth - The authentication type of the resource. Set to Container.
type - The resource type. Set to javax.sql.DataSource to create a datasource.
maxAcive - The maximum number of active connections that can be allocated from this pool at the same time, or negative for no limit.
maxIdele - The maximum number of connections that can remain idle in the pool, without extra ones being released, or negative for no limit.
maxWait - The maximum number of milliseconds that the pool will wait (when there are no available connections) for a connection to be returned before throwing an exception, or -1 to wait indefinitely.
timeBetweenEvictionRunsMillis - The number of milliseconds to sleep between runs of the idle object evictor thread. When non-positive, no idle object evictor thread will be run.
minEvictableIdleTimeMillis - The minimum amount of time an object may sit idle in the pool before it is eligable for eviction by the idle object evictor (if any).
factory - The factory, that provide the connections, to use Commons DBCP, use org.apache.commons.dbcp.BasicDataSourceFactory.
userName - The user name to access your database.
password - The password to access your database.
driverClassName - The driver class to access the database, in this case com.mysql.jdbc.Driver. The driver file must be copied into the lib directory of the Tomcat server.
url - The database url.
testOnBorrow - The indication of whether objects will be validated before being borrowed from the pool. If the object fails to validate, it will be dropped from the pool, and we will attempt to borrow another. Set to true.
testOnReturn - The indication of whether objects will be validated before being returned to the pool. Set to true.
validationQuery - The SQL query that will be used to validate connections from this pool before returning them to the caller. If specified, this query must be an SQL SELECT statement that returns at least one row.
Configuring datasource - Web application, context.xml
To access the defined global resource, modify the context.xml file in your web application. Open the context.xml with your favorite editor and put the following code between the <Context> </Context> tags:
<ResourceLink global="jdbc/sampleDB" name="jdbc/sampleDB" type="javax.sql.DataSource"/>
The global parameter is the global name of the defined resource in the server.xml, the name parameter is the name of the resource in our context, type is like in server.xml, the type of the resource, in this case javax.sql.DataSource.
Getting a connection from the pool
We're ready to get a connection from the pool and use it in a Hibernate transaction. The code:
...
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.sql.Connection;
...
public void someMethod() throws Exception {
//Getting the initial context.
Context initCtx = new InitialContext();
//Getting the env context from the initial context,
// where the resources are defined.
Context envCtx = (Context) initCtx.lookup("java:comp/env");
//Getting the datasource from the env context.
//The lookup parameter must be the name parameter
// of the ResourceLink tag in the application's context,xml.
DataSource dataSource = (DataSource) envCtx.lookup("jdbc/sampleDB");
//Getting a connection from the datasource.
Connection connection = dataSource.getConnection();
//sessionFactory must be set before use here, setting
// sessiobFactory is depend on the type of Hibernate
// type and version.
try {
Session session = sessionFactory.openSession(connection);
...
//Use the session
...
} catch(Exception ex) {
//Very important exception handling methods comes here
...
} finally {
//finally statement is very important if you use connection
// from datasource. if you don't use then the connection
// can be stuck and it will be not more available.
try {
//If you use datasource, closing the sessions are as important as
// opeining them.
session.close();
} catch(Excedption ex) { ... }
}
...
Tips
You must restart your Tomcat server after you copy something into lib directory or edit the server.xml file.
Labels:
commons dbcp,
connection pool,
context.xml,
database,
datasource,
hibernate,
java,
mysql,
server.xml,
tomcat,
web application
Tuesday, February 3, 2009
Did you know: Static import
Static Import is a very simply and unnecessary opportunity in Java.
Static Import
Static Import
The static import construct allows unqualified access to static members without inheriting from the type containing the static members. Instead, the program imports the members, either individually:
import static java.lang.Math.PI;or:
import static java.lang.Math.*;
Once the static members have been imported, they may be used without qualification:
double r = cos(PI * theta);
It's easy and unnecessary as I said.
Monday, February 2, 2009
Protected Access Modifier Facts
I show an interesting example to the protected access modifier.
Our first file, Animal.java in package world:
Our second file, Animal.java in package africa:
Our third file, Lion.java in package africa:
Our first file, Animal.java in package world:
01. package world;
02. public class Animal {
03. protected int age;
04. }
Our second file, Animal.java in package africa:
01. package africa;
02. import world.Animal;
03. public class Zebra extends Animal {
04. public void sayAge() {
05. System.out.println("My age is "+age); //Works well, age is protected;
06. }
07. public void sayFriendAge() {
08. Animal friend = new Animal();
09. System.out.println("My fried's age is " + friend.age ); //Compile error, age is accessible
10. // through inheritance
11. }
12. }
Our third file, Lion.java in package africa:
01. package africa;
02. public class Lion {
03. public void sayZebraAge() {
04. Zebra zebra = new Zebra();
05. System.out.println("Zebra's age is " + zebra.age ) ; //Compile error, Zebra and Lion are
06. // in the same package, but age is protected and only available using inheritance, Lion
07. // can't see it.
08. }
09. }
Wednesday, December 31, 2008
Some interesting facts from year 2008
You, visitors
I have had visitors from 73 country. This countries from Google Analytics:
On the map:

Search Engines
I searched the "Java Blog" (include quote marks) expression in some search engine, the result was:
Keyword java give 34,600,000 results in Google, 258,000,000 in MSN, 70,000,000 in Yahoo.
Posts
20 posts have been written, this is the 21th. First post is written at June 21, 2008.
Comments
I have had only one comment from you, I hope number of comments will be increased.
I have had visitors from 73 country. This countries from Google Analytics:
|
|
|

Search Engines
I searched the "Java Blog" (include quote marks) expression in some search engine, the result was:
- Google: I was the 41, Google PageRank give me 1/10.
- MSN: I tried, but didn't find myself in first 100.
- Yahoo: I tried, but didn't find myself in first 100.
Keyword java give 34,600,000 results in Google, 258,000,000 in MSN, 70,000,000 in Yahoo.
Posts
20 posts have been written, this is the 21th. First post is written at June 21, 2008.
Comments
I have had only one comment from you, I hope number of comments will be increased.
Friday, November 28, 2008
Show Image In JTable
In this short post I present, how can we put and show images in JTable component.
Problem
Sometimes we need to put and show images in JTable. A typical situation is when we have a boolean true or false and we don't want to write true/false or yes/no captions.
Solution
The solution is very simply. We have to override the
method of TableModel class, like this:
I hope it will be useful.
Problem
Sometimes we need to put and show images in JTable. A typical situation is when we have a boolean true or false and we don't want to write true/false or yes/no captions.
Solution
The solution is very simply. We have to override the
getColumnClass(int columnIndex)
method of TableModel class, like this:
DefaultTableModel model = new DefaultTableModel() {
@Override
public Class getColumnClass(int columnIndex) {
//Set the index of the column, where the images will be.
final int imageIndex = 5;
return columnIndex == imageIndex ? ImageIcon.class : Object.class;
}
};
I hope it will be useful.
Tuesday, November 25, 2008
Solve IllegalStateException: Illegal to call this method from injected, managed EntityManager
Problem
If we injected an EntityManager into our SessionBean and call the entityManager.getTransaction().begin() method then
IllegalStateException: Illegal to call this method from injected, managed EntityManager
exception is threw.
Java Enterprise version: JEE5
Used server: JBOSS 5.0.0.RC1
EJB version: EJB3
Why did this problem occur?
We wanted to use User-managed transaction, but this is not supported this way.
Solution
To solve this problem, we should use UserTransaction. To do this, inject a javax.ejb.SessionContext instance as Resource:
After this we can get an UserTransaction instrance in our method this way:
I hope it will be useful.
If we injected an EntityManager into our SessionBean and call the entityManager.getTransaction().begin() method then
IllegalStateException: Illegal to call this method from injected, managed EntityManager
exception is threw.
Java Enterprise version: JEE5
Used server: JBOSS 5.0.0.RC1
EJB version: EJB3
Why did this problem occur?
We wanted to use User-managed transaction, but this is not supported this way.
Solution
To solve this problem, we should use UserTransaction. To do this, inject a javax.ejb.SessionContext instance as Resource:
@Resource
SessionContext sc;
After this we can get an UserTransaction instrance in our method this way:
public void someMethod() {
UserTransaction ut = scgetUserTransaction();
ut.begin();
//We have an active transaction, we can access database use EntityManager intance.
ut.commit();
}
I hope it will be useful.
Labels:
ejb,
entitymanager,
illegalstateexception,
java,
jboss,
solution
Saturday, October 25, 2008
Big Java Blog is continued
Dear Visitors,
unfortunately I did not have time and energy to write posts in the last weeks. Now I make a promise, I return to blogging.
The puzzles, the SCJP Exams and Spring themes will be continued and I try present much more interesting Java technologies.
unfortunately I did not have time and energy to write posts in the last weeks. Now I make a promise, I return to blogging.
The puzzles, the SCJP Exams and Spring themes will be continued and I try present much more interesting Java technologies.
Friday, August 29, 2008
Load jar files and Java classes dynamically
In this post I present a way to load jar files and Java classes dynamically from java code. It can be very useful, if you want to create module, for example.
Design Pattern
The solution build up from three part, the
Loader - loads and uses the jar files and Java class dynamically,
Communication interface(s) - defines the interface, what can be used to communicate the program and the dynamic library,
Dynamic libraries - the Loader loads and uses this libraries through the communication interface(s).
The loader, the communication interface(s) and the dynamic libraries must be separated in different projects, because

Sample application
As usually, I made a sample application, what can help to you to understand my idea. The sample application is very similar now. The main program can be invocated with two parameter, the first is the name of the jar file to load, the second is the name of the class to load. The application loads the given jar file and class and say hello in two different language, depend on, which jar file is loaded.
Creating the communication interface(s)
There is only one communication interface, what defines only one simple method:
Creating a dynamic library
The sample dynamic library is as simple as the communication interface:
Creating the Loader
Sample application has a main class, what processes the program arguments:
and a class, where the codes are separated, that load the jar file and class dynamically:
Downloads
You can download sample projects here as NetBeans project.
Design Pattern
The solution build up from three part, the
Loader - loads and uses the jar files and Java class dynamically,
Communication interface(s) - defines the interface, what can be used to communicate the program and the dynamic library,
Dynamic libraries - the Loader loads and uses this libraries through the communication interface(s).
The loader, the communication interface(s) and the dynamic libraries must be separated in different projects, because
- Loader imports the communication interface(s)
- Dynamic libraries imports the communication interface(s)
- Loader can't know anything about the Dynamic libraries
- Dynamic libraries can't know anything about the Loader
Sample application
As usually, I made a sample application, what can help to you to understand my idea. The sample application is very similar now. The main program can be invocated with two parameter, the first is the name of the jar file to load, the second is the name of the class to load. The application loads the given jar file and class and say hello in two different language, depend on, which jar file is loaded.
Creating the communication interface(s)
There is only one communication interface, what defines only one simple method:
Creating a dynamic library
The sample dynamic library is as simple as the communication interface:
Creating the Loader
Sample application has a main class, what processes the program arguments:
and a class, where the codes are separated, that load the jar file and class dynamically:
Downloads
You can download sample projects here as NetBeans project.
Saturday, August 2, 2008
Spring Framework - XML configuration file - Part I
In this post the Spring framework's XML configuration file is presented. This files are the heart of Spring framework. Understand using these files is very important to understand Spring framework itself.
Part I - This part of post is about the XML scheme, the root element, the tags inside the root element and the properties of the <bean/> tag.
XML Scheme
To use the XML file with Spring framework, we have to start our XML file like this:
The next two lines is a DTD import. It can be used to check the validation of our XML file.
Root element
All XML file have to be a root element. If we create XML configuration file to Spring framework then the root element must be:
The following tags are allowed inside the <beans/> element:
<import/> tag: Importing beans from other XML files
It can be very useful when we can separate the beans to several XML files based on the business logic. Other benefit is the support of the team work. Everybody can work with its own beans and program code and using import tag, the XML files can be logically merged.
Importing beans from other XML file:
<alias/> tag: Aliasing beans
Using <alias/> tag we can give alias names to beans. This means we can give new reference-name to the bean:
Using <description/> tag we can write descriptions, comments to our XML configuration file:
<bean/> tag: Defining beans
A Spring IoC container manages one or more beans. These beans are created using the configuration metadata that has been supplied to the container
.
Within the container itself, these bean definitions are represented as BeanDefinition objects, which contain (among other information) the following metadata:
We can mark a bean explicit abstract. In this case we can define bean template without specifying its class. This abstract beans can use as parent of well-defined beans.
Example:
<bean/> tag, autowire attribute
The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory. The autowiring functionality has five modes. Autowiring is specified per bean and can thus be enabled for some beans, while other beans will not be autowired. Using autowiring, it is possible to reduce or eliminate the need to specify properties or constructor arguments, thus saving a significant amount of typing. When using XML-based configuration metadata, the autowire mode for a bean definition is specified
by using the autowire attribute of the <bean/> element. The following values are allowed:
<bean/> tag, class attribute
Using class property we can specify the class of the bean. The class definition must be contain the package name and the class name
Example:
<bean/> tag, dependency-check attribute
The Spring IoC container also has the ability to check for the existence of unresolved dependencies of a bean deployed into the container. These are JavaBeans properties of the bean, which do not have actual values set for them in the bean definition, or alternately provided automatically by the autowiring feature. This feature is sometimes useful when you want to ensure that all properties (or all properties of a certain type) are set on a bean. Of course, in many cases a bean class will have default values for many properties, or some properties do not apply to all usage scenarios, so this feature is of limited use. Dependency checking can also be enabled and disabled per bean, just as with the autowiring functionality. The default is to not check dependencies. Dependency checking can be handled in several different modes. When using XML-based configuration metadata, this is specified via the 'dependency-check' attribute in a bean definition, which may have the following values:
<bean/> tag, depends-on attribute
For most situations, the fact that a bean is a dependency of another is expressed by the fact that one bean is set as a property of another.
For the relatively infrequent situations where dependencies between beans are less direct (for
example, when a static initializer in a class needs to be triggered, such as database driver registration), the 'depends-on' attribute may be used to explicitly force one or more beans to be initialized before the bean using this element is initialized. Find below an example of using the 'depends-on' attribute to express a dependency on a single bean:
<bean/> tag, destroy-method attribute
Implementing the org.springframework.beans.factory.DisposableBean interface allows a bean to get a callback when the container containing it is destroyed. The DisposableBean interface specifies a single method:
Other way to define destruction callback is the destroy-method attribute. We can set a method of the class, that is invoced before it is destroyed:
In this case the cleanup() method is invoced before the bean is destroyed.
<bean/> tag, factory-bean, factory-method attributes
We can use factory method instead of constructor. We have two options to do that:
When defining a bean which is to be created using a static factory method, along with the class attribute which specifies the class containing the static factory method, another attribute named factory-method is needed to specify the name of the factory method itself. Spring expects to be able to call this method (with an optional list of arguments as described later) and get back a live object, which from that point on is treated as if it had been created normally via a constructor. One use for such a bean definition is to call static factories in legacy code.
The following example shows a bean definition which specifies that the bean is to be created by calling a factory-method. Note that the definition does not specify the type (class) of the returned object, only the class containing the factory method. In this example, the createInstance() method must be a static method:
Instance factory method
Instantiation using an instance factory method is where a non-static method of an existing bean from the container is invoked to create a new bean. To use this mechanism, the 'class' attribute must be left empty, and the 'factory-bean' attribute must specify the name of a bean in the current (or parent/ancestor) container that contains the instance method that is to be invoked to
create the object. The name of the factory method itself must be set using the 'factory-method' attribute. The createInstance method is an instance method of examples.FactoryBean class here:
Every bean has one or more ids (also called identifiers, or names; these terms refer to the same thing). These ids must be unique within the container the bean is hosted in. A bean will almost always have only one id, but if a bean has more than one id, the extra ones can essentially be considered aliases.
When using XML-based configuration metadata, you use the 'id' or 'name' attributes to specify the bean identifier(s). The 'id' attribute allows you to specify exactly one id, and as it is a real XML element ID attribute, the XML parser is able to do some extra validation when other elements reference the id; as such, it is the preferred way to specify a bean id. However, the XML specification does limit the characters which are legal in XML IDs. This is usually not a constraint, but if you have a need to use one of these special XML characters, or want to introduce other aliases to the bean, you may also or instead specify one or more bean ids,
separated by a comma (,), semicolon (;), or whitespace in the 'name' attribute.
Please note that you are not required to supply a name for a bean. If no name is supplied explicitly, the container will generate a unique name for that bean.
Example:
<bean/> tag, init-method attribute
Implementing the org.springframework.beans.factory.InitializingBean interface allows a bean to perform initialization work after all necessary properties on the bean have been set by the container. The InitializingBean interface specifies exactly one method:
Other way to define initialization callback is the init-method attribute. We can set a method of the class, that is invoced after all necessary properties on the bean have been set.
In this case the initBean() method is invoced after all necessary properties on the bean have been set.
<bean/> tag, lazy-init attribute
The default behavior for ApplicationContext implementations is to eagerly pre-instantiate all singleton beans at startup. Pre-instantiation means that an ApplicationContext will eagerly create and configure all of its singleton beans as part of its initialization process. Generally this is a good thing, because it means that any errors in the configuration or in the surrounding environment will be discovered immediately.
However, there are times when this behavior is not what is wanted. If we do not want a singleton bean to be pre-instantiated when using an ApplicationContext, you can selectively control this by marking a bean definition as lazy-initialized. A lazily-initialized bean indicates to the IoC container whether or not a bean instance should be created at startup or when it is first equested.
When configuring beans via XML, this lazy loading is controlled by the 'lazy-init' attribute on the <bean/> element; for example:
<bean/> tag, parent attribute
Use of parent attribute is based on inheritance.
A child bean definition will use the bean class from the parent definition if none is specified, but can also override it. In the latter case, the child bean class must be compatible with the parent, that is it must accept the parent's property values.
A child bean definition will inherit constructor argument values, property values and method overrides from the parent, with the option to add new values. If any init-method, destroy-method and/or static factory method settings are specified, they will override the corresponding parent settings.
Example:
If we mark a bean as singleton then if we get it through its id, always the same object is referred. The created beans are implicit singletons. If we want to get a new instance when we refer to the bean, we have to set explicit to no singleton:
Part I - This part of post is about the XML scheme, the root element, the tags inside the root element and the properties of the <bean/> tag.
XML Scheme
To use the XML file with Spring framework, we have to start our XML file like this:
<?xml version="1.0" encoding="UTF-8"?>These lines mean our XML file version is 1.0 and the encoding of the file is UTF-8. It's recommended keep these settings.
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
The next two lines is a DTD import. It can be used to check the validation of our XML file.
Root element
All XML file have to be a root element. If we create XML configuration file to Spring framework then the root element must be:
<beans>All bean definition, configuration code and everything have to be between the beans open and close tag.
...
</beans>
The following tags are allowed inside the <beans/> element:
- alias,
- bean,
- description,
- import.
<import/> tag: Importing beans from other XML files
It can be very useful when we can separate the beans to several XML files based on the business logic. Other benefit is the support of the team work. Everybody can work with its own beans and program code and using import tag, the XML files can be logically merged.
Importing beans from other XML file:
<import resource="an_other_xml_file.xml" />
<alias/> tag: Aliasing beans
Using <alias/> tag we can give alias names to beans. This means we can give new reference-name to the bean:
<alias name="the_exist_name_of_bean" alias="the_new_name_of_bean" /><description/> tag: Writing descriptions, comments
Using <description/> tag we can write descriptions, comments to our XML configuration file:
...
<description>
Some important description...
<description/>
...
<bean/> tag: Defining beans
A Spring IoC container manages one or more beans. These beans are created using the configuration metadata that has been supplied to the container
.
Within the container itself, these bean definitions are represented as BeanDefinition objects, which contain (among other information) the following metadata:
- a package-qualified class name: typically this is the actual implementation class of the bean being defined,
- bean behavioral configuration elements, which state how the bean should behave in the container (scope, lifecycle callbacks, and so forth),
- references to other beans which are needed for the bean to do its work; these references are also called collaborators or dependencies,
- other configuration settings to set in the newly created object. An example would be the number of connections to use in a bean that manages a connection pool, or the size limit of the pool.
- abstract
- autowire
- class
- dependency-check
- depends-on
- destroy-method
- factory-bean
- factory-method
- id
- init-method
- lazy-init
- name
- parent
- singleton
We can mark a bean explicit abstract. In this case we can define bean template without specifying its class. This abstract beans can use as parent of well-defined beans.
Example:
<bean id="beanId" class="pack.example.MyClass" abstract="true">
<property name="myProp" value="sample"/>
<bean/>
<bean/> tag, autowire attribute
The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory. The autowiring functionality has five modes. Autowiring is specified per bean and can thus be enabled for some beans, while other beans will not be autowired. Using autowiring, it is possible to reduce or eliminate the need to specify properties or constructor arguments, thus saving a significant amount of typing. When using XML-based configuration metadata, the autowire mode for a bean definition is specified
by using the autowire attribute of the <bean/> element. The following values are allowed:
- no - No autowiring at all. Bean references must be defined via a ref element. This is the default, and changing this is discouraged for larger deployments, since explicitly specifying collaborators gives greater control and clarity. To some extent, it is a form of documentation about the structure of a system.
- byName - Autowiring by property name. This option will inspect the container and look for a bean named exactly the same as the property which needs to be autowired. For example, if you have a bean definition which is set to autowire by name, and it contains a master property (that is, it has a setMaster(..) method), Spring will look for a bean definition named master, and use it to set the property.
- byType - Allows a property to be autowired if there is exactly one bean of the property type in the container. If there is more than one, a fatal exception is thrown, and this indicates that you may not use byType autowiring for that bean. If there are no matching beans, nothing happens; the property is not set. If this is not desirable, setting the dependency-check="objects" attribute value specifies that an error should be thrown in this case.
- constructor - This is analogous to byType, but applies to constructor arguments. If there isn't exactly one bean of the constructor argument type in the container, a fatal error is raised.
- autodetect - Chooses constructor or byType through introspection of the bean class. If a default constructor is found, the byType mode will be applied.
<bean id="beanId" class="pack.example.MyClass" autowire="no"/>
<bean/> tag, class attribute
Using class property we can specify the class of the bean. The class definition must be contain the package name and the class name
Example:
<bean id="beanId" class="pack.example.MyClass"/>
<bean/> tag, dependency-check attribute
The Spring IoC container also has the ability to check for the existence of unresolved dependencies of a bean deployed into the container. These are JavaBeans properties of the bean, which do not have actual values set for them in the bean definition, or alternately provided automatically by the autowiring feature. This feature is sometimes useful when you want to ensure that all properties (or all properties of a certain type) are set on a bean. Of course, in many cases a bean class will have default values for many properties, or some properties do not apply to all usage scenarios, so this feature is of limited use. Dependency checking can also be enabled and disabled per bean, just as with the autowiring functionality. The default is to not check dependencies. Dependency checking can be handled in several different modes. When using XML-based configuration metadata, this is specified via the 'dependency-check' attribute in a bean definition, which may have the following values:
- none - No dependency checking. Properties of the bean which have no value specified for them are simply not set.
- simple - Dependency checking is performed for primitive types and collections (everything except collaborators).
- object - Dependency checking is performed for collaborators only.
- all - Dependency checking is done for collaborators, primitive types and collections.
<bean id="beanId" class="pack.example.MyClass" dependency-check="none"/>
<bean/> tag, depends-on attribute
For most situations, the fact that a bean is a dependency of another is expressed by the fact that one bean is set as a property of another.
For the relatively infrequent situations where dependencies between beans are less direct (for
example, when a static initializer in a class needs to be triggered, such as database driver registration), the 'depends-on' attribute may be used to explicitly force one or more beans to be initialized before the bean using this element is initialized. Find below an example of using the 'depends-on' attribute to express a dependency on a single bean:
<bean id="myClass" class="pack.example.MyClass"/>
<bean id="myOtherClass" class="pack.example.MyOtherClass"/>
<bean id="beanId" class="pack.example.MyImportantClass" depends-on="myClass,myOtherClass"/>
<bean/> tag, destroy-method attribute
Implementing the org.springframework.beans.factory.DisposableBean interface allows a bean to get a callback when the container containing it is destroyed. The DisposableBean interface specifies a single method:
void destroy() throws Exception;
Other way to define destruction callback is the destroy-method attribute. We can set a method of the class, that is invoced before it is destroyed:
<bean id="myClass" class="pack.example.MyClass" destroy-method="cleanup"/>
In this case the cleanup() method is invoced before the bean is destroyed.
<bean/> tag, factory-bean, factory-method attributes
We can use factory method instead of constructor. We have two options to do that:
- static factory method
- instance factory method
When defining a bean which is to be created using a static factory method, along with the class attribute which specifies the class containing the static factory method, another attribute named factory-method is needed to specify the name of the factory method itself. Spring expects to be able to call this method (with an optional list of arguments as described later) and get back a live object, which from that point on is treated as if it had been created normally via a constructor. One use for such a bean definition is to call static factories in legacy code.
The following example shows a bean definition which specifies that the bean is to be created by calling a factory-method. Note that the definition does not specify the type (class) of the returned object, only the class containing the factory method. In this example, the createInstance() method must be a static method:
<bean id="exampleBean" class="examples.FactoryBean" factory-method="createInstance"/>
Instance factory method
Instantiation using an instance factory method is where a non-static method of an existing bean from the container is invoked to create a new bean. To use this mechanism, the 'class' attribute must be left empty, and the 'factory-bean' attribute must specify the name of a bean in the current (or parent/ancestor) container that contains the instance method that is to be invoked to
create the object. The name of the factory method itself must be set using the 'factory-method' attribute. The createInstance method is an instance method of examples.FactoryBean class here:
<bean id="factoryBean" class="examples.FactoryBean"/><bean/> tag, id, name attributes
<bean id="exampleBean" factory-bean="factoryBean" factory-method="createInstance"/>
Every bean has one or more ids (also called identifiers, or names; these terms refer to the same thing). These ids must be unique within the container the bean is hosted in. A bean will almost always have only one id, but if a bean has more than one id, the extra ones can essentially be considered aliases.
When using XML-based configuration metadata, you use the 'id' or 'name' attributes to specify the bean identifier(s). The 'id' attribute allows you to specify exactly one id, and as it is a real XML element ID attribute, the XML parser is able to do some extra validation when other elements reference the id; as such, it is the preferred way to specify a bean id. However, the XML specification does limit the characters which are legal in XML IDs. This is usually not a constraint, but if you have a need to use one of these special XML characters, or want to introduce other aliases to the bean, you may also or instead specify one or more bean ids,
separated by a comma (,), semicolon (;), or whitespace in the 'name' attribute.
Please note that you are not required to supply a name for a bean. If no name is supplied explicitly, the container will generate a unique name for that bean.
Example:
<bean id="exampleBean" class="examples.ExampleClass"/>
<bean/> tag, init-method attribute
Implementing the org.springframework.beans.factory.InitializingBean interface allows a bean to perform initialization work after all necessary properties on the bean have been set by the container. The InitializingBean interface specifies exactly one method:
void afterPropertiesSet() throws Exception;
Other way to define initialization callback is the init-method attribute. We can set a method of the class, that is invoced after all necessary properties on the bean have been set.
<bean id="myClass" class="pack.example.MyClass" init-method="initBean"/>
In this case the initBean() method is invoced after all necessary properties on the bean have been set.
<bean/> tag, lazy-init attribute
The default behavior for ApplicationContext implementations is to eagerly pre-instantiate all singleton beans at startup. Pre-instantiation means that an ApplicationContext will eagerly create and configure all of its singleton beans as part of its initialization process. Generally this is a good thing, because it means that any errors in the configuration or in the surrounding environment will be discovered immediately.
However, there are times when this behavior is not what is wanted. If we do not want a singleton bean to be pre-instantiated when using an ApplicationContext, you can selectively control this by marking a bean definition as lazy-initialized. A lazily-initialized bean indicates to the IoC container whether or not a bean instance should be created at startup or when it is first equested.
When configuring beans via XML, this lazy loading is controlled by the 'lazy-init' attribute on the <bean/> element; for example:
<bean id="myClass" class="pack.example.MyClass" lazy-init="true"/>
<bean/> tag, parent attribute
Use of parent attribute is based on inheritance.
A child bean definition will use the bean class from the parent definition if none is specified, but can also override it. In the latter case, the child bean class must be compatible with the parent, that is it must accept the parent's property values.
A child bean definition will inherit constructor argument values, property values and method overrides from the parent, with the option to add new values. If any init-method, destroy-method and/or static factory method settings are specified, they will override the corresponding parent settings.
Example:
<bean id="beanId" class="pack.example.MyClass" abstract="true"><bean/> tag, singleton attribute
<property name="myProp" value="sample"/>
<bean/>
<bean id="child" class="pack.example.MyClass" parent="beanId">
If we mark a bean as singleton then if we get it through its id, always the same object is referred. The created beans are implicit singletons. If we want to get a new instance when we refer to the bean, we have to set explicit to no singleton:
<bean id="child" class="pack.example.MyClass" singleton="false">
Spring Framework - First Steps
This post teaches you some useful basic information and function of Spring framework. Writing XML configuration files, wiring beans, loading XMLs, using ApplicationContext. Creating, publishing and listening events are discussed in this post too.
TaskbarNotifier example application
The functions above are represented through an example application. This application has a GUI frame, where we can create animals, given the genus, the name and the color:

and when user click to the Create and notify button, then the created animal properties are showed in a tooltip message on taskbar:

Step 1: Creating the project
Create a new java application project with your favorite IDE and add the following files from Spring to the application classpath:
Now we create the model, the objects, on our application operates. We have a simple JavaBean, named Animal with three simple properties:
Step 3: Creating the service interfaces
Services are very important in Spring. They implement the business logic, operate with the application data. To create a service, first we create an interface with methods, that the service will implement (it's function will be discussed in another post).
Our example application has two service interfaces:
Our TaskbarService interface:
Step 4: Implementing the service interfaces
Implementing the service interface is a simple interface implementation, its complexity depends on the complexity of the business logic.
Our application has two service interfsce implementations:
AnimalServiceImp source code:
TaskbarServiceImp source code:
Step 5: Creating and publishing events
Events can be very useful when we want to inform other parts of our application, something interesting happened.
To create an event, we have to extend the org.springframework.context.ApplicationEvent abstract class and create a constructor, what call a super() with a parameter. This parameter is usually the object, what is behind to the published event.
If we have an event instance then we can publish it through an ApplicationContext instance, using the publishEvent() method, like this (where context is an ApplicationContext instance):
Working of events is represented by the following chart:

Our application have only one publishable event:
Step 6 : Creating the Listener class
As I discussed above, ApplicationListeners are waiting for published events and they (of course we, programmers) decide, is the actual event important to this listener or not. If it is then the listener can run some event-specific code, otherwise it should do nothing (but can, if it wants).
To create an own listener, we need implement the org.springframework.context.ApplicationListener interface. This interface has a single method:
Through the event parameter we can access the actual published event. With the instanceof operator we can decide the type of the event.
The example application has only one Listener:
Step 7: Creating GUI
There's a simple thing, that I discuss in this step:
I write the windowClosing event to my Frame:
I did it because i want to run some code before the application is closed (remove the taskbar icon for example).
Our application has only one frame:
Step 8: The XML configuration file
As I said, we can use XML configuration files to define beans, wire beans, set configurations. In a separated post I will write only about the XML configuration file, now see only the required information to create our sample application.
Our sample application's XML configuration file looks like this:
XML Scheme
To use the XML file with Spring framework, we have to start our XML file like this:
The next two lines is a DTD import. It can be used to check the validation of our XML file.
Root element
All XML file have to be a root element. If we create XML configuration file to Spring framework then the root element must be:
Simple bean definition
The most easiest way to define a bean is the following:
We define a bean to access an example.taskbar.TaskbarServiceImp instance:
And now, we define an other bean, what is a little more complex, because we set the taskbarService properties of the created bean:
This definition means:
Summary
If your read this post, you can
Downloads
You can download example code here as NetBeans project.
TaskbarNotifier example application
The functions above are represented through an example application. This application has a GUI frame, where we can create animals, given the genus, the name and the color:
and when user click to the Create and notify button, then the created animal properties are showed in a tooltip message on taskbar:
Step 1: Creating the project
Create a new java application project with your favorite IDE and add the following files from Spring to the application classpath:
- spring.jar
- spring-core.jar
- spring-context.jar
- commons-logging.jar
- log4j-1.2.xy.jar
Now we create the model, the objects, on our application operates. We have a simple JavaBean, named Animal with three simple properties:
- genus - genus of the animal
- name - name of the animal
- color - color of the animal
Step 3: Creating the service interfaces
Services are very important in Spring. They implement the business logic, operate with the application data. To create a service, first we create an interface with methods, that the service will implement (it's function will be discussed in another post).
Our example application has two service interfaces:
- AnimalService - Creates Animal instance from its properties.
- TaskbarService - Shows the taskbar icon, displays tooltip message on taskbar and closes the taskbar icon.
Our TaskbarService interface:
Step 4: Implementing the service interfaces
Implementing the service interface is a simple interface implementation, its complexity depends on the complexity of the business logic.
Our application has two service interfsce implementations:
- AnimalServiceImp
- TaskbarServiceImp
AnimalServiceImp source code:
TaskbarServiceImp source code:
Step 5: Creating and publishing events
Events can be very useful when we want to inform other parts of our application, something interesting happened.
To create an event, we have to extend the org.springframework.context.ApplicationEvent abstract class and create a constructor, what call a super() with a parameter. This parameter is usually the object, what is behind to the published event.
If we have an event instance then we can publish it through an ApplicationContext instance, using the publishEvent() method, like this (where context is an ApplicationContext instance):
context.publishEvent(new TaskbarNotificationEvent(animal)); //This code segment is from AnimalServiceImp class
Working of events is represented by the following chart:
Our application have only one publishable event:
- TaskbarNotificationEvent - This event is published when a new Animal instance created.
Step 6 : Creating the Listener class
As I discussed above, ApplicationListeners are waiting for published events and they (of course we, programmers) decide, is the actual event important to this listener or not. If it is then the listener can run some event-specific code, otherwise it should do nothing (but can, if it wants).
To create an own listener, we need implement the org.springframework.context.ApplicationListener interface. This interface has a single method:
public void onApplicationEvent(ApplicationEvent event);
Through the event parameter we can access the actual published event. With the instanceof operator we can decide the type of the event.
The example application has only one Listener:
- TaskbarNotifier.
Step 7: Creating GUI
There's a simple thing, that I discuss in this step:
I write the windowClosing event to my Frame:
private void formWindowClosing(java.awt.event.WindowEvent evt) {
/**
* Close the application, using the AppController.exit() method.
* The defaultCloseOperation of form is set to EXIT_ON_CLOSE.
*/
AppController.exit();
}
I did it because i want to run some code before the application is closed (remove the taskbar icon for example).
Our application has only one frame:
- MainFrame.
Step 8: The XML configuration file
As I said, we can use XML configuration files to define beans, wire beans, set configurations. In a separated post I will write only about the XML configuration file, now see only the required information to create our sample application.
Our sample application's XML configuration file looks like this:
XML Scheme
To use the XML file with Spring framework, we have to start our XML file like this:
<?xml version="1.0" encoding="UTF-8"?>These lines mean our XML file version is 1.0 and the encoding of the file is UTF-8. It's recommended keep these settings.
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
The next two lines is a DTD import. It can be used to check the validation of our XML file.
Root element
All XML file have to be a root element. If we create XML configuration file to Spring framework then the root element must be:
<beans>All bean definition, configuration code and everything have to be between the beans open and close tag.
...
</beans>
Simple bean definition
The most easiest way to define a bean is the following:
<bean id="animalService" class="example.animal.AnimalServiceImp" />This definition means:
- create an instance of class example.animal.AnimalServiceImp
- assign the animalService identification to the created instance
- if we refering the created instance through the animalService identification, we always access to the same object instance (singleton) it can be changed, it will be discussed later
We define a bean to access an example.taskbar.TaskbarServiceImp instance:
<bean id="taskbarService" class="example.taskbar.TaskbarServiceImp" />
And now, we define an other bean, what is a little more complex, because we set the taskbarService properties of the created bean:
<bean id="taskbarNotifier" class="example.taskbar.TaskbarNotifier">
<property name="taskbarService">
<ref bean="taskbarService" />
</property>
</bean>
This definition means:
- create an instance of class example.taskbar.TaskbarNotifier
- assign the taskbarNotifier identification to the created instance
- if we refering the created instance through the taskbarNotifier identification, we always access to the same object instance (singleton) it can be changed, it will be discussed later
- get the example.taskbar.TaskbarServiceImp instance with taskbarService identification and set the created bean's taskbarService property through its setter method to this taskbarService object
Summary
If your read this post, you can
- add the required files to use Spring framework
- create service interfaces
- implement service interfaces
- create and publish events
- listen and handle events
Downloads
You can download example code here as NetBeans project.
Labels:
download,
event,
java,
service interface,
spring,
taskbar,
xml,
xml configuration file
Sunday, July 13, 2008
SCJP Exam - Objective 1.3 Part II
Develop code that declares, initializes, and uses primitives, arrays, enums, and objects as static, instance, and local variables. Also, use legal identifiers for variable names.
Arrays are objects in Java that store multiple variables of the same type. Arrays can hold either primitives or object references, but the array itself will always be an object on the heap, even if the array is declared to hold primitive elements. In other words, there is no such thing as a primitive array, but you can make an array of primitives.
There are three things, what you should know about array:
Declaring arrays
Arrays are declared by stating the type of element the array will hold, which can be an object or a primitive, followed by square brackets to the left or right of the identifier.
Declaring array of primitives
Declaration of an array of primitives looks like this:
for example:
There is another way to declare arrays (like in language C):
for example:
Declaration of array of objects:
for example:
Declaring multidimensional arrays
Java let you to declare multidimensional arrays. Multidimensional arrays are arrays of arrays.
A two dimensional array declaration:
The
declaration is interesting, but legal.
Constructing arrays
Constructing an array means creating the array object on the heap. To create an array object, Java must know how much space to allocate on the heap, so user must specify the size of the array at creation time. The size of the array is the number of elements the array will hold.
Examples
Constructing multidimensional array
Remember, multidimensional arrays are simply arrays of arrays. It means, elements of multidimensional arrays are arrays.
The
means we declare and construct a two-dimensional integer array and the size of the first dimension will be 2. When we initialize the array then we can put int array as elements with different size into the array.
The
means we declare and construct a two-dimensional integer array and the size of the first dimension will be 3 and declare and construct three one-dimension array with length 2 and put them into the array.
Initializing arrays
Initializing an array means putting things (primitives, object references) into it:
Notice, array indexes begin with 0 and go to size-1. If we try refer to an index that not exist (for example a negative number, or a number greater then size-1) then ArrayIndexOutOfBoundsException trowed.
Declaring, constructing and initializing arrays
It's possible to declare, construct and initialize array in the same time:
Anonymous array creation
Anonymous array creation can be used to construct and initialize an array, and then assign the array to a previously declared array reference variable:
Multidimensional array creation
Multidimensional array creation looks like this:
int[][] array = { { 1, 2, 3 }, { 10, 11 }, { 0 } };
Declare, initialize and uses arrays, enums, objects as static, instance and local variables
Example code:
You can download source code here.
Arrays are objects in Java that store multiple variables of the same type. Arrays can hold either primitives or object references, but the array itself will always be an object on the heap, even if the array is declared to hold primitive elements. In other words, there is no such thing as a primitive array, but you can make an array of primitives.
There are three things, what you should know about array:
- declaring array
- constructing array
- initializing array
Declaring arrays
Arrays are declared by stating the type of element the array will hold, which can be an object or a primitive, followed by square brackets to the left or right of the identifier.
Declaring array of primitives
Declaration of an array of primitives looks like this:
<primitive type>[] <identifier>;
for example:
int[] integer_array;
There is another way to declare arrays (like in language C):
<primitive type> <identifier>[];
for example:
int anotherArray[];Declaring array of objects
Declaration of array of objects:
<classname>[] <identifier>;
for example:
String[] stringArray;Array of object can be declared as in language C too.
Declaring multidimensional arrays
Java let you to declare multidimensional arrays. Multidimensional arrays are arrays of arrays.
A two dimensional array declaration:
String[][] twoDimensionalArray;
The
String[][] threeDimensionalArray[];
declaration is interesting, but legal.
Constructing arrays
Constructing an array means creating the array object on the heap. To create an array object, Java must know how much space to allocate on the heap, so user must specify the size of the array at creation time. The size of the array is the number of elements the array will hold.
Examples
int[] intArray; //Declare an one-dimensional array
intArray = new int[3]; //Construct an int array to hold 3 int value
long longArray = new long[1]; //Declare and construct a long array with one element
Constructing multidimensional array
Remember, multidimensional arrays are simply arrays of arrays. It means, elements of multidimensional arrays are arrays.
The
int[][] array = new int[2][];
means we declare and construct a two-dimensional integer array and the size of the first dimension will be 2. When we initialize the array then we can put int array as elements with different size into the array.
The
int otherArray = new int[3][2];
means we declare and construct a two-dimensional integer array and the size of the first dimension will be 3 and declare and construct three one-dimension array with length 2 and put them into the array.
Initializing arrays
Initializing an array means putting things (primitives, object references) into it:
int[] a = new int[3];
a[0] = 1;
a[1] = 2;
a[2] = 3;
int b[] = new int[2];
b[0] = 8;
b[1] = 9;
int[][] c;
c = new int[2][];
c[0] = a;
c[1] =b;
String[] s = new String[3];
s[0] = "hello";
s[1] = null; //null can be use as string element
s[2] = new String("World");
Notice, array indexes begin with 0 and go to size-1. If we try refer to an index that not exist (for example a negative number, or a number greater then size-1) then ArrayIndexOutOfBoundsException trowed.
Declaring, constructing and initializing arrays
It's possible to declare, construct and initialize array in the same time:
int[] a = { 5, 6, 7 };
String lenovo = new String("Lenovo");
String[] computerProducers = { "Dell", lenovo, "HP", "Apple" };
Anonymous array creation
Anonymous array creation can be used to construct and initialize an array, and then assign the array to a previously declared array reference variable:
String[] operatingSystems;
operatingSystems = new String[] { "Windows XP", "Windows Vista", "OpenSuSE 10.3" };
Multidimensional array creation
Multidimensional array creation looks like this:
int[][] array = { { 1, 2, 3 }, { 10, 11 }, { 0 } };
Declare, initialize and uses arrays, enums, objects as static, instance and local variables
Example code:
You can download source code here.
Thursday, July 10, 2008
Spring Framework - Introduction
Spring is an open-source framework, created by Rod Johnson. It was created to address the complexity of enterprise application development. Spring makes it possible to use JavaBeans to achieve things that were previously only possible with EJBs. However, Spring’s usefulness isn’t limited to server-side development. Any Java application can benefit from Spring in terms of simplicity, testability, and loose coupling.
Web: http://www.springframework.org/
Lightweight — Spring is lightweight in terms of both size and overhead. The entire Spring framework can be distributed in a single JAR file that weighs in at just over 1 MB. And the processing overhead required by Spring is negligible. What’s more, Spring is non intrusive: objects in a Spring-enabled application typically have no dependencies on Spring specific classes.
Inversion of control — Spring promotes loose coupling through a technique known as inversion of control (IoC). When IoC is applied, objects are passively given their dependencies instead of creating or looking for dependent objects for themselves. You can think of IoC as JNDI in reverse—instead of an object looking up dependencies from a container, the container gives the dependencies to the object at instantiation without waiting to be asked.
Aspect-oriented — Spring comes with rich support for aspect-oriented programming
that enables cohesive development by separating application business logic from system services (such as auditing and transaction management). Application objects do what they’re supposed to do—perform business logic—and nothing more. They are not responsible for (or even aware of) other system concerns, such as logging or transactional support.
Container — Spring is a container in the sense that it contains and manages the life cycle and configuration of application objects. You can configure how your each of your beans should be created—either create one single instance of your bean or produce a new instance every time one is needed based on a configurable prototype—and how they should be associated with each other. Spring should not, however, be confused with traditionally heavyweight EJB containers, which are often large and cumbersome to work with.
Framework — Spring makes it possible to configure and compose complex applications from simpler components. In Spring, application objects are composed declaratively, typically in an XML file. Spring also provides much infrastructure functionality (transaction management, persistence framework integration, etc.), leaving the development of application logic to developer.
Starting with Spring Framework
Downloading required files
You can download the latest release of Spring framework from this link. Select the spring-framework-2.x.z-with-dependencies.zip file, that contains the base files and the files to use Spring modules.
Unpacking file
Unpack the downloaded zip file to a directory. The directory structure, that is created looks like this:
The [lib] is the most important directory, the JAR files to Spring extensions are here.
Creating the first Spring application
Our sample application will have a service interface and implementation, what writes the Hello World to the console.
Required JAR files
To build and run our first application using Spring framework, we must add the following JAR files to the classpath:
Creating the Service interface
I don't discuss this step, this is a simple interface declaration.
Source code:
Implementing the interface
This is an easy step too, a simple interface implementation, I hope everyone realizes it.
Source code:
Creating configuration XML file
This is the first step, where we see something new: the XML configuration file. These files are the "heart of Spring". Here are the bean definitions, configuration data, I discuss it later in detail.
In brief, we create 3 instance of GreetingServiceImp with identification
XML file:
Running the code
The running code gets the three GreetingServiceImp instance from the ApplicationContext and calls the sayHello() methods.
The
line create an ApplicationContext instance. Through this context we can access the beans defined in greeting.xml file, like this:
Source code:
Downloads
You can download this sample application as NetBeans project with dependencies here.
Web: http://www.springframework.org/
Lightweight — Spring is lightweight in terms of both size and overhead. The entire Spring framework can be distributed in a single JAR file that weighs in at just over 1 MB. And the processing overhead required by Spring is negligible. What’s more, Spring is non intrusive: objects in a Spring-enabled application typically have no dependencies on Spring specific classes.
Inversion of control — Spring promotes loose coupling through a technique known as inversion of control (IoC). When IoC is applied, objects are passively given their dependencies instead of creating or looking for dependent objects for themselves. You can think of IoC as JNDI in reverse—instead of an object looking up dependencies from a container, the container gives the dependencies to the object at instantiation without waiting to be asked.
Aspect-oriented — Spring comes with rich support for aspect-oriented programming
that enables cohesive development by separating application business logic from system services (such as auditing and transaction management). Application objects do what they’re supposed to do—perform business logic—and nothing more. They are not responsible for (or even aware of) other system concerns, such as logging or transactional support.
Container — Spring is a container in the sense that it contains and manages the life cycle and configuration of application objects. You can configure how your each of your beans should be created—either create one single instance of your bean or produce a new instance every time one is needed based on a configurable prototype—and how they should be associated with each other. Spring should not, however, be confused with traditionally heavyweight EJB containers, which are often large and cumbersome to work with.
Framework — Spring makes it possible to configure and compose complex applications from simpler components. In Spring, application objects are composed declaratively, typically in an XML file. Spring also provides much infrastructure functionality (transaction management, persistence framework integration, etc.), leaving the development of application logic to developer.
Starting with Spring Framework
Downloading required files
You can download the latest release of Spring framework from this link. Select the spring-framework-2.x.z-with-dependencies.zip file, that contains the base files and the files to use Spring modules.
Unpacking file
Unpack the downloaded zip file to a directory. The directory structure, that is created looks like this:
Creating the first Spring application
Our sample application will have a service interface and implementation, what writes the Hello World to the console.
Required JAR files
To build and run our first application using Spring framework, we must add the following JAR files to the classpath:
- spring.jar
- spring-core.jar
- spring-context.jar
- commons-logging.jar
- log4j-1.2.xy.jar
Creating the Service interface
I don't discuss this step, this is a simple interface declaration.
Source code:
Implementing the interface
This is an easy step too, a simple interface implementation, I hope everyone realizes it.
Source code:
Creating configuration XML file
This is the first step, where we see something new: the XML configuration file. These files are the "heart of Spring". Here are the bean definitions, configuration data, I discuss it later in detail.
In brief, we create 3 instance of GreetingServiceImp with identification
- greetingService
- inheritedGreetingService
- wrongGreetingService
- greetingMessage
- name
<bean id="greetingService" class="spring.example.helloworld.GreetingServiceImp">bean definition means:
<property name="greetingMessage">
<value>Hello</value>
</property>
<property name="name">
<value>World</value>
</property>
</bean>
- create a spring.example.helloworld.GreetingServiceImp instance,
- set the property greetingMessage to "Hello",
- set the property name to "World",
- assign the greetingService identification to the instance.
XML file:
Running the code
The running code gets the three GreetingServiceImp instance from the ApplicationContext and calls the sayHello() methods.
The
ApplicationContext context = new ClassPathXmlApplicationContext("greeting.xml");
line create an ApplicationContext instance. Through this context we can access the beans defined in greeting.xml file, like this:
GreetingService greeting = (GreetingService) context.getBean("greetingService");
Source code:
Downloads
You can download this sample application as NetBeans project with dependencies here.
Tuesday, July 8, 2008
Applying Model Viewing Controller to Java Web Applications Using JSP and Servlet
Model viewing controller is an architectural pattern. We can use to separate the user interface and the business logic. By decoupling models and views, MVC helps to reduce the complexity in architectural design, and to increase flexibility and reuse.
It isn't goal of this post to explain the using JSP and Servlet technologies. Maybe in another post I will do it.
Participants of the Model Viewing Controller Design Pattern
(based on Wikipedia)
model - the domain-specific representation of the information on which the application operates. Domain logic adds meaning to raw data (e.g., calculating whether today is the user's birthday, or the totals, taxes, and shipping charges for shopping cart items). Many applications use a persistent storage mechanism (such as a database) to store data. MVC does not specifically mention the data access layer because it is understood to be underneath or encapsulated by the Model.
viewing - renders the model into a form suitable for interaction, typically a user interface element. Multiple views can exist for a single model for different purposes.
controller - processes and responds to events, typically user actions, and may invoke changes on the model.
A simple diagram depicting the relationship
between the Model, View, and Controller.
Model Viewing Controller in action
Model Viewing Controller in action
Participants of the Model Viewing Controller Design Pattern - Java Web Application Using JSP and Servlet
model - a web application usually operates on database. There are several ways to access database from web application (JDBC, Hibernate, Toplink...).
viewing - Java Server Pages (JSP) can be used as user interface. With JSP technologies we can generate contents to web browsers, mobile phones, XML files.
controller - Servlets was developed to control the web application and access to the database, what the application use.
Model Viewing Controller in action - Java Web Application Using JSP and Servlet
In the first step, the user visits a web portal with his web browser:
Example web application
The viewed content is generated by a viewer, a JSP file:
By clicking Greeting! button, the given name will be sent to the controller Servlet. In this time the form's content is sent to the specified controller (action property, in this case greeting.controller). The property method specify the type of request (GET or POST).
The controller, in this case the GreetingServlet get the http request.
The servlets have two entry point, depends on it get a http GET or http POST query:
In my example the servlet looks like this:
The servlet processes the data and the processing is forwarded to the result.jsp, where greetings message will be showed:
Downloads
You can download example code here as NetBeans project.
It isn't goal of this post to explain the using JSP and Servlet technologies. Maybe in another post I will do it.
Participants of the Model Viewing Controller Design Pattern
(based on Wikipedia)
model - the domain-specific representation of the information on which the application operates. Domain logic adds meaning to raw data (e.g., calculating whether today is the user's birthday, or the totals, taxes, and shipping charges for shopping cart items). Many applications use a persistent storage mechanism (such as a database) to store data. MVC does not specifically mention the data access layer because it is understood to be underneath or encapsulated by the Model.
viewing - renders the model into a form suitable for interaction, typically a user interface element. Multiple views can exist for a single model for different purposes.
controller - processes and responds to events, typically user actions, and may invoke changes on the model.
between the Model, View, and Controller.
Model Viewing Controller in action
- The user interacts with the user interface.
- A controller handles the input event from the user interface, often via a registered handler or callback.
- The controller notifies the model of the user action, possibly resulting in a change in the model's state.
- A view uses the model (indirectly) to generate an appropriate user interface. The view gets its own data from the model. The model has no direct knowledge of the view.
- The user interface waits for further user interactions, which begins the cycle anew.
Participants of the Model Viewing Controller Design Pattern - Java Web Application Using JSP and Servlet
model - a web application usually operates on database. There are several ways to access database from web application (JDBC, Hibernate, Toplink...).
viewing - Java Server Pages (JSP) can be used as user interface. With JSP technologies we can generate contents to web browsers, mobile phones, XML files.
controller - Servlets was developed to control the web application and access to the database, what the application use.
Model Viewing Controller in action - Java Web Application Using JSP and Servlet
In the first step, the user visits a web portal with his web browser:
The viewed content is generated by a viewer, a JSP file:
By clicking Greeting! button, the given name will be sent to the controller Servlet. In this time the form's content is sent to the specified controller (action property, in this case greeting.controller). The property method specify the type of request (GET or POST).
The controller, in this case the GreetingServlet get the http request.
The servlets have two entry point, depends on it get a http GET or http POST query:
protected void doGet(HttpServletRequest request, HttpServletResponse response)So depend on the type of request, the suitable method is invocated, the specified codes begin to run.
throws ServletException, IOException { ... }
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { ... }
In my example the servlet looks like this:
The servlet processes the data and the processing is forwarded to the result.jsp, where greetings message will be showed:
Downloads
You can download example code here as NetBeans project.
Labels:
download,
java,
model viewing control,
mvc,
tomcat,
web application
Friday, July 4, 2008
SCJP Exam - Objective 1.3 Part I
Develop code that declares, initializes, and uses primitives, arrays, enums, and objects as static, instance, and local variables. Also, use legal identifiers for variable names.
Legal identifiers
Technically, legal identifiers must be composed of only Unicode characters, numbers, currency symbols, and connecting characters (like underscores).
Java keywords
Static variables
Instance variables
Local variables
Variables - default values
Declare, initialize, use primitives as static, instance and local variable
The Java programming language is strongly-typed, which means that all variables must first be declared before they can be used. This involves stating the variable's type and name, as you've already seen:
There are 8 primitive type in java:
Primitive and string literals
Integer literals
There are three ways to represent integer numbers in the Java language:
Decimal literals
Decimal representation is the most common in Java, for example:
Octal literals
because 077 is the octal representation of number 63.
Hexadecimal literals
You can download source code here.
Casting primitives
Casts can be implicit or explicit. An implicit cast means you don't have to write code for the cast; the conversion happens automatically. Typically, an implicit cast happens when you're doing a widening conversion.
Implicit cast
Int type is bigger the byte, implicit cast work.
Explicit cast
We need use explicit cast, if we want to assign a bigger value to a smaller type. It can cause loss of procession so explicit cast is required.
Explicit cast look like this:
Legal identifiers
Technically, legal identifiers must be composed of only Unicode characters, numbers, currency symbols, and connecting characters (like underscores).
- Identifiers must start with a letter, a currency character ($), or a connecting character such as the underscore ( _ ).
- Identifiers cannot start with a number!
- After the first character, identifiers can contain any combination of letters, currency characters, connecting characters, or numbers.
- There is no limit to the number of characters an identifier can contain.
- Java keywords can't be used as identifier.
- Identifiers in Java are case-sensitive.
Java keywords
| abstract | assert | boolean | break |
| byte | case | catch | char |
| class | const | continue | default |
| do | double | else | enum |
| extends | final | finally | float |
| for | goto | if | implements |
| import | instanceof | int | interface |
| long | native | new | package |
| private | protected | public | return |
| short | static | strictfp | super |
| switch | synchronized | this | throw |
| throws | transient | try | void |
| volatile | while |
Static variables
- static variables belong to the class, not the instance
- static variables can be public, protected, default and private
- static variables can accessed through class reference
- access static variables through instance variables is legal, but not a good idea
- static variables get their default value at declaration
- static variables declared when the class loader load their class
- static variables live as long as their class lives
- static variables can declared and initialized at the same time, except when the initialization can throw exception, in this case use static initialization block:
//Required imports here
...
class ThisClassUseStream {
//Compilation fails, because FileInputStream constructor can throw exception.
static InputStream stream = new FileInputStream("filename");
//Works well, otherStream declared and initialized as null.
static InputStream otherStream;
//static initialization block
static {
try {
otherStream = new FileInputStream("filename");
} catch( Exception ex } { ... }
}
}
- static initialization block execute top-down
- static variables are not inherited
- static variables cannot be serialized
Instance variables
- instance variables belong to an object instance
- instance variables can be accessed only through an instance
- instance variables can be accessed from somewhere in their instance
- instance variables can be public, protected, default and private
- instance variable can be inherited
- private variables are not inherited
- variables with default visibility are not inherited
- instance variables are created when the constructor is called
- instance variable get their default values at declaration
Local variables
- local variables are created inside a method body
- local variables live as long as their method is running
- local variables can be accessed only the method where they was declared
- local variables don't have default values
- local variables can be marked only as final
Variables - default values
- boolean variables: false
- byte variables: 0
- char variables: '\u0000'
- double variables: 0.0D
- float variables: 0.0F
- int variables: 0
- long variables: 0L
- object references: null
- short variables: 0
Declare, initialize, use primitives as static, instance and local variable
The Java programming language is strongly-typed, which means that all variables must first be declared before they can be used. This involves stating the variable's type and name, as you've already seen:
int a = 5;Primitive types
There are 8 primitive type in java:
- boolean data type has only two possible values: true and false.
- byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive).
- char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
- double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values isn't important.
- float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values isn't important.
- int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive).
- long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive).
- short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive).
Primitive and string literals
Integer literals
There are three ways to represent integer numbers in the Java language:
- decimal (base 10)
- octal (base 8)
- hexadecimal (base 16)
Decimal literals
Decimal representation is the most common in Java, for example:
int a = 1;
long l = 5L;
byte b = 0;
short s = 8;
Octal literals
- octal literals use only the digits 0 to 7
- octal literals always begin with 0
- octal literals can up to 21 digits in an octal number, not including the leading zero
o77 != 77
because 077 is the octal representation of number 63.
- some octal literals:
int a = 07 //equals decimal 7
int b = 08 //compilation fails, 8 digit not allowed
int c= 01234 equals decimal 668
Hexadecimal literals
- hexadecimal numbers are constructed using 16 distinct symbols: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A (or a), B (or b), C (or c), D (or d), E (or e) , F (or f)
- hexadecimal literals always begin with 0x or 0X
- hexadecimal numbers can be up to 16, not including the prefix Ox
- floating point literals include the decimal point (.)
- the left side of decimal point is the integer part
- the right side of decimal point is the fraction part
- one of the integer or the fraction part must be declared
- legal declaration and initialization:
double d1 = .1;
double d2 = 1.;
double d3 = 1.d;
double d4 = .3D;
double _____________ = -.66d;
float f1 = 9.66f;
- not legal declaration and initialization:
double d3 = .;Boolean literals
float f1 = 0.0;
- there are two boolean literals: true and false
- character literals can declared between two single quotes
- character literals can declared as number
- legal character literals:
char c1 = 'a';String literals
char c2 = '\u00ff';
char c3 = 32;
char c4 = 04;
char c5 = 0xf;
- string literals are declared between two double quote
- string literal declaration:
String s = "Hello World";Declaration Example
You can download source code here.
Casting primitives
Casts can be implicit or explicit. An implicit cast means you don't have to write code for the cast; the conversion happens automatically. Typically, an implicit cast happens when you're doing a widening conversion.
Implicit cast
byte b = 5;
int i = b;
Int type is bigger the byte, implicit cast work.
Explicit cast
We need use explicit cast, if we want to assign a bigger value to a smaller type. It can cause loss of procession so explicit cast is required.
Explicit cast look like this:
int a = (int) 5.5; //5.5 is a double, it must be cast to int
byte b = (byte) 128; //128 is too big to store in a byte
byte c = 100;
Subscribe to:
Posts (Atom)



