001/*
002 *  Copyright 2014 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.plugins.proxiedcontent;
017
018import java.util.regex.Matcher;
019import java.util.regex.Pattern;
020
021/**
022 * Utility class
023 */
024public final class Utils
025{
026    private static Pattern _pattern = Pattern.compile("(https?://[^/]*).*");
027    
028    private Utils()
029    {
030        // utility class
031    }
032
033    /**
034     * Normalize URL
035     * @param url The url
036     * @return The normalized URL
037     */
038    static String normalizeUrl(String url)
039    {
040        String checkedUrl = url;
041        
042        if (!"".equals(url) && !url.startsWith("https://") && !url.startsWith("http://"))
043        {
044            checkedUrl = "http://" + url;
045        }
046        
047        if (checkedUrl != null && checkedUrl.endsWith("/"))
048        {
049            checkedUrl = checkedUrl.substring(0, checkedUrl.lastIndexOf("/"));
050        }
051        
052        return checkedUrl;
053    }
054    
055    /**
056     * Get the remote host from the given url
057     * @param url the url
058     * @return the remote host or empty if url does not match
059     */
060    static String getRemoteHostFromUrl(String url)
061    {
062        String remoteHost = "";
063        
064        Matcher matcher = _pattern.matcher(url);
065        
066        if (matcher.matches())
067        {
068            remoteHost = matcher.group(1);
069        }
070        
071        return remoteHost;
072    }
073}