KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > jetspeed > services > webpage > WebPageHelper


1 /*
2  * Copyright 2000-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.apache.jetspeed.services.webpage;
18
19
20 // java.io
21
import java.io.IOException JavaDoc;
22 import java.io.FileOutputStream JavaDoc;
23
24 // java.util
25
import java.util.StringTokenizer JavaDoc;
26 import java.util.Date JavaDoc;
27 import java.text.SimpleDateFormat JavaDoc;
28
29 // java.net
30
import java.net.InetAddress JavaDoc;
31 import java.net.UnknownHostException JavaDoc;
32
33 // javax.servlet
34
import javax.servlet.http.Cookie JavaDoc;
35
36
37 /**
38  * Helper methods for WebPage Service
39  *
40  * @author <a HREF="mailto:taylor@apache.org">David Sean Taylor</a>
41  * @version $Id: WebPageHelper.java,v 1.3 2004/02/23 03:46:26 jford Exp $
42  */

43 public class WebPageHelper
44 {
45     
46     public static final int CT_TEXT = 0;
47     public static final int CT_BINARY = 1;
48     public static final int CT_APPLICATION = 2;
49     public static final int CT_HTML = 3;
50     public static final int CT_IMAGE = 4;
51     public static final int CT_CSS = 5;
52     public static final int CT_JS = 6;
53
54
55     /**
56      * Given the content-type header string, returns a content type id
57      *
58      * @param typeString the http content-type header string.
59      * @return the integer value of the content-type
60      */

61
62     public static int getContentType(String JavaDoc typeString, String JavaDoc resource)
63     {
64         int contentType = CT_HTML;
65
66         if (null == typeString) {
67
68             if (null == resource)
69             {
70                 return contentType;
71             }
72
73             if (resource.endsWith(".js"))
74             {
75                 return CT_JS;
76             }
77             else if (resource.endsWith(".gif") ||
78                      resource.endsWith(".jpg") ||
79                      resource.endsWith(".png"))
80             {
81                 return CT_IMAGE;
82             }
83             else if (resource.endsWith(".css") )
84             {
85                 return CT_CSS;
86             }
87             return contentType;
88         }
89         if (typeString.equalsIgnoreCase("text/html"))
90             contentType = CT_HTML;
91         else if (typeString.startsWith("image"))
92             contentType = CT_IMAGE;
93         else if (typeString.startsWith("text/css"))
94             contentType = CT_CSS;
95         else if (typeString.startsWith("text"))
96             contentType = CT_TEXT;
97         else if (typeString.startsWith("binary"))
98             contentType = CT_BINARY;
99         else if (typeString.equals("application/x-javascript") )
100             contentType = CT_JS;
101         else if (typeString.startsWith("application"))
102             contentType = CT_APPLICATION;
103
104         return contentType;
105     }
106
107
108     /**
109      * Given a cookie object, build a http-compliant cookie string header
110      *
111      * @param Cookie the cookie source object.
112      * @return the cookie string formatted as a http header.
113      *
114      */

115     public static String JavaDoc buildCookieString(Cookie JavaDoc cookie)
116     {
117         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
118
119         int version = cookie.getVersion();
120         if (version != -1) {
121            buffer.append("$Version=\"");
122            buffer.append(cookie.getVersion());
123            buffer.append("\"; ");
124         }
125         // cookie name/value
126
buffer.append(cookie.getName());
127         //buffer.append("=\"");
128
buffer.append("=");
129         buffer.append(cookie.getValue());
130         //buffer.append("\"; ");
131

132         // cookie path
133
String JavaDoc path = cookie.getPath();
134         if (path != null) {
135             //buffer.append("path=\""); // $Path
136
buffer.append("; path=");
137             buffer.append(path);
138             //buffer.append("\"");
139
}
140
141         String JavaDoc cookieHeader = buffer.toString();
142
143         return cookieHeader;
144     }
145
146    /**
147      * Parses cookies from the HTTP response header string
148      * and stores them into this instance's cookies collection
149      *
150      * @param cookieHeader the string from the response header with the cookies.
151      * @return true when cookies were found, otherwise false
152      *
153      */

154
155     public static boolean parseCookies(String JavaDoc cookieHeader, SiteSession session)
156     {
157         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(cookieHeader, " =;");
158         String JavaDoc token, value;
159         boolean firstTime = true; // cookie name/value always comes first
160
Cookie JavaDoc cookie = null;
161
162         while (st.hasMoreTokens())
163         {
164             token = st.nextToken();
165             if (firstTime) {
166                 value = st.nextToken();
167                 cookie = new Cookie JavaDoc(token, value);
168                 cookie.setVersion(-1);
169                 firstTime = false;
170             }
171             else if (token.equalsIgnoreCase("path")) {
172                 cookie.setPath(st.nextToken());
173             }
174             else if (token.equalsIgnoreCase("version")) {
175                 cookie.setVersion(Integer.getInteger(st.nextToken()).intValue());
176             }
177             else if (token.equalsIgnoreCase("max-age")) {
178                 cookie.setMaxAge( Integer.getInteger(st.nextToken()).intValue() );
179             }
180             else if (token.equalsIgnoreCase("domain")) {
181                 cookie.setDomain( st.nextToken() );
182             }
183             else if (token.equalsIgnoreCase("secure")) {
184                 cookie.setSecure(true);
185             }
186             else
187             {
188                 if (null != cookie)
189                     session.addCookieToSession(cookie);
190                 if (!st.hasMoreTokens()) {
191                     break;
192                 }
193                 value = st.nextToken();
194                 cookie = new Cookie JavaDoc(token, value);
195                 cookie.setVersion(-1);
196            }
197         }
198         if (null != cookie)
199            session.addCookieToSession(cookie);
200
201         return (null != cookie); // found a cookie
202
}
203
204     /**
205      * given a stringbuffer, replaces 'find' with 'replacement'
206      *
207      * @param buffer the string to be manipulated.
208      * @param find the string to be replaced.
209      * @param replacement the string that is put in place.
210      *
211      */

212     public static StringBuffer JavaDoc replaceAll(StringBuffer JavaDoc buffer,
213                                           String JavaDoc find,
214                                           String JavaDoc replacement)
215     {
216
217         int bufidx = buffer.length() - 1;
218         int offset = find.length();
219         while( bufidx > -1 ) {
220             int findidx = offset -1;
221             while( findidx > -1 ) {
222                 if( bufidx == -1 ) {
223                     //Done
224
return buffer;
225                 }
226                 if( buffer.charAt( bufidx ) == find.charAt( findidx ) ) {
227                     findidx--; //Look for next char
228
bufidx--;
229                 } else {
230                     findidx = offset - 1; //Start looking again
231
bufidx--;
232                     if( bufidx == -1 ) {
233                         //Done
234
return buffer;
235                     }
236                     continue;
237                 }
238             }
239             buffer.replace( bufidx+1,
240                             bufidx+1+offset,
241                             replacement);
242             //start looking again
243
}
244         //No more matches
245
return buffer;
246             
247     }
248
249     /**
250      * Given a base string and a path string, concatenates the strings to make a full URL.
251      * Handles the concatenation for proper path separators.
252      *
253      * @param base the base part of a URL, such as http://localhost/
254      * @param path the path part of the url, such as /webinterface/controllers/x.php
255      * @param the concatenated path, such as http://localhost/webinterface/controllers/x.php
256      *
257      */

258     public static String JavaDoc concatURLs(String JavaDoc base, String JavaDoc path)
259     {
260         String JavaDoc result = "";
261         if (base.endsWith("/"))
262         {
263             if (path.startsWith("/"))
264             {
265                 result = base.concat( path.substring(1));
266                 return result;
267             }
268             
269         }
270         else
271         {
272             if (!path.startsWith("/"))
273             {
274                 result = base.concat("/").concat(path);
275                 return result;
276             }
277         }
278         return base.concat(path);
279     }
280
281     /*
282      * Maps the availability status code to a small string message
283      *
284      * @param status the integer availability status code.
285      * @return the corresponding string message for the status code.
286      */

287     public static String JavaDoc getAvailabilityStatus(int status)
288     {
289         switch(status)
290         {
291         case 0: return "Not Initialized";
292         case 1: return "Online";
293         default: return "Offline";
294         }
295     }
296
297
298     /*
299      * Writes the date/time stamp header to the content log.
300      *
301      * @param fos The file output stream that is written to (the content log).
302      *
303      */

304     private static final String JavaDoc DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";
305     private static final String JavaDoc CONTENT_LOG_HEADER =
306         "------------------------------------------------------" ;
307
308     public static void writeHeader(FileOutputStream JavaDoc fos, String JavaDoc resource)
309         throws IOException JavaDoc
310     {
311         fos.write(13);
312         fos.write(10);
313         fos.write(CONTENT_LOG_HEADER.getBytes());
314         fos.write(13);
315         fos.write(10);
316         SimpleDateFormat JavaDoc sdf = new SimpleDateFormat JavaDoc(DATE_PATTERN);
317         fos.write(sdf.format(new Date JavaDoc()).getBytes());
318         fos.write(13);
319         fos.write(10);
320         fos.write(resource.getBytes());
321         fos.write(13);
322         fos.write(10);
323     }
324
325     /*
326      * Gets the IP address for a given hostname.
327      *
328      * @param hostname The hostname that we are looking up the IP address for.
329      * @return The IP address of the given hostname.
330      */

331     public static String JavaDoc getIP(String JavaDoc hostname)
332     {
333         String JavaDoc ip = null;
334
335         try
336         {
337             InetAddress JavaDoc computer = InetAddress.getByName(hostname);
338             ip = computer.getHostAddress();
339         }
340         catch (UnknownHostException JavaDoc ex)
341         {
342         }
343         return ip;
344     }
345
346     private static int id = 0;
347     
348     public static synchronized long generateId()
349     {
350         id = id + 1;
351         return id;
352     }
353 }
354
Popular Tags