Wednesday, March 24, 2010

Email validation in Java

You can write your own code to validate email, but why bother if you have it ready. The Apache Commons project has a sub project called: Commons Validator. This project contains all sort of validation methods. One of the validations is used for email. In order to check if email address is valid all you have to do is:
EmailValidator.getInstance().isValid("some.mail.address@gmail.com");

Make sure to add the Commons Validator jar file and it's dependencies to your project.

Sunday, March 21, 2010

Java interview question: Check array for duplicate values in one pass

This question should be asked more precisely: How can array of size N filled with numbers up to N (0 to N – 1) be scanned for duplicate values (or more) with one scan (O(n))?

The answer lies in the body of the question: The fact that the array is filled with numbers up to N only, implies that a helper array of size N can be used to store the number of times each number appears in the first array. The value of the number in the first array is used as an index in the helper array. For example, if the first value in the array is: 5, then the 5th element in the helper array is incremented by 1. Of course, before incrementing the value in the helper array, we check if it is larger than 0. If it is larger than 0, the value of the first array was already counted once, and this current value is a duplicate.

The code of such method is very simple, lets have a look:

public class ArrayDuplicates {
  public static boolean isDuplicate(int[] arr)
  {
    int size = arr.length;
    int[] helperArr = new int[size];
    for (int i = 0; i < size; i++)
    {
      if (helperArr[arr[i]]++ > 0)
      {
        return true;
      }
    }
    return false;
  }
  public static void main(String[] args)
  {
    System.out.println(isDuplicate(new int[] { 2, 1, 0 }));
    System.out.println(isDuplicate(new int[] { 2, 0, 2 }));
  }
}


Note, that incrementing the index of the helper array (according to the value from the first array) and checking if we have already counted this number is all done the “if” sentence.

Friday, March 19, 2010

Java interview question: List “contains” method

This question verifies that you know how the “contains” method of List works.
Let’s have a look at this small piece of code:
Person person = new Person("guy");
List<Person> persons = new ArrayList<Person>();
persons.add(person);
System.out.println(persons.contains(person));

The question: Is it possible, that the output of this little piece of code returns: “false”.

At first look, the answer seems to be: NO, meaning, this code will always return “true”. So how can a “Person” object that was just created and added to a list, not be contained in it?

The answer, is in the way the “contains” method works. The “contains” method, is using the “equals” method in order to check if an object is contained in the list. Therefore, the code above can return “false” if the writer of the “Person” object overridden the equals method.

Java interview question: Count the number of “1” bits in a byte

Frankly, I think it is quite an idiotic question. Not because it is too easy or too hard question, but because I think this question doesn’t really imply on the practical programming capabilities of the person being interviewed. Anyway, a friend of mine was asked to solve this question, so I though it might be an interest for more developers looking for a job and having to handle all sort of weird questions.
In general, there are 2 solutions for this question:
  • First solution is iterating 8 times (a byte contains 8 bits). Each time the right most bit is extracted from the byte. and then the byte is shifted right one bit.
  • Second solution, is a little bit less straight forward, but more efficient: Divide the number by 2, if there is a modulo, count it. Repeat this operation as long as the number we are dividing is greater than zero.
Here is how the first solution looks in Java code:
public class GetBits {
public static int countBits(byte num)
{
  int count = 0;
  for (int i = 0; i < 8; i++)
{
    if ((num & 1) == 1) // check if right most bit is 1
{
count++;
}
num = (byte)(num >>> 1); // shit right 1 bit, including the sign bit
}
  return count;    
}


Here is how the second solution looks like:

public static int countBits(byte num)
{
  int count = 0;
  while (num > 0)
{
    if (num % 2 == 1) // check if number have modulo
{
count++;
}
num /= 2; // divide the number by 2
}
  return count;    
}

Note, that the first solution is a bit less efficient, because it always iterates 8 times. But, it handles both positive and negative values. The second solution will simply won’t work with negative numbers.

Monday, March 15, 2010

Excel Pivot Tables and Dynamic Range

Excel Pivot Table is a great tool for viewing and aggregating data. The data shown in a Pivot Table is taken from some range in one of the sheets of the excel file. The problem with Pivot Tables, is when you add new data. After refreshing the Pivot Table the new data is not shown. To solve this issue we can use a dynamic range. A dynamic range knows to grow automatically according to the rows we add. Suppose we have an excel file that contains 2 sheets: “data” and “pivot table”. We would like to create from the raw data in the sheet: “data” a dynamic range. This will allow us to add more rows to the “data” sheet, and just refresh the pivot table to see our new rows.
This is how our “data” sheet looks like:
1_pivot_data

And this is how our “pivot_table” sheet looks like:


2_pivot_table

In order to create a dynamic range from our raw data, we should go to the “Formulas” tab on excel and choose the “Define Name” option. A pop up window will be opened. In the window we should name the range. For example: “pivot_data_source”. In the “Refers to” field we define the dynamic range. The value that should be put there look like:
=OFFSET(data!$A$1,0,0, COUNTA(data!$A:$A), COUNTA(data!$1:$1))

Where the “data” is the name of the sheet in which the dynamic range is located.
The popup window looks like this:

image

After defining the dynamic data source, we should connect the pivot table with it. We do it by standing on the pivot table and selecting the “Options” tab from the main menu and choosing the “Change Data Source” option. A popup window is opened. In the field: “Table/Range” we should put the name of the dynamic range we defined: “pivot_data_source”.
The popup windows looks like:

5_pivot_data_source_change

Finally we would like the pivot table to be automatically refreshed every time our excel file is being opened. We do it by standing on the pivot table, then selecting “PivotTable Options…”. A popup window will be opened. On the “Data” tab we should check the option: “Refresh data when opening the file”. The popup window looks like:

7_pivot_table_refresh_on_load

Note that if you add new rows to the raw data, and you immediately want to see the changes in the pivot table, you should right click on the pivot table and choose the option “Refresh”. Press here to see an example of an excel file with pivot table and dynamic range defined.

Wednesday, March 3, 2010

Seam and Quartz integration

Seam is a great framework for easily building Internet applications in Java. It integrates with lots of well known existing java technologies and serves as a complement to JSF (Java Server Faces).
Quartz is a job scheduling framework allowing to easily add the capability of running scheduled jobs in your applications.
Quartz can be easily integrated with Seam. By integrating both technologies you will be able to enjoy Seam approach to managing beans on your web application.
Let’s take a look at a simple example:
First make sure you have all the jars needed to run Quartz and Seam.
Then go to your Seam “components.xml” file and add these lines:
<async:quartz-dispatcher/>
  <event type="org.jboss.seam.postInitialization">
  <action execute="#{quartzController.scheduleTimer}"/>
</event>
Now, put in your sources root directory (usually the “src”) the file: “seam.quartz.properties” file. A typical file may look like this:
org.quartz.scheduler.instanceName = Sched1
org.quartz.scheduler.instanceId = 1
org.quartz.scheduler.rmi.export = false
org.quartz.scheduler.rmi.proxy = false
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 3
org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
Now, to the Java code. The code is constructed from 2 Seam beans. The first bean contains the Quartz trigger class. I looks like:
package com.bashan.blog.job;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.async.QuartzTriggerHandle;
import java.io.Serializable;
import java.util.Date;
/**
* @author Bashan
*/
@Name("quartzController")
@AutoCreate
public class QuartzController implements Serializable {
@In
ScheduleProcessor processor;
private QuartzTriggerHandle quartzTriggerHandleDoJob;
public void scheduleTimer() {
quartzTriggerHandleDoJob = processor.doJob(new Date(), "0 0/1 * * * ?");
}
}
Note, that when calling to “doJob” method, a cron expression is passed. This expression describes the frequency in which the job will run (event minute in the example).

The second class contains the actual task we would like to do:
package com.bashan.blog.job;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.async.Asynchronous;
import org.jboss.seam.annotations.async.Expiration;
import org.jboss.seam.annotations.async.IntervalCron;
import org.jboss.seam.async.QuartzTriggerHandle;
import org.jboss.seam.log.Log;
import java.util.Date;
/**
* @author Bashan
*/
@Name("processor")
@AutoCreate
@Scope(ScopeType.APPLICATION)
public class ScheduleProcessor {
 
  @Logger
  static Log log;
 
  @Asynchronous
  public QuartzTriggerHandle doJob(@Expiration Date when, @IntervalCron String interval) {
    System.out.println("I am a Quartz job.");
    log.debug("Pass some information to the log");
    return null;
  }
}
The method “doJob” is a Seam asynchronous method. This method will be executed according to the data of the cron expression given in the class: QuartzController.

Sunday, February 28, 2010

Fixing Facelets/XHTML corrupted page issues in Google Chrome

I had a problem for quite some time on a web site being shown corrupted in Google Chrome. On the original HTML page everything was working great. On the resulted JSF/Seam/Facelets produced page, things were looking corrupted. The problem appeared only on Google Chrome. In other web browsers things look good. When I made a diff on the original working page and the page generated by JSF/Seam/Facelets, there was no difference. But still, page was corrupted on Google Chrome. After some investigation I noticed that Google Chrome was showing the page corrupted, simply because the generated page was not setting content type of: text/html. Google Chrome, unlike the other browsers, was probably sensitive to this issue. The solution to this problem is very simple. Just add to your JSF view tag the property: contentType. If your IDE (for example, IntelliJ) marks the contentType as unrecognized, ignore it. It runs ok. Here is an example of how the contentType is used:
<f:view contentType="text/html" />
Note, that you don’t have to wrap the view tag on all of your page, if you are using Facelets (the view tag is not mandatory in Facelets), so just putting the view tag is enough (like in the example).

Monday, February 22, 2010

Resize to max width and crop to height using ImageMagick

ImageMagik is a great open source tool that allows many conversions and manipulations of images. It supports huge amount of image types and comes as a command line tool, which makes it very easy to be executed from your favorite programming language.

Resizing an image to a maximum width is an easy task using ImageMagik. It is done with a command line tool named “convert”. For example, if we would like to proportionally resize an image named “image.jpg” to the maximum width of 160 we can do:

convert "c:\image.jpg" -resize 160 "c:\image_out.jpg"

Suppose we would like to do something a bit more complex than proportionally resizing and image to a maximum width: we would like to resize an image to a maximum width, but also crop the image to maximum height. We might want to do this kind of resize, since we want to show group of thumbnails at exactly the same size no matter what is the original image proportions are. Achieving this goal with ImageMagik is an easy task, but adds quite a few complexities to the above command.

For example, if we would like to proportionally resize an image maximum size of 100 pixels and crop the image to height of 80 pixels we have to use the “convert” command this way:

convert "c:\image.jpg" -resize 160x -resize "x160<" -resize 50% -gravity center -crop 100x100+0+0 +repage "c:\image_out.jpg"

If you really want to understand what this set of command exactly do, you can the ImageMagik documentation, which is pretty good. Note that the number 160 is exactly twice than 80. So if we would like to crop an image to height of 100 we would use the number 200.

Wednesday, January 20, 2010

Using Hibernate Transformers

There are times we have a class, we would like to fill with data according the data returned from a query. The class is a simple POJO and not an Hibernate entity, so Hibernate won’t recognize this class.
This can be done in Hibernate by using Transformers. Let’s have a look on a simple example, showing how Transformers can be used. First, let’s have a look at a simple POJO class named: “UserActivityStat”.
This class contains some statistical information. We would like to fill the statistical information of an instance, directly from running an Hibernate HQL.
public class UserActivityStat
{
private int totalPhotos;
private int totalViews;

public UserActivityStat() {
}

public int getTotalPhotos() {
return totalPhotos;
}

public void setTotalPhotos(int totalPhotos) {
this.totalPhotos = totalPhotos;
}

public int getTotalViews() {
return totalViews;
}

public void setTotalViews(int totalViews) {
this.totalViews = totalViews;
}
}
Now, let’s have a look at a simple method, that uses hibernate HQL and the Transformers class to fill “UserActivityStat” instance with data:
public UserActivityStat getUserActivityStat(User user)
{
return (UserActivityStat)hibernateSession.createQuery("select count(*) as totalPhotos, sum(p.views) as totalViews " +
"from Photo p where p.user = :user " +
"p.dateCreated  <= :now").
setParameter("user", user).
setTimestamp("now", new Date()).
setResultTransformer(Transformers.aliasToBean(UserActivityStat.class)).uniqueResult();
}
Note, that each of the 2 columns has an alias. This alias must be the name of the property on the “UserActivityStat” class. Also note for the use of the “setResultTransformer” along the “Transformers” class.

Tuesday, January 19, 2010

Calculate the distance between 2 Ips in Java using maxmind

Calculating the distance between 2 ips can be done easily by using the great geo service: Maxmind.

Maxmind is an affordable geo service with broad range of solutions like:

  • Country
  • City
  • Organization
  • ISP

and more…

Maxmind services comes in 2 flavors:

  • Paid service: This is very accurate data, in a reasonable low cost.
  • Free service: This is a little less accurate data, but a totally free service.

In order to calculate the distance between 2 IPs, we will use the free version of Maxmind. The free service is called: geoLite. we will use the service named: geoLite city. The geoLite city data contains location information. The location contains latitude and longitude information for ip ranges. Latitude and longitude information is a coordinate method used in may location services such GPS.

In order to use Maxmind we need 2 things:

Calculating the distance between 2 IPs is very easy, since Maxmind did all the hard work for us. We just have to get “Location” instance for the 2 IP and use the “distance” method of the “Location” instance. The returned result is the distance between the 2 IPs in kilometers.

Let’s have a look at a sample code that calculates the distance between Google and Apple:

package com.bashan.blog.maxmind;
import com.maxmind.geoip.Location;
import com.maxmind.geoip.LookupService;
import java.io.IOException;
/**
 * @author Bashan
 */
public class MaxmindTest {
  public static void main(String args[]) throws Exception {
    LookupService lookupService = new LookupService("C:\\GeoLiteCity.dat");
    Location locationGoogle = lookupService.getLocation("74.125.39.147");
    Location locationMicrosoft = lookupService.getLocation("17.251.200.70");
    System.out.println("Google is located on: " + locationGoogle.city);
    System.out.println("Apple is located on: " + locationMicrosoft.city);
    System.out.print("Distance: " + locationGoogle.distance(locationMicrosoft) + " kilometers");
  }
}

And the output:

Google is located on: Mountain View
Apple is located on: Cupertino
Distance: 13.218970226605398 kilometers
Not too far as you can see… ;-)