Skip to content

Commit

Permalink
签入一个完整的可以从客户端使用ajax访问后台restful service的原型实现,可以根据车次号查询和简单的购票.
Browse files Browse the repository at this point in the history
  • Loading branch information
shiyimin committed Nov 23, 2012
1 parent 6caef0e commit ebfe115
Show file tree
Hide file tree
Showing 24 changed files with 389 additions and 69 deletions.
Empty file removed trunk/empty.txt
Empty file.
1 change: 0 additions & 1 deletion trunk/src/test.txt

This file was deleted.

4 changes: 4 additions & 0 deletions trunk/tpms/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,10 @@
</build>
<properties>
<jersey-version>1.8</jersey-version>
<!--
使用cp936编码方式编译,以便处理中文windows和linux下的默认编码差异,感觉cp936是兼容utf-8编码的
这样在linux下写程序(默认是utf-8编码),和中文windows下写程序(默认是cp936编码)都能正常编译
-->
<!--<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>-->
<project.build.sourceEncoding>cp936</project.build.sourceEncoding>
</properties>
Expand Down
24 changes: 24 additions & 0 deletions trunk/tpms/src/main/java/org/ng12306/tpms/Order.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package org.ng12306.tpms;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Order {
// 车次号
public String train;

// 上车站点
public String departure;

// 下车站点
public String termination;

// 座位号
public String seat;

// 身份证号
public String id;

// 上车时间
public String date;
}
141 changes: 137 additions & 4 deletions trunk/tpms/src/main/java/org/ng12306/tpms/TicketResource.java
Original file line number Diff line number Diff line change
@@ -1,16 +1,85 @@
package org.ng12306.tpms;

import com.sun.jersey.spi.resource.Singleton;
import com.sun.jersey.api.json.JSONWithPadding;
import javax.ws.rs.*;
import javax.ws.rs.core.GenericEntity;

@Singleton
@Path("/ticket")
public class TicketResource {
// 由于需要支持跨域访问,默认的json格式不支持跨域访问,需要使用jsonp格式。
// 所以在Produces属性里添加了"application/x-javascript; charset=UTF-8",
// 每个MIME类型后面加上charset是为了防止中文输出乱码的问题
//
// 把问题详细描述一下,因为前台是一个single page web app,所有的数据都是通过
// ajax调用restful api的方式调用。但这带来一个问题,原型系统里我没有装tomcat
// 采用的jersey restful库是自己启动的web服务器响应ajax调用的,因此就无法做到
// single page web app和restful service在同一个域里面。
//
// 在jsonp格式里面,其实浏览器会将restful service返回的json对象当作一段javascript
// 代码处理,导致javascript解释器因为语法错误停止工作,因此需要动态创建一个callback
// 函数来绕过这个限制。
//
// 上面的话可能不好理解,当我们以json格式向restful service发送请求时,
// $.ajax({ url: 'restful-url', dataType: 'json' });
// 人家返回的是如下格式:
// { key: 'value' }
//
// 但如果以jsonp格式发送时,请求的url后面需要带一个参数,指明要动态生成的callback函数
// $.ajax({ url: 'restful-url?jsonpcallback=jpcb', dataType: 'jsonp', jsonp: 'jpcb' });
// 返回的是如下格式:
// jpcb({key: 'value'});
//
// 参考文献:http://weblogs.java.net/blog/felipegaucho/archive/2010/02/25/jersey-feat-jquery-jsonp
// http://api.jquery.com/jQuery.ajax/
// http://forum.jquery.com/topic/ajax-jsonpcallback
@GET
@Path("/id/{trainId}")
@Produces("application/json; charset=UTF-8")
public Train[] query(@PathParam("trainId") String trainId) {
Train[] trains = new Train[1];
@Produces({"application/x-javascript; charset=UTF-8", "application/json; charset=UTF-8"})
public JSONWithPadding query(@QueryParam("jsonpcallback") @DefaultValue("jsonpcallback") String callback,
@PathParam("trainId") String trainId) {
Train[] trains = queryImpl(trainId);

return new JSONWithPadding(
new GenericEntity<Train[]>(trains) {},
callback);
}

@GET
@Path("/make")
@Produces({"application/x-javascript; charset=UTF-8", "application/json; charset=UTF-8"})
public String make(@QueryParam("jsonpcallback") @DefaultValue("jsonpcallback") String callback,
@QueryParam("train") String train,
@QueryParam("seat") String seat,
@QueryParam("departure") String departure,
@QueryParam("termination") String termination,
@QueryParam("id") String id,
@QueryParam("date") String date) {
if ( train == null ) {
throw new IllegalArgumentException("车次号不应该为空!");
}
if ( seat == null ) {
throw new IllegalArgumentException("座位号不应该为空!");
}
if ( departure == null ) {
throw new IllegalArgumentException("出发站点号不应该为空!");
}
if ( termination == null ) {
throw new IllegalArgumentException("到达站点不应该为空!");
}
if ( id == null ) {
throw new IllegalArgumentException("身份证号不应该为空!");
}
if ( date == null ) {
throw new IllegalArgumentException("出发日期不应该为空!");
}

return "true";
}

public Train[] queryImpl(String trainId) {
Train[] trains = new Train[4];

Train train = new Train();
train.name = "G101";
Expand All @@ -27,7 +96,71 @@ public Train[] query(@PathParam("trainId") String trainId) {
train.availables = availables;

trains[0] = train;

train = new Train();
train.name = "G105";
train.departure = "北京南";
train.departureTime = "07:30";
train.termination = "上海虹桥";
train.arrivalTime = "13:07";

availables = new String[2][2];
availables[0][0] = "二等软座";
availables[0][1] = "无票";
availables[1][0] = "一等软座";
availables[1][1] = "5";
train.availables = availables;

trains[1] = train;

train = new Train();
train.name = "D365";
train.departure = "北京南";
train.departureTime = "07:35";
train.termination = "上海虹桥";
train.arrivalTime = "15:42";

availables = new String[4][2];
availables[0][0] = "二等软座";
availables[0][1] = "有票";
availables[1][0] = "一等软座";
availables[1][1] = "有票";
availables[2][0] = "软卧上";
availables[2][1] = "有票";
availables[3][0] = "软卧下";
availables[3][1] = "有票";
train.availables = availables;

trains[2] = train;

train = new Train();
train.name = "T109";
train.departure = "北京";
train.departureTime = "19:33";
train.termination = "上海";
train.arrivalTime = "10:26";

availables = new String[8][2];
availables[0][0] = "硬座";
availables[0][1] = "有票";
availables[1][0] = "硬卧上";
availables[1][1] = "有票";
availables[2][0] = "硬卧中";
availables[2][1] = "有票";
availables[3][0] = "硬卧下";
availables[3][1] = "有票";
availables[4][0] = "软卧上";
availables[4][1] = "有票";
availables[5][0] = "软卧下";
availables[5][1] = "无票";
availables[6][0] = "高级软卧上";
availables[6][1] = "有票";
availables[7][0] = "高级软卧下";
availables[7][1] = "5";
train.availables = availables;

trains[3] = train;

return trains;
}
}
}
2 changes: 2 additions & 0 deletions trunk/tpms/src/main/java/org/ng12306/tpms/Train.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.ng12306.tpms;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlElement;

@XmlRootElement
public class Train {
Expand All @@ -20,5 +21,6 @@ public class Train {
public String arrivalTime;

// 余票信息
@XmlElement
public String[][] availables;
}
5 changes: 4 additions & 1 deletion trunk/tpms/src/test/java/org/ng12306/tpms/MainTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,14 @@ protected void tearDown() throws Exception {

/**
* Test to see that the message "Got it!" is sent in the response.
*/
* TODO: 需要找回myresource这个由maven自带的路径
* 它已经被我删掉了,但后面想想还是应该有这么一个玩意,用以在排错时
* 确保jersey是正常工作的。
public void _testMyResource() {
String responseMsg = r.path("myresource").get(String.class);
assertEquals("Got it!", responseMsg);
}
*/

/**
* Test if a WADL document is available at the relative path
Expand Down
43 changes: 43 additions & 0 deletions trunk/tpms/src/test/java/org/ng12306/tpms/TicketResourceTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package org.ng12306.tpms;

import junit.framework.TestCase;

import com.sun.grizzly.http.SelectorThread;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.ClientResponse;

public class TicketResourceTest extends TestCase {
private SelectorThread threadSelector;

private Client c;

public TicketResourceTest(String testName) {
super(testName);
}

@Override
protected void setUp() throws Exception {
super.setUp();

threadSelector = Main.startServer();
c = Client.create();
}

@Override
protected void tearDown() throws Exception {
super.tearDown();

threadSelector.stopEndpoint();
}

// 测试根据车次号查询车次
public void testQueryTrainByTrainNo() {
WebResource r = c.resource(Main.BASE_URI.toString() + "ticket/id/1");
ClientResponse response = r.get(ClientResponse.class);
assertEquals(200, response.getStatus());
assertNotNull(response.getEntity(String.class));
}

// TODO: 添加更多的测试用例!
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8" ?>
<testsuite failures="0" time="4.895" errors="0" skipped="0" tests="1" name="org.ng12306.tpms.MainTest">
<properties>
<property name="java.runtime.name" value="Java(TM) SE Runtime Environment"/>
<property name="sun.boot.library.path" value="/usr/lib/jvm/jdk1.7.0_05/jre/lib/i386"/>
<property name="java.vm.version" value="23.1-b03"/>
<property name="java.vm.vendor" value="Oracle Corporation"/>
<property name="java.vendor.url" value="http://java.oracle.com/"/>
<property name="path.separator" value=":"/>
<property name="guice.disable.misplaced.annotation.check" value="true"/>
<property name="java.vm.name" value="Java HotSpot(TM) Client VM"/>
<property name="file.encoding.pkg" value="sun.io"/>
<property name="user.country" value="US"/>
<property name="sun.java.launcher" value="SUN_STANDARD"/>
<property name="sun.os.patch.level" value="unknown"/>
<property name="java.vm.specification.name" value="Java Virtual Machine Specification"/>
<property name="user.dir" value="/vagrant/trunk/tpms"/>
<property name="java.runtime.version" value="1.7.0_05-b06"/>
<property name="java.awt.graphicsenv" value="sun.awt.X11GraphicsEnvironment"/>
<property name="java.endorsed.dirs" value="/usr/lib/jvm/jdk1.7.0_05/jre/lib/endorsed"/>
<property name="os.arch" value="i386"/>
<property name="java.io.tmpdir" value="/tmp"/>
<property name="line.separator" value="
"/>
<property name="java.vm.specification.vendor" value="Oracle Corporation"/>
<property name="os.name" value="Linux"/>
<property name="classworlds.conf" value="/usr/local/maven/bin/m2.conf"/>
<property name="sun.jnu.encoding" value="ISO-8859-1"/>
<property name="java.library.path" value="/usr/java/packages/lib/i386:/lib:/usr/lib"/>
<property name="java.specification.name" value="Java Platform API Specification"/>
<property name="java.class.version" value="51.0"/>
<property name="sun.management.compiler" value="HotSpot Client Compiler"/>
<property name="os.version" value="2.6.32-38-generic"/>
<property name="user.home" value="/home/vagrant"/>
<property name="user.timezone" value="Europe/Brussels"/>
<property name="java.awt.printerjob" value="sun.print.PSPrinterJob"/>
<property name="file.encoding" value="ISO-8859-1"/>
<property name="java.specification.version" value="1.7"/>
<property name="user.name" value="vagrant"/>
<property name="java.class.path" value="/usr/local/maven/boot/plexus-classworlds-2.4.jar"/>
<property name="java.vm.specification.version" value="1.7"/>
<property name="sun.arch.data.model" value="32"/>
<property name="java.home" value="/usr/lib/jvm/jdk1.7.0_05/jre"/>
<property name="sun.java.command" value="org.codehaus.plexus.classworlds.launcher.Launcher test"/>
<property name="java.specification.vendor" value="Oracle Corporation"/>
<property name="user.language" value="en"/>
<property name="awt.toolkit" value="sun.awt.X11.XToolkit"/>
<property name="java.vm.info" value="mixed mode"/>
<property name="java.version" value="1.7.0_05"/>
<property name="java.ext.dirs" value="/usr/lib/jvm/jdk1.7.0_05/jre/lib/ext:/usr/java/packages/lib/ext"/>
<property name="securerandom.source" value="file:/dev/./urandom"/>
<property name="sun.boot.class.path" value="/usr/lib/jvm/jdk1.7.0_05/jre/lib/resources.jar:/usr/lib/jvm/jdk1.7.0_05/jre/lib/rt.jar:/usr/lib/jvm/jdk1.7.0_05/jre/lib/sunrsasign.jar:/usr/lib/jvm/jdk1.7.0_05/jre/lib/jsse.jar:/usr/lib/jvm/jdk1.7.0_05/jre/lib/jce.jar:/usr/lib/jvm/jdk1.7.0_05/jre/lib/charsets.jar:/usr/lib/jvm/jdk1.7.0_05/jre/lib/jfr.jar:/usr/lib/jvm/jdk1.7.0_05/jre/classes"/>
<property name="java.vendor" value="Oracle Corporation"/>
<property name="maven.home" value="/usr/local/maven"/>
<property name="file.separator" value="/"/>
<property name="java.vendor.url.bug" value="http://bugreport.sun.com/bugreport/"/>
<property name="sun.cpu.endian" value="little"/>
<property name="sun.io.unicode.encoding" value="UnicodeLittle"/>
<property name="sun.cpu.isalist" value=""/>
</properties>
<testcase time="4.781" classname="org.ng12306.tpms.MainTest" name="testApplicationWadl"/>
</testsuite>
Loading

0 comments on commit ebfe115

Please sign in to comment.