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 */
018package org.apache.hadoop.hbase.util;
019
020import java.net.URL;
021import org.apache.hadoop.hbase.master.HMaster;
022
023/** Determines HBase home path from either class or jar directory */
024public class HBaseHomePath {
025
026  private static final String TARGET_CLASSES = "/target/classes";
027  private static final String JAR_SUFFIX = ".jar!";
028  private static final String FILE_PREFIX = "file:";
029
030  private HBaseHomePath() {
031  }
032
033  public static String getHomePath() {
034    String className = HMaster.class.getName(); // This could have been any HBase class.
035    String relPathForClass = className.replace(".", "/") + ".class";
036    URL url = ClassLoader.getSystemResource(relPathForClass);
037    relPathForClass = "/" + relPathForClass;
038    if (url == null) {
039      throw new RuntimeException("Could not lookup class location for " + className);
040    }
041
042    String path = url.getPath();
043    if (!path.endsWith(relPathForClass)) {
044      throw new RuntimeException(
045        "Got invalid path trying to look up class " + className + ": " + path);
046    }
047    path = path.substring(0, path.length() - relPathForClass.length());
048
049    if (path.startsWith(FILE_PREFIX)) {
050      path = path.substring(FILE_PREFIX.length());
051    }
052
053    if (path.endsWith(TARGET_CLASSES)) {
054      path = path.substring(0, path.length() - TARGET_CLASSES.length());
055    } else if (path.endsWith(JAR_SUFFIX)) {
056      int slashIndex = path.lastIndexOf("/");
057      if (slashIndex != -1) {
058        throw new RuntimeException("Expected to find slash in jar path " + path);
059      }
060      path = path.substring(0, slashIndex);
061    } else {
062      throw new RuntimeException(
063        "Cannot identify HBase source directory or installation path " + "from " + path);
064    }
065    return path;
066  }
067
068}