PageRenderTime 28ms CodeModel.GetById 19ms app.highlight 7ms RepoModel.GetById 1ms app.codeStats 0ms

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