Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Monday, March 10, 2014

Getting started with RESTful webservice using Jersey

Jersey helps developing RESTful webservices seamlessly and makes your life easy. This article gives you a quick start on how to create your first RESTful web service using Jersey & Maven.  I assume you have a decent understanding of maven and J2EE.

Make sure you have
  1. Eclipse Kepler
  2. M2Eclipse plugin
  3. Java 1.7
  4. Tomcat 7
Step 1 - Maven Project
Create a new maven project from your eclipse.  Select maven-archetype-webapp archetype,  provide group id, artifact id, package in the following dialog. (See screenshot below)


Note: By default installed facets will not be Java 1.7, Dynamic web module 2.4.  You can edit this in org.eclipse.wst.common.project.facet.core.xml under .settings folder.  Also make sure to change the JRE from 1.5 to 1.7 in your project build path.

Step 2 - Maven Dependencies
Add the following jersey server and jersey servlet dependencies to your pom.xml
Step 3 - Deployment Descriptor
Add the Jersey servlet container to your web.xml.
Step 4 - REST Resource
Create your package and SampleRestResource class.  Add the path "/sample" at the class level, and add 2 GET resources. One with path "/hello" and the other with "/hello/{message}".  
Step 5 - Run your application
Right click on your project --> Run As --> Run on Server --> Select tomcat.  Now your first resource can be accessed from http://localhost:8080/jersey-rest-helloworld/jersey/sample/hello and the other resource from http://localhost:8080/jersey-rest-helloworld/jersey/sample/hello/your%20message

You can download the complete source here.

Monday, January 20, 2014

Why Singleton design pattern is still a good interview question to Java developers

Why every interviewer asks about singleton design pattern?
Well the answer could be either,
  1. That's what the interviewer knows to ask for.
  2. Or its a good way to start and branch into several other discussions.
  3. Or its one of the simplest design pattern and a controversial one in terms of usage.
What ever the reason may be, we better know it.

What is Singleton
Singleton is categorized under "Creational design pattern" and part of Gang of Four design pattern.  Singleton is a design pattern which suggests only one instance of a class for the entire application at any condition. There are several ways to achieve this, and be assured that most of answers you say may not convince the interviewer and he can over rule the solution.

Ways to do it
Before getting into the details are there any examples of Singleton to be used in real scenarios?  Yes, java Runtime, Logger, Service locators of JEE pattern follows singleton.  Now, we shall look into the most common ways to implement Singleton.

Singleton - Eager Initialization Example
As the name states in this approach the instance is "eagerly" created before it is expected/asked for.  It means the class will be initialized during the application startup.
In this example the interviewer would be interested in asking, What if the instance of this class is not required at all.

Yes it is a drawback that the instance is created even if it is not required. And that would be an issue only if this object is large, or else it is the best to leave it as is.  Lets say the interviewer says,  it is a large object and I do not want it to be eager loaded.  Well the next section describes you how you could write Singleton with lazy initialization.

Singleton - Lazy Initialization Example
Lazy loading is an interesting topic in programming, it means creating the object in a delayed(lazy) way. Generally any expensive process could adapt lazy style. To make our singleton lazy we have initialize the instance variable only when it is expected.
You could see the instance variable is assigned with the object when it is null and then on the same variable is reused. Take a closer look into line 10, it ensures thread safety.  If you are just writing just the pseudo code, there could be a question what would you synchronize as you haven't initialized the object yet. We synchronize the block with the class here.

Next is the volatile keyword for the instance variable, do we need that? If so why.
Yes it is absolutely required or you may run in into out of order write error scenario. ie. The reference is returned even before the object is constructed (in other words the memory is allocated but the constructor code isn't finished execution). Also volatile keyword helps as the concurrency control tool in a multi-threaded application.

Singleton - Enum way Example
Easiest of the ways, by default Enums are thread safe and ensures single instance.
For an interview I would not suggest this approach,  since it would finish up the question pretty quick.  You don't want to do that,  better hold the interviewer on the topic you know well. In terms of implementation I would suggestion the Enum way or the one that is discussed in the next section.

Singleton - Bill pugh way Example
William Pugh co-author of findbugs static code analyzing tool, on his research suggested the following way while implementing singleton.
You could witness  SingletonHolder, SingletonBillPughExample will not be initialized until getInstance() is invoked.

Friday, December 20, 2013

Spring MVC 3 + Spring Security + Hibernate 4 tutorial

This tutorial helps you to create a spring mvc application integrated with hibernate 4 and Spring security. Before continuing read through my previous article on Spring MVC 3 - Hello world example

The tutorial uses MySQL as database and source code enhanced from the previous Hello world example.

Changes to your pom
Add/modify the following to the properties section of your pom.xml. The spring version is increased to 3.2.3 to support transactions.
Add the following to the dependencies section

Now we are set to use hibernate and spring security in your application.

Create file application-security.xml inside your webapp >> WEB-INF >> spring folder and paste this content.
Replace the following to your servlet-context.xml. The changes include adding necessary namespaces and made beans as default namespace for convenience.
Create a new file controllers.xml Now all the configurations are done.  Create your controllers and views, I have not explained the views, web.xml for simplicity. The complete sample can be found here in github
Create User.java with the following content, make sure your test database has an user table with fields that matches the properties in the below
Create UserController.java with the following content
Create UserDAO.java with the following content
Download the complete code in github

Friday, November 15, 2013

Spring MVC 3 - hello world example - Quick start

This tutorial helps you to quickly create and run a spring-mvc hello world application.  Spring version used for this example is 3.2.3-RELEASE.

Prerequisites
  1. JDK 1.6+
  2. Eclipse Juno+
  3. Spring IDE 3.4+ for eclipse
  4. Maven 3
  5. Maven Integration plugin for eclipse
  6. Tomcat 7+
Initial Steps
Right click and create New --> Spring project.  In the next dialog, fill in the project name as "spring-mvc-spring-sample" and select "Spring MVC Project".  Please specify package name "com.ananth.spring" and click Finish.


Run your application
Right click on your eclipse project --> Run As --> Run on server --> Finish.
From your browser navigate to http://localhost:8080/spring/ you will see this screen.

The source can be download from github. Next chapter Spring MVC with Spring security & Hibernate.

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed - Axis2

I was recently working on writing some client code which makes multiple webservices calls.  The stubs for both my client were generated using Axis2.  I had to make requests to 2 different services, where one of the service was serving a dummy SSL certificate and the other one was serving a valid SSL certificate.

I landed up getting the following exception,
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at org.apache.axis.AxisFault.makeFault(AxisFault.java:101)
at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:154)
at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
at org.apache.axis.client.AxisClient.invoke(AxisClient.java:165)
at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
at org.apache.axis.client.Call.invoke(Call.java:2767)
at org.apache.axis.client.Call.invoke(Call.java:2443)
at org.apache.axis.client.Call.invoke(Call.java:2366)
at org.apache.axis.client.Call.invoke(Call.java:1812)

Here are the steps I took to overcome this error,

Bypass SSL security check
I googled and got several links on how to bypass the SSL security check in Java.  Most of them were suggesting to use XTrustProvider.install() to turn off SSL check.  After implementing this solution the error went away if I invoked only the service which was serving a dummy SSL certificate. When I tried  using both the services I again got caught with the same exception,  though I tried ignoring the SSL check in the 2nd service.  Axis2 actually for some reason "reuses" or caches the security certificate and the SSL socket factory is singleton. So use this class only if you are using a single service.

XTrustProvider.java
Loading the certificate to the "trust store"
Use the following InstallCert.java to generate your certificate and tell your SSL socket factory to use this trust store like this.  Note:  Add this line before the call to your first service,  else you will end up in the same exception.
InstallCert.java

Thursday, October 10, 2013

How to make Eclipse autocomplete to suggest as you type

Recently some one was asking if Eclipse content assist/autocomplete can be made to suggest as I type my class name? Immediately I could remember XCode for mac doing something like that and I felt there should be a way in Eclipse.

By default eclipse autosuggest would trigger once you type "." the goal is to make it suggest me the "Type/Class" names too. How to make it do?

Steps:
Go to Eclipse(Windows for windows users) --> Preferences --> Java --> Editor --> Content Assist

Under subsection "Auto Activation" the default value for Auto activation triggers for Java will be "." change this to

.ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

Optionally you can increase/reduce the Auto activation delay to a lesser value.



You are all set! Now Eclipse will start suggesting as you type.

Thursday, July 25, 2013

How to convert XML to Java object and vice versa in runtime?

Well the obvious choice would be to use JaxB, due to its familiarity. Let us see it with a simple example. JAXB is governed by the same team as Glassfish. JAXB comes by default with JDK1.6+. JAXB stands for Java Architecture for XML Binding.

XML has become a common form of data storage in many applications and for webservices. There are two common operations that are required while dealing with XML from Java. Read an xml file and convert it to a Java object, and write a Java object to an xml file.

JAXB does both the above said operations and those operations are called as
  1. Marshalling – Convert a Java object into a XML.
  2. Unmarshalling – Convert a XML into a Java Object.
Let us see this with an example,
Marshalling: Converting Java object to XML
Its a simple process, lets see this with a sample program
Output
While running the above example you will run into the following exception,

Exception in thread "main" javax.xml.bind.MarshalException
 - with linked exception:
[com.sun.istack.internal.SAXException2: unable to marshal type "com.ananth.samples.Employee" as an element because it is missing an @XmlRootElement annotation]
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:317)
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:243)
at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(AbstractMarshallerImpl.java:75)
at com.ananth.samples.Java2XMLExample.main(Java2XMLExample.java:20)
Caused by: com.sun.istack.internal.SAXException2: unable to marshal type "com.ananth.samples.Employee" as an element because it is missing an @XmlRootElement annotation
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.reportError(XMLSerializer.java:216)
at com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.serializeRoot(ClassBeanInfoImpl.java:286)
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:462)
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:314)
... 3 more

To fix the above exception you have to add an @XmlRootElement annotation to your Employee Pojo.
Instead of System.out you can point to the File to which you want to write the output during jaxbMarshaller.marshal(employee, file);. Once make the change while rerunning the sample will give your the following output.
UnMarshalling: Converting XML to Java object
Its a simple process, lets see this with a sample program
Now, I had a question why do I should I have a @XmlRootElement annotation in my pojo.  Cant I do I deal with my existing POJOs of my application?
The answer is you cant do it with JAXB but there are other options like XStream. I have referred their two minutes tutorial and it really look me only 2 minutes to try it out.
Add the XStream maven dependency and after that it is as easy as calling toXML and fromXML methods of XStream object.


Friday, July 19, 2013

XML reader error: javax.xml.stream.XMLStreamException: ParseError at [row,col]

100/100 times I know that this exception happens while there is a parse error in your xml and there is something wrong at the specified row and column.

Knowing the following exception is due to an XML parse error, recently I was puzzled for a while trying to look into the actual content of the file.  I couldn't see any closing tag error at the row and column mentioned.

After looking closer, I figured out my xml is used by multiple threads where a few threads were trying to write the XML and the other was trying to read the same file. And the exception was due to thread safety and the file was not fully written before the read. :-)

Message: XML document structures must start and end within the same entity.
com.sun.xml.internal.ws.streaming.XMLStreamReaderException: XML reader error: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[8829,4]
Message: XML document structures must start and end within the same entity.
at com.sun.xml.internal.ws.streaming.XMLStreamReaderUtil.wrapException(XMLStreamReaderUtil.java:256)
at com.sun.xml.internal.ws.streaming.XMLStreamReaderUtil.skipTags(XMLStreamReaderUtil.java:146)
at com.sun.xml.internal.ws.streaming.XMLStreamReaderUtil.skipElement(XMLStreamReaderUtil.java:119)
at com.sun.xml.internal.ws.wsdl.parser.WSDLParserExtensionFacade.definitionsElements(WSDLParserExtensionFacade.java:129)
at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.parseWSDL(RuntimeWSDLParser.java:314)
at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.parse(RuntimeWSDLParser.java:135)
at com.sun.xml.internal.ws.client.WSServiceDelegate.parseWSDL(WSServiceDelegate.java:254)
at com.sun.xml.internal.ws.client.WSServiceDelegate.(WSServiceDelegate.java:217)
at com.sun.xml.internal.ws.client.WSServiceDelegate.(WSServiceDelegate.java:165)
at com.sun.xml.internal.ws.spi.ProviderImpl.createServiceDelegate(ProviderImpl.java:93)

Thursday, June 13, 2013

Type mismatch: cannot convert from null to double

Today while I was doing a code review with my team mates, I noticed some code like this
When I asked them why do you type cast "null to double", the answer they gave was I got "Type mismatch: cannot convert from null to double". There are 2 possible solutions for this,
  1. Use Double instead of double, then you may use null.
  2. Use "not a number" (NaN) like this 
submit to reddit

Thursday, May 30, 2013

Why should you have your code "neat"

It is a painful truth that most of my fellow developers don't care about code readability and maintainability.  Sometimes its frustrating to make changes on an unformatted, in other words poorly written code.

Code that we write represents our brain and I consider my code as how an artist considers his painting.

After reading an article on Style matters, I thought of writing this post on few important readability factors and how important it is to have your source code neat.

Top 5 readability & maintainability factors
  1. Documentation with proper comments
  2. Formatted code with proper indentations
  3. Organized file folders
  4. Proper naming conventions
  5. Never use deprecated code
Comments & Documentation
A good developer learns a project just from the code; javadoc plays a significant role in the learning process. Imagine that all open source projects and JDK code with no comments and documentation.  I am sure that it would at least take 10 times more effort to figure how to use them. A good javadoc in your application saves enormous amount of time for fellow developers.
All IDEs shows help texts for a method or class on mouse over for quick assistance, remember they all come from the javadoc of that method or class.  When you leave your code with no comments, then you are letting some fellow developer to be handicapped in some way.

Formatted code with proper indentations
When my sister write Java classes in notepad for her college project,  it is acceptable to have a code which doesn't have a decent formatting. Considering the modern IDEs that we use, formatting takes a few seconds. It has to be a habit to write formatted code and not for the sake of your manager or your lead wants it.
To the least there are options to do a format at your project level which formats all your classes in the project.  For example using eclipse, "Right click on your project -> Source -> Format". Boom all your code is formatted decently with the basic code formatting settings, however you can go and edit the settings as you want and also you can share it across your team as an xml file.

Organized file folders
During several code reviews that I have witnessed project documents kept under "src". One common answer I heard from developers was its easy to access. I was shocked to see project documents going inside your deployable files. A good java project should have well organized packages which very well represents OO design being followed. Writing everything in the same folder makes it unmaintainable as the project grows.

Proper naming conventions
In most cases the people who maintain the code is not same as the author. They may not be knowing the project as good as the original author, or may be less skilled programmers compared to the author. Having very good class, method and variable names makes it very much easy for the person who maintains it. Reading java code should more or less be similar to reading english. Following descriptive naming convention helps to understand the code much faster. Using i, j, k, abc, xyz as your method or variable names through out your project makes it almost an unsolvable puzzle for people who follow. Sometimes it makes it tougher to debug for even the author who wrote it.

Never use deprecated code
A method or class is deprecated when a code is "buggy" or "inefficient" or for a "bad coding practice". And it is represented with @deprecated annotation. A good API would always give an alternative better option before deprecating the existing one. Look for the alternative option and never use deprecated code.

Note:  All the points discussed here are for code written Java and may be applicable for other programming languages too.

Friday, April 5, 2013

Comparison of primitive type vs Wrapper object

After coming across this question in several interviews, came up with a small piece of code to compare primitive type and wrapper object.  Auto boxing after Java 5 has shadowed the behind seen happenings to fellow developers. :-)

There will be n number of pages in google to give the differences, I am just giving a small program to compare the performance of int and Integer.


import java.util.Date;

/**
 * PerformanceTester.java
 *
 * @author cananth
 */
public class PerformanceTester {
   public void processWithWrapper() {
      long startTime = new Date().getTime();
      Integer ctr = 0;
      for (int i = 0; i < Integer.MAX_VALUE; i++) {
         ctr += i;
      }
      long endtime = new Date().getTime();
      System.out.println("---------------------------------------------------");
      System.out.println("Time using Integer: " + (endtime - startTime) + " ms");
      System.out.println("---------------------------------------------------");
   }

   public void processWithPrimitive() {
       long startTime = new Date().getTime();
       int i = 0;
       int ctr = 0;
       for (i = 0; i < Integer.MAX_VALUE; i++) {
           ctr += i;
       }
       long endtime = new Date().getTime();
       System.out.println("Time using int: " + (endtime - startTime) + " ms");
       System.out.println("---------------------------------------------------");
   }

   public static void main(String[] args) {
       System.out.println("Same Object");
       System.out.println("---------------------------------------------------");
       PerformanceTester test = new PerformanceTester();
       test.processWithWrapper();
       test.processWithPrimitive();
       test.processWithWrapper();
       test.processWithPrimitive();
             
       System.out.println();
       System.out.println("New Object");
       System.out.println("---------------------------------------------------");
       new PerformanceTester().processWithWrapper();
       new PerformanceTester().processWithPrimitive();
       new PerformanceTester().processWithWrapper();
       new PerformanceTester().processWithPrimitive();
   }
}

Output:
Same Object
---------------------------------------------------
Time using Integer: 7835 ms
---------------------------------------------------
Time using int: 1505 ms
---------------------------------------------------
Time using Integer: 7685 ms
---------------------------------------------------
Time using int: 1489 ms
---------------------------------------------------

New Object
---------------------------------------------------
Time using Integer: 7369 ms
---------------------------------------------------
Time using int: 1 ms
---------------------------------------------------
Time using Integer: 7356 ms
---------------------------------------------------
Time using int: 1 ms
---------------------------------------------------

The difference in execution is huge.  In few of my trials I have got 0ms too for the int.

Verdict: Never use wrapper class for computations.

submit to reddit

Monday, October 5, 2009

How to access office 2007(OOXML) from Java

Apache POI is the solution you are looking for. The project made java developers life simple to read and write excel, word and powerpoint files. I have used Apache POI 3.1 which helped me to read Office 2003 documents.
When microsoft released office 2007 it used OOXML formats such as XLSX and DOCX, which limited POIs capabilities. The earlier versions of POI used OLE 2 Compound Document format, and now you can easily read or write excel, doc(97-2007).
The latest release POI 3.5 final came out in 28-September-09 and I am very eager to use it for my project and I swear u will be eager too.

Thursday, September 17, 2009

Best Java based open source eCommerce Software

There are a number of open source java based ERP softwares. Listing few good ones here

The Open For Business (OFBiz) project is an open source enterprise automation software project licensed under the MIT Open Source License. By open source enterprise automation we mean: Open Source ERP, Open Source CRM, Open Source E-Business / E-Commerce, Open Source SCM, Open Source MRP, Open Source CMMS/EAM, and so on.
SourceTap's CRM application is a highly flexible Sales Force Automation (SFA) tool that meets both the needs of sales managers and the sales rep. SourceTap's CRM includes Sales Force Automation (SFA), marketing, campaign management, and customer service.
Compiere is a Open Source ERP software application with fully integrated CRM software solutions. Compiere is a fully integrated business solution for small-to-medium enterprises worldwide. Compiere is based on business process rather then departmental boundaries.
Centric CRM is an enterprise-class Open Source Customer Relationship Management web application that allows companies to better develop and maintain customers. Key application modules include Sales, Help Desk, Project Management, Communications, and Document Management. The license prevent the redistribution of the source code.
Openbravo is an open source ERP solution designed specifically for the SME (small to midsize firm). Developed in a web based environment, it includes many robust functionalities which are considered part of the extended ERP: procurement and warehouse management, project and service management, production management, and financial management. Additionally, this same application seemlessly integrates the rest of the areas, starting with a management scope directly helping clients with its CRM (Customer Relationship Management) and BI (Business Intelligence).

And there are more. A quick googling would produce more results.

KonaKart is an affordable java based shopping cart software solution for online retailers. Let KonaKart help increase your eCommerce sales.
In my views after a trial with konakart, I would rate it as the best eCommerce / Shopping cart software.

Tuesday, September 1, 2009

P6Spy Open Source Framework to detect database performance bottlenecks in Java applications

What is P6Spy?
P6Spy is an open source framework for applications that intercept and optionally modify database statements. The P6Spy distribution includes the following modules:
  1. P6Log. P6Log intercepts and logs the database statements of any application that uses JDBC. This application is particularly useful for developers to monitor the SQL statements produced by EJB servers, enabling the developer to write code that achieves maximum efficiency on the server. P6Spy is designed to be installed in minutes and requires no code changes.
  2. P6Outage. P6Outage detects long-running statements that may be indicative of a database outage proble and will log any statement that surpasses the configurable time boundary during its execution. P6Outage was designed to minimize any logging performance penalty by logging only long running statements.
P6Spy includes installation instructions for JBoss, ATG, Orion, JOnAS, iPlanet, WebLogic, WebSphere, Resin and Tomcat.
What if you want it inside your favorite Eclipse IDE?
Don't worry there is an eclipse plugin for you here.

Thursday, August 13, 2009

Code in a "finally" clause "may" fail to execute!!!

We all would have studied that finally block always executes. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
But here's an example where the finally code will not execute,
try
{
if (userInput)
{
while (true) ;
}
else
{
System.exit(1);
}
}
finally
{
// what ever you want to clean up
}
Please note: If the JVM exits while the try or catch code is being executed, then the finally block will not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block will not execute even though the application as a whole continues.

Sunday, August 9, 2009

Debate on best framework for developing JEE applications

Frameworks, Frameworks everywhere. Listing frameworks for developing JEE applications:
  1. Echo
  2. Struts
  3. RIFE
  4. JPublish
  5. Verge
  6. Action Framework
  7. Expresso
  8. OpenEmcee
  9. JWAA
  10. Smile
  11. Jeenius
  12. Dovetail
  13. Japple
  14. Nacho
  15. Click
  16. Cocoon
  17. SOFIA
  18. Spring MVC
  19. JATO
  20. Niggle
  21. Shocks
  22. Bento
  23. Turbine
  24. Jaffa
  25. MyFaces
  26. JWarp
  27. Cameleon
  28. Helma
  29. Cassandra
  30. GWT
  31. Millstone
  32. Tapestry
  33. Canyamo
  34. Folium
  35. Bishop
  36. TeaServlet
  37. jStatemachine
  38. Scope
  39. Jacquard
  40. Chiba
  41. Genie
  42. JFormular
  43. Dinamica
  44. Baritus
  45. OXF
  46. WebWork
  47. Maverick
  48. Jucas
  49. Barracuda
  50. wingS
  51. jZonic
  52. Warfare
  53. Macaw
  54. JBanana
  55. Melati
  56. Xoplon
  57. WebOnSwing
  58. Stripes
  59. JSF
May be more...
Introducing Wicket
JSP is by far the worst offender, allowing the embedding of Java code directly in web pages, but to some degree almost all of the frameworks from the list (except Tapestry) above introduce some kind of special syntax to your HTML code.
Special syntax is highly undesirable because it changes the nature of HTML from the kind of pure-and-simple HTML markup that web designers are familiar with, to some kind of special HTML. This special HTML can be more difficult to preview, edit and understand.
Wicket does not introduce any special syntax to HTML. Instead, it extends HTML in a standards-compliant way via a Wicket namespace that is fully compliant with the XHTML standard. This means that you can use Macromedia Dreamweaver, Microsoft Front Page, Word, Adobe Go Live, or any other existing HTML editor to work on your web pages and Wicket components.
A comment on struts
Struts is great for small to medium size application. When the application gets big, especially when presentation logic gets complicated, it is really a big hassle to maintain the a big xml config file. Also a problem to maintain a big properties file for message used all over the application.
This URL discusses on struts and introduces shine.
Too much frameworks, my take will be do not ignore any. Though we may not able to master many.
Struts vs JSF
A good article on Struts vs JSF. http://www.simplica.com/strutsvsjsf.htm
Choosing a java web framework
A comparison presentation given in 2008 javaone conference. http://developers.sun.com/learning/javaoneonline/2008/pdf/TS-6457.pdf
This blog by Manoj maniraj has few more important points to be considered while picking your framework.
Just put in your views on the best framework.

Monday, July 27, 2009

History of java

James Gosling initiated the Java language project in June 1991 for use in one of his many set-top box projects. The language, initially called Oak after an oak treethat stood outside Gosling's office, also went by the name Green and ended up later renamed as Java, from a list of random words. Gosling aimed to implement a virtual machine and a language that had a familiar C/C++ style of notation.

For the past 13 years, Java has changed our world . . . and our expectations..

Today, with technology such a part of our daily lives, we take it for granted that we can be connected and access applications and content anywhere, anytime. Because of Java, we expect digital devices to be smarter, more functional, and way more entertaining.

In the early 90s, extending the power of network computing to the activities of everyday life was a radical vision. In 1991, a small group of Sun engineers called the "Green Team" believed that the next wave in computing was the union of digital consumer devices and computers. Led by James Gosling, the team worked around the clock and created the programming language that would revolutionize our world – Java.

The Green Team demonstrated their new language with an interactive, handheld home-entertainment controller that was originally targeted at the digital cable television industry. Unfortunately, the concept was much too advanced for the them at the time. But it was just right for the Internet, which was just starting to take off. In 1995, the team announced that the Netscape Navigator Internet browser would incorporate Java technology.

Today, Java not only permeates the Internet, but also is the invisible force behind many of the applications and devises that power our day-to-day lives. From mobile phones to handheld devises, games and navigation systems to e-business solutions, Java is everywhere!


Wednesday, July 15, 2009

Performance Test for Java While loop, For loop and Iterator

Do you wonder which of the following methods are the faster way to loop through a list or collection before?

1) While Loop
2) For Loop
3) Iterator Loop

Performance Test – While , For and Iterator

Here i create a simple program to loop through a List with 1,5,10 and 15 millions of data in While loop, For loop and Iterator loop. It’s will calculate and display the elapsed time in output.

Here is the performance test source code

public class ArrayToList {

public static void main(String[] argv) {

String sArray[] = createArray();

//convert array to list

List lList = Arrays.asList(sArray);

System.out.println("\n--------- Iterator Loop -------\n");

long lIteratorStartTime = new Date().getTime();

System.out.println("Start: " + lIteratorStartTime);

//iterator loop

Iterator iterator = lList.iterator();

while ( iterator.hasNext() ){

String stemp = iterator.next();

}

long lIteratorEndTime = new Date().getTime();

System.out.println("End: " + lIteratorEndTime);

long lIteratorDifference = lIteratorEndTime - lIteratorStartTime;

System.out.println("Iterator - Elapsed time in milliseconds: " + lIteratorDifference);

System.out.println("\n-------END-------");

System.out.println("\n--------- For Loop --------\n");

long lForStartTime = new Date().getTime();

System.out.println("Start: " + lForStartTime);

//for loop

for (int i=0; i<>

String stemp = (String)lList.get(i);

}

long lForEndTime = new Date().getTime();

System.out.println("End: " + lForEndTime);

long lForDifference = lForEndTime - lForStartTime;

System.out.println("For - Elapsed time in milliseconds: " + lForDifference);

System.out.println("\n-------END-------");

System.out.println("\n--------- While Loop -------\n");

long lWhileStartTime = new Date().getTime();

System.out.println("Start: " + lWhileStartTime);

//while loop

int j=0;

while (j<>

{

String stemp = (String)lList.get(j);

j++;

}

long lWhileEndTime = new Date().getTime();

System.out.println("End: " + lWhileEndTime);

long lWhileDifference = lWhileEndTime - lWhileStartTime;

System.out.println("While - Elapsed time in milliseconds: " + lWhileDifference);

System.out.println("\n-------END-------");

}

static String [] createArray(){

String sArray[] = new String [15000000];

for(int i=0; i<15000000;>

sArray[i] = "Array " + i;

return sArray;

}

}

Output

D:\test>java -Xms1024m -Xmx1024m ArrayToList

--------- Iterator Loop -------

Start: 1232435614372

End: 1232435614763

Iterator - Elapsed time in milliseconds: 390

-------END-------

--------- For Loop --------

Start: 1232435614763

End: 1232435614997

For - Elapsed time in milliseconds: 234

-------END-------

--------- While Loop -------

Start: 1232435614997

End: 1232435615232

While - Elapsed time in milliseconds: 234

-------END-------

Performance Test Result (in milliseconds)

Conclusion

Well… the result show Iterator mechanism is the slowest method to loop through a list. There’s not much performance different between For and While loop.

Iterator provides a very handy way to loop through a list or collection, but it is slower than For and While loop. Please be remind that the different is just in milliseconds (not even 1 second for 15 millions of data looping). So, just choose any looping mechanism you want, there’s not much performance different.