Add Default Port to a URL If Missing : URL « Network Protocol « Java






Add Default Port to a URL If Missing

    

/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utils {
  public static String addDefaultPortIfMissing(String urlString, String defaultPort) {
    URL url = null;
    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        return urlString;
    }
    if (url.getPort() != -1) {
        return urlString;
    }
    String regex = "http://([^/]+)";        
    String found = getFirstFound(urlString, regex);
    String replacer = "http://" + found + ":" + defaultPort;
    
    if (!isEmpty(found)) {
        urlString = urlString.replaceFirst(regex, replacer);
    }                
    return urlString;
}
  public static String getFirstFound(String contents, String regex) {
    List<String> founds = getFound(contents, regex);
    if (isEmpty(founds)) {
        return null;
    }
    return founds.get(0);
}
  public static List<String> getFound(String contents, String regex) {
      if (isEmpty(regex) || isEmpty(contents)) {
          return null;
      }
      List<String> results = new ArrayList<String>();
      Pattern pattern = Pattern.compile(regex, Pattern.UNICODE_CASE);
      Matcher matcher = pattern.matcher(contents);
      
      while (matcher.find()) {
          if (matcher.groupCount() > 0) {
              results.add(matcher.group(1));
          } else {
              results.add(matcher.group());
          }
      }
      return results;
  } 
  public static boolean isEmpty(List<String> list) {
    if (list == null || list.size() == 0) {
        return true;
    }
    if (list.size() == 1 && isEmpty(list.get(0))) {
        return true;
    }
    return false;
}
  public static boolean isEmpty(String str) {
      if (str != null && str.trim().length() > 0) {
          return false;
      }
      return true;
  }
}

   
    
    
    
  








Related examples in the same category

1.Creating a URL with a single string.
2.Creating a URL With components
3.Converting Between a Filename Path and a URL
4.URL Constructor Test
5.URL Encode Test
6.Get URL Content
7.Get URL Parts
8.Read from a URL
9.Convert a URL to a URI
10.Converting Between a URL and a URI
11.Convert an absolute URI to a URL
12.URL Equality
13.Parsing a URL
14.URL Request
15.URL Get
16.A URL Retrieval Example
17.URL Reader
18.URL Connection ReaderURL Connection Reader
19.Using URLConnection
20.Parse URLParse URL
21.Resolve a relative URL
22.sends e-mail using a mailto: URLsends e-mail using a mailto: URL
23.Convert the absolute URI to a URL object
24.Convert URI to URL
25.Get parts of a url
26.Checks, whether the URL uses a file based protocol.
27.Add Parameter to URL
28.Returns the anchor value of the given URL
29.Extracts the file name from the URL.
30.Creates a relative url by stripping the common parts of the the url.
31.Checks, whether the URL points to the same service. A service is equal if the protocol, host and port are equal.
32.Extracts the base URL from the given URL by stripping the query and anchor part.
33.Returns true if the URL represents a path, and false otherwise.
34.Parse Port
35.Parse Host
36.Given a URL check if its a jar url(jar:!/archive) and if it is, extract the archive entry into the given dest directory and return a file URL to its location
37.check the validity of url pattern according to the spec.
38.A collection of File, URL and filename utility methods
39.Build Relative URL Path
40.Checks that the protocol://host:port part of two URLs are equal
41.Create valid URL from a system id
42.Extract URL File Name
43.Extract the URL page name from the given path
44.Get Domain Name
45.Get Locale From String
46.Get URL Last Modified
47.Get the name of the parent of the given URL path
48.Get the parent of the given URL path
49.Has URLContent Changed
50.Is URL a local file
51.Normalize an URL
52.Normalizes an URL
53.Resolve a relative URL string against an absolute URL string
54.ResourceBundle String manager
55.Save URL contents to a file
56.URL Path: standardize the creation of mutation of path-like structures
57.Utility class for building URLs
58.Get Relative Path To URL
59.Download from a URL and save to a file