Determine whether application is running on local server or App Engine

If you are working on developing some application on Google App Engine. You may come up with such situation to switch your production code with your local dev code. Following is my solution for this problem. I have initialized a servlet from web.xml. That set appropriate value in a static boolean. I will use this boolean in whole of my application. I used getServletContext().getServerInfo().

Note: You must read App Engine docs about how they take load-on-startup.

App Engine supports the <load-on-startup> element for servlet declarations. However, the load actually occurs during the first request handled by the web server instance, not prior to it.

Following is my code snippet.

StartupServlet.java: A generic servlet. Which will be initialized when server starts.

public class StartupServlet extends GenericServlet {

public void init() {
String serverInfo = getServletContext().getServerInfo();
/* ServletContext.getServerInfo() will return "Google App Engine Development/x.x.x"
* if will run locally, and "Google App Engine/x.x.x" if run on production envoirnment */
if (serverInfo.contains("Development")) {
Constants.DEV_MODE = true;
}else {
Constants.DEV_MODE = false;
}
}

@Override
public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {
// TODO Auto-generated method stub

}
}

web.xml: Add following contents in it

  <servlet>
    <servlet-name>StartupServlet</servlet-name>
    <servlet-class>com.servlet.StartupServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

    <servlet-mapping>
    <servlet-name>StartupServlet</servlet-name>
    <url-pattern>/Startup</url-pattern>
  </servlet-mapping>

Now you can use Constants.DEV_MODE anywhere in your application. It will be true if you are on local server. And false if you are on GAE. For this constant you can make a class with name Constant and declare a static boolean with name DEV_MODE.

If you have anyother idea to implement this solution or you can help me to improve my one. Please drop your comments.

Related Posts Plugin for WordPress, Blogger...

Leave a Reply

Your email address will not be published. Required fields are marked *