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.

Extracting The Subdomain In Java

A short code example today: how to extract the subdomain in Java. The req object represents HttpServletRequest.

String subdomain = req.getRequestURL().toString();
subdomain = subdomain.substring(subdomain.indexOf("/") + 2, subdomain.indexOf("."));

For example, if the user entered http://subdomain.example.com , this code would store the word subdomain in the subdomain variable.

Google Error Page

A few weeks ago I wrote a post about how designing good error pages is important for UX. For another demonstration of a good error page, look at Google’s 404 error page:

And here’s a closeup of the robot:

It’s a simple, straightforward error page. It explains the error, pokes fun at the problem with a broken robot picture, and links the user to the root page (the Google logo links to the Google home page).

Displaying Time In Java

Web applications frequently need to display times and dates in other timezones, not just their local time zone or UTC. Here’s a code example that takes a date and expresses it in several different time zones:

Date add_date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("MMMMMMMMMM dd, yyyy hh:mm aa");
formatter.setTimeZone(java.util.TimeZone.getTimeZone("America/Los_Angeles"));
String cali_time = formatter.format(add_date);
formatter.setTimeZone(java.util.TimeZone.getTimeZone("America/Denver"));
String denver_time = formatter.format(add_date);
formatter.setTimeZone(java.util.TimeZone.getTimeZone("America/Chicago"));
String chicago_time = formatter.format(add_date);
formatter.setTimeZone(java.util.TimeZone.getTimeZone("America/New_York"));
String ny_time = formatter.format(add_date);
formatter.setTimeZone(java.util.TimeZone.getTimeZone("France/Paris"));
String paris_time = formatter.format(add_date);
formatter.setTimeZone(java.util.TimeZone.getTimeZone("Russia/Moscow"));
String moscow_time = formatter.format(add_date);
formatter.setTimeZone(java.util.TimeZone.getTimeZone("China/Shanghai"));
String shanghai_time = formatter.format(add_date);

Deleting An Entity In Golang

Here’s a short code example demonstrating how to delete an entity in Go. C is an appengine.Contextreference, kind is the entity kind, and entity_id_int represents the integer ID of the entity.

key := datastore.NewKey(c, kind, "", entity_id_int, nil)
datastore.Delete(c, key)

Integrating App Engine Into A Google Cloud Project

If you currently have an App Engine application, you might be interested in connecting it to other Google Cloud services such as Cloud Storage and Compute Engine. But before you do, you need to integrate your App Engine application into a Google Cloud project.

Go to https://cloud.google.com/console‎ and click on a project (in this picture, Fact is an App Engine application):

If you see this screen (no options for Cloud SQL, Cloud Storage, etc) then you haven’t integrated your App Engine app into a Google Cloud project:

Here’s how to integrate your App Engine application. First, go to Application Settings in App Engine’s administration console:

Go to the bottom of the page. You’ll see a Cloud Integration section:

Press the button marked Add Project. The section will change to this screen:

Wait a few minutes, and the integration should complete:

Now your project console should show options for Cloud Storage, Cloud SQL, and other Google Cloud services: