Java URI Normalize normalizeLink(String link, URI parent, boolean removeParams)

Here you can find the source of normalizeLink(String link, URI parent, boolean removeParams)

Description

Normalizes a link: removes all redundant spaces and parameters.

License

Open Source License

Parameter

Parameter Description
link absolute or relative link
parent parent URI. Can be null
removeParams if true then parameters and anchor tags will be removed from URI

Return

Returns normalized URI

Declaration

public static URI normalizeLink(String link, URI parent, boolean removeParams) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.net.URI;
import java.net.URISyntaxException;

public class Main {
    /**/*from   w w  w  .j a v a 2  s  .  com*/
     * Normalizes a link: removes all redundant spaces and parameters.
     * Uses parent URI to resolve relative links.
     * @param link absolute or relative link
     * @param parent parent URI. Can be null
     * @param removeParams if true then parameters and anchor tags will be removed from URI
     * @return Returns normalized URI
     */
    public static URI normalizeLink(String link, URI parent, boolean removeParams) {

        link = link.toLowerCase().trim().replace('\\', '/').replace(" ", "%20");

        URI mergedURL;
        if (parent == null) {
            try {
                mergedURL = URI.create(link);
            } catch (Exception ex) {
                return null;
            }
            if (mergedURL.getScheme() == null) {
                /* Absolute URIs should have a scheme */
                return null;
            }
        } else {
            try {
                mergedURL = URI.create(parent.toString() + "/").resolve(link);
            } catch (Exception ex) {
                return null;
            }
        }

        if (removeParams) {
            try {
                mergedURL = new URI(mergedURL.getScheme(), mergedURL.getUserInfo(), mergedURL.getHost(),
                        mergedURL.getPort(), mergedURL.getPath(), null, null);
            } catch (URISyntaxException e) {
                return null;
            }
        }

        StringBuilder stringURL = new StringBuilder(mergedURL.toString());

        while (stringURL.lastIndexOf("/") == stringURL.length() - 1
                || stringURL.lastIndexOf(".") == stringURL.length() - 1) {
            stringURL.replace(stringURL.length() - 1, stringURL.length(), "");
        }

        return URI.create(stringURL.toString());
    }
}

Related

  1. normalize(URI location)
  2. normalize(URI uri)
  3. normalizedSetCookiePath(final String path, final URI originUri)
  4. normalizedUri(URI uri)
  5. normalizeGitRepoLocation(URI location)
  6. normalizeURI(final URI uri)
  7. normalizeURI(String uri)
  8. normalizeURIPath(String uri)
  9. normalizeUriPath(String uriPath)