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:

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.