Java URL Sanitize sanitizeDefaultPort(String url)

Here you can find the source of sanitizeDefaultPort(String url)

Description

Removes the port from a URL if this port is the default one for the URL's scheme.

License

Open Source License

Parameter

Parameter Description
url the url to be sanitized.

Return

the sanitized url.

Declaration

public static String sanitizeDefaultPort(String url) 

Method Source Code

//package com.java2s;
/*//from  www.j  a va2 s .  c  o m
 * Copyright (C) 2015 Red Hat, inc., and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301  USA
 */

public class Main {
    /**
     * Removes the port from a URL if this port is the default one for the URL's scheme.
     * @param url the url to be sanitized.
     * @return  the sanitized url.
     */
    public static String sanitizeDefaultPort(String url) {
        int afterSchemeIndex = url.indexOf("://");
        if (afterSchemeIndex < 0) {
            return url;
        }
        String scheme = url.substring(0, afterSchemeIndex);
        int fromIndex = scheme.length() + 3;
        //Let's see if it is an IPv6 Address
        int ipv6StartIndex = url.indexOf('[', fromIndex);
        if (ipv6StartIndex > 0) {
            fromIndex = url.indexOf(']', ipv6StartIndex);
        }
        int portIndex = url.indexOf(':', fromIndex);
        if (portIndex >= 0) {
            int port = Integer.parseInt(url.substring(portIndex + 1));
            if (isDefaultPort(port, scheme)) {
                return url.substring(0, portIndex);
            }
        }
        return url;
    }

    private static boolean isDefaultPort(int port, String protocol) {
        return (("http".equals(protocol) && 80 == port) || ("https"
                .equals(protocol) && 443 == port));
    }
}

Related

  1. sanitizeCollabNetUrl(String url)
  2. sanitizeForNextUrl(String url)
  3. sanitizeUri(String uri)
  4. sanitizeUri(String uri)
  5. sanitizeURL(String url)