【问题标题】:Is there a standard way to package many Restlets into a single Restlet?有没有一种标准方法可以将许多 Restlet 打包成一个 Restlet?
【发布时间】:2017-12-13 01:57:30
【问题描述】:

我的情况是应用程序开发人员和框架提供者不是人。作为框架提供者,我希望能够为开发人员提供看起来像单个过滤器,但实际上是标准过滤器链(例如身份验证、设置调用上下文、指标、++)。

我似乎在标准库中找不到这个功能,但也许有一个扩展。

【问题讨论】:

    标签: restlet


    【解决方案1】:

    我没有等待答案,而是继续我自己的实现,如果有人需要,我会在这里分享。

    /**
     * Composes an array of Restlet Filters into a single Filter.
     */
    public class ComposingFilter extends Filter
    {
        private final Filter first;
        private final Filter last;
    
        public ComposingFilter( Filter... composedOf )
        {
            Objects.requireNonNull( composedOf );
            if( composedOf.length == 0 )
            {
                throw new IllegalArgumentException( "Filter chain can't be empty." );
            }
            first = composedOf[ 0 ];
            Filter prev = first;
            for( int i = 1; i < composedOf.length; i++ )
            {
                Filter next = composedOf[ i ];
                prev.setNext( next );
                prev = next;
            }
            last = composedOf[ composedOf.length - 1 ];
        }
    
        @Override
        protected int doHandle( Request request, Response response )
        {
            if( first != null )
            {
                first.handle( request, response );
                Response.setCurrent( response );
                if( getContext() != null )
                {
                    Context.setCurrent( getContext() );
                }
            }
            else
            {
                response.setStatus( Status.SERVER_ERROR_INTERNAL );
                getLogger().warning( "The filter " + getName() + " was executed without a next Restlet attached to it." );
            }
            return CONTINUE;
        }
    
        @Override
        public synchronized void start()
            throws Exception
        {
            if( isStopped() )
            {
                first.start();
                super.start();
            }
        }
    
        @Override
        public synchronized void stop()
            throws Exception
        {
            if( isStarted() )
            {
                super.stop();
                first.stop();
            }
        }
    
        @Override
        public Restlet getNext()
        {
            return last.getNext();
        }
    
        @Override
        public void setNext( Class<? extends ServerResource> targetClass )
        {
            last.setNext( targetClass );
        }
    
        @Override
        public void setNext( Restlet next )
        {
            last.setNext( next );
        }
    }
    

    注意:尚未测试。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-11
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    相关资源
    最近更新 更多