Java File Link sanitizeUrl(String link)

Here you can find the source of sanitizeUrl(String link)

Description

Make sure an URL is "portable", in that it doesn't contain bad characters that break the open command in some OSes.

License

Open Source License

Parameter

Parameter Description
link the URL to sanitize.

Return

the sanitized URL

Declaration

public static String sanitizeUrl(String link) 

Method Source Code


//package com.java2s;
/*  Copyright (C) 2003-2015 JabRef contributors.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version./*from w  w w.  ja  v a 2s  .  c  om*/
    
This program 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 General Public License for more details.
    
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

import java.io.UnsupportedEncodingException;

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

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

public class Main {
    /**
     * Make sure an URL is "portable", in that it doesn't contain bad characters that break the open command in some
     * OSes. A call to this method will also remove \\url{} enclosings.
     *
     * It does:
     * - trim whitespace
     * - remove Latex \\url{} tags
     *
     * @param link the URL to sanitize.
     * @return the sanitized URL
     */
    public static String sanitizeUrl(String link) {
        // remove whitespace
        link = link.trim();

        // Remove \\url{}
        if (link.startsWith("\\url{") && link.endsWith("}")) {
            link = link.substring(5, link.length() - 1);
        }

        // FIXME: everything below is really flawed atm
        link = link.replaceAll("\\+", "%2B");

        try {
            link = URLDecoder.decode(link, StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException ignored) {
            // Ignored
        }

        /**
         * Fix for: [ 1574773 ] sanitizeUrl() breaks ftp:// and file:///
         *
         * http://sourceforge.net/tracker/index.php?func=detail&aid=1574773&group_id=92314&atid=600306
         */
        try {
            return new URI(null, link, null).toASCIIString();
        } catch (URISyntaxException e) {
            return link;
        }
    }
}

Related

  1. isSymlinkJava7(@Nonnull File file)
  2. makeSymLink(File target, File destination)
  3. readSymbolicLink(@Nonnull File symlink)
  4. readSymlinkTarget(File file)
  5. resolveSymbolicLink(File file)
  6. textLinksInBytes()