Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * ====================================================================
   * Copyright (c) 2004-2006 TMate Software Ltd.  All rights reserved.
   *
   * This software is licensed as described in the file COPYING, which
   * you should have received as part of this distribution.  The terms
   * are also available at http://svnkit.com/license.html
   * If newer versions of this license are posted there, you may use a
   * newer version instead, at your option.
  * ====================================================================
  */
 package org.tmatesoft.svn.core;
 
 import java.net.URL;
 import java.util.Map;
 import java.io.File;
 
The SVNURL class is used for representing urls. Those SVNKit API methods, that need repository locations to carry out an operation, receive a repository location url represented by SVNURL. This class does all the basic work for a caller: parses an original url string (splitting it to components), encodes/decodes a path component to/from the UTF-8 charset, checks for validity (such as protocol support - if SVNKit does not support a particular protocol, SVNURL throws a corresponding exception).

To create a new SVNURL representation, pass an original url string (like "http://userInfo@host:port/path") to a corresponding parse method of this class.

Author(s):
TMate Software Ltd.
Version:
1.1.0
See also:
Examples
 
 public class SVNURL {
    
Creates a new SVNURL representation from the given url components.

Parameters:
protocol a protocol component
userInfo a user info component
host a host component
port a port number
path a path component
uriEncoded true if path is UTF-8 encoded, false otherwise
Returns:
a new SVNURL representation
Throws:
SVNException if the resultant url (composed of the given components) is malformed
 
     public static SVNURL create(String protocolString userInfoString hostint portString pathboolean uriEncodedthrows SVNException {
         if (host == null || host.indexOf('@') >= 0) {
             SVNErrorManager.error(SVNErrorMessage.create(."Invalid host name ''{0}''"host));
         }
         path = path == null ? "/" : path.trim();
         if (!uriEncoded) {
             path = SVNEncodingUtil.uriEncode(path);
         } else {
             path = SVNEncodingUtil.autoURIEncode(path);
         }
         if (path.length() > 0 && path.charAt(0) != '/') {
             path = "/" + path;
         }
         if (path.length() > 0 && path.charAt(path.length() - 1) == '/') {
             path = path.substring(0, path.length() - 1);
         }
         protocol = protocol == null ? "http" : protocol.toLowerCase();
         String errorMessage = null;
         if (userInfo != null && userInfo.indexOf('/') >= 0) {
             errorMessage = "Malformed URL: user info part could not include '/' symbol";
         } else if (host == null && !"file".equals(protocol)) {
             errorMessage = "Malformed URL: host could not be NULL";
         } else if (!"file".equals(protocol) && host.indexOf('/') >= 0) {
             errorMessage = "Malformed URL: host could not include '/' symbol";
         }
         if (errorMessage != null) {
             SVNErrorMessage err = SVNErrorMessage.create(.errorMessage);
             SVNErrorManager.error(err);
         }
         String url = composeURL(protocoluserInfohostportpath);
         return new SVNURL(urltrue);
     }

    
Parses the given decoded (not UTF-8 encoded) url string and creates a new SVNURL representation for this url.

Parameters:
url an input url string (like 'http://myhost/mypath')
Returns:
a new SVNURL representation of url
Throws:
SVNException if url is malformed
    public static SVNURL parseURIDecoded(String urlthrows SVNException {
        return new SVNURL(urlfalse);
    }
    
    
Parses the given UTF-8 encoded url string and creates a new SVNURL representation for this url.

Parameters:
url an input url string (like 'http://myhost/my%20path')
Returns:
a new SVNURL representation of url
Throws:
SVNException if url is malformed
    public static SVNURL parseURIEncoded(String urlthrows SVNException {
        return new SVNURL(urltrue);
    }
    
    
Creates a "file:///" SVNURL representation given a filesystem style repository path.

Parameters:
repositoryPath a repository path as a filesystem path
Returns:
an SVNURL representation
Throws:
SVNException
    public static SVNURL fromFile(File repositoryPaththrows SVNException {
        if (repositoryPath == null) {
            return null;
        }
        String path = repositoryPath.getAbsoluteFile().getAbsolutePath();
        path = path.replace(.'/');
        if (!path.startsWith("/")) {
            path = "/" + path;
        }
        return SVNURL.parseURIDecoded("file://" + path);
    }
    
    
Returns the default port number for the specified protocol.

Parameters:
protocol a particular access protocol
Returns:
default port number
    public static int getDefaultPortNumber(String protocol) {
        if (protocol == null) {
            return -1;
        }
        protocol = protocol.toLowerCase();
        if ("file".equals(protocol)) {
            return -1;
        }
        Integer dPort = (Integer.get(protocol);
        if (dPort != null) {
            return dPort.intValue();
        }
        return -1;
    }
    
    private static final Map DEFAULT_PORTS = new HashMap();
    
    static {
        .put("svn"new Integer(3690));
        .put("svn+ssh"new Integer(22));
        .put("http"new Integer(80));
        .put("https"new Integer(443));
        .put("file"new Integer(0));
    }
    
    private String myURL;
    private String myProtocol;
    private String myHost;
    private String myPath;
    private String myUserName;
    private int myPort;
    private String myEncodedPath;
    private boolean myIsDefaultPort;
    
    private SVNURL(String urlboolean uriEncodedthrows SVNException {
        if (url == null) {
            SVNErrorMessage err = SVNErrorMessage.create(."URL cannot be NULL");
            SVNErrorManager.error(err);
        }
        if (url.endsWith("/")) {
            url = url.substring(0, url.length() - 1);
        }
        int index = url.indexOf("://");
        if (index <= 0) {
            SVNErrorMessage err = SVNErrorMessage.create(."Malformed URL ''{0}''"url);
            SVNErrorManager.error(err);
        }
         = url.substring(0, index);
         = .toLowerCase();
        if (!.containsKey() && !.startsWith("svn+")) {
            SVNErrorMessage err = SVNErrorMessage.create(."URL protocol is not supported ''{0}''"url);
            SVNErrorManager.error(err);
        }
        if ("file".equals()) {
            String normalizedPath = norlmalizeURLPath(urlurl.substring("file://".length()));
            URL testURL = null;
            try {
                testURL = new URL( + "://" + normalizedPath);
            } catch (MalformedURLException e) {
                SVNErrorMessage err = SVNErrorMessage.create(."Malformed URL: ''{0}'': {1}"new Object[] {urle.getLocalizedMessage()});
                SVNErrorManager.error(erre);
                return;
            }
            String testPath = getPath(testURL);
            if(testPath == null || "".equals(testPath)){
                //no path, only host - follow subversion behaviour
                SVNErrorMessage err = SVNErrorMessage.create(."Local URL ''{0}'' contains only a hostname, no path"url);
                SVNErrorManager.error(err);
                return;
            }
             = testURL.getHost() == null ? "" : testURL.getHost();
            if (uriEncoded) {
                // autoencode it.
                 = SVNEncodingUtil.autoURIEncode(testPath);
                SVNEncodingUtil.assertURISafe();
                 = SVNEncodingUtil.uriDecode();
                 = .replace(.'/');
                if(!.startsWith("/")){
                     = "/" + ;
                }
            } else {
                 = testPath;
                if(!.startsWith("/")){
                     = "/" + ;
                }
                 = SVNEncodingUtil.uriEncode();
            }
             = testURL.getUserInfo();
             = testURL.getPort();
        } else {
            String testURL = "http" + url.substring(index);
            URL httpURL;
            try {
                httpURL = new URL(testURL);
            } catch (MalformedURLException e) {
                SVNErrorMessage err = SVNErrorMessage.create(."Malformed URL: ''{0}'': {1}"new Object[] {urle.getLocalizedMessage()});
                SVNErrorManager.error(erre);
                return;
            }
             = httpURL.getHost();
            String httpPath = norlmalizeURLPath(urlgetPath(httpURL));
            if (uriEncoded) {
                // autoencode it.
                 = SVNEncodingUtil.autoURIEncode(httpPath);
                SVNEncodingUtil.assertURISafe();
                 = SVNEncodingUtil.uriDecode();
            } else {
                 = httpPath;
                 = SVNEncodingUtil.uriEncode();
            }
             = httpURL.getUserInfo();
             = httpURL.getPort();
             =  < 0;
            if ( < 0) {
                Integer defaultPort = (Integer.get();
                 = defaultPort != null ? defaultPort.intValue() : 0;
            } 
        }
    }
    
    
Returns the protocol component of the url represented by this object.

Returns:
a protocol name (like http)
    public String getProtocol() {
        return ;
    }
    
    
Returns the host component of the url represented by this object.

Returns:
a host name
    public String getHost() {
        return ;
    }
    
    
Returns the port number specified (or default) for the host.

Returns:
a port number
    public int getPort() {
        return ;
    }
    
    
Says if the url is provided with a non-default port number or not.

Returns:
true if the url comes with a non-default port number, false otherwise
See also:
getPort()
    public boolean hasPort() {
        return !;
    }
    
    
Returns the path component of the url represented by this object as a uri-decoded string

Returns:
a uri-decoded path
    public String getPath() {
        return ;
    }
    
    
Returns the path component of the url represented by this object as a uri-encoded string

Returns:
a uri-encoded path
    public String getURIEncodedPath() {
        return ;
    }
    
    
Returns the user info component of the url represented by this object.

Returns:
a user info part of the url (if it was provided)
    public String getUserInfo() {
        return ;
    }
    
    
Returns a string representing a UTF-8 encoded url.

Returns:
an encoded url string
    public String toString() {
        if ( == null) {
             = composeURL(getProtocol(), getUserInfo(), getHost(),  ? -1 : getPort(), getURIEncodedPath());
        }
        return ;
    }
    
    
Returns a string representing a decoded url.

Returns:
a decoded url string
    public String toDecodedString() {
        return composeURL(getProtocol(), getUserInfo(), getHost(),  ? -1 : getPort(), getPath());
    }
    
    
Constructs a new SVNURL representation appending a new path segment to the path component of this representation.

Parameters:
segment a new path segment
uriEncoded true if segment is UTF-8 encoded, false otherwise
Returns:
a new SVNURL representation
Throws:
SVNException if a parse error occurred
    public SVNURL appendPath(String segmentboolean uriEncodedthrows SVNException {
        if (segment == null || "".equals(segment)) {
            return this;
        }
        if (!uriEncoded) {
            segment = SVNEncodingUtil.uriEncode(segment);
        } else {
            segment = SVNEncodingUtil.autoURIEncode(segment);
        }
        String path = getURIEncodedPath();
        if ("".equals(path)) {
            path = "/" + segment;
        } else {
            path = SVNPathUtil.append(pathsegment);
        }
        String url = composeURL(getProtocol(), getUserInfo(), getHost(),  ? -1 : getPort(), path);
        return parseURIEncoded(url);
    }

    
Creates a new SVNURL object replacing a path component of this object with a new provided one.

Parameters:
path a path component
uriEncoded true if path is UTF-8 encoded
Returns:
a new SVNURL representation
Throws:
SVNException if a parse error occurred
    public SVNURL setPath(String pathboolean uriEncodedthrows SVNException {
        if (path == null || "".equals(path)) {
            path = "/";
        }
        if (!uriEncoded) {
            path = SVNEncodingUtil.uriEncode(path);
        } else {
            path = SVNEncodingUtil.autoURIEncode(path);
        }
        String url = composeURL(getProtocol(), getUserInfo(), getHost(),  ? -1 : getPort(), path);
        return parseURIEncoded(url);
    }
    
    
Constructs a new SVNURL representation removing a tail path segment from the path component of this representation.

Returns:
a new SVNURL representation
    public SVNURL removePathTail() throws SVNException {
        String newPath = SVNPathUtil.removeTail();
        String url = composeURL(getProtocol(), getUserInfo(), getHost(),  ? -1 : getPort(), newPath);
        return parseURIDecoded(url);
    }
    
Compares this object with another one.

Parameters:
obj an object to compare with
Returns:
true if obj is an instance of SVNURL and has got the same url components as this object has
    public boolean equals(Object obj) {
        if (obj == null || obj.getClass() != SVNURL.class) {
            return false;
        }
        SVNURL url = (SVNURLobj;
        boolean eq = .equals(url.myProtocol) && 
             == url.myPort &&
            .equals(url.myHost) &&
            .equals(url.myPath) &&
            hasPort() == url.hasPort();
        if ( == null) {
            eq &= url.myUserName == null;
        } else {
            eq &= .equals(url.myUserName);
        }
        return eq;
    }
    
    
Calculates and returns a hash code for this object.

Returns:
a hash code value
    public int hashCode() {
        int code = .hashCode() + .hashCode()*27 + .hashCode()*31 + *17;
        if ( != null) {
            code += 37*.hashCode();
        }
        return code;
    }
    private static String composeURL(String protocolString userInfoString hostint portString path) {
        StringBuffer url = new StringBuffer();
        url.append(protocol);
        url.append("://");
        if (userInfo != null) {
            url.append(userInfo);
            url.append("@");
        }
        url.append(host);
        if (port >= 0) {
            url.append(":");
            url.append(port);
        }
        url.append(path);
        return url.toString();
    }
    
    private static String norlmalizeURLPath(String urlString paththrows SVNException {
        StringBuffer result = new StringBuffer(path.length());
        for(StringTokenizer tokens = new StringTokenizer(path"/"); tokens.hasMoreTokens();) {
            String token = tokens.nextToken();
            if ("".equals(token) || ".".equals(token)) {
                continue;
            } else if ("..".equals(token)) {
                SVNErrorMessage err = SVNErrorMessage.create(."URL ''{0}'' contains '..' element"url);
                SVNErrorManager.error(err);
            } else {
                result.append("/");
                result.append(token);
            }
        }
        if (!path.startsWith("/") && result.length() > 0) {
            result = result.delete(0, 1);
        }
        return result.toString();
    }
    
    private static String getPath(URL url) {
        String path = url.getPath();
        String ref = url.getRef();
        if (ref != null) {
            if (path == null) {
                path = "";
            }
            path += '#' + ref;
        }
        return path;
    }
New to GrepCode? Check out our FAQ X