/src/org/ooc/libs/DistLocator.java

http://github.com/nddrylliog/ooc · Java · 87 lines · 56 code · 20 blank · 11 comment · 12 complexity · 8b33eca9c8621ef721aed01de42b6d98 MD5 · raw file

  1. package org.ooc.libs;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.util.Map;
  5. import java.util.StringTokenizer;
  6. import org.ooc.utils.FileUtils;
  7. import org.ooc.utils.ReadEnv;
  8. public class DistLocator {
  9. public static File locate() {
  10. try {
  11. File location;
  12. Map<String, String> env = ReadEnv.getEnv();
  13. Object envDist = env.get("OOC_DIST");
  14. if(envDist != null) {
  15. return new File(envDist.toString());
  16. }
  17. location = tryUnderscore(env);
  18. if(location != null) return location;
  19. location = tryClassPath();
  20. if(location != null) return location;
  21. } catch (IOException e) {
  22. e.printStackTrace();
  23. }
  24. return null;
  25. }
  26. /**
  27. * Assume we're launched as GCJ-compiled executable, and
  28. * try to get our path from the "_" environment variable, which seems to
  29. * be set by bash under Gentoo and by MSYS 1.0.11/whatever under MinGW/WinXP
  30. * @throws IOException
  31. */
  32. protected static File tryUnderscore(Map<String, String> env) throws IOException {
  33. Object underscore = env.get("_");
  34. if(underscore != null) {
  35. File file = new File(underscore.toString().trim());
  36. if(file.getPath().endsWith("ooc") || file.getPath().endsWith("ooc.exe")) {
  37. String canonicalPath = file.getCanonicalPath();
  38. return new File(canonicalPath).getParentFile().getParentFile();
  39. }
  40. }
  41. return null;
  42. }
  43. /**
  44. * Assume we're launched with java -jar bin/ooc.jar or
  45. * java -classpath path/to/ooc/build/classes/ org.ooc.frontend.CommandLine
  46. * and try to find ourselves in the classpath.
  47. */
  48. protected static File tryClassPath() {
  49. String classPath = System.getProperty("java.class.path");
  50. StringTokenizer st = new StringTokenizer(classPath, File.pathSeparator);
  51. while(st.hasMoreTokens()) {
  52. String token = st.nextToken();
  53. String base = "";
  54. for(int i = 0; i < 8; i++) { // brute force. works for the .class and the .jar methods
  55. base += "../";
  56. try {
  57. File distribLocation = new File(token, base).getCanonicalFile();
  58. File idFile = FileUtils.resolveRedundancies(new File(distribLocation, "sdk/ooc_sdk_id"));
  59. if(idFile.exists()) {
  60. return FileUtils.resolveRedundancies(distribLocation);
  61. }
  62. } catch(IOException e) {}
  63. }
  64. }
  65. return null;
  66. }
  67. }