KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mmbase > util > scanpage


1 /*
2
3 This software is OSI Certified Open Source Software.
4 OSI Certified is a certification mark of the Open Source Initiative.
5
6 The license (Mozilla version 1.0) can be read at the MMBase site.
7 See http://www.MMBase.org/license
8
9 */

10 package org.mmbase.util;
11
12 import java.net.InetAddress JavaDoc;
13 import java.net.UnknownHostException JavaDoc;
14 import java.util.Vector JavaDoc;
15
16 import javax.servlet.ServletConfig JavaDoc;
17 import javax.servlet.ServletContext JavaDoc;
18 import javax.servlet.http.HttpServletRequest JavaDoc;
19 import javax.servlet.http.HttpServletResponse JavaDoc;
20
21 import org.mmbase.module.ProcessorInterface;
22 import org.mmbase.module.sessionInfo;
23 import org.mmbase.module.sessionsInterface;
24 import org.mmbase.servlet.JamesServlet;
25 import org.mmbase.util.logging.Logger;
26 import org.mmbase.util.logging.Logging;
27
28 /**
29  * The scanpage is a container class.
30  * It holds all information that is needed to identify a user, including
31  * servlet objects and MMBase session information.
32  * It was introduced to make {@link org.mmbase.servlet.servscan} threadsafe but will probably in the future
33  * hold all request related information, because we want to extend the model
34  * of offline page generation.
35  *
36  * @application SCAN, this class will be troubelsome to move as it is used in MMObjectBuilder and ProcessorModule
37  * @rename ScanPage
38  * @author Daniel Ockeloen
39  * @version $Id: scanpage.java,v 1.29 2006/03/09 16:38:36 michiel Exp $
40  */

41 public class scanpage extends PageInfo {
42     // logger
43
private static Logger log = Logging.getLoggerInstance(scanpage.class.getName());
44
45     /**
46      * The parameters of this page.
47      * These are either set mnaually using {@link #setParamsVector}, or
48      * determined from the page using the {@link #req} field
49      */

50     public Vector JavaDoc params;
51     /**
52      * The processor set for this page.
53      * This values is set and used by scanparser to determine the default
54      * processor to call when interpreting LIST tags.
55      */

56     public ProcessorInterface processor;
57     /**
58      * Object for accessing values sent by a form using
59      * enctype multipart/form-data.
60      */

61     public HttpPost poster;
62     /**
63      * The user's MMBase session object, if available.
64      */

65     public sessionInfo session=null;
66     /**
67      * The session name.
68      */

69     public String JavaDoc sname=null;
70
71     public String JavaDoc name=null;
72     public int rstatus=0;
73     public String JavaDoc body;
74     public String JavaDoc req_line;
75     public String JavaDoc wantCache=null;
76     public String JavaDoc mimetype=null;
77     public String JavaDoc querystring=null;
78     public int partlevel=0;
79     public String JavaDoc loadmode="cache";
80     /**
81      * Indicates whether elements sucha s 'multilevel' should be reloaded, or
82      * whether results stored in cache should be used.
83      */

84     public boolean reload=false;
85
86     /**
87      * Empty constructor for code not yet fixed, constructing its own scanpage
88      * Should use new constructor if possible.
89      */

90     public scanpage() {}
91
92     /**
93      * Construct a scanpage for a servlet
94      */

95     public scanpage(JamesServlet servlet, HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res, sessionsInterface sessions) {
96         super(req,res);
97         req_line = req.getServletPath();
98         querystring = req.getQueryString();
99
100         // needs to be replaced (get the context ones)
101
ServletConfig JavaDoc sc = servlet.getServletConfig();
102         ServletContext JavaDoc sx = sc.getServletContext();
103         mimetype = sx.getMimeType(req_line);
104         if (mimetype==null) mimetype = "text/html";
105
106         sname = servlet.getCookie(req, res);
107         if (sessions != null) session = sessions.getSession(this, sname);
108         CheckEditorReload();
109     }
110
111     /**
112      * Check whether the page, multilevels etc may be fetched from the caches
113      * or they should be (re-)calculated/retrieved. The session variable RELOAD
114      * will be checked, if it contains the value "R" and the sessionvariable
115      * RELOADTIME contains a time less than the const EXPIRE seconds ago, then
116      * the request for reload will be honoured.
117      * @return the method returns void and sets the field reload to true or false
118      */

119     private final static int EXPIRE = 120;
120
121     void CheckEditorReload() {
122         reload = false;
123         // try to obtain and set the reload mode.
124
if (session==null) return;
125         String JavaDoc s=session.getValue("RELOAD");
126         if ((s==null) || !s.equals("R")) return;
127         // check if it expired
128
s = session.getValue("RELOADTIME");
129         if (s!=null) {
130             try {
131                 int then=Integer.parseInt(s);
132                 int now= (int)(System.currentTimeMillis()/1000);
133                 if ((now-then)<EXPIRE) {
134                     reload = true;
135                     if (log.isDebugEnabled()) {
136                         log.debug("CheckEditorReload remote user:"+HttpAuth.getRemoteUser(req));
137                     }
138                 } else {
139                     if (log.isDebugEnabled()) log.debug("CheckEditorReload, reload expired for remote user:"+HttpAuth.getRemoteUser(req));
140                 }
141             } catch(Exception JavaDoc e) {}
142         }
143         if (!reload) session.setValue("RELOAD","N");
144     }
145
146     /**
147      * Sets the HttpServletRequest.
148      * This method is invoked either by the MMBase servlets, or through the MMCI.
149      */

150     public void setReq(HttpServletRequest JavaDoc req) {
151         setRequest(req);
152     }
153
154     /**
155      * Sets the HttpServletResponse.
156      * This method is invoked either by the MMBase servlets, or through the MMCI.
157      */

158     public void setRes(HttpServletResponse JavaDoc res) {
159         setResponse(res);
160     }
161
162     /**
163      * Get the parameter specified.
164      * @param num index of the parameter to retrieve
165      * @return the parametervalue
166      */

167     public String JavaDoc getParam(int num) {
168         String JavaDoc str;
169         if (params==null) {
170             params=buildparams();
171         }
172         try {
173             str=(String JavaDoc)params.elementAt(num);
174         } catch(IndexOutOfBoundsException JavaDoc e) {
175             str=null;
176         }
177         return str;
178     }
179
180
181     /**
182      * Parse the querystring of the current page to retrieve all paarmeters
183      * @return a <code>Vector</code> of parameter values
184      */

185     private Vector JavaDoc buildparams() {
186         Vector JavaDoc params=new Vector JavaDoc();
187         if (querystring!=null) {
188             String JavaDoc paramline=querystring;
189             //StringTokenizer tok=new StringTokenizer(querystring,"+\n\r",true);
190
int pos=paramline.indexOf("+");
191             while(pos!=-1) {
192                 params.addElement(paramline.substring(0,pos));
193                 paramline=paramline.substring(pos+1);
194                 pos=paramline.indexOf("+");
195             }
196             params.addElement(paramline);
197         }
198         return params;
199     }
200
201     /**
202      * Manually set the parameters of a page.
203      * @param params a <code>Vector</code> of parameter values
204      */

205     public boolean setParamsVector(Vector JavaDoc params) {
206         this.params=params;
207         return true;
208     }
209
210     /**
211      * Retrieve all parameters of a page.
212      * @return a <code>Vector</code> of parameter values
213      */

214     public Vector JavaDoc getParamsVector() {
215         if (params==null) params=buildparams();
216         if (params.size()==0) return null;
217         return params;
218     }
219
220
221     /**
222      * Manually set the parameterline of a page (as if it was a querystring).
223      * @param paramline a string containing teh parametervalues seperated by '+' characters
224      */

225     public boolean setParamsLine(String JavaDoc paramline) {
226         this.params=new Vector JavaDoc();
227         //StringTokenizer tok=new StringTokenizer(paramline,"+\n\r");
228
// rico
229
int pos=paramline.indexOf("+");
230         while(pos!=-1) {
231             params.addElement(paramline.substring(0,pos));
232             paramline=paramline.substring(pos+1);
233             pos=paramline.indexOf("+");
234         }
235         params.addElement(paramline);
236         return true;
237     }
238
239     /**
240      * Retrieve a HTTP request header, if available
241      * @param name the name of the header
242      * @return the header, <code>nul</code> if it can not be retrieved
243      */

244     public String JavaDoc getHeader(String JavaDoc name) {
245         if (req!=null) {
246             return req.getHeader(name);
247         } else {
248             return null;
249         }
250     }
251
252     /**
253      * Return the session name.
254      */

255     public String JavaDoc getSessionName() {
256         return sname;
257     }
258
259     /**
260      * Set the session name.
261      */

262     public void setSessionName(String JavaDoc name) {
263         this.sname=name;
264     }
265
266 // ------------------------------------------------------------------------------------------------------------
267

268     /**
269      * Return page URL and parameters
270      */

271     public String JavaDoc getUrl() {
272         String JavaDoc result = null;
273         if( req != null ) {
274             result = req.getRequestURI();
275             if( req.getQueryString() != null )
276                 result += "?" + req.getQueryString();
277             return result;
278         } else {
279             return null;
280         }
281     }
282
283 // ------------------------------------------------------------------------------------------------------------
284

285     private static String JavaDoc VPROProxyName = "vpro6d.vpro.nl"; // name of proxyserver
286
private static String JavaDoc VPROProxyAddress = "145.58.172.6"; // address of proxyserver
287

288     // methods
289
// -------
290

291     /**
292      * Extract hostname from scanpage, get address and determine the proxies between it.
293      * Needed to determine if user comes from internal or external host, because
294      * we use two streaming servers, one for external users and one for internal users.
295      * <br />
296      * input : scanpage sp, contains hostname as ipaddress<br />
297      * output : String "clientproxy.clientside.com->dialin07.clientside.com"<br />
298      * <br />
299      * uses : VPROProxyName, VPROProxyAddress
300      */

301     public String JavaDoc getAddress() {
302         String JavaDoc result = null;
303         boolean fromProxy = false;
304         String JavaDoc addr = req.getRemoteHost();
305
306         // check whether the user came through a proxy
307
// This code tests for a specific vpro proxy server
308
// should probably be made generic
309
// Not sure how to do this, maybe just test for X-Forwarded-For header?
310
if( addr != null && (addr.indexOf( VPROProxyName ) != -1 || addr.indexOf( VPROProxyAddress ) != -1 )) {
311             // get real address
312
fromProxy = true;
313             addr = req.getHeader("X-Forwarded-For");
314         }
315         if (addr != null) {
316             // get hostnames for this user
317
result = getHostNames( addr );
318
319             // extend the path with a proxy (?) server
320
// vpro specific server, so should be made generic
321
// (no idea how, maybe make configurable?)
322
if( fromProxy ) {
323                 result = "zen.vpro.nl->" + result;
324             }
325         }
326         return result;
327     }
328
329     /**
330      * Determine the host names of a String containing a comma-separated list of
331      * ip addresses and/or host names.
332      * Used to retrieve a list of proxies.
333      * @param host an comma-seperated String containing ip-addressed and/or host names
334      * @return a strong containing hostnames separated by "->" tokens
335      */

336     private String JavaDoc getHostNames(String JavaDoc host) {
337         String JavaDoc result = null;
338         String JavaDoc hn = null;
339         // comes client from his own proxy?
340
// --------------------------------
341
if( host.indexOf(",") != -1 ) {
342             int pos;
343             // filter and display the clientproxies
344
// ------------------------------------
345
while( (pos = host.indexOf(",")) != -1 ) {
346                 hn = host.substring( 0, pos );
347                 host = host.substring( pos + 2 );
348                 if( result == null )
349                     result = getHostName( hn );
350                 else
351                     result += "->" + getHostName( hn );
352             }
353             // which results in "proxy.clientside.com->dailin07.clientside.com"
354
} else {
355             result = getHostName( host );
356         }
357         return result;
358     }
359
360     /**
361      * Determine the host name of a passed ip address or host name.
362      * If the passed parameter is an IP-address, the hostname for
363      * that address is retrieved if possible.
364      * @param hostname an ip-address or host name
365      * @return the resulting hostname
366      */

367     private String JavaDoc getHostName( String JavaDoc hostname ) {
368         // if hostname == ipaddress, try to get a hostname for it
369
String JavaDoc hn = hostname;
370         if( hn != null && !hn.equals("")) {
371             try {
372                 hn = InetAddress.getByName( hostname ).getHostName();
373             } catch( UnknownHostException JavaDoc e) {
374             }
375         }
376         return hn;
377     }
378
379     /**
380      * Gets the referrer from the request header.
381      * @return a <code>String</code> with the referer,
382      * <code>null</code> when reqheader is <code>null</code>.
383      */

384     public String JavaDoc getReferer() {
385         if (req==null) {
386             log.error("scanpage:getReferer: req="+req+", can't get referer.");
387             return null;
388         } else {
389             return req.getHeader("Referer");
390         }
391     }
392
393     /**
394      * Creates a duplicate of this scanpage
395      * @return the duplicate scanpage
396      */

397     public scanpage duplicate() {
398         scanpage dup=new scanpage();
399         dup.res=null;
400         dup.req=null;
401         dup.params=null;
402         dup.processor=this.processor;
403         dup.session=this.session;
404         dup.sname=this.sname;
405         dup.name=this.name;
406         dup.rstatus=this.rstatus;
407         dup.body=this.body;
408         dup.req_line=this.req_line;
409         dup.wantCache=this.wantCache;
410         dup.mimetype=this.mimetype;
411         dup.querystring=this.querystring;
412         dup.partlevel=this.partlevel;
413         dup.loadmode=this.loadmode;
414         dup.reload=this.reload;
415         return dup;
416     }
417 }
418
Popular Tags