001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
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    }