Scheduling with Java Threads

Posted on
  1. Get the desired start time for your task from a form:
    
    String startTime = request.getParameter("startTime");
    String startDate = request.getParameter("startDate");
    
    //assume time is in HH:MM format, date is in MMDDYEAR format
    int startHour = Integer.parseInt(startTime.substring(0, 2));
    int startMin = Integer.parseInt(startTime.substring(3, 5));
    int startMonth = Integer.parseInt(startDate.substring(0, 2));
    int startDate = Integer.parseInt(startDate.substring(2, 4));
    int startYear = Integer.parseInt(startDate.substring(4, 8));
    
    
  2. Get a time zone:
    Below are three approaches to get a Los Angeles time zone.
    • Method 1:
      This is the simplest way. If you can not find a supported time zone suits you, you can use method 2.
      TimeZone timezone = TimeZone.getTimeZone("America/Los_Angeles");
      
    • Method 2:
      String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000);
      SimpleTimeZone timezone = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]);
    • Method 3:
      SimpleTimeZone timezone = new  SimpleTimeZone(-28800000,
                      "America/Los_Angeles",
                      Calendar.APRIL, 1, -Calendar.SUNDAY,
                      7200000,
                      Calendar.OCTOBER, -1, Calendar.SUNDAY,
                      7200000,
                      3600000);
      
  3. Get the sleep time for the thread by comparing two timestamps:
    //get the timestamp for the start time set by users
    Calendar calendar = new GregorianCalendar(timezone);
    //the index values in the some parameters start from 0
    calendar.set(startYear, startMonth - 1, startDate - 1, startHour - 1, startMin, 0);
    Timestamp ts = new Timestamp(calendar.getTimeInMillis());
    long startTime = ts.getTime();
    
    //get current timestamp
    Calendar calendarNow = new GregorianCalendar(tz);
    Timestamp tsNow = new Timestamp(calendarNow.getTimeInMillis());
    long now = tsNow.getTime();
    
    // there are 90000000 ms offset
    long sleepTime = startTime - now + 90000000;
    
    
  4. Finally, wake up the thread after specific time period.
    try {
    	if (sleepTime > 0)
    		Thread.sleep(sleepTime);
            else{
                    System.out.println("Tasks are executing now...");
            }
    
            //list of tasks
    
    } catch (InterruptedException e) {
    	e.printStackTrace();
    }
    
    

Reference:

  • TimeZone Javadoc: http://download.oracle.com/javase/6/docs/api/java/util/TimeZone.html#getAvailableIDs%28%29
  • SimpleTimeZone Javadoc: http://download.oracle.com/javase/6/docs/api/java/util/SimpleTimeZone.html

Calculate the Distance between Two Locations Using Java

Posted on

This programming question occurred to me when I was preparing the solution for an introductory programming class. I have found this programming problem very interesting and I think it is a starting stone for many different applications that requires geographic information.

It is not an hard problem but the key is to understand the conversion between angle and radian during the calculation. First, you will need to get the latitude and longitude of the two cities. In this example, I will use San Jose and Los Angeles. I got the geographic information from http://www.gorissen.info/Pierre/maps/googleMapLocation.php.

San Jose: lat=37.220997, lon=-121.816406
Los Angeles: lat=33.920268, lon=-118.872070

Secondly, the formula to calculate the distance is given in the Wikipedia:

Below is the source code of the program:

public class Distance
{
   public static void main(String[] args)
   {
      Scanner in = new Scanner(System.in);

      System.out.print("Enter latitude and longitude for the first location: ");
      double x1 = Math.toRadians(in.nextDouble());
      double y1 = Math.toRadians(in.nextDouble());
      System.out.print("Enter latitude and longitude for the second location: ");
      double x2 = Math.toRadians(in.nextDouble());
      double y2 = Math.toRadians(in.nextDouble());

      double sec1 = Math.sin(x1)*Math.sin(x2);
      double dl=Math.abs(y1-y2);
      double sec2 = Math.cos(x1)* Math.cos(x2);
      //sec1,sec2,dl are in degree, need to convert to radians
      double centralAngle = Math.acos(sec1+sec2*Math.cos(dl));
      //Radius of Earth: 6378.1 kilometers
      double distance =  centralAngle * 6378.1;
      System.out.println("The distance is " + distance+" kilometers.");
   }
}

The distance between San Jose and Los Angeles is 453.9025838385787 kilometers.


REST and JAX-RS

Posted on

REST stands for Representational State Transfer. It’s a software architectural style for Web-based systems providing Web Services. It has become a preferable architecture style because it results in better Web performance, scalability, and simplified client and server interactions.

The resources on the Internet are the documents that can be access through URIs(Uniform Resource Identifier). A RESTful API means to provide the unique access to each document. Since each response will return the same document, when the client sends a request, its browser will check the modified date and it can probably use the cached document. This increases the Web performance on client side and at the same time reduces a great amount of traffic to the server. The other major feature of REST is keep the Web state-less, which means no needs for the session management.

Different from the RPC calls, the URIs for REST API calls are supposed to be used for locating the resource only and not the operations, which should be specified by the type of the HTTP request. There are four major types of requests for RESTful Web services:
1) get – retrieved resources with known URIs
2) post – create or modify resources with known URIs
3) put – create or modify resources. The server will return an URI when allocated
4) delete – remove resources with known URIs

JAX-RS is a Java API for RESTful Web Services. It defines a set of annotations to support HTTP requests. You can create a custom annotation using an @HTTpMethod designator. Here are a list of basic annotations:
@Path – relative URI path in the Web server
@PathParm – bind the value of a URI template parameter
@FormParm – bind the value of a form parameter contained in the request
@Produces – MIME media type that the method will return to the client browser
@Consumes – MIME media type that the method accepts

For more available annotations, please check out Java EE 6 API – javax.ws.rs.

Example:


@Path("/")
public class Library {

 /**
  * Handle get requests to relative path /book
  * @param book ID extracted from the URI
  * @return Book details
  */
 @Path("/book/{id}")
 @Get 
 public Book getBook(@PathParam("id") int id) {...}

 /**
  * Handle post requests that are in json format to relative path /book
  * @param all the form data sent from the client
  * @return Book details
  */
 @Path("/book/{id}")
 @POST 
 @Consumes("application/json")    
 @Produces("application/json")    
 public Book addBook(@FormParam("") Book newBook) {...}

}