📄 restsession.java
字号:
/* * 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: RestSession.java,v 1.11 2005/05/17 16:40:15 jmettraux Exp $ *///// RestSession.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 openwfe.org.Utils;import openwfe.org.ExceptionUtils;import openwfe.org.ServiceException;import openwfe.org.OpenWfeException;import openwfe.org.ApplicationContext;import openwfe.org.net.NetUtils;/** * The skeleton of a REST session, implement it to handle your REST actions. * * <p><font size=2>CVS Info : * <br>$Author: jmettraux $ * <br>$Date: 2005/05/17 16:40:15 $ * <br>$Id: RestSession.java,v 1.11 2005/05/17 16:40:15 jmettraux Exp $ </font> * * @author john.mettraux@openwfe.org */public abstract class RestSession{ private final static org.apache.log4j.Logger log = org.apache.log4j.Logger .getLogger(RestSession.class.getName()); // // CONSTANTS and DEFINITIONS public final static String ACTION_END_WORK_SESSION = "endworksession"; // // FIELDS protected RestService service = null; protected ApplicationContext applicationContext = null; protected java.util.Map serviceParams = null; protected Long sessionId = null; protected long lastUsed = -1; // // CONSTRUCTORS public void init (final RestService service, final Long sessionId, final String username, final String password) throws ServiceException { this.service = service; this.sessionId = sessionId; touch(); authentify(username, password); } // // ABSTRACT METHODS /** * Implement this method so that it sets up the RMI or whatever * back session. */ protected abstract boolean authentify (String userName, String password) throws ServiceException; /** * Implement for determining what to do with every REST action */ protected boolean evalRequest (final String action, final SelectionKey key, final String firstLine, final byte[] request) throws Exception { final String methodName = "do_"+action.toLowerCase(); final java.lang.reflect.Method method = this.getClass() .getMethod (methodName, new Class[] { SelectionKey.class, String.class, byte[].class }); final Object result = method.invoke (this, new Object[] { key, firstLine, request }); if (result == null) return true; return ((Boolean)result).booleanValue(); } // // METHODS public long getLastUsed () { return this.lastUsed; } /** * Handles the incoming REST request */ public void handle (final SelectionKey key, final byte[] request) { touch(); // // which action is requested ? String firstLine = null; String action = null; Exception exception = null; try { firstLine = RestService.createBufferedReader(request) .readLine(); action = RestUtils.extractFromLine(firstLine, "action"); } catch (java.io.IOException ie) { log.info("Failed to parse 'action' from http request", ie); exception = ie; } if (action == null) { Object body = exception; if (body == null) body = "No specific action requested"; NetUtils.httpReply (key, 400, "Bad Request", this.service.getServerName(), null, "text/plain", body); return; } action = action.toLowerCase(); // // point to action handling if (action.equals(ACTION_END_WORK_SESSION)) { if (this.service != null) this.service.removeSession(this.sessionId); log.info("Session "+this.sessionId+" ended."); NetUtils.httpReply (key, 200, "OK", this.service.getServerName(), null, "text/xml", new org.jdom.Element("bye")); return; } try { try { if (evalRequest(action, key, firstLine, request)) return; } catch (final java.lang.reflect.InvocationTargetException ite) { throw ite.getCause(); } } catch (final java.net.MalformedURLException mue) { log.info("Malformed URL Exception : ", mue); NetUtils.httpReply (key, 400, "Bad Request", this.service.getServerName(), null, "text/plain", mue); return; } catch (final HttpException he) { log.info("HTTP error : ", he); NetUtils.httpReply (key, he.getErrorCode(), he.getMessage(), this.service.getServerName(), null, "text/plain", he); return; } catch (final Throwable t) { log.info("Internal Server error : ", t); final Throwable rootCause = ExceptionUtils.getRootCause(t); NetUtils.httpReply (key, 500, rootCause.toString()+" : "+rootCause.getMessage(), this.service.getServerName(), null, "text/plain", t); return; } NetUtils.httpReply (key, 400, "Bad Request", this.service.getServerName(), null, "text/plain", "Action '"+action+"' has no implementation."); } /** * This method simply updates the lastUsed field. */ public void touch () { this.lastUsed = System.currentTimeMillis(); } protected void reply (final SelectionKey key, final org.jdom.Element elt) { NetUtils.httpReply (key, 200, "OK", this.service.getServerName(), null, "text/xml", elt); //log.debug("reply() :\n"+elt); } // // STATIC METHODS public static String printSessions (final java.util.Map sessions) { StringBuffer sb = new StringBuffer(); sb.append("\n[\n "); java.util.Iterator it = sessions.keySet().iterator(); while (it.hasNext()) { Long sessionId = (Long)it.next(); RestSession session = (RestSession)sessions.get(sessionId); sb.append(" "); sb.append(sessionId); sb.append(" : "); sb.append(new java.util.Date(session.getLastUsed())); if (it.hasNext()) { sb.append(",\n"); } } sb.append("\n]\n"); return sb.toString(); } private static String determineEncoding (String request) throws OpenWfeException { int i = request.indexOf("\r\n\r\n"); if (i < 0) throw new OpenWfeException("Double EOL not found."); request = request.substring(i+4); i = request.indexOf("encoding=\""); if (i < 1) return Utils.getEncoding(); // returns OpenWFE defined encoding request = request.substring(i+10); i = request.indexOf("\""); return request.substring(0, i); } public static org.jdom.Element parseBody (final SelectionKey key, final byte[] request) throws Exception { // debug //Utils.dump("rest_", request); final String encoding = determineEncoding(new String(request)); log.debug("parseBody() encoding is >"+encoding+"<"); String sRequest = new String(request, encoding); // remove header int i = sRequest.indexOf("\r\n\r\n"); if (i < 0) throw new OpenWfeException("Double EOL not found."); sRequest = sRequest.substring(i+4); // debug //Utils.dump("rest_2_", sRequest.getBytes("iso-8859-1")); // remove noise i = sRequest.lastIndexOf(">"); sRequest = sRequest.substring(0, i+1) + "\n"; //log.debug("parseBody() after : \n"+sRequest); java.io.InputStream is = new java.io.ByteArrayInputStream (sRequest.getBytes(encoding)); org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(); org.jdom.Document doc = builder.build(is); return doc.getRootElement(); } /** * This method is used to turn a simple exception into an HttpError, * very useful in final implementations of this class. */ public static void rethrowAsHttpException (final int httpErrorCode, final Exception e) throws HttpException { throw new HttpException(httpErrorCode, e.getMessage()); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -