Wednesday, April 30, 2014

Java QR Code Decoder using ZXing


Today, I came across a requirement in my office project where I had to scan some QR codes in Java. For that we used Tasman Barcode Recognition software owned by Accusoft. Then I was interested to see if there are any free and open source softwares for QR Code encoding/decoding. Then I came across ZXing ("zebra crossing") which is a multi-format 1D/2D barcode/qrcode image processing library implemented in Java, with ports to other languages as well.

Below is the example of how a QR Code image can be decoded using ZXing librabry.

Library Downloads:

You'll need two jars core.jar and javase.jar which can be downloaded from here:

  • Core: http://repo1.maven.org/maven2/com/google/zxing/core/
  • Javase: http://repo1.maven.org/maven2/com/google/zxing/javase/

Steps:

1. Create a Java Project.

  • The following is the project I created in eclipse. 


2. Create a folder "libs" in the above example and put the jars into the folder.

3. Add the jars to the Project Build Path:

  • Right click on the project -> Properties -> Java Build Path -> Libraries Tab -> Add JARs...



4. Create a main class as follows:

package com.qrcode.decoder;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Reader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;

public class QRCodeDecoder {
       public static void main(String[] args) throws IOException {

              File imageFile = new File("D:\\image.png");

              BufferedImage image = ImageIO.read(imageFile);

              try {
                     LuminanceSource source = new BufferedImageLuminanceSource(image);

                     BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
                     Reader reader = new MultiFormatReader();
                     Result result = reader.decode(bitmap);

                     System.out.println("Barcode text: " + result.getText());
              } catch (Exception e) {
                     e.printStackTrace();
              }
       }
}


5. DONE.

Userful Reference:

https://github.com/zxing/zxing/


Saturday, April 12, 2014

Enable Nexus 5 Google Now in Nepal ( Location reporting in Nepal Issue)


I bought a Nexus 5 while I was in US, where Google Now was working perfectly fine. When I returned back to Nepal, Google Nexus was still working. But unfortunately, while exploring my Nexus 5, I happened to disable 'Google Now' feature. Then walla! it's gone. And it didn't let me enable the 'Google Now' again. It asks to first enable the 'Location Reporting'. Nexus 5 says the Location Reporting is 'Not Available in Nepal'. I searched for the wayout in the internet couple hours, tried apps to fake the GPS location, but none of them worked. I couldn't enable 'Location Reporting' in Nexus 5 here (in Nepal). 

But eventually, I found a solutions to enable 'Google Now' even if the Location Reporting is unavailable. And now, I have enabled the 'Google Now' in my Nexus 5. So, I thought it would be helpful to share the wayout with you guys. 

Here is the list of steps to follow. It didn't work for me at first. I needed to repeat the steps from 11 through 14 couple times. And finally it worked!

 
1. Turn on Developer Options: 
  • Settings > About Phone > tap 'Build Number' several times until you are notified that you are a developer
2. Allow Mock Locations: 
  • Settings > Developer Options > check 'Allow mock locations'
3. Download and install 'Fake GPS location' by LEXA from Google Play

4. Set a fake location to somewhere where Google Now is enabled (e.g. New York): 
  • open 'Fake GPS' > click on the search button > type the location > click OK > click 'Set location'
5. Make sure that the fake location is started when the device is switched on: 
  • open 'Fake GPS' > go to settings > check 'Start on boot'
6. Switch off your phone

7. Take out your SIM

8. Switch on your phone

9. Deactivate Android Device Manager: 
  • Google Settings > Android Device Manager > Uncheck both options
10. Disable Google Play Services: 
  • Settings > Apps > All > Google Play Services > Disable
11. Disconnect your account: 
  • Settings > Google (under the subtitle 'ACCOUNTS') > Search > Accounts & Privacy > Google Account > Sign out
12. Re-connect your account: 
  • Settings > Google (under the subtitle 'ACCOUNTS') > Search > Accounts & Privacy > Google Account > click on your email address
13. Now accept Google Now: 
  • (if not asked automatically) Settings > Google (under the subtitle 'ACCOUNTS') > Search > turn on Google Now
14. Enable Google Play Services: 
  • Settings > Apps > Disbaled > Google Play Services > Enable
15. Now, you can stop fake GPS: 
  • open 'Fake GPS' > click 'Stop'
16. Uninstall 'Fake GPS' if you want

17. Activate Android Device Manager: Google Settings > Android Device Manager > check both options

18. Switch off your phone

19. Put your SIM in

20. Switch on your phone
 


That's it! Now you should be able to enable 'Google Now' in your Nexus 5 from anywhere.

Please comment below to let everyone know how it goes with your Nexus 5.

Thanks.

Tuesday, April 8, 2014

JSP Basics


You'll find here some basics of JavaServer Pages (JSP), which I summed up as a note while I was learning it.

The Intro of JSP
  • An extension of the servlet technology which offers both scripting ( as in HTML) as well as programming (as in Servlets) 
  • When a JSP page is requested, the JSP container ( also called page compiler) compiles the jsp page into a servlet class. 
  • The JSP API that handles all the JSP technology has been bundled under the following two packages: 
    • javax.servlet.jsp 
    • javax.servlet.jsp.tagext 


JSP Syntax

A JSP page is all about JSP tags and some template data ( such as HTML tags). That's pretty much of it. It always feels good learning about JSP as we get to see the very well-know HTML tags (I presumed that you already know HTML at this point).

JSP consists of three types of elements.
  • Directive elements 
  • Scripting elements 
  • Action elements 


DIRECTIVES
<%@ directiveName (attributeName="atrributeValue") %>

These are the messages/information to the JSP container on how it should translate the JSP page into the corresponding servlet.

Again, there are three types of directives:

  • Page directives
  • Include directives
  • Tag library directives 

1. Page Directive
<%@ page (attributeName="atrributeValue") %>

You might have encountered some "import" statements at the beginning of some JSP pages. Those import statements falls under this category. E.g.

<%@ page import="java.util.Date, java.util.Enumeration" language="java" %>
where,
          page => represents directiveName
          import/language => represents attributeName
          and the values enclosed by quotes represents atrributeValue

The following is the list of available Page directive attributes:
Attribute
Value Type
Default Value
language
Scripting language name
"java"
info
String
Depends on the JSP container
contentType
MIME type, character set
"text/html;charset=ISO-8859-1"
extends
Class name
None
import
Fully qualified class name or package name
None
buffer
Buffer size or false
8Kb
autoFlush
Boolean
"true"
session
Boolean
"true"
isThreadSafe
Boolean
"true"
errorPage
URL
None
isErrorPage
Boolean
"false"

NOTE:
  • Except for the import attribute, JSP does not allow to repeat the same attribute within a page directive or in multiple directives on the same page. 

Page Attributes a little in-depth:
  • language 
    • <%@ page language="java" %>
    • The only supported language by Tomcat JSP Container
    • Other JSP containers might accept different languages
  • info 
    • <%@ page info="any string here" %>
    • Can be retrieved by calling the method getServletInfo() from anywhere withing the page
  • contentType 
    • <%@ page contentType="application/json; charset=UTF-8" %> 
    • Defines MIME type of the HTTP response sent to the client 
  • extends 
    • <%@ page extends="yourClass" %>
    • Defines the parent class that will be inherited by the generated servlet of the current page
    • This attribute is less common
  • import 
    • <%@ page import="java.io.*" %>
    • One of the most common attributes used
    • Same as we do in java classes/interfaces
    • By default, tomcat imports the following packages:
      • javax.servlet.* 
      • javax.servlet.http.* 
      • javax.servlet.jsp.* 
      • javax.servlet.jsp.tagext.*
      • org.apache.jasper.runtime.*
  • buffer 
    • <%@ page buffer="none" %>
    • <%@ page buffer="20kb" %>
    • <%@ page buffer="20" %>
    • buffer="20" is the same as "20kb"
    • But it's up to the JSP container to use its discretion to increase the buffer in order for the improved performance
  • autoFlush 
    • <%@ page autoFlush="false" %>
    • If true, the JSP container automatically flushes the buffer when it's full.
    • If false, the buffer can be flushed manually by the following statement: 
      • out.flush()
  • session 
    • <%@ page session="true" %>
    • By default, the session is set "true", meaning the JSP page takes part in session management
    • It is wise and strongly advised not to set it true unless you specifically require it because this consumes resources.
  • isThreadSafe 
    • <%@ page isThreadSafe="true" %>
    • True indicates that the simultaneous access to this page is safe
    • False indicates that the simultaneous access to this page is not safe. In that case, the JSP container puts multiple requests in a queue and serves them only one at a time.
  • errorPage 
    • <%@ page errorPage="MyErrorPage.jsp" %>
    • Indicates the error page which is displayed if an uncaught exception occurs in the current page
    • The error page must have the page attribute isErrorPage="true"
  • isErrorPage 
    • <%@ page isErrorPage="true" %>
    • If true, then only be set as an error page in other JSP pages
    • If true, this page has an access to the exception implicit object

2. Include directives
<%@ include file="includes/Footer.html" %>
  • As the name suggest, Include Directive enables us to include the contents of other files in the current JSP page.
  • The included page can be static HTML page as well as dynamic JSP page.
  • Very commonly used to include Header page, Footer page or a page containing import statements and so on.


2. Taglib directives

  • The taglib, or tag library, directive can be used to extend JSP functionality. It's a broad topic so it's not covered here at this moment. It will be covered under it's own topic later soon.

SCRIPTING ELEMENTS


Scripting elements allow you to insert Java code in your JSP pages. There are three types of scripting elements:
  • Scriptlets
  • Declarations
  • Expressions 

1. Scriptlets
<% ... %>
  • Syntax looks similar to Directives. But don't get confused, Directives starts with <%@ i.e. <%@ ... %>

<%
  try {
    Class.forName("com.mysql.jdbc.Driver");
    System.out.println("JDBC driver loaded");
  }
  catch (ClassNotFoundException e) {
    System.out.println(e.toString());
  }
%>

...
...

<%
out.println("You can do anything here");

String str = "some string";
str = str + " string concatenation";
out.println( str );

%>


2. Declarations
<%! ... %>

  • Used to declare methods and variables that can be used from any point in the JSP page.
  • Can appear anywhere throughout the page. For instance, a method declaration can appear above a page directive that imports a class, even though the class is used in the method.
<%!
  String getSystemTime() {
    return Calendar.getInstance().getTime().toString();
  }
%>

<%@ page import="java.util.Calendar" %>

<%
  out.println("Current Time: " + getSystemTime());
%>

3. Expressions 
<%= ... %> 

  • Expressions get evaluated when the JSP page is requested and their results are converted into a String and fed to the print method of the out implicit object. 
  • If the result cannot be converted into a String, an error will be raised at translation time. If this is not detected at translation time, at request-processing time, a ClassCastException will be raised.
  • Don't need to add a semicolon at the end of an expression

Below is the two equivalent statements:


<!-- Expression -->

<%= java.util.Calendar.getInstance().getTime() %>

<!-- Equivalent Scriptlet -->

<% out.print(java.util.Calendar.getInstance().getTime()); %>



TO BE CONTINUED...