david_williams | dce4ddd | 2005-03-18 05:35:37 +0000 | [diff] [blame] | 1 | /******************************************************************************* |
| 2 | * Copyright (c) 2001, 2004 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 | * Jens Lukowski/Innoopract - initial renaming/restructuring |
| 11 | * |
| 12 | *******************************************************************************/ |
| 13 | package org.eclipse.wst.sse.core.internal.encoding.util; |
| 14 | |
| 15 | import java.io.IOException; |
| 16 | import java.net.MalformedURLException; |
| 17 | import java.net.URL; |
| 18 | import java.net.URLClassLoader; |
| 19 | import java.util.Locale; |
| 20 | import java.util.ResourceBundle; |
| 21 | |
| 22 | import org.eclipse.core.runtime.Platform; |
| 23 | |
| 24 | //TODO: rework this with new platform/runtime APIs (if still needed). |
| 25 | |
| 26 | public class ResourceBundleHelper { |
| 27 | |
| 28 | public static ResourceBundle getResourceBundle(String resourceURI) throws MalformedURLException, IOException { |
| 29 | return getResourceBundle(resourceURI, Locale.getDefault()); |
| 30 | } |
| 31 | |
| 32 | public static ResourceBundle getResourceBundle(String resourceURI, Locale targetLocale) throws MalformedURLException, IOException { |
| 33 | // try to load bundle from the location specified in the resourceURI |
| 34 | // we make the assumption that the resourceURI points to the local |
| 35 | // file system |
| 36 | |
| 37 | int index = resourceURI.lastIndexOf("/"); //$NON-NLS-1$ |
| 38 | if (index == -1) { |
| 39 | throw new IllegalArgumentException("Invalid resourceURI"); //$NON-NLS-1$ |
| 40 | } |
| 41 | |
| 42 | // Below we set 'resourceDirectory' so that it ends with a '/'. |
| 43 | // Here's an excerpt from the ClassLoader Javadoc ... |
| 44 | // Any URL that ends with a '/' is assumed to refer to a directory. |
| 45 | // Otherwise, the URL is assumed |
| 46 | // to refer to a JAR file which will be opened as needed. |
| 47 | // |
| 48 | String resourceDirectory = resourceURI.substring(0, index + 1); |
| 49 | String resourceBundleName = resourceURI.substring(index + 1); |
| 50 | |
| 51 | // create a class loader with a class path that points to the resource |
| 52 | // bundle's location |
| 53 | // |
| 54 | URL[] classpath = new URL[1]; |
| 55 | classpath[0] = Platform.resolve(new URL(resourceDirectory)); |
| 56 | ClassLoader resourceLoader = new URLClassLoader(classpath, null); |
| 57 | |
| 58 | return ResourceBundle.getBundle(resourceBundleName, targetLocale, resourceLoader); |
| 59 | } |
| 60 | } |
| 61 | |