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… :)

Advertisements

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: