/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenUtil.java

https://bitbucket.org/nbargnesi/idea · Java · 726 lines · 620 code · 89 blank · 17 comment · 121 complexity · 0341a227e39a3832f1815cda6c323cb3 MD5 · raw file

  1. /*
  2. * Copyright 2000-2009 JetBrains s.r.o.
  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 org.jetbrains.idea.maven.utils;
  17. import com.intellij.codeInsight.template.TemplateManager;
  18. import com.intellij.codeInsight.template.impl.TemplateImpl;
  19. import com.intellij.execution.configurations.ParametersList;
  20. import com.intellij.ide.fileTemplates.FileTemplate;
  21. import com.intellij.ide.fileTemplates.FileTemplateManager;
  22. import com.intellij.notification.Notification;
  23. import com.intellij.notification.NotificationType;
  24. import com.intellij.notification.Notifications;
  25. import com.intellij.openapi.application.ApplicationManager;
  26. import com.intellij.openapi.application.ModalityState;
  27. import com.intellij.openapi.application.PathManager;
  28. import com.intellij.openapi.application.impl.LaterInvocator;
  29. import com.intellij.openapi.editor.Editor;
  30. import com.intellij.openapi.fileEditor.FileEditorManager;
  31. import com.intellij.openapi.fileEditor.OpenFileDescriptor;
  32. import com.intellij.openapi.progress.ProcessCanceledException;
  33. import com.intellij.openapi.progress.ProgressIndicator;
  34. import com.intellij.openapi.progress.ProgressManager;
  35. import com.intellij.openapi.progress.Task;
  36. import com.intellij.openapi.project.DumbService;
  37. import com.intellij.openapi.project.Project;
  38. import com.intellij.openapi.startup.StartupManager;
  39. import com.intellij.openapi.util.Comparing;
  40. import com.intellij.openapi.util.Pair;
  41. import com.intellij.openapi.util.SystemInfo;
  42. import com.intellij.openapi.util.io.FileUtil;
  43. import com.intellij.openapi.util.text.StringUtil;
  44. import com.intellij.openapi.vfs.JarFileSystem;
  45. import com.intellij.openapi.vfs.LocalFileSystem;
  46. import com.intellij.openapi.vfs.VfsUtil;
  47. import com.intellij.openapi.vfs.VirtualFile;
  48. import com.intellij.util.Function;
  49. import com.intellij.util.SystemProperties;
  50. import com.intellij.util.containers.ContainerUtil;
  51. import gnu.trove.THashSet;
  52. import org.jetbrains.annotations.NotNull;
  53. import org.jetbrains.annotations.Nullable;
  54. import org.jetbrains.idea.maven.model.MavenConstants;
  55. import org.jetbrains.idea.maven.model.MavenId;
  56. import org.jetbrains.idea.maven.project.MavenProject;
  57. import org.jetbrains.idea.maven.server.MavenServerManager;
  58. import org.jetbrains.idea.maven.server.MavenServerUtil;
  59. import java.io.File;
  60. import java.io.IOException;
  61. import java.net.URL;
  62. import java.util.*;
  63. import java.util.concurrent.ExecutionException;
  64. import java.util.concurrent.Future;
  65. import java.util.regex.Matcher;
  66. import java.util.regex.Pattern;
  67. import java.util.regex.PatternSyntaxException;
  68. public class MavenUtil {
  69. public static final String MAVEN_NOTIFICATION_GROUP = "Maven";
  70. public static final String SETTINGS_XML = "settings.xml";
  71. public static final String DOT_M2_DIR = ".m2";
  72. public static final String PROP_USER_HOME = "user.home";
  73. public static final String ENV_M2_HOME = "M2_HOME";
  74. public static final String M2_DIR = "m2";
  75. public static final String BIN_DIR = "bin";
  76. public static final String CONF_DIR = "conf";
  77. public static final String M2_CONF_FILE = "m2.conf";
  78. public static final String REPOSITORY_DIR = "repository";
  79. public static final String LIB_DIR = "lib";
  80. @SuppressWarnings("unchecked")
  81. private static final Pair<Pattern, String>[] SUPER_POM_PATHS = new Pair[]{
  82. Pair.create(Pattern.compile("maven-\\d+\\.\\d+\\.\\d+-uber\\.jar"), "org/apache/maven/project/" + MavenConstants.SUPER_POM_XML),
  83. Pair.create(Pattern.compile("maven-model-builder-\\d+\\.\\d+\\.\\d+\\.jar"), "org/apache/maven/model/" + MavenConstants.SUPER_POM_XML)
  84. };
  85. private static volatile Map<String, String> ourPropertiesFromMvnOpts;
  86. public static Map<String, String> getPropertiesFromMavenOpts() {
  87. Map<String, String> res = ourPropertiesFromMvnOpts;
  88. if (res == null) {
  89. String mavenOpts = System.getenv("MAVEN_OPTS");
  90. if (mavenOpts != null) {
  91. ParametersList mavenOptsList = new ParametersList();
  92. mavenOptsList.addParametersString(mavenOpts);
  93. res = mavenOptsList.getProperties();
  94. }
  95. else {
  96. res = Collections.emptyMap();
  97. }
  98. ourPropertiesFromMvnOpts = res;
  99. }
  100. return res;
  101. }
  102. public static void invokeLater(Project p, Runnable r) {
  103. invokeLater(p, ModalityState.defaultModalityState(), r);
  104. }
  105. public static void invokeLater(final Project p, final ModalityState state, final Runnable r) {
  106. if (isNoBackgroundMode()) {
  107. r.run();
  108. }
  109. else {
  110. ApplicationManager.getApplication().invokeLater(new Runnable() {
  111. public void run() {
  112. if (p.isDisposed()) return;
  113. r.run();
  114. }
  115. }, state);
  116. }
  117. }
  118. public static void invokeAndWait(Project p, Runnable r) {
  119. invokeAndWait(p, ModalityState.defaultModalityState(), r);
  120. }
  121. public static void invokeAndWait(final Project p, final ModalityState state, final Runnable r) {
  122. if (isNoBackgroundMode()) {
  123. r.run();
  124. }
  125. else {
  126. if (ApplicationManager.getApplication().isDispatchThread()) {
  127. r.run();
  128. }
  129. else {
  130. ApplicationManager.getApplication().invokeAndWait(new Runnable() {
  131. public void run() {
  132. if (p.isDisposed()) return;
  133. r.run();
  134. }
  135. }, state);
  136. }
  137. }
  138. }
  139. public static void invokeAndWaitWriteAction(Project p, final Runnable r) {
  140. invokeAndWait(p, new Runnable() {
  141. public void run() {
  142. ApplicationManager.getApplication().runWriteAction(r);
  143. }
  144. });
  145. }
  146. public static void runDumbAware(final Project project, final Runnable r) {
  147. if (DumbService.isDumbAware(r)) {
  148. r.run();
  149. }
  150. else {
  151. DumbService.getInstance(project).runWhenSmart(new Runnable() {
  152. public void run() {
  153. if (project.isDisposed()) return;
  154. r.run();
  155. }
  156. });
  157. }
  158. }
  159. public static void runWhenInitialized(final Project project, final Runnable r) {
  160. if (project.isDisposed()) return;
  161. if (isNoBackgroundMode()) {
  162. r.run();
  163. return;
  164. }
  165. if (!project.isInitialized()) {
  166. StartupManager.getInstance(project).registerPostStartupActivity(r);
  167. return;
  168. }
  169. runDumbAware(project, r);
  170. }
  171. public static boolean isNoBackgroundMode() {
  172. return (ApplicationManager.getApplication().isUnitTestMode()
  173. || ApplicationManager.getApplication().isHeadlessEnvironment());
  174. }
  175. public static boolean isInModalContext() {
  176. if (isNoBackgroundMode()) return false;
  177. return LaterInvocator.isInModalContext();
  178. }
  179. public static void showError(Project project, String title, Throwable e) {
  180. MavenLog.LOG.warn(title, e);
  181. Notifications.Bus.notify(new Notification(MAVEN_NOTIFICATION_GROUP, title, e.getMessage(), NotificationType.ERROR), project);
  182. }
  183. public static Properties getSystemProperties() {
  184. Properties result = (Properties)System.getProperties().clone();
  185. for (String each : new THashSet<String>((Set)result.keySet())) {
  186. if (each.startsWith("idea.")) {
  187. result.remove(each);
  188. }
  189. }
  190. return result;
  191. }
  192. public static Properties getEnvProperties() {
  193. Properties reuslt = new Properties();
  194. for (Map.Entry<String, String> each : System.getenv().entrySet()) {
  195. if (isMagicalProperty(each.getKey())) continue;
  196. reuslt.put(each.getKey(), each.getValue());
  197. }
  198. return reuslt;
  199. }
  200. private static boolean isMagicalProperty(String key) {
  201. return key.startsWith("=");
  202. }
  203. public static File getPluginSystemDir(String folder) {
  204. // PathManager.getSystemPath() may return relative path
  205. return new File(PathManager.getSystemPath(), "Maven" + "/" + folder).getAbsoluteFile();
  206. }
  207. public static VirtualFile findProfilesXmlFile(VirtualFile pomFile) {
  208. return pomFile.getParent().findChild(MavenConstants.PROFILES_XML);
  209. }
  210. public static File getProfilesXmlIoFile(VirtualFile pomFile) {
  211. return new File(pomFile.getParent().getPath(), MavenConstants.PROFILES_XML);
  212. }
  213. public static <T, U> List<T> collectFirsts(List<Pair<T, U>> pairs) {
  214. List<T> result = new ArrayList<T>(pairs.size());
  215. for (Pair<T, ?> each : pairs) {
  216. result.add(each.first);
  217. }
  218. return result;
  219. }
  220. public static <T, U> List<U> collectSeconds(List<Pair<T, U>> pairs) {
  221. List<U> result = new ArrayList<U>(pairs.size());
  222. for (Pair<T, U> each : pairs) {
  223. result.add(each.second);
  224. }
  225. return result;
  226. }
  227. public static List<String> collectPaths(List<VirtualFile> files) {
  228. return ContainerUtil.map(files, new Function<VirtualFile, String>() {
  229. public String fun(VirtualFile file) {
  230. return file.getPath();
  231. }
  232. });
  233. }
  234. public static List<VirtualFile> collectFiles(Collection<MavenProject> projects) {
  235. return ContainerUtil.map(projects, new Function<MavenProject, VirtualFile>() {
  236. public VirtualFile fun(MavenProject project) {
  237. return project.getFile();
  238. }
  239. });
  240. }
  241. public static <T> boolean equalAsSets(final Collection<T> collection1, final Collection<T> collection2) {
  242. return toSet(collection1).equals(toSet(collection2));
  243. }
  244. private static <T> Collection<T> toSet(final Collection<T> collection) {
  245. return (collection instanceof Set ? collection : new THashSet<T>(collection));
  246. }
  247. public static <T, U> List<Pair<T, U>> mapToList(Map<T, U> map) {
  248. return ContainerUtil.map2List(map.entrySet(), new Function<Map.Entry<T, U>, Pair<T, U>>() {
  249. public Pair<T, U> fun(Map.Entry<T, U> tuEntry) {
  250. return Pair.create(tuEntry.getKey(), tuEntry.getValue());
  251. }
  252. });
  253. }
  254. public static String formatHtmlImage(URL url) {
  255. return "<img src=\"" + url + "\"> ";
  256. }
  257. public static void runOrApplyMavenProjectFileTemplate(Project project,
  258. VirtualFile file,
  259. MavenId projectId,
  260. boolean interactive) throws IOException {
  261. runOrApplyMavenProjectFileTemplate(project, file, projectId, null, null, interactive);
  262. }
  263. public static void runOrApplyMavenProjectFileTemplate(Project project,
  264. VirtualFile file,
  265. MavenId projectId,
  266. MavenId parentId,
  267. VirtualFile parentFile,
  268. boolean interactive) throws IOException {
  269. Properties properties = new Properties();
  270. Properties conditions = new Properties();
  271. properties.setProperty("GROUP_ID", projectId.getGroupId());
  272. properties.setProperty("ARTIFACT_ID", projectId.getArtifactId());
  273. properties.setProperty("VERSION", projectId.getVersion());
  274. if (parentId != null) {
  275. conditions.setProperty("HAS_PARENT", "true");
  276. properties.setProperty("PARENT_GROUP_ID", parentId.getGroupId());
  277. properties.setProperty("PARENT_ARTIFACT_ID", parentId.getArtifactId());
  278. properties.setProperty("PARENT_VERSION", parentId.getVersion());
  279. if (parentFile != null) {
  280. VirtualFile modulePath = file.getParent();
  281. VirtualFile parentModulePath = parentFile.getParent();
  282. if (!Comparing.equal(modulePath.getParent(), parentModulePath)) {
  283. String relativePath = VfsUtil.getPath(file, parentModulePath, '/');
  284. if (relativePath != null) {
  285. if (relativePath.endsWith("/")) relativePath = relativePath.substring(0, relativePath.length() - 1);
  286. conditions.setProperty("HAS_RELATIVE_PATH", "true");
  287. properties.setProperty("PARENT_RELATIVE_PATH", relativePath);
  288. }
  289. }
  290. }
  291. }
  292. runOrApplyFileTemplate(project, file, MavenFileTemplateGroupFactory.MAVEN_PROJECT_XML_TEMPLATE, properties, conditions, interactive);
  293. }
  294. public static void runFileTemplate(Project project,
  295. VirtualFile file,
  296. String templateName) throws IOException {
  297. runOrApplyFileTemplate(project, file, templateName, new Properties(), new Properties(), true);
  298. }
  299. private static void runOrApplyFileTemplate(Project project,
  300. VirtualFile file,
  301. String templateName,
  302. Properties properties,
  303. Properties conditions,
  304. boolean interactive) throws IOException {
  305. FileTemplateManager manager = FileTemplateManager.getInstance();
  306. FileTemplate fileTemplate = manager.getJ2eeTemplate(templateName);
  307. Properties allProperties = manager.getDefaultProperties(project);
  308. if (!interactive) {
  309. allProperties.putAll(properties);
  310. }
  311. allProperties.putAll(conditions);
  312. String text = fileTemplate.getText(allProperties);
  313. Pattern pattern = Pattern.compile("\\$\\{(.*)\\}");
  314. Matcher matcher = pattern.matcher(text);
  315. StringBuffer builder = new StringBuffer();
  316. while (matcher.find()) {
  317. matcher.appendReplacement(builder, "\\$" + matcher.group(1).toUpperCase() + "\\$");
  318. }
  319. matcher.appendTail(builder);
  320. text = builder.toString();
  321. TemplateImpl template = (TemplateImpl)TemplateManager.getInstance(project).createTemplate("", "", text);
  322. for (int i = 0; i < template.getSegmentsCount(); i++) {
  323. if (i == template.getEndSegmentNumber()) continue;
  324. String name = template.getSegmentName(i);
  325. String value = "\"" + properties.getProperty(name, "") + "\"";
  326. template.addVariable(name, value, value, true);
  327. }
  328. if (interactive) {
  329. OpenFileDescriptor descriptor = new OpenFileDescriptor(project, file);
  330. Editor editor = FileEditorManager.getInstance(project).openTextEditor(descriptor, true);
  331. editor.getDocument().setText("");
  332. TemplateManager.getInstance(project).startTemplate(editor, template);
  333. }
  334. else {
  335. VfsUtil.saveText(file, template.getTemplateText());
  336. }
  337. }
  338. public static <T extends Collection<Pattern>> T collectPattern(String text, T result) {
  339. String antPattern = FileUtil.convertAntToRegexp(text.trim());
  340. try {
  341. result.add(Pattern.compile(antPattern));
  342. }
  343. catch (PatternSyntaxException ignore) {
  344. }
  345. return result;
  346. }
  347. public static boolean isIncluded(String relativeName, List<Pattern> includes, List<Pattern> excludes) {
  348. boolean result = false;
  349. for (Pattern each : includes) {
  350. if (each.matcher(relativeName).matches()) {
  351. result = true;
  352. break;
  353. }
  354. }
  355. if (!result) return false;
  356. for (Pattern each : excludes) {
  357. if (each.matcher(relativeName).matches()) return false;
  358. }
  359. return true;
  360. }
  361. public static void run(Project project, String title, final MavenTask task) throws MavenProcessCanceledException {
  362. final Exception[] canceledEx = new Exception[1];
  363. final RuntimeException[] runtimeEx = new RuntimeException[1];
  364. final Error[] errorEx = new Error[1];
  365. ProgressManager.getInstance().run(new Task.Modal(project, title, true) {
  366. public void run(@NotNull ProgressIndicator i) {
  367. try {
  368. task.run(new MavenProgressIndicator(i));
  369. }
  370. catch (MavenProcessCanceledException e) {
  371. canceledEx[0] = e;
  372. }
  373. catch (ProcessCanceledException e) {
  374. canceledEx[0] = e;
  375. }
  376. catch (RuntimeException e) {
  377. runtimeEx[0] = e;
  378. }
  379. catch (Error e) {
  380. errorEx[0] = e;
  381. }
  382. }
  383. });
  384. if (canceledEx[0] instanceof MavenProcessCanceledException) throw (MavenProcessCanceledException)canceledEx[0];
  385. if (canceledEx[0] instanceof ProcessCanceledException) throw new MavenProcessCanceledException();
  386. if (runtimeEx[0] != null) throw runtimeEx[0];
  387. if (errorEx[0] != null) throw errorEx[0];
  388. }
  389. public static MavenTaskHandler runInBackground(final Project project,
  390. final String title,
  391. final boolean cancellable,
  392. final MavenTask task) {
  393. final MavenProgressIndicator indicator = new MavenProgressIndicator();
  394. Runnable runnable = new Runnable() {
  395. public void run() {
  396. if (project.isDisposed()) return;
  397. try {
  398. task.run(indicator);
  399. }
  400. catch (MavenProcessCanceledException ignore) {
  401. indicator.cancel();
  402. }
  403. catch (ProcessCanceledException ignore) {
  404. indicator.cancel();
  405. }
  406. }
  407. };
  408. if (isNoBackgroundMode()) {
  409. runnable.run();
  410. return new MavenTaskHandler() {
  411. public void waitFor() {
  412. }
  413. };
  414. }
  415. else {
  416. final Future<?> future = ApplicationManager.getApplication().executeOnPooledThread(runnable);
  417. final MavenTaskHandler handler = new MavenTaskHandler() {
  418. public void waitFor() {
  419. try {
  420. future.get();
  421. }
  422. catch (InterruptedException e) {
  423. MavenLog.LOG.error(e);
  424. }
  425. catch (ExecutionException e) {
  426. MavenLog.LOG.error(e);
  427. }
  428. }
  429. };
  430. invokeLater(project, new Runnable() {
  431. public void run() {
  432. if (future.isDone()) return;
  433. new Task.Backgroundable(project, title, cancellable) {
  434. public void run(@NotNull ProgressIndicator i) {
  435. indicator.setIndicator(i);
  436. handler.waitFor();
  437. }
  438. }.queue();
  439. }
  440. });
  441. return handler;
  442. }
  443. }
  444. @Nullable
  445. public static File resolveMavenHomeDirectory(@Nullable String overrideMavenHome) {
  446. if (!isEmptyOrSpaces(overrideMavenHome)) {
  447. return new File(overrideMavenHome);
  448. }
  449. String m2home = System.getenv(ENV_M2_HOME);
  450. if (!isEmptyOrSpaces(m2home)) {
  451. final File homeFromEnv = new File(m2home);
  452. if (isValidMavenHome(homeFromEnv)) {
  453. return homeFromEnv;
  454. }
  455. }
  456. String userHome = SystemProperties.getUserHome();
  457. if (!isEmptyOrSpaces(userHome)) {
  458. final File underUserHome = new File(userHome, M2_DIR);
  459. if (isValidMavenHome(underUserHome)) {
  460. return underUserHome;
  461. }
  462. }
  463. if (SystemInfo.isMac) {
  464. File home = fromBrew();
  465. if (home != null) {
  466. return home;
  467. }
  468. if ((home = fromMacSystemJavaTools()) != null) {
  469. return home;
  470. }
  471. }
  472. else if (SystemInfo.isLinux) {
  473. File home = new File("/usr/share/maven2");
  474. if (isValidMavenHome(home)) {
  475. return home;
  476. }
  477. }
  478. return null;
  479. }
  480. @Nullable
  481. private static File fromMacSystemJavaTools() {
  482. final File symlinkDir = new File("/usr/share/maven");
  483. if (isValidMavenHome(symlinkDir)) {
  484. return symlinkDir;
  485. }
  486. // well, try to search
  487. final File dir = new File("/usr/share/java");
  488. final String[] list = dir.list();
  489. if (list == null || list.length == 0) {
  490. return null;
  491. }
  492. String home = null;
  493. final String prefix = "maven-";
  494. final int versionIndex = prefix.length();
  495. for (String path : list) {
  496. if (path.startsWith(prefix) &&
  497. (home == null || StringUtil.compareVersionNumbers(path.substring(versionIndex), home.substring(versionIndex)) > 0)) {
  498. home = path;
  499. }
  500. }
  501. if (home != null) {
  502. File file = new File(dir, home);
  503. if (isValidMavenHome(file)) {
  504. return file;
  505. }
  506. }
  507. return null;
  508. }
  509. @Nullable
  510. private static File fromBrew() {
  511. final File brewDir = new File("/usr/local/Cellar/maven");
  512. final String[] list = brewDir.list();
  513. if (list == null || list.length == 0) {
  514. return null;
  515. }
  516. if (list.length > 1) {
  517. Arrays.sort(list, new Comparator<String>() {
  518. @Override
  519. public int compare(String o1, String o2) {
  520. return StringUtil.compareVersionNumbers(o2, o1);
  521. }
  522. });
  523. }
  524. final File file = new File(brewDir, list[0] + "/libexec");
  525. return isValidMavenHome(file) ? file : null;
  526. }
  527. public static boolean isEmptyOrSpaces(@Nullable String str) {
  528. return str == null || str.length() == 0 || str.trim().length() == 0;
  529. }
  530. public static boolean isValidMavenHome(File home) {
  531. return getMavenConfFile(home).exists();
  532. }
  533. public static File getMavenConfFile(File mavenHome) {
  534. return new File(new File(mavenHome, BIN_DIR), M2_CONF_FILE);
  535. }
  536. @Nullable
  537. public static File resolveGlobalSettingsFile(@Nullable String overriddenMavenHome) {
  538. File directory = resolveMavenHomeDirectory(overriddenMavenHome);
  539. if (directory == null) return null;
  540. return new File(new File(directory, CONF_DIR), SETTINGS_XML);
  541. }
  542. @NotNull
  543. public static File resolveUserSettingsFile(@Nullable String overriddenUserSettingsFile) {
  544. if (!isEmptyOrSpaces(overriddenUserSettingsFile)) return new File(overriddenUserSettingsFile);
  545. return new File(resolveM2Dir(), SETTINGS_XML);
  546. }
  547. @NotNull
  548. public static File resolveM2Dir() {
  549. return new File(SystemProperties.getUserHome(), DOT_M2_DIR);
  550. }
  551. @NotNull
  552. public static File resolveLocalRepository(@Nullable String overriddenLocalRepository,
  553. @Nullable String overriddenMavenHome,
  554. @Nullable String overriddenUserSettingsFile) {
  555. File result = null;
  556. if (!isEmptyOrSpaces(overriddenLocalRepository)) result = new File(overriddenLocalRepository);
  557. if (result == null) {
  558. result = doResolveLocalRepository(resolveUserSettingsFile(overriddenUserSettingsFile),
  559. resolveGlobalSettingsFile(overriddenMavenHome));
  560. }
  561. try {
  562. return result.getCanonicalFile();
  563. }
  564. catch (IOException e) {
  565. return result;
  566. }
  567. }
  568. @NotNull
  569. public static File doResolveLocalRepository(@Nullable File userSettingsFile, @Nullable File globalSettingsFile) {
  570. if (userSettingsFile != null) {
  571. final String fromUserSettings = getRepositoryFromSettings(userSettingsFile);
  572. if (!StringUtil.isEmpty(fromUserSettings)) {
  573. return new File(fromUserSettings);
  574. }
  575. }
  576. if (globalSettingsFile != null) {
  577. final String fromGlobalSettings = getRepositoryFromSettings(globalSettingsFile);
  578. if (!StringUtil.isEmpty(fromGlobalSettings)) {
  579. return new File(fromGlobalSettings);
  580. }
  581. }
  582. return new File(resolveM2Dir(), REPOSITORY_DIR);
  583. }
  584. @Nullable
  585. public static String getRepositoryFromSettings(final File file) {
  586. try {
  587. byte[] bytes = FileUtil.loadFileBytes(file);
  588. return expandProperties(MavenJDOMUtil.findChildValueByPath(MavenJDOMUtil.read(bytes, null), "localRepository", null));
  589. }
  590. catch (IOException e) {
  591. return null;
  592. }
  593. }
  594. public static String expandProperties(String text) {
  595. if (StringUtil.isEmptyOrSpaces(text)) return text;
  596. Properties props = MavenServerUtil.collectSystemProperties();
  597. for (Map.Entry<Object, Object> each : props.entrySet()) {
  598. Object val = each.getValue();
  599. text = text.replace("${" + each.getKey() + "}", val instanceof CharSequence ? (CharSequence)val : val.toString());
  600. }
  601. return text;
  602. }
  603. @NotNull
  604. public static VirtualFile resolveSuperPomFile(@Nullable File mavenHome) {
  605. VirtualFile result = null;
  606. if (mavenHome != null) {
  607. result = doResolveSuperPomFile(new File(mavenHome, LIB_DIR));
  608. }
  609. if (result == null) {
  610. result = doResolveSuperPomFile(MavenServerManager.collectClassPathAndLibsFolder().second);
  611. }
  612. return result;
  613. }
  614. @Nullable
  615. public static VirtualFile doResolveSuperPomFile(@NotNull File mavenHome) {
  616. File[] files = mavenHome.listFiles();
  617. if (files == null) return null;
  618. for (File library : files) {
  619. for (Pair<Pattern, String> path : SUPER_POM_PATHS) {
  620. if (path.first.matcher(library.getName()).matches()) {
  621. VirtualFile libraryVirtualFile = LocalFileSystem.getInstance().findFileByIoFile(library);
  622. if (libraryVirtualFile == null) continue;
  623. VirtualFile root = JarFileSystem.getInstance().getJarRootForLocalFile(libraryVirtualFile);
  624. if (root == null) continue;
  625. VirtualFile pomFile = root.findFileByRelativePath(path.second);
  626. if (pomFile != null) {
  627. return pomFile;
  628. }
  629. }
  630. }
  631. }
  632. return null;
  633. }
  634. public interface MavenTaskHandler {
  635. void waitFor();
  636. }
  637. }