KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > core > internal > runtime > auth > URLTool


1 /*******************************************************************************
2  * Copyright (c) 2000, 2006 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.core.internal.runtime.auth;
12
13 import java.net.MalformedURLException JavaDoc;
14 import java.net.URL JavaDoc;
15 import org.eclipse.core.runtime.Assert;
16
17 /**
18  * A utility for manipulating <code>URL</code>s.
19  */

20 public class URLTool {
21
22     /**
23      * Returns the parent URL of the given URL, or <code>null</code> if the
24      * given URL is the root.
25      * <table>
26      * <caption>Example</caption>
27      * <tr>
28      * <th>Given URL</th>
29      * <th>Parent URL</th>
30      * <tr>
31      * <td>"http://hostname/"</td>
32      * <td>null</td>
33      * <tr>
34      * <td>"http://hostname/folder/file</td>
35      * <td>"http://hostname/folder/</td>
36      * </table>
37      *
38      * @param url a URL
39      * @return the parent of the given URL
40      */

41     public static URL JavaDoc getParent(URL JavaDoc url) {
42         String JavaDoc file = url.getFile();
43         int len = file.length();
44         if (len == 0 || len == 1 && file.charAt(0) == '/')
45             return null;
46         int lastSlashIndex = -1;
47         for (int i = len - 2; lastSlashIndex == -1 && i >= 0; --i) {
48             if (file.charAt(i) == '/')
49                 lastSlashIndex = i;
50         }
51         if (lastSlashIndex == -1)
52             file = ""; //$NON-NLS-1$
53
else
54             file = file.substring(0, lastSlashIndex + 1);
55
56         try {
57             url = new URL JavaDoc(url.getProtocol(), url.getHost(), url.getPort(), file);
58         } catch (MalformedURLException JavaDoc e) {
59             Assert.isTrue(false, e.getMessage());
60         }
61         return url;
62     }
63 }
64
Popular Tags