`
tangay
  • 浏览: 94653 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

REST Web Service开发实践--Jersey,Google Protocol Buffer, Tomcat结合样例

    博客分类:
  • REST
阅读更多
一 综述:

  当前REST化的WebService大行其道,Jersey是Sun推出的REST WEB Service参考实现,而Google Protocol Buffer由于其高效,短小,代码自动生成而成为分布式系统数据交互的优良选择, tomcat以市场占有率第一Servlet容器而知名,所以本文就讲叙怎么用Jersey, Google PB, Tomcat这三大法宝开发REST式的WEB service.


二 环境准备:

jersey版本:jersey-archive-1.2-SNAPSHOT
Google PB版本: protobuf-2.3.0
tomcat: tomcat6.0
Eclipse: 3.5.1 + tomcat plug in:http://www.eclipsetotale.com/tomcatPlugin.html

三 项目依赖的lib

sm-3.1.jar
jersey-server-1.2-SNAPSHOT.jar
jackson-core-asl-1.1.1.jar    
jersey-spring-1.2-SNAPSHOT.jar
jersey-client-1.2-SNAPSHOT.jar
jettison-1.1.jar
jersey-core-1.2-SNAPSHOT.jar  
jsr311-api-1.1.1.jar
jersey-json-1.2-SNAPSHOT.jar  
protobuf-java-2.3.0.jar

请到jersey的包中和pb的包中找上述的lib

四 动手吧

4.1 在Eclipse新建一个tomcat工程, Eclipse的workspace为D:/workspace:
工程展开如图



4.2 图中元素说明:

addressbook.proto                            pb自带的电话本message定义文件

compile.bat                                       自己写的message编译脚本

protoc.exe                                         pb的编译命令行工具

ContactClient.java                             访问REST service的client端代码

CreatePerson.java                             自己写的生成Person PB结构,并存在D:盘根目录下的小工具类

AddressBookResource                        REST Service核心Resource类

HelloResource.java                             Hello world Resource类

AddressBookStore.java                      自己写的一个服务器段电话簿存储类,以D:/addressBooks.txt为存储文件

AddressBookProtos.java                    addressbook.proto 被PB命令行工具编译后生成的java类

ProtobufMessageBodyReader.java    服务器把Request输入流转化成PB结构的Provider类,用以把用户上穿的字节流转成PB结构

ProtobufMessageBodyWriter.java      服务器把PB机构转化成输出流的Provider类,用以把PB结构转成字节流输出给用户

4.3 代码:

addressbook.proto

package demo;

option java_package = "sample.pb";
option java_outer_classname = "AddressBookProtos";

message Person {
  required string name = 1;
  required int32 id = 2;
  optional string email = 3;

  enum PhoneType {
    MOBILE = 0;
    HOME = 1;
    WORK = 2;
  }

  message PhoneNumber {
    required string number = 1;
    optional PhoneType type = 2 [default = HOME];
  }

  repeated PhoneNumber phone = 4;
}

message AddressBook {
  repeated Person person = 1;
}

----------------------------------------------------------------------

compile.bat

protoc -I=D:/workspace/jerseydemo/src --java_out=D:/workspace/jerseydemo/src D:/workspace/jerseydemo/src/demo/pb/addressbook.proto

--------------------------------------------------------------------------------------

ContactClient.java

package sample.hello.client;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import sample.pb.AddressBookProtos.Person;
import sample.pb.AddressBookProtos.Person.PhoneNumber;

public class ContactClient {
  
    public static void main(String[] args) throws IOException {
        String url1 = "http://localhost:8080/jerseydemo/rest/addressbook/";
        putContacts(url1, "hery");
        String url2 = "http://localhost:8080/jerseydemo/rest/addressbook/hery";
        getContacts(url2);
    }
    public static void putContacts(String url, String name) throws IOException {
        File file = new File("D:/"+name+".per");
        Person p = Person.parseFrom(new FileInputStream(file));
        byte[] content = p.toByteArray();
      
        URL target = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) target.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("PUT");
        conn.setRequestProperty("Content-Type", "application/x-protobuf");
        conn.setRequestProperty("Accept", "application/x-protobuf;q=0.5");
      
        conn.setRequestProperty("Content-Length", Integer.toString(content.length));
            // set stream mode to decrease memory usage
        conn.setFixedLengthStreamingMode(content.length);
        OutputStream out = conn.getOutputStream();
        out.write(content);
        out.flush();
        out.close();
        conn.connect();
        // check response code
        int code = conn.getResponseCode();
        boolean success = (code >= 200) && (code < 300);
        System.out.println("put person:"+name+" "+(success?"successful!":"failed!"));
    }
    public static void getContacts(String url) throws IOException {
        URL target = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) target.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type", "application/x-protobuf");
        conn.setRequestProperty("Accept", "application/x-protobuf");
        conn.connect();
        // check response code
        int code = conn.getResponseCode();
        boolean success = (code >= 200) && (code < 300);
        InputStream in = success ? conn.getInputStream() : conn.getErrorStream();
              
        int size = conn.getContentLength();
      
        byte[] response = new byte[size];
        int curr = 0, read = 0;
      
        while (curr < size) {
            read = in.read(response, curr, size - curr);
            if (read <= 0) break;
            curr += read;
        }
      
        Person p = Person.parseFrom(response);
        System.out.println("id:"+p.getId());
        System.out.println("name:"+p.getName());
        System.out.println("email:"+p.getEmail());
        List<PhoneNumber> pl = p.getPhoneList();
        for(PhoneNumber pn : pl) {
            System.out.println("number:"+pn.getNumber()+" type:"+pn.getType().name());
        }
    }
}
------------------------------------------------------------------------

CreatePerson.java

package sample.hello.client;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;

import sample.pb.AddressBookProtos.Person;



public class CreatePerson {
    // This function fills in a Person message based on user input.
      static Person create(BufferedReader stdin,
                                     PrintStream stdout) throws IOException {
        Person.Builder person = Person.newBuilder();

        stdout.print("Enter person ID: ");
        person.setId(Integer.valueOf(stdin.readLine()));

        stdout.print("Enter name: ");
        person.setName(stdin.readLine());

        stdout.print("Enter email address (blank for none): ");
        String email = stdin.readLine();
        if (email.length() > 0) {
          person.setEmail(email);
        }

        while (true) {
          stdout.print("Enter a phone number (or leave blank to finish): ");
          String number = stdin.readLine();
          if (number.length() == 0) {
            break;
          }

          Person.PhoneNumber.Builder phoneNumber =
            Person.PhoneNumber.newBuilder().setNumber(number);

          stdout.print("Is this a mobile, home, or work phone? ");
          String type = stdin.readLine();
          if (type.equals("mobile")) {
            phoneNumber.setType(Person.PhoneType.MOBILE);
          } else if (type.equals("home")) {
            phoneNumber.setType(Person.PhoneType.HOME);
          } else if (type.equals("work")) {
            phoneNumber.setType(Person.PhoneType.WORK);
          } else {
            stdout.println("Unknown phone type.  Using default.");
          }

          person.addPhone(phoneNumber);
        }

        return person.build();
      }

      // Main function:  Reads the entire address book from a file,
      //   adds one person based on user input, then writes it back out to the same
      //   file.
      public static void main(String[] args) throws Exception {
     
          Person p = create(new BufferedReader(new InputStreamReader(System.in)),
                           System.out);

        // Write the new address book back to disk.
        FileOutputStream output = new FileOutputStream("D:/"+p.getName()+".per");
        p.writeTo(output);
        output.close();
      }
}
------------------------------------------------------------------

AddressBookResource.java

package sample.hello.resources;

import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

import sample.hello.util.AddressBookStore;
import sample.pb.AddressBookProtos.Person;



@Path("/addressbook")
public class AddressBookResource {
    @PUT
    public Response putPerson(Person person) {      
        AddressBookStore.store(person);
        return Response.ok().build();
    }
  
    @GET
    @Path("/{name}")
    public Response getPerson(@PathParam("name") String name) {      
        Person p = AddressBookStore.getPerson(name);
        return Response.ok(p, "application/x-protobuf").build();
    }
}
------------------------------------------------------------------------------

AddressBookStore.java

package sample.hello.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import sample.pb.AddressBookProtos.AddressBook;
import sample.pb.AddressBookProtos.Person;

public class AddressBookStore {
    static AddressBook addressBook = null;
    static {
        try {
            addressBook =
                  AddressBook.parseFrom(new FileInputStream("D:/addressBooks.txt"));
        } catch (FileNotFoundException e) {
          
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
  
    public static Person getPerson(String name) {
        for(Person person: addressBook.getPersonList()) {
            if(person.getName().equals(name)) {
                return person;
            }
        }
        return null;
    }
  
    public static void store(Person p) {
         AddressBook.Builder addressBookBuilder = AddressBook.newBuilder();
         try {
            String fileName = "D:/addressBooks.txt";
            File file = new File(fileName);
            if(!file.exists()) {
                file.createNewFile();
            }
            addressBookBuilder.mergeFrom(new FileInputStream(fileName));
            addressBookBuilder.addPerson(p);
            addressBookBuilder.build().writeTo(new FileOutputStream(fileName));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        }
  
}

--------------------------------------------------------------------------

AddressBookProtos.java

自动生成的,略

-----------------------------------------------------------------------------

ProtobufMessageBodyReader.java

package sample.pb;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.Consumes;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;

import sample.pb.AddressBookProtos.Person;


@Provider
@Consumes("application/x-protobuf")
public class ProtobufMessageBodyReader implements MessageBodyReader<Object> {
    @Override
    public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations,
            MediaType mediaType) {
        return mediaType.toString().equals("application/x-protobuf");
    }

    @Override
    public Object readFrom(Class<Object> type, Type genericType,
            Annotation[] annotations, MediaType mediaType,
            MultivaluedMap<String, String> httpHeaders, InputStream inputStream)
            throws IOException, WebApplicationException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int read;
        long total = 0L;
        do {
            read = inputStream.read(buffer, 0, buffer.length);
            if (read > 0) {
                baos.write(buffer, 0, read);
                total += read;
            }
        } while (read > 0);

        return Person.parseFrom(baos.toByteArray());
    }
}
---------------------------------------------------------------------------------------------

ProtobufMessageBodyWriter.java

package sample.pb;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.WeakHashMap;

import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;

import sample.pb.AddressBookProtos.Person;

@Provider
@Produces("application/x-protobuf")
public class ProtobufMessageBodyWriter implements MessageBodyWriter<Object> {
    /** a cache to save the cost of duplicated call(getSize, writeTo) to one object. */
    private Map<Object, byte[]> buffer = new WeakHashMap<Object, byte[]>();
  
    @Override
    public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations,
            MediaType mediaType) {
        // it will handle all model classes
        return mediaType.toString().equals("application/x-protobuf");
    }
  
    @Override
    public long getSize(Object message, Class<?> type, Type genericType,
            Annotation[] annotations, MediaType mediaType) {
        Person p = (Person)message;
        byte[] bytes = p.toByteArray();
        buffer.put(message, bytes);
        return bytes.length;
    }

    @Override
    public void writeTo(Object message, Class<?> type, Type genericType,
            Annotation[] annotations, MediaType mediaType,
            MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
            throws IOException, WebApplicationException {
        entityStream.write(buffer.remove(message));
    }
}
--------------------------------------------------------------------------------------

web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">
    <servlet>
        <servlet-name>ServletAdaptor</servlet-name>
        <servlet-class>com.sun.jersey.server.impl.container.servlet.ServletAdaptor</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>ServletAdaptor</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

</web-app>
------------------------------------------------------------------------------------------


五 测试过程:

5.1 设定web application的context name为:

/jerseydemo

web application的root 为

/context

使用Eclipse的tomcat plugin的菜单


会在%TOMACT_HOME%\conf\Catalina\localhost下生成文件:

jerseydemo.xml

内容如下:

<Context path="/jerseydemo" reloadable="true" docBase="D:\workspace\jerseydemo\context" workDir="D:\workspace\jerseydemo\work" />

5.2 运行CreatePerson生成Person并写入磁盘:

在console进行如下输入:



查看D:盘根目录,发现新生成的  hery.per 文件.

5.3 启动tomcat(我就是点下Eclipse上的那只小猫)

5.4 运行ContactClient, 执行结果如下:



可见我们上传成功,并且能按名字查询.

D盘根目录下,同时生成了文件addressBooks.txt,这个为server段保留电话簿的地方.



六 完整的工程打包文件







  • 大小: 45 KB
  • 大小: 20.9 KB
  • 大小: 34.3 KB
  • 大小: 21.5 KB
  • jerseydemo.rar (2.4 MB)
  • 描述: 完整的工程打包文件
  • 下载次数: 446
分享到:
评论

相关推荐

    Rest-Web-Service-Client_v3.6.0.crx.zip

    在实际开发过程中,"Rest-Web-Service-Client_v3.6.0.crx"能够帮助开发者快速测试新API的功能,验证接口的正确性,以及在开发过程中进行持续集成测试。它使得开发者无需编写额外的测试代码,就能直观地看到接口的...

    REST Web Service开发实践

    本文将深入探讨如何使用Jersey、Google Protocol Buffer(简称PB)以及Tomcat这三大组件来开发REST风格的Web服务。 首先,让我们了解一下这三个关键组件: 1. **Jersey**:由Sun Microsystems(现Oracle)开发的...

    Rest-Web-Service-Client_v3.6.0.crx

    基于REST的Web服务客户端是一款功能强大的谷歌浏览器插件,使用基于REST的Web服务客户端(模拟REST客户端)可以让用户使用谷歌浏览器模拟REST请求来测试REST风格,这款插件使用非常方便,欢迎大家来下载使用!

    jersey-core、jersey-client jar包.rar

    Jersey是实现Java RESTful Web服务(JAX-RS)规范的开源框架,由Sun Microsystems(现Oracle)开发,用于构建高效、灵活的Web应用程序。 jersey-core是Jersey的核心模块,包含实现JAX-RS标准所需的基本组件和服务。...

    jersey和Google Protocol Buffer开发Demo

    【标题】:Jersey与Google Protocol Buffer开发Demo详解 【描述】:本示例将深入探讨如何使用Jersey,一个强大的Java RESTful Web服务框架,与Google Protocol Buffers(简称PB)结合,进行高效的数据序列化。这个...

    Rest-Web-Service-Client v3.6.0 for Chrome

    Rest Client Chrome 插件,调试工具

    airavata-rest-service-webapp-0.11-sources.jar

    标签:airavata-rest-service-webapp-0.11-sources.jar,airavata,rest,service,webapp,0.11,sources,jar包下载,依赖包

    matters-rest-spring-jersey-tomcat-mybatis:事项休息春天泽西岛tomcat mybatis

    标题 "matters-rest-spring-jersey-tomcat-mybatis" 暗示这是一个关于构建RESTful服务的项目,使用了Spring、Jersey、Tomcat和MyBatis这些技术。描述中的“事项-休息-春天-球衣-tomcat-mybatis 1”可能是项目名的另...

    airavata-rest-service-webapp-0.9-sources.jar

    标签:airavata-rest-service-webapp-0.9-sources.jar,airavata,rest,service,webapp,0.9,sources,jar包下载,依赖包

    airavata-rest-service-webapp-0.7-sources.jar

    标签:airavata-rest-service-webapp-0.7-sources.jar,airavata,rest,service,webapp,0.7,sources,jar包下载,依赖包

    airavata-rest-service-webapp-0.8-sources.jar

    标签:airavata-rest-service-webapp-0.8-sources.jar,airavata,rest,service,webapp,0.8,sources,jar包下载,依赖包

    airavata-rest-service-webapp-0.6-sources.jar

    标签:airavata-rest-service-webapp-0.6-sources.jar,airavata,rest,service,webapp,0.6,sources,jar包下载,依赖包

    airavata-rest-service-webapp-0.10-sources.jar

    标签:airavata-rest-service-webapp-0.10-sources.jar,airavata,rest,service,webapp,0.10,sources,jar包下载,依赖包

    ASP-NET-Web-API-2-Building-a-REST-Service-from-Start-to-Finish

    The ASP.NET MVC Framework has always been a good platform on which to implement REST-based services, but the introduction of the ASP.NET Web API Framework raised the bar to a whole new level. ...

    Jersey Java规范下REST风格Web Service开发框架

    Jersey Java 规范下 REST 风格 Web Service 开发框架 Jersey 是一个基于 Java 规范的 REST 风格 Web Service 开发框架,旨在帮助开发者快速构建 REST 风格 Web 服务。Jersey 是 JAX-RS(Java API for RESTful Web ...

    MyEclipse REST Web Service 简单的实现例子

    【标题】:MyEclipse REST Web Service 简单实现案例 在当今互联网技术日新月异的时代,REST(Representational State Transfer)架构风格已成为构建Web服务的重要方式,它强调资源的表述和状态转换,简单易用且...

    eclipse-maven-jersey demo

    【标题】"eclipse-maven-jersey demo"是一个演示项目,它展示了如何在Eclipse环境中使用Maven构建和管理一个基于Jersey的RESTful Web服务应用。Jersey是Java平台上的一个开源框架,用于实现 Representational State ...

    Eclipse中使用Jersey和Tomcat构建RESTful WebService及其调用

    "Eclipse中使用Jersey和Tomcat构建RESTful WebService及其调用" RESTful Web服务简介 ----------------- ...使用Jersey和Tomcat构建RESTful Web服务可以提供灵活的Web服务开发体验,同时也可以提高开发效率和质量。

    使用Maven和Jersey Framework开发REST风格Web Service

    总之,结合Maven和Jersey框架,我们可以高效地开发REST风格的Web服务。通过理解Maven的项目管理功能和Jersey的API,开发者可以轻松地创建、部署和维护RESTful服务。同时,与数据库的集成使得这些服务能够处理更复杂...

    eclipse-maven-jersey demo2

    【标题】"eclipse-maven-jersey demo2"是一个示例项目,旨在演示如何在Eclipse集成开发环境中创建一个基于Maven构建的Web工程,并整合Jersey框架来实现RESTful服务。这个教程将帮助开发者了解如何配置Maven、Eclipse...

Global site tag (gtag.js) - Google Analytics