⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 restservice.java

📁 一个工作流设计及定义的系统,可以直接与数据库结合进行系统工作流程的定义及应用.
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/* * Copyright (c) 2005, John Mettraux, OpenWFE.org * All rights reserved. *  * Redistribution and use in source and binary forms, with or without  * modification, are permitted provided that the following conditions are met: *  * . Redistributions of source code must retain the above copyright notice, this *   list of conditions and the following disclaimer.   *  * . Redistributions in binary form must reproduce the above copyright notice,  *   this list of conditions and the following disclaimer in the documentation  *   and/or other materials provided with the distribution. *  * . Neither the name of the "OpenWFE" nor the names of its contributors may be *   used to endorse or promote products derived from this software without *   specific prior written permission. *  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE  * POSSIBILITY OF SUCH DAMAGE. * * $Id: RestService.java,v 1.11 2005/05/17 16:40:15 jmettraux Exp $ *///// RestService.java//// john.mettraux@openwfe.org//// generated with // jtmpl 1.0.04 31.10.2002 John Mettraux (jmettraux@openwfe.org)//package openwfe.org.rest;import java.nio.channels.SelectionKey;import java.nio.channels.SocketChannel;import java.nio.channels.ReadableByteChannel;import openwfe.org.MapUtils;import openwfe.org.Application;import openwfe.org.ServiceException;import openwfe.org.ApplicationContext;import openwfe.org.xml.XmlUtils;import openwfe.org.net.NetUtils;import openwfe.org.net.SocketService;import openwfe.org.time.Time;/** * http listening * (London Calling ?) * * <p><font size=2>CVS Info : * <br>$Author: jmettraux $ * <br>$Date: 2005/05/17 16:40:15 $ * <br>$Id: RestService.java,v 1.11 2005/05/17 16:40:15 jmettraux Exp $ </font> * * @author john.mettraux@openwfe.org */public class RestService    extends SocketService{    private final static org.apache.log4j.Logger log = org.apache.log4j.Logger        .getLogger(RestService.class.getName());    //    // CONSTANTS & co    public final static int DEFAULT_PORT         = 6080;    /**      * Use this parameter name ('serverName') to tell the service what     * is the server name to be advertised to the client.     */    public final static String P_SERVER_NAME        = "serverName";    /**     * Use this parameter ('restSessionClass') to tell the service which     * RestSession implementation it should use.     */    public final static String P_REST_SESSION_CLASS        = "restSessionClass";    /**     * Use this parameter name ('purgeFrequency') to tell the RestService     * how frequently it should check for timed out sessions.     */    public final static String P_PURGE_FREQUENCY        = "purgeFrequency";    /**     * Use this parameter name ('sessionTimeout') to tell the RestService     * what is the max idle time for a REST session.     */    public final static String P_SESSION_TIMEOUT        = "sessionTimeout";    protected final static String DEFAULT_SERVER_NAME        = "$Id: RestService.java,v 1.11 2005/05/17 16:40:15 jmettraux Exp $";    protected final static long DEFAULT_PURGE_FREQUENCY        = Time.parseTimeString("2m");    protected final static long DEFAULT_SESSION_TIMEOUT        = Time.parseTimeString("10m");    //    // FIELDS    private java.util.Map unmodifiableServiceParams = null;    private String serverName = null;    private String restSessionClassName = null;    private java.util.Map sessions = new java.util.HashMap();    private java.util.TimerTask timeOutTask = null;    private Long lastGivenId = new Long(-1);    //    // CONSTRUCTORS    public void init         (final String serviceName,          final ApplicationContext context,          final java.util.Map serviceParams)    throws         ServiceException    {        setDefaultPort(DEFAULT_PORT); // else it will listen on 7000...        super.init(serviceName, context, serviceParams);        this.unmodifiableServiceParams = java.util.Collections            .unmodifiableMap(serviceParams);        //        // determining serverName                this.serverName = MapUtils.getAsString            (serviceParams, P_SERVER_NAME, DEFAULT_SERVER_NAME);        //        // determining RestSession implementation to use                this.restSessionClassName = MapUtils.getAsString            (serviceParams, P_REST_SESSION_CLASS);        try        {            final Class c = Class.forName(this.restSessionClassName);            final RestSession tmpSession = (RestSession)c.newInstance();            //            // the tmpSession establishment is performed once at initialization            // of the RestService. If succesfull, it proves that the             // wrapped around RestSession is operational and thus that the            // RestService is operational.            //        }        catch (final Throwable t)        {            throw new ServiceException                ("Cannot use RestSession of class "+this.restSessionClassName,                  t);        }        //        // starting session timeout system                long timeout = MapUtils.getAsLong            (serviceParams, P_SESSION_TIMEOUT, DEFAULT_SESSION_TIMEOUT);        long frequency = MapUtils.getAsLong            (serviceParams, P_PURGE_FREQUENCY, DEFAULT_PURGE_FREQUENCY);        log.info("Session timeout set to "+timeout+" ms");        log.info("Purge frequency set to "+frequency+" ms");        final long finalTimeout = timeout;        this.timeOutTask = new java.util.TimerTask()        {            public void run ()            {                timeOutSessions(finalTimeout);            }        };        Application.getTimer().schedule(this.timeOutTask, 15, frequency);        //        // done        log.info("Service '"+getName()+"' ready.");    }    //    // METHODS    public String getServerName ()    {        return this.serverName;    }    public String getRestSessionClassName ()    {        return this.restSessionClassName;    }    //    // METHODS from Service    public org.jdom.Element getStatus ()    {        org.jdom.Element result = new org.jdom.Element(getName());        result.addContent(XmlUtils.getClassElt(this));        result.addContent(XmlUtils.getRevisionElt("$Id: RestService.java,v 1.11 2005/05/17 16:40:15 jmettraux Exp $"));        return result;    }    //    // METHODS from SocketService    public void handle (final SelectionKey key)        throws ServiceException    {        try        {            final SocketChannel channel = (SocketChannel)key.channel();            log.debug                ("Incoming connection from "+                 channel.socket().getInetAddress());            final byte[] request = extractRequest(channel);            if ( ! verify(key, request)) return;            final Long sessionId = extractSessionId(request);            if (sessionId == null)                //                // authenticate            {                authenticate(key, request);            }            else                //                // is the session registered ?            {                final RestSession session = (RestSession)this.sessions                    .get(sessionId);                //log.debug                //    ("Sessions : "+                //     RestSession.printSessions(this.sessions));                if (session == null)                    //                    // no                {                    NetUtils.httpReply                        (key,                         404,                         "No such session",                         this.serverName,                         null,                         "text/plain",                         null);                    return;                }                //                // yes                session.handle(key, request);            }        }        catch (java.io.IOException ie)        {            throw new ServiceException                ("Socket handling failed", ie);        }    }    public void stop ()        throws ServiceException    {        this.timeOutTask.cancel();        log.info("timeout system for rest sessions stopped.");        super.stop();    }    //    // METHODS    private void authenticate (SelectionKey key, byte[] request)    {        Exception exception = null;            // perhaps some exception will be lodged here. Hope none...        //        // is it an authorization request        // or whatever else ?                String sAuth = extractHeaderValue(request, "Authorization");        if (sAuth != null)        {            if ( ! sAuth.toLowerCase().startsWith("basic"))            {                NetUtils.httpReply                    (key,                     401,                     "Unauthorized: only 'BASIC' authentication supported",                     this.serverName,                     null,                     "text/plain",                     null);                return;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -