Create QR Codes in Java & Servlet

Nowadays, Quick Response (QR) Codes are becoming more and more useful as they have gone mainstream, thanks to the smart phones. Right from the bus shelter, product packaging, home improvement store, automobile, a lot of internet websites are integrating QR Codes on their pages to let people quickly reach them. With increase in number of users of smart phones day by day, the QR codes usage is going up exponentially.QR codes are a type of two-dimensional barcode. They are also known as hardlinks or physical world hyperlinks. QR Codes store up to 4,296 alphanumeric characters of arbitrary text. This text can be anything, for example URL, contact information, a telephone number etc.

Let us see a quick overview of Quick Response (QR) codes and also how to generate these codes in Java.

Introduction to QR Codes

A QR code (abbreviated from Quick Response code) is a type of matrix barcode (or two-dimensional code) first designed for the automotive industry. More recently, the system has become popular outside of the industry due to its fast readability and comparatively large storage capacity. The code consists of black modules arranged in a square pattern on a white background. The information encoded can be made up of four standardized kinds (“modes”) of data (numeric, alphanumeric, byte/binary, Kanji), or by supported extensions virtually any kind of data.

Created by Toyota subsidiary Denso Wave in 1994 to track vehicles during the manufacturing process, the QR code is one of the most popular types of two-dimensional barcodes. It was designed to allow its contents to be decoded at high speed.

Let’s Create QR Code in JAVA

Zebra Crossing (ZXing) is an awesome open source library that one can use to generate / parse QR Codes in almost all the platforms (Android, JavaSE, IPhone, RIM, Symbian etc). But if you have to generate simple QR Codes, I found it a bit clumsy to implement.

However QRGen is a good library that creates a layer on top of ZXing and makes QR Code generation in Java a piece of cake. It has a dependency on ZXing, so you would need ZXing jar files along with QRGen to create QR Codes in Java.

Download this three files and rename it with .doc to .jar & put in lib to generate QR.

zxing-j2se-1.7.doc

zxing-core-1.7.doc

qrgen-1.0.doc

Include these JAR files in your Classpath and execute following Java code to generate QR Code.


package com.javamagic.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;

public class GenerateQR {
public static void main(String[] args) {

ByteArrayOutputStream out = QRCode.from("Sanjay Prajapati - Java Magic").to(ImageType.PNG).stream();

try {

FileOutputStream fout = new FileOutputStream(new File("D:\\Generated_QR.PNG"));

fout.write(out.toByteArray());

fout.flush();
fout.close();

} catch (FileNotFoundException e) {
// Do Logging
e.printStackTrace();
} catch (IOException e) {
// Do Logging
e.printStackTrace();
}
}
}

The code is pretty straight forward. We used QRCode class to generate QR Code Stream and write the byte stream to a file D:\Generated_QR.PNG.

If you open this JPEG file and scan using your iPhone or Android QR scanner, you’ll find a cool “Sanjay Prajapati – Java Magic” in it :)

Apart from generating Sterams of data using QRGen API, we can also use below APIs to create QR Codes:

// get QR file from text using defaults
File file = QRCode.from("Hello World").file();
// get QR stream from text using defaults
ByteArrayOutputStream stream = QRCode.from("Hello World").stream();

// override the image type to be JPG
QRCode.from("Hello World").to(ImageType.JPG).file();
QRCode.from("Hello World").to(ImageType.JPG).stream();

// override image size to be 250x250
QRCode.from("Hello World").withSize(250, 250).file();
QRCode.from("Hello World").withSize(250, 250).stream();

// override size and image type
QRCode.from("Hello World").to(ImageType.GIF).withSize(250, 250).file();
QRCode.from("Hello World").to(ImageType.GIF).withSize(250, 250).stream();

Website Link (URLs) QR Code in Java

One of the most common use of a QR Code is to bring traffic to a particular webpage or download page of website. Thus QR Code encodes a URL or website address which a user can scan using phone camera and open in their browser. URLs can be straight forward included in QR Codes. In above Java Hello World example, just replace “Sanjay Prajapati – Java Magic” string with the URL you want to encode in QR Code. Below is the code snippet:


ByteArrayOutputStream out = QRCode.from("http://www.javamagic.wordpress.com").to(ImageType.PNG).stream();

QR Code in Servlet

Most of the time you would need to generate QR Codes dynamically in some website. We already saw how easy it is to generate QR code in Java. Now we will see how to integrate this QR Code generation in a Java Servlet.

Following is a simple Http Servlet that creates QR Code using QRGen and ZXing library. User provides the text for which QR Code is generated.

The index jsp file contains a simple html form with a textbox and submit button. User can enter the text that user wishes to generate QR code of and presses submit.

file: index.jsp


<html>
<head>
<title>QR Code in Java Servlet - Java Magic</title>
</head>
<body>

<form action="generateQRServlet" method="get">
<p>Enter Text to create QR Code</p>
<input type="text" name="qrtext" />
<input type="submit" value="Generate QR Code" />
</form>
</body>
</html>

The magic happens in QRCodeServlet.java. Here we uses QRGen library along with ZXing and generates QR Code for given text (Text we get from request.getParameter). Once the QR Stream is generated, we write this to response and set appropriate content type.

File: GenerateQRCodeServlet.java


package com.javamagic.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;

public class GenerateQRCodeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

String qrtext = request.getParameter("qrtext");

ByteArrayOutputStream out = QRCode.from(qrtext).to(
ImageType.PNG).stream();

response.setContentType("image/png");
response.setContentLength(out.size());

OutputStream outStream = response.getOutputStream();

outStream.write(out.toByteArray());

outStream.flush();
outStream.close();
}
}

The below web.xml simply maps GenerateQRCodeServlet.java with /GenerateQR URL.

File: web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">

<display-name>QR_Code_Servlet</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>GenerateQRCodeServlet</servlet-name>
<servlet-class>com.javamagic.util.GenerateQRCodeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GenerateQRCodeServlet</servlet-name>
<url-pattern>/GenerateQR</url-pattern>
</servlet-mapping>

</web-app>

Now execute in browser and you will get QR Code of entered text.

Generating QR Codes in Java is not only easy, but quite straight forward. Integrating this functionality with any existing Java based app is just a piece of cake! In this tutorial we saw how to generate these QR codes in Java and also with Servlet.

Hope you’ll like this… Cheers… :)

Project Coin – Java 7 new features

After reading the title “project Coin“, few of you must be thinking that what is it ? And how it is related to Java 7 new features.

So, here we go…

Project Coin is the part of Java 7 development which is running since January 2009 with the aim of coming with small changes to the Java language.

In February to march 2009, there were nearly 70 proposals were submitted for huge range of possible changes in Java 7. Project coin has set up the example that how language can be developed in the future by discussion in openly manner with the public all around the world.

Java 7 new Features :

Support of Strings in “Switch” statement:
Before Java 7, we can only use constants of type byte, char, short or enum. However, now we can use the string also in switch case statement.

switch(dayOfWeek)
{
   case "Monday" : System.out.println("Its first day of the office");break;
   ....
   case "Sunday" : System.out.println("Hurrey.. its weekend");break;
}

Enhanced Syntax of Numeric literals

  • Numeric constants expressed as binary.
  • Use of underscores in integer constants for readability.
  • A specific suffix to denote that an integer constant has type short or byte.

Improved Exception handling
Before Java 7, we used to write multiple catch blocks in our program which looks like very verbose.
with the help of pipe operator in Java 7, we can write multiple catch blocks in one line as shown below :

public void printFileContent(String fileName_) {
Configuration cfg = null;
try {
String fileText = getFile(fileName_);
//...code to print content
} catch (FileNotFoundException|ParseException|FileLockInterruptionException e) {
System.err.println("error while opening file");
} catch (IOException iox) {
System.err.println("Error while processing file");
}

}

Try with resources

try ( FileOutputStream fos = new FileOutputStream(file);
InputStream is = url.openStream() ) {
byte[] buf = new byte[4096];
int len;
while ((len = is.read(buf)) > 0) {
fos.write(buf, 0, len);
}
}

Diamond Syntax :
Before Java 7, generic Syntax was like :

Map<Movie,Songs> m = new HashMap<Movie,Songs>();

As you can see, we are repeating the syntax at right hand side, why compiler should not be able to take care of that?
Below is the new user friendly syntax.

Map<Movie,Songs> m = new HashMap<>();

There is also change in Varargs Syntax which we will discuss in detail later on.
Please leave your valuable suggestions to improve the article and content.

When does the finally clause in java exception block never executes?

The finally clause in the try-catch exeception block always executes, irrespective of the occurence of exeception. This is applicable for the normal java program flow. If the execution flow is stopped irreversibly before the finally clause, then the finally block will not be executed.

How can the user achieve that in Java?
Include “System.exit(1);” before the finally block and stop the execution flow of the java program.

Differentiate JVM JRE JDK JIT

Java Virtual Machine (JVM) is an abstract computing machine. Java Runtime Environment (JRE) is an implementation of the JVM. Java Development Kit (JDK) contains JRE along with various development tools like Java libraries, Java source compilers, Java debuggers, bundling and deployment tools.

JVM becomes an instance of JRE at runtime of a java program. It is widely known as a runtime interpreter. The Java virtual machine (JVM) is the cornerstone on top of which the Java technology is built upon. It is the component of the Java technology responsible for its hardware and platform independence. JVM largely helps in the abstraction of inner implementation from the programmers who make use of libraries for their programmes from JDK.

JVM

Internals

Like a real computing machine, JVM has an instruction set and manipulates various memory areas at run time. Thus for different hardware platforms one has corresponding implementation of JVM available as vendor supplied JREs. It is common to implement a programming language using a virtual machine. Historicaly the best-known virtual machine may be the P-Code machine of UCSD Pascal.

A Java virtual machine instruction consists of an opcode specifying the operation to be performed, followed by zero or more operands embodying values to be operated upon. From the point of view of a compiler, the Java Virtual Machine (JVM)is just another processor with an instruction set, Java bytecode, for which code can be generated. Life cycle is as follows, source code to byte code to be interpreted by the JRE and gets converted to the platform specific executable ones.

Sun’s JVM

Sun’s implementations of the Java virtual machine (JVM) is itself called as JRE. Sun’s JRE is availabe as a separate application and also available as part of JDK. Sun’s Java Development Tool Kit (JDK) comes with utility tools for byte code compilation “javac”. Then execution of the byte codes through java programmes using “java” and many more utilities found in the binary directory of JDK. ‘java’ tools forks the JRE. Implementation of JVMs are also actively released by other companies besides Sun Micro Systems.

JVM for other languages

A JVM can also be used to implement programming languages other than Java. For example, Ada source code can be compiled to Java bytecode, which may then be executed by a Java virtual machine (JVM). That is, any language with functionality that can be expressed in terms of a valid class file can be hosted by the Java virtual machine (JVM). Attracted by a generally available, machine-independent platform, implementors of other languages are turning to the Java virtual machine (JVM) as a delivery vehicle for their languages. PHP with Quercus is such an example.

Just-in-time Compiler (JIT)

JIT is the part of the Java Virtual Machine (JVM) that is used to speed up the execution time. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here the term “compiler” refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

serialVersionUID

I found eclipse is continuously warning me about ‘serialVersionUID’
whenever i tried to save a Java file. I was thinking that there will
be a relation between jdk version in which the class has been created.
please see http://www.javaworld.com/javaworld/jw-02-2006/jw-0227-control.html

Java serialisation provides a serialisation id serialVersionUID or
suid for version control. this informs the java serialisation
mechanism which class version is suitable with that serialised object.

java.io.UTFDataFormatException: Invalid byte 1 of 1-byte UTF-8 sequence

Today I got interrupted with an interesting exception

java.io.UTFDataFormatException: Invalid byte 1 of 1-byte UTF-8 sequence

The scenario was, I am trying to parse an xml string. I am taking the byte array from the xml string, and give that array as input to xml reader stream. I have used java.lang.String.getBytes() for this.

Unfortunately, I got a chinese (or any other funny) characters as a value of one node in the xml. Ooof. I got up with the above error. Later, I found that getBytes() method supports only the western encoding, not UTF-8. So by using java.lang.String.getBytes("UTF-8") method, we solved the issue! nice na!

How long is your String object?

How long is your text string? You might need to know that answer to check whether user input conforms to data field length constraints. Database text fields usually make you constrain entries to a specific length, so you might need to confirm text length before submitting it. Whatever the reason, we all occasionally need to know the length of a text field. Many programmers use a String object’s length method to get that information. In many situations, the length method provides the right solution. However, this isn’t the only way to determine a String object’s length, and it’s not always the correct way either.

You have at least three common ways to measure text length in the Java platform:

  1. number of char code units
  2. number of characters or code points
  3. number of bytes

Counting char Units

The Java platform uses the Unicode Standard to define its characters. The Unicode Standard once defined characters as fixed-width, 16-bit values in the range U+0000 through U+FFFF. The U+ prefix signifies a valid Unicode character value as a hexadecimal number. The Java language conveniently adopted the fixed-width standard for the char type. Thus, a char value could represent any 16-bit Unicode character.

Most programmers are familiar with the length method. The following code counts the number of char values in a sample string. Notice that the sample String object contains a few simple characters and several characters defined with the Java language’s \u notation. The \u notation defines a 16-bit char value as a hexadecimal number and is similar to the U+ notation used by the Unicode Standard.

private String testString = "abcd\u5B66\uD800\uDF30";
int charCount = testString.length();
System.out.printf("char count: %d\n", charCount);

The length method counts the number of char values in a String object. The sample code prints this:

char count: 7

Counting Character Units

When Unicode version 4.0 defined a significant number of new characters above U+FFFF, the 16-bit char type could no longer represent all characters. Starting with the Java 2 Platform, Standard Edition 5.0 (J2SE 5.0), the Java platform began to support the new Unicode characters as pairs of 16-bit char values called a surrogate pair. Two char units act as a surrogate representation of Unicode characters in the range U+10000 through U+10FFFF. Characters in this new range are called supplementary characters.

Although a single char value can still represent a Unicode value up to U+FFFF, only a char surrogate pair can represent supplementary characters. The leading or high value of the pair is in the U+D800 through U+DBFF range. The trailing or low value is in the U+DC00 through U+DFFF range. The Unicode Standard allocates these two ranges for special use in surrogate pairs. The standard also defines an algorithm for mapping between a surrogate pair and a character value above U+FFFF. Using surrogate pairs, programmers can represent any character in the Unicode Standard. This special use of 16-bit units is called UTF-16, and the Java Platform uses UTF-16 to represent Unicode characters. The char type is now a UTF-16 code unit, not necessarily a complete Unicode character (code point).

The length method cannot count supplementary characters since it only counts char units. Fortunately, the J2SE 5.0 API has a new String method: codePointCount(int beginIndex, int endIndex) . This method tells you how many Unicode code points (characters) are between the two indices. The index values refer to code unit or char locations. The value of the expression endIndex - beginIndex is the same value provided by the length method. This difference is not always the same as the value returned by the codePointCount method. If you’re text contains surrogate pairs, the length counts are definitely different. A surrogate pair defines a single character code point, which can be either one or two char units.

To find out how many Unicode character code points are in a string, use the codePointCount method:

private String testString = "abcd\u5B66\uD800\uDF30";
int charCount = testString.length();
int characterCount = testString.codePointCount(0, charCount);
System.out.printf("character count: %d\n", characterCount);

This example prints this:

character count: 6

The testString variable contains two interesting characters, which are a Japanese character meaning “learning” and a character named GOTHIC LETTER AHSA. The Japanese character has Unicode code point U+5B66, which has the same hexadecimal char value \u5B66. The Gothic letter’s code point is U+10330. In UTF-16, the Gothic letter is the surrogate pair \uD800\uDF30. The pair represents a single Unicode code point, and so the character code point count of the entire string is 6 instead of 7.

Counting Bytes

How many bytes are in a String? The answer depends on the byte-oriented character set encoding used. One common reason for asking “how many bytes?” is to make sure you’re satisfying string length constraints in a database. The getBytes method converts its Unicode characters into a byte-oriented encoding, and it returns a byte[]. One byte-oriented encoding is UTF-8, which is unlike most other byte-oriented encodings since it can accurately represent all Unicode code points.

The following code converts text into an array of byte values:

byte[] utf8 = null;
int byteCount = 0;
try {
utf8 = str.getBytes("UTF-8");
byteCount = utf8.length;
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
}
System.out.printf("UTF-8 Byte Count: %d\n", byteCount);

The target character set determines how many bytes are generated. The UTF-8 encoding transforms a single Unicode code point into one to four 8-bit code units (a byte). The characters a, b, c, and d require a total of only four bytes. The Japanese character turns into three bytes. The Gothic letter takes four bytes. The total result is shown here:

UTF-8 Byte Count: 11

String length
Figure 1. Strings have varying lengths depending on what you count.

Summary

Unless you use supplementary characters, you will never see a difference between the return values of length and codePointCount. However, as soon as you use characters above U+FFFF, you’ll be glad to know about the different ways to determine length. If you send your products to China or Japan, you’re almost certain to find a situation in which length and codePointCount return different values. Database character set enco
dings and some serialization formats encourage UTF-8 as a best practice. In that case, the text length measurement is different yet again. Depending on how you intend to use length, you have a variety of options for measuring it.

More Information

Use the following resources to find more information about the material in this technical tip:

How should I compare String objects

You can compare String objects in a variety of ways, and the results are often different. The correctness of your result depends largely on what type of comparison you need. Common comparison techniques include the following:

  • Compare with the == operator.
  • Compare with a String object’s equals method.
  • Compare with a String object’s compareTo method.
  • Compare with a Collator object.

Comparing with the == Operator

The == operator works on String object references. If two String variables point to the same object in memory, the comparison returns a true result. Otherwise, the comparison returns false, regardless whether the text has the same character values. The == operator does not compare actual char data. Without this clarification, you might be surprised that the following code snippet prints The strings are unequal.

String name1 = "Sanjay";
String name2 = new String("Sanjay");
if (name1 == name2) {
System.out.println("The strings are equal.");
} else {
System.out.println("The strings are unequal.");
}

The Java platform creates an internal pool for string literals and constants. String literals and constants that have the exact same char values and length will exist exactly once in the pool. Comparisons of String literals and constants with the same char values will always be equal.

Comparing with the equals Method

The equals method compares the actual char content of two strings. This method returns true when two String objects hold char data with the same values. This code sample prints The strings are equal.

String name1 = "Sanjay";
String name2 = new String("Sanjay");
if (name1.equals(name2) {
System.out.println("The strings are equal.");
} else {
System.out.println("The strings are unequal.");
}

Comparing with the compareTo Method

The compareTo method compares char values similarly to the equals method. Additionally, the method returns a negative integer if its own String object precedes the argument string. It returns zero if the strings are equal. It returns a positive integer if the object follows the argument string. The compareTo, method says that cat precedes hat. The most important information to understand about this comparison is that the method compares the char values literally. It determines that the value of ‘c’ in cat has a numeric value less than the ‘h’ in hat.

String w1 = "cat";
String w2 = "hat";
int comparison = w1.compareTo(w2);
if (comparison < 0) {
System.out.printf("%s < %s\n", w1, w2);
} else {
System.out.printf("%s < %s\n", w2, w1);
}

The above code sample demonstrates the behavior of the compareTo method and prints cat < hat. We expect that result, so where’s the weakness? Where’s the problem?

Producing Errors

A problem appears when you want to compare text as natural language, like you do when using a word dictionary. The String class doesn’t have the ability to compare text from a natural language perspective. Its equals and compareTo methods compare the individual char values in the string. If the char value at index n in name1 is the same as the char value at index n in name2 for all n in both strings, the equals method returns true.

Ask the same compareTo method to compare cat and Hat, and the method produces results that would confuse most students. Any second grader knows that cat still precedes Hat regardless of capitalization. However, the compareTo method will tell you Hat < cat. The method determines this because the uppercase letters precede lowercase letters in the Unicode character table. This is the same ordering that appears in the ASCII character tables as well. Clearly, this ordering is not always desirable when you want to present your application users with sorted text.

Another potential problem appears when trying to determine string equality. Text can have multiple internal representations. For example, the name “Michèle” contains the Unicode character sequence M i c h è l e. However, you can also use the sequence M i c h e ` l e. The second version of the name uses a “combining sequence” (‘e’ + ‘`’) to represent ‘è’. Graphical systems that understand Unicode will display these two representations so that they appear the same even though their internal character sequences are slightly different. A String object’s simplistic equals method says that these two strings have different text. They are not lexicographically equal, but they are definitely equal linguistically .

The following code snippet prints this: The strings are unequal. Neither the equals nor compareTo methods understand the linguistic equivalence of these strings.

String name1 = "Michèle";
String name2 = "Miche\u0300le"; //U+0300 is the COMBINING GRAVE ACCENT
if (name1.equals(name2)) {
System.out.println("The strings are equal.");
} else {
System.out.println("The strings are unequal.");
}

If you’re trying to sort a list of names, the results of String’s compareTo method are almost certainly wrong. If you want to search for a name, again the equals method will subtly trip you up if your user enters combining sequences…or if your database normalizes data differently from how the user enters them. The point is that String’s simplistic comparisons are wrong whenever you are working with natural language sorting or searching. For these operations, you need something more powerful than simple char value comparisons.

Using a Collator

The java.text.Collator class provides natural language comparisons. Natural language comparisons depend upon locale-specific rules that determine the equality and ordering of characters in a particular writing system.

A Collator object understands that people expect “cat” to come before “Hat” in a dictionary. Using a collator comparison, the following code prints cat < Hat.

Collator collator = Collator.getInstance(new Locale("en", "US"));
int comparison = collator.compare("cat", "Hat");
if (comparison < 0) {
System.out.printf("%s < %s\n", "cat", "Hat");
} else {
System.out.printf("%s < %s\n", "Hat", "cat");
}

A collator knows that the character sequence M i c h è l e is equal to M i c h e ` l e in some situations, usually those in which natural language processing is important.

The following comparison uses a Collator object. It recognizes the combining sequence and evaluates the two strings as equal. It prints this: The strings are equal.

Collator collator = Collator.getInstance(Locale.US);
String name1 = "Michèle";
String name2 = "Miche\u0300le";
int comparison = collator.compare(name1, name2);
if (comparison == 0) {
System.out.println("The strings are equal.");
} else {
System.out.println("The string are unequal.");
}

A Collator object can even understand several “levels” of character differences. For example, e and d are two different letters. Their difference is a “primary” difference. The letters e and è are different too, but the difference is a “secondary” one. Depending upon how you configure a Collator instance, you can consider the words “Michèle” and “Michele” to be equal. The following code will print The strings are equal.

Collator collator = Collator.getInstance(Locale.US);
collator.setStrength(Collator.PRIMARY);
int comparison = collator.compare("Michèle", "Michele");
if (comparison == 0) {
System.out.println("The strings are equal.");
} else {
System.out.println("The string are unequal.");
}

Summary

Consider when the equals method is more appropriate than the == operator. Also, when you need to order text, consider whether a Collator object’s natural language comparison is needed. After you consider the subtle differences among the various comparisons, you might discover that you’ve been using the wrong API in some places. Knowing the differences helps you make the right choices for your applications and customers.

More Information

Use the following resources to find more information about the material in this technical tip:

Make fun with Text : java.util.Scanner

Scanner accepts streams, file and other string input mechanisms and parses the string and give is the tokens. (It also allows the user to specify using which encoding the text has been built). By default, whatever you have given, it is homogenized by having the default delimiter, space, See the following example,


import java.util.*;
import java.io.*;
public class test
{
    public static void main(String [] args) throws FileNotFoundException
    {
       File f = new File(“test.java”);
       Scanner scanner = new Scanner(f);
       while (scanner.hasNext())
       {
           System.out.println(scanner.next());
       }
       scanner.close();
    }
}

OutPut:


C:\>java testimport
java.util.*;
import
java.io.*;
public
class
test
{
public
static
void
main(String
[]
args)
throws
FileNotFoundException
{
File
f
=
new
File(“test.java”);
Scanner
scanner
=
new
Scanner(f);
while
(scanner.hasNext())
{
System.out.println(scanner.next());
}
scanner.close();
}
}

funny, isnt it!!!

We can also change the delimiter, see the following example


import java.util.*;

import java.io.*;
public class test
{
 public static void main(String [] args) throws FileNotFoundException
 {
 File f = new File(“test.java”);
 Scanner scanner = new Scanner(f);
 scanner.useDelimiter(“\n”);
 while (scanner.hasNext())
 {
 System.out.println(scanner.next());
 }
 scanner.close();
 }
}

The output is same as that of above code, want to see that one also?


C:\>java test
import java.util.*;
import java.io.*;
public class test
{
 public static void main(String [] args) throws FileNotFoundException
 {
 File f = new File(“test.java”);
 Scanner scanner = new Scanner(f);
 scanner.useDelimiter(“\n”);
 while (scanner.hasNext())
 {
 System.out.println(scanner.next());
 }
 scanner.close();
 }
}

Really good one!

Spring Vs EJB ( A feature comparison)

In quite a few design brainstorming sessions, the debate between Spring and EJB results in a deadlock. There are developers who are damn passionate about Spring and hate EJBs. Let’s have a look at the main important differences between the two in terms of features they support.

Feature

EJB

Spring
Transaction management
  • Must use a JTA transaction manager.
  • Supports transactions that span remote method calls.
  • Supports multiple transaction environments through its PlatformTransactionManager interface, including JTA, Hibernate, JDO, and JDBC.
  • Does not natively support distributed transactions—it must be used with a JTA transaction manager.
Declarative transaction support
  • Can define transactions declaratively through the deployment descriptor.
  • Can define transaction behavior per method or per class by using the wildcard character *.
  • Cannot declaratively define rollback behavior—this must be done programmatically.
  • Can define transactions declaratively through the Spring configuration file or through class metadata.
  • Can define which methods to apply transaction behavior explicitly or by using regular expressions.
  • Can declaratively define rollback behavior per method and per exception type.
Persistence Supports programmatic bean-managed persistence and declarative container managed persistence. Provides a framework for integrating with several persistence technologies, including JDBC, Hibernate, JDO, and iBATIS.
Declarative security
  • Supports declarative security through users and roles. The management and implementation of users and roles is container specific.
  • Declarative security is configured in the deployment descriptor.
  • No security implementation out-of-the box.
  • Acegi, an open source security framework built on top of Spring, provides declarative security through the Spring configuration file or class metadata.
Distributed computing Provides container-managed remote method calls. Provides proxying for remote calls via RMI, JAX-RPC, and web services.