Geolocating A Tweet In Java

Here’s a demonstration of how to use the twitter4j library to post a tweet and set a location from where it was posted.

This example requires a twitter4j.twitter object (the twitter variable) to be preconfigured with authentication tokens. Replace the text Orlando, FL with a string describing the user’s location, and the GPS coordinates with your user’s coordinates.

    StatusUpdate status = new StatusUpdate(tweet_text);
    /**
     * We'll add location information for this tweet. 
     * Here, we tell Twitter that this tweet was made from Orlando, FL.
     * The GPS coordinates here are for Walt Disney's Hollywood Studios theme park.
     */
    status.placeId("Orlando, FL");
    GeoLocation geolocate = new GeoLocation(28.355269, -81.559390);
    status.setLocation(geolocate);
    status.setDisplayCoordinates(true);
    //And finally, post this tweet.
    try {
        twitter.updateStatus(status);
    }
    catch (TwitterException e) {
        System.err.println("Problem accessing Twitter. Exception message: " + e.getMessage());
    }

Remember the appropriate import:

import twitter4j.*;

The Cron Log

The following is an example of a request originating from a cron:

It’s easy to tell this request originates from cron because (1) the originating IP is 0.1.0.1 (which is a reserved IP; cron requests come only from that address) and (2) the queue name is listed as cron .

Adding A Cookie To A Response In Java

Here’s a basic example of how to set a cookie into a servlet response.

Cookie_name and cookie_value is the name and value for the cookie to store. The variable resp represents a javax.servlet.http.HttpServletResponse reference. Notice setMaxAge(int expiry) – this method sets how long the cookie should last before it expires in seconds. In this example I set a value of 2 weeks (multiplying the following together: 60 seconds, 60 minutes, 24 hours, 7 days, 2 weeks).

Cookie cookie = new Cookie(cookie_name, cookie_value);
cookie.setMaxAge(2 * 7 * 24 * 60 * 60);//Two weeks to expire, in seconds.
resp.addCookie(cookie);

Remember to add the import (the package includes the Cookie class and HttpServletResponse ):

import javax.servlet.http.*;

Checking To See If An Application Is In Production

Sometimes an application needs to be able to tell if it’s in production (deployed on App Engine servers) or in development (deployed on the dev appserver on a developer’s local machine). You can test this by querying the SystemProperty class. Here’s a code example:

String runtime_env = SystemProperty.environment.value().toString(); 
if (runtime_env.equalsIgnoreCase("Production")) {
    //This application is in production. Do something special.
}
else {
    //This application is NOT in production (perhaps the dev appserver)
}

Remember to import the appropriate class:

import com.google.appengine.api.utils.SystemProperty;

Setting SPF For Your Domain

Sender Policy Framework (SPF) is a way to validate outgoing mail; it essentially allows a domain to say, “only these named servers are allowed to send mail under my name; any other servers attempting to do so may be malicious or may be sending spam.” If you send mail from your domain, it’s important to set SPF rules so receiving domains know that your mail is valid and isn’t spam.

To create your SPF record, visit the SPF website and figure out the appropriate SPF record for your domain. Then place it as a TXT record in your domain’s DNS.

As an example, my domain sends no mail so the appropriate SPF record is:

v=spf1 -all

If you have NameCheap as your domain registrar, here’s how to set an SPF record. First, log in and click the link All Host Records:

Put in the following settings:

Host Name: @
IP Address: v=spf1 -all
Record Type: TXT
TTL: 1800

Here’s how it looks like on the administration console:

If you use a different domain registrar there should be similar options. If not, contact your registrar for the appropriate steps to take.

Measuring Elapsed Time: System.nanoTime()

When I need to measure elapsed time (for example, timing how long an API call takes) I prefer to use System.nanoTime() instead of using the usual method of (new Date()).getTime().

The key idea to remember is that nanoTime() doesn’t return a timestamp – it represents a measurement of time from some arbitrary point (so for example nanoTime() could return a negative figure). This helps when writing self-documenting code: a variable storing a nanoTime() value can only be used for elapsed time comparisons, not timestamp recording.

Here’s an example of measuring elapsed time with System.nanoTime(). First, record the start time:

/**
 * Records the start time 
 * using System.nanoTime()
 */
Long start_time;
//Record the start time.
start_time = System.nanoTime();

Insert some time-consuming operation here, or another long-running call. Place this code where you want to end the timer:

//Calculate how long we've been running in nanoseconds.
Long diff_time = System.nanoTime() - start_time;

The variable diff_time stores the number of nanoseconds that has elapsed during the timer. Now suppose you wanted to throw an exception if the timer took more than 30 seconds (30 billion nanoseconds); here’s the example code:

//We set the maximum time in nanoseconds, multiplied by milliseconds, 
//multiplied by seconds.
Long MAXIMUM_TIME_OPEN = new Long(1000000L * 1000 * 30);
//If the runtime of this operation is longer than the time we've set, 
//throw an Exception.
if (diff_time > MAXIMUM_TIME_OPEN) {
    throw new IOException("Timeout has been exceeded.");
}

To keep the code easy to understand, we’re showing how the maximum time amount is computed: there are 1 million (1,000,000) nanoseconds in a millisecond, multiplied by 1 thousand milliseconds in a second (1,000), multiplied by 30 seconds.

Creating A Server In Java On Compute Engine

Compute Engine is a terrific hosting platform for applications – not only HTTP-based applications, but for servers running all types of services. To run these services an application has to listen for incoming connections using a server socket. Here’s how to do that in Java.

First, bind a server socket to a port. Here we’re binding it to the SMTP-reserved port 25. The port binding will fail if there’s already a server bound to that port.

//The server socket that handles all incoming connections.
ServerSocket server_socket = null;
//Bind the server socket to port 25. Fail and exit 
//if we fail to bind.
try {
    server_socket = new ServerSocket(25);
    System.out.println("OK: Bound to port 25.");
} 
catch (IOException e) {
    System.err.println("ERROR: Unable to bind to port 25.");
    e.printStackTrace();
    System.exit(-1);
}

Now wait for an incoming connection to accept (you can put the following code into a while loop if you want to accept multiple connections):

//Now we need to wait for a client to connect to us.
//Accept() blocks until it receives a new connection.
try {
    //A new client has connected.
    Socket client_socket = server_socket.accept();
    System.out.println("Accepted!");
    //Hand off the socket for further handling.
    //Do something here with the socket.
} 
catch (IOException e) {
    System.err.println("Failed to accept incoming connection:" + e.getMessage());
    e.printStackTrace();
    System.exit(-1);
}

From here, handle the socket as needed.

Remember to import the following classes:

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;