Create valid URL from a system id : URL « Network Protocol « Java






Create valid URL from a system id

    

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;

public final class URLUtil {
  private URLUtil() {
  }

  /**
   * Method that tries to figure out how to create valid URL from a system id,
   * without additional contextual information. If we could use URIs this might
   * be easier to do, but they are part of JDK 1.4, and preferably code should
   * only require 1.2 (or maybe 1.3)
   */
  public static URL urlFromSystemId(String sysId) throws IOException {
    try {
      /*
       * Ok, does it look like a full URL? For one, you need a colon. Also, to
       * reduce likelihood of collision with Windows paths, let's only accept it
       * if there are 3 preceding other chars... Not sure if Mac might be a
       * problem? (it uses ':' as file path separator, alas, at least prior to
       * MacOS X)
       */
      int ix = sysId.indexOf(':', 0);
      /*
       * Also, protocols are generally fairly short, usually 3 or 4 chars (http,
       * ftp, urn); so let's put upper limit of 8 chars too
       */
      if (ix >= 3 && ix <= 8) {
        return new URL(sysId);
      }
      // Ok, let's just assume it's local file reference...
      /*
       * 24-May-2006, TSa: Amazingly, this single call does show in profiling,
       * for small docs. The problem is that deep down it tries to check
       * physical file system, to check if the File pointed to is a directory:
       * and that is (relatively speaking) a very expensive call. Since in this
       * particular case it should never be a dir (and/or doesn't matter), let's
       * just implement conversion locally
       */
      String absPath = new java.io.File(sysId).getAbsolutePath();
      // Need to convert colons/backslashes to regular slashes?
      {
        char sep = File.separatorChar;
        if (sep != '/') {
          absPath = absPath.replace(sep, '/');
        }
      }
      if (absPath.length() > 0 && absPath.charAt(0) != '/') {
        absPath = "/" + absPath;
      }
      return new URL("file", "", absPath);
    } catch (MalformedURLException e) {

      return null; // never gets here
    }
  }

  public static URL urlFromSystemId(String sysId, URL ctxt) throws IOException {
    if (ctxt == null) {
      return urlFromSystemId(sysId);
    }
    try {
      return new URL(ctxt, sysId);
    } catch (MalformedURLException e) {

      return null; // never gets here
    }
  }

  /**
   * Method that tries to create and return URL that denotes current working
   * directory. Usually used to create a context, when one is not explicitly
   * passed.
   */
  public static URL urlFromCurrentDir() throws java.net.MalformedURLException /*
                                                                               * an
                                                                               * IOException
                                                                               */
  {
    /*
     * This seems to work; independent of whether there happens to be such/file
     * dir or not.
     */
    return new File("a").getAbsoluteFile().getParentFile().toURL();
  }

  /**
   * Method that tries to get a stream (ideally, optimal one) to read from the
   * specified URL. Currently it just means creating a simple file input stream
   * if the URL points to a (local) file, and otherwise relying on URL classes
   * input stream creation method.
   */
  public static InputStream inputStreamFromURL(URL url) throws IOException {
    if ("file".equals(url.getProtocol())) {
      /*
       * As per [WSTX-82], can not do this if the path refers to a network drive
       * on windows. This fixes the problem; might not be needed on all
       * platforms (NFS?), but should not matter a lot: performance penalty of
       * extra wrapping is more relevant when accessing local file system.
       */
      String host = url.getHost();
      if (host == null || host.length() == 0) {
        return new FileInputStream(url.getPath());
      }
    }
    return url.openStream();
  }

  /**
   * Method that tries to get a stream (ideally, optimal one) to write to the
   * resource specified by given URL. Currently it just means creating a simple
   * file output stream if the URL points to a (local) file, and otherwise
   * relying on URL classes input stream creation method.
   */
  public static OutputStream outputStreamFromURL(URL url) throws IOException {
    if ("file".equals(url.getProtocol())) {
      /*
       * As per [WSTX-82], can not do this if the path refers to a network drive
       * on windows.
       */
      String host = url.getHost();
      if (host == null || host.length() == 0) {
        return new FileOutputStream(url.getPath());
      }
    }
    return url.openConnection().getOutputStream();
  }

}

   
    
    
    
  








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.Extract URL File Name
42.Extract the URL page name from the given path
43.Get Domain Name
44.Get Locale From String
45.Get URL Last Modified
46.Get the name of the parent of the given URL path
47.Get the parent of the given URL path
48.Has URLContent Changed
49.Is URL a local file
50.Normalize an URL
51.Normalizes an URL
52.Resolve a relative URL string against an absolute URL string
53.ResourceBundle String manager
54.Save URL contents to a file
55.URL Path: standardize the creation of mutation of path-like structures
56.Utility class for building URLs
57.Add Default Port to a URL If Missing
58.Get Relative Path To URL
59.Download from a URL and save to a file