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;

Retweeting In Java

Earlier I posted examples of how to log into Twitter and post a tweet using the twitter4j library. Now here’s a function demonstrating how to retweet a post.

This function is entirely self-contained; all it requires is a global variable twitter, which represents a twitter4j.Twitter object preconfigured with the proper authentication details.

public void doRetweet() {
    /**
     * To demonstrate retweeting, we'll search Twitter for all tweets that contain 
     * the phrase "mail not working" (including quotation marks). We'll then select 
     * a random tweet, and retweet it into our stream.
     */
    try {
        //Search for tweets, then pull out a list of those tweets.
        //A Status is how twitter4j refers to an individual tweet.
        twitter4j.Query q = new twitter4j.Query("\"mail not working\"");
        q.count(100);
        List<Status> results = twitter.search(q).getTweets();
        //Randomly select a tweet
        Random generator = new Random();
        int pick = generator.nextInt(results.size());
        Status status_to_retweet = results.get(pick);
        //Log the tweet we're retweeting
        System.out.println("Now retweeting: " + status_to_retweet.toString());
        //And finally retweet that tweet
        long status_id = status_to_retweet.getId();
        twitter.retweetStatus(status_id);
    }
    catch (TwitterException e) {
        System.err.println("A TwitterException has occurred while attempting to retweet. Exception message: " + e.getMessage());
    }
}//end function

Creating A Static IP Address In Google Compute Engine

First, go to the Google Cloud console at https://cloud.google.com/console . You’ll see the following screen. Click on a project or create a new one:

Click on the Compute Engine link on the next screen:

Press the Networks link on the left hand side navigation bar:

You’ll see the button New static IP within the Networks screen:

Name your new IP address, set a description (optional), and set the region where your IP address is located in. You can optionally also attach your new IP to a machine, if you have one running.

After you click the Create button, Compute Engine will need a few seconds to allocate a new IP address:

Once the allocation is complete, your new IP address will be listed in the Networks screen:

Querying The Datastore In Golang

Here’s a demonstration of how to query the datastore in Go.

In this example we filter on PropertyOne, requiring it to be equal to true. You can also set other inequalities such as greater than ( > ). Kind is the kind of the entities to query, and PropertyTwodemonstrates ordering by descending order. CustomStruct is the struct that was used to create the entity. Remember to put your entity processing code just before the last brace ( } ).

//Search the datastore for entities
q := datastore.NewQuery(kind).Filter("PropertyOne =", true).Order("-PropertyTwo")
//Loop through each returned entity.
for t := q.Run(c); ; {
    //This represents the entity currently being processed.
    var x CustomStruct
    key, err := t.Next(&x)
    if err == datastore.Done {
        //This "error" means that we're done going through entities
        //Since we're done, break out of this loop.
        break
    }
    if err != nil {
        //Some other error happened. Report error and panic.
        c.Infof("Error in querying datastore: %v", err)
        panic(err)
    }
    //DO SOMETHING HERE WITH ENTITY x
}//end for going through q.Run

Oops! We Couldn’t Retrieve Your List Of Kinds.

Occasionally you may see the error Oops! We couldn’t retrieve your list of kinds from the datastore viewer screen of the App Engine admin console:

Generally this is a transient error: it essentially means that the App Engine admin console is currently too busy to show a view of your datastore’s contents. Wait a few minutes and refresh the page, your datastore’s information should appear.

Seeing this error can also mean that the datastore is empty; for example, if it’s a just-created application.