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