GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — javaxt-express/src/javaxt/express/ServiceRequest.java at master · javaxt-project/javaxt-express Expand file tree/ Copy pathServiceRequest.javaMore file actions 2100 lines (1769 loc) · 76.4 KB / Copy pathServiceRequest.javaFile metadata and controls2100 lines (1769 loc) · 76.4 KB 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 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 package javaxt.express; import java.util.*; import java.io.StringReader; //JavaXT includes import javaxt.json.*; import javaxt.sql.Model; import javaxt.express.utils.StringUtils; import static javaxt.utils.Console.console; import javaxt.http.servlet.ServletException; import javaxt.http.servlet.HttpServletRequest; //JSQLParser includes import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.Function; import net.sf.jsqlparser.parser.CCJSqlParserManager; import net.sf.jsqlparser.statement.select.*; //****************************************************************************** //** ServiceRequest //****************************************************************************** /** * Used to encapsulate an HttpServletRequest and simplify the * parsing/extracting of parameters from the raw HTTP request. * ******************************************************************************/ public class ServiceRequest { private HttpServletRequest request; private String service; private String method = ""; private String[] path; private java.security.Principal user; private javaxt.utils.URL url; private byte[] payload; private JSONObject json; private HashMap<String, List<String>> parameters; //<- Don't use this directly! Use the static getParameter() and setParameter() methods private Field[] fields; private Filter filter; private Sort sort; private Long limit; private Long offset; private Long id; private boolean readOnly = false; private boolean parseJson = false; private static String[] approvedFunctions = new String[]{ "min", "max", "count", "avg", "sum" }; private Map<String, String> keywords = Map.ofEntries( Map.entry("fields", "fields"), Map.entry("orderby", "orderby"), Map.entry("limit", "limit"), Map.entry("offset", "offset"), //Used by the list method in the WebService class Map.entry("format", "format"), Map.entry("count", "count"), //Legacy - may be removed in the future Map.entry("filter", "filter"), Map.entry("where", "where"), Map.entry("page", "page") ); //************************************************************************** //** Constructor //************************************************************************** /** Creates a new instance of this class using a JavaXT HttpServletRequest. */ public ServiceRequest(javaxt.http.servlet.HttpServletRequest request){ this(null, request); } //************************************************************************** //** Constructor //************************************************************************** /** Creates a new instance of this class using a JavaXT HttpServletRequest. * @param service A path segment in the request URL used to designate the * start of the path variable. See setService() and setPath() for more info * on how the path variable is set. */ public ServiceRequest(String service, javaxt.http.servlet.HttpServletRequest request){ this.request = request; this.url = new javaxt.utils.URL(request.getURL()); this.parameters = url.getParameters(); //Parse payload if it contains URL encoded form data String contentType = request.getContentType(); if (contentType!=null){ if (contentType.equalsIgnoreCase("application/x-www-form-urlencoded")){ byte[] b = getPayload(); if (b!=null && b.length>0){ try{ LinkedHashMap<String, List<String>> params = javaxt.utils.URL.parseQueryString(new String(b, "UTF-8")); for (String key : params.keySet()) { List<String> values = params.get(key); List<String> currValues = this.parameters.get(key); if (currValues==null){ this.parameters.put(key, values); } else{ for (String val : values){ currValues.add(val); } } } } catch(Exception e){} } } } //Update service (and path) after parsing params setService(service); //Get offset and limit updateOffsetLimit(); } //************************************************************************** //** Constructor //************************************************************************** /** Creates a new instance of this class using a "javax" HttpServletRequest * and HttpServlet. */ public ServiceRequest(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServlet servlet){ this(new javaxt.http.servlet.HttpServletRequest(request, servlet)); } //************************************************************************** //** Constructor //************************************************************************** /** Creates a new instance of this class using a "jakarta" HttpServletRequest * and HttpServlet. */ public ServiceRequest(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServlet servlet){ this(new javaxt.http.servlet.HttpServletRequest(request, servlet)); } //************************************************************************** //** setService //************************************************************************** /** Used to update the service and path variables associated with the * request. This method determines which URL segments are included in the * path, which in turn affects the method name returned by getMethod(). * Call this method when routing a request from an HttpServlet or WebService * to another WebService to ensure proper routing. * @param service A segment in the request URL used to designate the start * of the path variable. The service segment should appear after the * servlet. For example, the service segment in * "http://localhost/servlet/service/a/b/c" is simply "service" and the * resultant path is "/a/b/c". If the servlet path is undefined/missing * (e.g. "http://localhost/service/a/b/c"), you can still specify "service" * as the service and the resultant path would be "/a/b/c". You can even * use multiple segments for the service parameter (e.g. "/path/to/service/" * for "http://localhost/servlet/path/to/service/a/b/c"). If the service * parameter is empty or null or simply doesn't exist in the URL, then the * path variable will be set to whatever is to the right of the servlet * path. */ public void setService(String service){ if (service!=null){ service = service.trim(); if (service.isEmpty()) service = null; } this.service = service; //Parse path, excluding servlet setPath(request.getPathInfo()); } //************************************************************************** //** getService //************************************************************************** /** Returns the service path in the request URL. Returns null if the service * is not set. */ public String getService(){ return service; } //************************************************************************** //** getMethod //************************************************************************** /** Returns a method name for the HTTP request using the first path segment * returned by getPath(0) and the HTTP request method (GET, POST, etc). * Examples: * <ul> * <li>GET "http://localhost/user" returns "getUser"</li> * <li>DELETE "http://localhost/user" returns "deleteUser"</li> * <li>POST or PUT "http://localhost/user" returns "saveUser"</li> * </ul> * * Returns an empty string if the path is empty. * * <p> * Note that the path starts after the servlet and service. Consider the * following URL: "http://localhost/myapp/admin/user". In this example, the * servlet is "myapp" and the service is "admin". The method name is * derived from the first path segment after the servlet and service (i.e. * "user"). An HTTP GET request to this URL would yield "getUser". See * setService() and setPath() for more information. * </p> * * <p> * If the request is read-only, "POST", "PUT", and "DELETE" requests will * be re-mapped to "GET". See set setReadOnly(). * </p> * * Note that the WebService class relies on this method to map service * requests to REST service endpoints and execute CRUD operations. */ public String getMethod(){ return method; } //************************************************************************** //** setReadOnly //************************************************************************** /** Used to enable/disable insert, update, and delete operations by updating * the string returned by getMethod(). * @param readOnly If true, "POST", "PUT", and "DELETE" requests are * remapped to "GET" for getMethod(). */ public void setReadOnly(boolean readOnly){ if (readOnly==this.readOnly) return; this.readOnly = readOnly; setPath(request.getPathInfo()); } //************************************************************************** //** isReadOnly //************************************************************************** /** Returns true if insert, update, and delete operations have been disabled. * See setReadOnly() for more information. Default is false. */ public boolean isReadOnly(){ return readOnly; } //************************************************************************** //** getPath //************************************************************************** /** Returns a segment from the requested URL path at a given index. Note * that the path starts after the servlet and service. See setService() and * setPath() for more information on how the path variable is set. * @param i Index number, starting from 0. For example, index 0 for * "http://localhost/servlet/service/a/b/c" would yield "a". */ public javaxt.utils.Value getPath(int i){ if (path==null || i>=path.length) return new javaxt.utils.Value(null); else return new javaxt.utils.Value(path[i]); } //************************************************************************** //** getPath //************************************************************************** /** Returns a part of the requested URL path after the servlet and service. * For example, "http://localhost/servlet/service/a/b/c" would yield * "/a/b/c". See setService() and setPath() for more information on how * the path variable is set. */ public String getPath(){ if (path==null) return null; StringBuilder str = new StringBuilder(); for (String s : path){ str.append("/"); str.append(s); } return str.toString(); } //************************************************************************** //** setPath //************************************************************************** /** Used to update the path variable associated with the request. The path * variable is essential for several methods in this class (e.g. getId and * getMethod) and is critical for routing requests to different web methods * in the WebService class. This method is called whenever the service is * updated (see setService). * * @param path URL path after the servlet path. For example, if a URL * follows a pattern like "http://localhost/servlet/service/a/b/c", * you should provide everything to the right of the servlet (i.e. * "/service/a/b/c"). If a service is defined, the resultant path would be * "/a/b/c". If a service is not defined, the resultant path would be * "/service/a/b/c". */ public void setPath(String path){ this.path = null; if (path!=null){ boolean addPath = service==null; //Special case for service if (service!=null && service.contains("/")){ int idx = path.indexOf(service); if (idx>-1) path = path.substring(idx+service.length()); addPath = true; } if (path.startsWith("/")) path = path.substring(1); ArrayList<String> arr = new ArrayList<>(); for (String str : path.split("/")){ if (addPath) arr.add(str); if (str.equalsIgnoreCase(service)){ addPath = true; } } if (!arr.isEmpty()){ this.path = arr.toArray(new String[arr.size()]); } } //Generate a method name using the request method and first "directory" //in the path. Example: "GET /config/users" would yield the "getUsers" //from the "config" service. String name = getPath(0).toString(); if (name!=null && name.length()>0){ name = name.substring(0, 1).toUpperCase() + name.substring(1); if (readOnly){ this.method = "get" + name; } else{ String method = request.getMethod(); if (method.equals("GET")){ this.method = "get" + name; } else if (method.equals("PUT") || method.equals("POST")){ this.method = "save" + name; } else if (method.equals("DELETE")){ this.method = "delete" + name; } } } //Get ID id = getPath(1).toLong(); if (id==null) id = getParameter("id").toLong(); } //************************************************************************** //** getID //************************************************************************** /** Returns the ID associated with the request. Assuming the service request * follows the convention "http://localhost/servlet/service/object", the ID * for the "http://localhost/photos/config/user/54" is 54. If an ID is not * found in the path or is invalid, then the id parameter in the query * string is returned. Example: "http://localhost/photos/config/user?id=54" */ public Long getID(){ return id; } //************************************************************************** //** getURL //************************************************************************** /** Returns the original url used to make the request. */ public javaxt.utils.URL getURL(){ return url; } //************************************************************************** //** getParameter //************************************************************************** /** Returns the value associated with a parameter in the request. Performs a * case insensitive search for the keyword in the query string. In addition, * will search the JSON payload of the request if parseJson is set to true. * If the value is an empty string or "null" then a null value is returned. */ public javaxt.utils.Value getParameter(String key){ Object val = null; if (key!=null){ //Search the URL querystring List<String> parameters = getParameter(key, this.parameters); if (parameters!=null){ LinkedHashSet<String> vals = new LinkedHashSet<>(); for (String v : parameters){ if (v.length()>0){ if (v.equalsIgnoreCase("null")) v = null; } else{ v = null; } if (v!=null) vals.add(v); } if (!vals.isEmpty()){ if (vals.size()==1){ val = vals.iterator().next(); } else{ val = vals.toArray(new String[vals.size()]); } } } //If nothing found in the querystring, search the payload as directed if (val==null && parseJson){ //&& !getRequest().getMethod().equals("GET") JSONObject json = getJson(); if (json!=null && json.has(key)){ return new javaxt.utils.Value(json.get(key).toObject()); } } } return new javaxt.utils.Value(val); } //************************************************************************** //** hasParameter //************************************************************************** /** Returns true if the request contains a given parameter in the request. * Performs a case insensitive search for the keyword in the query string. * In addition, will search the JSON payload of the request if parseJson is * set to true. */ public boolean hasParameter(String key){ if (key!=null){ List<String> parameters = getParameter(key, this.parameters); if (parameters!=null) return true; if (parseJson){ //&& !getRequest().getMethod().equals("GET") JSONObject json = getJson(); if (json!=null && json.has(key)){ return true; } } } return false; } //************************************************************************** //** setParameter //************************************************************************** /** Used to update a parameter extracted from the original request. Performs * a case insensitive search for the keyword. */ public void setParameter(String key, String val){ if (key==null) return; if (val==null){ removeParameter(key, this.parameters); } else{ //Get parameters List<String> parameters = getParameter(key, this.parameters); //Special case for classes that override the hasParameter and //getParameter methods. if (parameters==null && hasParameter(key)){ parameters = new ArrayList<>(); parameters.add(getParameter(key).toString()); setParameter(key, parameters, this.parameters); } //Add or update value if (parameters==null){ if (val!=null){ parameters = new ArrayList<>(); parameters.add(val); setParameter(key, parameters, this.parameters); } } else{ if (val!=null) parameters.set(0, val); } } //Update offset and limit as needed String k = key.toLowerCase(); if (k.equals(getKeyword("offset")) || k.equals(getKeyword("limit")) || k.equals(getKeyword("page"))){ updateOffsetLimit(); } } //************************************************************************** //** removeParameter //************************************************************************** /** Used to remove a parameter from the request. Performs a case insensitive * search for the keyword. */ public void removeParameter(String key){ setParameter(key, null); } //************************************************************************** //** getParameterNames //************************************************************************** /** Returns a list of all the parameter keywords found in this request. */ public String[] getParameterNames(){ LinkedHashSet<String> keys = new LinkedHashSet<>(); Iterator<String> it = this.parameters.keySet().iterator(); while (it.hasNext()) keys.add(it.next()); if (parseJson){ JSONObject json = getJson(); if (json!=null){ for (String key : json.keySet()){ keys.add(key); } } } return keys.toArray(new String[keys.size()]); } private static List<String> getParameter(String key, HashMap<String, List<String>> parameters){ return javaxt.utils.URL.getParameter(key, parameters); }; private static void setParameter(String key, List<String> values, HashMap<String, List<String>> parameters){ javaxt.utils.URL.setParameter(key, values, parameters); } private static void removeParameter(String key, HashMap<String, List<String>> parameters){ javaxt.utils.URL.removeParameter(key, parameters); } //************************************************************************** //** updateOffsetLimit //************************************************************************** private void updateOffsetLimit(){ offset = getParameter(getKeyword("offset")).toLong(); limit = getParameter(getKeyword("limit")).toLong(); Long page = getParameter(getKeyword("page")).toLong(); if (offset==null && page!=null){ if (limit==null) limit = 25L; offset = (page*limit)-limit; } } //************************************************************************** //** getOffset //************************************************************************** /** Returns the value of the "offset" parameter in the request as a number. * This parameter is used by the WebService class to paginate through list * requests. */ public Long getOffset(){ return offset; } //************************************************************************** //** getLimit //************************************************************************** /** Returns the value of the "limit" parameter in the request as a number. * This parameter is used by the WebService class to paginate through list * requests. */ public Long getLimit(){ return limit; } //************************************************************************** //** getFormat //************************************************************************** /** Returns the value of the "format" parameter in the request. */ protected String getFormat(){ String format = getParameter(getKeyword("format")).toString(); if (format==null) return ""; else return format.toLowerCase(); } //************************************************************************** //** getCount //************************************************************************** /** Returns the value of the "count" parameter in the request. */ protected boolean getCount(){ Boolean count = getParameter(getKeyword("count")).toBoolean(); if (count==null) return false; else return count; } //************************************************************************** //** getClientIP //************************************************************************** /** Returns the client IP address from the request (the direct socket * address). Equivalent to getClientIP(false). */ public String getClientIP() { return getClientIP(false); } //************************************************************************** //** getClientIP //************************************************************************** /** Returns the client IP address from the request. * @param trustProxy When true, and an "X-Forwarded-For" header is present, * the first (client) entry of that header is returned instead of the socket * address. Only enable this when the server sits behind a trusted reverse * proxy/CDN that sets the header; otherwise clients could spoof their IP. */ public String getClientIP(boolean trustProxy) { if (trustProxy) { String xff = request.getHeader("X-Forwarded-For"); if (xff != null && !xff.isEmpty()) { int comma = xff.indexOf(","); String forwarded = (comma > 0 ? xff.substring(0, comma) : xff).trim(); if (!forwarded.isEmpty()) return forwarded; } } String ip = request.getRemoteAddr(); if (ip != null && ip.startsWith("/") && ip.length() > 1) { ip = ip.substring(1); } return ip; } //************************************************************************** //** getRequest //************************************************************************** /** Returns the original, unmodified HTTP request used to instantiate this * class. */ public HttpServletRequest getRequest(){ return request; } //************************************************************************** //** setPayload //************************************************************************** /** Used to update the raw bytes representing the payload of the request */ public void setPayload(byte[] payload){ this.payload = payload; json = null; } //************************************************************************** //** getPayload //************************************************************************** /** Returns the raw bytes from the payload of the request */ public byte[] getPayload(){ if (payload==null){ try{ payload = request.getBody(); } catch(Exception e){} } return payload; } //************************************************************************** //** getJson //************************************************************************** /** Returns the payload of the request as a JSON object */ public JSONObject getJson(){ if (json==null){ byte[] b = getPayload(); if (b!=null && b.length>0){ try{ json = new JSONObject(new String(b, "UTF-8")); } catch(Exception e){} } } return json; } //************************************************************************** //** parseJson //************************************************************************** /** Calling this method will expand parameter searches into the payload of * the request. See getParameter() for more info. */ public void parseJson(){ parseJson = true; if (id==null) id = getParameter("id").toLong(); updateOffsetLimit(); } //************************************************************************** //** getUser //************************************************************************** /** Returns the user associated with the request */ public java.security.Principal getUser(){ if (user==null){ user = request.getUserPrincipal(); } return user; } //************************************************************************** //** getCredentials //************************************************************************** /** Returns the credentials associated with an HTTP request. The credentials * will vary based on the security authentication scheme used to * authenticate clients (e.g. "BASIC", "DIGEST", "NTLM", etc). In the case * of "BASIC" authentication, the credentials typically include a username * and password. In the case of "NTLM" authentication, the credentials may * only contain a username. What is actually returned is up to the * javaxt.http.servlet.Authenticator used to authenticate the request. */ public String[] getCredentials(){ return request.getCredentials(); } //************************************************************************** //** authenticate //************************************************************************** /** Used to authenticate a client request. Authentication is performed by a * javaxt.http.servlet.Authenticator. If no Authenticator is defined or if * the Authenticator fails to authenticate the client, this method throws a * ServletException. */ public void authenticate() throws ServletException { request.authenticate(); } //************************************************************************** //** isCacheable //************************************************************************** /** Returns true if a given eTag matches the "if-none-match" request header. * Additional checks are performed against other cache related headers * (e.g. "cache-control" and "if-modified-since"). If true is returned, * the corresponding HTTP response can be set to a 304 "Not Modified". * @param eTag A custom string that acts as a unique identifier (including * version) for an HTTP response. ETags are frequently used when sending * static data such as files. In the context of dynamic web services, the * same concept can be applied for static, or semi-static responses (e.g. * static keywords, images in a database, etc). * @param date A date associated with the HTTP response. The date should be * in GMT and in "EEE, dd MMM yyyy HH:mm:ss zzz" format (e.g. * "Sat, 23 Oct 2010 13:04:28 GMT"). */ public boolean isCacheable(String eTag, String date){ String matchTag = request.getHeader("if-none-match"); String cacheControl = request.getHeader("cache-control"); if (matchTag==null) matchTag = ""; if (cacheControl==null) cacheControl = ""; if (cacheControl.equalsIgnoreCase("no-cache")==false){ if (eTag.equalsIgnoreCase(matchTag)){ return true; } else{ //Internet Explorer 6 uses "if-modified-since" instead of "if-none-match" matchTag = request.getHeader("if-modified-since"); if (matchTag!=null){ for (String tag: matchTag.split(";")){ if (tag.trim().equalsIgnoreCase(date)){ return true; } } } } } return false; } //************************************************************************** //** getFields //************************************************************************** /** Returns an array of ServiceRequest.Fields by parsing the "fields" * parameter in the HTTP request (e.g. "?fields=id,firstName,lastName"). */ public Field[] getFields(){ if (fields!=null) return fields; String fields = getParameter(getKeyword("fields")).toString(); //If fields are empty, simply return an ampty array if (fields==null || fields.length()==0){ this.fields = new Field[0]; return this.fields; } //Parse the fields this.fields = getFields(fields); return this.fields; } //************************************************************************** //** getFields //************************************************************************** /** Used to parse a given String into an array of Fields. * @param fields A comma delimited list of fields (e.g. "id,firstName,lastName") */ public Field[] getFields(String fields){ ArrayList<Field> arr = new ArrayList<>(); try{ //Parse fields parameter using JSQLParser CCJSqlParserManager parserManager = new CCJSqlParserManager(); Select select = (Select) parserManager.parse(new StringReader("SELECT " + fields + " FROM T")); PlainSelect plainSelect = (PlainSelect) select.getSelectBody(); //Iterate through the fields and update the array Iterator<SelectItem> it = plainSelect.getSelectItems().iterator(); while (it.hasNext()){ SelectExpressionItem si = (SelectExpressionItem) it.next(); Expression expression = si.getExpression(); String alias = si.getAlias()==null ? null : si.getAlias().getName(); //Check if the expression contains a function String functionName = null; try{ Function f = (Function) expression; functionName = f.getName().toLowerCase(); } catch(Exception e){ try{ SubSelect ss = (SubSelect) expression; functionName = "SELECT"; } catch(Exception ex){ } } String column = expression.toString(); boolean isFunction = functionName!=null; if (!isFunction) column = StringUtils.camelCaseToUnderScore(column); Field field = new Field(column); field.setAlias(alias); field.isFunction(isFunction); field.setFunctionName(functionName); arr.add(field); } } catch(Throwable e){ //JSQLParser doesn't like one of the fields or JSqlParser is missing //from the class path. If so, fallback to the JavaXT SQL parser. arr.clear(); javaxt.sql.Parser sqlParser = new javaxt.sql.Parser("SELECT " + fields + " FROM T"); for (javaxt.sql.Parser.SelectStatement stmt : sqlParser.getSelectStatements()){ String column = stmt.getField(); boolean isFunction = stmt.isFunction(); if (!isFunction) column = StringUtils.camelCaseToUnderScore(column); Field field = new Field(column); field.setAlias(stmt.getAlias()); field.isFunction(isFunction); arr.add(field); } } return arr.toArray(new Field[arr.size()]); } //************************************************************************** //** getFilter //************************************************************************** /** Returns a ServiceRequest.Filter by parsing the query string associated * this request. Examples: * <ul> * <li>http://localhost?id=1 (id = 1)</li> * <li>http://localhost?id>=1 (id > 1)</li> * <li>http://localhost?id!=1 (id <> 1)</li> * <li>http://localhost?id=1,2,3 (id in (1,2,3))</li> * <li>http://localhost?id!=1,2,3 (id not in (1,2,3))</li> * <li>http://localhost?active=true (active = true)</li> * <li>http://localhost?name='Bob' (name = 'Bob')</li> * <li>http://localhost?name='Bo%' (name like 'Bo%')</li> * <li>http://localhost?name!='Bo%' (name not like 'Bo%')</li> * </ul> * Note that the operators can be transposed without altering the filter * (e.g. ">=" is the same as "=>"). * * <p> * Alternatively, a Filter can be generated by parsing a "filter" parameter * containing JSON object. In fact, if a "filter" parameter is provided, it * will be used instead of the query string. * </p> */ public Filter getFilter(){ if (filter!=null) return filter; //Parse querystring LinkedHashMap<String, javaxt.utils.Value> params = new LinkedHashMap<>(); if (hasParameter(getKeyword("filter"))){ String str = getParameter(getKeyword("filter")).toString(); if (str.startsWith("{") && str.endsWith("}")){ JSONObject json = new JSONObject(str); for (String key : json.keySet()){ params.put(key, json.get(key)); } } else{ LinkedHashMap<String, List<String>> map = javaxt.utils.URL.parseQueryString(str); for (String key : map.keySet()){ List<String> vals = map.get(key); if (!vals.isEmpty()) params.put(key, new javaxt.utils.Value(vals.get(0))); } } } else{ for (String key : getParameterNames()){ params.put(key, getParameter(key)); } } //Create filter filter = new Filter(); HashSet<String> reservedKeywords = getKeywords(); for (String key : params.keySet()){ key = key.trim(); if (key.isEmpty()) continue; if (key.equals("_")) continue; if (reservedKeywords.contains(key.toLowerCase())) continue; //Parse val String[] vals; |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |