Pages

Wednesday, February 23, 2011

Java Threads Example

This is a small example of how to use Threads in Java. The code will check if a number is prime or not. You can configure the number of threads that will run. Each thread will try to divide the number to be tested  by a different number. If the number to be tested gets divided by another number, the program will print that it is not prime and also print the number that it can be divided by. This example also demonstrates the use of the "AtomicIntger" class in the "java.util.concurrent" package. If you are looking for a simpler example you can take a look at this example first and then come back and take a look at this.

public class Divisor extends Thread {

  //Will hold the number to be tested
  private int testNumber;

  //Will hold the number we will try to divide by
  private AtomicInteger nextNumber;
 
  private int sqrtOfTestNumber;

  public Divisor(AtomicInteger nextNumber, int testNumber) {   
    this.nextNumber = nextNumber;
    this.testNumber = testNumber;
    sqrtOfTestNumber = (int) Math.ceil(Math.sqrt(testNumber));
  }

  @Override
  public void run() {
    while (nextNumber.intValue() < sqrtOfTestNumber
              &&
            PrimeTester.IS_PRIME.get()) {
      if (testNumber % nextNumber.incrementAndGet() == 0) {
        PrimeTester.IS_PRIME.set(false);
        System.out.println(testNumber + " is not a prime!");
        System.out.println("It can be divided by "
                             + nextNumber.intValue() + ".");
        return;
      }
    }   
  } 
}
public class PrimeTester {

  public static AtomicBoolean IS_PRIME =
                                  new AtomicBoolean(true); 
  private AtomicInteger nextNumber = new AtomicInteger(1);
  private int numberOfThreads;
  private int testNumber;

  public PrimeTester(int numberOfThreads, int testNumber) {
    this.numberOfThreads = numberOfThreads;
    this.testNumber = testNumber;
  }

  public void test() {
    for (int i = 0; i < numberOfThreads; i++) {
      new Divisor(nextNumber, testNumber).start();
    }
  }
 
  public static void main(String[] args) {
    PrimeTester primeTester = new PrimeTester(5, 370248452);
    primeTester.test();
  }
}

Note that the program will not output anything if the number is prime. This is because additional checks have to be performed in order to do this and it will complicate the code. Since this is meant to be a simple example, it has not been included here. Maybe it can be explained in a future post.

Sunday, February 20, 2011

PHP Logging Libraries

Recently while doing a project, I came across the need of a PHP logging library. The search for a php logging framework found me a few interesting results. The following are the libraries that I came across.

1) log4php
This logging library seems to be the most feature-rich library available. The RollingFile and DailyFile logging systems in this library can come in quite useful. Mail and Database logging are also available. This library can be configured using xml, properties file or through code, just like log4j. The log message format can be configured using layouts. This library is ideal for someone who is experienced with using log4j. The file compression functionality does not seem to be present in log4php at this time.

2) Zend_Log
This the Zend library component for logging. Other than logging to a file you can log to a database or email as well. Similar to log4php with Zend_Log you can configure the logged message's format.

3) Pear Logging Framework
This is the pear library for logging. This library supports logging to file,database and mail. You also have the option of setting the format of the log message.

4) KLogger
This library can log to file only. So for a lightweight application that does not require logging to database and email, this library can be used.

Hope this helped you to find the logging library that best suits your needs. You can follow the above links to find out more.

Wednesday, February 16, 2011

Maven Profiles Example

This is an example on a simple use-case for Maven profiles. It will be useful for someone who wants to implement one in their build or for someone who wants to know what is the use of having profiles.
Let us imagine that you need to have two builds. The difference in the two builds is the version of a single jar. For example, let us say that you need to have a build named profile-A with the version 1.0.0 of a jar and profile-B with the version 2.0.0 of a jar. The following is the pom.xml which shows how to do this.

<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>profiles-example</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>profiles-example</name>
  <url>http://maven.apache.org</url>
 
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <profiles>
      <profile>
          <id>profile-A</id>
          <dependencies>
              <dependency>
                <groupId>com.example</groupId>
                <artifactId>dependency</artifactId>
                <version>1.0.0</version>
              </dependency>
          </dependencies>
      </profile>
      <profile>
          <id>profile-B</id>
          <dependencies>
              <dependency>
                <groupId>com.example</groupId>
                <artifactId>dependency</artifactId>
                <version>2.0.0</version>
              </dependency>
          </dependencies>
      </profile>
  </profiles>
</project>

Now you can invoke profile-A using the command
mvn -Pprofile-A install
which will build the project with the dependency version 1.0.0.

Why would someone want to do this? This is a good example where  profiles can be used. To learn more about profiles, take a look at introduction to profiles in the maven documentation. You can specify other build specific parameters such as "plugins"," dependency management" etc. via profiles.

Tuesday, February 15, 2011

Copying Files in Maven

The need to copy files/directories is something that we come across when we use maven as the build tool. The maven resources plugin can be used to achieve this functionality. This example shows how to do this using the plugin. This link talks about some other methods that can be used to achieve this.

Debugging Firefox Add-Ons Using Chromebug

When writing add-ons for Firefox, the ability to debug the add-on makes the development process quite easier and faster as well. Chromebug is a Firefox add-on which provides this capability. The Chromebug user guide has instructions on how to install and start Chromebug. You can inspect the XUL elements of the add-on and debug JavaScript code using this tool. The following are some screenshots of the add-on in action.







Saturday, February 12, 2011

Sorting a HashMap in Java

First of all I have to point out that a HashMap can not be in a "sorted" state. This is because a HashMap does not have an order. On the other hand a TreeMap does have an order (it implements the interface SortedMap). So to sort a HashMap by key, you can use the code below.

Map sortedMap = new TreeMap(yourOriginalMap);

This will sort the map according to the keys' natural order.


In order to sort the HashMap based on the values, we have to pass a Comparator to the constructor of TreeMap. For this example let us assume that the values of the HashMap that you need to sort are Integers. Then the comparator would look like the following.


public class MyComparator implements Comparator<Object> {

    Map theMapToSort;

    public MyComparator(Map theMapToSort) {
        this.theMapToSort = theMapToSort;
    }

    public int compare(Object key1, Object key2) {
        Integer val1 = (Integer) theMapToSort.get(key1);
        Integer val2 = (Integer) theMapToSort.get(key2);
        if (val1 < val2) {
            return -1;
        } else {
            return 1;
        }
    }
}

Then you can sort the map using the following code

MyComparator comp = new MyComparator(originalMap);
TreeMap treeMap = new TreeMap(comp);
treeMap.putAll(originalMap);


Now the treeMap object will contain the values in the orginalMap, sorted by the values.

Friday, February 11, 2011

Using Google Search More Productively

When we want to find something on the web we turn to the search engines for help. Google is one of those search engines that help us find things. Today I though of sharing with you some tricks to easily find what you are looking for.
For convenience I will include all search queries inside "[" and "]".

Including terms inside double quotes will find you the exact match. For example, let us say that a software that you are using/writing is throwing an error. Let us say that the error is "could not open file". If someone else encountered this problem before you and asked for help online, then the phrase would exist in the same format and same words. But using the query [could not open file] would not find exact matches but similar ones. So if you want to find exact matches you can search with the phrase inside double quotes marks. So the search query ["could not open file"] would bring you results more relevant to your problem than the query [could not open file].

Another thing that we search the web for is opinions and reviews others have about products/services. As we all know such opinions and reviews are most found on blogs. For example let us say that we want to find a site that offers images for free(with no strings attached). If you use the Google query [free images] you will find several sites that say that they offer free images. But when you go to the actual site they say that you have to include a link to their site wherever you use the images. If someone found a site where they offer images for free they would have mentioned it in their blog. We can use Google to search all the  "wordpress.com" or "blogger.com" sites for the phrase "free images" using the query [free images site:wordpress.com] or [free images site:blogger.com]. You can also choose to double quote the search phrase to find an exact match as ["free images" site:wordpress.com].
Or let us take our first example. Let us say that the error "could not open file" is thrown by a php program that you are writing. Then you would find the answer on the php.net site or on a programming discussion site such as stackoverflow.com. You can use the queries ["could not open file" site:php.net] and ["could not open file" site:stackoverflow.com] to search those sites and find your answers.

You would probably have seen search functions provided within web sites. For example the zend framework site provides a search functionality which allows us to search the site. But what I experienced was that searching via Google provided faster results than using the search provided within the site. For example searching for the phrase "Zend_Application" via Google gave faster results than searching via the zend framework site.

You can find more help on using Google search here and here. They are sources provided by Google. I just thought of mentioning a few use cases so that anyone reading this blog can understand how to utilize the functionality that Google provides. Hope these tips will be useful to you.