001    // Copyright 2008, 2010, 2011 The Apache Software Foundation
002    //
003    // Licensed under the Apache License, Version 2.0 (the "License");
004    // you may not use this file except in compliance with the License.
005    // You may obtain a copy of the License at
006    //
007    // http://www.apache.org/licenses/LICENSE-2.0
008    //
009    // Unless required by applicable law or agreed to in writing, software
010    // distributed under the License is distributed on an "AS IS" BASIS,
011    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012    // See the License for the specific language governing permissions and
013    // limitations under the License.
014    
015    package org.apache.tapestry5.internal.services;
016    
017    import org.apache.tapestry5.SymbolConstants;
018    import org.apache.tapestry5.ioc.annotations.Inject;
019    import org.apache.tapestry5.ioc.annotations.Symbol;
020    import org.apache.tapestry5.services.BaseURLSource;
021    import org.apache.tapestry5.services.Request;
022    
023    public class BaseURLSourceImpl implements BaseURLSource
024    {
025        private final Request request;
026        
027        private String hostname;
028        private int hostPort;
029        private int secureHostPort;
030    
031        public BaseURLSourceImpl(Request request, @Inject @Symbol(SymbolConstants.HOSTNAME) String hostname,
032                @Symbol(SymbolConstants.HOSTPORT) int hostPort, @Symbol(SymbolConstants.HOSTPORT_SECURE) int secureHostPort)
033        {
034            this.request = request;
035            this.hostname = hostname;
036            this.hostPort = hostPort;
037            this.secureHostPort = secureHostPort;
038        }
039    
040        public String getBaseURL(boolean secure)
041        {
042            int port = secure ? secureHostPort : hostPort;
043            String portSuffix = "";
044    
045            if (port <= 0) { 
046                port = request.getServerPort();
047                int schemeDefaultPort = request.isSecure() ? 443 : 80;
048                portSuffix = port == schemeDefaultPort ? "" : ":" + port;
049            }
050            else if (secure && port != 443) portSuffix = ":" + port;
051            else if (port != 80) portSuffix = ":" + port;
052            
053            String hostname = "".equals(this.hostname) ? request.getServerName() : this.hostname.startsWith("$") ? System.getenv(this.hostname.substring(1)) : this.hostname;
054            
055            return String.format("%s://%s%s", secure ? "https" : "http", hostname, portSuffix);
056        }
057    }