zoukankan      html  css  js  c++  java
  • 通过代码学REST之二——Restlet框架学习

    /**
     *  
     * @摘自
     * 
    http://www.restlet.org/documentation/1.1/firstResource
     * 一个服务器端的组件,用来启动一个服务,监听8182端口,并将/firstResource的URL请求,交给
     * FirstResourceApplication
     
    */
    public class FirstResourceServerMain
    {
        
    public static void main(String[] args) throws Exception
        {
            
    // Create a new Component.
            Component component = new Component();
            
    // Add a new HTTP server listening on port 8182.
            component.getServers().add(Protocol.HTTP, 8182);
            
    // Attach the sample application.
            component.getDefaultHost().attach("/firstResource",new FirstResourceApplication());
            
    // Start the component.
            component.start();
        }
    }
    package firstSteps;

    import java.util.concurrent.ConcurrentHashMap;
    import java.util.concurrent.ConcurrentMap;

    import org.restlet.Application;
    import org.restlet.Restlet;
    import org.restlet.Router;
    -----------------------------------------------------这个类类似于Struts中的中央控制器的作用--------------------------------------------------
    /**/
    public class FirstResourceApplication extends Application
    {  
          
            
    /** The list of items is persisted in memory. */  
            
    private final ConcurrentMap<String, Item> items =  new ConcurrentHashMap<String, Item>();  
          
            
    /** 
             * Creates a root Restlet that will receive all incoming calls. 
             * In general, instances of Router, Filter or Handler classes will be used as initial application Restlet. 
             * The default implementation returns null by default. This method is intended to be overriden by subclasses. 
             * 
             
    */  
            @Override  
            
    public Restlet createRoot() 
            {  
                
    // Create a router Restlet that defines routes.  
                Router router = new Router(getContext());  
                
    // Defines a route for the resource "list of items"  
                router.attach("/items", ItemsResource.class);  
                
    // Defines a route for the resource "item"  
                router.attach("/items/{itemName}", ItemResource.class);  
          
                
    return router;  
            }  
          
            
    /** 
             * Returns the list of registered items. 
             *  
             * 
    @return the list of registered items. 
             
    */  
            
    public ConcurrentMap<String, Item> getItems()
            {  
                
    return items;  
            }  
        }  
    package firstSteps;

    import java.io.IOException;

    import org.restlet.Client;
    import org.restlet.data.Form;
    import org.restlet.data.Protocol;
    import org.restlet.data.Reference;
    import org.restlet.data.Response;
    import org.restlet.resource.Representation;

    public class FirstResourceClientMain 
    {
            
    public static void main(String[] args) throws IOException
            {  
                    
    // Define our Restlet HTTP client.  
                    Client client = new Client(Protocol.HTTP);  //作为一个通用连接器
                    
    // The URI of the resource "list of items".  
                    Reference itemsUri = new Reference("http://localhost:8102/firstResource/items");  
                    
    // Create a new item  
                    Item item = new Item("item1""this is an item.");  
                    Reference itemUri 
    = createItem(item, client, itemsUri);  
                    
    if (itemUri != null) {  
                        
    // Prints the representation of the newly created resource.  
                        get(client, itemUri);  
                    }  
              
                    
    // Prints the list of registered items.  
                    get(client, itemsUri);  
              
                    
    // Update the item  
                    item.setDescription("This is an other description");  
                    updateItem(item, client, itemUri);  
              
                    
    // Prints the list of registered items.  
                    get(client, itemsUri);  
              
                    
    // delete the item  
                    deleteItem(client, itemUri);  
              
                    
    // Print the list of registered items.  
                    get(client, itemsUri);  
                }  
              
                
    /** 
                 * Try to create a new item. 
                 * 
                 * 
    @param item 
                 *                the new item. 
                 * 
    @param client 
                 *                the Restlet HTTP client. 
                 * 
    @param itemsUri 
                 *                where to POST the data. 
                 * 
    @return the Reference of the new resource if the creation succeeds, null 
                 *         otherwise. 
                 
    */  
                
    public static Reference createItem(Item item, Client client,   Reference itemsUri)
                {  
                    
    // Gathering informations into a Web form.  
                    Form form = new Form();  
                    form.add(
    "name", item.getName());  
                    form.add(
    "description", item.getDescription());  
                    Representation rep 
    = form.getWebRepresentation();  
                    
    // Launch the request  
                    Response response = client.post(itemsUri, rep);  
                    
    if (response.getStatus().isSuccess())
                    {  
                        
    return response.getEntity().getIdentifier();  
                    }  
              
                    
    return null;  
                }  
              
                
    /** 
                 * Prints the resource's representation. 
                 * 
                 * 
    @param client 
                 *                client Restlet. 
                 * 
    @param reference 
                 *                the resource's URI. 
                 * 
    @throws IOException 
                 
    */  
                
    public static void get(Client client, Reference reference)  throws IOException 
                   {  
                    Response response 
    = client.get(reference);  
                    
    if (response.getStatus().isSuccess()) {  
                        
    if (response.isEntityAvailable()) {  
                            response.getEntity().write(System.out);  
                        }  
                    }  
                }  
              
                
    /** 
                 * Try to update an item. 
                 * 
                 * 
    @param item 
                 *                the item. 
                 * 
    @param client 
                 *                the Restlet HTTP client. 
                 * 
    @param itemUri 
                 *                the resource's URI. 
                 
    */  
                
    public static boolean updateItem(Item item,   
                                                 Client client,   
                                                 Reference itemUri) {  
                    
    // Gathering informations into a Web form.  
                    Form form = new Form();  
                    form.add(
    "name", item.getName());  
                    form.add(
    "description", item.getDescription());  
                    Representation rep 
    = form.getWebRepresentation();  
              
                    
    // Launch the request  
                    Response response = client.put(itemUri, rep);  
                    
    return response.getStatus().isSuccess();  
                }  
              
                
    /** 
                 * Try to delete an item. 
                 * 
                 * 
    @param client 
                 *                the Restlet HTTP client. 
                 * 
    @param itemUri 
                 *                the resource's URI. 
                 
    */  
                
    public static boolean deleteItem(Client client, Reference itemUri) {  
                    
    // Launch the request  
                    Response response = client.delete(itemUri);  
                    
    return response.getStatus().isSuccess();  
                }  
    }

    Hander:
      extends Object
    Final handler of calls typcially created by Finders.Handler 的实例允许对处理的请求在一个线程安全的上下文

    中运行.
    -------------------------------------------------------------------------------------------------------
    Uniform:
      extends Object
    显露了统一的REST接口的基类.REST架构风格与其他基于网络的开发风格的重要特征是强调组件之间的一个统一接口。
    -------------------------------------------------------------------------------------------------------
    Resource:
      extends Handler
    资源表示超连接资源目标中的概念
    Intended conceptual target of a hypertext reference. "Any information that can be named can be a
    resource: a document or image, a temporal service (e.g. "today's weather in Los Angeles"),
    -------------------------------------------------------------------------------------------------------
    Variant:
    资源的可能表现形式的描述
    Descriptor for available representations of a resource. It contains all the important metadata about a
    representation but is not able to actually serve the representation's content itself.
    --------------------------------------------------------------------------------------------------------
    Representation:
    表现用来展示资源(Resource)当前或即将的状态.
    The content of a representataion can be retrieved several times if there is a stable and accessible
    source,like a local file or a string.When the representation is obtained via a temporary source like a
    network socket,
    -------------------------------------------------------------------------------------------------------
    Client:
     Connector acting as a generic client.[作为一个通用客户端的连接器].
    -------------------------------------------------------------------------------------------------------
    Reference:
     Reference to a URI.与Java中的URI类相比,这个接口表示互变的引用.
    -------------------------------------------------------------------------------------------------------
    Form:
     Form是一个专门的可修改的参数列表.
    -------------------------------------------------------------------------------------------------------
    Restlet:
     Restlet是一个提供上下文和生命周期支持的统一类。它有很多子类聚焦在采用特别方式对请求进行处理。
     The context property is typically provided by a parent Component as a way to encapsulate access to

    shared features such as logging and client connector.
    -------------------------------------------------------------------------------------------------------
    Application:
     Restlet子类,可以被attached到一个或多个虚拟主机。
     Application同样也有很多有用的关系服务。
     @"connectorService" to declare necessary client and server connector.
     #"decoderService" to automatically decode or decompress request entities.
     #"metadataService" to provide access to metadata and their associated extension names.
     #"statusService" to provide common representations for exception status.
     # "taskService" to run tasks asynchronously.
     # "tunnelService" to tunnel method names or client preferences via query parameters.
    -------------------------------------------------------------------------------------------------------
    Component:
    Restlet子类,用来管理一系列连接器、虚拟主机和应用程序。应用Application.Application are expected to be directly attached to VirtualHosts. Components are expose several services: access logging and status setting.
    从软件架构的角度,组件是什么?
    Component is an abstract unit of software instruction and internal state that provides a tranformation
    of data via its interface"...
    -------------------------------------------------------------------------------------------------------
    Virtual Host: extends Router
    将来自Server连接器的请求路由到Restlets. The attached Restlets are typically Application.
    虚拟主机下的三个类:

    Route attach(Restlet target)   
          Attaches a target Restlet to this router with an empty URI pattern.
    Route attach(String uriPattern, Restlet target)
          Atttaches a target Restlet to this router based on a given URI pattern.
    Route attachDefault(Restlet defaultTarget)


  • 相关阅读:
    SQL Server 与 Entity Framework 级联删除
    web api 2 学习笔记 (Odata ODataQueryOptions 使用)
    【建议收藏】设计师必备-史上最全的个人资料页面设计模板下载
    浅谈产品经理入门和学习路径
    最全面!2019年最新UX设计趋势预测合集
    最新Dashboard设计实例、技巧和资源集锦,视觉和功能两不误,妥妥的!
    【技巧分享】设计师如何向开发人员顺利交付作品?
    摹客iDoc201901-2新功能点评
    企业类Web原型制作分享-Kraftwerk
    【新年福利】2019年值得一用的8款协作工具
  • 原文地址:https://www.cnblogs.com/chp008/p/1708368.html
Copyright © 2011-2022 走看看