1 /* 2 * Copyright (C) 2013 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.android.tradefed.util; 17 18 import com.android.tradefed.log.LogUtil.CLog; 19 20 import java.io.File; 21 import java.io.IOException; 22 23 /** Fetch the version of the running tradefed artifacts. */ 24 public class VersionParser { 25 26 public static final String DEFAULT_IMPLEMENTATION_VERSION = "default"; 27 private static final String VERSION_FILE = "version.txt"; 28 private static final String TF_MAIN_JAR = "/tradefed.jar"; 29 fetchVersion()30 public static String fetchVersion() { 31 return getPackageVersion(); 32 } 33 34 /** 35 * Version fetcher on the implementation version of the jar files from this class to ensure 36 * a match in the classloader. 37 */ getPackageVersion()38 private static String getPackageVersion() { 39 Package p = VersionParser.class.getPackage(); 40 if (p != null) { 41 String packageVersion = p.getImplementationVersion(); 42 if (packageVersion != null && !DEFAULT_IMPLEMENTATION_VERSION.equals(packageVersion)) { 43 return packageVersion; 44 } 45 } 46 File dir = getTradefedJarDir(); 47 if (dir != null) { 48 File versionFile = new File(dir, VERSION_FILE); 49 if (versionFile.exists()) { 50 try { 51 String version = FileUtil.readStringFromFile(versionFile); 52 return version.trim(); 53 } catch (IOException e) { 54 // Failed to fetch version. 55 CLog.e(e); 56 } 57 } 58 CLog.e("Did not find Version file in directory: %s", dir.getAbsolutePath()); 59 } 60 return null; 61 } 62 getTradefedJarDir()63 private static File getTradefedJarDir() { 64 try { 65 File f = 66 new File( 67 VersionParser.class 68 .getProtectionDomain() 69 .getCodeSource() 70 .getLocation() 71 .getPath()); 72 return f.getParentFile(); 73 } catch (Exception e) { 74 CLog.e("Failed to find TF JAR dir:"); 75 CLog.e(e); 76 } 77 return null; 78 } 79 } 80