001// Copyright 2004, 2005 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
015package org.apache.tapestry.services.impl;
016
017import org.apache.tapestry.services.AbsoluteURLBuilder;
018import org.apache.tapestry.web.WebRequest;
019
020/**
021 * @author Howard M. Lewis Ship
022 * @since 4.0
023 */
024public class AbsoluteURLBuilderImpl implements AbsoluteURLBuilder
025{
026    private WebRequest _request;
027
028    public String constructURL(String URI, String scheme, String server, int port)
029    {
030        // Though, really, what does a leading colon with no scheme before it
031        // mean?
032
033        if (URI.indexOf(':') >= 0)
034            return URI;
035
036        StringBuffer buffer = new StringBuffer();
037
038        // Should check the length here, first.
039
040        if (URI.length()> 2 && URI.substring(0, 2).equals("//"))
041        {
042            buffer.append(scheme);
043            buffer.append(':');
044            buffer.append(URI);
045            return buffer.toString();
046        }
047
048        buffer.append(scheme);
049        buffer.append("://");
050        buffer.append(server);
051
052        if (port > 0)
053        {
054            buffer.append(':');
055            buffer.append(port);
056        }
057
058        if (URI.charAt(0) != '/')
059            buffer.append('/');
060
061        buffer.append(URI);
062
063        return buffer.toString();
064    }
065
066    public String constructURL(String URI)
067    {
068        String scheme = _request.getScheme();
069        String server = _request.getServerName();
070        int port = _request.getServerPort();
071
072        // Keep things simple ... port 80 is accepted as the
073        // standard port for http so it can be ommitted.
074        // Some of the Tomcat code indicates that port 443 is the default
075        // for https, and that needs to be researched.
076
077        if (scheme.equals("http") && port == 80)
078            port = 0;
079
080        return constructURL(URI, scheme, server, port);
081    }
082
083    public void setRequest(WebRequest request)
084    {
085        _request = request;
086    }
087}