PageRenderTime 26ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/src/java/org/eclim/plugin/jdt/PluginResources.java

https://github.com/rue/eclim
Java | 310 lines | 195 code | 43 blank | 72 comment | 16 complexity | 945b8911db236e170f8087cd6f4c4c17 MD5 | raw file
  1. /**
  2. * Copyright (C) 2005 - 2010 Eric Van Dewoestine
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. package org.eclim.plugin.jdt;
  18. import java.io.ByteArrayInputStream;
  19. import java.io.File;
  20. import java.io.FilenameFilter;
  21. import java.io.InputStream;
  22. import java.util.HashMap;
  23. import java.util.Properties;
  24. import java.util.regex.Pattern;
  25. import org.apache.commons.lang.SystemUtils;
  26. import org.apache.tools.ant.taskdefs.condition.Os;
  27. import org.eclim.Services;
  28. import org.eclim.logging.Logger;
  29. import org.eclim.plugin.AbstractPluginResources;
  30. import org.eclim.plugin.jdt.preference.OptionHandler;
  31. import org.eclim.plugin.jdt.project.JavaProjectManager;
  32. import org.eclim.plugin.core.preference.PreferenceFactory;
  33. import org.eclim.plugin.core.preference.Preferences;
  34. import org.eclim.plugin.core.project.ProjectManagement;
  35. import org.eclim.plugin.core.project.ProjectNatureFactory;
  36. import org.eclim.util.IOUtils;
  37. import org.eclim.util.StringUtils;
  38. import org.eclim.util.file.FileUtils;
  39. import org.eclipse.core.runtime.IPath;
  40. import org.eclipse.core.runtime.Path;
  41. import org.eclipse.jdt.core.JavaCore;
  42. import org.eclipse.jdt.launching.IVMInstall;
  43. import org.eclipse.jdt.launching.JavaRuntime;
  44. import org.eclipse.jdt.launching.LibraryLocation;
  45. /**
  46. * Implementation of AbstractPluginResources.
  47. *
  48. * @author Eric Van Dewoestine
  49. */
  50. public class PluginResources
  51. extends AbstractPluginResources
  52. {
  53. /**
  54. * Name that can be used to lookup this PluginResources from
  55. * {@link Services#getPluginResources(String)}.
  56. */
  57. public static final String NAME = "org.eclim.jdt";
  58. /**
  59. * The eclipse nature id for this plugin.
  60. */
  61. public static final String NATURE = JavaCore.NATURE_ID;
  62. private static final Logger logger = Logger.getLogger(PluginResources.class);
  63. private static final String VARIABLES = "resources/classpath_variables";
  64. private static final String[] SRC_LOCATIONS = {
  65. "src.zip",
  66. "share/src.zip",
  67. SystemUtils.JAVA_HOME.replace('\\', '/') + "/src.zip",
  68. SystemUtils.JAVA_HOME.replace('\\', '/') + "/share/src.zip",
  69. SystemUtils.JAVA_HOME.replace('\\', '/') + "/../src.zip",
  70. SystemUtils.JAVA_HOME.replace('\\', '/') + "/../share/src.zip",
  71. };
  72. /**
  73. * {@inheritDoc}
  74. * @see AbstractPluginResources#initialize(String)
  75. */
  76. @Override
  77. public void initialize(String name)
  78. {
  79. super.initialize(name);
  80. logger.debug("Initializing java environment");
  81. // initialize variables.
  82. initializeJreSrc();
  83. initializeVars(VARIABLES);
  84. /*java.util.Hashtable options = JavaCore.getOptions();
  85. options.put(
  86. DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR,
  87. JavaCore.SPACE);
  88. options.put(
  89. DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, "2");
  90. options.put(
  91. DefaultCodeFormatterConstants.FORMATTER_USE_TABS_ONLY_FOR_LEADING_INDENTATIONS,
  92. DefaultCodeFormatterConstants.FALSE);
  93. JavaCore.setOptions(options);*/
  94. Preferences.addOptionHandler("org.eclipse.jdt", new OptionHandler());
  95. ProjectNatureFactory.addNature("java", NATURE);
  96. ProjectManagement.addProjectManager(NATURE, new JavaProjectManager());
  97. PreferenceFactory.addPreferences(NATURE,
  98. "JDT org.eclim.java.logging.impl commons-logging " +
  99. "(commons-logging|log4j|slf4j|jdk|custom)\n" +
  100. "JDT org.eclim.java.logging.template logger.gst\n" +
  101. "JDT org.eclim.java.validation.ignore.warnings false (true|false)\n" +
  102. "JDT org.eclim.java.checkstyle.config\n" +
  103. "JDT org.eclim.java.checkstyle.properties\n" +
  104. "JDT org.eclim.java.compile.sourcepath\n" +
  105. "JDT org.eclim.java.run.mainclass none ^[a-zA-Z0-9_.]*$\n" +
  106. "JDT/Javadoc org.eclim.java.doc.version\n" +
  107. "JDT/Javadoc org.eclim.java.doc.dest doc\n" +
  108. "JDT/Javadoc org.eclim.java.doc.sourcepath\n" +
  109. "JDT/Javadoc org.eclim.java.doc.packagenames\n" +
  110. "JDT/JUnit org.eclim.java.junit.command\n" +
  111. "JDT/JUnit org.eclim.java.junit.output_dir\n" +
  112. "JDT/JUnit org.eclim.java.junit.src_dir\n" +
  113. "JDT/JUnit org.eclim.java.junit.version 4 (3|4)"
  114. );
  115. // Indentation settings found in DefaultCodeFormatterConstants
  116. PreferenceFactory.addOptions(NATURE,
  117. "JDT org.eclipse.jdt.core.compiler.source 1\\.[3-6]\n" +
  118. "JDT org.eclipse.jdt.core.formatter.tabulation.char (space|tab|mixed)\n" +
  119. "JDT org.eclipse.jdt.core.formatter.tabulation.size [1-9][0-9]*\n" +
  120. "JDT org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations (true|false)\n" +
  121. "JDT org.eclipse.jdt.ui.importorder [a-zA-Z0-9_.#;]+"
  122. );
  123. }
  124. /**
  125. * {@inheritDoc}
  126. * @see AbstractPluginResources#getBundleBaseName()
  127. */
  128. protected String getBundleBaseName()
  129. {
  130. return "org/eclim/plugin/jdt/messages";
  131. }
  132. /**
  133. * Performs additional logic to locate jre src zip file in alternate locations
  134. * not checked by eclipse.
  135. */
  136. protected void initializeJreSrc()
  137. {
  138. // doing a straight JavaCore.setClasspathVariable() doesn't work, so we need
  139. // to modify the library path of the default vm install.
  140. try{
  141. IVMInstall vm = JavaRuntime.getDefaultVMInstall();
  142. LibraryLocation[] locations = JavaRuntime.getLibraryLocations(vm);
  143. LibraryLocation[] newLocations = new LibraryLocation[locations.length];
  144. for(int ii = 0; ii < locations.length; ii++){
  145. IPath libraryPath = locations[ii].getSystemLibraryPath();
  146. // eclipse didn't find src.zip, so search other known locations.
  147. if (libraryPath.lastSegment().equals("rt.jar") &&
  148. (locations[ii].getSystemLibrarySourcePath().isEmpty() ||
  149. !locations[ii].getSystemLibrarySourcePath().toFile().exists())){
  150. IPath jreSrc = null;
  151. logger.debug("Attempting to locate jre src.zip for JAVA_HOME: {}",
  152. SystemUtils.JAVA_HOME);
  153. for (int jj = 0; jj < SRC_LOCATIONS.length; jj++){
  154. String location = SRC_LOCATIONS[jj];
  155. // absolute path
  156. if (location.startsWith("/") ||
  157. location.indexOf(':') != -1){
  158. jreSrc = new Path(location);
  159. // relative path
  160. }else{
  161. jreSrc = libraryPath.removeLastSegments(3).append(location);
  162. }
  163. logger.debug("Trying location: {}", jreSrc);
  164. if(jreSrc.toFile().exists()){
  165. break;
  166. }
  167. }
  168. // other possibilities on windows machines:
  169. // library path: C:/.../jre<version>/
  170. // src archive: C:/.../jdk<version>/src.zip
  171. // or
  172. // library path: C:/.../jre<major>/
  173. // src archive: C:/.../jdk1.<major>.<minor>_<patch>/src.zip
  174. if (!jreSrc.toFile().exists() && Os.isFamily(Os.FAMILY_WINDOWS)){
  175. String path = libraryPath.toOSString()
  176. .replaceFirst("\\\\(lib\\\\)rt.jar", "");
  177. // first scenerio
  178. String altHome = path.replaceFirst(
  179. "jre(\\d+\\.\\d+\\.\\d+_\\d+)", "jdk$1");
  180. if (!altHome.equals(path)){
  181. jreSrc = new Path(altHome).append("src.zip");
  182. }
  183. // second scenerio
  184. if (!jreSrc.toFile().exists()){
  185. String base = FileUtils.getBaseName(path);
  186. final String major = base.replaceFirst("^jre(\\d)$", "$1");
  187. if (!major.equals(base)){
  188. File dir = new File(FileUtils.getFullPath(path));
  189. String[] jdks = dir.list(new FilenameFilter(){
  190. private final Pattern JDK =
  191. Pattern.compile("jdk\\d+\\." + major + "\\.\\d+_\\d+");
  192. public boolean accept(File dir, String name){
  193. return JDK.matcher(name).matches();
  194. }
  195. });
  196. for (String jdk : jdks){
  197. jreSrc = new Path(dir.toString()).append(jdk).append("src.zip");
  198. if (jreSrc.toFile().exists()){
  199. break;
  200. }
  201. }
  202. }
  203. }
  204. }
  205. // jre src found.
  206. if(jreSrc.toFile().exists()){
  207. logger.info("Setting '{}' to '{}'",
  208. JavaRuntime.JRESRC_VARIABLE, jreSrc);
  209. newLocations[ii] = new LibraryLocation(
  210. locations[ii].getSystemLibraryPath(),
  211. jreSrc,
  212. locations[ii].getPackageRootPath(),
  213. locations[ii].getJavadocLocation());
  214. // jre src not found.
  215. }else{
  216. logger.warn(
  217. "Unable to locate jre src.zip for JAVA_HOME: " +
  218. SystemUtils.JAVA_HOME);
  219. newLocations[ii] = new LibraryLocation(
  220. locations[ii].getSystemLibraryPath(),
  221. Path.EMPTY,
  222. locations[ii].getPackageRootPath(),
  223. locations[ii].getJavadocLocation());
  224. }
  225. }else{
  226. newLocations[ii] = locations[ii];
  227. }
  228. }
  229. vm.setLibraryLocations(newLocations);
  230. }catch(Exception e){
  231. logger.error("", e);
  232. }
  233. }
  234. /**
  235. * Loads variables from property file.
  236. *
  237. * @param variable The prefix of the property file.
  238. */
  239. protected void initializeVars(String variable)
  240. {
  241. String file = "/" + variable + ".properties";
  242. logger.debug("Loading classpath variables from '{}'.", file);
  243. InputStream in = null;
  244. try{
  245. in = getClass().getResourceAsStream(file);
  246. String propertiesString = IOUtils.toString(in);
  247. HashMap<Object, String> values = new HashMap<Object, String>();
  248. for(Object key : System.getProperties().keySet()){
  249. values.put(key, System.getProperty((String)key).replace('\\', '/'));
  250. }
  251. propertiesString =
  252. StringUtils.replacePlaceholders(propertiesString, values);
  253. Properties properties = new Properties();
  254. properties.load(new ByteArrayInputStream(propertiesString.getBytes()));
  255. for(Object key : properties.keySet()){
  256. String name = (String)key;
  257. IPath path = new Path(properties.getProperty(name));
  258. logger.debug("Setting classpath variable '{}' to path '{}'", name, path);
  259. JavaCore.setClasspathVariable(name, path, null);
  260. }
  261. }catch(Exception e){
  262. logger.error("", e);
  263. }finally{
  264. IOUtils.closeQuietly(in);
  265. }
  266. }
  267. }