001    /**
002     * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portal.kernel.util;
016    
017    import com.liferay.portal.kernel.servlet.ServletVersionDetector;
018    
019    import javax.portlet.PortletRequest;
020    
021    import javax.servlet.ServletContext;
022    import javax.servlet.http.HttpServletRequest;
023    
024    /**
025     * @author Igor Spasic
026     * @author Brian Wing Shun Chan
027     */
028    public class ContextPathUtil {
029    
030            public static String getContextPath(HttpServletRequest request) {
031                    return getContextPath(request.getContextPath());
032            }
033    
034            public static String getContextPath(PortletRequest portletRequest) {
035                    return getContextPath(portletRequest.getContextPath());
036            }
037    
038            public static String getContextPath(ServletContext servletContext) {
039                    String contextPath = null;
040    
041                    if (ServletVersionDetector.is2_5()) {
042                            contextPath = servletContext.getContextPath();
043                    }
044                    else {
045                            contextPath = (String)servletContext.getAttribute(WebKeys.CTX_PATH);
046    
047                            if (contextPath == null) {
048                                    contextPath = servletContext.getServletContextName();
049                            }
050                    }
051    
052                    return getContextPath(contextPath);
053            }
054    
055            public static String getContextPath(String contextPath) {
056                    contextPath = GetterUtil.getString(contextPath);
057    
058                    if ((contextPath.length() == 0) ||
059                            contextPath.equals(StringPool.SLASH)) {
060    
061                            contextPath = StringPool.BLANK;
062                    }
063                    else if (!contextPath.startsWith(StringPool.SLASH)) {
064                            contextPath = StringPool.SLASH.concat(contextPath);
065                    }
066    
067                    return contextPath;
068            }
069    
070    }