国产一级a片免费看高清,亚洲熟女中文字幕在线视频,黄三级高清在线播放,免费黄色视频在线看

打開APP
userphoto
未登錄

開通VIP,暢享免費電子書等14項超值服

開通VIP
使用CXF開發(fā)RESTFul服務

相信大家在閱讀

CXF官方文檔(http://cxf.apache.org/docs/index.html)時,總是一知半解。這里向大家推薦一本PacktPub.Apache.CXF.Web.Service.Development。目前,這本書是沒有中文版的,為此筆者簡單的寫了一些經驗總結。

CXF官方文檔(http://cxf.apache.org/docs/index.html)時,總是一知半解。這里向大家推薦一本PacktPub.Apache.CXF.Web.Service.Development。目前,這本書是沒有中文版的,為此筆者簡單的寫了一些經驗總結。

 

 

 

這本書內容上安排的比較淺顯,語言上也沒有什么深奧的,值得一讀。另外值得一提的是,這本書比官方文檔高明之處是每個概念就介紹得很清楚,像第二章的Code-firstContract-first,第5章的FeatureInterceptor概念的介紹,還有第6章的REST概念簡介,內容上都比官方文檔詳細很多。缺點就是并沒有將CXF所有的特性都寫下來,這就需要將samples中的內容好好消化一下了。

 

代碼使用Maven組織

 

http://dl.iteye.com/topics/download/fbbf344b-2357-33fe-86d7-a44116e6de85

 

使用CXF開發(fā)RESTFul服務

在各個系統(tǒng)交互領域,Web services逐漸成為主流。有兩種主要方式來開發(fā)Web ServicesSimple Object Access Protocol (SOAP)Representational State Transfer (REST)

 

開發(fā)基于SOAPWeb Services需要很多的約束, 以便客戶端和服務端交互信息,例如,使用Web Service Description Language (WSDL)來描述信息。還有很多WS的標準如WS-Security。

 

使用REST構架的服務被稱為RESTful服務。這種架構利用簡單的XMLHTTP協(xié)議上,就像網頁一樣發(fā)送請求,簡化了基于SOAP架構開發(fā)。RESTful Web Services尤其適用于只需要提交和接受簡單的XML信息。

 

接下來會介紹使用CXF框架來開發(fā)RESTful風格的Web Services。

 

簡介

Java API for RESTful services

CXF JAX-RS實現(xiàn)

開發(fā)RESTful服務

 

簡介

 

REST也就是Representational State TransferREST并不特指一種技術,也不是一個標準,它僅僅是一個構架風格。REST 指的是一組架構約束條件和原則。滿足這些約束條件和原則通過網絡暴露資源給用戶。事實上,WWW就是經典的REST架構風格。在服務器端,應用程序狀態(tài)和功能可以分為各種資源。它向客戶端公開。每個資源都使用 URI (Universal Resource Identifier) 得到一個惟一的地址。所有資源都共享統(tǒng)一的界面,以便在客戶端和服務器之間傳輸狀態(tài)。使用的是標準的 HTTP 方法,比如 GET、PUT、POST 和 DELETE。客戶端通過交換各種資源的表現(xiàn)體來查詢或更新資源。資源的表現(xiàn)體包括HTML,XML,JSON等??蛻舳诵枰馕鲰憫掌鞯谋憩F(xiàn)體。客戶端和服務器之間的交互在請求之間是無狀態(tài)的,無狀態(tài)請求可以由任何可用服務器應答。

 

下面是一些RESTfu例子,提供雇員和部門的信息,并介紹客戶端怎樣訪問這些服務

 

URI for the RESTful service—http://<host>/department/deptname/employee:

·     GET—獲得deptname部門的所有員工信息

·     POST—deptname部門創(chuàng)建員工信息。

·     DELETE—刪除 deptname部門一名員工信息

URI for the RESTful service—http://<host>/department/deptname/employee/naveen:

·     GET—獲得deptname部門名叫naveen的員工信息

·     PUT—deptname部門創(chuàng)建名叫naveen的員工信息

·     DELETE—刪除deptname部門名叫naveen的員工信息

 

下面是POST請求的例子http://<host>/department/deptname/employee

 

 

POST /department/deptname/employee HTTP/1.1

Content-Type: */*

Accept: application/xml

User-Agent: Apache CXF 2.2.2

Cache-Control: no-cache

Pragma: no-cache

Host: 127.0.0.1:9001

<employee><firstname>rajeev</firstname><lastname>hathi</lastname>

<dob>10/26/78</dob></employee>

 

Java API for RESTful services

 

上一節(jié),我們了解雇員POST請求。如果需要提供一種實現(xiàn)去識別雇員POST請求,我們應該做如下工作:

 

識別這是否一個HTTP POST請求。

HTTP POST請求中的XML的內容轉換為實現(xiàn)端所需要的格式,例如JAVA對象。

執(zhí)行指定的操作,例如插入雇員信息到數(shù)據(jù)庫。

HTTP形式響應客戶端,例如設置標志響應成功的HTTP狀態(tài)200 ,并將響應轉換到指定格式(XMLJSON),最后將其設置到HTTP Body。

 

依據(jù)需求,可能你要實現(xiàn)所有的HTTP方法,如GET,PUT,DELETE等。這不就是標準的RESTful JAVA開發(fā)模式嗎?接著,Java API for RESTful Web services (JAX-RS)規(guī)范制定了開發(fā)RESTful的標準。

 

JAX-RS規(guī)范定義了創(chuàng)建RESTful服務的語法。JAX-RS使用annotations注解在實現(xiàn)RESTful的服務,使用annotations注解POJO將它暴露為RESTful資源。RESTful服務類中,通過URI/category)和HTTPGET, POST)方法注解方法。

 

@GET

       @Path("/category/{id}")

       public Category getCategory(@PathParam("id") String id)

 

實現(xiàn)JAX-RS的框架在運行的時候,通過映射HTTP請求到RESTful方法,負責調用正確的JAVA實現(xiàn)方法。JAX-RS規(guī)范提供這種映射的方法的算法?;A算法包括,判斷JAVA資源類,判斷HTTP URI請求,判斷內容格式(例如application/xml),還有HTTP方法(例如GET

 

JAX-RS規(guī)范提出如下要點:

 

POJO依賴性

為了暴露為資源,使用annotations注解POJO

 

HTTP依賴性

RESTful資源暴露在HTTP中,規(guī)范中將HTTP 協(xié)議和JAX-RS API相對應映射。

 

格式獨立性

API中提供嵌入式的方法,標準化添加HTTP內容的類型。例如,application/xml就是HTTP內容的類型中的一種。

 

容器獨立性

可以在任何一種容器中部署實現(xiàn)JAX-RS規(guī)范的應用程序。

 

 

 

CXF JAX-RS實現(xiàn)

 

CXF實現(xiàn)了JAX-RS1.0規(guī)范,并提供了很多特性幫助開發(fā)者搭建企業(yè)級的RESTful服務。

 

下面是CXF框架提供創(chuàng)建RESTful服務的各種特性。

 

 

集成Spring

Spring框架已經變成事實上的構建企業(yè)級JAVA應用程序集成框架。CXF提供與Spring整合,簡化了配置和部署RESTful應用程序。Spring提供依賴注入促進松散耦合,提供各種服務,像聲明式事務管理。所有這些Spring提供的特性都可以被開發(fā)RESTful服務的CXF框架使用。

 

插入式數(shù)據(jù)綁定

數(shù)據(jù)庫綁定就是映射HTTP請求,例如JSONXML,到對應的JAVA對象。同樣的,在發(fā)送HTTP響應之前,服務端的JAVA實現(xiàn)需要映射為客戶端所需要的格式。通過提供數(shù)據(jù)庫綁定組件,CXF在后臺透明的處理映射。CXF支持各種數(shù)據(jù)綁定機制,如JAXB,JSON,XMLBeanAegis。CXF允許指定特定的綁定機制。

 

客戶端API

JAX-RS規(guī)范并沒有提供客戶端調用REST服務的API。CXF提供了這種API直接調用RESTful服務,也可以使用Spring框架配置到應用程序中。

 

安全

CXF可以使用Spring框架集成的聲明式安全組件,按照應用程序的需要限制資源類和方法,而不必使用代碼處理安全性問題。

 

過濾器

過濾器用來預處理或后處理信息。CXF可以創(chuàng)建和配置過濾器來審核信息,記錄信息的日志,還有基于應用要求修改請求或響應。

 

 

 

CXF也運行開發(fā)者使用JAX-WS ProviderDispatch API來創(chuàng)建RESTful服務。

 

開發(fā)RESTful服務

 

本節(jié)將介紹使用JAX-RS實現(xiàn)的方法來開發(fā)RESTful服務,并執(zhí)行CRUD操作。首先看一下Book Shop應用。

 

Book Shop應用是一款網絡應用,提供技術書籍(JAVA.NET)的分類。Book Shop讓管理員為新的書籍創(chuàng)建分類,修改分類等。一旦這個分類存在,應用可以為這個分類添加新的書籍。

 

這個應用將提供如下方法:

創(chuàng)建分類

更新分類

刪除分類

獲取分類列表

獲取特定分類

為特定分類添加書籍

獲取特定分類中所有書籍

 

 

為了開發(fā)RESTful服務,需要做如下工作:

 

創(chuàng)建POJO

POJO類提供數(shù)據(jù)綁定

創(chuàng)建實現(xiàn)RESTful功能的服務類

創(chuàng)建調用RESTful服務的客戶端

 

創(chuàng)建POJO

 

Java代碼  
  1. package demo.restful;  
  2.   
  3. import javax.xml.bind.annotation.XmlRootElement;  
  4.   
  5. @XmlRootElement(name = "Book")  
  6. public class Book {  
  7.   
  8.     private String bookId;  
  9.       
  10.     private String bookISBNnumber;  
  11.       
  12.     private String bookName;  
  13.       
  14.     //Let assume one author only  
  15.     private String author;  
  16.   
  17.     public String getBookId() {  
  18.         return bookId;  
  19.     }  
  20.   
  21.     public void setBookId(String bookId) {  
  22.         this.bookId = bookId;  
  23.     }  
  24.   
  25.     public String getBookISBNnumber() {  
  26.         return bookISBNnumber;  
  27.     }  
  28.   
  29.     public void setBookISBNnumber(String bookISBNnumber) {  
  30.         this.bookISBNnumber = bookISBNnumber;  
  31.     }  
  32.   
  33.     public String getBookName() {  
  34.         return bookName;  
  35.     }  
  36.   
  37.     public void setBookName(String bookName) {  
  38.         this.bookName = bookName;  
  39.     }  
  40.   
  41.     public String getAuthor() {  
  42.         return author;  
  43.     }  
  44.   
  45.     public void setAuthor(String author) {  
  46.         this.author = author;  
  47.     }  
  48.       
  49. }  

 

Java代碼  
  1. package demo.restful;  
  2.   
  3. import java.util.Collection;  
  4.   
  5. import javax.xml.bind.annotation.XmlRootElement;  
  6.   
  7. @XmlRootElement(name = "Category")  
  8. public class Category {  
  9.   
  10.     private String categoryId;  
  11.   
  12.     private String categoryName;  
  13.   
  14.     private Collection<Book> books;  
  15.   
  16.     public String getCategoryId() {  
  17.         return categoryId;  
  18.     }  
  19.   
  20.     public void setCategoryId(String categoryId) {  
  21.         this.categoryId = categoryId;  
  22.     }  
  23.   
  24.     public String getCategoryName() {  
  25.         return categoryName;  
  26.     }  
  27.   
  28.     public void setCategoryName(String categoryName) {  
  29.         this.categoryName = categoryName;  
  30.     }  
  31.   
  32.     public Collection<Book> getBooks() {  
  33.         return books;  
  34.     }  
  35.   
  36.     public void setBooks(Collection<Book> books) {  
  37.         this.books = books;  
  38.     }  
  39.   
  40. }  

 

 

 

 

POJO類提供數(shù)據(jù)綁定

 

為了提供RESTful服務端和客戶端通信,POJO需要轉換為特定的格式,例如XMLJSON。為了實現(xiàn)這部分功能,需要一個數(shù)據(jù)綁定的組件來映射JAVA對象和XML(或者指定的格式)。

 

CXF使用JAXB作為默認的數(shù)據(jù)綁定組件。JAXB使用注解來定義JAVA對象和XML之間映射的關系。

 

POJOCategory中,注解@XmlRootElement指定CategoryXML的根元素。Category類的屬性默認指定映射為@XmlElement。@XmlElement用來定義XML中的子元素。@XmlRootElement@XmlElement允許自定義命名空間和XML中元素的名稱。如果沒有定義的話,JAXB在運行的時候默認的使用同樣的屬性名和類名來定義XML元素。

 

下面的XML請求表示了Category數(shù)據(jù)對象。

 

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

   <Category>

      <books>

         <author>Naveen Balani</author>

         <bookISBNnumber>ISBNB001</bookISBNnumber>

         <bookId>NB001</bookId>

         <bookName>Fiction Book1</bookName>

      </books>

      <categoryId>005</categoryId>

      <categoryName>Fiction Series</categoryName>

   </Category>

 

 

創(chuàng)建實現(xiàn)RESTful功能的服務類

 

類注解

 

CategoryService的類聲明上定義了@Path @Produces注解。@Path定義了URI路徑,客戶端可以通過這個路徑訪問到CategoryService對象。如@Path("/categoryservice"),那么URI請求,就可以是http://localhost:9000/categoryservice/。@Produces定義了服務類和方法生產內容的類型。如@Produces("application/xml"),那么CategoryService只會生產application/xml。

 

方法注解

 

每個方法都和@Produces相關,它決定了這個方法生產什么樣的響應。每個方法都有和HTTP方法映射的的注解,例如@GET @POST。方法中的@Path注解指定了該方法的URI。例如getCategory()方法上的@Path("/category/{id}"),可以使用http://localhost:9000/categoryservice/category/001,訪問到category id 001的分類。{id}就好比參數(shù)。接著,讓我們看看@PathParam注解。@PathParam注解是用來給URI 路徑一個模板變量,方法的輸入參數(shù)。@PathParam("id") 就是URI中的 @Path ("/category/{id}")。

 

@GET

       @Path("/category/{id}")

       public Category getCategory(@PathParam("id") String id)

 

異常處理

 

讓我們看一種情況,客戶端發(fā)送一個請求刪除或者更新一個分類,但是這個分類并不存在,那么服務端需要返回正確的錯誤信息給客戶端。

 

為了處理異常,JAX-RS提供了WebApplicationException,它繼承自RuntimeException類。WebApplicationException可以使用HTTP狀態(tài)代碼或者javax.ws.rs.core.Response對象作為構造器。Response對象除了提供HTTP狀態(tài)代碼外,還可以提供用戶容易識別的錯誤信息。

 

RESTful服務的異常處理可以分為如下幾類:

 

實現(xiàn)類拋出帶有HTTP錯誤代碼的WebApplicationException異常。一般的,4XX定義了客戶端錯誤,如錯誤請求;5XX定義了服務端錯誤,如服務器沒有完成請求。

直接發(fā)回javax.ws.rs.core.Response對象,Response對象中包含了HTTP錯誤代碼。

 

為了測試異常處理代碼,啟動CategoryServerStart類。在IE瀏覽器中輸入

http://localhost:9000/categoryservice/category/011

由于IE不會顯示自定義的錯誤信息,我們會看到HTTP 400 BAD Request。

如果你在Firefox或者Chrome,就會返回

<error>Category Not Found</error>

 

 

 

添加JSON支持

 

@Produces @Consumes注解中添加application/json,指定CategoryService除了application/xml外,還接收和產生application/jsonCXF運行時會處理HTTP JSON請求到JAVA對象的轉換,還有JAVA對象到HTTP JSON響應的映射。

Java代碼  
  1. package demo.restful;  
  2.   
  3. //JAX-RS Imports  
  4. import javax.ws.rs.Consumes;  
  5. import javax.ws.rs.DELETE;  
  6. import javax.ws.rs.GET;  
  7. import javax.ws.rs.POST;  
  8. import javax.ws.rs.PUT;  
  9. import javax.ws.rs.Path;  
  10. import javax.ws.rs.PathParam;  
  11. import javax.ws.rs.Produces;  
  12. import javax.ws.rs.WebApplicationException;  
  13. import javax.ws.rs.core.Response;  
  14. import javax.ws.rs.core.Response.ResponseBuilder;  
  15. import javax.ws.rs.core.Response.Status;  
  16.   
  17. /* 
  18.  * CategoryService class - Add/Removes category for books  
  19.  */  
  20.   
  21. @Path("/categoryservice")  
  22. @Produces({"application/json","application/xml"})  
  23. public class CategoryService {  
  24.   
  25.     private CategoryDAO categoryDAO = new CategoryDAO();  
  26.   
  27.     public CategoryDAO getCategoryDAO() {  
  28.         return categoryDAO;  
  29.     }  
  30.   
  31.     public void setCategoryDAO(CategoryDAO categoryDAO) {  
  32.         this.categoryDAO = categoryDAO;  
  33.     }  
  34.   
  35.     @GET  
  36.     @Path("/category/{id}")  
  37.     @Produces({"application/json","application/xml"})  
  38.     public Category getCategory(@PathParam("id") String id) {  
  39.   
  40.         System.out.println("getCategory called with category id: " + id);  
  41.   
  42.         Category cat = (Category) getCategoryDAO().getCategory(id);  
  43.         if (cat == null) {  
  44.             ResponseBuilder builder = Response.status(Status.BAD_REQUEST);  
  45.             builder.type("application/xml");  
  46.             builder.entity("<error>Category Not Found</error>");  
  47.             throw new WebApplicationException(builder.build());  
  48.         } else {  
  49.             return cat;  
  50.         }  
  51.     }  
  52.   
  53.     @POST  
  54.     @Path("/category")  
  55.     @Consumes({"application/json","application/xml"})  
  56.     public Response addCategory(Category category) {  
  57.   
  58.         System.out.println("addCategory called");  
  59.   
  60.         Category cat = (Category) getCategoryDAO().getCategory(  
  61.                 category.getCategoryId());  
  62.   
  63.         if (cat != null) {  
  64.             return Response.status(Status.BAD_REQUEST).build();  
  65.         } else {  
  66.             getCategoryDAO().addCategory(category);  
  67.             return Response.ok(category).build();  
  68.         }  
  69.   
  70.     }  
  71.   
  72.     @DELETE  
  73.     @Path("/category/{id}")  
  74.     @Consumes({"application/json","application/xml"})  
  75.     public Response deleteCategory(@PathParam("id") String id) {  
  76.   
  77.         System.out.println("deleteCategory with category id : " + id);  
  78.   
  79.         Category cat = (Category) getCategoryDAO().getCategory(id);  
  80.         if (cat == null) {  
  81.             return Response.status(Status.BAD_REQUEST).build();  
  82.         } else {  
  83.             getCategoryDAO().deleteCategory(id);  
  84.             return Response.ok().build();  
  85.         }  
  86.     }  
  87.   
  88.     @PUT  
  89.     @Path("/category")  
  90.     @Consumes({"application/json","application/xml"})  
  91.     public Response updateCategory(Category category) {  
  92.   
  93.         System.out.println("updateCategory with category id : "  
  94.                 + category.getCategoryId());  
  95.   
  96.         Category cat = (Category) getCategoryDAO().getCategory(  
  97.                 category.getCategoryId());  
  98.         if (cat == null) {  
  99.             return Response.status(Status.BAD_REQUEST).build();  
  100.         } else {  
  101.             getCategoryDAO().updateCategory(category);  
  102.             return Response.ok(category).build();  
  103.         }  
  104.     }  
  105.   
  106.     @POST  
  107.     @Path("/category/book")  
  108.     @Consumes({"application/json","application/xml"})  
  109.     public Response addBooks(Category category) {  
  110.   
  111.         System.out.println("addBooks with category id : "  
  112.                 + category.getCategoryId());  
  113.   
  114.         Category cat = (Category) getCategoryDAO().getCategory(  
  115.                 category.getCategoryId());  
  116.         if (cat == null) {  
  117.             return Response.status(Status.NOT_FOUND).build();  
  118.         } else {  
  119.             getCategoryDAO().addBook(category);  
  120.             return Response.ok(category).build();  
  121.         }  
  122.     }  
  123.   
  124.     @GET  
  125.     @Path("/category/{id}/books")  
  126.     @Consumes("application/xml,application/json")  
  127.     public Response getBooks(@PathParam("id") String id) {  
  128.   
  129.         System.out.println("getBooks called with category id : " + id);  
  130.   
  131.         Category cat = (Category) getCategoryDAO().getCategory(id);  
  132.   
  133.         if (cat == null) {  
  134.             return Response.status(Status.NOT_FOUND).build();  
  135.         } else {  
  136.             cat.setBooks(getCategoryDAO().getBooks(id));  
  137.             return Response.ok(cat).build();  
  138.   
  139.         }  
  140.     }  
  141.   
  142. }  

 

 

 

 

DAO

 

 

Java代碼  
  1. package demo.restful;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.Collection;  
  5. import java.util.HashMap;  
  6. import java.util.Map;  
  7.   
  8. /* 
  9.  * DataAcess object for performing CRUD operations. 
  10.  * Dummy implementation. 
  11.  */  
  12. public class CategoryDAO {  
  13.   
  14.     private static Map<String, Category> categoryMap = new HashMap<String, Category>();  
  15.     private static Map<String, Collection<Book>> bookMap = new HashMap<String, Collection<Book>>();  
  16.   
  17.     static {  
  18.   
  19.         Category category1 = new Category();  
  20.         category1.setCategoryId("001");  
  21.         category1.setCategoryName("Java");  
  22.         categoryMap.put(category1.getCategoryId(), category1);  
  23.   
  24.         Book book1 = new Book();  
  25.         book1.setAuthor("Naveen Balani");  
  26.         book1.setBookName("Spring Series");  
  27.         book1.setBookId("001");  
  28.         book1.setBookISBNnumber("ISB001");  
  29.   
  30.         Book book2 = new Book();  
  31.         book2.setAuthor("Rajeev Hathi");  
  32.         book2.setBookName("CXF Series");  
  33.         book2.setBookId("002");  
  34.         book2.setBookISBNnumber("ISB002");  
  35.   
  36.         Collection<Book> booksList = new ArrayList<Book>();  
  37.         booksList.add(book1);  
  38.         booksList.add(book2);  
  39.   
  40.         bookMap.put(category1.getCategoryId(), booksList);  
  41.     }  
  42.   
  43.     public void addCategory(Category category) {  
  44.         categoryMap.put(category.getCategoryId(), category);  
  45.   
  46.     }  
  47.   
  48.     public void addBook(Category category) {  
  49.         bookMap.put(category.getCategoryId(), category.getBooks());  
  50.   
  51.     }  
  52.   
  53.     public Collection<Book> getBooks(String categoryId) {  
  54.         return bookMap.get(categoryId);  
  55.   
  56.     }  
  57.   
  58.     public Category getCategory(String id) {  
  59.         Category cat = null;  
  60.         //Dummy implementation to return a new copy of category to   
  61.       //avoid getting overridden by service  
  62.         if(categoryMap.get(id) != null) {  
  63.         cat = new Category();  
  64.         cat.setCategoryId(categoryMap.get(id).getCategoryId());  
  65.         cat.setCategoryName(categoryMap.get(id).getCategoryName());  
  66.         }  
  67.         return cat;  
  68.     }  
  69.   
  70.     public void deleteCategory(String id) {  
  71.         categoryMap.remove(id);  
  72.         // Remove association of books  
  73.         bookMap.remove(id);  
  74.     }  
  75.   
  76.     public void updateCategory(Category category) {  
  77.         categoryMap.put(category.getCategoryId(), category);  
  78.   
  79.     }  
  80.   
  81. }  

 

 

 

創(chuàng)建調用RESTful服務的客戶端

 

JAX-RS并不提供調用RESTful服務客戶端。CXF框架提供了兩種方式來創(chuàng)建客戶端,這兩種都可以使用Spring配置。

 

代理API

代理API允許你使用RESTful服務的資源類和接口。代理類是客戶端直接調用接口方法,使用戶不需要手工創(chuàng)建HTTP請求。將RESTful服務類傳遞給org.apache.cxf.jaxrs.client.JAXRSClientFactory類。一旦代理類創(chuàng)建好了,你可以直接使用RESTful服務接口類的任何方法。

 

CategoryService store = JAXRSClientFactory.create("http://

localhost:9000", CategoryService.class);

//Makes remote call to Category RESTFul service

store.getBooks("001");

 

HTTP客戶端

使用org.apache.cxf.jaxrs.client.WebClient調用RESTful服務。本例中采用HTTP客戶端。

 

Java代碼  
  1. package demo.restful.client;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.Collection;  
  5. import java.util.Iterator;  
  6.   
  7. import javax.ws.rs.core.Response;  
  8.   
  9. import org.apache.cxf.jaxrs.client.WebClient;  
  10.   
  11. import demo.restful.Book;  
  12. import demo.restful.Category;  
  13.   
  14. public class CategoryServiceRESTClient {  
  15.   
  16.     //Put some static value  
  17.     private static final String CATEGORY_URL = "http://localhost:9000/";  
  18.     private static final String CATEGORY_ID = "005";  
  19.     private static final String TYPE_XML = "application/xml";  
  20.     private static final String TYPE_JSON = "application/json";  
  21.   
  22.     public static void main(String[] args) {  
  23.   
  24.         //System.out.println("Format is " + args[0]);  
  25.   
  26.         testAddCategory(TYPE_XML);  
  27.         testUpdateCategory(TYPE_XML);  
  28.         testGetCategory(TYPE_XML);  
  29.         testAddBooksForCategory(TYPE_XML);  
  30.         testGetBooksForCategory(TYPE_XML);  
  31.         testDeleteCategory(TYPE_XML);  
  32.   
  33.         testAddCategory(TYPE_JSON);  
  34.         testUpdateCategory(TYPE_JSON);  
  35.         testGetCategory(TYPE_JSON);  
  36.         testAddBooksForCategory(TYPE_JSON);  
  37.         testGetBooksForCategory(TYPE_JSON);  
  38.         testDeleteCategory(TYPE_JSON);  
  39.   
  40. //      if(args[0] !=null && args[0].equalsIgnoreCase(TYPE_XML)){  
  41. //          //Content type- XML  
  42. //          testAddCategory(TYPE_XML);  
  43. //          testUpdateCategory(TYPE_XML);  
  44. //          testGetCategory(TYPE_XML);  
  45. //          testAddBooksForCategory(TYPE_XML);  
  46. //          testGetBooksForCategory(TYPE_XML);  
  47. //          testDeleteCategory(TYPE_XML);  
  48. //      }  
  49. //        
  50. //      if(args[0] !=null && args[0].equalsIgnoreCase(TYPE_JSON)){  
  51. //          //ContentType- JSON  
  52. //          testAddCategory(TYPE_JSON);  
  53. //          testUpdateCategory(TYPE_JSON);  
  54. //          testGetCategory(TYPE_JSON);  
  55. //          testAddBooksForCategory(TYPE_JSON);  
  56. //          testGetBooksForCategory(TYPE_JSON);  
  57. //          testDeleteCategory(TYPE_JSON);  
  58. //      }  
  59.   
  60.   
  61.     }  
  62.   
  63.     private static void testAddCategory(final String format) {  
  64.   
  65.         System.out.println("testAddCategory called with format " + format);  
  66.         WebClient client = WebClient.create(CATEGORY_URL);  
  67.         client.path("/categoryservice/category").accept(  
  68.                 format).type(format);  
  69.         Category cat = new Category();  
  70.         cat.setCategoryId(CATEGORY_ID);  
  71.         cat.setCategoryName("Fiction");  
  72.         Category catResponse = client.post(cat, Category.class);  
  73.         System.out.println("Category Id retreived for format " + format + " is " + catResponse.getCategoryId());  
  74.         assertEquals(catResponse.getCategoryId(), CATEGORY_ID);  
  75.   
  76.   
  77.     }  
  78.   
  79.     private static void testUpdateCategory(final String format) {  
  80.   
  81.         System.out.println("testUpdateCategory called with format " + format);  
  82.         WebClient client = WebClient.create(CATEGORY_URL);  
  83.         client.path("/categoryservice/category").accept(  
  84.                 format).type(format);  
  85.         Category cat = new Category();  
  86.         cat.setCategoryId(CATEGORY_ID);  
  87.         cat.setCategoryName("Fiction Series");  
  88.         Response response = client.put(cat);  
  89.         System.out.println("Status retreived for update category for format " + format + " is " + response.getStatus());  
  90.         assertEquals("200", String.valueOf(response.getStatus()));  
  91.   
  92.   
  93.     }  
  94.   
  95.     private static void testGetCategory(final String format) {  
  96.   
  97.         System.out.println("testGetCategory called with format " + format);  
  98.         WebClient client = WebClient.create(CATEGORY_URL);  
  99.         Category category = client.path("/categoryservice/category/" + CATEGORY_ID).accept(  
  100.                 format).type(format).get(Category.class);  
  101.         System.out.println("Category details retreived from service with format " + format);  
  102.         System.out.println("Category Name " + category.getCategoryName());  
  103.         System.out.println("Category Id " + category.getCategoryId());  
  104.         assertEquals(CATEGORY_ID, category.getCategoryId());  
  105.   
  106.   
  107.     }  
  108.   
  109.     private static void testAddBooksForCategory(final String format) {  
  110.   
  111.         System.out.println("testAddBooksForCategory called with format " + format);  
  112.         WebClient client = WebClient.create(CATEGORY_URL);  
  113.         client.path("/categoryservice/category/book").type(format).  
  114.                 accept(format);  
  115.         Category cat = new Category();  
  116.         cat.setCategoryId(CATEGORY_ID);  
  117.         cat.setCategoryName("Fiction Series");  
  118.         Book book1 = new Book();  
  119.         book1.setAuthor("Naveen Balani");  
  120.         book1.setBookId("NB001");  
  121.         book1.setBookISBNnumber("ISBNB001");  
  122.         book1.setBookName("Fiction Book1");  
  123.   
  124.         Collection<Book> booksList = new ArrayList<Book>();  
  125.         booksList.add(book1);  
  126.         cat.setBooks(booksList);  
  127.         client.post(cat, Category.class);  
  128.   
  129.   
  130.   
  131.     }  
  132.   
  133.     private static void testGetBooksForCategory(final String format) {  
  134.   
  135.         System.out.println("testGetBooksForCategory called with format " + format);  
  136.         WebClient clientBook = WebClient.create(CATEGORY_URL);  
  137.         Category categoryBooks = clientBook.path(  
  138.                 "/categoryservice/category/" + CATEGORY_ID + "/books").type(format).accept(format).get(Category.class);  
  139.         System.out.println("Book details retreived from service with format " + format);  
  140.   
  141.         assertEquals(String.valueOf(categoryBooks.getBooks().size()), "1");  
  142.   
  143.         Iterator<Book> iterator = categoryBooks.getBooks().iterator();  
  144.         while (iterator.hasNext()) {  
  145.             Book book = iterator.next();  
  146.             System.out.println("Book Name " + book.getBookName());  
  147.             System.out.println("Book ISBN " + book.getBookISBNnumber());  
  148.             System.out.println("Book ID " + book.getBookId());  
  149.             System.out.println("Book Author " + book.getAuthor());  
  150.   
  151.         }  
  152.   
  153.   
  154.     }  
  155.   
  156.     private static void testDeleteCategory(final String format) {  
  157.   
  158.         System.out.println("testDeleteCategory called with format " + format);  
  159.         WebClient client = WebClient.create(CATEGORY_URL);  
  160.         client.path("/categoryservice/category/" + CATEGORY_ID).type(format).  
  161.                 accept(format);  
  162.         Response response = client.delete();  
  163.         System.out.println("Status retreived for delete category for format " + format + " is " + response.getStatus());  
  164.         assertEquals("200", String.valueOf(response.getStatus()));  
  165.   
  166.   
  167.     }  
  168.   
  169.     private static void assertEquals(String expected, String result) {  
  170.         if (!expected.equalsIgnoreCase(result)) {  
  171.             throw new RuntimeException("Expecte value " + expected + ", Got value" + result);  
  172.         }  
  173.     }  
  174. }  

 

 

 

 

 

本站僅提供存儲服務,所有內容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權內容,請點擊舉報。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
REST方式的CXF WebService實現(xiàn)
CXF Rest Client
Apache CXF 3.0: CDI 1.1 Support as Alternative to Spring
使用 Jersey 和 Apache Tomcat 構建 RESTful Web 服務
C# 服務端篇之實現(xiàn)RestFul Service開發(fā)(簡單實用)
Java 與 REST 的邂逅(一)淺談 Jersey 及 JAX
更多類似文章 >>
生活服務
分享 收藏 導長圖 關注 下載文章
綁定賬號成功
后續(xù)可登錄賬號暢享VIP特權!
如果VIP功能使用有故障,
可點擊這里聯(lián)系客服!

聯(lián)系客服