KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > core > runtime > internal > adaptor > LocationHelper


1 /*******************************************************************************
2  * Copyright (c) 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.runtime.internal.adaptor;
12
13 import java.io.File JavaDoc;
14 import java.net.MalformedURLException JavaDoc;
15 import java.net.URL JavaDoc;
16
17 /**
18  * @since 3.3
19  */

20 public class LocationHelper {
21     /**
22      * Builds a URL with the given specification
23      * @param spec the URL specification
24      * @param trailingSlash flag to indicate a trailing slash on the spec
25      * @return a URL
26      */

27     public static URL JavaDoc buildURL(String JavaDoc spec, boolean trailingSlash) {
28         if (spec == null)
29             return null;
30         boolean isFile = spec.startsWith("file:"); //$NON-NLS-1$
31
try {
32             if (isFile)
33                 return adjustTrailingSlash(new File JavaDoc(spec.substring(5)).toURL(), trailingSlash);
34             return new URL JavaDoc(spec);
35         } catch (MalformedURLException JavaDoc e) {
36             // if we failed and it is a file spec, there is nothing more we can do
37
// otherwise, try to make the spec into a file URL.
38
if (isFile)
39                 return null;
40             try {
41                 return adjustTrailingSlash(new File JavaDoc(spec).toURL(), trailingSlash);
42             } catch (MalformedURLException JavaDoc e1) {
43                 return null;
44             }
45         }
46     }
47
48     private static URL JavaDoc adjustTrailingSlash(URL JavaDoc url, boolean trailingSlash) throws MalformedURLException JavaDoc {
49         String JavaDoc file = url.getFile();
50         if (trailingSlash == (file.endsWith("/"))) //$NON-NLS-1$
51
return url;
52         file = trailingSlash ? file + "/" : file.substring(0, file.length() - 1); //$NON-NLS-1$
53
return new URL JavaDoc(url.getProtocol(), url.getHost(), file);
54     }
55
56 }
57
Popular Tags