001 /**
002 * Copyright (c) 2010 Yahoo! Inc. All rights reserved.
003 * Licensed under the Apache License, Version 2.0 (the "License");
004 * you may not use this file except in compliance with the License.
005 * You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software
010 * distributed under the License is distributed on an "AS IS" BASIS,
011 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012 * See the License for the specific language governing permissions and
013 * limitations under the License. See accompanying LICENSE file.
014 */
015 package org.apache.oozie.util;
016
017 import java.util.Enumeration;
018 import java.net.URL;
019 import java.net.URLDecoder;
020 import java.io.IOException;
021
022 /**
023 * Class utilities.
024 */
025 public class ClassUtils {
026
027 /**
028 * Return the path to the JAR file in the classpath containing the specified class. <p/> This method has been
029 * canibalized from Hadoop's JobConf class.
030 *
031 * @param clazz class to find its JAR file.
032 * @return the JAR file of the class.
033 */
034 public static String findContainingJar(Class clazz) {
035 ClassLoader loader = clazz.getClassLoader();
036 String class_file = clazz.getName().replaceAll("\\.", "/") + ".class";
037 try {
038 for (Enumeration itr = loader.getResources(class_file); itr.hasMoreElements();) {
039 URL url = (URL) itr.nextElement();
040 if ("jar".equals(url.getProtocol())) {
041 String toReturn = url.getPath();
042 if (toReturn.startsWith("file:")) {
043 toReturn = toReturn.substring("file:".length());
044 }
045 toReturn = URLDecoder.decode(toReturn, "UTF-8");
046 return toReturn.replaceAll("!.*$", "");
047 }
048 }
049 }
050 catch (IOException e) {
051 throw new RuntimeException(e);
052 }
053 return null;
054 }
055
056 }