1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.jot.web.server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.Socket; import java.security.Principal; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Enumeration; import java.util.Hashtable; import java.util.Locale; import java.util.Map; import java.util.Vector; import javax.servlet.RequestDispatcher; import javax.servlet.ServletInputStream; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import net.jot.logger.JOTLogger; import net.jot.logger.JOTLoggerLocation; import net.jot.utils.JOTTimezoneUtils; /** * HttpServletRequest impl. (not fully impl. yet) * Use JOTRequestParser to parse a socket input into a request. * @author thibautc */ public class JOTWebRequest implements HttpServletRequest { private static final DateFormat HEADER_FORMAT = new SimpleDateFormat(JOTTimezoneUtils.FORMAT_HEADER); private static final Enumeration EMPTY_ENUM = new Vector().elements(); Socket socket = null; private String method = "GET"; private String protocol = null; private String path; // requestLine as it came to us private String rawRequestLine; private String remoteHost = null; private int remotePort = -1; private String localHost = null; private int localPort = -1; /** headers (header name -> Vector of values(string)) **/ private Hashtable headers = new Hashtable(); // parameters (hash of Vector of strings) private Hashtable parameters = new Hashtable(); // vector of Cookie private Vector cookies = new Vector(); private String rawParams; private String sessionId; private String requestedSessionId; private String contextPath = ""; private Hashtable attributes = new Hashtable(); private String encoding = null; // TODO: basic authentication ? //String user; //String password; // body if any (ex: multipart) byte[] body; // local server name / host //those, lazy inited private String serverName = null; private StringBuffer url = new StringBuffer(); private String scheme = null; static final JOTLoggerLocation logger = new JOTLoggerLocation(JOTLogger.CAT_SERVER, JOTWebRequest.class); private boolean requestedSIDFromCookies = true; private ServletInputStream in = null; private BufferedReader reader = null; private Vector locales; /** * should be retrieved through JOTRequestParser */ JOTWebRequest() { } /************************************************************************* * HttpServletRequest Impl. methods * @return */ public String getScheme() { if (scheme != null) { return scheme; } //TODO scheme = "http"; return scheme; } /** * * @return */ public StringBuffer getRequestURL() { if (url != null) { return url; } StringBuffer sb = new StringBuffer(getScheme()).append("://").append(getServerName()); if (getLocalPort() != 80) { sb.append(":").append(getLocalPort()); } sb.append(path); if (rawParams != null && rawParams.length() > 0) { sb.append("?").append(rawParams); } url = sb; // should we return a copy ?? according to spec probably not return url; } public Hashtable getHeaders() { return headers; } public String getRemoteHost() { return remoteHost; } public String getMethod() { return method; } public Hashtable getParameters() { return parameters; } public int getRemotePort() { return remotePort; } public String getProtocol() { return protocol; } protected void addHeader(String key, String value) { Vector v = new Vector(); if (headers.containsKey(key)) { v = (Vector) headers.get(key); } v.add(value); headers.put(key, v); if (key.equalsIgnoreCase("cookie")) { parseCookieLine(value); } } public int getLocalPort() { return localPort; } public String getServerName() { // lazy inited if (serverName != null) { return serverName; } // Return host from absolute URI /*serverName=_uri.getHost(); if (serverName!=null) return serverName; */ // Return host from header field String host = (String) headers.get("Host"); if (host != null) { int column = host.indexOf(":"); if (column == -1) { serverName = host; } else { serverName = host.substring(0, column); try { localPort = new Integer(host.substring(column + 1, host.length())).intValue(); } catch (Exception e) { logger.exception("Malformed Host HTTP Header: " + host, e); } } } if (serverName != null) { return serverName; } // Try from socket host if (socket != null) { //TODO: use canonial or regular host name ?? serverName = socket.getLocalAddress().getCanonicalHostName(); if (serverName != null) { return serverName; } } // Fallback to local host try { serverName = InetAddress.getLocalHost().getHostAddress(); } catch (java.net.UnknownHostException e) {/*How could that fail ?? */ } return serverName; } public String getAuthType() { // TODO: support this ?? throw new UnsupportedOperationException("Not supported yet."); } public Cookie[] getCookies() { return (Cookie[]) cookies.toArray(new Cookie[0]); } public long getDateHeader(String headerName) { String header = getHeader(headerName); if (header == null) { return -1; } Date d = null; try { d = HEADER_FORMAT.parse(header); } catch (ParseException e) { throw new IllegalArgumentException(e); } return d.getTime(); } public String getHeader(String headerName) { Vector v = (Vector) headers.get(headerName); return (v == null || v.size() < 1) ? null : (String) v.get(0); } public Enumeration getHeaders(String headerName) { Vector v = (Vector) headers.get(headerName); return v == null ? EMPTY_ENUM : v.elements(); } public Enumeration getHeaderNames() { return headers.keys(); } public int getIntHeader(String headerName) { String header = getHeader(headerName); return header == null ? -1 : new Integer(header).intValue(); } public String getPathInfo() { // TODO: unsure about impl. throw new UnsupportedOperationException("Not supported yet."); } public String getPathTranslated() { // TODO: unsure about impl. throw new UnsupportedOperationException("Not supported yet."); } public String getContextPath() { return contextPath; } public String getQueryString() { return rawParams; } public String getRemoteUser() { throw new UnsupportedOperationException("Not supported yet."); } public boolean isUserInRole(String arg0) { throw new UnsupportedOperationException("Not supported yet."); } public Principal getUserPrincipal() { throw new UnsupportedOperationException("Not supported yet."); } public String getRequestedSessionId() { return requestedSessionId; } public String getRequestURI() { return path; } public String getServletPath() { return path; } public HttpSession getSession(boolean createIfNew) { String id = requestedSessionId; if (id == null || !isRequestedSessionIdValid()) { id = sessionId; } JOTWebSession session = null; if (createIfNew) { session = JOTSessionManager.getInstance().getSession(sessionId); } else { JOTSessionManager.getInstance().getOrCreateSession(sessionId); } sessionId = session.getId(); return session; } public HttpSession getSession() { return getSession(true); } public boolean isRequestedSessionIdValid() { return JOTSessionManager.getInstance().getSession(requestedSessionId) != null; } public boolean isRequestedSessionIdFromCookie() { return requestedSIDFromCookies; } public boolean isRequestedSessionIdFromURL() { return !requestedSIDFromCookies; } /** * @deprecated * @return */ public boolean isRequestedSessionIdFromUrl() { return isRequestedSessionIdFromURL(); } public Object getAttribute(String key) { return attributes.get(key); } public Enumeration getAttributeNames() { return attributes.keys(); } public String getCharacterEncoding() { return encoding; } public void setCharacterEncoding(String encoding) throws UnsupportedEncodingException { //TODO: check that encoding is valid this.encoding = encoding; } public int getContentLength() { try { return getInputStream().available(); } catch (IOException e) { } return -1; } public String getContentType() { //TODO: how to determine this ?? return null; } public ServletInputStream getInputStream() throws IOException { if (reader != null) { throw new IllegalStateException("Can't use both getInputStream() and getReader()"); } if (in == null) { in = (ServletInputStream) socket.getInputStream(); } return in; } public String getParameter(String name) { Vector v = (Vector) parameters.get(name); if (v == null) { return null; } return (String) v.get(0); } public Enumeration getParameterNames() { return parameters.keys(); } public String[] getParameterValues(String name) { Vector v = (Vector) parameters.get(name); if (v == null) { return null; } return (String[]) v.toArray(new String[0]); } public Map getParameterMap() { return parameters; } public int getServerPort() { return localPort; } public BufferedReader getReader() throws IOException { if (in != null) { throw new IllegalStateException("Can't use both getInputStream() and getReader()"); } if (reader == null) { if (encoding == null) { reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); } else { reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), encoding)); } } return reader; } public String getRemoteAddr() { return remoteHost; } public void setAttribute(String key, Object value) { if (value == null) { removeAttribute(key); } else { attributes.put(key, value); } } public void removeAttribute(String key) { attributes.remove(key); } public Locale getLocale() { if (locales == null) { getLocales(); } return (Locale) locales.get(0); } public Enumeration getLocales() { if (locales == null) { locales = new Vector(); Enumeration e = getHeaders("Accept-Language"); while (e.hasMoreElements()) { String s = (String) e.nextElement(); if (s != null) { String[] vals = s.split(","); for (int i = 0; i != vals.length; i++) { Locale locale = getIndividualLocale(vals[i]); if (locale != null) { locales.add(locale); } } } } if (locales.size() == 0) { // if no valid locale, then return default server local as per spec locales.add(Locale.getDefault()); } } return locales.elements(); } public boolean isSecure() { //TODO: how do i know that ?? throw new UnsupportedOperationException("Not supported yet."); } public RequestDispatcher getRequestDispatcher(String arg0) { //TODO throw new UnsupportedOperationException("Not supported yet."); } /** * @deprecated * @param arg0 * @return */ public String getRealPath(String paht) { // need to be call with ServletContext.getRealPath return JOTSessionManager.getInstance().getServletContext().getRealPath(path); } public String getLocalAddr() { return localHost; } public String getLocalName() { return getServerName(); } /********************************************************** * Others */ void setRawParameters(String params) { rawParams = params; } /** * * @param id * @param fromCookies - if flase : from url */ void setRequestedSessionId(String id, boolean fromCookies) { requestedSessionId = id; requestedSIDFromCookies = fromCookies; if (isRequestedSessionIdValid()) { sessionId = id; } } void setSessionId(String id) { sessionId = id; } String getSessionId() { return sessionId; } void setRawParams(String rawParams) { this.rawParams = rawParams; } void setRemoteHost(String host) { this.remoteHost = host; } void setMethod(String method) { this.method = method; } void setParameters(Hashtable parameters) { this.parameters = parameters; } void setPath(String path) { this.path = path; } void setRemotePort(int port) { this.remotePort = port; } void setProtocol(String protocol) { this.protocol = protocol; } void setRawRequestLine(String rawRequestLine) { this.rawRequestLine = rawRequestLine; } public void parseCookieLine(String value) { //TODO: look at cookie spec some more String[] cooks = value.split(";"); for (int i = 0; i != cooks.length; i++) { String cookie = cooks[i]; int index = cookie.indexOf("="); if (index != -1) { String key = cookie.substring(0, index).trim(); String val = ""; // Is trim safe in this case ?? if (cookie.length() > index) { val = cookie.substring(index + 1, cookie.length()).trim(); } cookies.add(new Cookie(key, val)); if (key.equals("JSESSIONID")) { setRequestedSessionId(val, true); } } } } /** * Print detailed infos about the request * @return */ public String toString() { String str = "" + getClass().getSimpleName() + " [method:" + method + " proto:" + protocol + " path:" + path + " host:" + remoteHost + " port:" + remotePort + "]"; str += "\n\tHeaders:"; Enumeration e = headers.keys(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); str += "\n\t\t" + key + " -> "; Vector v = (Vector) headers.get(key); for (int i = 0; i != v.size(); i++) { str += v.get(i) + " | "; } } str += "\n\tCookies:"; for (int i = 0; i != cookies.size(); i++) { Cookie cookie = (Cookie) cookies.get(i); str += "\n\t\t" + cookie.getName() + " : " + cookie.getValue(); } str += "\n\tParams:"; Enumeration e2 = parameters.keys(); while (e2.hasMoreElements()) { String key = (String) e2.nextElement(); String val = (String) parameters.get(key); str += "\n\t\t" + key + " -> " + val; } str += "\n"; return str; } /** * Get the raw requestline as sent from the browser * @return */ public String getRawRequestLine() { return rawRequestLine; } String getLocalHost() { return localHost; } void setLocalHost(String localHost) { //TODO: return servername instead ?? this.localHost = localHost; } void setLocalPort(int localPort) { this.localPort = localPort; } void setContextPath(String path) { contextPath = path; } private Locale getIndividualLocale(String str) { //We might have something like en-us;q=0.5 // remove qvalue stuff int i = str.indexOf(';'); if (i != -1) { str = str.substring(0, i); } str = str.trim(); //We might have something like en-us String language = str; String country = ""; // there might be a "-" followed by a countryname int countrySeparator = language.indexOf('-'); Locale locale = null; if (countrySeparator != -1) { country = language.substring(countrySeparator + 1, language.length()); language = language.substring(0, countrySeparator); } try { locale = new Locale(language, country); } catch (Exception e) { //if parsing failed, this will be null ? } return locale; } }