View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with this
4    * work for additional information regarding copyright ownership. The ASF
5    * licenses this file to you under the Apache License, Version 2.0 (the
6    * "License"); you may not use this file except in compliance with the License.
7    * You may obtain a copy of the License at
8    *
9    * http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14   * License for the specific language governing permissions and limitations
15   * under the License.
16   */
17  package org.apache.hadoop.hbase.util;
18  
19  import java.net.URL;
20  
21  import org.apache.hadoop.hbase.master.HMaster;
22  
23  /** Determines HBase home path from either class or jar directory */
24  public class HBaseHomePath {
25  
26    private static final String TARGET_CLASSES = "/target/classes";
27    private static final String JAR_SUFFIX = ".jar!";
28    private static final String FILE_PREFIX = "file:";
29  
30    private HBaseHomePath() {
31    }
32  
33    public static String getHomePath() {
34      String className = HMaster.class.getName();  // This could have been any HBase class.
35      String relPathForClass = className.replace(".", "/") + ".class";
36      URL url = ClassLoader.getSystemResource(relPathForClass);
37      relPathForClass = "/" + relPathForClass;
38      if (url == null) {
39        throw new RuntimeException("Could not lookup class location for " + className);
40      }
41  
42      String path = url.getPath();
43      if (!path.endsWith(relPathForClass)) {
44        throw new RuntimeException("Got invalid path trying to look up class " + className +
45            ": " + path);
46      }
47      path = path.substring(0, path.length() - relPathForClass.length());
48  
49      if (path.startsWith(FILE_PREFIX)) {
50        path = path.substring(FILE_PREFIX.length());
51      }
52  
53      if (path.endsWith(TARGET_CLASSES)) {
54        path = path.substring(0, path.length() - TARGET_CLASSES.length());
55      } else if (path.endsWith(JAR_SUFFIX)) {
56        int slashIndex = path.lastIndexOf("/");
57        if (slashIndex != -1) {
58          throw new RuntimeException("Expected to find slash in jar path " + path);
59        }
60        path = path.substring(0, slashIndex);
61      } else {
62        throw new RuntimeException("Cannot identify HBase source directory or installation path " +
63            "from " + path);
64      }
65      return path;
66    }
67  
68  }