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:

Retrieving An Entity By ID In Go

Here is a code snippet demonstrating how to retrieve a datastore entity by a known kind and integer ID. This code also retrieves the entity ID from a HTTP parameter.

R represents a http.Request reference. The entity ID to retrieve is accessed from the user’s submitted form under the name entity_idKind represents a string containing the name of the kind to retrieve from the datastore. The retrieved entity is stored into the variable entity, which is the struct CustomStruct.

c := appengine.NewContext(r)
//Retrieve the entity ID from the submitted form. Convert to an int64
entity_id := r.FormValue("entity_id")
entity_id_int, err := strconv.ParseInt(entity_id, 10, 64) 
if err != nil {
    fmt.Fprint(w, "Unable to parse key")
    return;
}
//We manufacture a datastore key based on the Kind and the 
//entity ID (passed to us via the HTTP request parameter.
key := datastore.NewKey(c, kind, "", entity_id_int, nil)
//Load the Entity this key represents.
//We have to state the variable first, then conduct the Get operation 
//so the datastore understands the struct representing the entity.
var entity CustomStruct
datastore.Get(c, key, &entity)

In short, this code pulls out the Entity ID from the HTTP request, converts it into an integer, manufactures the entity’s key using the kind and entity id, and then retrieves the corresponding entity. The code then translates the retrieved entity into the defined CustomStruct variable entity.

app.yaml In PHP

I’ve been poking around the PHP runtime and building a few demonstration applications. One of the major difficulties with configuring a PHP app is getting the app.yaml file to work properly.

Here’s a demonstration app,yaml file to get a basic app going:

application: [app-id]
version: 1
runtime: php
api_version: 1
threadsafe: true
handlers:
- url: /static
  static_dir: static
  expiration: 30d
- url: /favicon.ico
  static_files: static/favicon.ico
  upload: static/favicon.ico
- url: .*
  script: yourphpfile.php

A Failed Cron

Occasionally, an application’s cron request may fail. If so, you’ll see the below screen in the Cron tab of the application dashboard:

Cron requests can fail for many reasons, so it’s important to check the application logs when you see this failure message.

App Engine Logos

Badge logos (sometimes called button logos) are used to advertise a website’s server software or platform. Here’s a few examples:

Apache Badge Logo

Apple Xserve:

PHP:

Personally, I always like seeing badge logos because they give an interesting insight into that website: which stack is powering the website, the preferred coding language of the webmaster, etc.

Here’s logos for App Engine:

For reference, these are the equivalent badge logos for Microsoft Azure and AWS:

 

Google Cloud Storage RetryHelper Failure

I have numerous applications which use Google Cloud Storage buckets to save files, maintain backups, etc. Most of these applications are Java apps using the official Google Cloud Storage library.

Yesterday one of these applications had difficulty accessing Cloud Storage and printed out the following error report:

The GCS library attempted to access Cloud Storage a total of 6 times; this image shows the last failure and the final “giving-up” error.

Here’s a copy of the error in text form:

com.google.appengine.tools.cloudstorage.RetryHelper doRetry: 
    RetryHelper(4.114 s, 6 attempts, com.google.appengine.tools.cloudstorage.GcsServiceImpl): 
    Attempt 6 failed, sleeping for 3140 ms: java.io.IOException: Response code 503, 
    retryable: Request: POST https://storage.googleapis.com/[bucket_url]/[file_name]
x-goog-resumable: start
x-goog-api-version: 2
Content-Type: image/jpg

no content

Response: 503 with 19 bytes of content
Content-Length: 19
Date: Thu, 01 Aug 2013 [time]
Server: HTTP Upload Server Built on Jul 21 2013 19:20:38 (1374459638)
Content-Type: text/html; charset=UTF-8
X-Google-Cache-Control: remote-fetch
Via: HTTP/1.1 GWA
Service Unavailable

And after 6 failures attempting to access the Google Cloud Storage bucket, the library reports an error and stops:

.<stderr>: IO Exception: RetryHelper(4.115 s, 6 attempts, 
    com.google.appengine.tools.cloudstorage.GcsServiceImpl): 
    Too many failures, giving up

Fortunately this seemed to be only a transient problem; the next upload to GCS succeeded.