Auto Detect Environment in Google AppEngine
If you were working in a product which is in production or potentially get to production, then for sure you will be having other environments like Staging, Alpha (and Development of-course) to test your code before deploying it to production
And for each of these environments you need to setup different Credentials, Configurations and other properties, etc… Eg: ApiKeys, API Urls etc.
For this we will usually be having App mode based on enums like below,
and in a Constants class , we will be setting up property with different mode before deploying it. Like,
then based on the app mode, you may be loading a configurations from Json or Property file or setting up variables directly in the Constants.
But the big problem is, before each deployment we need to manually go and change the App Mode in Constants class, sometimes we may forget to do it (Oops!!!)
Lucky you don’t need to do this in Appengine, Lets see how we can avoid this.
Step 1: Determine whether our application is running locally or in appengine, for that appengine has provided a neat System Property,
SystemProperty.environment.value()
which has two possible values,
Development (when running locally)
Production (when running in appengine servers)
so with this we can quickly able to figure out if our application is running locally or not,
Step 2: Determining to which Appengine ID (app id or project id), our application is deployed to, once again appengine provides a System Property which tells the application id in which it was running, we can get the value by using the key,
SystemProperty.applicationId.key()
whose value is “com.google.appengine.application.id”, so a helper method like below can return the application id,
Note: you can also directly use ApiProxy.getCurrentEnvironment().getAppId()
And thats it, by using these two helper methods we can able to auto detect the app mode, so the final constants file will look like,
Great, now you can deploy your application to any environment without manually needing to update app mode.
Happy coding!!!