25
May
11

Creating a Mock Data Provider


This page describes the process of creating a Java Servlet that returns mock data in JSON format, based on a query string provided by the client .

Background

Developers sometimes find themselves in situations where the back-end is still a work in progress. There also may be situations where (due to security restrictions) you don’t have access to the back end at all! User interface components require data in order for them to display properly on the page.

This page will describe a process of creating a MOCK data layer to read / generate data that you can use to feed your extJS components while they are being developed.

We will test the code by creating a simple client that makes an AJAX call to the Resource to display data.

In order to make this tutorial portable we will use HyperSQL Java in memory database to store the data.

This page uses the following frameworks/libraries

Solution

Create a Java Web Application that will allow the client to specify a query in Hibernate SQL Query Language (HSQL). The servlet will issue the call to get the data and return the JSON back to the caller.

WARNING: Don’t use this in production code. This is only scaffolding code to assist you in retrieving data to assist in developing the User Interface. Once your Interface is finished the servlet can simply be removed from your application.

Create the project

Create a new Project using a Maven archetype.

mvn archetype:generate -DarchetypeArtifactId=maven-archetype-webapp

groupId: com.test
artifactId: mock-data-provider

Answer the rest of the questions with defaults “Just hit the enter key”,

cd to the project base folder.

cd mock-data-provider

Since this is a web project maven2 does not create the java source folder.

Create missing folders now.
mkdir -p src/main/java/com/test
mkdir -p src/main/resources/com/test
mkdir -p src/main/resources/META-INF

Modify the project Configuration

The pom.xml file should look something like this.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.test</groupId>
  <artifactId>mock-data-provider</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>mock-data-provider Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20090211</version>
        </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate</artifactId>
      <version>3.2.6.ga</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>3.3.1.ga</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-annotations</artifactId>
      <version>3.3.1.GA</version>
    </dependency>
    <dependency>
      <groupId>commons-collections</groupId>
      <artifactId>commons-collections</artifactId>
      <version>3.2.1</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.9</version>
    </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring</artifactId>
            <version>2.5.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>2.5.6</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.14</version>
        </dependency>
        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <version>1.8.0.10</version>
        </dependency>
        <dependency>
            <groupId>org.apache.ddlutils</groupId>
            <artifactId>ddlutils</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>
 
  </dependencies>
  <build>
    <finalName>mock-data-provider</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.0.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
				<version>7.0.0.v20091005</version>
                <configuration>
                    <scanIntervalSeconds>2</scanIntervalSeconds>
                    <webAppConfig>
                        <contextPath>/dataProvider</contextPath>
                    </webAppConfig>
                    <stopKey>s</stopKey>
                </configuration>
            </plugin>
        </plugins>
  </build>
</project>

Database Setup and Configuration

The following configuration file is used by Apache DDLUtils to generate apply the schema changes each time the application restarts. Changes are made incrementally and every attempt is made to preserve the data. For more information about DDLUtils please see my other tutorial.

src/main/resources/ddl.xml

<?xml version="1.0"?>
<!DOCTYPE database SYSTEM "http://db.apache.org/torque/dtd/database.dtd">

<database name="mockdb">
    <table name="countries">
        <column name="name" type="VARCHAR" size="50" required="true" primaryKey="true" />
        <column name="shortName" type="CHAR" size="2" required="true" />
        <index name="country_x">
            <index-column name="name" />
        </index>
    </table>
</database>

JPA Configuration

src/main/resources/META-INF/persistence.xml

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">
   <persistence-unit name="manager1">
      <provider>org.hibernate.ejb.HibernatePersistence</provider>
      <properties>
         <property name="hibernate.archive.autodetection" value="class, hbm"/>
         <property name="hibernate.show_sql" value="true"/>
         <property name="hibernate.format_sql" value="true"/>
         <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
         <property name="hibernate.connection.url" value="jdbc:hsqldb:file:src/main/webapp/WEB-INF/db/mockdb"/>
         <property name="hibernate.connection.username" value="sa"/>
         <property name="hibernate.connection.password" value=""/>
         <property name="hibernate.connection.pool_size" value="0"/>
 
         <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
         <property name="hibernate.max_fetch_depth" value="3"/>
 
         <property name="hibernate.hbm2ddl.auto" value="validate"/>
 <!--
    * validate: validate the schema, makes no changes to the database.
    * update: update the schema.
    * create: creates the schema, destroying previous data.
    * create-drop: drop the schema at the end of the session.
-->
      </properties>
   </persistence-unit>
</persistence>

Shutting down the database gracefully

Since we are working with HSQLDB, it is critical that we gracefully shut-down the database when the application stops. Otherwise the data that was cached in memory will be lost.

We will use a “ServletContextListener” to listen for the application shut-down event. This will allow us to execute code to graceful shut-down the HSQLDB database.

Spring Configuration

Most of the spring configuration was done using Java Annotations, therefore this file is not too large.

src/main/resources/applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
 
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
 
http://www.springframework.org/schema/context
 
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
 
    <context:annotation-config/>
    <context:component-scan base-package="com.test"/>
 
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean" />
    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
 
</beans>

Java Code

src/main/java/com/test/Country.java

package com.test;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="countries")
public class Country {
	
	private String name;
	
	private String shortName;
	
	public Country() {
		super();
	}
	public Country(String name, String shortName) {		
		this.name = name;
		this.shortName = shortName;		
	}
	
	public void setName(String name) {
		this.name = name;
	}
	@Id
	public String getName() {
		return name;
	}
	public void setShortName(String shortName) {
		this.shortName = shortName;
	}

	@Column(columnDefinition="CHAR", length=2)
	public String getShortName() {
		return shortName;
	}
	

}

src/main/java/com/test/DBLifecycleContextListener.java

package com.test;
 
import java.io.InputStreamReader;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.sql.DataSource;

import org.apache.ddlutils.Platform;
import org.apache.ddlutils.PlatformFactory;
import org.apache.ddlutils.io.DatabaseIO;
import org.apache.ddlutils.model.Database;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
 
/**
 * This listener initializes or gracefully shuts down the database based on
 * events from the web application.
 */

public class DBLifecycleContextListener implements ServletContextListener {
    private DataSource dataSource = null;
 
    public DataSource getDataSource() {
		return dataSource;
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}
	public void contextDestroyed(ServletContextEvent event) {
        SimpleJdbcTemplate template = new SimpleJdbcTemplate(dataSource);
        template.update("SHUTDOWN;");
        System.out.println("Database Successfully Shutdown.");
    }

    public void contextInitialized(ServletContextEvent event) {
   		try {
			Class.forName("org.hsqldb.jdbcDriver");
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		}

		dataSource = new DriverManagerDataSource(
				"jdbc:hsqldb:file:src/main/webapp/WEB-INF/db/mockdb", "sa", "");
		Platform platform = PlatformFactory
				.createNewPlatformInstance(dataSource);
 
        Database database = new DatabaseIO().read(new InputStreamReader(
                getClass().getResourceAsStream("/ddl.xml")));
 
        platform.alterTables(database, false);
    }
}

src/main/java/com/test/MockDataManager.java

package com.test;

import java.util.List;

public interface MockDataManager {
	public List<Object> getList(String query);
}

src/main/java/com/test/MockDataManagerImpl.java

package com.test;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

@Repository("mockDataManager")
public class MockDataManagerImpl implements MockDataManager {
    private EntityManager entityManager;
    
    
    @PersistenceContext
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }
    
    
	@Override
	public List<Object> getList(String query) {
		return entityManager.createQuery(query).getResultList();
	}

}

src/main/java/com/test/MockDataServlet.java

package com.test;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class MockDataServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private MockDataManager mockDataManager;
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		ApplicationContext applicationContext = WebApplicationContextUtils
				.getWebApplicationContext(config.getServletContext());
		mockDataManager = (MockDataManager)applicationContext.getBean("mockDataManager");		
	}
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String query = request.getParameter("q");
		request.setAttribute("q", query);
		request.setAttribute("encodedq", query);
		if(query != null && !"".equals(query.trim())) {
			List stateList = mockDataManager.getList(query);
			System.out.println(stateList.size());
			JSONArray array = new JSONArray();
			
			for (Object object : stateList) {
				array.put(new JSONObject(object));
			}
			System.out.println(array.toString());
			
			PrintWriter writer = response.getWriter();
			String output = array.toString();
			writer.write(output);
			request.setAttribute("output", output);			
		}
		
	}
	
}

Web Configuration

src/main/webapp/WEB-INF/web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
 
    <listener>
        <listener-class>com.test.DBLifecycleContextListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
  
  <servlet>
  	<servlet-name>mockDataServlet</servlet-name>
  	<servlet-class>com.test.MockDataServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>mockDataServlet</servlet-name>
  	<url-pattern>/mockData</url-pattern>  	
  </servlet-mapping>
</web-app>

src/main/webapp/index.jsp

<jsp:useBean id="q" scope="request" class="java.lang.String"/>

<html>
<body>
<form action="mockData" method="get">
	<label>Enter Hibernate Query Example: select c from Country c where name like 'B%'</label><br/>
	<textarea name="q" cols="80" rows="5"><%=q%></textarea>
	<br/>
	<input type="submit" value="Submit"/>	
</form>
</body>
</html>

Test the application

Clean the project compile and start Jetty Servlet Engine.

mvn clean compile jetty:run

Shutdown the application

We shut down the application. This will ensure that the proper data file were created. We will open these data files and modify them inserting our data.

Insert the data

src/main/webapp/WEB-INF/db/mockdb.script

CREATE SCHEMA PUBLIC AUTHORIZATION DBA
CREATE MEMORY TABLE COUNTRIES(NAME VARCHAR(50) NOT NULL PRIMARY KEY,SHORTNAME CHAR(2) NOT NULL)
CREATE INDEX COUNTRY_X ON COUNTRIES(NAME)
CREATE USER SA PASSWORD ""
GRANT DBA TO SA
SET WRITE_DELAY 10
SET SCHEMA PUBLIC
INSERT INTO COUNTRIES VALUES('AFGHANISTAN','AF')
INSERT INTO COUNTRIES VALUES('ALBANIA','AL')
INSERT INTO COUNTRIES VALUES('ALGERIA','DZ')
INSERT INTO COUNTRIES VALUES('AMERICAN SAMOA','AS')
INSERT INTO COUNTRIES VALUES('ANDORRA','AD')
INSERT INTO COUNTRIES VALUES('ANGOLA','AO')
INSERT INTO COUNTRIES VALUES('ANGUILLA','AI')
INSERT INTO COUNTRIES VALUES('ANTARCTICA','AQ')
INSERT INTO COUNTRIES VALUES('ANTIGUA AND BARBUDA','AG')
INSERT INTO COUNTRIES VALUES('ARGENTINA','AR')
INSERT INTO COUNTRIES VALUES('ARMENIA','AM')
INSERT INTO COUNTRIES VALUES('ARUBA','AW')
INSERT INTO COUNTRIES VALUES('AUSTRALIA','AU')
INSERT INTO COUNTRIES VALUES('AUSTRIA','AT')
INSERT INTO COUNTRIES VALUES('AZERBAIJAN','AZ')
INSERT INTO COUNTRIES VALUES('BAHAMAS','BS')
INSERT INTO COUNTRIES VALUES('BAHRAIN','BH')
INSERT INTO COUNTRIES VALUES('BANGLADESH','BD')
INSERT INTO COUNTRIES VALUES('BARBADOS','BB')
INSERT INTO COUNTRIES VALUES('BELARUS','BY')
INSERT INTO COUNTRIES VALUES('BELGIUM','BE')
INSERT INTO COUNTRIES VALUES('BELIZE','BZ')
INSERT INTO COUNTRIES VALUES('BENIN','BJ')
INSERT INTO COUNTRIES VALUES('BERMUDA','BM')
INSERT INTO COUNTRIES VALUES('BHUTAN','BT')
INSERT INTO COUNTRIES VALUES('BOLIVIA, PLURINATIONAL STATE OF','BO')
INSERT INTO COUNTRIES VALUES('BONAIRE, SAINT EUSTATIUS AND SABA','BQ')
INSERT INTO COUNTRIES VALUES('BOSNIA AND HERZEGOVINA','BA')
INSERT INTO COUNTRIES VALUES('BOTSWANA','BW')
INSERT INTO COUNTRIES VALUES('BOUVET ISLAND','BV')
INSERT INTO COUNTRIES VALUES('BRAZIL','BR')
INSERT INTO COUNTRIES VALUES('BRITISH INDIAN OCEAN TERRITORY','IO')
INSERT INTO COUNTRIES VALUES('BRUNEI DARUSSALAM','BN')
INSERT INTO COUNTRIES VALUES('BULGARIA','BG')
INSERT INTO COUNTRIES VALUES('BURKINA FASO','BF')
INSERT INTO COUNTRIES VALUES('BURUNDI','BI')
INSERT INTO COUNTRIES VALUES('CAMBODIA','KH')
INSERT INTO COUNTRIES VALUES('CAMEROON','CM')
INSERT INTO COUNTRIES VALUES('CANADA','CA')
INSERT INTO COUNTRIES VALUES('CAPE VERDE','CV')
INSERT INTO COUNTRIES VALUES('CAYMAN ISLANDS','KY')
INSERT INTO COUNTRIES VALUES('CENTRAL AFRICAN REPUBLIC','CF')
INSERT INTO COUNTRIES VALUES('CHAD','TD')
INSERT INTO COUNTRIES VALUES('CHILE','CL')
INSERT INTO COUNTRIES VALUES('CHINA','CN')
INSERT INTO COUNTRIES VALUES('CHRISTMAS ISLAND','CX')
INSERT INTO COUNTRIES VALUES('COCOS (KEELING) ISLANDS','CC')
INSERT INTO COUNTRIES VALUES('COLOMBIA','CO')
INSERT INTO COUNTRIES VALUES('COMOROS','KM')
INSERT INTO COUNTRIES VALUES('CONGO','CG')
INSERT INTO COUNTRIES VALUES('CONGO, THE DEMOCRATIC REPUBLIC OF THE','CD')
INSERT INTO COUNTRIES VALUES('COOK ISLANDS','CK')
INSERT INTO COUNTRIES VALUES('COSTA RICA','CR')
INSERT INTO COUNTRIES VALUES('CROATIA','HR')
INSERT INTO COUNTRIES VALUES('CUBA','CU')
INSERT INTO COUNTRIES VALUES('CURA\u00c7AO','CW')
INSERT INTO COUNTRIES VALUES('CYPRUS','CY')
INSERT INTO COUNTRIES VALUES('CZECH REPUBLIC','CZ')
INSERT INTO COUNTRIES VALUES('C\u00d4TE D''IVOIRE','CI')
INSERT INTO COUNTRIES VALUES('DENMARK','DK')
INSERT INTO COUNTRIES VALUES('DJIBOUTI','DJ')
INSERT INTO COUNTRIES VALUES('DOMINICA','DM')
INSERT INTO COUNTRIES VALUES('DOMINICAN REPUBLIC','DO')
INSERT INTO COUNTRIES VALUES('ECUADOR','EC')
INSERT INTO COUNTRIES VALUES('EGYPT','EG')
INSERT INTO COUNTRIES VALUES('EL SALVADOR','SV')
INSERT INTO COUNTRIES VALUES('EQUATORIAL GUINEA','GQ')
INSERT INTO COUNTRIES VALUES('ERITREA','ER')
INSERT INTO COUNTRIES VALUES('ESTONIA','EE')
INSERT INTO COUNTRIES VALUES('ETHIOPIA','ET')
INSERT INTO COUNTRIES VALUES('FALKLAND ISLANDS (MALVINAS)','FK')
INSERT INTO COUNTRIES VALUES('FAROE ISLANDS','FO')
INSERT INTO COUNTRIES VALUES('FIJI','FJ')
INSERT INTO COUNTRIES VALUES('FINLAND','FI')
INSERT INTO COUNTRIES VALUES('FRANCE','FR')
INSERT INTO COUNTRIES VALUES('FRENCH GUIANA','GF')
INSERT INTO COUNTRIES VALUES('FRENCH POLYNESIA','PF')
INSERT INTO COUNTRIES VALUES('FRENCH SOUTHERN TERRITORIES','TF')
INSERT INTO COUNTRIES VALUES('GABON','GA')
INSERT INTO COUNTRIES VALUES('GAMBIA','GM')
INSERT INTO COUNTRIES VALUES('GEORGIA','GE')
INSERT INTO COUNTRIES VALUES('GERMANY','DE')
INSERT INTO COUNTRIES VALUES('GHANA','GH')
INSERT INTO COUNTRIES VALUES('GIBRALTAR','GI')
INSERT INTO COUNTRIES VALUES('GREECE','GR')
INSERT INTO COUNTRIES VALUES('GREENLAND','GL')
INSERT INTO COUNTRIES VALUES('GRENADA','GD')
INSERT INTO COUNTRIES VALUES('GUADELOUPE','GP')
INSERT INTO COUNTRIES VALUES('GUAM','GU')
INSERT INTO COUNTRIES VALUES('GUATEMALA','GT')
INSERT INTO COUNTRIES VALUES('GUERNSEY','GG')
INSERT INTO COUNTRIES VALUES('GUINEA','GN')
INSERT INTO COUNTRIES VALUES('GUINEA-BISSAU','GW')
INSERT INTO COUNTRIES VALUES('GUYANA','GY')
INSERT INTO COUNTRIES VALUES('HAITI','HT')
INSERT INTO COUNTRIES VALUES('HEARD ISLAND AND MCDONALD ISLANDS','HM')
INSERT INTO COUNTRIES VALUES('HOLY SEE (VATICAN CITY STATE)','VA')
INSERT INTO COUNTRIES VALUES('HONDURAS','HN')
INSERT INTO COUNTRIES VALUES('HONG KONG','HK')
INSERT INTO COUNTRIES VALUES('HUNGARY','HU')
INSERT INTO COUNTRIES VALUES('ICELAND','IS')
INSERT INTO COUNTRIES VALUES('INDIA','IN')
INSERT INTO COUNTRIES VALUES('INDONESIA','ID')
INSERT INTO COUNTRIES VALUES('IRAN, ISLAMIC REPUBLIC OF','IR')
INSERT INTO COUNTRIES VALUES('IRAQ','IQ')
INSERT INTO COUNTRIES VALUES('IRELAND','IE')
INSERT INTO COUNTRIES VALUES('ISLE OF MAN','IM')
INSERT INTO COUNTRIES VALUES('ISRAEL','IL')
INSERT INTO COUNTRIES VALUES('ITALY','IT')
INSERT INTO COUNTRIES VALUES('JAMAICA','JM')
INSERT INTO COUNTRIES VALUES('JAPAN','JP')
INSERT INTO COUNTRIES VALUES('JERSEY','JE')
INSERT INTO COUNTRIES VALUES('JORDAN','JO')
INSERT INTO COUNTRIES VALUES('KAZAKHSTAN','KZ')
INSERT INTO COUNTRIES VALUES('KENYA','KE')
INSERT INTO COUNTRIES VALUES('KIRIBATI','KI')
INSERT INTO COUNTRIES VALUES('KOREA, DEMOCRATIC PEOPLE''S REPUBLIC OF','KP')
INSERT INTO COUNTRIES VALUES('KOREA, REPUBLIC OF','KR')
INSERT INTO COUNTRIES VALUES('KUWAIT','KW')
INSERT INTO COUNTRIES VALUES('KYRGYZSTAN','KG')
INSERT INTO COUNTRIES VALUES('LAO PEOPLE''S DEMOCRATIC REPUBLIC','LA')
INSERT INTO COUNTRIES VALUES('LATVIA','LV')
INSERT INTO COUNTRIES VALUES('LEBANON','LB')
INSERT INTO COUNTRIES VALUES('LESOTHO','LS')
INSERT INTO COUNTRIES VALUES('LIBERIA','LR')
INSERT INTO COUNTRIES VALUES('LIBYAN ARAB JAMAHIRIYA','LY')
INSERT INTO COUNTRIES VALUES('LIECHTENSTEIN','LI')
INSERT INTO COUNTRIES VALUES('LITHUANIA','LT')
INSERT INTO COUNTRIES VALUES('LUXEMBOURG','LU')
INSERT INTO COUNTRIES VALUES('MACAO','MO')
INSERT INTO COUNTRIES VALUES('MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF','MK')
INSERT INTO COUNTRIES VALUES('MADAGASCAR','MG')
INSERT INTO COUNTRIES VALUES('MALAWI','MW')
INSERT INTO COUNTRIES VALUES('MALAYSIA','MY')
INSERT INTO COUNTRIES VALUES('MALDIVES','MV')
INSERT INTO COUNTRIES VALUES('MALI','ML')
INSERT INTO COUNTRIES VALUES('MALTA','MT')
INSERT INTO COUNTRIES VALUES('MARSHALL ISLANDS','MH')
INSERT INTO COUNTRIES VALUES('MARTINIQUE','MQ')
INSERT INTO COUNTRIES VALUES('MAURITANIA','MR')
INSERT INTO COUNTRIES VALUES('MAURITIUS','MU')
INSERT INTO COUNTRIES VALUES('MAYOTTE','YT')
INSERT INTO COUNTRIES VALUES('MEXICO','MX')
INSERT INTO COUNTRIES VALUES('MICRONESIA, FEDERATED STATES OF','FM')
INSERT INTO COUNTRIES VALUES('MOLDOVA, REPUBLIC OF','MD')
INSERT INTO COUNTRIES VALUES('MONACO','MC')
INSERT INTO COUNTRIES VALUES('MONGOLIA','MN')
INSERT INTO COUNTRIES VALUES('MONTENEGRO','ME')
INSERT INTO COUNTRIES VALUES('MONTSERRAT','MS')
INSERT INTO COUNTRIES VALUES('MOROCCO','MA')
INSERT INTO COUNTRIES VALUES('MOZAMBIQUE','MZ')
INSERT INTO COUNTRIES VALUES('MYANMAR','MM')
INSERT INTO COUNTRIES VALUES('NAMIBIA','NA')
INSERT INTO COUNTRIES VALUES('NAURU','NR')
INSERT INTO COUNTRIES VALUES('NEPAL','NP')
INSERT INTO COUNTRIES VALUES('NETHERLANDS','NL')
INSERT INTO COUNTRIES VALUES('NEW CALEDONIA','NC')
INSERT INTO COUNTRIES VALUES('NEW ZEALAND','NZ')
INSERT INTO COUNTRIES VALUES('NICARAGUA','NI')
INSERT INTO COUNTRIES VALUES('NIGER','NE')
INSERT INTO COUNTRIES VALUES('NIGERIA','NG')
INSERT INTO COUNTRIES VALUES('NIUE','NU')
INSERT INTO COUNTRIES VALUES('NORFOLK ISLAND','NF')
INSERT INTO COUNTRIES VALUES('NORTHERN MARIANA ISLANDS','MP')
INSERT INTO COUNTRIES VALUES('NORWAY','NO')
INSERT INTO COUNTRIES VALUES('OMAN','OM')
INSERT INTO COUNTRIES VALUES('PAKISTAN','PK')
INSERT INTO COUNTRIES VALUES('PALAU','PW')
INSERT INTO COUNTRIES VALUES('PALESTINIAN TERRITORY, OCCUPIED','PS')
INSERT INTO COUNTRIES VALUES('PANAMA','PA')
INSERT INTO COUNTRIES VALUES('PAPUA NEW GUINEA','PG')
INSERT INTO COUNTRIES VALUES('PARAGUAY','PY')
INSERT INTO COUNTRIES VALUES('PERU','PE')
INSERT INTO COUNTRIES VALUES('PHILIPPINES','PH')
INSERT INTO COUNTRIES VALUES('PITCAIRN','PN')
INSERT INTO COUNTRIES VALUES('POLAND','PL')
INSERT INTO COUNTRIES VALUES('PORTUGAL','PT')
INSERT INTO COUNTRIES VALUES('PUERTO RICO','PR')
INSERT INTO COUNTRIES VALUES('QATAR','QA')
INSERT INTO COUNTRIES VALUES('ROMANIA','RO')
INSERT INTO COUNTRIES VALUES('RUSSIAN FEDERATION','RU')
INSERT INTO COUNTRIES VALUES('RWANDA','RW')
INSERT INTO COUNTRIES VALUES('R\u00c9UNION','RE')
INSERT INTO COUNTRIES VALUES('SAINT BARTH\u00c9LEMY','BL')
INSERT INTO COUNTRIES VALUES('SAINT HELENA, ASCENSION AND TRISTAN DA CUNHA','SH')
INSERT INTO COUNTRIES VALUES('SAINT KITTS AND NEVIS','KN')
INSERT INTO COUNTRIES VALUES('SAINT LUCIA','LC')
INSERT INTO COUNTRIES VALUES('SAINT MARTIN (FRENCH PART)','MF')
INSERT INTO COUNTRIES VALUES('SAINT PIERRE AND MIQUELON','PM')
INSERT INTO COUNTRIES VALUES('SAINT VINCENT AND THE GRENADINES','VC')
INSERT INTO COUNTRIES VALUES('SAMOA','WS')
INSERT INTO COUNTRIES VALUES('SAN MARINO','SM')
INSERT INTO COUNTRIES VALUES('SAO TOME AND PRINCIPE','ST')
INSERT INTO COUNTRIES VALUES('SAUDI ARABIA','SA')
INSERT INTO COUNTRIES VALUES('SENEGAL','SN')
INSERT INTO COUNTRIES VALUES('SERBIA','RS')
INSERT INTO COUNTRIES VALUES('SEYCHELLES','SC')
INSERT INTO COUNTRIES VALUES('SIERRA LEONE','SL')
INSERT INTO COUNTRIES VALUES('SINGAPORE','SG')
INSERT INTO COUNTRIES VALUES('SINT MAARTEN (DUTCH PART)','SX')
INSERT INTO COUNTRIES VALUES('SLOVAKIA','SK')
INSERT INTO COUNTRIES VALUES('SLOVENIA','SI')
INSERT INTO COUNTRIES VALUES('SOLOMON ISLANDS','SB')
INSERT INTO COUNTRIES VALUES('SOMALIA','SO')
INSERT INTO COUNTRIES VALUES('SOUTH AFRICA','ZA')
INSERT INTO COUNTRIES VALUES('SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS','GS')
INSERT INTO COUNTRIES VALUES('SPAIN','ES')
INSERT INTO COUNTRIES VALUES('SRI LANKA','LK')
INSERT INTO COUNTRIES VALUES('SUDAN','SD')
INSERT INTO COUNTRIES VALUES('SURINAME','SR')
INSERT INTO COUNTRIES VALUES('SVALBARD AND JAN MAYEN','SJ')
INSERT INTO COUNTRIES VALUES('SWAZILAND','SZ')
INSERT INTO COUNTRIES VALUES('SWEDEN','SE')
INSERT INTO COUNTRIES VALUES('SWITZERLAND','CH')
INSERT INTO COUNTRIES VALUES('SYRIAN ARAB REPUBLIC','SY')
INSERT INTO COUNTRIES VALUES('TAIWAN, PROVINCE OF CHINA','TW')
INSERT INTO COUNTRIES VALUES('TAJIKISTAN','TJ')
INSERT INTO COUNTRIES VALUES('TANZANIA, UNITED REPUBLIC OF','TZ')
INSERT INTO COUNTRIES VALUES('THAILAND','TH')
INSERT INTO COUNTRIES VALUES('TIMOR-LESTE','TL')
INSERT INTO COUNTRIES VALUES('TOGO','TG')
INSERT INTO COUNTRIES VALUES('TOKELAU','TK')
INSERT INTO COUNTRIES VALUES('TONGA','TO')
INSERT INTO COUNTRIES VALUES('TRINIDAD AND TOBAGO','TT')
INSERT INTO COUNTRIES VALUES('TUNISIA','TN')
INSERT INTO COUNTRIES VALUES('TURKEY','TR')
INSERT INTO COUNTRIES VALUES('TURKMENISTAN','TM')
INSERT INTO COUNTRIES VALUES('TURKS AND CAICOS ISLANDS','TC')
INSERT INTO COUNTRIES VALUES('TUVALU','TV')
INSERT INTO COUNTRIES VALUES('UGANDA','UG')
INSERT INTO COUNTRIES VALUES('UKRAINE','UA')
INSERT INTO COUNTRIES VALUES('UNITED ARAB EMIRATES','AE')
INSERT INTO COUNTRIES VALUES('UNITED KINGDOM','GB')
INSERT INTO COUNTRIES VALUES('UNITED STATES','US')
INSERT INTO COUNTRIES VALUES('UNITED STATES MINOR OUTLYING ISLANDS','UM')
INSERT INTO COUNTRIES VALUES('URUGUAY','UY')
INSERT INTO COUNTRIES VALUES('UZBEKISTAN','UZ')
INSERT INTO COUNTRIES VALUES('VANUATU','VU')
INSERT INTO COUNTRIES VALUES('VENEZUELA, BOLIVARIAN REPUBLIC OF','VE')
INSERT INTO COUNTRIES VALUES('VIET NAM','VN')
INSERT INTO COUNTRIES VALUES('VIRGIN ISLANDS, BRITISH','VG')
INSERT INTO COUNTRIES VALUES('VIRGIN ISLANDS, U.S.','VI')
INSERT INTO COUNTRIES VALUES('WALLIS AND FUTUNA','WF')
INSERT INTO COUNTRIES VALUES('WESTERN SAHARA','EH')
INSERT INTO COUNTRIES VALUES('YEMEN','YE')
INSERT INTO COUNTRIES VALUES('ZAMBIA','ZM')
INSERT INTO COUNTRIES VALUES('ZIMBABWE','ZW')

Start the server again (see above) and Navigate to: http://localhost:8080/dataProvider/

Creating a WAR file

If you want to run the application in another environment you can create a war file and drop it into a server of your choice. This method will also package up any runtime dependencies and put them in the /WEB-INF/lib folder of the WAR file.

mvn clean compile package

The war file should appear in the “target/” folder.

Additional Topics: Custom JSON

Since reflection is being used to create the JSON, the field names will represent the name of the attributes in the bean. Currently there is no easy way around this… We can build wrappers that map bean attributes to json attributes but this will require alot of work. If you guys have any suggestions on how this can be done please comment below.

A few reasons why you may want to build a custom mapping layer is:

  1. You may not want to return all the attributes of the bean
  2. You want to rename the field names to something other than the class attribute names.
Advertisements

0 Responses to “Creating a Mock Data Provider”



  1. Leave a Comment

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 78 other followers

May 2011
S M T W T F S
« Apr   Jul »
1234567
891011121314
15161718192021
22232425262728
293031  

Blog Stats

  • 822,357 hits

%d bloggers like this: