001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with this
004 * work for additional information regarding copyright ownership. The ASF
005 * licenses this file to you under the Apache License, Version 2.0 (the
006 * "License"); you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
013 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
014 * License for the specific language governing permissions and limitations
015 * under the License.
016 */
017package org.apache.hadoop.hbase.util;
018
019import java.net.URL;
020
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("Got invalid path trying to look up class " + className +
045          ": " + 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("Cannot identify HBase source directory or installation path " +
063          "from " + path);
064    }
065    return path;
066  }
067
068}