Created
February 13, 2012 04:41
-
-
Save jteso/1813740 to your computer and use it in GitHub Desktop.
Example of REST service in spring framework 3.1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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:jdbc="http://www.springframework.org/schema/jdbc" | |
xmlns:tx="http://www.springframework.org/schema/tx" | |
xmlns:context="http://www.springframework.org/schema/context" | |
xmlns:mongo="http://www.springframework.org/schema/data/mongo" | |
xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd | |
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd | |
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd | |
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd | |
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> | |
<!-- The configuration of the application. --> | |
<context:annotation-config/> | |
<mongo:mongo host="172.21.0.151" port="27017" /> | |
<bean id="mongoTemplate" class="org.springframework.data.document.mongodb.MongoTemplate"> | |
<constructor-arg ref="mongo" /> | |
<constructor-arg name="databaseName" value="db" /> | |
<constructor-arg name="defaultCollectionName" value="transaction_history" /> | |
</bean> | |
<!-- Weaves in transactional advice around @Transactional methods --> | |
<!-- <tx:annotation-driven transaction-manager="transactionManager" /> --> | |
<!-- Service Layer --> | |
<bean id="transactionManager" class="dgw.services.TransactionManager"> | |
<property name="transactionHistoryDao" ref="transactionHistoryDao" /> | |
</bean> | |
<!-- Daos --> | |
<bean id="transactionHistoryDao" class="dgw.dao.TransactionHistoryDAOImpl" /> | |
</beans> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Ant properties for building the springapp | |
appserver.home=C:\\opt\\apache-tomcat-7.0.23 | |
# for Tomcat 5 use $appserver.home}/server/lib | |
# for Tomcat 6 use $appserver.home}/lib | |
appserver.lib=C:\\opt\\apache-tomcat-7.0.23\\lib | |
deploy.path=C:\\opt\\apache-tomcat-7.0.23\\webapps | |
tomcat.manager.url=http://localhost:8080/manager/text | |
tomcat.manager.username=tomcat | |
tomcat.manager.password=s3cret |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0"?> | |
<project name="dgw" basedir="." default="usage"> | |
<property file="build.properties"/> | |
<property name="src.dir" value="src"/> | |
<property name="web.dir" value="war"/> | |
<property name="build.dir" value="${web.dir}/WEB-INF/classes"/> | |
<property name="name" value="dgw"/> | |
<path id="master-classpath"> | |
<fileset dir="${web.dir}/WEB-INF/lib"> | |
<include name="*.jar"/> | |
</fileset> | |
<!-- We need the servlet API classes: --> | |
<!-- * for Tomcat 5/6 use servlet-api.jar --> | |
<!-- * for other app servers - check the docs --> | |
<fileset dir="${appserver.lib}"> | |
<include name="servlet*.jar"/> | |
</fileset> | |
<pathelement path="${build.dir}"/> | |
</path> | |
<target name="usage"> | |
<echo message=""/> | |
<echo message="${name} build file"/> | |
<echo message="-----------------------------------"/> | |
<echo message=""/> | |
<echo message="Available targets are:"/> | |
<echo message=""/> | |
<echo message="build --> Build the application"/> | |
<echo message="deploy --> Deploy application as directory"/> | |
<echo message="deploywar --> Deploy application as a WAR file"/> | |
<echo message="install --> Install application in Tomcat"/> | |
<echo message="reload --> Reload application in Tomcat"/> | |
<echo message="start --> Start Tomcat application"/> | |
<echo message="stop --> Stop Tomcat application"/> | |
<echo message="list --> List Tomcat applications"/> | |
<echo message=""/> | |
</target> | |
<target name="build" description="Compile main source tree java files"> | |
<mkdir dir="${build.dir}"/> | |
<javac destdir="${build.dir}" source="1.5" target="1.5" debug="true" | |
deprecation="false" optimize="false" failonerror="true"> | |
<src path="${src.dir}"/> | |
<classpath refid="master-classpath"/> | |
</javac> | |
</target> | |
<target name="deploy" depends="build" description="Deploy application"> | |
<copy todir="${deploy.path}/${name}" preservelastmodified="true"> | |
<fileset dir="${web.dir}"> | |
<include name="**/*.*"/> | |
</fileset> | |
</copy> | |
</target> | |
<target name="deploywar" depends="build" description="Deploy application as a WAR file"> | |
<war destfile="${name}.war" | |
webxml="${web.dir}/WEB-INF/web.xml"> | |
<fileset dir="${web.dir}"> | |
<include name="**/*.*"/> | |
</fileset> | |
</war> | |
<copy todir="${deploy.path}" preservelastmodified="true"> | |
<fileset dir="."> | |
<include name="*.war"/> | |
</fileset> | |
</copy> | |
</target> | |
<!-- ============================================================== --> | |
<!-- Tomcat tasks - remove these if you don't have Tomcat installed --> | |
<!-- ============================================================== --> | |
<path id="catalina-ant-classpath"> | |
<!-- We need the Catalina jars for Tomcat --> | |
<!-- * for other app servers - check the docs --> | |
<fileset dir="${appserver.lib}"> | |
<include name="catalina-ant.jar"/> | |
<include name="tomcat-coyote.jar"/> | |
<include name="tomcat-util.jar" /> | |
</fileset> | |
<fileset dir="${appserver.home}/bin"> | |
<include name="tomcat-juli.jar"/> | |
</fileset> | |
</path> | |
<taskdef name="install" classname="org.apache.catalina.ant.DeployTask"> | |
<classpath refid="catalina-ant-classpath"/> | |
</taskdef> | |
<taskdef name="reload" classname="org.apache.catalina.ant.ReloadTask"> | |
<classpath refid="catalina-ant-classpath"/> | |
</taskdef> | |
<taskdef name="list" classname="org.apache.catalina.ant.ListTask"> | |
<classpath refid="catalina-ant-classpath"/> | |
</taskdef> | |
<taskdef name="start" classname="org.apache.catalina.ant.StartTask"> | |
<classpath refid="catalina-ant-classpath"/> | |
</taskdef> | |
<taskdef name="stop" classname="org.apache.catalina.ant.StopTask"> | |
<classpath refid="catalina-ant-classpath"/> | |
</taskdef> | |
<target name="install" description="Install application in Tomcat"> | |
<install url="${tomcat.manager.url}" | |
username="${tomcat.manager.username}" | |
password="${tomcat.manager.password}" | |
path="/${name}" | |
war="${name}"/> | |
</target> | |
<target name="reload" description="Reload application in Tomcat"> | |
<reload url="${tomcat.manager.url}" | |
username="${tomcat.manager.username}" | |
password="${tomcat.manager.password}" | |
path="/${name}"/> | |
</target> | |
<target name="start" description="Start Tomcat application"> | |
<start url="${tomcat.manager.url}" | |
username="${tomcat.manager.username}" | |
password="${tomcat.manager.password}" | |
path="/${name}"/> | |
</target> | |
<target name="stop" description="Stop Tomcat application"> | |
<stop url="${tomcat.manager.url}" | |
username="${tomcat.manager.username}" | |
password="${tomcat.manager.password}" | |
path="/${name}"/> | |
</target> | |
<target name="list" description="List Tomcat applications"> | |
<list url="${tomcat.manager.url}" | |
username="${tomcat.manager.username}" | |
password="${tomcat.manager.password}"/> | |
</target> | |
<!-- End Tomcat tasks --> | |
</project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
./src/Controller.java | |
./test/ | |
./war/WEB-INF/ | |
|-> application-context.xml | |
|-> transaction-servlet.xml | |
|-> web.xml |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package springapp.test; | |
import java.io.IOException; | |
import org.apache.commons.httpclient.Header; | |
import org.apache.commons.httpclient.HttpClient; | |
import org.apache.commons.httpclient.HttpException; | |
import org.apache.commons.httpclient.methods.GetMethod; | |
import org.codehaus.jackson.map.ObjectMapper; | |
import org.junit.Assert; | |
import org.springframework.http.HttpEntity; | |
import org.springframework.http.HttpHeaders; | |
import org.springframework.http.MediaType; | |
import dgw.model.TransactionHistoryModelList; | |
public class Test { | |
/** | |
* server URL ending with the servlet mapping on which the application can be reached. | |
*/ | |
private static final String BASE_URL = "http://localhost:8080/dgw/rest/transactions"; | |
private static HttpEntity<String> prepareGet(MediaType type) { | |
HttpHeaders headers = new HttpHeaders(); | |
headers.setContentType(type); | |
HttpEntity<String> entity = new HttpEntity<String>(headers); | |
return entity; | |
} | |
@org.junit.Test | |
public void gimmeAllTransactionsXMLformat() throws HttpException, IOException { | |
String url = BASE_URL + "/all"; | |
HttpClient httpClient = new HttpClient(); | |
GetMethod getRequest = new GetMethod(url); | |
try{ | |
getRequest.setRequestHeader(new Header("Accept","application/xml")); | |
int responseCode = httpClient.executeMethod(getRequest); | |
Assert.assertTrue(responseCode == 200); | |
//TODO convert the xml into string and validate result with some assertions, in the meantime, printing result in the console... | |
System.out.println(getRequest.getResponseBodyAsString()); | |
}finally{ | |
getRequest.releaseConnection(); | |
} | |
} | |
@org.junit.Test | |
public void gimmeAllTransactionsJSONformat() throws HttpException, IOException { | |
String url = BASE_URL + "/all"; | |
HttpClient httpClient = new HttpClient(); | |
GetMethod getRequest = new GetMethod(url); | |
try{ | |
getRequest.setRequestHeader(new Header("Accept","application/json")); | |
int responseCode = httpClient.executeMethod(getRequest); | |
Assert.assertTrue(responseCode == 200); | |
ObjectMapper mapper = new ObjectMapper(); | |
TransactionHistoryModelList result = mapper.readValue(getRequest.getResponseBodyAsString(), TransactionHistoryModelList.class); | |
Assert.assertTrue(result.getCount() == 10); | |
Assert.assertTrue(result.getTransactions().size() == 10); | |
}finally{ | |
getRequest.releaseConnection(); | |
} | |
} | |
@org.junit.Test | |
public void gimmeAllTransactionsFilterByTerms() throws HttpException, IOException { | |
String url = BASE_URL + "/accounts/21000/terms/INTERNAL+TRANSFER"; | |
HttpClient httpClient = new HttpClient(); | |
GetMethod getRequest = new GetMethod(url); | |
try{ | |
getRequest.setRequestHeader(new Header("Accept","application/json")); | |
int responseCode = httpClient.executeMethod(getRequest); | |
Assert.assertTrue(responseCode == 200); | |
ObjectMapper mapper = new ObjectMapper(); | |
TransactionHistoryModelList result = mapper.readValue(getRequest.getResponseBodyAsString(), TransactionHistoryModelList.class); | |
Assert.assertTrue(result.getCount() == 10); | |
Assert.assertTrue(result.getTransactions().size() == 10); | |
}finally{ | |
getRequest.releaseConnection(); | |
} | |
} | |
@org.junit.Test | |
public void gimmeAllInterestTransctionsForAGivenAccount() throws HttpException, IOException { | |
String url = BASE_URL + "/accounts/21001/terms/INTEREST"; | |
HttpClient httpClient = new HttpClient(); | |
GetMethod getRequest = new GetMethod(url); | |
try{ | |
getRequest.setRequestHeader(new Header("Accept","application/json")); | |
int responseCode = httpClient.executeMethod(getRequest); | |
Assert.assertTrue(responseCode == 200); | |
//System.out.println("Code:" + responseCode); | |
System.out.println("Body:" + getRequest.getResponseBodyAsString()); | |
}finally{ | |
getRequest.releaseConnection(); | |
} | |
} | |
/* | |
@Test | |
public void createAccount() { | |
String url = BASE_URL + "/accounts"; | |
// use a unique number to avoid conflicts | |
String number = String.format("12345%4d", random.nextInt(10000)); | |
Account account = new Account(number, "John Doe"); | |
account.addBeneficiary("Jane Doe"); | |
URI newAccountLocation = restTemplate.postForLocation(url, account); | |
Account retrievedAccount = restTemplate.getForObject(newAccountLocation, Account.class); | |
assertEquals(account, retrievedAccount); | |
assertNotNull(retrievedAccount.getEntityId()); | |
} | |
@Test | |
public void addAndDeleteBeneficiary() { | |
// perform both add and delete to avoid issues with side effects | |
String addUrl = BASE_URL + "/accounts/{accountId}/beneficiaries"; | |
URI newBeneficiaryLocation = restTemplate.postForLocation(addUrl, "David", 0); | |
Beneficiary newBeneficiary = restTemplate.getForObject(newBeneficiaryLocation, Beneficiary.class); | |
assertEquals("David", newBeneficiary.getName()); | |
restTemplate.delete(newBeneficiaryLocation); | |
try { | |
restTemplate.getForObject(newBeneficiaryLocation, Beneficiary.class); | |
fail("Should have received 404 Not Found after deleting beneficiary at " + newBeneficiaryLocation); | |
} catch (HttpClientErrorException e) { | |
assertEquals(HttpStatus.NOT_FOUND, e.getStatusCode()); | |
} | |
}*/ | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package dgw.controller; | |
import java.util.ArrayList; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import org.springframework.stereotype.Controller; | |
import org.springframework.util.StringUtils; | |
import org.springframework.web.bind.annotation.PathVariable; | |
import org.springframework.web.bind.annotation.RequestMapping; | |
import org.springframework.web.bind.annotation.RequestMethod; | |
import org.springframework.web.bind.annotation.ResponseBody; | |
import dgw.model.TransactionHistoryModelList; | |
import dgw.services.TransactionManager; | |
@Controller | |
@RequestMapping("/transactions") | |
public class TransactionController { | |
protected final Logger logger = LoggerFactory.getLogger(TransactionController.class); | |
private TransactionManager transactionManager; | |
public void setTransactionManager(TransactionManager transactionManager) { | |
this.transactionManager = transactionManager; | |
} | |
@RequestMapping(value="/all", method=RequestMethod.GET, headers = "Accept=application/xml, application/json") | |
public @ResponseBody TransactionHistoryModelList retrieveTransactions() { | |
TransactionHistoryModelList list = new TransactionHistoryModelList(); | |
list.setTransactions(transactionManager.queryAllInternalTransferCIF()); | |
list.setCount(list.getTransactions().size()); | |
return list; | |
} | |
@RequestMapping(value="/accounts/{account}/terms/{terms}", method=RequestMethod.GET, headers = "Accept=application/xml, application/json") | |
public @ResponseBody TransactionHistoryModelList retrieveTransactionsByTerms(@PathVariable String account, @PathVariable String terms) { | |
ArrayList<String> lTerms = new ArrayList<String>(); | |
// Determine the account number | |
if ("all".equalsIgnoreCase(account)== false){ | |
lTerms.add(account); | |
} | |
// Determine the searching criteria terms | |
if (terms != null && terms.length() != 0){ | |
if (terms.contains("+")){ | |
//case of multi term being entered (+) separator | |
String[] split = StringUtils.split(terms, "+"); | |
for (String term : split) | |
lTerms.add(term); | |
}else{ | |
//case of single term being entered | |
lTerms.add(terms); | |
} | |
} | |
// Determine the searching terms | |
TransactionHistoryModelList list = new TransactionHistoryModelList(); | |
list.setTransactions(transactionManager.queryByCIFandTerms("01999999", lTerms.toArray(new String[lTerms.size()] ), 10, 0)); | |
return list; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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" | |
xmlns:mvc="http://www.springframework.org/schema/mvc" | |
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd | |
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-3.0.xsd"> | |
<context:component-scan base-package="springapp.controller"/> | |
<!-- To enable @RequestMapping process on type level and method level --> | |
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> | |
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> | |
<property name="messageConverters"> | |
<list> | |
<ref bean="marshallingConverter" /> | |
<!-- | |
<ref bean="atomConverter" /> | |
--> | |
<ref bean="jsonConverter" /> | |
</list> | |
</property> | |
</bean> | |
<bean id="marshallingConverter" class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter"> | |
<constructor-arg ref="jaxbMarshaller" /> | |
<property name="supportedMediaTypes" value="application/xml"/> | |
</bean> | |
<!-- | |
<bean id="atomConverter" class="org.springframework.http.converter.feed.AtomFeedHttpMessageConverter"> | |
<property name="supportedMediaTypes" value="application/atom+xml" /> | |
</bean> | |
--> | |
<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> | |
<property name="supportedMediaTypes" value="application/json" /> | |
</bean> | |
<bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller"> | |
<property name="classesToBeBound"> | |
<list> | |
<value>dgw.model.TransactionHistoryModel</value> | |
<value>dgw.model.TransactionHistoryModelList</value> | |
</list> | |
</property> | |
</bean> | |
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> | |
<property name="mediaTypes"> | |
<map> | |
<entry key="xml" value="application/xml"/> | |
<entry key="html" value="text/html"/> | |
<entry key="json" value="application/json" /> | |
</map> | |
</property> | |
<property name="defaultContentType" value="application/xml" /> | |
<!-- | |
<property name="viewResolvers"> | |
<list> | |
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/> | |
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> | |
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> | |
<property name="prefix" value="/WEB-INF/jsp/"/> | |
<property name="suffix" value=".jsp"/> | |
</bean> | |
</list> | |
</property> | |
--> | |
</bean> | |
<!--bean id="viewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver" /--> | |
<bean id="transactionController" class="dgw.controller.TransactionController"> | |
<property name="transactionManager" ref="transactionManager" /> | |
<!-- <property name="jaxb2Mashaller" ref="jaxbMarshaller" /> --> | |
</bean> | |
</beans> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<web-app version="2.4" | |
xmlns="http://java.sun.com/xml/ns/j2ee" | |
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | |
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee | |
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" > | |
<display-name>(REST API)</display-name> | |
<!-- | |
Beans in these files will makeup the configuration of the root web | |
application context | |
--> | |
<context-param> | |
<param-name>contextConfigLocation</param-name> | |
<param-value>/WEB-INF/application-context.xml</param-value> | |
</context-param> | |
<!-- | |
Bootstraps the root web application context before servlet | |
initialization | |
--> | |
<listener> | |
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> | |
</listener> | |
<!-- | |
Deploys the 'transactions' dispatcher servlet whose configuration resides | |
in /WEB-INF/accounts-servlet-config.xml | |
--> | |
<servlet> | |
<servlet-name>rest</servlet-name> | |
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> | |
<init-param> | |
<param-name>contextConfigLocation</param-name> | |
<param-value>/WEB-INF/transactions-servlet-config.xml</param-value> | |
</init-param> | |
<load-on-startup>1</load-on-startup> | |
</servlet> | |
<!-- Maps all URLs starting with /app to the 'accounts' servlet. --> | |
<servlet-mapping> | |
<servlet-name>rest</servlet-name> | |
<url-pattern>/rest/*</url-pattern> | |
</servlet-mapping> | |
<!-- TODO to be removed after REST api is implemented --> | |
<jsp-config> | |
<taglib> | |
<taglib-uri>/spring</taglib-uri> | |
<taglib-location>/WEB-INF/tld/spring-form.tld</taglib-location> | |
</taglib> | |
</jsp-config> | |
</web-app> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment