001/* 002 * Copyright 2013 Anyware Services 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.ametys.cms; 017 018import org.apache.avalon.framework.component.Component; 019import org.apache.avalon.framework.context.Context; 020import org.apache.avalon.framework.context.ContextException; 021import org.apache.avalon.framework.context.Contextualizable; 022import org.apache.cocoon.components.ContextHelper; 023import org.apache.cocoon.environment.Request; 024import org.apache.commons.lang.StringUtils; 025 026import org.ametys.runtime.workspace.WorkspaceMatcher; 027 028/** 029 * Component providing base paths for computing URIs. 030 */ 031public class URIPrefixHandler implements Contextualizable, Component 032{ 033 /** Avalon role */ 034 public static final String ROLE = URIPrefixHandler.class.getName(); 035 036 /** The request attribute name holding the current URL prefix */ 037 public static final String PATH_PREFIX = "path-prefix"; 038 039 /** The avalon context */ 040 protected Context _context; 041 042 @Override 043 public void contextualize(Context context) throws ContextException 044 { 045 _context = context; 046 } 047 048 /** 049 * Get the application context path. Can be empty if the application 050 * resides in the root context. Use it to create a link beginning with 051 * the application root. 052 * @return The application context path. 053 * @see Request#getContextPath() 054 */ 055 public String getUriPrefix() 056 { 057 Request request = ContextHelper.getRequest(_context); 058 String prefix = (String) request.getAttribute(PATH_PREFIX); 059 String workspaceURI = (String) request.getAttribute(WorkspaceMatcher.WORKSPACE_URI); 060 061 return request.getContextPath() + workspaceURI + StringUtils.trimToEmpty(prefix); 062 } 063 064 /** 065 * Get the absolutized version of the context path. Use it to create an absolute 066 * link beginning with the application root, for instance when sending a mail 067 * linking to the application. 068 * @return The absolute context path. 069 */ 070 public String getAbsoluteUriPrefix() 071 { 072 Request request = ContextHelper.getRequest(_context); 073 074 String uriPrefix = getUriPrefix(); 075 if (!uriPrefix.startsWith("http")) 076 { 077 uriPrefix = request.getScheme() + "://" + request.getServerName() + (request.getServerPort() != 80 ? ":" + request.getServerPort() : "") + uriPrefix; 078 } 079 080 return uriPrefix; 081 } 082}