00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030 package org.openmobileis.embedded.webserver;
00031
00032 import java.io.BufferedOutputStream;
00033 import java.io.BufferedReader;
00034 import java.io.ByteArrayOutputStream;
00035 import java.io.File;
00036 import java.io.FileOutputStream;
00037 import java.io.IOException;
00038 import java.io.InputStreamReader;
00039 import java.io.OutputStream;
00040 import java.io.OutputStreamWriter;
00041 import java.io.PrintWriter;
00042 import java.io.UnsupportedEncodingException;
00043 import java.net.InetAddress;
00044 import java.net.Socket;
00045 import java.security.Principal;
00046 import java.text.SimpleDateFormat;
00047 import java.util.Date;
00048 import java.util.Enumeration;
00049 import java.util.Hashtable;
00050 import java.util.Locale;
00051 import java.util.StringTokenizer;
00052 import java.util.Vector;
00053
00054 import javax.servlet.RequestDispatcher;
00055 import javax.servlet.ServletException;
00056 import javax.servlet.ServletInputStream;
00057 import javax.servlet.ServletOutputStream;
00058 import javax.servlet.ServletRequest;
00059 import javax.servlet.ServletResponse;
00060 import javax.servlet.SingleThreadModel;
00061 import javax.servlet.http.Cookie;
00062 import javax.servlet.http.HttpServlet;
00063 import javax.servlet.http.HttpServletRequest;
00064 import javax.servlet.http.HttpServletResponse;
00065 import javax.servlet.http.HttpSession;
00066
00067
00068 import org.apache.commons.fileupload.MultipartStream;
00069 import org.openmobileis.common.context.SessionContext;
00070 import org.openmobileis.common.context.SessionContextManager;
00071 import org.openmobileis.common.util.log.LogManager;
00072 import org.openmobileis.common.util.log.LogServices;
00073
00074 public class WebServerConnection implements HttpServletRequest, HttpServletResponse {
00075
00076 public final static String WWWFORMURLENCODE = "application/x-www-form-urlencoded";
00077 public final static String WWWMULTIPARTURLENCODE = "multipart/form-data";
00078 public final static String TRANSFERENCODING = "Transfer-Encoding";
00079 public final static String CHUNKED = "chunked";
00080 public final static String CONTENTLENGTH = "Content-Length";
00081 public final static String CONTENTTYPE = "Content-Type";
00082
00083 private Socket socket;
00084 private WebServer webserver;
00085
00086 private String reqMethod;
00087
00088 private String reqUriPath;
00089
00090 private boolean oneOne;
00091
00092 String reqQuery = null;
00093
00094 private Vector reqHeaderNames = new Vector();
00095 private Vector reqHeaderValues = new Vector();
00096 private Locale locale;
00097
00098 private int uriLen;
00099 private static final Hashtable EMPTYHASHTABLE = new Hashtable(10);
00100
00101 protected long connexionLifeTime = 0;
00102
00103 private ServletInputStream in;
00104
00105 private ServletOutputStream out;
00106
00107 private boolean reqMime;
00108
00109 private String reqProtocol;
00110 private String reqCharEncoding;
00111
00112 private Hashtable formParameters = new Hashtable(10);
00113
00114 private Hashtable attributes = new Hashtable(10);
00115
00116 private int resCode = -1;
00117
00118 private String resMessage = null;
00119
00120 private Hashtable resHeaderNames = new Hashtable(10);
00121
00122 private boolean headersWritten = false;
00123
00124 protected static final SimpleDateFormat expdatefmt = new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss 'GMT'");
00125
00126 protected static final SimpleDateFormat headerdateformat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
00127
00128 private PrintWriter printWriter = null;
00129
00130 private String defaultCharacterEncoding;
00131
00132 private boolean hasUrlDecoder = true;
00133
00134 public WebServerConnection() {
00135 super();
00136 }
00137
00138 public void init(WebServer webserver, Socket socket) {
00139
00140 this.webserver = webserver;
00141 this.socket = socket;
00142 out = null;
00143 in = null;
00144 oneOne = false;
00145 reqMethod = null;
00146 reqUriPath = null;
00147 reqQuery = null;
00148 reqProtocol = null;
00149 reqCharEncoding = null;
00150 reqHeaderNames = new Vector();
00151 reqHeaderValues = new Vector();
00152 formParameters = null;
00153 attributes = new Hashtable();
00154 locale = null;
00155 uriLen = -1;
00156 resCode = -1;
00157 connexionLifeTime = 0;
00158 reqMime = false;
00159 resMessage = "";
00160 resHeaderNames = new Hashtable();
00161 headersWritten = false;
00162 printWriter = null;
00163 this.defaultCharacterEncoding = System.getProperty("file.encoding");
00164 try {
00165 String test = java.net.URLDecoder.decode("", "UTF-8");
00166 } catch (Throwable ex){
00167 hasUrlDecoder = false;
00168 }
00169
00170 }
00171
00172
00173 public void run() {
00174 SessionContextManager.getManager().joinSessionContext("OPENMOBILEISSESSION");
00175 try {
00176
00177 in = new ServeInputStream(socket.getInputStream());
00178 out = new ServeOutputStream(socket.getOutputStream(), this);
00179 } catch (IOException e) {
00180 problem("Getting streams: " + e.getMessage(), SC_BAD_REQUEST);
00181 LogManager.traceError(0, e.toString());
00182 try {
00183 socket.close();
00184 } catch (Exception ex) {
00185 }
00186 return;
00187 }
00188
00189
00190 parseRequest();
00191
00192
00193
00194
00195
00196
00197
00198
00199
00200 try {
00201 this.execURI(this.reqUriPath);
00202 } catch (Exception e) {
00203 problem("Getting streams: " + e.getMessage(), SC_BAD_REQUEST);
00204 LogManager.traceError(0, e);
00205 } finally {
00206 try {
00207
00208 socket.close();
00209 } catch (IOException e) {
00210 org.openmobileis.common.util.log.LogManager.traceError(org.openmobileis.common.util.log.LogServices.WEBSERVICE,
00211 "Impossible to close socket : WebServerConnection");
00212 org.openmobileis.common.util.log.LogManager.traceError(org.openmobileis.common.util.log.LogServices.WEBSERVICE, e);
00213 }
00214 }
00215 }
00216
00217 private void parseRequest() {
00218 byte[] lineBytes = new byte[4096];
00219 int len;
00220 String line;
00221
00222 try {
00223
00224
00225 len = in.readLine(lineBytes, 0, lineBytes.length);
00226 if (len == -1 || len == 0) {
00227 problem("Empty request", SC_BAD_REQUEST);
00228 return;
00229 }
00230 line = new String(lineBytes, 0, len);
00231 StringTokenizer ust = new StringTokenizer(line);
00232 reqProtocol = null;
00233 if (ust.hasMoreTokens()) {
00234 reqMethod = ust.nextToken();
00235 if (ust.hasMoreTokens()) {
00236 reqUriPath = ust.nextToken();
00237 if (ust.hasMoreTokens()) {
00238 reqProtocol = ust.nextToken();
00239 oneOne = !reqProtocol.toUpperCase().equals("HTTP/1.0");
00240 reqMime = true;
00241
00242 String s;
00243 while ((s = ((ServeInputStream) in).readLine()) != null) {
00244 if (s.length() == 0)
00245 break;
00246
00247 int c = s.indexOf(':', 0);
00248 if (c > 0) {
00249 String key = s.substring(0, c).trim();
00250 String value = s.substring(c + 1, s.length()).trim();
00251 reqHeaderNames.addElement(key.toLowerCase());
00252 reqHeaderValues.addElement(value);
00253 } else {
00254 LogManager.traceError(LogServices.WEBSERVICE, "header field without ':'");
00255 }
00256 }
00257 } else {
00258 reqProtocol = "HTTP/0.9";
00259 oneOne = false;
00260 reqMime = false;
00261 }
00262 }
00263 }
00264 if (reqProtocol == null) {
00265 problem("Malformed request line", SC_BAD_REQUEST);
00266 return;
00267 }
00268
00269 if (oneOne) {
00270 String host = getHeader("host");
00271 if (host == null) {
00272 problem("Host header missing on HTTP/1.1 request", SC_BAD_REQUEST);
00273 return;
00274 }
00275 }
00276
00277
00278
00279
00280 int qmark = reqUriPath.indexOf('?');
00281 if (qmark > -1) {
00282 reqQuery = reqUriPath.substring(qmark + 1);
00283 reqUriPath = reqUriPath.substring(0, qmark);
00284 }
00285 if (CHUNKED.equals(getHeader(TRANSFERENCODING))) {
00286 setHeader(CONTENTLENGTH, null);
00287 ((ServeInputStream) in).chunking(true);
00288 }
00289
00290 } catch (IOException e) {
00291 problem("Reading request: " + e.getMessage(), SC_BAD_REQUEST);
00292 }
00293 }
00294
00295 private void execURI(String URI) throws ServletException {
00296
00297 if (URI.equals("/index")) {
00298 URI = "/services/index";
00299 reqUriPath = URI;
00300 }
00301 Object[] os = webserver.getServletByURLorClassName(URI);
00302 if (os[0] == null) {
00303 os = webserver.getServletByURLorClassName("defaultServlet");
00304 if (os[0] == null) {
00305 throw new ServletException("WebServerConnection::execUri Unable to find file servlet");
00306 }
00307
00308 uriLen = 0;
00309 runServlet((HttpServlet) os[0]);
00310 } else {
00311 uriLen = ((Integer) os[1]).intValue();
00312 runServlet((HttpServlet) os[0]);
00313 }
00314 }
00315
00316
00317
00318
00319 void writeHeaders() throws IOException {
00320 synchronized (this) {
00321 if (headersWritten)
00322 return;
00323
00324 headersWritten = true;
00325 }
00326 if (reqMime) {
00327
00328 out.println(reqProtocol + " " + resCode + " " + resMessage);
00329
00330 Enumeration he = resHeaderNames.keys();
00331 while (he.hasMoreElements()) {
00332 String name = (String) he.nextElement();
00333 Object o = resHeaderNames.get(name);
00334 if (o instanceof String) {
00335 String value = (String) o;
00336 if (value != null)
00337 out.println(name + ": " + value);
00338
00339
00340
00341
00342 } else if (o instanceof String[]) {
00343 String[] values = (String[]) o;
00344 out.println(name + ": " + values[0]);
00345 for (int i = 0; i < values.length; i++)
00346 out.print("," + values[i]);
00347 out.println();
00348 }
00349 }
00350
00351
00352
00353
00354 out.println("Pragma: no-cache");
00355 out.println("Cache-Control: no-cache, must-revalidate");
00356 out.println("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
00357 out.println("Date: Mon, 26 Jul 1997 05:00:00 GMT");
00358
00359 out.println("Last-Modified: Mon, 26 Jul 1997 05:00:00 GMT");
00360 out.println("Connection: close");
00361
00362 out.println();
00363 out.flush();
00364
00365 }
00366 }
00367
00368 private void runServlet(HttpServlet servlete) {
00369
00370 setStatus(SC_OK);
00371
00372
00373
00374
00375
00376 try {
00377 authenticate();
00378 ((SessionContext) this.getSession()).setServletContext(servlete.getServletConfig().getServletContext());
00379 if (servlete instanceof SingleThreadModel)
00380 synchronized (servlete) {
00381 servlete.service((ServletRequest) this, (ServletResponse) this);
00382 }
00383 else {
00384 servlete.service((ServletRequest) this, (ServletResponse) this);
00385 }
00386 if (((ServeOutputStream) out).isReturnedAsWriter() && printWriter != null) {
00387 printWriter.flush();
00388 } else {
00389 out.flush();
00390 }
00391 } catch (IOException e) {
00392 e.printStackTrace();
00393 problem("IO problem running servlet: " + e.toString(), SC_BAD_REQUEST);
00394 } catch (ServletException e) {
00395 e.printStackTrace();
00396 problem("problem running servlet: " + e.toString(), SC_BAD_REQUEST);
00397 } catch (Exception e) {
00398 e.printStackTrace();
00399 problem("unexpected problem running servlet: " + e.toString(), SC_INTERNAL_SERVER_ERROR);
00400 }
00401 }
00402
00403 private boolean authenticate() throws IOException {
00404
00405 return true;
00406 }
00407
00408
00409 private void problem(String logMessage, int resCode) {
00410 LogManager.traceError(LogServices.WEBSERVICE, logMessage);
00411 try {
00412 sendError(resCode);
00413 } catch (IllegalStateException e) {
00414 } catch (IOException e) {
00415 }
00416 }
00417
00425 private Hashtable parseQueryString(String queryString) throws UnsupportedEncodingException {
00426 Hashtable map = new Hashtable();
00427
00428 StringTokenizer token = new StringTokenizer(queryString, "&");
00429 while (token.hasMoreTokens()) {
00430 String tok = token.nextToken();
00431 int index = tok.indexOf('=');
00432 if (index == -1) {
00433
00434 continue;
00435 }
00436 String key = Acme.Utils.urlDecoder(tok.substring(0, index));
00437 String value = null;
00438 if(hasUrlDecoder) {
00439 String encoding = this.defaultCharacterEncoding;
00440 if (encoding == null) encoding = "UTF-8";
00441 String valueToDecode = tok.substring(index + 1, tok.length());
00442 value = java.net.URLDecoder.decode(valueToDecode, encoding);
00443
00444 if (this.detectBadURLDecoding(value)) {
00445 if ( encoding.equals("UTF-8")) value = java.net.URLDecoder.decode(valueToDecode, "ISO-8859-1");
00446 else value = java.net.URLDecoder.decode(valueToDecode, "UTF-8");
00447 }
00448 } else {
00449 value = Acme.Utils.urlDecoder(tok.substring(index + 1, tok.length()));
00450 }
00451
00452 if (map.containsKey(key)) {
00453 String[] oldValue = (String[]) map.get(key);
00454 String[] newValue = new String[oldValue.length + 1];
00455 System.arraycopy(oldValue, 0, newValue, 0, oldValue.length);
00456 newValue[oldValue.length] = value;
00457 map.put(key, newValue);
00458 } else {
00459 map.put(key, new String[] { value });
00460 }
00461 }
00462
00463 return map;
00464 }
00465
00466 private boolean detectBadURLDecoding(String value) {
00467 char[] buff = value.toCharArray();
00468 for (int i=0; i<buff.length; i++) {
00469 if (((int)buff[i]) == 65533) {
00470 return true;
00471 }
00472 }
00473 return false;
00474 }
00475
00476 private Hashtable getParametersFromRequest() {
00477 Hashtable result = null;
00478
00479
00480 if ("GET".equals(reqMethod)) {
00481 if (reqQuery != null)
00482 try {
00483 result = this.parseQueryString(reqQuery);
00484 } catch (Exception ex) {
00485 LogManager.traceError(LogServices.WEBSERVICE, "Exception " + ex.toString() + " Error parsing query strind");
00486 }
00487 } else if ("POST".equals(reqMethod)) {
00488 if (WWWFORMURLENCODE.equals(getContentType())) {
00489 try {
00490
00491 result = this.parsePostData(getContentLength(), getInputStream(), null);
00492
00493 if (reqQuery != null && reqQuery.length() > 0) {
00494 Acme.Utils.putAll(result, parseQueryString(reqQuery));
00495 }
00496 } catch (Exception ex) {
00497 LogManager.traceError(LogServices.WEBSERVICE, "Exception " + ex.toString() + " at parsing post data of length " + getContentLength());
00498 }
00499 } else if (this.getContentType().startsWith(WWWMULTIPARTURLENCODE)) {
00500
00501 String contentType = this.getContentType();
00502 int boundaryIndex = contentType.indexOf("boundary=");
00503 if (boundaryIndex > 0) {
00504 try {
00505 result = new Hashtable();
00506 byte[] boundary = contentType.substring(boundaryIndex + 9).getBytes();
00507 MultipartStream multi = new MultipartStream(getInputStream(), boundary);
00508
00509 boolean nextPart = multi.skipPreamble();
00510 while (nextPart) {
00511 String header = multi.readHeaders();
00512
00513
00514 int index = header.indexOf("form-data;");
00515 String paramName = null;
00516 String fileName = null;
00517 if (index > 0) {
00518 header = header.substring(index + 10, header.length());
00519 index = header.indexOf("name=");
00520 if (index > 0) {
00521 header = header.substring(index + 6, header.length());
00522 index = header.indexOf('"');
00523 if (index > 0) {
00524 paramName = header.substring(0, index);
00525 }
00526 index = header.indexOf("filename=");
00527 if (index > 0) {
00528 header = header.substring(index + 10, header.length());
00529 index = header.indexOf('"');
00530 if (index > 0) {
00531 fileName = header.substring(0, index);
00532
00533 }
00534 }
00535 }
00536 }
00537
00538 OutputStream out = null;
00539 if (fileName != null) {
00540 String path = System.getProperty("user.dir") + File.separator + "temp";
00541 File dirtmp = new File(path);
00542 if (!dirtmp.exists())
00543 dirtmp.mkdirs();
00544 fileName = path + File.separator + fileName;
00545 out = new BufferedOutputStream(new FileOutputStream(fileName));
00546 } else {
00547 out = new ByteArrayOutputStream();
00548 }
00549
00550 multi.readBodyData(out);
00551 out.flush();
00552 out.close();
00553 if (fileName != null && paramName != null) {
00554 result.put(paramName, new String[] { fileName });
00555 } else if (paramName != null) {
00556
00557 result.put(paramName, new String[] { out.toString() });
00558 }
00559 nextPart = multi.readBoundary();
00560 }
00561
00562 } catch (Throwable ex) {
00563 LogManager.traceError(LogServices.WEBSERVICE, "Exception " + ex.toString() + " Error parsing multipart query strind");
00564 }
00565 }
00566 }
00567 } else {
00568 try {
00569 if (reqQuery != null)
00570 result = parseQueryString(reqQuery);
00571 } catch (Exception ex) {
00572 LogManager.traceError(LogServices.WEBSERVICE, "Exception " + ex.toString() + " Error parsing query strind");
00573 }
00574 }
00575 return result != null ? result : EMPTYHASHTABLE;
00576 }
00577
00578 private Hashtable parsePostData(int len, ServletInputStream in, String encoding) {
00579 if (len <= 0)
00580 return new Hashtable();
00581
00582
00583
00584 byte[] postedBytes = new byte[len];
00585 try {
00586 int offset = 0;
00587 do {
00588 int inputLen = in.read(postedBytes, offset, len - offset);
00589 if (inputLen <= 0) {
00590 throw new IllegalArgumentException("Error during servlet input stream read");
00591 }
00592 offset += inputLen;
00593 } while ((len - offset) > 0);
00594
00595 } catch (IOException e) {
00596 throw new IllegalArgumentException(e.getMessage());
00597 }
00598
00599
00600
00601
00602
00603
00604 try {
00605 String postedBody = new String(postedBytes, 0, len);
00606 return parseQueryString(postedBody);
00607 } catch (java.io.UnsupportedEncodingException e) {
00608
00609
00610 throw new IllegalArgumentException(e.getMessage());
00611 }
00612 }
00613
00614 private void realSendError() throws IOException {
00615 if (isCommitted())
00616 throw new IllegalStateException("Can not send error, headers have been already written");
00617 synchronized (out) {
00618
00619 ((ServeOutputStream) out).setReturnedAsStream(true);
00620 ((ServeOutputStream) out).setReturnedAsWriter(true);
00621 }
00622 setContentType("text/html");
00623 StringBuffer sb = new StringBuffer(100);
00624 sb.append("<HTML><HEAD>").append("<TITLE>" + resCode + " " + resMessage + "</TITLE>").append("</HEAD><BODY BGCOLOR=\"#F1D0F2\">").append(
00625 "<H2>" + resCode + " " + resMessage + "</H2>").append("<HR>");
00626 Identification.writeAddress(sb);
00627 sb.append("</BODY></HTML>");
00628 setContentLength(sb.length());
00629 out.print(sb.toString());
00630 out.flush();
00631 }
00632
00633
00634
00635
00636
00637
00638
00639 public Object getAttribute(String name) {
00640 return attributes.get(name);
00641 }
00642
00643
00644 public Enumeration getAttributeNames() {
00645 return attributes.keys();
00646 }
00647
00648 public String getAuthType() {
00649
00650 return null;
00651 }
00652
00653
00654
00655 public int getContentLength() {
00656 try {
00657 return this.getIntHeader(CONTENTLENGTH);
00658 } catch (Exception ex) {
00659 return -1;
00660 }
00661 }
00662
00663
00664
00665
00666 public String getContentType() {
00667 return getHeader(CONTENTTYPE);
00668 }
00669
00670 public String getContextPath() {
00671 return "";
00672 }
00673
00674 public Cookie[] getCookies() {
00675
00676 return null;
00677 }
00678
00679 public long getDateHeader(String name) {
00680 String val = getHeader(name);
00681 if (val == null)
00682 return 0;
00683 try {
00684 return headerdateformat.parse(val).getTime();
00685 } catch (Exception e) {
00686 throw new IllegalArgumentException("Value " + val + " can't be converted to Date using " + headerdateformat.toPattern());
00687 }
00688 }
00689
00690 public String getHeader(String name) {
00691 int i = reqHeaderNames.indexOf(name.toLowerCase());
00692 if (i == -1)
00693 return null;
00694 return (String) reqHeaderValues.elementAt(i);
00695 }
00696
00697 public Enumeration getHeaderNames() {
00698 return reqHeaderNames.elements();
00699 }
00700
00701 public Enumeration getHeaders(String header) {
00702 Vector result = new Vector();
00703 int i = -1;
00704 while ((i = reqHeaderNames.indexOf(header.toLowerCase(), i + 1)) >= 0)
00705 result.addElement(reqHeaderValues.elementAt(i));
00706 return result.elements();
00707 }
00708
00709
00710
00711
00712 public ServletInputStream getInputStream() throws IOException {
00713 synchronized (in) {
00714 if (((ServeInputStream) in).isReturnedAsReader())
00715 throw new IllegalStateException("Already returned as a reader.");
00716 ((ServeInputStream) in).setReturnedAsReader(true);
00717 }
00718 return in;
00719 }
00720
00721
00722
00723 public int getIntHeader(String name) {
00724 String val = getHeader(name);
00725 if (val == null)
00726 return -1;
00727
00728
00729
00730
00731 return Integer.parseInt(val);
00732 }
00733
00744 public String getLocalAddr() {
00745 return null;
00746 }
00747
00748
00749 public Enumeration getLocales() {
00750
00751
00752 return null;
00753 }
00754
00764 public String getLocalName() {
00765 return null;
00766 }
00767
00776 public int getLocalPort() {
00777 return webserver.port;
00778 }
00779
00780 public String getMethod() {
00781 return reqMethod;
00782 }
00783
00784
00785
00786
00787 public String getParameter(String name) {
00788 String[] params = getParameterValues(name);
00789 if (params == null || params.length == 0)
00790 return null;
00791
00792 return params[0];
00793 }
00794
00806 public java.util.Map getParameterMap() {
00807 return (java.util.Map) formParameters;
00808 }
00809
00810
00811 public Enumeration getParameterNames() {
00812 if (formParameters == null)
00813 formParameters = getParametersFromRequest();
00814 return formParameters.keys();
00815 }
00816
00817
00818
00819 public String[] getParameterValues(String name) {
00820 if (formParameters == null)
00821 getParameterNames();
00822
00823 return (String[]) formParameters.get(name);
00824 }
00825
00826 public String getPathInfo() {
00827
00828
00829
00830 return uriLen >= reqUriPath.length() ? null : reqUriPath.substring(uriLen);
00831 }
00832
00833 public String getPathTranslated() {
00834
00835
00836
00837 return getRealPath(getPathInfo());
00838 }
00839
00840
00841
00842
00843 public String getProtocol() {
00844 return reqProtocol;
00845 }
00846
00847
00848
00849 public String getQueryString() {
00850 return reqQuery;
00851 }
00852
00853
00854
00855
00856
00857
00858 public BufferedReader getReader() throws IOException {
00859 synchronized (in) {
00860 if (((ServeInputStream) in).isReturnedAsStream())
00861 throw new IllegalStateException("Already returned as a stream.");
00862 ((ServeInputStream) in).setReturnedAsStream(true);
00863 }
00864 if (reqCharEncoding != null)
00865 try {
00866 return new BufferedReader(new InputStreamReader(in, reqCharEncoding));
00867 } catch (UnsupportedEncodingException uee) {
00868 }
00869 return new BufferedReader(new InputStreamReader(in));
00870 }
00871
00872
00873
00874
00875
00876
00877
00878 public String getRealPath(String path) {
00879 return webserver.getRealPath(path);
00880 }
00881
00882
00883
00884 public String getRemoteAddr() {
00885 return socket.getInetAddress().getHostAddress().toString();
00886 }
00887
00888
00889
00890
00891 public String getRemoteHost() {
00892 String result = socket.getInetAddress().getHostName();
00893 return result != null ? result : getRemoteAddr();
00894 }
00895
00904 public int getRemotePort() {
00905
00906 return webserver.port;
00907 }
00908
00909
00910
00911 public String getRemoteUser() {
00912
00913 return null;
00914 }
00915
00916 public RequestDispatcher getRequestDispatcher(String urlpath) {
00917
00918 return null;
00919 }
00920
00921 public String getRequestedSessionId() {
00922
00923 return this.getSession().getId();
00924 }
00925
00926 public String getRequestURI() {
00927 return reqUriPath;
00928 }
00929
00930 public void setRequestURI(String uri) {
00931 reqUriPath = uri;
00932 }
00933
00934 public StringBuffer getRequestURL() {
00935 return new StringBuffer().append(getScheme()).append("://").append(this.getServerName()).append(
00936 webserver.port == 80 ? "" : ":" + String.valueOf(webserver.port)).append(getRequestURI());
00937 }
00938
00939
00940
00941
00942
00943
00944 public String getScheme() {
00945 if (socket.getClass().getName().toUpperCase().indexOf("SSL") < 0)
00946 return "http";
00947 else
00948 return "https";
00949 }
00950
00951
00952
00953
00954 public String getServerName() {
00955 String serverName;
00956 serverName = getHeader("Host");
00957 if (serverName != null && serverName.length() > 0) {
00958 int colon = serverName.indexOf(':');
00959 if (colon >= 0) {
00960 if (colon < serverName.length())
00961 serverName = serverName.substring(0, colon);
00962 }
00963 }
00964
00965 if (serverName == null) {
00966 try {
00967 serverName = InetAddress.getLocalHost().getHostName();
00968 } catch (java.net.UnknownHostException ignore) {
00969 serverName = "127.0.0.0";
00970 }
00971 }
00972
00973 int slash = serverName.indexOf("/");
00974 if (slash >= 0)
00975 serverName = serverName.substring(slash + 1);
00976 return serverName;
00977 }
00978
00979
00980
00981
00982 public int getServerPort() {
00983 return socket.getLocalPort();
00984 }
00985
00986 public String getServletPath() {
00987
00988
00989
00990 return uriLen > 0 ? reqUriPath.substring(0, uriLen) : "";
00991 }
00992
00993 public HttpSession getSession() {
00994 return this.getSession(true);
00995 }
00996
00997 public HttpSession getSession(boolean create) {
00998
00999 SessionContext session = SessionContextManager.getManager().getSessionContext("OPENMOBILEISSESSION");
01000 if (session == null) {
01001 synchronized (SessionContextManager.getManager()) {
01002 session = SessionContextManager.getManager().getSessionContext("OPENMOBILEISSESSION");
01003 if (session == null) {
01004 session = SessionContextManager.getManager().createSessionContext("OPENMOBILEISSESSION");
01005 }
01006 }
01007 }
01008 SessionContextManager.getManager().joinSessionContext(session.getId());
01009 return SessionContextManager.getManager().getSessionContext();
01010 }
01011
01012 public Principal getUserPrincipal() {
01013
01014 return null;
01015 }
01016
01017 public boolean isRequestedSessionIdFromCookie() {
01018
01019 return false;
01020 }
01021
01022 public boolean isRequestedSessionIdFromURL() {
01023
01024 return false;
01025 }
01026
01027 public boolean isRequestedSessionIdFromUrl() {
01028
01029 return false;
01030 }
01031
01032 public boolean isRequestedSessionIdValid() {
01033 HttpSession session = this.getSession();
01034 if (session != null) {
01035 return true;
01036 }
01037 return false;
01038 }
01039
01040 public boolean isSecure() {
01041 return false;
01042 }
01043
01044 public boolean isUserInRole(String arg0) {
01045
01046 return false;
01047 }
01048
01049 public void removeAttribute(String name) {
01050 attributes.remove(name);
01051 }
01052
01053 public void setAttribute(String key, Object o) {
01054 attributes.put(key, o);
01055 }
01056
01068 public void setCharacterEncoding(String _enc) {
01069 this.reqCharEncoding = _enc;
01070 }
01071
01072
01073
01074
01075
01076
01077
01078
01079 public String getCharacterEncoding() {
01080 String ct = (String) resHeaderNames.get(CONTENTTYPE);
01081 if (ct != null) {
01082 int scp = ct.indexOf(';');
01083 if (scp > 0) {
01084 scp = ct.toLowerCase().indexOf("charset=", scp);
01085 if (scp >= 0) {
01086 ct = ct.substring(scp + 8);
01087 scp = ct.indexOf(' ');
01088 if (scp > 0)
01089 ct = ct.substring(0, scp);
01090 scp = ct.indexOf(';');
01091 if (scp > 0)
01092 ct = ct.substring(0, scp);
01093 return ct;
01094 }
01095 }
01096 }
01097 return null;
01098 }
01099
01100 public Locale getLocale() {
01101 return locale;
01102 }
01103
01104
01105
01106
01107
01108
01109 public void addCookie(Cookie cookie) {
01110
01111 }
01112
01113 public void addDateHeader(String header, long date) {
01114 addHeader(header, expdatefmt.format(new Date(date)));
01115 }
01116
01117 public void addHeader(String header, String value) {
01118 Object o = resHeaderNames.get(header);
01119 if (o == null)
01120 setHeader(header, value);
01121 else {
01122 if (o instanceof String[]) {
01123 String[] oldVal = (String[]) o;
01124 String[] newVal = new String[oldVal.length + 1];
01125 System.arraycopy(oldVal, 0, newVal, 0, oldVal.length);
01126 newVal[oldVal.length] = value;
01127 resHeaderNames.put(header, newVal);
01128 } else if (o instanceof String) {
01129 String[] newVal = new String[2];
01130 newVal[0] = (String) o;
01131 newVal[1] = value;
01132 resHeaderNames.put(header, newVal);
01133 } else
01134 throw new RuntimeException("Invalid content of header hash - " + o.getClass().getName());
01135 }
01136 }
01137
01138 public void addIntHeader(String header, int value) {
01139 addHeader(header, Integer.toString(value));
01140 }
01141
01142
01143
01144 public boolean containsHeader(String name) {
01145 return resHeaderNames.contains(name);
01146 }
01147
01148
01149
01150
01151
01152
01153
01154
01155
01156
01157
01158
01159 public String encodeRedirectUrl(String url) {
01160 return url;
01161 }
01162
01163 public String encodeRedirectURL(String url) {
01164 return url;
01165 }
01166
01167
01168
01169
01170
01171
01172
01173
01174
01175
01176
01177
01178
01179
01180 public String encodeUrl(String url) {
01181 return url;
01182 }
01183
01184
01185 public String encodeURL(String url) {
01186 return url;
01187 }
01188
01189
01190
01191 public void flushBuffer() {
01192 }
01193
01194 public int getBufferSize() {
01195 return 0;
01196 }
01197
01198
01199 public ServletOutputStream getOutputStream() throws IOException {
01200 synchronized (out) {
01201 if (((ServeOutputStream) out).isReturnedAsWriter())
01202 throw new IllegalStateException("Already returned as a writer");
01203 ((ServeOutputStream) out).setReturnedAsStream(true);
01204 }
01205 return out;
01206 }
01207
01208
01209
01210
01211
01212
01213
01214
01215 public PrintWriter getWriter() throws IOException {
01216 synchronized (out) {
01217 if (((ServeOutputStream) out).isReturnedAsStream())
01218 throw new IllegalStateException("Already was returned as servlet output stream");
01219 ((ServeOutputStream) out).setReturnedAsWriter(true);
01220 }
01221 String encoding = getCharacterEncoding();
01222 if (encoding != null) {
01223
01224 printWriter = new PrintWriter(new OutputStreamWriter(out, encoding));
01225 } else {
01226
01227 printWriter = new PrintWriter(out);
01228 }
01229 return printWriter;
01230 }
01231
01239
01240 public boolean isCommitted() {
01241 return headersWritten;
01242 }
01243
01253 public void reset() {
01254 if (!isCommitted()) {
01255 resHeaderNames.clear();
01256 } else
01257 throw new IllegalStateException("Header have already been committed.");
01258 }
01259
01260 public void resetBuffer() {
01261 throw new IllegalStateException("The method not implemented");
01262 }
01263
01264
01265
01266
01267
01268 public void sendError(int resCode, String resMessage) throws IOException {
01269 setStatus(resCode, resMessage);
01270 realSendError();
01271 }
01272
01273
01274
01275
01276
01277 public void sendError(int resCode) throws IOException {
01278 setStatus(resCode);
01279 realSendError();
01280 }
01281
01282
01283
01284
01285
01286 public void sendRedirect(String location) throws IOException {
01287 if (isCommitted())
01288 throw new IllegalStateException("Can not redirect, headers have been already written");
01289 synchronized (out) {
01290
01291 ((ServeOutputStream) out).setReturnedAsStream(true);
01292 ((ServeOutputStream) out).setReturnedAsWriter(true);
01293 }
01294 setHeader("Location", location);
01295 setStatus(SC_MOVED_TEMPORARILY);
01296 setContentType("text/html");
01297 StringBuffer sb = new StringBuffer(200);
01298 sb.append("<HTML><HEAD>" + "<TITLE>" + SC_MOVED_TEMPORARILY + " Moved</TITLE>" + "</HEAD><BODY BGCOLOR=\"#F1D0F2\">" + "<H2>" + SC_MOVED_TEMPORARILY
01299 + " Moved</H2>" + "This document has moved <a href=" + location + ">here.<HR>");
01300 Identification.writeAddress(sb);
01301 sb.append("</BODY></HTML>");
01302 setContentLength(sb.length());
01303
01304 out.print(sb.toString());
01305 out.flush();
01306 }
01307
01308
01309
01310 public void setBufferSize(int size) {
01311 }
01312
01313
01314
01315 public void setContentLength(int length) {
01316 setIntHeader(CONTENTLENGTH, length);
01317 }
01318
01319
01320
01321 public void setContentType(String type) {
01322 setHeader(CONTENTTYPE, type != null ? type : "Unknown");
01323 }
01324
01325
01326
01327
01328 public void setDateHeader(String name, long value) {
01329 setHeader(name, expdatefmt.format(new Date(value)));
01330 }
01331
01332
01333
01334
01335 public void setHeader(String name, String value) {
01336 resHeaderNames.put(name, value);
01337 }
01338
01339
01340
01341
01342 public void setIntHeader(String name, int value) {
01343 setHeader(name, Integer.toString(value));
01344 }
01345
01356 public void setLocale(Locale locale) {
01357 this.locale = locale;
01358 }
01359
01360
01361
01362 public void setStatus(int resCode) {
01363 switch (resCode) {
01364 case SC_CONTINUE:
01365 setStatus(resCode, "Continue");
01366 break;
01367 case SC_SWITCHING_PROTOCOLS:
01368 setStatus(resCode, "Switching protocols");
01369 break;
01370 case SC_OK:
01371 setStatus(resCode, "Ok");
01372 break;
01373 case SC_CREATED:
01374 setStatus(resCode, "Created");
01375 break;
01376 case SC_ACCEPTED:
01377 setStatus(resCode, "Accepted");
01378 break;
01379 case SC_NON_AUTHORITATIVE_INFORMATION:
01380 setStatus(resCode, "Non-authoritative");
01381 break;
01382 case SC_NO_CONTENT:
01383 setStatus(resCode, "No content");
01384 break;
01385 case SC_RESET_CONTENT:
01386 setStatus(resCode, "Reset content");
01387 break;
01388 case SC_PARTIAL_CONTENT:
01389 setStatus(resCode, "Partial content");
01390 break;
01391 case SC_MULTIPLE_CHOICES:
01392 setStatus(resCode, "Multiple choices");
01393 break;
01394 case SC_MOVED_PERMANENTLY:
01395 setStatus(resCode, "Moved permanentently");
01396 break;
01397 case SC_MOVED_TEMPORARILY:
01398 setStatus(resCode, "Moved temporarily");
01399 break;
01400 case SC_SEE_OTHER:
01401 setStatus(resCode, "See other");
01402 break;
01403 case SC_NOT_MODIFIED:
01404 setStatus(resCode, "Not modified");
01405 break;
01406 case SC_USE_PROXY:
01407 setStatus(resCode, "Use proxy");
01408 break;
01409 case SC_BAD_REQUEST:
01410 setStatus(resCode, "Bad request");
01411 break;
01412 case SC_UNAUTHORIZED:
01413 setStatus(resCode, "Unauthorized");
01414 break;
01415 case SC_PAYMENT_REQUIRED:
01416 setStatus(resCode, "Payment required");
01417 break;
01418 case SC_FORBIDDEN:
01419 setStatus(resCode, "Forbidden");
01420 break;
01421 case SC_NOT_FOUND:
01422 setStatus(resCode, "Not found");
01423 break;
01424 case SC_METHOD_NOT_ALLOWED:
01425 setStatus(resCode, "Method not allowed");
01426 break;
01427 case SC_NOT_ACCEPTABLE:
01428 setStatus(resCode, "Not acceptable");
01429 break;
01430 case SC_PROXY_AUTHENTICATION_REQUIRED:
01431 setStatus(resCode, "Proxy auth required");
01432 break;
01433 case SC_REQUEST_TIMEOUT:
01434 setStatus(resCode, "Request timeout");
01435 break;
01436 case SC_CONFLICT:
01437 setStatus(resCode, "Conflict");
01438 break;
01439 case SC_GONE:
01440 setStatus(resCode, "Gone");
01441 break;
01442 case SC_LENGTH_REQUIRED:
01443 setStatus(resCode, "Length required");
01444 break;
01445 case SC_PRECONDITION_FAILED:
01446 setStatus(resCode, "Precondition failed");
01447 break;
01448 case SC_REQUEST_ENTITY_TOO_LARGE:
01449 setStatus(resCode, "Request entity too large");
01450 break;
01451 case SC_REQUEST_URI_TOO_LONG:
01452 setStatus(resCode, "Request URI too large");
01453 break;
01454 case SC_UNSUPPORTED_MEDIA_TYPE:
01455 setStatus(resCode, "Unsupported media type");
01456 break;
01457 case SC_INTERNAL_SERVER_ERROR:
01458 setStatus(resCode, "Internal server error");
01459 break;
01460 case SC_NOT_IMPLEMENTED:
01461 setStatus(resCode, "Not implemented");
01462 break;
01463 case SC_BAD_GATEWAY:
01464 setStatus(resCode, "Bad gateway");
01465 break;
01466 case SC_SERVICE_UNAVAILABLE:
01467 setStatus(resCode, "Service unavailable");
01468 break;
01469 case SC_GATEWAY_TIMEOUT:
01470 setStatus(resCode, "Gateway timeout");
01471 break;
01472 case SC_HTTP_VERSION_NOT_SUPPORTED:
01473 setStatus(resCode, "HTTP version not supported");
01474 break;
01475 default:
01476 setStatus(resCode, "");
01477 break;
01478 }
01479 }
01480
01481
01482
01483
01484 public void setStatus(int resCode, String resMessage) {
01485
01486
01487
01488 this.resCode = resCode;
01489 this.resMessage = resMessage;
01490 }
01491
01492 }