KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openbravo > base > HttpBaseUtils


1 /*
2  ************************************************************************************
3  * Copyright (C) 2001-2006 Openbravo S.L.
4  * Licensed under the Apache Software License version 2.0
5  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
6  * Unless required by applicable law or agreed to in writing, software distributed
7  * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
8  * CONDITIONS OF ANY KIND, either express or implied. See the License for the
9  * specific language governing permissions and limitations under the License.
10  ************************************************************************************
11 */

12 package org.openbravo.base;
13
14 import javax.servlet.ServletException JavaDoc;
15 import javax.servlet.http.HttpServletRequest JavaDoc;
16 import org.apache.log4j.Logger;
17
18 public class HttpBaseUtils {
19   public static Logger log4j = Logger.getLogger(HttpBaseUtils.class);
20
21   /** Creates a new instance of LoginUtils */
22   private HttpBaseUtils() {
23   }
24
25   public static String JavaDoc getLocalHostAddress(HttpServletRequest JavaDoc request) {
26     return getLocalHostAddress(request, false);
27   }
28
29   public static String JavaDoc getLocalHostAddress(HttpServletRequest JavaDoc request, boolean includePort) {
30     String JavaDoc scheme = request.getScheme();
31     String JavaDoc serverName = request.getServerName();
32     String JavaDoc port = "";
33     if (includePort) {
34       int p = request.getServerPort();
35       port = (p == 80) ? "" : ":" + p;
36     }
37     return scheme + "://" + serverName + port;
38   }
39
40   public static String JavaDoc getLocalAddress(HttpServletRequest JavaDoc request) {
41     // reads local address
42
String JavaDoc host = getLocalHostAddress(request, true);
43     return host + request.getContextPath();
44   }
45   
46   public static String JavaDoc getRelativeUrl(HttpServletRequest JavaDoc request, String JavaDoc url) {
47     if (!url.startsWith(getLocalHostAddress(request, true) + "/")) return url;
48     url = url.replace((getLocalHostAddress(request, true) + "/"), "");
49     String JavaDoc actualServlet = request.getContextPath() + request.getServletPath();
50     if (actualServlet.startsWith("/")) actualServlet = actualServlet.substring(1);
51     int i = actualServlet.indexOf("/");
52     while (i!=-1) {
53       if (url.startsWith(actualServlet.substring(0, i))) url = url.replace(actualServlet.substring(0, i+1), "");
54       else url = "../" + url;
55       actualServlet = actualServlet.substring(i+1);
56       i = actualServlet.indexOf("/");
57     }
58     return url;
59   }
60 }
61
Popular Tags