001    package railo.runtime.net.http;
002    
003    import java.io.BufferedReader;
004    import java.io.IOException;
005    import java.io.Serializable;
006    import java.io.UnsupportedEncodingException;
007    import java.net.InetAddress;
008    import java.net.UnknownHostException;
009    import java.security.Principal;
010    import java.util.ArrayList;
011    import java.util.Date;
012    import java.util.Enumeration;
013    import java.util.HashSet;
014    import java.util.Locale;
015    import java.util.Map;
016    
017    import javax.servlet.RequestDispatcher;
018    import javax.servlet.ServletInputStream;
019    import javax.servlet.http.Cookie;
020    import javax.servlet.http.HttpServletRequest;
021    import javax.servlet.http.HttpSession;
022    
023    import railo.commons.collections.HashTable;
024    import railo.commons.io.IOUtil;
025    import railo.commons.io.res.Resource;
026    import railo.commons.lang.Pair;
027    import railo.runtime.config.Config;
028    import railo.runtime.exp.PageException;
029    import railo.runtime.op.Caster;
030    import railo.runtime.op.date.DateCaster;
031    import railo.runtime.type.Array;
032    import railo.runtime.type.KeyImpl;
033    import railo.runtime.type.Struct;
034    import railo.runtime.type.StructImpl;
035    import railo.runtime.type.dt.DateTimeImpl;
036    import railo.runtime.util.EnumerationWrapper;
037    
038    public final class HttpServletRequestDummy implements HttpServletRequest,Serializable {
039            
040    
041            private Cookie[] cookies;
042            
043            private String authType;
044            private Pair[] headers=new Pair[0];
045            private Pair[] parameters=new Pair[0];
046            private Struct attributes=new StructImpl();
047            private String method="GET";
048            private String pathInfo;
049            private String pathTranslated;
050            private String contextPath="/";
051            private String queryString;
052            private String remoteUser;
053            private String requestedSessionId;
054            private String requestURI;
055    
056            private String protocol="HTTP/1.1";
057            private String serverName="localhost";
058            private int port=80;
059    
060            private String characterEncoding="ISO-8859-1";
061    
062            private String contentType;
063            private byte[] inputData=new byte[0];
064    
065    
066            private static InetAddress DEFAULT_REMOTE;
067            private static String DEFAULT_REMOTE_ADDR;
068            private static String DEFAULT_REMOTE_HOST;
069            static {
070                    try {
071                            DEFAULT_REMOTE=InetAddress.getLocalHost();
072                            DEFAULT_REMOTE_ADDR=DEFAULT_REMOTE.getHostAddress();
073                            DEFAULT_REMOTE_HOST=DEFAULT_REMOTE.getHostName();
074                    } 
075                    catch (UnknownHostException e) {}
076            }
077            //private InetAddress remoteq=DEFAULT_REMOTE;
078            private String remoteAddr=DEFAULT_REMOTE_ADDR;
079            private String remoteHost=DEFAULT_REMOTE_HOST;
080    
081            private Locale locale=Locale.getDefault();
082    
083            private boolean secure;
084    
085            private Resource contextRoot;
086    
087            private String scheme="http";
088    
089            private HttpSession session;
090    
091    
092    
093            /**
094             * constructor of the class
095             * @param headers 
096             * @param parameters 
097             * @param httpSession 
098             * @param pairs 
099             * @param cookiess 
100             */
101            public HttpServletRequestDummy(Resource contextRoot,String serverName, String scriptName,String queryString, 
102                            Cookie[] cookies, Pair[] headers, Pair[] parameters, Struct attributes, HttpSession session) {
103                    this.serverName=serverName;
104                    requestURI=scriptName;
105                    this.queryString=queryString;
106                    this.parameters=translateQS(queryString);
107                    this.contextRoot=contextRoot;
108                    if(cookies!=null)setCookies(cookies);
109                    if(headers!=null)this.headers=headers;
110                    if(parameters!=null)this.parameters=parameters;
111                    if(attributes!=null)this.attributes=attributes;
112                    this.session=session;
113            }
114            /**
115             * constructor of the class
116             * @throws PageException
117             * /
118            public HttpServletRequestDummy(String serverName, String scriptName,Struct queryString) throws PageException {
119                    this.serverName=serverName;
120                    requestURI=scriptName;
121                    
122                    StringBuffer qs=new StringBuffer();
123                    String[] keys=queryString.keys();
124                    parameters=new Item[keys.length];
125                    String key;
126                    Object value;
127                    for(int i=0;i<keys.length;i++) {
128                            if(i>0) qs.append('&');
129                            key=keys[i];
130                            value=queryString.get(key);
131                            parameters[i]=new Item(key,value);
132                            
133                            qs.append(key);
134                            qs.append('=');
135                            qs.append(Caster.toString(value));
136                    }
137                    
138                    this.queryString=qs.toString();
139            }*/
140            
141            private Pair[] translateQS(String qs) {
142            if(qs==null) return new Pair[0];
143            Array arr=railo.runtime.type.List.listToArrayRemoveEmpty(qs,"&");
144            Pair[] parameters=new Pair[arr.size()];
145            //Array item;
146            int index;
147            String name;
148            
149            for(int i=1;i<=parameters.length;i++) {
150                name=Caster.toString(arr.get(i,""),"");
151                index=name.indexOf('=');
152                if(index!=-1) parameters[i-1]=new Pair(name.substring(0,index),name.substring(index+1));
153                else parameters[i-1]=new Pair(name,"");
154                  
155            }
156            return parameters;
157        }
158            
159            
160    
161            /** 
162             * @see javax.servlet.http.HttpServletRequest#getAuthType()
163             */
164            public String getAuthType() {
165                    return authType;
166            }
167            
168            /**
169             * sets the name of the authentication scheme used to protect the servlet. 
170             * All servlet containers support basic, 
171             * form and client certificate authentication, 
172             * and may additionally support digest authentication. 
173             * @param authType authentication type
174             */
175            public void setAuthType(String authType) {
176                    this.authType=authType;
177            }
178            
179            /**
180             * @see javax.servlet.http.HttpServletRequest#getCookies()
181             */
182            public Cookie[] getCookies() {
183                    return cookies;
184            }
185            
186            /**
187             * sets an array containing all of the Cookie objects 
188             * the client sent with this request. 
189             * This method returns null if no cookies were sent.
190             * @param cookies
191             */
192            public void setCookies(Cookie[] cookies) {
193                    this.cookies=cookies;
194            }
195            
196            /**
197             * @see javax.servlet.http.HttpServletRequest#getDateHeader(java.lang.String)
198             */
199            public long getDateHeader(String name) {
200                    Object value=getHeader(name);
201                    if(value!=null) {
202                            Date date=DateCaster.toDateAdvanced(value,null,null);
203                            if(date!=null)return date.getTime();
204                            throw new IllegalArgumentException("can't convert value "+value+" to a Date");
205                    }
206                    return -1;
207            }
208            
209            public void setDateHeader(String name, long value) {
210                    // TODO wrong format
211                    setHeader(name,new DateTimeImpl(value,false).castToString());
212            }
213            
214            /**
215             * @see javax.servlet.http.HttpServletRequest#getHeader(java.lang.String)
216             */
217            public String getHeader(String name) {
218                    return ReqRspUtil.get(headers,name);
219            }
220            
221            /**
222             * sets a new header value
223             * @param name name of the new value
224             * @param value header value
225             */ 
226            public void setHeader(String name, String value) {
227                    headers=ReqRspUtil.set(headers,name,value);
228            }
229            
230            /**
231             * add a new header value
232             * @param name name of the new value
233             * @param value header value
234             */ 
235            public void addHeader(String name, String value) {
236                    headers=ReqRspUtil.add(headers,name,value);
237            }
238            
239            
240            /**
241             * @see javax.servlet.http.HttpServletRequest#getHeaders(java.lang.String)
242             */
243            public Enumeration getHeaders(String name) {
244                    HashSet set=new HashSet();
245                    for(int i=0;i<headers.length;i++) {
246                            if(headers[i].getName().equalsIgnoreCase(name))
247                                    set.add(Caster.toString(headers[i].getValue(),null));
248                    }
249                    return new EnumerationWrapper(set);
250            }
251            
252            /**
253             * @see javax.servlet.http.HttpServletRequest#getHeaderNames()
254             */
255            public Enumeration getHeaderNames() {
256                    HashSet set=new HashSet();
257                    for(int i=0;i<headers.length;i++) {
258                            set.add(headers[i].getName());
259                    }
260                    return new EnumerationWrapper(set);
261            }
262            
263            /**
264             * @see javax.servlet.http.HttpServletRequest#getIntHeader(java.lang.String)
265             */
266            public int getIntHeader(String name) {
267                    Object value=getHeader(name);
268                    if(value!=null) {
269                            try {
270                                    return Caster.toIntValue(value);
271                            } catch (PageException e) {
272                                    throw new NumberFormatException(e.getMessage());
273                            }
274                    }
275                    return -1;
276            }
277            
278            /**
279             * @see javax.servlet.http.HttpServletRequest#getMethod()
280             */
281            public String getMethod() {
282                    return method;
283            }
284            
285            /**
286             * sets the request method
287             * @param method
288             */
289            public void setMethod(String method) {
290                    this.method = method;
291            }
292            
293            /**
294             * @see javax.servlet.http.HttpServletRequest#getPathInfo()
295             */
296            public String getPathInfo() {
297                    return pathInfo;
298            }
299            
300            
301            /**
302             * Sets any extra path information associated with the URL the client sent 
303             * when it made this request. 
304             * The extra path information follows the servlet path but precedes 
305             * the query string. 
306             * @param pathInfo
307             */
308            public void setPathInfo(String pathInfo) {
309                    this.pathInfo = pathInfo;
310            }
311            
312            
313            /**
314             * @see javax.servlet.http.HttpServletRequest#getPathTranslated()
315             */
316            public String getPathTranslated() {
317                    return pathTranslated;
318            }
319    
320            /**
321             * sets any extra path information after the servlet name 
322             * but before the query string, translates to a real path. 
323             * Same as the value of the CGI variable PATH_TRANSLATED. 
324             * @param pathTranslated
325             */
326            public void setPathTranslated(String pathTranslated) {
327                    // TODO muss auf pathinfo basieren
328                    this.pathTranslated = pathTranslated;
329            }
330            
331            /**
332             * @see javax.servlet.http.HttpServletRequest#getContextPath()
333             */
334            public String getContextPath() {
335                    return contextPath;
336            }
337            
338            /**
339             * sets the portion of the request URI that indicates the context of the request. 
340             * The context path always comes first in a request URI. 
341             * The path starts with a "/" character but does not end with a "/" character. 
342             * @param contextPath
343             */
344            public void setContextPath(String contextPath) {
345                    this.contextPath = contextPath;
346            }
347            
348            /**
349             * @see javax.servlet.http.HttpServletRequest#getQueryString()
350             */
351            public String getQueryString() {
352                    return queryString;
353            }
354            
355            /**
356             * sets the query string that is contained in the request URL after the path. 
357             * Same as the value of the CGI variable QUERY_STRING.
358    
359             * @param queryString
360             */
361            public void setQueryString(String queryString) {
362                    this.queryString = queryString;
363                    parameters=translateQS(queryString);
364            }
365            
366            /**
367             * @see javax.servlet.http.HttpServletRequest#getRemoteUser()
368             */
369            public String getRemoteUser() {
370                    return remoteUser;
371            }
372            
373            /**
374             * sets the login of the user making this request, 
375             * if the user has been authenticated, 
376             * or null if the user has not been authenticated. 
377             * Whether the user name is sent with each subsequent request depends 
378             * on the browser and type of authentication. 
379             * Same as the value of the CGI variable REMOTE_USER.
380             * @param remoteUser
381             */
382            public void setRemoteUser(String remoteUser) {
383                    this.remoteUser = remoteUser;
384            }
385            
386            /**
387             * @see javax.servlet.http.HttpServletRequest#isUserInRole(java.lang.String)
388             */
389            public boolean isUserInRole(String role) {
390                    // TODO impl
391                    return false;
392            }
393            
394            /**
395             * @see javax.servlet.http.HttpServletRequest#getUserPrincipal()
396             */
397            public Principal getUserPrincipal() {
398                     //TODO impl
399                    return null;
400            }
401            
402            /**
403             * @see javax.servlet.http.HttpServletRequest#getRequestedSessionId()
404             */
405            public String getRequestedSessionId() {
406                    return requestedSessionId;
407            }
408            
409            /**
410             * sets the session ID specified by the client. 
411             * This may not be the same as the ID of the actual session in use. 
412             * For example, if the request specified an old (expired) session ID 
413             * and the server has started a new session, 
414             * this method gets a new session with a new ID. 
415             * @param requestedSessionId
416             */
417            public void setRequestedSessionId(String requestedSessionId) {
418                    this.requestedSessionId = requestedSessionId;
419            }
420            
421            /**
422             * @see javax.servlet.http.HttpServletRequest#getRequestURI()
423             */
424            public String getRequestURI() {
425                    return requestURI;
426            }
427    
428            /**
429             * sets the part of this request's URL from the protocol name 
430             * up to the query string in the first line of the HTTP request. 
431             * The web container does not decode this String.
432             * @param requestURI
433             */
434            public void setRequestURI(String requestURI) {
435                    this.requestURI = requestURI;
436            }
437            
438            /**
439             * @see javax.servlet.http.HttpServletRequest#getRequestURL()
440             */
441            public StringBuffer getRequestURL() {
442                    return new StringBuffer(isSecure()?"https":"http").
443                            append("://").
444                            append(serverName).
445                            append(':').
446                            append(port).
447                            append('/').
448                            append(requestURI);
449            }
450            
451            /**
452             * @see javax.servlet.http.HttpServletRequest#getServletPath()
453             */
454            public String getServletPath() {
455                    // TODO when different ?
456                    return requestURI;
457            }
458            /**
459             * @see javax.servlet.http.HttpServletRequest#getSession(boolean)
460             */
461            public HttpSession getSession(boolean arg0) {
462                    return session;
463            }
464            /**
465             * @see javax.servlet.http.HttpServletRequest#getSession()
466             */
467            public HttpSession getSession() {
468                    return getSession(true);
469            }
470            /**
471             * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdValid()
472             */
473            public boolean isRequestedSessionIdValid() {
474    //               not supported
475                    return false;
476            }
477            /**
478             * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromCookie()
479             */
480            public boolean isRequestedSessionIdFromCookie() {
481    //               not supported
482                    return false;
483            }
484            /**
485             * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromURL()
486             */
487            public boolean isRequestedSessionIdFromURL() {
488    //               not supported
489                    return false;
490            }
491            /**
492             * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromUrl()
493             */
494            public boolean isRequestedSessionIdFromUrl() {
495                    return isRequestedSessionIdFromURL();
496            }
497            /**
498             * @see javax.servlet.ServletRequest#getAttribute(java.lang.String)
499             */
500            public Object getAttribute(String key) {
501                    return attributes.get(key,null);
502            }
503            
504            /**
505             * @see javax.servlet.ServletRequest#setAttribute(java.lang.String, java.lang.Object)
506             */
507            public void setAttribute(String key, Object value) {
508                    attributes.setEL(key,value);
509            }
510            
511            /**
512             * @see javax.servlet.ServletRequest#removeAttribute(java.lang.String)
513             */
514            public void removeAttribute(String key) {
515                    attributes.removeEL(KeyImpl.init(key));
516            }
517            
518            /**
519             * @see javax.servlet.ServletRequest#getAttributeNames()
520             */
521            public Enumeration getAttributeNames() {
522                    return new EnumerationWrapper(attributes.keyIterator());
523            }
524            /**
525             * @see javax.servlet.ServletRequest#getCharacterEncoding()
526             */
527            public String getCharacterEncoding() {
528                    return characterEncoding;
529            }
530            /**
531             * @see javax.servlet.ServletRequest#setCharacterEncoding(java.lang.String)
532             */
533            public void setCharacterEncoding(String characterEncoding)
534                            throws UnsupportedEncodingException {
535                    this.characterEncoding=characterEncoding;
536            }
537            /**
538             * @see javax.servlet.ServletRequest#getContentLength()
539             */
540            public int getContentLength() {
541                    return -1;
542            }
543            /**
544             * @see javax.servlet.ServletRequest#getContentType()
545             */
546            public String getContentType() {
547                    return contentType;
548            }
549            
550            /**
551             * sets the content Type of the Request
552             * @param contentType
553             */
554            public void setContentType(String contentType) {
555                    this.contentType=contentType;
556            }
557            
558            /**
559             * @see javax.servlet.ServletRequest#getInputStream()
560             */
561            public ServletInputStream getInputStream() throws IOException {
562                    return new ServletInputStreamDummy(inputData);
563            }
564    
565            public void setParameter(String key,String value) {
566                    parameters=ReqRspUtil.set(parameters,key,value);
567                    rewriteQS();
568            }
569    
570            public void addParameter(String key,String value) {
571                    parameters=ReqRspUtil.add(parameters,key,value);
572                    rewriteQS();
573            }
574            
575            /**
576             * @see javax.servlet.ServletRequest#getParameter(java.lang.String)
577             */
578            public String getParameter(String key) {
579                    return ReqRspUtil.get(parameters,key);
580            }
581            
582            /**
583             * @see javax.servlet.ServletRequest#getParameterValues(java.lang.String)
584             */
585            public String[] getParameterValues(String key) {
586                    ArrayList list=new ArrayList();
587                    for(int i=0;i<parameters.length;i++) {
588                            if(parameters[i].getName().equalsIgnoreCase(key))
589                                    list.add(Caster.toString(parameters[i].getValue(),null));
590                    }
591                    return (String[]) list.toArray(new String[list.size()]);
592            }
593            
594            /**
595             * @see javax.servlet.ServletRequest#getParameterNames()
596             */
597            public Enumeration getParameterNames() {
598                    HashSet set=new HashSet();
599                    for(int i=0;i<parameters.length;i++) {
600                            set.add(parameters[i].getName());
601                    }
602                    return new EnumerationWrapper(set);
603            }
604            
605            /**
606             * @see javax.servlet.ServletRequest#getParameterMap()
607             */
608            public Map getParameterMap() {
609                    Map p=new HashTable(); 
610                    for(int i=0;i<parameters.length;i++) {
611                            p.put(parameters[i].getName(), parameters[i].getValue());
612                    }
613                    return p;
614            }
615    
616            /**
617             * set the Protocol (Default "http")
618             * @param protocol
619             */
620            public void setProtocol(String protocol) {
621                    this.protocol=protocol;
622            }
623            
624            /**
625             * @see javax.servlet.ServletRequest#getProtocol()
626             */
627            public String getProtocol() {
628                    return protocol;
629            }
630            
631            /**
632             * @see javax.servlet.ServletRequest#getScheme()
633             */
634            public String getScheme() {
635                    return scheme;
636            }
637            
638            /**
639             * @see javax.servlet.ServletRequest#getScheme()
640             */
641            public void setScheme(String scheme) {
642                    this.scheme=scheme;
643            }
644            
645            /**
646             * @see javax.servlet.ServletRequest#getServerName()
647             */
648            public String getServerName() {
649                    return serverName;
650            }
651            
652            /**
653             * @see javax.servlet.ServletRequest#getServerPort()
654             */
655            public int getServerPort() {
656                    return port;
657            }       
658            
659            /**
660             * @param port The port to set.
661             */
662            public void setServerPort(int port) {
663                    this.port = port;
664            }
665            
666        /**
667         * @see javax.servlet.ServletRequest#getReader()
668         */
669        public BufferedReader getReader() throws IOException {
670            return IOUtil.toBufferedReader(IOUtil.getReader(getInputStream(),"ISO-8859-1"));
671        }
672    
673            /**
674             * @see javax.servlet.ServletRequest#getRemoteAddr()
675             */
676            public String getRemoteAddr() {
677                    return remoteAddr;
678            }
679    
680            public void setRemoteAddr(String remoteAddr) {
681                    this.remoteAddr=remoteAddr;
682            }
683            public void setRemoteHost(String remoteHost) {
684                    this.remoteHost=remoteHost;
685            }
686            
687            /**
688             * @see javax.servlet.ServletRequest#getRemoteHost()
689             */
690            public String getRemoteHost() {
691                    return remoteHost;
692            }
693            
694            public void setRemoteInetAddress(InetAddress ia) {
695                    setRemoteAddr(ia.getHostAddress());
696                    setRemoteHost(ia.getHostName());
697            }
698            
699            /**
700             * @see javax.servlet.ServletRequest#getLocale()
701             */
702            public Locale getLocale() {
703                    return locale;
704            }
705            
706            public void setLocale(Locale locale) {
707                    this.locale=locale;
708            }
709            
710            /**
711             * @see javax.servlet.ServletRequest#getLocales()
712             */
713            public Enumeration getLocales() {
714                    return new EnumerationWrapper(Locale.getAvailableLocales());
715            }
716            
717            /**
718             * @see javax.servlet.ServletRequest#isSecure()
719             */
720            public boolean isSecure() {
721                    return secure;
722            }
723            
724            public void setSecure(boolean secure) {
725                    this.secure=secure;
726            }
727            
728            /**
729             * @see javax.servlet.ServletRequest#getRequestDispatcher(java.lang.String)
730             */
731            public RequestDispatcher getRequestDispatcher(String arg0) {
732                    return new RequestDispatcherDummy(this);
733            }
734            
735            /**
736             * @see javax.servlet.ServletRequest#getRealPath(java.lang.String)
737             */
738            public String getRealPath(String path) {
739                    return contextRoot.getReal(path);
740            }
741    
742            /**
743             * @return the inputData
744             */
745            public byte[] getInputData() {
746                    return inputData;
747            }
748            /**
749             * @param inputData the inputData to set
750             */
751            public void setInputData(byte[] inputData) {
752                    this.inputData = inputData;
753            }
754    
755            private void rewriteQS() {
756                    StringBuffer qs=new StringBuffer();
757                    Pair p;
758                    for(int i=0;i<parameters.length;i++) {
759                            if(i>0) qs.append('&');
760                            p=parameters[i];
761                            qs.append(p.getName());
762                            qs.append('=');
763                            qs.append(Caster.toString(p.getValue(),""));
764                    }
765                    queryString=qs.toString();
766            }
767            public void setSession(HttpSession session) {
768                    this.session=session;
769            }
770            public static HttpServletRequestDummy clone(Config config,Resource rootDirectory,HttpServletRequest req) {
771    
772                    HttpServletRequestDummy dest = new HttpServletRequestDummy(
773                                    rootDirectory,
774                                    req.getServerName(),
775                                    req.getRequestURI(),
776                                    req.getQueryString(),
777                                    HttpUtil.cloneCookies(config,req),
778                                    HttpUtil.cloneHeaders(req),
779                                    HttpUtil.cloneParameters(req),
780                                    HttpUtil.getAttributesAsStruct(req),
781                                    getSessionEL(req)
782                            );
783                    
784    
785                    try {
786                            dest.setCharacterEncoding(req.getCharacterEncoding());
787                    } catch (Exception e) {
788                            
789                    }
790                    
791                    dest.setRemoteAddr(req.getRemoteAddr());
792                    dest.setRemoteHost(req.getRemoteHost());
793                    dest.setAuthType(req.getAuthType());
794                    dest.setContentType(req.getContentType());
795                    dest.setContextPath(req.getContextPath());
796                    dest.setLocale(req.getLocale());
797                    dest.setMethod(req.getMethod());
798                    dest.setPathInfo(req.getPathInfo());
799                    dest.setProtocol(req.getProtocol());
800                    dest.setRequestedSessionId(req.getRequestedSessionId());
801                    dest.setScheme(req.getScheme());
802                    dest.setServerPort(req.getServerPort());
803                    dest.setSession(getSessionEL(req));
804                    return dest;
805            }
806            private static HttpSession getSessionEL(HttpServletRequest req) {
807                    try{
808                            return req.getSession();
809                    }
810                    catch(Throwable t){}
811                    return null;
812            }
813            public void setAttributes(Struct attributes) {
814                    this.attributes=attributes;
815            }
816            
817    }