diff --git a/.idea/modules.xml b/.idea/modules.xml index e177cad44135..d48c568c7a5d 100644 --- a/.idea/modules.xml +++ b/.idea/modules.xml @@ -58,7 +58,8 @@ - + + diff --git a/build/scripts/layouts.gant b/build/scripts/layouts.gant index 0ef5893a72fc..cd56346c2752 100644 --- a/build/scripts/layouts.gant +++ b/build/scripts/layouts.gant @@ -174,10 +174,14 @@ def layoutFull(String home, String targetDirectory) { layoutPlugin("maven") { - jar("maven-facade.jar") { - module("maven-facade") + jar("maven-facade-api.jar") { + module("maven-facade-api") } - fileset(dir: "$home/plugins/maven/lib") + jar("maven-facade-impl.jar") { + module("maven-facade-impl") + } + fileset(dir: "$home/plugins/maven/facade-impl/lib") + fileset(dir: "$home/plugins/maven/facade-api/lib") } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java index a5f75d1b6229..02c587c440d0 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java @@ -109,20 +109,8 @@ public class HighlightVisitorImpl extends JavaElementVisitor implements Highligh LOG.assertTrue(element.isValid()); } element.accept(this); - - if (myRefCountHolder != null) { - instantiateInjections(element); - } } - private void instantiateInjections(final PsiElement element) { - InjectedLanguageUtil.enumerate(element, myFile, new PsiLanguageInjectionHost.InjectedPsiVisitor() { - public void visit(@NotNull final PsiFile injectedPsi, @NotNull final List places) { - // no op - } - }, false); - } - private void registerReferencesFromInjectedFragments(final PsiElement element) { InjectedLanguageUtil.enumerate(element, myFile, new PsiLanguageInjectionHost.InjectedPsiVisitor() { public void visit(@NotNull final PsiFile injectedPsi, @NotNull final List places) { diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/RemoveUnusedVariableFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/RemoveUnusedVariableFix.java index 6d12e5e69805..cf9505c1b85c 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/RemoveUnusedVariableFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/RemoveUnusedVariableFix.java @@ -39,8 +39,6 @@ import java.util.*; public class RemoveUnusedVariableFix implements IntentionAction { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.quickfix.RemoveUnusedVariableFix"); private final PsiVariable myVariable; - @NonNls private static final String JAVA_LANG_PCKG = "java.lang"; - @NonNls private static final String JAVA_IO_PCKG = "java.io"; public RemoveUnusedVariableFix(PsiVariable variable) { myVariable = variable; @@ -356,10 +354,10 @@ public class RemoveUnusedVariableFix implements IntentionAction { PsiFile file = aClass.getContainingFile(); PsiDirectory directory = file.getContainingDirectory(); PsiPackage classPackage = JavaDirectoryService.getInstance().getPackage(directory); - String packageName = classPackage.getQualifiedName(); + String packageName = classPackage == null ? null : classPackage.getQualifiedName(); // all Throwable descendants from java.lang are side effects free - if (JAVA_LANG_PCKG.equals(packageName) || JAVA_IO_PCKG.equals(packageName)) { + if ("java.lang".equals(packageName) || "java.io".equals(packageName)) { PsiClass throwableClass = JavaPsiFacade.getInstance(aClass.getProject()).findClass("java.lang.Throwable", aClass.getResolveScope()); if (throwableClass != null && InheritanceUtil.isInheritorOrSelf(aClass, throwableClass, true)) { return true; diff --git a/java/java-impl/src/com/intellij/psi/impl/file/PsiPackageImpl.java b/java/java-impl/src/com/intellij/psi/impl/file/PsiPackageImpl.java index bd7885956600..94422d944b9c 100644 --- a/java/java-impl/src/com/intellij/psi/impl/file/PsiPackageImpl.java +++ b/java/java-impl/src/com/intellij/psi/impl/file/PsiPackageImpl.java @@ -497,7 +497,8 @@ public class PsiPackageImpl extends PsiElementBase implements PsiPackage, Querya NameHint nameHint = processor.getHint(NameHint.KEY); if (nameHint != null) { final String shortName = nameHint.getName(state); - if (containsClassNamed(shortName) && processClassesByName(processor, state, place, scope, shortName)) return false; + if ((migration != null || containsClassNamed(shortName)) + && processClassesByName(processor, state, place, scope, shortName)) return false; } else if (prefixMatcher != null && migration == null) { for (String className : getClassNamesCache()) { diff --git a/java/java-impl/src/com/intellij/psi/impl/source/PsiClassReferenceType.java b/java/java-impl/src/com/intellij/psi/impl/source/PsiClassReferenceType.java index be09f49c2670..0022b749bf5d 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/PsiClassReferenceType.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/PsiClassReferenceType.java @@ -138,7 +138,9 @@ public class PsiClassReferenceType extends PsiClassType { return factory.createType(aClass, rawSubstitutor, getLanguageLevel(), getAnnotations()); } String qualifiedName = myReference.getQualifiedName(); - LightClassReference reference = new LightClassReference(myReference.getManager(), myReference.getReferenceName(), qualifiedName, myReference.getResolveScope()); + String name = myReference.getReferenceName(); + if (name==null) name=""; + LightClassReference reference = new LightClassReference(myReference.getManager(), name, qualifiedName, myReference.getResolveScope()); return new PsiClassReferenceType(reference, null,getAnnotations()); } diff --git a/java/openapi/src/com/intellij/psi/util/PropertyUtil.java b/java/openapi/src/com/intellij/psi/util/PropertyUtil.java index 615dce0ebb35..ec4cb396e9a4 100644 --- a/java/openapi/src/com/intellij/psi/util/PropertyUtil.java +++ b/java/openapi/src/com/intellij/psi/util/PropertyUtil.java @@ -54,16 +54,17 @@ public class PropertyUtil { String methodName = method.getName(); PsiType returnType = method.getReturnType(); - if (methodName.startsWith("get") && methodName.length() > "get".length()) { + int methodNameLength = methodName.length(); + if (methodName.startsWith("get") && methodNameLength > "get".length()) { if (Character.isLowerCase(methodName.charAt("get".length())) - && (methodName.length() == "get".length() + 1 || Character.isLowerCase(methodName.charAt("get".length() + 1)))) { + && (methodNameLength == "get".length() + 1 || Character.isLowerCase(methodName.charAt("get".length() + 1)))) { return false; } if (returnType != null && PsiType.VOID.equals(returnType)) return false; } - else if (methodName.startsWith("is") && methodName.length() > "is".length()) { + else if (methodName.startsWith("is") && methodNameLength > "is".length()) { if (Character.isLowerCase(methodName.charAt("is".length())) - && (methodName.length() == "is".length() + 1 || Character.isLowerCase(methodName.charAt("is".length() + 1)))) { + && (methodNameLength == "is".length() + 1 || Character.isLowerCase(methodName.charAt("is".length() + 1)))) { return false; } return isBoolean(returnType); @@ -209,7 +210,8 @@ public class PropertyUtil { return null; } - @Nullable public static PsiMethod findPropertyGetterWithType(String propertyName, boolean isStatic, PsiType type, Iterator methods) { + @Nullable + public static PsiMethod findPropertyGetterWithType(String propertyName, boolean isStatic, PsiType type, Iterator methods) { while (methods.hasNext()) { PsiMethod method = methods.next(); if (method.hasModifierProperty(PsiModifier.STATIC) != isStatic) continue; @@ -252,7 +254,8 @@ public class PropertyUtil { return null; } - @Nullable public static PsiMethod findPropertySetterWithType(String propertyName, boolean isStatic, PsiType type, Iterator methods) { + @Nullable + public static PsiMethod findPropertySetterWithType(String propertyName, boolean isStatic, PsiType type, Iterator methods) { while (methods.hasNext()) { PsiMethod method = methods.next(); if (method.hasModifierProperty(PsiModifier.STATIC) != isStatic) continue; @@ -500,7 +503,8 @@ public class PropertyUtil { /** * "xxx", "void setMyProperty(String pp)" -> "setXxx" */ - @Nullable public static String suggestPropertyAccessor(String name, PsiMethod accessorTemplate) { + @Nullable + public static String suggestPropertyAccessor(String name, PsiMethod accessorTemplate) { if (isSimplePropertyGetter(accessorTemplate)) { PsiType type = accessorTemplate.getReturnType(); return suggestGetterName(name, type, accessorTemplate.getName()); diff --git a/native/fsNotifier/linux/fsnotifier b/native/fsNotifier/linux/fsnotifier index 3d84ba68c1c2..9290ab239af5 100755 Binary files a/native/fsNotifier/linux/fsnotifier and b/native/fsNotifier/linux/fsnotifier differ diff --git a/native/fsNotifier/linux/fsnotifier64 b/native/fsNotifier/linux/fsnotifier64 index 1c959e2ddfb8..3a573dd7a183 100755 Binary files a/native/fsNotifier/linux/fsnotifier64 and b/native/fsNotifier/linux/fsnotifier64 differ diff --git a/native/fsNotifier/linux/inotify.c b/native/fsNotifier/linux/inotify.c index b3306e5c64ed..411a6def1733 100644 --- a/native/fsNotifier/linux/inotify.c +++ b/native/fsNotifier/linux/inotify.c @@ -284,7 +284,9 @@ static int walk_tree(const char* path, watch_node* parent, array* ignores) { int watch(const char* root, array* ignores) { - return walk_tree(root, NULL, ignores); + char buf[PATH_MAX]; + const char* normalized = realpath(root, buf); + return walk_tree((normalized != NULL ? normalized : root), NULL, ignores); } diff --git a/native/fsNotifier/linux/make.sh b/native/fsNotifier/linux/make.sh index e2741da2778d..f2ec112fc406 100755 --- a/native/fsNotifier/linux/make.sh +++ b/native/fsNotifier/linux/make.sh @@ -1,2 +1,5 @@ +#!/bin/sh +echo "compiling 32-bit version" gcc -O2 -m32 -Wall -std=c99 -D_BSD_SOURCE -D_XOPEN_SOURCE=500 -o fsnotifier main.c inotify.c util.c +echo "compiling 64-bit version" gcc -O2 -m64 -Wall -std=c99 -D_BSD_SOURCE -D_XOPEN_SOURCE=500 -o fsnotifier64 main.c inotify.c util.c diff --git a/platform/lang-api/src/com/intellij/execution/configurations/CommandLineState.java b/platform/lang-api/src/com/intellij/execution/configurations/CommandLineState.java index f74fa8690af7..ea75268d6e7d 100644 --- a/platform/lang-api/src/com/intellij/execution/configurations/CommandLineState.java +++ b/platform/lang-api/src/com/intellij/execution/configurations/CommandLineState.java @@ -18,7 +18,6 @@ package com.intellij.execution.configurations; import com.intellij.execution.*; import com.intellij.execution.executors.DefaultRunExecutor; import com.intellij.execution.filters.TextConsoleBuilder; -import com.intellij.execution.process.OSProcessHandler; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.runners.ProgramRunner; @@ -61,7 +60,7 @@ public abstract class CommandLineState implements RunnableState { return new DefaultExecutionResult(console, processHandler, createActions(console, processHandler, executor)); } - protected abstract OSProcessHandler startProcess() throws ExecutionException; + protected abstract ProcessHandler startProcess() throws ExecutionException; protected AnAction[] createActions(final ConsoleView console, final ProcessHandler processHandler) { return createActions(console, processHandler, null); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/CollectHighlightsUtil.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/CollectHighlightsUtil.java index 6afc04842402..59f11b128a57 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/CollectHighlightsUtil.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/CollectHighlightsUtil.java @@ -26,10 +26,13 @@ import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.Condition; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.*; +import com.intellij.psi.PsiCodeFragment; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtilBase; -import gnu.trove.TIntArrayList; +import com.intellij.util.containers.Stack; +import gnu.trove.TIntStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -37,7 +40,7 @@ import java.util.ArrayList; import java.util.List; public class CollectHighlightsUtil { - private static final ExtensionPointName> EP_NAME = ExtensionPointName.create("com.intellij.elementsToHighlightFilter"); + public static final ExtensionPointName> EP_NAME = ExtensionPointName.create("com.intellij.elementsToHighlightFilter"); private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.CollectHighlightsUtil"); @@ -76,65 +79,58 @@ public class CollectHighlightsUtil { final int currentOffset = commonParent.getTextRange().getStartOffset(); final Condition[] filters = Extensions.getExtensions(EP_NAME); - final PsiElementVisitor visitor = new PsiElementVisitor() { - int offset = currentOffset; - - final TIntArrayList starts = new TIntArrayList(STARTING_TREE_HEIGHT); - final List elements = new ArrayList(STARTING_TREE_HEIGHT); - final List children = new ArrayList(STARTING_TREE_HEIGHT); - - @Override public void visitElement(PsiElement element) { - children.add(PsiUtilBase.NULL_PSI_ELEMENT); - - while (true) { - ProgressManager.checkCanceled(); - - PsiElement child = children.remove(children.size() - 1); + int offset = currentOffset; - for (Condition filter : filters) { - if (!filter.value(element)) { - assert child == PsiUtilBase.NULL_PSI_ELEMENT; - child = null; // do not want to process children - break; - } - } + final TIntStack starts = new TIntStack(STARTING_TREE_HEIGHT); + final Stack elements = new Stack(STARTING_TREE_HEIGHT); + final Stack children = new Stack(STARTING_TREE_HEIGHT); + PsiElement element = commonParent; - boolean startChildrenVisiting = false; + PsiElement child = PsiUtilBase.NULL_PSI_ELEMENT; + while (true) { + ProgressManager.checkCanceled(); - if (child == PsiUtilBase.NULL_PSI_ELEMENT) { - startChildrenVisiting = true; - child = element.getFirstChild(); - } - - if (child == null) { - if (startChildrenVisiting) { - // leaf element - offset += element.getTextLength(); - } - - if (elements.size() == 0) break; - int start = starts.remove(starts.size() - 1); - if (startOffset <= start && offset <= endOffset) result.add(element); - - element = elements.remove(elements.size() - 1); - } - else { - // composite element - if (offset <= endOffset) { - starts.add(offset); - children.add(child.getNextSibling()); - children.add(PsiUtilBase.NULL_PSI_ELEMENT); - elements.add(element); - element = child; - } else { - break; - } - } + for (Condition filter : filters) { + if (!filter.value(element)) { + assert child == PsiUtilBase.NULL_PSI_ELEMENT; + child = null; // do not want to process children + break; } } - }; - commonParent.accept(visitor); - + + boolean startChildrenVisiting; + if (child == PsiUtilBase.NULL_PSI_ELEMENT) { + startChildrenVisiting = true; + child = element.getFirstChild(); + } + else { + startChildrenVisiting = false; + } + + if (child == null) { + if (startChildrenVisiting) { + // leaf element + offset += element.getTextLength(); + } + + if (elements.isEmpty()) break; + int start = starts.pop(); + if (startOffset <= start && offset <= endOffset) result.add(element); + + element = elements.pop(); + child = children.pop(); + } + else { + // composite element + if (offset > endOffset) break; + children.push(child.getNextSibling()); + starts.push(offset); + elements.push(element); + element = child; + child = PsiUtilBase.NULL_PSI_ELEMENT; + } + } + return result; } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerImpl.java index 98e0398777e2..6c14fadc30d7 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerImpl.java @@ -16,35 +16,54 @@ package com.intellij.codeInsight.daemon.impl; -import com.intellij.codeHighlighting.*; +import com.intellij.codeHighlighting.BackgroundEditorHighlighter; +import com.intellij.codeHighlighting.HighlightingPass; import com.intellij.codeHighlighting.Pass; -import com.intellij.codeInsight.daemon.*; -import com.intellij.codeInsight.hint.*; -import com.intellij.codeInsight.intention.impl.*; -import com.intellij.concurrency.*; -import com.intellij.lang.annotation.*; -import com.intellij.openapi.application.*; -import com.intellij.openapi.diagnostic.*; +import com.intellij.codeHighlighting.TextEditorHighlightingPass; +import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer; +import com.intellij.codeInsight.daemon.DaemonCodeAnalyzerSettings; +import com.intellij.codeInsight.daemon.LineMarkerInfo; +import com.intellij.codeInsight.daemon.ReferenceImporter; +import com.intellij.codeInsight.hint.HintManager; +import com.intellij.codeInsight.intention.impl.IntentionHintComponent; +import com.intellij.concurrency.Job; +import com.intellij.lang.annotation.HighlightSeverity; +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; -import com.intellij.openapi.editor.*; -import com.intellij.openapi.editor.ex.*; -import com.intellij.openapi.editor.markup.*; -import com.intellij.openapi.extensions.*; -import com.intellij.openapi.fileEditor.*; -import com.intellij.openapi.fileEditor.impl.text.*; -import com.intellij.openapi.fileTypes.*; -import com.intellij.openapi.progress.*; -import com.intellij.openapi.project.*; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.editor.ex.EditorMarkupModel; +import com.intellij.openapi.editor.markup.MarkupModel; +import com.intellij.openapi.editor.markup.RangeHighlighter; +import com.intellij.openapi.extensions.Extensions; +import com.intellij.openapi.fileEditor.FileEditor; +import com.intellij.openapi.fileEditor.TextEditor; +import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider; +import com.intellij.openapi.fileTypes.FileType; +import com.intellij.openapi.fileTypes.StdFileTypes; +import com.intellij.openapi.progress.ProgressIndicator; +import com.intellij.openapi.project.Project; import com.intellij.openapi.util.*; -import com.intellij.openapi.vfs.*; -import com.intellij.packageDependencies.*; -import com.intellij.psi.*; -import com.intellij.psi.search.scope.packageSet.*; -import com.intellij.util.*; -import com.intellij.util.containers.*; -import gnu.trove.*; -import org.jdom.*; -import org.jetbrains.annotations.*; +import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.openapi.vfs.VirtualFileManager; +import com.intellij.packageDependencies.DependencyValidationManager; +import com.intellij.psi.PsiCompiledElement; +import com.intellij.psi.PsiDocumentManager; +import com.intellij.psi.PsiFile; +import com.intellij.psi.PsiFileSystemItem; +import com.intellij.psi.search.scope.packageSet.NamedScope; +import com.intellij.psi.search.scope.packageSet.NamedScopeManager; +import com.intellij.psi.search.scope.packageSet.NamedScopesHolder; +import com.intellij.util.Alarm; +import com.intellij.util.SmartList; +import com.intellij.util.containers.ContainerUtil; +import gnu.trove.THashMap; +import gnu.trove.THashSet; +import org.jdom.Element; +import org.jetbrains.annotations.NonNls; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.TestOnly; import java.util.*; @@ -82,6 +101,7 @@ public class DaemonCodeAnalyzerImpl extends DaemonCodeAnalyzer implements JDOMEx @NonNls private static final String FILE_TAG = "file"; @NonNls private static final String URL_ATT = "url"; private DaemonListeners myDaemonListeners; + private StatusBarUpdater myStatusBarUpdater; private final PassExecutorService myPassExecutorService; private static final Key> HIGHLIGHTS_TO_REMOVE_KEY = Key.create("HIGHLIGHTS_TO_REMOVE"); private int myModificationCount = 0; @@ -126,6 +146,9 @@ public class DaemonCodeAnalyzerImpl extends DaemonCodeAnalyzer implements JDOMEx public void projectOpened() { assert !myInitialized : "Double Initializing"; + myStatusBarUpdater = new StatusBarUpdater(myProject); + Disposer.register(myProject, myStatusBarUpdater); + myDaemonListeners = new DaemonListeners(myProject, this, myEditorTracker); Disposer.register(myProject, myDaemonListeners); reloadScopes(); @@ -451,6 +474,11 @@ public class DaemonCodeAnalyzerImpl extends DaemonCodeAnalyzer implements JDOMEx markup.putUserData(HIGHLIGHTS_IN_EDITOR_DOCUMENT_KEY, Collections.unmodifiableList(highlightsToSet)); markup.putUserData(HIGHLIGHTS_TO_REMOVE_KEY, Collections.unmodifiableList(highlightsToRemove)); + + DaemonCodeAnalyzer codeAnalyzer = DaemonCodeAnalyzer.getInstance(project); + if (codeAnalyzer instanceof DaemonCodeAnalyzerImpl && ((DaemonCodeAnalyzerImpl)codeAnalyzer).myStatusBarUpdater != null) { + ((DaemonCodeAnalyzerImpl)codeAnalyzer).myStatusBarUpdater.updateStatus(); + } } private static void stripWarningsCoveredByErrors(final Project project, List highlights, MarkupModel markup) { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/StatusBarUpdater.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/StatusBarUpdater.java new file mode 100644 index 000000000000..67c7ddebd635 --- /dev/null +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/StatusBarUpdater.java @@ -0,0 +1,94 @@ + +/* + * Copyright 2000-2009 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.intellij.codeInsight.daemon.impl; + +import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer; +import com.intellij.openapi.Disposable; +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.editor.Document; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.editor.EditorFactory; +import com.intellij.openapi.editor.event.CaretEvent; +import com.intellij.openapi.editor.event.CaretListener; +import com.intellij.openapi.editor.ex.DocumentEx; +import com.intellij.openapi.fileEditor.FileEditorManager; +import com.intellij.openapi.fileEditor.FileEditorManagerAdapter; +import com.intellij.openapi.fileEditor.FileEditorManagerEvent; +import com.intellij.openapi.fileEditor.FileEditorManagerListener; +import com.intellij.openapi.project.DumbAwareRunnable; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.wm.StatusBar; +import com.intellij.openapi.wm.WindowManager; +import com.intellij.openapi.wm.ex.StatusBarEx; + +public class StatusBarUpdater implements Disposable { + private final Project myProject; + private final UpdateStatusRunnable myUpdateStatusRunnable = new UpdateStatusRunnable(); + + public StatusBarUpdater(Project project) { + myProject = project; + + CaretListener caretListener = new CaretListener() { + public void caretPositionChanged(CaretEvent e) { + ApplicationManager.getApplication().invokeLater(myUpdateStatusRunnable); + } + }; + EditorFactory.getInstance().getEventMulticaster().addCaretListener(caretListener, this); + + project.getMessageBus().connect().subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileEditorManagerAdapter() { + @Override + public void selectionChanged(FileEditorManagerEvent event) { + ApplicationManager.getApplication().invokeLater(myUpdateStatusRunnable); + } + }); + } + + public void dispose() { + } + + public void updateStatus() { + Editor editor = FileEditorManager.getInstance(myProject).getSelectedTextEditor(); + if (editor == null || !editor.getContentComponent().hasFocus()){ + return; + } + + final Document document = editor.getDocument(); + if (document instanceof DocumentEx && ((DocumentEx)document).isInBulkUpdate()) return; + + int offset = editor.getCaretModel().getOffset(); + DaemonCodeAnalyzer codeAnalyzer = DaemonCodeAnalyzer.getInstance(myProject); + HighlightInfo info = ((DaemonCodeAnalyzerImpl)codeAnalyzer).findHighlightByOffset(document, offset, false); + String text = info != null && info.description != null ? info.description : ""; + + StatusBar statusBar = WindowManager.getInstance().getStatusBar(myProject); + if (statusBar instanceof StatusBarEx) { + StatusBarEx barEx = (StatusBarEx)statusBar; + if (!text.equals(barEx.getInfo())){ + statusBar.setInfo(text); + } + } + } + + private class UpdateStatusRunnable implements DumbAwareRunnable { + public void run() { + if (!myProject.isDisposed()) { + updateStatus(); + } + } + } +} \ No newline at end of file diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/smartEnter/SmartEnterAction.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/smartEnter/SmartEnterAction.java index 4fdf4dfad206..23f66a8cb3ad 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/smartEnter/SmartEnterAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/smartEnter/SmartEnterAction.java @@ -33,8 +33,6 @@ import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiUtilBase; import com.intellij.util.text.CharArrayUtil; -import java.util.List; - /** * @author max */ @@ -91,14 +89,9 @@ public class SmartEnterAction extends EditorAction { final Language language = PsiUtilBase.getLanguageInEditor(editor, project); boolean processed = false; if (language != null) { - final List processors = SmartEnterProcessors.INSTANCE.forKey(language); - if (!processors.isEmpty()) { - for (SmartEnterProcessor processor : processors) { - if (processor.process(project, editor, psiFile)) { - processed = true; - break; - } - } + final SmartEnterProcessor processor = SmartEnterProcessors.INSTANCE.forLanguage(language); + if (processor != null && processor.process(project, editor, psiFile)) { + processed = true; } } if (!processed) { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/problems/WolfTheProblemSolverImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/problems/WolfTheProblemSolverImpl.java index 4318a65a2cb6..69624d0e7bb4 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/problems/WolfTheProblemSolverImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/problems/WolfTheProblemSolverImpl.java @@ -73,25 +73,6 @@ public class WolfTheProblemSolverImpl extends WolfTheProblemSolver { } }; - private final VirtualFileListener myVirtualFileListener = new VirtualFileAdapter() { - public void fileDeleted(final VirtualFileEvent event) { - onDeleted(event.getFile()); - } - - public void fileMoved(final VirtualFileMoveEvent event) { - onDeleted(event.getFile()); - } - - private void onDeleted(final VirtualFile file) { - if (file.isDirectory()) { - clearInvalidFiles(); - } - else { - doRemove(file); - } - } - }; - private void doRemove(VirtualFile problemFile) { ProblemFileInfo old; synchronized (myProblems) { @@ -106,8 +87,6 @@ public class WolfTheProblemSolverImpl extends WolfTheProblemSolver { } } - private final PsiTreeChangeListener myChangeListener; - private static class ProblemFileInfo { private final Collection problems = new THashSet(); private boolean hasSyntaxErrors; @@ -118,10 +97,7 @@ public class WolfTheProblemSolverImpl extends WolfTheProblemSolver { final ProblemFileInfo that = (ProblemFileInfo)o; - if (hasSyntaxErrors != that.hasSyntaxErrors) return false; - if (!problems.equals(that.problems)) return false; - - return true; + return hasSyntaxErrors == that.hasSyntaxErrors && problems.equals(that.problems); } public int hashCode() { @@ -133,7 +109,7 @@ public class WolfTheProblemSolverImpl extends WolfTheProblemSolver { public WolfTheProblemSolverImpl(Project project, PsiManager psiManager, VirtualFileManager virtualFileManager) { myProject = project; - myChangeListener = new PsiTreeChangeAdapter() { + PsiTreeChangeListener changeListener = new PsiTreeChangeAdapter() { public void childAdded(PsiTreeChangeEvent event) { childrenChanged(event); } @@ -158,8 +134,26 @@ public class WolfTheProblemSolverImpl extends WolfTheProblemSolver { clearSyntaxErrorFlag(event); } }; - psiManager.addPsiTreeChangeListener(myChangeListener); - virtualFileManager.addVirtualFileListener(myVirtualFileListener, myProject); + psiManager.addPsiTreeChangeListener(changeListener); + VirtualFileListener virtualFileListener = new VirtualFileAdapter() { + public void fileDeleted(final VirtualFileEvent event) { + onDeleted(event.getFile()); + } + + public void fileMoved(final VirtualFileMoveEvent event) { + onDeleted(event.getFile()); + } + + private void onDeleted(final VirtualFile file) { + if (file.isDirectory()) { + clearInvalidFiles(); + } + else { + doRemove(file); + } + } + }; + virtualFileManager.addVirtualFileListener(virtualFileListener, myProject); FileStatusManager fileStatusManager = FileStatusManager.getInstance(myProject); if (fileStatusManager != null) { //tests? fileStatusManager.addFileStatusListener(new FileStatusListener() { diff --git a/platform/lang-impl/src/com/intellij/execution/rmi/RemoteProcessSupport.java b/platform/lang-impl/src/com/intellij/execution/rmi/RemoteProcessSupport.java index 9da838b8559e..bd514d0da822 100644 --- a/platform/lang-impl/src/com/intellij/execution/rmi/RemoteProcessSupport.java +++ b/platform/lang-impl/src/com/intellij/execution/rmi/RemoteProcessSupport.java @@ -13,8 +13,8 @@ import com.intellij.execution.process.ProcessOutputTypes; import com.intellij.execution.runners.DefaultProgramRunner; import com.intellij.execution.runners.ProgramRunner; import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressManager; -import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Ref; @@ -34,20 +34,16 @@ import java.util.List; * @author Gregory.Shrago */ public abstract class RemoteProcessSupport { - private final Project myProject; + public static final Logger LOG = Logger.getInstance("#" + RemoteProcessSupport.class); + private final Class myValueClass; private final HashMap, Object> myProcMap = new HashMap, Object>(); - public RemoteProcessSupport(Project project, Class valueClass) { - myProject = project; + public RemoteProcessSupport(Class valueClass) { myValueClass = valueClass; } - public Project getProject() { - return myProject; - } - protected abstract void fireModificationCountChanged(); protected abstract String getName(Target target); @@ -55,7 +51,6 @@ public abstract class RemoteProcessSupport { protected void logText(Parameters configuration, ProcessEvent event, Key outputType, Object info) { } - public void stopAll() { final ArrayList allHandlers = new ArrayList(); synchronized (myProcMap) { @@ -86,17 +81,7 @@ public abstract class RemoteProcessSupport { final Ref ref = Ref.create(null); final Pair key = Pair.create(target, configuration); if (!getExistingInfo(ref, key)) { - final Runnable runnable = new Runnable() { - public void run() { - startProcess(target, configuration, key); - } - }; - if (ApplicationManager.getApplication().isDispatchThread()) { - runnable.run(); - } - else { - ApplicationManager.getApplication().invokeLater(runnable); - } + startProcess(target, configuration, key); if (ref.isNull()) { try { synchronized (ref) { @@ -166,7 +151,8 @@ public abstract class RemoteProcessSupport { } } - protected abstract RunProfileState getRunProfileState(Target target, Parameters configuration, Executor executor) throws ExecutionException; + protected abstract RunProfileState getRunProfileState(Target target, Parameters configuration, Executor executor) + throws ExecutionException; private boolean getExistingInfo(Ref ref, final Pair key) { Object info; @@ -214,7 +200,7 @@ public abstract class RemoteProcessSupport { } private static T narrowImpl(Remote remote, Class to) { - return (T) (to.isInstance(remote)? remote : PortableRemoteObject.narrow(remote, to)); + return (T)(to.isInstance(remote) ? remote : PortableRemoteObject.narrow(remote, to)); } private ProcessListener getProcessListener(final Pair key) { @@ -240,6 +226,13 @@ public abstract class RemoteProcessSupport { } public void onTextAvailable(ProcessEvent event, Key outputType) { + if (outputType == ProcessOutputTypes.STDERR) { + LOG.warn(event.getText()); + } + else { + LOG.info(event.getText()); + } + Info result = null; final PendingInfo info; synchronized (myProcMap) { @@ -262,7 +255,9 @@ public abstract class RemoteProcessSupport { info.stderr.append(event.getText()); } } - else info = null; + else { + info = null; + } } if (result != null) { synchronized (info.ref) { @@ -280,8 +275,8 @@ public abstract class RemoteProcessSupport { final PendingInfo pendingInfo; synchronized (myProcMap) { o = myProcMap.remove(key); - pendingInfo = o instanceof PendingInfo? (PendingInfo)o : null; - if (pendingInfo != null && (pendingInfo.stderr.length() > 0 || pendingInfo.ref.isNull())) { + pendingInfo = o instanceof PendingInfo ? (PendingInfo)o : null; + if (pendingInfo != null && (pendingInfo.stderr.length() > 0 || pendingInfo.ref.isNull())) { if (errorMessage != null) pendingInfo.stderr.append(errorMessage); pendingInfo.ref.set(new Info(null, -1, pendingInfo.stderr.toString())); } diff --git a/platform/lang-impl/src/com/intellij/extapi/psi/ASTDelegatePsiElement.java b/platform/lang-impl/src/com/intellij/extapi/psi/ASTDelegatePsiElement.java index 5dbb53923a0d..308512ecd921 100644 --- a/platform/lang-impl/src/com/intellij/extapi/psi/ASTDelegatePsiElement.java +++ b/platform/lang-impl/src/com/intellij/extapi/psi/ASTDelegatePsiElement.java @@ -148,17 +148,33 @@ public abstract class ASTDelegatePsiElement extends PsiElementBase { return node == null ? null : node.getPsi(); } + @NotNull + protected PsiElement findNotNullChildByType(IElementType type) { + return notNullChild(findChildByType(type)); + } + + @Nullable protected PsiElement findChildByType(TokenSet type) { ASTNode node = getNode().findChildByType(type); return node == null ? null : node.getPsi(); } + @NotNull + protected PsiElement findNotNullChildByType(TokenSet type) { + return notNullChild(findChildByType(type)); + } + @Nullable protected PsiElement findChildByFilter(TokenSet tokenSet) { ASTNode[] nodes = getNode().getChildren(tokenSet); return nodes == null || nodes.length == 0 ? null : nodes[0].getPsi(); } + @NotNull + protected PsiElement findNotNullChildByFilter(TokenSet tokenSet) { + return notNullChild(findChildByFilter(tokenSet)); + } + protected T[] findChildrenByType(IElementType elementType, Class arrayClass) { return ContainerUtil.map2Array(SharedImplUtil.getChildrenOfType(getNode(), elementType), arrayClass, new Function() { public T fun(final ASTNode s) { diff --git a/platform/lang-impl/src/com/intellij/extapi/psi/PsiElementBase.java b/platform/lang-impl/src/com/intellij/extapi/psi/PsiElementBase.java index 51b3594a0fda..6a238c15a1aa 100644 --- a/platform/lang-impl/src/com/intellij/extapi/psi/PsiElementBase.java +++ b/platform/lang-impl/src/com/intellij/extapi/psi/PsiElementBase.java @@ -241,7 +241,11 @@ public abstract class PsiElementBase extends ElementBase implements NavigatableP @NotNull protected T findNotNullChildByClass(Class aClass) { - final T child = findChildByClass(aClass); + return notNullChild(findChildByClass(aClass)); + } + + @NotNull + protected T notNullChild(T child) { if (child == null) { LOG.error(getText() + "\n parent=" + getParent().getText()); } diff --git a/platform/lang-impl/src/com/intellij/ide/fileTemplates/FileTemplateUtil.java b/platform/lang-impl/src/com/intellij/ide/fileTemplates/FileTemplateUtil.java index 2bfc43b57dc4..9f763221b164 100644 --- a/platform/lang-impl/src/com/intellij/ide/fileTemplates/FileTemplateUtil.java +++ b/platform/lang-impl/src/com/intellij/ide/fileTemplates/FileTemplateUtil.java @@ -213,7 +213,7 @@ public class FileTemplateUtil{ }; Velocity.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, emptyLogSystem); Velocity.setProperty(RuntimeConstants.RESOURCE_LOADER, "file,class"); - //todo[myakovlev] implement my oun Loader, with ability to load templates from classpath + //todo[myakovlev] implement my own Loader, with ability to load templates from classpath Velocity.setProperty("file.resource.loader.class", MyFileResourceLoader.class.getName()); Velocity.setProperty("class.resource.loader.class", MyClasspathResourceLoader.class.getName()); Velocity.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, modifiedPatternsPath.getAbsolutePath()); @@ -321,7 +321,7 @@ public class FileTemplateUtil{ File modifiedPatternsPath = new File(PathManager.getConfigPath()); modifiedPatternsPath = new File(modifiedPatternsPath, INCLUDES_PATH); - try{ + try { Field pathsField = FileResourceLoader.class.getDeclaredField("paths"); pathsField.setAccessible(true); Collection paths = (Collection)pathsField.get(this); @@ -333,12 +333,13 @@ public class FileTemplateUtil{ paths.add(testsDir.getAbsolutePath()); } } - catch (Exception e){ + catch (Exception e) { + LOG.error(e); throw new RuntimeException(e); } } } - + public static boolean canCreateFromTemplate (PsiDirectory[] dirs, FileTemplate template) { FileType fileType = FileTypeManagerEx.getInstanceEx().getFileTypeByExtension(template.getExtension()); if (fileType.equals(FileTypes.UNKNOWN)) return false; diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/BaseProjectTreeBuilder.java b/platform/lang-impl/src/com/intellij/ide/projectView/BaseProjectTreeBuilder.java index 62c157186e1d..ae4abf72fef1 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/BaseProjectTreeBuilder.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/BaseProjectTreeBuilder.java @@ -25,24 +25,22 @@ import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.Progressive; import com.intellij.openapi.progress.util.StatusBarProgress; import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.ActionCallback; -import com.intellij.openapi.util.AsyncResult; -import com.intellij.openapi.util.Condition; -import com.intellij.openapi.util.Conditions; +import com.intellij.openapi.util.*; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.psi.PsiDirectory; +import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; +import com.intellij.psi.PsiFileSystemItem; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; +import java.util.*; public abstract class BaseProjectTreeBuilder extends AbstractTreeBuilder { protected final Project myProject; @@ -52,10 +50,54 @@ public abstract class BaseProjectTreeBuilder extends AbstractTreeBuilder { DefaultTreeModel treeModel, AbstractTreeStructure treeStructure, Comparator comparator) { - super(tree, treeModel, treeStructure, comparator); + init(tree, treeModel, new AbstractTreeStructure.Delegate(treeStructure) { + @Override + public AsyncResult revalidateElement(Object element) { + return _revalidateElement(element); + } + }, comparator, DEFAULT_UPDATE_INACTIVE); myProject = project; } + private AsyncResult _revalidateElement(Object element) { + final AsyncResult result = new AsyncResult(); + + if (element instanceof AbstractTreeNode) { + AbstractTreeNode node = (AbstractTreeNode)element; + final Object value = node.getValue(); + VirtualFile vFile = null; + if (value instanceof PsiFileSystemItem) { + vFile = ((PsiFileSystemItem)value).getVirtualFile(); + } else if (value instanceof PsiElement) { + PsiFile psiFile = ((PsiElement)value).getContainingFile(); + if (psiFile != null) { + vFile = psiFile.getVirtualFile(); + } + } + final ActionCallback cb = new ActionCallback(); + + final VirtualFile finalVFile = vFile; + batch(new Progressive() { + public void run(@NotNull ProgressIndicator indicator) { + final Ref target = new Ref(); + _select(value, finalVFile, false, Conditions.alwaysTrue(), cb, indicator, target); + cb.doWhenDone(new Runnable() { + public void run() { + result.setDone(target.get()); + } + }).doWhenRejected(new Runnable() { + public void run() { + result.setRejected(); + } + }); + } + }); + } else { + result.setRejected(); + } + return result; + } + protected boolean isAlwaysShowPlus(NodeDescriptor nodeDescriptor) { return ((AbstractTreeNode)nodeDescriptor).isAlwaysShowPlus(); } @@ -132,7 +174,7 @@ public abstract class BaseProjectTreeBuilder extends AbstractTreeBuilder { public void run() { batch(new Progressive() { public void run(@NotNull ProgressIndicator indicator) { - _select(element, file, requestFocus, nonStopCondition, result, indicator); + _select(element, file, requestFocus, nonStopCondition, result, indicator, null); } }); } @@ -148,12 +190,13 @@ public abstract class BaseProjectTreeBuilder extends AbstractTreeBuilder { final boolean requestFocus, final Condition nonStopCondition, final ActionCallback result, - ProgressIndicator indicator) { + ProgressIndicator indicator, + @Nullable final Ref virtualSelectTarget) { AbstractTreeNode alreadySelected = alreadySelectedNode(element); final Runnable onDone = new Runnable() { public void run() { - if (requestFocus) { + if (requestFocus && virtualSelectTarget == null) { IdeFocusManager.getInstance(myProject).requestFocus(getTree(), true); } @@ -169,15 +212,23 @@ public abstract class BaseProjectTreeBuilder extends AbstractTreeBuilder { }; if (alreadySelected == null) { - expandPathTo(file, (AbstractTreeNode)getTreeStructure().getRootElement(), element, condition, indicator) + expandPathTo(file, (AbstractTreeNode)getTreeStructure().getRootElement(), element, condition, indicator, virtualSelectTarget) .doWhenDone(new AsyncResult.Handler() { public void run(AbstractTreeNode node) { - select(node, onDone); + if (virtualSelectTarget == null) { + select(node, onDone); + } else if (onDone != null) { + onDone.run(); + } } }).notifyWhenRejected(result); } else { - select(alreadySelected, onDone); + if (virtualSelectTarget == null) { + select(alreadySelected, onDone); + } else if (onDone != null) { + onDone.run(); + } } } @@ -210,15 +261,21 @@ public abstract class BaseProjectTreeBuilder extends AbstractTreeBuilder { final AbstractTreeNode root, final Object element, final Condition nonStopCondition, - final ProgressIndicator indicator) { + final ProgressIndicator indicator, + @Nullable final Ref target) { final AsyncResult async = new AsyncResult(); if (root.canRepresent(element)) { - expand(root, new Runnable() { - public void run() { - async.setDone(root); - } - }); + if (target == null) { + expand(root, new Runnable() { + public void run() { + async.setDone(root); + } + }); + } else { + target.set(root); + async.setDone(root); + } return async; } @@ -228,27 +285,50 @@ public abstract class BaseProjectTreeBuilder extends AbstractTreeBuilder { } - expand(root, new Runnable() { - public void run() { - indicator.checkCanceled(); + if (target == null) { + expand(root, new Runnable() { + public void run() { + indicator.checkCanceled(); + final DefaultMutableTreeNode rootNode = getNodeForElement(root); + if (rootNode != null) { + final List kids = collectChildren(rootNode); + expandChild(kids, 0, nonStopCondition, file, element, async, indicator, target); + } + else { + async.setRejected(); + } + } + }); + } else { + if (indicator.isCanceled()) { + async.setRejected(); + } else { final DefaultMutableTreeNode rootNode = getNodeForElement(root); - if (rootNode != null) { - final List kids = collectChildren(rootNode); - expandChild(kids, 0, nonStopCondition, file, element, async, indicator); - } - else { - async.setRejected(); + final ArrayList kids = new ArrayList(); + if (rootNode != null && getTree().isExpanded(new TreePath(rootNode.getPath()))) { + kids.addAll(collectChildren(rootNode)); + } else { + List list = Arrays.asList(getTreeStructure().getChildElements(root)); + for (Object each : list) { + kids.add((AbstractTreeNode)each); + } } + + yield(new Runnable() { + public void run() { + expandChild(kids, 0, nonStopCondition, file, element, async, indicator, target); + } + }); } - }); + } return async; } private void expandChild(final List kids, final int i, final Condition nonStopCondition, final VirtualFile file, final Object element, - final AsyncResult async, final ProgressIndicator indicator) { + final AsyncResult async, final ProgressIndicator indicator, final Ref virtualSelectTarget) { if (i >= kids.size()) { async.setRejected(); @@ -263,7 +343,7 @@ public abstract class BaseProjectTreeBuilder extends AbstractTreeBuilder { } if (nonStopCondition.value(eachKid)) { - expandPathTo(file, eachKid, element, nonStopCondition, indicator).doWhenDone(new AsyncResult.Handler() { + expandPathTo(file, eachKid, element, nonStopCondition, indicator, virtualSelectTarget).doWhenDone(new AsyncResult.Handler() { public void run(AbstractTreeNode abstractTreeNode) { indicator.checkCanceled(); @@ -273,10 +353,10 @@ public abstract class BaseProjectTreeBuilder extends AbstractTreeBuilder { public void run() { indicator.checkCanceled(); - if (nodeWasCollapsed[0]) { + if (nodeWasCollapsed[0] && virtualSelectTarget == null) { collapseChildren(eachKid, null); } - expandChild(kids, i + 1, nonStopCondition, file, element, async, indicator); + expandChild(kids, i + 1, nonStopCondition, file, element, async, indicator, virtualSelectTarget); } }); } else { diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/GroupByTypeComparator.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/GroupByTypeComparator.java index 605c41bc52d5..f28ba06f9ea2 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/GroupByTypeComparator.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/GroupByTypeComparator.java @@ -97,7 +97,8 @@ public class GroupByTypeComparator implements Comparator { } } } - + if (descriptor1 == null) return -1; + if (descriptor2 == null) return 1; return AlphaComparator.INSTANCE.compare(descriptor1, descriptor2); } diff --git a/platform/lang-impl/src/com/intellij/openapi/wm/impl/status/TogglePopupHintsPanel.java b/platform/lang-impl/src/com/intellij/openapi/wm/impl/status/TogglePopupHintsPanel.java index 7876b29fe694..5de4a5e4f39e 100644 --- a/platform/lang-impl/src/com/intellij/openapi/wm/impl/status/TogglePopupHintsPanel.java +++ b/platform/lang-impl/src/com/intellij/openapi/wm/impl/status/TogglePopupHintsPanel.java @@ -96,7 +96,7 @@ public class TogglePopupHintsPanel implements StatusBarWidget, StatusBarWidget.I return "InspectionProfile"; } - public Presentation getPresentation(@NotNull Type type) { + public WidgetPresentation getPresentation(@NotNull Type type) { return this; } diff --git a/platform/lang-impl/src/com/intellij/psi/filters/FilterPositionUtil.java b/platform/lang-impl/src/com/intellij/psi/filters/FilterPositionUtil.java index 5799c9f946b5..459ec283eb59 100644 --- a/platform/lang-impl/src/com/intellij/psi/filters/FilterPositionUtil.java +++ b/platform/lang-impl/src/com/intellij/psi/filters/FilterPositionUtil.java @@ -30,10 +30,17 @@ public class FilterPositionUtil { @Nullable public static PsiElement searchNonSpaceNonCommentBack(PsiElement element) { + return searchNonSpaceNonCommentBack(element, false); + } + + @Nullable + public static PsiElement searchNonSpaceNonCommentBack(PsiElement element, final boolean strict) { if(element == null || element.getNode() == null) return null; ASTNode leftNeibour = TreeUtil.prevLeaf(element.getNode()); - while (leftNeibour != null && (leftNeibour.getElementType() == TokenType.WHITE_SPACE || leftNeibour.getPsi() instanceof PsiComment)){ - leftNeibour = TreeUtil.prevLeaf(leftNeibour); + if (!strict) { + while (leftNeibour != null && (leftNeibour.getElementType() == TokenType.WHITE_SPACE || leftNeibour.getPsi() instanceof PsiComment)){ + leftNeibour = TreeUtil.prevLeaf(leftNeibour); + } } return leftNeibour != null ? leftNeibour.getPsi() : null; diff --git a/platform/lang-impl/src/com/intellij/psi/filters/position/AfterElement.java b/platform/lang-impl/src/com/intellij/psi/filters/position/AfterElement.java new file mode 100644 index 000000000000..233bb683fb79 --- /dev/null +++ b/platform/lang-impl/src/com/intellij/psi/filters/position/AfterElement.java @@ -0,0 +1,44 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.psi.filters.position; + +import com.intellij.psi.PsiElement; +import com.intellij.psi.filters.ElementFilter; +import com.intellij.psi.filters.FilterPositionUtil; + +/** + * User: spLeaner + */ +public class AfterElement extends PositionElementFilter { + public AfterElement(){} + + public AfterElement(ElementFilter filter){ + setFilter(filter); + } + + public boolean isAcceptable(Object element, PsiElement context){ + if (!(element instanceof PsiElement)) return false; + final PsiElement previous = FilterPositionUtil.searchNonSpaceNonCommentBack((PsiElement) element, true); + if(previous != null){ + return getFilter().isAcceptable(previous, context); + } + return false; + } + + public String toString(){ + return "after(" +getFilter()+")"; + } +} diff --git a/platform/lang-impl/src/com/intellij/psi/impl/PsiDocumentManagerImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/PsiDocumentManagerImpl.java index b2151518a7b1..accd3020209a 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/PsiDocumentManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/PsiDocumentManagerImpl.java @@ -170,7 +170,7 @@ public class PsiDocumentManagerImpl extends PsiDocumentManager implements Projec if (!file.getViewProvider().isEventSystemEnabled()) return null; document = FileDocumentManager.getInstance().getDocument(file.getViewProvider().getVirtualFile()); - if (!file.getViewProvider().isPhysical()) { + if (document != null && !file.getViewProvider().isPhysical()) { cachePsi(document, file); } diff --git a/platform/lang-impl/src/com/intellij/psi/impl/search/PsiSearchHelperImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/search/PsiSearchHelperImpl.java index f7f7ffb274c4..91bc2f046286 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/search/PsiSearchHelperImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/search/PsiSearchHelperImpl.java @@ -384,7 +384,6 @@ public class PsiSearchHelperImpl implements PsiSearchHelper { } final Ref cancelled = new Ref(Boolean.FALSE); - final GlobalSearchScope finalScope = searchScope; for (int i = 0; i < files.length; i++) { if (progress != null) progress.checkCanceled(); @@ -394,16 +393,15 @@ public class PsiSearchHelperImpl implements PsiSearchHelper { public void run() { CharSequence text = psiFile.getViewProvider().getContents(); for (int index = LowLevelSearchUtil.searchWord(text, 0, text.length(), searcher, progress); index >= 0;) { - PsiReference referenceAt = psiFile.findReferenceAt(index); - if (referenceAt == null || originalElement == null || - !PsiSearchScopeUtil.isInScope(getUseScope(originalElement).intersectWith(finalScope), psiFile)) { - if (!processor.process(psiFile, index, index + searcher.getPattern().length())) { + final int endOffset = index + searcher.getPattern().length(); + if (originalElement == null || !containsReferenceTo(psiFile, index, endOffset, originalElement)) { + if (!processor.process(psiFile, index, endOffset)) { cancelled.set(Boolean.TRUE); return; } } - index = LowLevelSearchUtil.searchWord(text, index + searcher.getPattern().length(), text.length(), searcher, progress); + index = LowLevelSearchUtil.searchWord(text, endOffset, text.length(), searcher, progress); } } }); @@ -418,6 +416,20 @@ public class PsiSearchHelperImpl implements PsiSearchHelper { } } + private static boolean containsReferenceTo(@NotNull PsiFile psiFile, int startOffset, int endOffset, @NotNull PsiElement originalElement) { + int index = startOffset; + while (index < endOffset) { + PsiReference referenceAt = psiFile.findReferenceAt(index); + if (referenceAt == null) return false; + if (referenceAt.isReferenceTo(originalElement)) { + return true; + } + int end = referenceAt.getElement().getTextRange().getStartOffset() + referenceAt.getRangeInElement().getLength(); + index = Math.max(end, index + 1); + } + return false; + } + public void processAllFilesWithWord(@NotNull String word, @NotNull GlobalSearchScope scope, @NotNull Processor processor, final boolean caseSensitively) { myManager.getCacheManager().processFilesWithWord(processor,word, UsageSearchContext.IN_CODE, scope, caseSensitively); } diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/resolve/ResolveCache.java b/platform/lang-impl/src/com/intellij/psi/impl/source/resolve/ResolveCache.java index 6fb25fbaec28..f44214835449 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/source/resolve/ResolveCache.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/source/resolve/ResolveCache.java @@ -29,6 +29,7 @@ import com.intellij.util.ArrayFactory; import com.intellij.util.ArrayUtil; import com.intellij.util.containers.ConcurrentWeakHashMap; import com.intellij.util.containers.ContainerUtil; +import org.jetbrains.annotations.Nullable; import java.lang.ref.Reference; import java.util.Arrays; @@ -100,6 +101,7 @@ public class ResolveCache { myRunnablesToRunOnDropCaches.add(r); } + @Nullable private TResult resolve(TRef ref, AbstractResolver resolver, Map>[] maps, diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReference.java b/platform/lang-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReference.java index b3a4b296e486..0793c3b22424 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReference.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReference.java @@ -383,7 +383,21 @@ public class FileReference implements FileReferenceOwner, PsiPolyVariantReferenc } } } - if (root == null) return element; + if (root == null) { + PsiFileSystemItem _dstItem = FileReferenceHelperRegistrar.NullFileReferenceHelper.INSTANCE.getPsiFileSystemItem(project, dstVFile); + if (_dstItem != null) { + PsiFileSystemItem _root = FileReferenceHelperRegistrar.NullFileReferenceHelper.INSTANCE.findRoot(project, dstVFile); + if (_root != null) { + root = _root; + dstItem = _dstItem; + } + } + + if (root == null) { + return element; + } + } + final String relativePath = PsiFileSystemItemUtil.getRelativePath(root, dstItem); if (relativePath == null) { return element; diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReferenceHelperRegistrar.java b/platform/lang-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReferenceHelperRegistrar.java index ee3592b530fb..613ee02c8ffb 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReferenceHelperRegistrar.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReferenceHelperRegistrar.java @@ -48,7 +48,7 @@ public class FileReferenceHelperRegistrar { @NotNull public static FileReferenceHelper getNotNullHelper(@NotNull T psiFileSystemItem) { final FileReferenceHelper helper = getHelper(psiFileSystemItem); - return helper == null ? new NullFileReferenceHelper() : helper; + return helper == null ? NullFileReferenceHelper.INSTANCE : helper; } @Nullable @@ -67,7 +67,9 @@ public class FileReferenceHelperRegistrar { return element2.getManager().areElementsEquivalent(element1, element2); } - private static class NullFileReferenceHelper extends FileReferenceHelper { + public static class NullFileReferenceHelper extends FileReferenceHelper { + + public static final NullFileReferenceHelper INSTANCE = new NullFileReferenceHelper(); public PsiFileSystemItem findRoot(final Project project, @NotNull final VirtualFile file) { final ProjectFileIndex index = ProjectRootManager.getInstance(project).getFileIndex(); diff --git a/platform/platform-api/src/com/intellij/ide/DataManager.java b/platform/platform-api/src/com/intellij/ide/DataManager.java index 7b49b2d85426..41c71dffaed0 100644 --- a/platform/platform-api/src/com/intellij/ide/DataManager.java +++ b/platform/platform-api/src/com/intellij/ide/DataManager.java @@ -32,7 +32,7 @@ public abstract class DataManager { /** * @return {@link DataContext} constructed by the current focused component - * @deprecated use either {@link #getDataContext(java.awt.Component)} or {@link #getDataContextFromFocus()) + * @deprecated use either {@link #getDataContext(java.awt.Component)} or {@link #getDataContextFromFocus()} */ public abstract DataContext getDataContext(); diff --git a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeBuilder.java b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeBuilder.java index 1190f882346a..55d3cb0827c4 100644 --- a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeBuilder.java +++ b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeBuilder.java @@ -492,4 +492,9 @@ public class AbstractTreeBuilder implements Disposable { return app != null && app.isUnitTestMode(); } + public static boolean isToPaintSelection(JTree tree) { + AbstractTreeBuilder builder = getBuilderFor(tree); + return builder == null ? true : builder.getUi().isToPaintSelection(); + } + } diff --git a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeStructure.java b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeStructure.java index f383b43b6b86..bff7c077e2ac 100644 --- a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeStructure.java +++ b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeStructure.java @@ -16,6 +16,7 @@ package com.intellij.ide.util.treeView; +import com.intellij.openapi.util.AsyncResult; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -39,4 +40,62 @@ public abstract class AbstractTreeStructure { return false; } + public AsyncResult revalidateElement(Object element) { + return new AsyncResult.Done(element); + } + + public static class Delegate extends AbstractTreeStructure { + private AbstractTreeStructure myDelegee; + + public Delegate(AbstractTreeStructure delegee) { + myDelegee = delegee; + } + + @Override + public Object getRootElement() { + return myDelegee.getRootElement(); + } + + @Override + public Object[] getChildElements(Object element) { + return myDelegee.getChildElements(element); + } + + @Override + public Object getParentElement(Object element) { + return myDelegee.getParentElement(element); + } + + @NotNull + @Override + public NodeDescriptor createDescriptor(Object element, NodeDescriptor parentDescriptor) { + return myDelegee.createDescriptor(element, parentDescriptor); + } + + @Override + public void commit() { + myDelegee.commit(); + } + + @Override + public boolean hasSomethingToCommit() { + return myDelegee.hasSomethingToCommit(); + } + + @Override + public boolean isToBuildChildrenInBackground(Object element) { + return myDelegee.isToBuildChildrenInBackground(element); + } + + @Override + public boolean isAlwaysLeaf(Object element) { + return myDelegee.isAlwaysLeaf(element); + } + + @Override + public AsyncResult revalidateElement(Object element) { + return myDelegee.revalidateElement(element); + } + } + } \ No newline at end of file diff --git a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java index a02f6ec482da..f4716cf9cf0c 100644 --- a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java +++ b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java @@ -106,7 +106,6 @@ public class AbstractTreeUi { private UpdaterTreeState myUpdaterState; private AbstractTreeBuilder myBuilder; - private boolean myReleaseRequested; private final Set myUpdatingChildren = new HashSet(); private long myJanitorPollPeriod = Time.SECOND * 10; @@ -172,6 +171,9 @@ public class AbstractTreeUi { private Map myCancelledBuild = new WeakHashMap(); + private boolean mySelectionIsAdjusted; + private boolean myReleaseRequested; + protected void init(AbstractTreeBuilder builder, JTree tree, DefaultTreeModel treeModel, @@ -213,14 +215,14 @@ public class AbstractTreeUi { public void showNotify() { myShowing = true; myWasEverShown = true; - if (!isReleaseRequested()) { + if (canInitiateNewActivity()) { activate(true); } } public void hideNotify() { myShowing = false; - if (!validateReleaseRequested()) { + if (canInitiateNewActivity()) { deactivate(); } } @@ -271,6 +273,13 @@ public class AbstractTreeUi { } } + private void setHoldSize(boolean holdSize) { + if (myTree instanceof com.intellij.ui.treeStructure.Tree) { + final com.intellij.ui.treeStructure.Tree tree = (Tree)myTree; + tree.setHoldSize(holdSize); + } + } + private void cleanUpAll() { final long now = System.currentTimeMillis(); final AbstractTreeUi[] uis = ourUi2Countdown.keySet().toArray(new AbstractTreeUi[ourUi2Countdown.size()]); @@ -282,7 +291,7 @@ public class AbstractTreeUi { ourUi2Countdown.remove(eachUi); Runnable runnable = new Runnable() { public void run() { - if (isReleased()) return; + if (!canInitiateNewActivity()) return; myCleanupTask = null; getBuilder().cleanUp(); @@ -301,7 +310,7 @@ public class AbstractTreeUi { protected void doCleanUp() { Runnable cleanup = new Runnable() { public void run() { - if (!isReleaseRequested()) { + if (canInitiateNewActivity()) { cleanUpNow(); } } @@ -363,8 +372,8 @@ public class AbstractTreeUi { if (!myWasEverShown) return; - if (isNodeActionsPending()) { - cancelBackgroundLoading(); + if (!isReady()) { + cancelUpdate(); myUpdateFromRootRequested = true; } @@ -385,15 +394,12 @@ public class AbstractTreeUi { } public void requestRelease() { - if (isReleaseRequested()) return; - - assertIsDispatchThread(); - myReleaseRequested = true; - - getUpdater().requestRelease(); - - maybeReady(); + cancelUpdate().doWhenDone(new Runnable() { + public void run() { + releaseNow(); + } + }); } private void releaseNow() { @@ -429,24 +435,6 @@ public class AbstractTreeUi { myYeildingDoneRunnables.clear(); } - public boolean isReleaseRequested() { - return myReleaseRequested; - } - - public boolean validateReleaseRequested() { - if (isReleaseRequested()) { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - maybeReady(); - } - }); - return true; - } - else { - return false; - } - } - public boolean isReleased() { return myBuilder == null; } @@ -455,14 +443,9 @@ public class AbstractTreeUi { if (!myUnbuiltNodes.contains(node)) return; if (isLoadedInBackground(getElementFor(node))) return; - if (!isReleaseRequested()) { - getTreeStructure().commit(); - addSubtreeToUpdate(node); - getUpdater().performUpdate(); - } - else { - processNodeActionsIfReady(node); - } + getTreeStructure().commit(); + addSubtreeToUpdate(node); + getUpdater().performUpdate(); } public final AbstractTreeStructure getTreeStructure() { @@ -812,12 +795,11 @@ public class AbstractTreeUi { else { UIUtil.invokeLaterIfNeeded(new Runnable() { public void run() { - if (!validateReleaseRequested()) { - result.setDone(_update(nodeDescriptor)); - } - else { - result.setRejected(); - } + execute(new Runnable() { + public void run() { + result.setDone(_update(nodeDescriptor)); + } + }); } }); } @@ -861,6 +843,8 @@ public class AbstractTreeUi { } catch (InterruptedException e) { throw new ProcessCanceledException(); + } catch (ProcessCanceledException e) { + throw e; } finally { myStateLock.readLock().release(); } @@ -962,7 +946,10 @@ public class AbstractTreeUi { } final void updateSubtreeNow(TreeUpdatePass pass, boolean canSmartExpand) { + + maybeSetBusyAndScheduleWaiterForReady(true); + setHoldSize(true); boolean consumed = initRootNodeNowIfNeeded(pass); if (consumed) return; @@ -1086,13 +1073,7 @@ public class AbstractTreeUi { if (processAlwaysLeaf(node)) return; - Pair unbuilt; - try { - unbuilt = processUnbuilt(node, descriptor, pass, wasExpanded, null); - } - catch (ProcessCanceledException e) { - return; - } + Pair unbuilt = processUnbuilt(node, descriptor, pass, wasExpanded, null); if (unbuilt.getFirst()) return; preloaded.set(unbuilt.getSecond()); @@ -1127,6 +1108,8 @@ public class AbstractTreeUi { } } finally { + if (isReleased()) return; + processNodeActionsIfReady(node); } } @@ -1191,7 +1174,9 @@ public class AbstractTreeUi { final boolean wasExpanded, final boolean wasLeaf, final boolean forceUpdate) { - if (!canInitiateNewActivity()) return; + if (!canInitiateNewActivity()) { + throw new ProcessCanceledException(); + } final NodeDescriptor descriptor = getDescriptorFrom(node); @@ -1533,7 +1518,7 @@ public class AbstractTreeUi { } private boolean isRerunNeeded(TreeUpdatePass pass) { - if (pass.isExpired()) return false; + if (pass.isExpired() || !canInitiateNewActivity()) return false; final boolean rerunBecauseTreeIsHidden = !pass.isExpired() && !isTreeShowing() && getUpdater().isInPostponeMode(); @@ -1552,11 +1537,6 @@ public class AbstractTreeUi { pass.setCurrentNode(node); boolean wasRun = yieldAndRun(new Runnable() { public void run() { - if (validateReleaseRequested()) { - result.setRejected(); - return; - } - if (pass.isExpired()) { result.setRejected(); return; @@ -1634,13 +1614,15 @@ public class AbstractTreeUi { if (node != null) { addToCancelled(node); } - resetToReady(); + if (!isReleased()) { + resetToReady(); + } throw e; } } private boolean canInitiateNewActivity() { - return !myResettingToReadyNow.get(); + return !myResettingToReadyNow.get() && !myReleaseRequested && !isReleased(); } private ActionCallback resetToReady() { @@ -1652,14 +1634,13 @@ public class AbstractTreeUi { invokeLaterIfNeeded(new Runnable() { public void run() { - resetToReadyNow(); - Progressive[] progressives = myBatchIndicators.keySet().toArray(new Progressive[myBatchIndicators.size()]); for (Progressive each : progressives) { myBatchIndicators.remove(each).cancel(); myBatchCallbacks.remove(each).setRejected(); } + resetToReadyNow(); myResettingToReadyNow.set(false); result.setDone(); @@ -1698,6 +1679,8 @@ public class AbstractTreeUi { myDeferredExpansions.clear(); myDeferredSelections.clear(); + + maybeReady(); } public void addToCancelled(DefaultMutableTreeNode node) { @@ -1723,8 +1706,6 @@ public class AbstractTreeUi { } private boolean yieldAndRun(final Runnable runnable, final TreeUpdatePass pass) { - if (validateReleaseRequested()) return false; - myYeildingPasses.add(pass); myYeildingNow = true; yield(new Runnable() { @@ -1745,19 +1726,39 @@ public class AbstractTreeUi { } private boolean hasSheduledUpdates() { - return getUpdater().hasNodesToUpdate() || isLoadingInBackgroundNow(); + return getUpdater().hasNodesToUpdate(); } public boolean isReady() { return isIdle() && !hasPendingWork() && !isNodeActionsPending(); } + public String getStatus() { + return "isReady=" + isReady() + "\n" + + " isIdle=" + isIdle() + "\n" + + " isYeildingNow=" + isYeildingNow() + "\n" + + " isWorkerBusy=" + isWorkerBusy() + "\n" + + " hasUpdatingNow=" + hasUpdatingNow() + "\n" + + " isLoadingInBackgroundNow=" + isLoadingInBackgroundNow() + "\n" + + " hasPendingWork=" + hasPendingWork() + "\n" + + " hasNodesToUpdate=" + hasNodesToUpdate() + "\n" + + " updaterState=" + myUpdaterState + "\n" + + " hasScheduledUpdates=" + hasSheduledUpdates() + "\n" + + " isPostponedMode=" + getUpdater().isInPostponeMode() + "\n" + + " nodeActions=" + myNodeActions.keySet() + "\n" + + "isReleased=" + isReleased() + "\n" + + " isReleaseRequested=" + isReleaseRequested() + "\n" + + "isCancelProcessed=" + isCancelProcessed() + "\n" + + " isCancelRequested=" + myCancelRequest + "\n" + + " isResettingToReadyNow=" + myResettingToReadyNow; + } + public boolean hasPendingWork() { - return hasNodesToUpdate() || (myUpdaterState != null && myUpdaterState.isProcessingNow()); + return hasNodesToUpdate() || (myUpdaterState != null && myUpdaterState.isProcessingNow()) || (hasSheduledUpdates() && !getUpdater().isInPostponeMode()); } public boolean isIdle() { - return !isYeildingNow() && !isWorkerBusy() && (!hasSheduledUpdates() || getUpdater().isInPostponeMode()); + return !isYeildingNow() && !isWorkerBusy() && !hasUpdatingNow() && !isLoadingInBackgroundNow(); } private void executeYieldingRequest(Runnable runnable, TreeUpdatePass pass) { @@ -1766,7 +1767,9 @@ public class AbstractTreeUi { runnable.run(); } finally { - maybeYeildingFinished(); + if (!isReleased()) { + maybeYeildingFinished(); + } } } @@ -1783,27 +1786,23 @@ public class AbstractTreeUi { if (isReleased()) return; if (isReady()) { - if (isReleaseRequested()) { - releaseNow(); - return; - } + myInitialized.setDone(); - if (myTree.isShowing() || myUpdateIfInactive) { - myInitialized.setDone(); - } + if (canInitiateNewActivity()) { + if (myUpdaterState != null && !myUpdaterState.isProcessingNow()) { + UpdaterTreeState oldState = myUpdaterState; + if (!myUpdaterState.restore(null)) { + setUpdaterState(oldState); + } - - if (myUpdaterState != null && !myUpdaterState.isProcessingNow()) { - UpdaterTreeState oldState = myUpdaterState; - if (!myUpdaterState.restore(null)) { - setUpdaterState(oldState); - } - - if (!isReady()) { - return; + if (!isReady()) { + return; + } } } + setHoldSize(false); + if (myTree.isShowing()) { if (getBuilder().isToEnsureSelectionOnFocusGained() && Registry.is("ide.tree.ensureSelectionOnFocusGained")) { TreeUtil.ensureSelection(myTree); @@ -1813,6 +1812,19 @@ public class AbstractTreeUi { if (myInitialized.isDone()) { myBusyObject.onReady(); } + + if (canInitiateNewActivity()) { + TreePath[] selection = getTree().getSelectionPaths(); + Rectangle visible = getTree().getVisibleRect(); + if (selection != null) { + for (TreePath each : selection) { + Rectangle bounds = getTree().getPathBounds(each); + if (bounds != null && (visible.contains(bounds) || visible.intersects(bounds))) { + getTree().repaint(bounds); + } + } + } + } } } @@ -2042,7 +2054,7 @@ public class AbstractTreeUi { } public boolean hasNodesToUpdate() { - return getUpdater().hasNodesToUpdate() || hasUpdatingNow() || isLoadingInBackgroundNow(); + return getUpdater().hasNodesToUpdate(); } public List getExpandedElements() { @@ -2070,8 +2082,13 @@ public class AbstractTreeUi { resetToReadyNow(); done.setDone(); } else { - requestCancel(); - getReady(this).notify(done); + if (isIdle() && hasPendingWork()) { + resetToReadyNow(); + done.setDone(); + } else { + requestCancel(); + getReady(this).notify(done); + } } maybeReady(); @@ -2108,6 +2125,8 @@ public class AbstractTreeUi { try { progressive.run(indicator); } finally { + if (isReleased()) return new ActionCallback.Rejected(); + getReady(this).doWhenDone(new Runnable() { public void run() { if (myBatchIndicators.containsKey(progressive)) { @@ -2136,6 +2155,14 @@ public class AbstractTreeUi { return myCancelRequest.get() || myResettingToReadyNow.get(); } + public boolean isToPaintSelection() { + return isReady() || !mySelectionIsAdjusted; + } + + public boolean isReleaseRequested() { + return myReleaseRequested; + } + static class ElementNode extends DefaultMutableTreeNode { Set myElements = new HashSet(); @@ -2220,8 +2247,6 @@ public class AbstractTreeUi { private boolean queueBackgroundUpdate(final UpdateInfo updateInfo, final DefaultMutableTreeNode node) { assertIsDispatchThread(); - if (validateReleaseRequested()) return false; - final Object oldElementFromDescriptor = getElementFromDescriptor(updateInfo.getDescriptor()); UpdateInfo loaded = getLoadedInBackground(oldElementFromDescriptor); @@ -2266,7 +2291,6 @@ public class AbstractTreeUi { return; } - if (!updateInfo.isDescriptorIsUpToDate()) { update(updateInfo.getDescriptor(), true); } @@ -2281,6 +2305,7 @@ public class AbstractTreeUi { elementFromDescriptor.set(element); Object[] loadedElements = getChildrenFor(getBuilder().getTreeStructureElement(updateInfo.getDescriptor())); + LoadedChildren loaded = new LoadedChildren(loadedElements); for (Object each : loadedElements) { NodeDescriptor eachChildDescriptor = getTreeStructure().createDescriptor(each, updateInfo.getDescriptor()); @@ -2288,6 +2313,12 @@ public class AbstractTreeUi { } children.set(loaded); + + } + + @Override + public String toString() { + return "runnable=" + oldElementFromDescriptor; } }; @@ -2396,8 +2427,10 @@ public class AbstractTreeUi { if (!isUpdatingParent(node) && !isWorkerBusy()) { final UpdaterTreeState state = myUpdaterState; if (myNodeActions.size() == 0 && state != null && !state.isProcessingNow()) { - if (!state.restore(childrenReady ? node : null)) { - setUpdaterState(state); + if (canInitiateNewActivity()) { + if (!state.restore(childrenReady ? node : null)) { + setUpdaterState(state); + } } } } @@ -2749,6 +2782,8 @@ public class AbstractTreeUi { } if (toSelect != null) { + mySelectionIsAdjusted = isAdjustedSelection; + myTree.addSelectionPath(toSelect); if (isAdjustedSelection && myUpdaterState != null) { @@ -2897,7 +2932,7 @@ public class AbstractTreeUi { protected ActionCallback queueToBackground(@NotNull final Runnable bgBuildAction, @Nullable final Runnable edtPostRunnable) { - if (validateReleaseRequested() || !canInitiateNewActivity()) return new ActionCallback.Rejected(); + if (!canInitiateNewActivity()) return new ActionCallback.Rejected(); final ActionCallback result = new ActionCallback(); @@ -2917,50 +2952,64 @@ public class AbstractTreeUi { final Runnable pooledThreadWithProgressRunnable = new Runnable() { public void run() { - final AbstractTreeBuilder builder = getBuilder(); + try { + final AbstractTreeBuilder builder = getBuilder(); - if (isReleased() || !canInitiateNewActivity()) return; + if (!canInitiateNewActivity()) { + throw new ProcessCanceledException(); + } - builder.runBackgroundLoading(new Runnable() { - public void run() { - assertNotDispatchThread(); - if (isReleased() || !canInitiateNewActivity()) return; + builder.runBackgroundLoading(new Runnable() { + public void run() { - try { - execute(bgBuildAction); + assertNotDispatchThread(); + try { + if (!canInitiateNewActivity()) { + throw new ProcessCanceledException(); + } - if (edtPostRunnable != null) { - builder.updateAfterLoadedInBackground(new Runnable() { - public void run() { - try { - assertIsDispatchThread(); - if (isReleased() || !canInitiateNewActivity()) return; + execute(bgBuildAction); - execute(edtPostRunnable); + if (edtPostRunnable != null) { + + builder.updateAfterLoadedInBackground(new Runnable() { + public void run() { + try { + assertIsDispatchThread(); + if (!canInitiateNewActivity()) { + throw new ProcessCanceledException(); + } + + execute(edtPostRunnable); + + } + catch (ProcessCanceledException e) { + fail.set(true); + } + finally { + unregisterWorkerTask(bgBuildAction, finalizer); + } } - catch (ProcessCanceledException e) { - fail.set(true); - } - finally { - unregisterWorkerTask(bgBuildAction, finalizer); - } - } - }); + }); + } + else { + unregisterWorkerTask(bgBuildAction, finalizer); + } } - else { + catch (ProcessCanceledException e) { + fail.set(true); unregisterWorkerTask(bgBuildAction, finalizer); } + catch (Throwable t) { + unregisterWorkerTask(bgBuildAction, finalizer); + throw new RuntimeException(t); + } } - catch (ProcessCanceledException e) { - fail.set(true); - unregisterWorkerTask(bgBuildAction, finalizer); - } - catch (Throwable t) { - unregisterWorkerTask(bgBuildAction, finalizer); - throw new RuntimeException(t); - } - } - }); + }); + } + catch (ProcessCanceledException e) { + unregisterWorkerTask(bgBuildAction, finalizer); + } } }; @@ -3007,6 +3056,7 @@ public class AbstractTreeUi { private void unregisterWorkerTask(Runnable runnable, @Nullable Runnable finalizeRunnable) { boolean wasRemoved; + synchronized (myActiveWorkerTasks) { wasRemoved = myActiveWorkerTasks.remove(runnable); } @@ -3127,8 +3177,10 @@ public class AbstractTreeUi { } myTreeModel.nodeStructureChanged(parentNode); - while (expanded.hasMoreElements()) { - expandSilently(expanded.nextElement()); + if (expanded != null) { + while (expanded.hasMoreElements()) { + expandSilently(expanded.nextElement()); + } } if (selected != null) { @@ -3187,7 +3239,7 @@ public class AbstractTreeUi { return addSubtreeToUpdate(root, null); } - public boolean addSubtreeToUpdate(final DefaultMutableTreeNode root, Runnable runAfterUpdate) { + public boolean addSubtreeToUpdate(final DefaultMutableTreeNode root, final Runnable runAfterUpdate) { Object element = getElementFor(root); if (getTreeStructure().isAlwaysLeaf(element)) { removeLoading(root, true); @@ -3198,13 +3250,12 @@ public class AbstractTreeUi { return false; } - if (isReleaseRequested()) { - processNodeActionsIfReady(root); - } - else { - getUpdater().runAfterUpdate(runAfterUpdate); - getUpdater().addSubtreeToUpdate(root); - } + execute(new Runnable() { + public void run() { + getUpdater().runAfterUpdate(runAfterUpdate); + getUpdater().addSubtreeToUpdate(root); + } + }); return true; } @@ -3447,16 +3498,49 @@ public class AbstractTreeUi { final boolean deferred, final boolean canBeCentered, final boolean scrollToVisible, - boolean canSmartExpand) { + final boolean canSmartExpand) { final Runnable _onDone = new Runnable() { public void run() { if (!checkDeferred(deferred, onDone)) return; - selectVisible(element, onDone, addToSelection, canBeCentered, scrollToVisible); + + checkPathAndMaybeRevalidate(element, new Runnable() { + public void run() { + selectVisible(element, onDone, addToSelection, canBeCentered, scrollToVisible); + } + }, true, false, canSmartExpand); } }; _expand(element, _onDone, true, false, canSmartExpand); } + private void checkPathAndMaybeRevalidate(Object element, final Runnable onDone, final boolean parentsOnly, final boolean checkIfInStructure, final boolean canSmartExpand) { + boolean toRevalidate = getNodeForElement(element, false) == null && isInStructure(element); + if (!toRevalidate) { + runDone(onDone); + return; + } + + AsyncResult revalidated = getTreeStructure().revalidateElement(element); + if (revalidated == null) { + runDone(onDone); + return; + } + + revalidated.doWhenDone(new AsyncResult.Handler() { + public void run(final Object o) { + invokeLaterIfNeeded(new Runnable() { + public void run() { + _expand(o, onDone, parentsOnly, checkIfInStructure, canSmartExpand); + } + }); + } + }).doWhenRejected(new Runnable() { + public void run() { + runDone(onDone); + } + }); + } + public void scrollSelectionToVisible(@Nullable Runnable onDone, boolean shouldBeCentered) { int[] rows = myTree.getSelectionRows(); if (rows == null || rows.length == 0) { @@ -3497,6 +3581,7 @@ public class AbstractTreeUi { } if (Registry.is("ide.tree.autoscrollToVCenter") && canBeCentered) { + setHoldSize(false); runDone(new Runnable() { public void run() { TreeUtil.showRowCentered(myTree, row, false, scroll).doWhenDone(new Runnable() { @@ -3508,6 +3593,7 @@ public class AbstractTreeUi { }); } else { + setHoldSize(false); TreeUtil.showAndSelect(myTree, row - 2, row + 2, row, -1, addToSelection, scroll).doWhenDone(new Runnable() { public void run() { runDone(onDone); @@ -3764,13 +3850,12 @@ public class AbstractTreeUi { return; } - final DefaultMutableTreeNode nextNode = getNodeForElement(kidsToExpand.get(expandIndex - 1), false); - if (nextNode != null) { - processExpand(nextNode, kidsToExpand, expandIndex - 1, onDone, canSmartExpand); - } - else { - runDone(onDone); - } + checkPathAndMaybeRevalidate(kidsToExpand.get(expandIndex - 1), new Runnable() { + public void run() { + final DefaultMutableTreeNode nextNode = getNodeForElement(kidsToExpand.get(expandIndex - 1), false); + processExpand(nextNode, kidsToExpand, expandIndex - 1, onDone, canSmartExpand); + } + }, false, false, canSmartExpand); } }, true); @@ -3838,8 +3923,6 @@ public class AbstractTreeUi { } public final boolean isNodeBeingBuilt(Object node) { - if (isReleaseRequested()) return false; - return getParentBuiltNode(node) != null; } @@ -3900,6 +3983,7 @@ public class AbstractTreeUi { if (!isInnerChange()) { clearUpdaterState(); myAutoExpandRoots.clear(); + mySelectionIsAdjusted = false; } } @@ -4013,15 +4097,6 @@ public class AbstractTreeUi { return null; } - public void cancelBackgroundLoading() { - if (myWorker != null) { - myWorker.cancelTasks(); - clearWorkerTasks(); - } - - clearNodeActions(); - } - private void addNodeAction(Object element, NodeAction action, boolean shouldChildrenBeReady) { _addNodeAction(element, action, myNodeActions); if (shouldChildrenBeReady) { @@ -4042,7 +4117,7 @@ public class AbstractTreeUi { private void cleanUpNow() { - if (isReleaseRequested()) return; + if (!canInitiateNewActivity()) return; final UpdaterTreeState state = new UpdaterTreeState(this); diff --git a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUpdater.java b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUpdater.java index 3043fb87ad92..a24942cbaf54 100644 --- a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUpdater.java +++ b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUpdater.java @@ -197,6 +197,8 @@ public class AbstractTreeUpdater implements Disposable, Activatable { } private void queue(Update update) { + if (isReleased()) return; + myUpdateQueue.queue(update); } @@ -233,6 +235,8 @@ public class AbstractTreeUpdater implements Disposable, Activatable { }); } + if (isReleased()) return; + myTreeBuilder.getUi().maybeReady(); if (myRunAfterUpdate != null) { @@ -257,6 +261,10 @@ public class AbstractTreeUpdater implements Disposable, Activatable { } } + private boolean isReleased() { + return myTreeBuilder.getUi() == null; + } + protected void invokeLater(Runnable runnable) { if (myTreeBuilder.getUi().isPassthroughMode()) { runnable.run(); diff --git a/platform/platform-api/src/com/intellij/openapi/actionSystem/Presentation.java b/platform/platform-api/src/com/intellij/openapi/actionSystem/Presentation.java index 715a325a8c4c..54535d714467 100644 --- a/platform/platform-api/src/com/intellij/openapi/actionSystem/Presentation.java +++ b/platform/platform-api/src/com/intellij/openapi/actionSystem/Presentation.java @@ -18,6 +18,7 @@ package com.intellij.openapi.actionSystem; import com.intellij.util.ui.UIUtil; import gnu.trove.THashMap; import org.jetbrains.annotations.NonNls; +import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.beans.PropertyChangeListener; @@ -174,13 +175,14 @@ public final class Presentation implements Cloneable { setText(presentation.getTextWithMnemonic()); } - public static String restoreTextWithMnemonic(final String text, final int mnemonic) { - if (text != null) { - for (int i = 0; i < text.length(); i++) { - if (Character.toUpperCase(text.charAt(i)) == mnemonic) { - return text.replaceFirst(String.valueOf(text.charAt(i)), "_" + text.charAt(i)); - } - } + public static String restoreTextWithMnemonic(@Nullable String text, final int mnemonic) { + if (text == null) { + return null; + } + for (int i = 0; i < text.length(); i++) { + if (Character.toUpperCase(text.charAt(i)) == mnemonic) { + return text.substring(0, i) + "_" + text.substring(i); + } } return text; } diff --git a/platform/platform-api/src/com/intellij/openapi/util/SimpleTimer.java b/platform/platform-api/src/com/intellij/openapi/util/SimpleTimer.java index 4569932702ef..c04d74b0a3e1 100644 --- a/platform/platform-api/src/com/intellij/openapi/util/SimpleTimer.java +++ b/platform/platform-api/src/com/intellij/openapi/util/SimpleTimer.java @@ -16,6 +16,7 @@ package com.intellij.openapi.util; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.progress.ProcessCanceledException; import org.jetbrains.annotations.NonNls; import java.util.*; @@ -134,6 +135,9 @@ public class SimpleTimer { try { each.run(); } + catch (ProcessCanceledException e) { + throw e; + } catch (Throwable e) { LOG.error(e); } diff --git a/platform/platform-api/src/com/intellij/openapi/wm/StatusBar.java b/platform/platform-api/src/com/intellij/openapi/wm/StatusBar.java index 0972e4a3f238..8ac121f0642d 100644 --- a/platform/platform-api/src/com/intellij/openapi/wm/StatusBar.java +++ b/platform/platform-api/src/com/intellij/openapi/wm/StatusBar.java @@ -33,16 +33,20 @@ public interface StatusBar extends StatusBarInfo { abstract class Info implements StatusBarInfo { public static final Topic TOPIC = Topic.create("IdeStatusBar.Text", StatusBarInfo.class); - private Info() {} + private Info() { + } public static void set(@Nullable final String text, @Nullable final Project project) { - if (project != null && !project.isInitialized() && !project.isDisposed()) { - StartupManager.getInstance(project).runWhenProjectIsInitialized(new Runnable() { - public void run() { - project.getMessageBus().syncPublisher(TOPIC).setInfo(text); - } - }); - return; + if (project != null) { + if (project.isDisposed()) return; + if (!project.isInitialized()) { + StartupManager.getInstance(project).runWhenProjectIsInitialized(new Runnable() { + public void run() { + project.getMessageBus().syncPublisher(TOPIC).setInfo(text); + } + }); + return; + } } final MessageBus bus = project == null ? ApplicationManager.getApplication().getMessageBus() : project.getMessageBus(); @@ -51,9 +55,11 @@ public interface StatusBar extends StatusBarInfo { } void addWidget(@NotNull StatusBarWidget widget); + void addWidget(@NotNull StatusBarWidget widget, @NotNull String anchor); - + void addWidget(@NotNull StatusBarWidget widget, @NotNull Disposable parentDisposable); + void addWidget(@NotNull StatusBarWidget widget, @NotNull String anchor, @NotNull Disposable parentDisposable); /** @@ -61,9 +67,11 @@ public interface StatusBar extends StatusBarInfo { */ @Deprecated void addCustomIndicationComponent(@NotNull JComponent c); + void removeCustomIndicationComponent(@NotNull JComponent c); void removeWidget(@NotNull String id); + void updateWidget(@NotNull String id); void fireNotificationPopup(@NotNull JComponent content, Color backgroundColor); diff --git a/platform/platform-api/src/com/intellij/openapi/wm/StatusBarWidget.java b/platform/platform-api/src/com/intellij/openapi/wm/StatusBarWidget.java index da7aef112d89..1860eb2c07b0 100644 --- a/platform/platform-api/src/com/intellij/openapi/wm/StatusBarWidget.java +++ b/platform/platform-api/src/com/intellij/openapi/wm/StatusBarWidget.java @@ -15,16 +15,17 @@ */ package com.intellij.openapi.wm; -import com.intellij.openapi.*; -import com.intellij.openapi.ui.popup.*; -import com.intellij.openapi.util.*; -import com.intellij.util.*; -import org.jetbrains.annotations.*; +import com.intellij.openapi.Disposable; +import com.intellij.openapi.ui.popup.ListPopup; +import com.intellij.openapi.util.SystemInfo; +import com.intellij.util.Consumer; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import javax.swing.*; -import javax.swing.border.*; +import javax.swing.border.Border; import java.awt.*; -import java.awt.event.*; +import java.awt.event.MouseEvent; /** * User: spLeaner @@ -35,7 +36,7 @@ public interface StatusBarWidget extends Disposable { DEFAULT, MAC } - interface Presentation { + interface WidgetPresentation { @Nullable String getTooltipText(); @@ -43,12 +44,12 @@ public interface StatusBarWidget extends Disposable { Consumer getClickConsumer(); } - interface IconPresentation extends Presentation { + interface IconPresentation extends WidgetPresentation { @NotNull Icon getIcon(); } - interface TextPresentation extends Presentation { + interface TextPresentation extends WidgetPresentation { @NotNull String getText(); @@ -56,7 +57,7 @@ public interface StatusBarWidget extends Disposable { String getMaxPossibleText(); } - interface MultipleTextValuesPresentation extends Presentation { + interface MultipleTextValuesPresentation extends WidgetPresentation { @NotNull ListPopup getPopupStep(); @@ -71,7 +72,7 @@ public interface StatusBarWidget extends Disposable { String ID(); @Nullable - Presentation getPresentation(@NotNull Type type); + WidgetPresentation getPresentation(@NotNull Type type); void install(@NotNull final StatusBar statusBar); diff --git a/platform/platform-api/src/com/intellij/ui/treeStructure/Tree.java b/platform/platform-api/src/com/intellij/ui/treeStructure/Tree.java index 04fa252ddfdc..744a92eb4ead 100644 --- a/platform/platform-api/src/com/intellij/ui/treeStructure/Tree.java +++ b/platform/platform-api/src/com/intellij/ui/treeStructure/Tree.java @@ -29,6 +29,7 @@ import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.Nullable; import javax.swing.*; +import javax.swing.event.TreeSelectionEvent; import javax.swing.plaf.TreeUI; import javax.swing.plaf.basic.BasicTreeUI; import javax.swing.text.Position; @@ -47,6 +48,9 @@ public class Tree extends JTree implements ComponentWithEmptyText, Autoscroll, Q private boolean myBusy; private Rectangle myLastVisibleRec; + private Dimension myHoldSize; + private MySelectionModel mySelectionModel = new MySelectionModel(); + public Tree() { initTree_(); } @@ -78,6 +82,8 @@ public class Tree extends JTree implements ComponentWithEmptyText, Autoscroll, Q } setCellRenderer(new NodeRenderer()); + + setSelectionModel(mySelectionModel); } @Override @@ -159,15 +165,25 @@ public class Tree extends JTree implements ComponentWithEmptyText, Autoscroll, Q @Override public void paint(Graphics g) { - super.paint(g); - + Rectangle clip = g.getClipBounds(); final Rectangle visible = getVisibleRect(); - if (!visible.equals(myLastVisibleRec)) { - updateBusyIconLocation(); + if (!AbstractTreeBuilder.isToPaintSelection(this)) { + mySelectionModel.holdSelection(); } - myLastVisibleRec = visible; + try { + super.paint(g); + + if (!visible.equals(myLastVisibleRec)) { + updateBusyIconLocation(); + } + + myLastVisibleRec = visible; + } + finally { + mySelectionModel.unholdSelection(); + } } public void setPaintBusy(boolean paintBusy) { @@ -184,14 +200,26 @@ public class Tree extends JTree implements ComponentWithEmptyText, Autoscroll, Q myBusyIcon.setOpaque(false); myBusyIcon.setPaintPassiveIcon(false); add(myBusyIcon); + myBusyIcon.addMouseListener(new MouseAdapter() { + @Override + public void mousePressed(MouseEvent e) { + if (!UIUtil.isActionClick(e)) return; + AbstractTreeBuilder builder = AbstractTreeBuilder.getBuilderFor(Tree.this); + if (builder != null) { + builder.cancelUpdate(); + } + } + }); } } if (myBusyIcon != null) { if (myBusy) { myBusyIcon.resume(); + myBusyIcon.setToolTipText("Update is in progress. Click to cancel"); } else { myBusyIcon.suspend(); + myBusyIcon.setToolTipText(null); SwingUtilities.invokeLater(new Runnable() { public void run() { if (myBusyIcon != null) { @@ -439,6 +467,30 @@ public class Tree extends JTree implements ComponentWithEmptyText, Autoscroll, Q return treeNode != null ? new TreePath(treeNode.getPath()) : new TreePath(node); } + private static class MySelectionModel extends DefaultTreeSelectionModel { + + private TreePath[] myHeldSelection; + + @Override + protected void fireValueChanged(TreeSelectionEvent e) { + if (myHeldSelection == null) { + super.fireValueChanged(e); + } + } + + public void holdSelection() { + myHeldSelection = getSelectionPaths(); + clearSelection(); + } + + public void unholdSelection() { + if (myHeldSelection != null) { + setSelectionPaths(myHeldSelection); + myHeldSelection = null; + } + } + } + private class MyMouseListener extends MouseAdapter { public void mousePressed(MouseEvent mouseevent) { if (!SwingUtilities.isLeftMouseButton(mouseevent) && @@ -539,4 +591,24 @@ public class Tree extends JTree implements ComponentWithEmptyText, Autoscroll, Q public void reshape(int x, int y, int w, int h) { super.reshape(x, y, w, h); } + + public void setHoldSize(boolean hold) { + if (hold && myHoldSize == null) { + myHoldSize = getPreferredSize(); + } else if (!hold && myHoldSize != null) { + myHoldSize = null; + revalidate(); + } + } + + public Dimension getPreferredSize() { + Dimension size = super.getPreferredSize(); + + if (myHoldSize != null) { + size.width = Math.max(size.width, myHoldSize.width); + size.height = Math.max(size.height, myHoldSize.height); + } + + return size; + } } \ No newline at end of file diff --git a/platform/platform-api/src/com/intellij/util/concurrency/QueueProcessor.java b/platform/platform-api/src/com/intellij/util/concurrency/QueueProcessor.java index bbc770c55072..0f1420951f96 100644 --- a/platform/platform-api/src/com/intellij/util/concurrency/QueueProcessor.java +++ b/platform/platform-api/src/com/intellij/util/concurrency/QueueProcessor.java @@ -48,10 +48,8 @@ public class QueueProcessor { } } - public void cleanAndWait() throws InterruptedException { + public void waitFor() throws InterruptedException { synchronized (myQueue) { - myQueue.clear(); - while (isProcessing) { myQueue.wait(); } diff --git a/platform/platform-api/src/com/intellij/util/io/ReaderProcess.java b/platform/platform-api/src/com/intellij/util/io/ReaderProcess.java new file mode 100644 index 000000000000..566d771277c4 --- /dev/null +++ b/platform/platform-api/src/com/intellij/util/io/ReaderProcess.java @@ -0,0 +1,69 @@ +package com.intellij.util.io; + +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.diagnostic.Logger; +import com.intellij.util.concurrency.Semaphore; + +import java.io.IOException; +import java.io.Reader; + +public abstract class ReaderProcess { + private static final Logger LOG = Logger.getInstance("#com.intellij.util.io.ReaderProcess"); + + private final Reader myReader; + private final char[] myBuffer = new char[4096]; + private final Semaphore myReadSemaphore = new Semaphore(); + private boolean isClosed; + + public ReaderProcess(Reader reader) throws IOException { + myReader = reader; + ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { + public void run() { + doRun(); + } + } ); + } + + private void doRun() { + try { + while (true) { + while (!myReader.ready()) { + synchronized (this) { + myReadSemaphore.up(); + wait(300); + if (isClosed) return; + } + } + int read = myReader.read(myBuffer); + if (read == -1) break; + + onTextAvailable(new String(myBuffer, 0, read)); + } + } + catch (IOException e) { + if (isClosed) return; + LOG.warn(e); + } + catch (InterruptedException e) { + LOG.warn(e); + } + } + + protected abstract void onTextAvailable(String text); + + public void readFully() throws InterruptedException { + synchronized (this) { + myReadSemaphore.down(); + notifyAll(); + } + myReadSemaphore.waitForUnsafe(); + } + + public void close() throws IOException { + synchronized (this) { + isClosed = true; + notifyAll(); + } + myReader.close(); + } +} diff --git a/platform/platform-api/src/com/intellij/util/ui/AnimatedIcon.java b/platform/platform-api/src/com/intellij/util/ui/AnimatedIcon.java index 2fba827b9995..73db90d39e97 100644 --- a/platform/platform-api/src/com/intellij/util/ui/AnimatedIcon.java +++ b/platform/platform-api/src/com/intellij/util/ui/AnimatedIcon.java @@ -83,7 +83,7 @@ public abstract class AnimatedIcon extends JComponent implements Disposable { myEmptyPassiveIcon = new EmptyIcon(0); } - setOpaque(true); + setOpaque(false); } public void setPaintPassiveIcon(boolean paintPassive) { diff --git a/platform/platform-impl/src/com/intellij/diagnostic/IdeMessagePanel.java b/platform/platform-impl/src/com/intellij/diagnostic/IdeMessagePanel.java index fb63a9a7f551..70d7d437ac9f 100644 --- a/platform/platform-impl/src/com/intellij/diagnostic/IdeMessagePanel.java +++ b/platform/platform-impl/src/com/intellij/diagnostic/IdeMessagePanel.java @@ -70,7 +70,7 @@ public class IdeMessagePanel extends JPanel implements MessagePoolListener, Cust return "FatalError"; } - public Presentation getPresentation(@NotNull Type type) { + public WidgetPresentation getPresentation(@NotNull Type type) { return null; } diff --git a/platform/platform-impl/src/com/intellij/notification/impl/IdeNotificationArea.java b/platform/platform-impl/src/com/intellij/notification/impl/IdeNotificationArea.java index 1b53b9dda8f9..dde5ca627468 100644 --- a/platform/platform-impl/src/com/intellij/notification/impl/IdeNotificationArea.java +++ b/platform/platform-impl/src/com/intellij/notification/impl/IdeNotificationArea.java @@ -47,7 +47,7 @@ public class IdeNotificationArea implements StatusBarWidget, StatusBarWidget.Ico public IdeNotificationArea() { } - public Presentation getPresentation(@NotNull Type type) { + public WidgetPresentation getPresentation(@NotNull Type type) { return this; } diff --git a/platform/platform-impl/src/com/intellij/openapi/command/impl/DocumentReferenceManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/command/impl/DocumentReferenceManagerImpl.java index 80e7c6a9bf2d..2fe3bdf3d4fa 100644 --- a/platform/platform-impl/src/com/intellij/openapi/command/impl/DocumentReferenceManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/command/impl/DocumentReferenceManagerImpl.java @@ -25,6 +25,7 @@ import com.intellij.openapi.util.Key; import com.intellij.openapi.vfs.*; import com.intellij.openapi.vfs.newvfs.NewVirtualFile; import com.intellij.util.containers.WeakValueHashMap; +import com.intellij.util.io.fs.FilePath; import org.jetbrains.annotations.NotNull; import java.lang.ref.Reference; diff --git a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapImpl.java b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapImpl.java index 19ee284dc689..96e11e646bc0 100644 --- a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapImpl.java @@ -269,6 +269,8 @@ public class KeymapImpl implements Keymap, ExternalizableScheme { } private Map> getKeystroke2ListOfIds() { + if (myKeystroke2ListOfIds != null) return myKeystroke2ListOfIds; + myKeystroke2ListOfIds = new THashMap>(); for (String id : ContainerUtil.concat(myActionId2ListOfShortcuts.keySet(), getKeymapManager().getBoundActions())) { addKeystrokesMap(id, myKeystroke2ListOfIds); diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/ex/StatusBarEx.java b/platform/platform-impl/src/com/intellij/openapi/wm/ex/StatusBarEx.java index 993a03137b96..d0f7dcb278d8 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/ex/StatusBarEx.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/ex/StatusBarEx.java @@ -42,4 +42,7 @@ public interface StatusBarEx extends StatusBar, Disposable { boolean isProcessWindowOpen(); void setProcessWindowOpen(boolean open); + + @Deprecated + void removeCustomIndicationComponents(); } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFrameImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFrameImpl.java index caef891f1da1..b4d0879f55b0 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFrameImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFrameImpl.java @@ -261,6 +261,8 @@ public class IdeFrameImpl extends JFrame implements IdeFrame, DataProvider { statusBar.removeWidget(positionPanel.ID()); statusBar.removeWidget(readOnlyAttributePanel.ID()); if (finalInsertOverwritePanel != null) statusBar.removeWidget(finalInsertOverwritePanel.ID()); + + ((StatusBarEx)statusBar).removeCustomIndicationComponents(); } }); } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeRootPane.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeRootPane.java index 7c99d15a5946..38c6329fac67 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeRootPane.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeRootPane.java @@ -224,7 +224,7 @@ public class IdeRootPane extends JRootPane implements UISettingsListener { return c.getClass().getSimpleName(); } - public Presentation getPresentation(@NotNull Type type) { + public WidgetPresentation getPresentation(@NotNull Type type) { return null; } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/TestWindowManager.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/TestWindowManager.java index c92380f4ff11..a1edce391e21 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/TestWindowManager.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/TestWindowManager.java @@ -119,6 +119,9 @@ public final class TestWindowManager extends WindowManagerEx implements Applicat public void setProcessWindowOpen(final boolean open) { } + public void removeCustomIndicationComponents() { + } + public BalloonHandler notifyProgressByBalloon(@NotNull MessageType type, @NotNull String htmlBody) { return new BalloonHandler() { public void hide() { diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/EncodingPanel.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/EncodingPanel.java index 77208ea51373..b6b680e0cec8 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/EncodingPanel.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/EncodingPanel.java @@ -58,7 +58,7 @@ public class EncodingPanel implements StatusBarWidget, StatusBarWidget.MultipleT return "Encoding"; } - public Presentation getPresentation(@NotNull Type type) { + public WidgetPresentation getPresentation(@NotNull Type type) { return this; } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/IdeStatusBarImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/IdeStatusBarImpl.java index 53006a5b18d4..93aad7ed8bb4 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/IdeStatusBarImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/IdeStatusBarImpl.java @@ -53,10 +53,10 @@ public class IdeStatusBarImpl extends JComponent implements StatusBarEx { private JPanel myRightPanel; private JPanel myCenterPanel; - private ProcessIconWidget myProcessWidget; - private String myInfo; + private List myCustomComponentIds = new ArrayList(); + private static class WidgetBean { JComponent component; Position position; @@ -73,10 +73,7 @@ public class IdeStatusBarImpl extends JComponent implements StatusBarEx { public IdeStatusBarImpl() { setLayout(new BorderLayout()); - setBorder(BorderFactory.createEmptyBorder(1, 2, 0, 2)); - - myProcessWidget = new ProcessIconWidget(); - addWidget(myProcessWidget, Position.LEFT); + setBorder(BorderFactory.createEmptyBorder(1, 4, 0, 2)); myInfoAndProgressPanel = new InfoAndProgressPanel(); addWidget(myInfoAndProgressPanel, Position.CENTER); @@ -115,15 +112,24 @@ public class IdeStatusBarImpl extends JComponent implements StatusBarEx { }); } + public void removeCustomIndicationComponents() { + for (final String id : myCustomComponentIds) { + removeWidget(id); + } + + myCustomComponentIds.clear(); + } + public void addCustomIndicationComponent(@NotNull final JComponent c) { + final String customId = c.getClass().getName() + new Random().nextLong(); addWidget(new CustomStatusBarWidget() { @NotNull public String ID() { - return c.getClass().getSimpleName() + new Random().toString(); + return customId; } @Nullable - public Presentation getPresentation(@NotNull Type type) { + public WidgetPresentation getPresentation(@NotNull Type type) { return null; } @@ -137,6 +143,8 @@ public class IdeStatusBarImpl extends JComponent implements StatusBarEx { return c; } }); + + myCustomComponentIds.add(customId); } public void removeCustomIndicationComponent(@NotNull final JComponent c) { @@ -275,12 +283,12 @@ public class IdeStatusBarImpl extends JComponent implements StatusBarEx { } public void startRefreshIndication(String tooltipText) { - myProcessWidget.setToolTipText(tooltipText); - myProcessWidget.setRefreshVisible(true); + myInfoAndProgressPanel.setRefreshToolTipText(tooltipText); + myInfoAndProgressPanel.setRefreshVisible(true); } public void stopRefreshIndication() { - myProcessWidget.setRefreshVisible(false); + myInfoAndProgressPanel.setRefreshVisible(false); } public BalloonHandler notifyProgressByBalloon(@NotNull MessageType type, @NotNull String htmlBody) { @@ -304,7 +312,7 @@ public class IdeStatusBarImpl extends JComponent implements StatusBarEx { } private static JComponent wrap(@NotNull final StatusBarWidget widget) { - final StatusBarWidget.Presentation presentation = + final StatusBarWidget.WidgetPresentation presentation = widget.getPresentation(SystemInfo.isMac ? StatusBarWidget.Type.MAC : StatusBarWidget.Type.DEFAULT); assert presentation != null : "Presentation should not be null!"; @@ -431,6 +439,8 @@ public class IdeStatusBarImpl extends JComponent implements StatusBarEx { popup.show(new RelativePoint(e.getComponent(), at)); } }); + + setOpaque(false); } @SuppressWarnings({"unchecked"}) @@ -485,6 +495,8 @@ public class IdeStatusBarImpl extends JComponent implements StatusBarEx { myMouseOver = false; } }); + + setOpaque(false); } public void beforeUpdate() { @@ -512,6 +524,7 @@ public class IdeStatusBarImpl extends JComponent implements StatusBarEx { }); ToolTipManager.sharedInstance().registerComponent(this); + setOpaque(false); } public void beforeUpdate() { diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InfoAndProgressPanel.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InfoAndProgressPanel.java index 3d8774b3c8d5..38de0902bb49 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InfoAndProgressPanel.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InfoAndProgressPanel.java @@ -46,6 +46,7 @@ public class InfoAndProgressPanel extends JPanel implements CustomStatusBarWidge private final ProcessPopup myPopup; private final TextPanel myInfoPanel = new TextPanel(); + private final JPanel myRefreshAndInfoPanel = new JPanel(); private final AsyncProcessIcon myProgressIcon; private final ArrayList myOriginals = new ArrayList(); @@ -59,10 +60,32 @@ public class InfoAndProgressPanel extends JPanel implements CustomStatusBarWidge private final Alarm myQueryAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD); private boolean myShouldClosePopupAndOnProcessFinish; + private AsyncProcessIcon myRefreshIcon; + private EmptyIcon myEmptyRefreshIcon; public InfoAndProgressPanel() { setOpaque(false); + myRefreshIcon = new AsyncProcessIcon("Refreshing filesystem") { + protected Icon getPassiveIcon() { + return myEmptyRefreshIcon; + } + + @Override + public Dimension getPreferredSize() { + if (!isRunning()) return new Dimension(0, 0); + return super.getPreferredSize(); + } + }; + + myRefreshIcon.setPaintPassiveIcon(false); + myEmptyRefreshIcon = new EmptyIcon(0, myRefreshIcon.getPreferredSize().height); + + myRefreshAndInfoPanel.setLayout(new BorderLayout()); + myRefreshAndInfoPanel.setOpaque(false); + myRefreshAndInfoPanel.add(myRefreshIcon, BorderLayout.WEST); + myRefreshAndInfoPanel.add(myInfoPanel, BorderLayout.CENTER); + myProgressIcon = new AsyncProcessIcon("Background process"); myProgressIcon.setOpaque(false); @@ -92,7 +115,7 @@ public class InfoAndProgressPanel extends JPanel implements CustomStatusBarWidge return "InfoAndProgress"; } - public Presentation getPresentation(@NotNull Type type) { + public WidgetPresentation getPresentation(@NotNull Type type) { return null; } @@ -100,6 +123,7 @@ public class InfoAndProgressPanel extends JPanel implements CustomStatusBarWidge } public void dispose() { + setRefreshVisible(false); } public JComponent getComponent() { @@ -236,7 +260,7 @@ public class InfoAndProgressPanel extends JPanel implements CustomStatusBarWidge //myProgressIcon.setBorder(new IdeStatusBarImpl.MacStatusBarWidgetBorder()); progressCountPanel.add(myProgressIcon, BorderLayout.WEST); - add(myInfoPanel, BorderLayout.CENTER); + add(myRefreshAndInfoPanel, BorderLayout.CENTER); progressCountPanel.setBorder(new EmptyBorder(0, 0, 0, 4)); add(progressCountPanel, BorderLayout.EAST); @@ -248,7 +272,7 @@ public class InfoAndProgressPanel extends JPanel implements CustomStatusBarWidge private void buildInInlineIndicator(final InlineProgressIndicator inline) { removeAll(); setLayout(new InlineLayout()); - add(myInfoPanel); + add(myRefreshAndInfoPanel); final JPanel inlinePanel = new JPanel(new BorderLayout()) { @Override @@ -270,14 +294,30 @@ public class InfoAndProgressPanel extends JPanel implements CustomStatusBarWidge add(inlinePanel); - myInfoPanel.revalidate(); - myInfoPanel.repaint(); + myRefreshAndInfoPanel.revalidate(); + myRefreshAndInfoPanel.repaint(); } public void setText(final String text) { myInfoPanel.setText(text); } + public void setRefreshVisible(final boolean visible) { + if (visible) { + myRefreshIcon.resume(); + } + else { + myRefreshIcon.suspend(); + } + + myRefreshIcon.revalidate(); + myRefreshIcon.repaint(); + } + + public void setRefreshToolTipText(final String tooltip) { + myRefreshIcon.setToolTipText(tooltip); + } + public BalloonHandler notifyByBalloon(MessageType type, String htmlBody, Icon icon, HyperlinkListener listener) { final Balloon balloon = JBPopupFactory.getInstance().createHtmlTextBalloonBuilder( htmlBody.replace("\n", "
"), @@ -382,9 +422,7 @@ public class InfoAndProgressPanel extends JPanel implements CustomStatusBarWidge private void restoreEmptyStatus() { removeAll(); setLayout(new BorderLayout()); - add(myInfoPanel, BorderLayout.CENTER); - - //myProgressIcon.setBorder(new IdeStatusBarImpl.MacStatusBarWidgetBorder()); + add(myRefreshAndInfoPanel, BorderLayout.CENTER); long wastedTime = ProgressManagerImpl.getWastedTime(); if (ApplicationManagerEx.getApplicationEx().isInternal() && wastedTime > 10 * 60 * 1000) { @@ -417,8 +455,8 @@ public class InfoAndProgressPanel extends JPanel implements CustomStatusBarWidge } myProgressIcon.suspend(); - myInfoPanel.revalidate(); - myInfoPanel.repaint(); + myRefreshAndInfoPanel.revalidate(); + myRefreshAndInfoPanel.repaint(); } private String formatTime(long t) { diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InlineProgressIndicator.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InlineProgressIndicator.java index 03eea5520ea6..c863892114dd 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InlineProgressIndicator.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InlineProgressIndicator.java @@ -46,7 +46,7 @@ public class InlineProgressIndicator extends ProgressIndicatorBase implements Di private final boolean myCompact; private TaskInfo myInfo; - private final FixedHeightLabel myProcessName = new FixedHeightLabel(); + private final TextPanel myProcessName = new TextPanel(); private boolean myDisposed; private long myLastTimeProgressWasAtZero; @@ -81,10 +81,10 @@ public class InlineProgressIndicator extends ProgressIndicatorBase implements Di textAndProgress.add(myText, BorderLayout.CENTER); final NonOpaquePanel progressWrapper = new NonOpaquePanel(new GridBagLayout()); - if (!myInfo.isCancellable()) progressWrapper.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 4)); final GridBagConstraints c = new GridBagConstraints(); c.weightx = 1; c.weighty = 1; + c.insets = new Insets(0, 0, 1, myInfo.isCancellable() ? 0 : 4); c.fill = GridBagConstraints.HORIZONTAL; progressWrapper.add(myProgress, c); @@ -108,6 +108,7 @@ public class InlineProgressIndicator extends ProgressIndicatorBase implements Di myProcessName.setFont(font.deriveFont(Font.PLAIN, size)); myProcessName.setForeground(UIManager.getColor("Panel.background").brighter().brighter()); myProcessName.setBorder(new EmptyBorder(2, 2, 2, 2)); + myProcessName.setDecorate(false); final NonOpaquePanel content = new NonOpaquePanel(new BorderLayout()); content.setBorder(new EmptyBorder(2, 2, 2, myInfo.isCancellable() ? 2 : 4)); @@ -122,6 +123,9 @@ public class InlineProgressIndicator extends ProgressIndicatorBase implements Di content.add(myProgress, BorderLayout.CENTER); content.add(myText2, BorderLayout.SOUTH); + myText.setDecorate(false); + myText2.setDecorate(false); + myComponent.setBorder(new EmptyBorder(2, 2, 2, 2)); myProgress.setActive(false); } @@ -130,6 +134,8 @@ public class InlineProgressIndicator extends ProgressIndicatorBase implements Di if (!myCompact) { myProcessName.recomputeSize(); + myText.recomputeSize(); + myText2.recomputeSize(); } } @@ -274,33 +280,6 @@ public class InlineProgressIndicator extends ProgressIndicatorBase implements Di return myInfo; } - // TODO: use TextPanel instead - private static class FixedHeightLabel extends JLabel { - private Dimension myPrefSize; - - public FixedHeightLabel() { - setOpaque(false); - if (SystemInfo.isMac) setFont(UIUtil.getLabelFont().deriveFont(11.0f)); - } - - public void recomputeSize() { - final String old = getText(); - setText("XXX"); - myPrefSize = getPreferredSize(); - setText(old); - } - - - public Dimension getPreferredSize() { - final Dimension size = super.getPreferredSize(); - if (myPrefSize != null) { - size.height = myPrefSize.height; - } - - return size; - } - } - private static class MyProgressBar extends JProgressBar { private boolean myActive = true; @@ -336,9 +315,9 @@ public class InlineProgressIndicator extends ProgressIndicatorBase implements Di private class MyComponent extends JPanel { private final boolean myCompact; - private final FixedHeightLabel myProcessName; + private final JComponent myProcessName; - private MyComponent(final boolean compact, final FixedHeightLabel processName) { + private MyComponent(final boolean compact, final JComponent processName) { myCompact = compact; myProcessName = processName; addMouseListener(new MouseAdapter() { diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InsertOverwritePanel.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InsertOverwritePanel.java index f9b035113313..cb24d4750822 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InsertOverwritePanel.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InsertOverwritePanel.java @@ -39,7 +39,7 @@ public class InsertOverwritePanel implements StatusBarWidget, StatusBarWidget.Te return "InsertOverwrite"; } - public Presentation getPresentation(@NotNull Type type) { + public WidgetPresentation getPresentation(@NotNull Type type) { return this; } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/MemoryUsagePanel.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/MemoryUsagePanel.java index dff5382b01db..95010417f1af 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/MemoryUsagePanel.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/MemoryUsagePanel.java @@ -64,7 +64,7 @@ public class MemoryUsagePanel extends JButton implements CustomStatusBarWidget { } @Nullable - public Presentation getPresentation(@NotNull Type type) { + public WidgetPresentation getPresentation(@NotNull Type type) { return null; } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/PositionPanel.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/PositionPanel.java index c1d4f615ee99..692a796c47cf 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/PositionPanel.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/PositionPanel.java @@ -52,7 +52,7 @@ public class PositionPanel implements StatusBarWidget, StatusBarWidget.TextPrese return "Position"; } - public Presentation getPresentation(@NotNull final Type type) { + public WidgetPresentation getPresentation(@NotNull final Type type) { return this; } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/ProcessIconWidget.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/ProcessIconWidget.java deleted file mode 100644 index 02a628659bfe..000000000000 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/ProcessIconWidget.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2000-2010 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.openapi.wm.impl.status; - -import com.intellij.openapi.wm.*; -import com.intellij.util.ui.*; -import org.jetbrains.annotations.*; - -import javax.swing.*; -import java.awt.*; - -/** - * User: spLeaner - */ -public class ProcessIconWidget implements CustomStatusBarWidget { - private AsyncProcessIcon myRefreshIcon; - private EmptyIcon myEmptyRefreshIcon; - - public ProcessIconWidget() { - myRefreshIcon = new AsyncProcessIcon("Refreshing filesystem") { - protected Icon getPassiveIcon() { - return myEmptyRefreshIcon; - } - - @Override - public Dimension getPreferredSize() { - if (!isRunning()) return new Dimension(4, 0); - return super.getPreferredSize(); - } - }; - - myRefreshIcon.setBorder(StatusBarWidget.WidgetBorder.INSTANCE); - myRefreshIcon.setOpaque(false); - - myEmptyRefreshIcon = new EmptyIcon(0 /*myRefreshIcon.getPreferredSize().width*/, myRefreshIcon.getPreferredSize().height); - setRefreshVisible(false); - } - - public JComponent getComponent() { - return myRefreshIcon; - } - - public void setRefreshVisible(final boolean visible) { - if (visible) { - myRefreshIcon.resume(); - } - else { - myRefreshIcon.suspend(); - } - - myRefreshIcon.revalidate(); - myRefreshIcon.repaint(); - } - - public void setToolTipText(final String tooltip) { - myRefreshIcon.setToolTipText(tooltip); - } - - @NotNull - public String ID() { - return "RefreshIcon"; - } - - public Presentation getPresentation(@NotNull Type type) { - return null; - } - - public void install(@NotNull StatusBar statusBar) { - } - - public void dispose() { - setRefreshVisible(false); - } -} diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/TextPanel.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/TextPanel.java index 9a89ea957285..74de6754f904 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/TextPanel.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/TextPanel.java @@ -25,11 +25,19 @@ import java.awt.*; public class TextPanel extends JComponent { private String myText; private final String myMaxPossibleString; + private Dimension myPrefSize; + + private boolean myDecorate = true; TextPanel() { this(null); } + TextPanel(final boolean decorate) { + this(null); + myDecorate = decorate; + } + TextPanel(@Nullable final String maxPossibleString) { myMaxPossibleString = maxPossibleString; @@ -37,6 +45,16 @@ public class TextPanel extends JComponent { setOpaque(false); } + public void recomputeSize() { + final JLabel label = new JLabel("XXX"); + label.setFont(getFont()); + myPrefSize = label.getPreferredSize(); + } + + public void setDecorate(boolean decorate) { + myDecorate = decorate; + } + @Override protected void paintComponent(final Graphics g) { final String s = getText(); @@ -47,14 +65,14 @@ public class TextPanel extends JComponent { final Graphics2D g2 = (Graphics2D)g; g2.setFont(getFont()); + UIUtil.applyRenderingHints(g2); + final int y = UIUtil.getStringY(s, bounds, g2); - if (SystemInfo.isMac) { + if (SystemInfo.isMac && myDecorate) { g2.setColor(new Color(215, 215, 215)); g2.drawString(s, insets.left, y+1); } - UIUtil.applyRenderingHints(g2); - g2.setColor(getForeground()); g2.drawString(s, insets.left, y); } @@ -88,6 +106,11 @@ public class TextPanel extends JComponent { public Dimension getPreferredSize(){ int max = 0; if (myMaxPossibleString != null) max = getFontMetrics(getFont()).stringWidth(myMaxPossibleString); + + if (myPrefSize != null) { + return new Dimension(20 + max, myPrefSize.height); + } + return new Dimension(20 + max, getMinimumSize().height); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/ToggleReadOnlyAttributePanel.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/ToggleReadOnlyAttributePanel.java index 728bad27eb9f..d2c9905e1585 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/ToggleReadOnlyAttributePanel.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/ToggleReadOnlyAttributePanel.java @@ -51,7 +51,7 @@ public class ToggleReadOnlyAttributePanel implements StatusBarWidget, StatusBarW return "ReadOnlyAttribute"; } - public Presentation getPresentation(@NotNull Type type) { + public WidgetPresentation getPresentation(@NotNull Type type) { return this; } diff --git a/platform/platform-impl/src/com/intellij/ui/AppIcon.java b/platform/platform-impl/src/com/intellij/ui/AppIcon.java index 33e51d08c00b..cfd003fb6d90 100644 --- a/platform/platform-impl/src/com/intellij/ui/AppIcon.java +++ b/platform/platform-impl/src/com/intellij/ui/AppIcon.java @@ -130,8 +130,8 @@ public abstract class AppIcon { @Override public void applicationActivated(IdeFrame ideFrame) { hideProgress(myCurrentProcessId); - setOkBadge(false); - setErrorBadge(null); + _setOkBadge(false); + _setTextBadge(null); } }; app.addApplicationListener(myAppListener); diff --git a/platform/platform-impl/testSrc/com/intellij/ide/util/treeView/AbstractTreeBuilderTest.java b/platform/platform-impl/testSrc/com/intellij/ide/util/treeView/AbstractTreeBuilderTest.java index 2b004f1e228d..2721428b3bdc 100644 --- a/platform/platform-impl/testSrc/com/intellij/ide/util/treeView/AbstractTreeBuilderTest.java +++ b/platform/platform-impl/testSrc/com/intellij/ide/util/treeView/AbstractTreeBuilderTest.java @@ -1,5 +1,6 @@ package com.intellij.ide.util.treeView; +import com.intellij.openapi.util.AsyncResult; import com.intellij.openapi.util.Condition; import com.intellij.testFramework.PlatformTestUtil; import com.intellij.ui.treeStructure.Tree; @@ -108,6 +109,7 @@ abstract class AbstractTreeBuilderTest extends BaseTreeTestCase myChild2Parent = new HashMap(); private final Map myElement2Node = new HashMap(); private final Set myLeaves = new HashSet(); + private Revalidator myRevalidator; public Object getRootElement() { return myRoot.myElement; @@ -464,7 +473,8 @@ abstract class AbstractTreeBuilderTest extends BaseTreeTestCase revalidateElement(Object element) { + return myRevalidator != null ? myRevalidator.revalidate((NodeElement)element) : super.revalidateElement(element); + } + + public void setRevalidator(Revalidator revalidator) { + myRevalidator = revalidator; + } + } + + interface Revalidator { + AsyncResult revalidate(NodeElement element); } class MyBuilder extends BaseTreeBuilder { diff --git a/platform/platform-impl/testSrc/com/intellij/ide/util/treeView/BaseTreeTestCase.java b/platform/platform-impl/testSrc/com/intellij/ide/util/treeView/BaseTreeTestCase.java index dd9c5c32ae0d..87ffd2aac14a 100644 --- a/platform/platform-impl/testSrc/com/intellij/ide/util/treeView/BaseTreeTestCase.java +++ b/platform/platform-impl/testSrc/com/intellij/ide/util/treeView/BaseTreeTestCase.java @@ -97,11 +97,12 @@ abstract class BaseTreeTestCase extends FlyIdeaTestCase { }.isConditionRealized(); if (myCancelRequest != null) { - Thread.dumpStack(); throw new Exception(myCancelRequest); } - Assert.assertTrue(getBuilder().getUi().getNodeActions().isEmpty()); + if (myCancelRequest == null && !myReadyRequest) { + Assert.assertTrue(getBuilder().getUi().getNodeActions().isEmpty()); + } Assert.assertTrue(success); } @@ -226,7 +227,13 @@ abstract class BaseTreeTestCase extends FlyIdeaTestCase { } void _runBackgroundLoading(Runnable runnable) { - SimpleTimer.getInstance().setUp(runnable, getChildrenLoadingDelay()); + try { + Thread.currentThread().sleep(getChildrenLoadingDelay()); + runnable.run(); + } + catch (InterruptedException e) { + throw new RuntimeException(e); + } } @@ -448,6 +455,7 @@ abstract class BaseTreeTestCase extends FlyIdeaTestCase { public static class NodeElement extends ComparableObject.Impl implements Comparable{ final String myName; + private NodeElement myForcedParent; public NodeElement(String name) { super(name); @@ -461,6 +469,14 @@ abstract class BaseTreeTestCase extends FlyIdeaTestCase { public int compareTo(NodeElement o) { return myName.compareTo(o.myName); } + + public NodeElement getForcedParent() { + return myForcedParent; + } + + public void setForcedParent(NodeElement forcedParent) { + myForcedParent = forcedParent; + } } } diff --git a/platform/platform-impl/testSrc/com/intellij/ide/util/treeView/TreeUiTest.java b/platform/platform-impl/testSrc/com/intellij/ide/util/treeView/TreeUiTest.java index c5ed81422547..b2832ec408aa 100644 --- a/platform/platform-impl/testSrc/com/intellij/ide/util/treeView/TreeUiTest.java +++ b/platform/platform-impl/testSrc/com/intellij/ide/util/treeView/TreeUiTest.java @@ -3,10 +3,7 @@ package com.intellij.ide.util.treeView; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.Progressive; -import com.intellij.openapi.util.ActionCallback; -import com.intellij.openapi.util.Condition; -import com.intellij.openapi.util.Disposer; -import com.intellij.openapi.util.Ref; +import com.intellij.openapi.util.*; import com.intellij.util.Time; import com.intellij.util.WaitFor; import junit.framework.TestSuite; @@ -1013,7 +1010,7 @@ public class TreeUiTest extends AbstractTreeBuilderTest { public void onElementAction(String action, Object element) { if (wasInterrupted[0]) { if (myCancelRequest == null) { - myCancelRequest = new AssertionError("Not supposed to be update after interruption request: action=" + action + " element=" + element); + myCancelRequest = new AssertionError("Not supposed to be update after interruption request: action=" + action + " element=" + element + " interruptAction=" + interruptAction + " interruptElement=" + interruptElement); } } else { if (element.equals(interruptElement) && action.equals(interruptAction)) { @@ -1411,6 +1408,72 @@ public class TreeUiTest extends AbstractTreeBuilderTest { doTestSelectionOnDelete(true); } + public void testRevalidateStructure() throws Exception { + final NodeElement com = new NodeElement("com"); + final NodeElement actionSystem = new NodeElement("actionSystem"); + actionSystem.setForcedParent(com); + + final NodeElement fabrique = new NodeElement("fabrique"); + final NodeElement ide = new NodeElement("ide"); + fabrique.setForcedParent(myRoot.getElement()); + + doAndWaitForBuilder(new Runnable() { + public void run() { + myRoot.addChild(com).addChild(actionSystem); + myRoot.addChild(fabrique).addChild(ide); + getBuilder().getUi().activate(true); + } + }); + + select(actionSystem, false); + expand(getPath("ide")); + + assertTree("-/\n" + + " -com\n" + + " [actionSystem]\n" + + " -fabrique\n" + + " ide\n"); + + + removeFromParentButKeepRef(actionSystem); + removeFromParentButKeepRef(fabrique); + + final NodeElement newActionSystem = new NodeElement("actionSystem"); + final NodeElement newFabrique = new NodeElement("fabrique"); + + myStructure.getNodeFor(com).addChild("intellij").addChild("openapi").addChild(newActionSystem); + myRoot.addChild("jetbrains").addChild("tools").addChild(newFabrique).addChild("ide"); + + assertSame(com, myStructure.getParentElement(actionSystem)); + assertNotSame(com, newActionSystem); + assertEquals(new NodeElement("openapi"), myStructure.getParentElement(newActionSystem)); + + assertSame(myRoot.getElement(), myStructure.getParentElement(fabrique)); + + myStructure.setRevalidator(new Revalidator() { + public AsyncResult revalidate(NodeElement element) { + if (element == actionSystem) { + return new AsyncResult.Done(newActionSystem); + } else if (element == fabrique) { + return new AsyncResult.Done(newFabrique); + } + return null; + } + }); + + updateFromRoot(); + + assertTree("-/\n" + + " -com\n" + + " -intellij\n" + + " -openapi\n" + + " [actionSystem]\n" + + " -jetbrains\n" + + " -tools\n" + + " -fabrique\n" + + " ide\n"); + } + private void doTestSelectionOnDelete(boolean keepRef) throws Exception { myComparator.setDelegate(new NodeDescriptor.NodeComparator() { public int compare(NodeDescriptor o1, NodeDescriptor o2) { @@ -1673,20 +1736,26 @@ public class TreeUiTest extends AbstractTreeBuilderTest { public void onElementAction(String action, Object element) { if (!element.toString().equals(actionElement.toString())) return; + Runnable runnable = new Runnable() { + public void run() { + myReadyRequest = true; + Disposer.dispose(getBuilder()); + } + }; + if (actionAction.equals(action)) { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - myReadyRequest = true; - Disposer.dispose(getBuilder()); - } - }); + if (getBuilder().getUi().isPassthroughMode()) { + runnable.run(); + } else { + SwingUtilities.invokeLater(runnable); + } } } }; buildAction.run(); - boolean released = new WaitFor(5000) { + boolean released = new WaitFor(15000) { @Override protected boolean condition() { return getBuilder().getUi() == null; @@ -1700,16 +1769,6 @@ public class TreeUiTest extends AbstractTreeBuilderTest { public SyncUpdate() { super(false, false); } - - @Override - public void testCancelUpdate() throws Exception { - super.testCancelUpdate(); - } - - @Override - public void testThrowingProcessCancelledInterruptsUpdate() throws Exception { - super.testThrowingProcessCancelledInterruptsUpdate(); - } } public static class Passthrough extends TreeUiTest { @@ -1717,11 +1776,6 @@ public class TreeUiTest extends AbstractTreeBuilderTest { super(true); } - @Override - public void testCancelUpdate() throws Exception { - super.testCancelUpdate(); - } - public void testSelectionGoesToParentWhenOnlyChildMoved2() throws Exception { //todo } @@ -1762,6 +1816,11 @@ public class TreeUiTest extends AbstractTreeBuilderTest { super(false, true); } + @Override + public void testReleaseBuilderDuringUpdate() throws Exception { + super.testReleaseBuilderDuringUpdate(); + } + @Override protected int getChildrenLoadingDelay() { return 300; diff --git a/platform/platform-resources/src/FileTypeManager.xml b/platform/platform-resources/src/FileTypeManager.xml index 5911348c1044..007518cdb91f 100644 --- a/platform/platform-resources/src/FileTypeManager.xml +++ b/platform/platform-resources/src/FileTypeManager.xml @@ -231,6 +231,7 @@ + @@ -258,7 +259,6 @@ - diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/FileUrlProvider.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/FileUrlProvider.java index f559ede447d5..33764f466176 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/FileUrlProvider.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/FileUrlProvider.java @@ -104,24 +104,25 @@ public class FileUrlProvider implements TestLocationProvider { final int lineCount = doc.getLineCount(); final int lineStartOffset; + final int endOffset; if (lineNum <= lineCount) { lineStartOffset = doc.getLineStartOffset(lineNum - 1); + endOffset = doc.getLineEndOffset(lineNum - 1); } else { // unknown line lineStartOffset = 0; + endOffset = doc.getTextLength(); } - PsiElement elementAtLine = psiFile.findElementAt(lineStartOffset); - if (elementAtLine != null) { - // skip whitespaces - while (elementAtLine instanceof PsiWhiteSpace) { - elementAtLine = elementAtLine.getNextSibling(); - } + int offset = lineStartOffset; + PsiElement elementAtLine = null; + while (offset <= endOffset) { + elementAtLine = psiFile.findElementAt(offset); + if (!(elementAtLine instanceof PsiWhiteSpace)) break; + int length = elementAtLine.getTextLength(); + offset += length > 1 ? length - 1 : 1; } - final PsiElement leafPsiElementAtLine = elementAtLine == null - ? null - : psiFile.findElementAt(elementAtLine.getTextOffset()); - return PsiLocation.fromPsiElement(project, leafPsiElementAtLine != null ? leafPsiElementAtLine : psiFile); + return PsiLocation.fromPsiElement(project, elementAtLine != null ? elementAtLine : psiFile); } } diff --git a/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/FileUrlLocationTest.java b/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/FileUrlLocationTest.java index 7a45329efef9..dc9b834fcea3 100644 --- a/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/FileUrlLocationTest.java +++ b/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/FileUrlLocationTest.java @@ -29,39 +29,16 @@ public class FileUrlLocationTest extends SMLightFixtureTestCase { } public void testSpecNavigation() throws Throwable { - createAndAddFile("my_example_spec.rb", + createAndAddFile("my_example_spec.xml", "\n" + - "require \"spec\"\n" + - "\n" + - "describe \"Blabla\" do\n" + - "\n" + - " # Called before each example.\n" + - " before(:each) do\n" + - " # Do nothing\n" + - " end\n" + - "\n" + - " # Called after each example.\n" + - " after(:each) do\n" + - " # Do nothing\n" + - " end\n" + - "\n" + - " it \"should fail\" do\n" + - "\n" + - " #should pass\n" + - " true.should == false\n" + - " end\n" + - "\n" + - " it \"should pass\" do\n" + - "\n" + - " #should pass\n" + - " true.should == true\n" + - " end\n" + - "end"); + "\n" + + " \n" + + "\n" + + "\n"); final String path = myFixture.getFile().getVirtualFile().getPath(); - doTest(17, "describe", path, 4); - doTest(189, "it", path, 16); - doTest(261, "it", path, 22); + doTest(1, "<", path, 2); + doTest(16, "<", path, 3); } private void doTest(final int expectedOffset, final String expectedStartsWith, diff --git a/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/SMLightFixtureTestCase.java b/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/SMLightFixtureTestCase.java index 2cda3fa48c0f..660550647287 100644 --- a/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/SMLightFixtureTestCase.java +++ b/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/SMLightFixtureTestCase.java @@ -23,6 +23,7 @@ import com.intellij.openapi.roots.ContentEntry; import com.intellij.openapi.roots.ModifiableRootModel; import com.intellij.psi.PsiFile; import com.intellij.testFramework.LightProjectDescriptor; +import com.intellij.testFramework.PlatformTestCase; import com.intellij.testFramework.UsefulTestCase; import com.intellij.testFramework.fixtures.CodeInsightTestFixture; import com.intellij.testFramework.fixtures.IdeaProjectTestFixture; @@ -37,6 +38,11 @@ import java.io.IOException; * @author Roman.Chernyatchik */ public abstract class SMLightFixtureTestCase extends UsefulTestCase { + + protected SMLightFixtureTestCase() { + PlatformTestCase.initPlatformLangPrefix(); + } + protected static final LightProjectDescriptor ourDescriptor = new LightProjectDescriptor() { public ModuleType getModuleType() { return ModuleType.EMPTY; diff --git a/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/BaseSMTRunnerTestCase.java b/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/BaseSMTRunnerTestCase.java index e6552e9b9f61..607e32a8a2de 100644 --- a/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/BaseSMTRunnerTestCase.java +++ b/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/BaseSMTRunnerTestCase.java @@ -18,6 +18,7 @@ package com.intellij.execution.testframework.sm.runner; import com.intellij.execution.configurations.RuntimeConfiguration; import com.intellij.execution.testframework.TestConsoleProperties; import com.intellij.testFramework.LightPlatformTestCase; +import com.intellij.testFramework.PlatformTestCase; /** * @author Roman Chernyatchik @@ -26,6 +27,10 @@ public abstract class BaseSMTRunnerTestCase extends LightPlatformTestCase { protected SMTestProxy mySuite; protected SMTestProxy mySimpleTest; + protected BaseSMTRunnerTestCase() { + PlatformTestCase.initPlatformLangPrefix(); + } + @Override protected void setUp() throws Exception { super.setUp(); diff --git a/platform/util/src/com/intellij/openapi/util/text/StringUtil.java b/platform/util/src/com/intellij/openapi/util/text/StringUtil.java index ed99449c231a..19faf3c99e3f 100644 --- a/platform/util/src/com/intellij/openapi/util/text/StringUtil.java +++ b/platform/util/src/com/intellij/openapi/util/text/StringUtil.java @@ -1172,7 +1172,7 @@ public class StringUtil { } @NotNull public static String replaceSubstring(@NotNull String string, @NotNull TextRange range, @NotNull String replacement) { - return string.substring(0, range.getStartOffset()) + replacement + string.substring(range.getEndOffset()); + return range.replace(string, replacement); } public static boolean startsWith(@NotNull CharSequence text, @NotNull CharSequence prefix) { diff --git a/platform/platform-api/src/com/intellij/openapi/vfs/FilePath.java b/platform/util/src/com/intellij/util/io/fs/FilePath.java similarity index 97% rename from platform/platform-api/src/com/intellij/openapi/vfs/FilePath.java rename to platform/util/src/com/intellij/util/io/fs/FilePath.java index 5a9c1c295b2e..dbf200971743 100644 --- a/platform/platform-api/src/com/intellij/openapi/vfs/FilePath.java +++ b/platform/util/src/com/intellij/util/io/fs/FilePath.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.intellij.openapi.vfs; +package com.intellij.util.io.fs; import com.intellij.openapi.util.io.FileUtil; diff --git a/platform/util/src/com/intellij/util/properties/EncodingAwareProperties.java b/platform/util/src/com/intellij/util/properties/EncodingAwareProperties.java index ab2457748cbe..064833aee51a 100644 --- a/platform/util/src/com/intellij/util/properties/EncodingAwareProperties.java +++ b/platform/util/src/com/intellij/util/properties/EncodingAwareProperties.java @@ -33,7 +33,7 @@ public class EncodingAwareProperties extends java.util.Properties{ propText = StringUtil.convertLineSeparators(propText); StringTokenizer stringTokenizer = new StringTokenizer(propText, "\n"); while (stringTokenizer.hasMoreElements()){ - String line = (String)stringTokenizer.nextElement(); + String line = stringTokenizer.nextElement(); int i = line.indexOf('='); String propName = i == -1 ? line : line.substring(0,i); String propValue = i == -1 ? "" : line.substring(i+1); diff --git a/platform/util/src/com/intellij/util/ui/UIUtil.java b/platform/util/src/com/intellij/util/ui/UIUtil.java index f11b23ab2538..1a3318868faf 100644 --- a/platform/util/src/com/intellij/util/ui/UIUtil.java +++ b/platform/util/src/com/intellij/util/ui/UIUtil.java @@ -1203,7 +1203,9 @@ public class UIUtil { final int containerWidth = tree.getParent() instanceof JViewport ? tree.getParent().getWidth() : tree.getWidth(); final int xOffset = tree.getParent() instanceof JViewport ? ((JViewport)tree.getParent()).getViewPosition().x : 0; - if (path != null && tree.isPathSelected(path)) { + boolean selected = false; + if (path != null) { + selected = tree.isPathSelected(path); Graphics2D rowGraphics = (Graphics2D)g.create(); if (clipBounds.height >= bounds.height) { // fill the row only if clip bounds intersects actual node bounds @@ -1216,14 +1218,24 @@ public class UIUtil { final Object sourceList = tree.getClientProperty(SOURCE_LIST_CLIENT_PROPERTY); if (sourceList != null && ((Boolean)sourceList)) { - if (tree.hasFocus()) { - LIST_FOCUSED_SELECTION_BACKGROUND_PAINTER.paintBorder(tree, rowGraphics, xOffset, bounds.y, containerWidth, bounds.height); - } - else { - LIST_SELECTION_BACKGROUND_PAINTER.paintBorder(tree, rowGraphics, xOffset, bounds.y, containerWidth, bounds.height); + if (selected) { + if (tree.hasFocus()) { + LIST_FOCUSED_SELECTION_BACKGROUND_PAINTER.paintBorder(tree, rowGraphics, xOffset, bounds.y, containerWidth, bounds.height); + } + else { + LIST_SELECTION_BACKGROUND_PAINTER.paintBorder(tree, rowGraphics, xOffset, bounds.y, containerWidth, bounds.height); + } + } else { + rowGraphics.setColor(tree.getBackground()); + rowGraphics.fillRect(xOffset, bounds.y, containerWidth, bounds.height); } } else { - rowGraphics.setColor(tree.hasFocus() ? getTreeSelectionBackground() : UNFOCUSED_SELECTION_COLOR); + Color bg = tree.hasFocus() ? getTreeSelectionBackground() : UNFOCUSED_SELECTION_COLOR; + if (!selected) { + bg = tree.getBackground(); + } + + rowGraphics.setColor(bg); rowGraphics.fillRect(xOffset, bounds.y, containerWidth, bounds.height - 1); } diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/IncomingChangesIndicator.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/IncomingChangesIndicator.java index 7a35159b4f26..400df91ebadc 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/IncomingChangesIndicator.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/IncomingChangesIndicator.java @@ -159,7 +159,7 @@ public class IncomingChangesIndicator implements ProjectComponent { return "IncomingChanges"; } - public Presentation getPresentation(@NotNull Type type) { + public WidgetPresentation getPresentation(@NotNull Type type) { return this; } diff --git a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/config/ui/MethodParameterPanel.java b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/config/ui/MethodParameterPanel.java index f2e78dc7eea8..45ecd07a2550 100644 --- a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/config/ui/MethodParameterPanel.java +++ b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/config/ui/MethodParameterPanel.java @@ -72,6 +72,7 @@ public class MethodParameterPanel extends AbstractInjectionPanel() { public Document fun(String s) { @@ -411,4 +412,8 @@ public class MethodParameterPanel extends AbstractInjectionPanel { +public class AdvancedXmlPanel extends AbstractInjectionPanel { private JPanel myRoot; @@ -37,30 +36,21 @@ public class AdvancedXmlPanel extends AbstractInjectionPanel { private JLabel myXPathConditionLabel; private JCheckBox mySingleFileCheckBox; - public AdvancedXmlPanel(Project project, BaseInjection injection) { + public AdvancedXmlPanel(Project project, AbstractTagInjection injection) { super(injection, project); $$$setupUI$$$(); // see IDEA-9987 - if (!(injection instanceof AbstractTagInjection)) { - myXPathCondition.setVisible(false); - myXPathConditionLabel.setVisible(false); - } - } - protected void apply(BaseInjection other) { + protected void apply(AbstractTagInjection other) { other.setValuePattern(myValuePattern.getText()); other.setSingleFile(mySingleFileCheckBox.isSelected()); - if (myOrigInjection instanceof AbstractTagInjection) { - ((AbstractTagInjection)other).setXPathCondition(myXPathCondition.getText()); - } + other.setXPathCondition(myXPathCondition.getText()); } protected void resetImpl() { myValuePattern.setText(myOrigInjection.getValuePattern()); mySingleFileCheckBox.setSelected(myOrigInjection.isSingleFile()); - if (myOrigInjection instanceof AbstractTagInjection) { - myXPathCondition.setText(((AbstractTagInjection)myOrigInjection).getXPathCondition()); - } + myXPathCondition.setText(myOrigInjection.getXPathCondition()); } public JPanel getComponent() { @@ -74,11 +64,10 @@ public class AdvancedXmlPanel extends AbstractInjectionPanel { } }); - if (myOrigInjection instanceof AbstractTagInjection) { -// don't even bother to look up the language when xpath-evaluation isn't possible - final XPathSupportProxy proxy = XPathSupportProxy.getInstance(); - myXPathCondition = new LanguageTextField(proxy != null ? InjectedLanguage.findLanguageById("XPath") : null, myProject, - ((AbstractTagInjection)myOrigInjection).getXPathCondition(), new Consumer() { + // don't even bother to look up the language when xpath-evaluation isn't possible + final XPathSupportProxy proxy = XPathSupportProxy.getInstance(); + myXPathCondition = new LanguageTextField(proxy != null ? InjectedLanguage.findLanguageById("XPath") : null, myProject, + myOrigInjection.getXPathCondition(), new Consumer() { public void consume(PsiFile psiFile) { // important to get proper validation & completion for Jaxen's built-in and PSI functions // like lower-case(), file-type(), file-ext(), file-name(), etc. @@ -87,10 +76,6 @@ public class AdvancedXmlPanel extends AbstractInjectionPanel { } } }); - } - else { - myXPathCondition = new EditorTextField(); - } } private void $$$setupUI$$$() { diff --git a/plugins/groovy/src/org/intellij/plugins/intelliLang/inject/groovy/PatternEditorContextMembersProvider.java b/plugins/groovy/src/org/intellij/plugins/intelliLang/inject/groovy/PatternEditorContextMembersProvider.java index b78c9061bd0e..02faaed56cb8 100644 --- a/plugins/groovy/src/org/intellij/plugins/intelliLang/inject/groovy/PatternEditorContextMembersProvider.java +++ b/plugins/groovy/src/org/intellij/plugins/intelliLang/inject/groovy/PatternEditorContextMembersProvider.java @@ -26,6 +26,8 @@ import org.intellij.plugins.intelliLang.inject.config.BaseInjection; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.groovy.GroovyFileType; import org.jetbrains.plugins.groovy.lang.resolve.NonCodeMembersProcessor; +import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil; +import org.jetbrains.plugins.groovy.lang.resolve.processors.ClassHint; /** * @author Gregory.Shrago @@ -38,13 +40,18 @@ public class PatternEditorContextMembersProvider implements NonCodeMembersProces final PsiFile file = place.getContainingFile().getOriginalFile(); final BaseInjection injection = file.getUserData(BaseInjection.INJECTION_KEY); if (injection == null) return true; - return ((UserDataHolderEx)file).putUserDataIfAbsent(INJECTION_PARSED_CONTEXT, new AtomicNotNullLazyValue() { - @NotNull - @Override - protected PsiFile compute() { - return parseInjectionContext(injection, file.getProject()); - } - }).getValue().processDeclarations(processor, ResolveState.initial(), null, place); + final PsiFile contextFile = + ((UserDataHolderEx)file).putUserDataIfAbsent(INJECTION_PARSED_CONTEXT, new AtomicNotNullLazyValue() { + @NotNull + @Override + protected PsiFile compute() { + return parseInjectionContext(injection, file.getProject()); + } + }).getValue(); + for (PsiElement cur = contextFile.getFirstChild(); cur != null; cur = cur.getNextSibling()) { + if (cur instanceof PsiNamedElement && !ResolveUtil.processElement(processor, (PsiNamedElement)cur)) return false; + } + return true; } private static PsiFile parseInjectionContext(@NotNull BaseInjection injection, Project project) { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/findUsages/GroovyFindUsagesProvider.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/findUsages/GroovyFindUsagesProvider.java index 0e1010e6fd4b..f29a2ed94974 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/findUsages/GroovyFindUsagesProvider.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/findUsages/GroovyFindUsagesProvider.java @@ -15,6 +15,7 @@ */ package org.jetbrains.plugins.groovy.findUsages; +import com.intellij.lang.cacheBuilder.WordsScanner; import com.intellij.lang.findUsages.FindUsagesProvider; import com.intellij.psi.*; import com.intellij.psi.util.PsiFormatUtil; @@ -35,7 +36,7 @@ public class GroovyFindUsagesProvider implements FindUsagesProvider { } @Nullable - public GroovyWordsScanner getWordsScanner() { + public WordsScanner getWordsScanner() { return new GroovyWordsScanner(); } diff --git a/plugins/hg4idea/resources/org/zmlx/hg4idea/HgVcsMessages.properties b/plugins/hg4idea/resources/org/zmlx/hg4idea/HgVcsMessages.properties index dd0c21cc4651..acd0c6cce8f3 100644 --- a/plugins/hg4idea/resources/org/zmlx/hg4idea/HgVcsMessages.properties +++ b/plugins/hg4idea/resources/org/zmlx/hg4idea/HgVcsMessages.properties @@ -1,5 +1,5 @@ group.hg4idea.global.menu.text=Mercurial -group.hg4idea.global.submenu.text=Mercurial +group.hg4idea.global.submenu.text=Mercurial Actions group.hg4idea.file.menu.text=Mercurial action.hg4idea.tag.text=Tag Repository action.hg4idea.tag.description=Create a tag for current revision @@ -21,6 +21,11 @@ hg4idea.error=Error hg4idea.revert=Revert hg4idea.commit=Commit +hg4idea.init.destination.directory.description=Select directory where the new Mercurial repository will be created. +hg4idea.init.destination.directory.title=Select directory for hg init +hg4idea.init.error.already.under.hg=The selected directory {0} is already under hg. +hg4idea.init.error.title=hg init Error + hg4idea.clone.title=Clone Mercurial Repostiroy hg4idea.clone.button.clone=Clone hg4idea.clone.button.test=&Test Repository diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/HgIdeConfigurable.java b/plugins/hg4idea/src/org/zmlx/hg4idea/HgIdeConfigurable.java index 861d0301ff36..07cc5989f4ee 100644 --- a/plugins/hg4idea/src/org/zmlx/hg4idea/HgIdeConfigurable.java +++ b/plugins/hg4idea/src/org/zmlx/hg4idea/HgIdeConfigurable.java @@ -19,7 +19,7 @@ import org.zmlx.hg4idea.ui.*; import javax.swing.*; -public class HgIdeConfigurable implements ApplicationComponent, Configurable { +public class HgIdeConfigurable implements SearchableConfigurable { private final HgConfigurationIdePanel panel; @@ -60,14 +60,11 @@ public class HgIdeConfigurable implements ApplicationComponent, Configurable { public void disposeUIResources() { } - @NotNull - public String getComponentName() { - return getClass().getName(); + public String getId() { + return "Mercurial"; } - public void initComponent() { - } - - public void disposeComponent() { + public Runnable enableSearch(String option) { + return null; } } diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/HgProjectConfigurable.java b/plugins/hg4idea/src/org/zmlx/hg4idea/HgProjectConfigurable.java index 5ccba0456b07..18197c9b130e 100644 --- a/plugins/hg4idea/src/org/zmlx/hg4idea/HgProjectConfigurable.java +++ b/plugins/hg4idea/src/org/zmlx/hg4idea/HgProjectConfigurable.java @@ -18,7 +18,7 @@ import org.zmlx.hg4idea.ui.*; import javax.swing.*; -public class HgProjectConfigurable implements Configurable { +public class HgProjectConfigurable implements SearchableConfigurable { private final HgConfigurationProjectPanel hgConfigurationProjectPanel; @@ -58,4 +58,12 @@ public class HgProjectConfigurable implements Configurable { public void disposeUIResources() { } + public String getId() { + return "Mercurial.Project"; + } + + public Runnable enableSearch(String option) { + return null; + } + } diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/HgUtil.java b/plugins/hg4idea/src/org/zmlx/hg4idea/HgUtil.java index 994c8b2c9e1a..97f4a89627e8 100644 --- a/plugins/hg4idea/src/org/zmlx/hg4idea/HgUtil.java +++ b/plugins/hg4idea/src/org/zmlx/hg4idea/HgUtil.java @@ -18,6 +18,7 @@ import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.changes.*; import com.intellij.openapi.vfs.*; import com.intellij.vcsUtil.*; +import org.jetbrains.annotations.Nullable; import java.io.*; @@ -127,6 +128,7 @@ public abstract class HgUtil { * @return The temporary copy the specified python file, with all the necessary hooks installed * to make sure it is completely removed at shutdown */ + @Nullable public static File getTemporaryPythonFile(String base) { try { final File file = copyResourceToTempFile(base, ".py"); diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/command/HgCommandService.java b/plugins/hg4idea/src/org/zmlx/hg4idea/command/HgCommandService.java index e4531f67fda7..f12e83b55470 100644 --- a/plugins/hg4idea/src/org/zmlx/hg4idea/command/HgCommandService.java +++ b/plugins/hg4idea/src/org/zmlx/hg4idea/command/HgCommandService.java @@ -29,7 +29,7 @@ import java.util.List; public final class HgCommandService { - private static final File PROMPT_HOOKS_PLUGIN = HgUtil.getTemporaryPythonFile("prompthooks"); + private static File PROMPT_HOOKS_PLUGIN; static final Logger LOG = Logger.getInstance(HgCommandService.class.getName()); @@ -43,6 +43,9 @@ public final class HgCommandService { public HgCommandService(Project project, HgGlobalSettings settings) { this.project = project; this.settings = settings; + if (PROMPT_HOOKS_PLUGIN == null) { + PROMPT_HOOKS_PLUGIN = HgUtil.getTemporaryPythonFile("prompthooks"); + } } public static HgCommandService getInstance(Project project) { diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgChangesetStatus.java b/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgChangesetStatus.java index dbef7b5d3e4f..8374a9163123 100644 --- a/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgChangesetStatus.java +++ b/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgChangesetStatus.java @@ -52,7 +52,7 @@ public class HgChangesetStatus extends JLabel implements CustomStatusBarWidget { return "HgChangeSetStatus"; } - public Presentation getPresentation(@NotNull Type type) { + public WidgetPresentation getPresentation(@NotNull Type type) { return null; } diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgConfigurationIdePanel.form b/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgConfigurationIdePanel.form index 79ffd1b867bb..4dcb91491827 100644 --- a/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgConfigurationIdePanel.form +++ b/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgConfigurationIdePanel.form @@ -34,7 +34,7 @@ - + diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgConfigurationIdePanel.java b/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgConfigurationIdePanel.java index cbad294a253f..3125be974af6 100644 --- a/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgConfigurationIdePanel.java +++ b/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgConfigurationIdePanel.java @@ -12,16 +12,13 @@ // limitations under the License. package org.zmlx.hg4idea.ui; -import com.intellij.openapi.fileChooser.*; import com.intellij.openapi.options.*; import com.intellij.openapi.ui.*; -import com.intellij.uiDesigner.core.*; import org.apache.commons.lang.*; import org.zmlx.hg4idea.*; import org.zmlx.hg4idea.command.*; import javax.swing.*; -import java.awt.*; import java.awt.event.*; public class HgConfigurationIdePanel { @@ -36,14 +33,6 @@ public class HgConfigurationIdePanel { this.globalSettings = globalSettings; loadSettings(); - String title = HgVcsMessages.message("hg4idea.configuration.title"); - String description = HgVcsMessages.message("hg4idea.configuration.description"); - - pathSelector.addBrowseFolderListener( - title, description, null, - new FileChooserDescriptor(true, false, false, false, false, false) - ); - final ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent e) { pathSelector.setEnabled(selectRadioButton.isSelected()); @@ -100,54 +89,7 @@ public class HgConfigurationIdePanel { } } - { -// GUI initializer generated by IntelliJ IDEA GUI Designer -// >>> IMPORTANT!! <<< -// DO NOT EDIT OR ADD ANY CODE HERE! - $$$setupUI$$$(); - } - - /** - * Method generated by IntelliJ IDEA GUI Designer - * >>> IMPORTANT!! <<< - * DO NOT edit this method OR call it in your code! - * - * @noinspection ALL - */ - private void $$$setupUI$$$() { - basePanel = new JPanel(); - basePanel.setLayout(new GridLayoutManager(2, 1, new Insets(0, 0, 0, 0), -1, -1)); - final JPanel panel1 = new JPanel(); - panel1.setLayout(new GridLayoutManager(2, 2, new Insets(0, 0, 0, 0), -1, -1)); - basePanel.add(panel1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); - panel1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Path to hg executable")); - autoRadioButton = new JRadioButton(); - autoRadioButton.setSelected(true); - autoRadioButton.setText("Autodetect hg in PATH"); - autoRadioButton.setMnemonic('A'); - autoRadioButton.setDisplayedMnemonicIndex(0); - panel1.add(autoRadioButton, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); - selectRadioButton = new JRadioButton(); - selectRadioButton.setEnabled(true); - selectRadioButton.setText("Specify executable path"); - selectRadioButton.setMnemonic('S'); - selectRadioButton.setDisplayedMnemonicIndex(0); - panel1.add(selectRadioButton, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); - pathSelector = new TextFieldWithBrowseButton(); - pathSelector.setEnabled(false); - panel1.add(pathSelector, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, new Dimension(100, -1), null, null, 0, false)); - final Spacer spacer1 = new Spacer(); - basePanel.add(spacer1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); - ButtonGroup buttonGroup; - buttonGroup = new ButtonGroup(); - buttonGroup.add(autoRadioButton); - buttonGroup.add(selectRadioButton); - } - - /** - * @noinspection ALL - */ - public JComponent $$$getRootComponent$$$() { - return basePanel; + private void createUIComponents() { + pathSelector = new HgSetExecutablePathPanel(); } } diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgCurrentBranchStatus.java b/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgCurrentBranchStatus.java index b7dfe76b4cf0..17bffa1dc0be 100644 --- a/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgCurrentBranchStatus.java +++ b/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgCurrentBranchStatus.java @@ -59,7 +59,7 @@ public class HgCurrentBranchStatus extends JLabel implements CustomStatusBarWidg return "HgCurrentBranchStatus"; } - public Presentation getPresentation(@NotNull Type type) { + public WidgetPresentation getPresentation(@NotNull Type type) { return null; } diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgSetExecutableDialog.form b/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgSetExecutableDialog.form index 2a0505454315..21934fd9a881 100644 --- a/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgSetExecutableDialog.form +++ b/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgSetExecutableDialog.form @@ -1,6 +1,6 @@
- + @@ -8,7 +8,7 @@ - + @@ -16,7 +16,7 @@ - + @@ -24,19 +24,9 @@ - - - - - - - - - - - + diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgSetExecutableDialog.java b/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgSetExecutableDialog.java index 6b9530eb03c5..915ed8000f75 100644 --- a/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgSetExecutableDialog.java +++ b/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgSetExecutableDialog.java @@ -12,20 +12,18 @@ // limitations under the License. package org.zmlx.hg4idea.ui; -import com.intellij.openapi.project.*; -import com.intellij.openapi.ui.*; -import com.intellij.uiDesigner.core.*; -import org.zmlx.hg4idea.*; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.ui.DialogWrapper; +import org.zmlx.hg4idea.HgVcsMessages; import javax.swing.*; -import java.awt.*; -import java.util.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; public class HgSetExecutableDialog extends DialogWrapper { - private JPanel centerPanel; - private TextFieldWithBrowseButton hgExecutablePath; - private JLabel infoLabel; - private JLabel errorLabel; + private JPanel myCenterPanel; + private HgSetExecutablePathPanel myHgExecutablePath; + private JLabel myInfoLabel; public HgSetExecutableDialog(Project project) { super(project, false); @@ -34,81 +32,24 @@ public class HgSetExecutableDialog extends DialogWrapper { @Override protected JComponent createCenterPanel() { - return centerPanel; + return myCenterPanel; } public void setBadHgPath(String hgPath) { - hgExecutablePath.setText(hgPath); - errorLabel.setText(HgVcsMessages.message("hg4idea.error.invalidExecutable", hgPath)); + myHgExecutablePath.setText(hgPath); + setErrorText(HgVcsMessages.message("hg4idea.configuration.executable.error", hgPath)); } public String getNewHgPath() { - return hgExecutablePath.getText(); + return myHgExecutablePath.getText(); } - - { -// GUI initializer generated by IntelliJ IDEA GUI Designer -// >>> IMPORTANT!! <<< -// DO NOT EDIT OR ADD ANY CODE HERE! - $$$setupUI$$$(); - } - - /** - * Method generated by IntelliJ IDEA GUI Designer - * >>> IMPORTANT!! <<< - * DO NOT edit this method OR call it in your code! - * - * @noinspection ALL - */ - private void $$$setupUI$$$() { - centerPanel = new JPanel(); - centerPanel.setLayout(new GridLayoutManager(4, 1, new Insets(0, 0, 0, 0), -1, -1)); - hgExecutablePath = new TextFieldWithBrowseButton(); - centerPanel.add(hgExecutablePath, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_NORTHWEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(400, -1), null, 0, false)); - infoLabel = new JLabel(); - infoLabel.setText("Full path to hg executable or 'hg' if PATH has it:"); - centerPanel.add(infoLabel, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); - errorLabel = new JLabel(); - errorLabel.setFont(new Font(errorLabel.getFont().getName(), Font.ITALIC, errorLabel.getFont().getSize())); - errorLabel.setForeground(Color.red); - this.$$$loadLabelText$$$(errorLabel, ResourceBundle.getBundle("org/zmlx/hg4idea/HgVcsMessages").getString("hg4idea.error.invalidExecutable")); - centerPanel.add(errorLabel, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); - final Spacer spacer1 = new Spacer(); - centerPanel.add(spacer1, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); - } - - /** - * @noinspection ALL - */ - private void $$$loadLabelText$$$(JLabel component, String text) { - StringBuffer result = new StringBuffer(); - boolean haveMnemonic = false; - char mnemonic = '\0'; - int mnemonicIndex = -1; - for (int i = 0; i < text.length(); i++) { - if (text.charAt(i) == '&') { - i++; - if (i == text.length()) break; - if (!haveMnemonic && text.charAt(i) != '&') { - haveMnemonic = true; - mnemonic = text.charAt(i); - mnemonicIndex = result.length(); - } + private void createUIComponents() { + myHgExecutablePath = new HgSetExecutablePathPanel(); + myHgExecutablePath.addOKListener(new ActionListener() { + public void actionPerformed(ActionEvent event) { + setErrorText(""); } - result.append(text.charAt(i)); - } - component.setText(result.toString()); - if (haveMnemonic) { - component.setDisplayedMnemonic(mnemonic); - component.setDisplayedMnemonicIndex(mnemonicIndex); - } - } - - /** - * @noinspection ALL - */ - public JComponent $$$getRootComponent$$$() { - return centerPanel; + }); } } diff --git a/plugins/maven/lib/lucene-core-2.3.0.jar b/plugins/maven/facade-api/lib/lucene-core-2.3.0.jar similarity index 100% rename from plugins/maven/lib/lucene-core-2.3.0.jar rename to plugins/maven/facade-api/lib/lucene-core-2.3.0.jar diff --git a/plugins/maven/facade-api/maven-facade-api.iml b/plugins/maven/facade-api/maven-facade-api.iml new file mode 100644 index 000000000000..8ba63b8dc7db --- /dev/null +++ b/plugins/maven/facade-api/maven-facade-api.iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacade.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacade.java new file mode 100644 index 000000000000..20e57f894c1d --- /dev/null +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacade.java @@ -0,0 +1,47 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.facade; + +import org.jetbrains.idea.maven.model.MavenArtifactInfo; +import org.jetbrains.idea.maven.model.MavenModel; +import org.jetbrains.idea.maven.model.MavenRepositoryInfo; + +import java.io.File; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.util.Collection; +import java.util.List; + +public interface MavenFacade extends Remote { + void setLogger(MavenFacadeLogger logger) throws RemoteException; + + MavenFacadeEmbedder createEmbedder(MavenFacadeSettings settings) throws RemoteException; + + MavenFacadeIndexer createIndexer() throws RemoteException; + + MavenModel interpolateAndAlignModel(MavenModel model, File basedir) throws RemoteException; + + MavenModel assembleInheritance(MavenModel model, MavenModel parentModel) throws RemoteException; + + ProfileApplicationResult applyProfiles(MavenModel model, + File basedir, + Collection explicitProfiles, + Collection alwaysOnProfiles) throws RemoteException; + + List getRepositories(String nexusUrl) throws RemoteException; + + List findArtifacts(MavenArtifactInfo template, String nexusUrl) throws RemoteException; +} diff --git a/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeConsole.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeConsole.java new file mode 100644 index 000000000000..84a3bafcf271 --- /dev/null +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeConsole.java @@ -0,0 +1,31 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.facade; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface MavenFacadeConsole extends Remote { + // must be same as in org.codehaus.plexus.logging.Logger + int LEVEL_DEBUG = 0; + int LEVEL_INFO = 1; + int LEVEL_WARN = 2; + int LEVEL_ERROR = 3; + int LEVEL_FATAL = 4; + int LEVEL_DISABLED = 5; + + void printMessage(int level, String message, Throwable throwable) throws RemoteException; +} diff --git a/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeEmbedder.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeEmbedder.java new file mode 100644 index 000000000000..e697ade5ee6c --- /dev/null +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeEmbedder.java @@ -0,0 +1,74 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.facade; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.idea.maven.model.*; + +import java.io.File; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public interface MavenFacadeEmbedder extends Remote { + void customizeForResolve(MavenFacadeConsole console, MavenFacadeProgressIndicator process) throws RemoteException; + + void customizeForResolve(Map projectIdToFileMap, + MavenFacadeConsole console, + MavenFacadeProgressIndicator process) throws RemoteException; + + void customizeForStrictResolve(Map projectIdToFileMap, + MavenFacadeConsole console, + MavenFacadeProgressIndicator process) throws RemoteException; + + @NotNull + MavenWrapperExecutionResult resolveProject(@NotNull File file, + @NotNull Collection activeProfiles) throws RemoteException, + MavenFacadeProcessCanceledException; + + @NotNull + MavenArtifact resolve(@NotNull MavenArtifactInfo info, + @NotNull List remoteRepositories) throws RemoteException, + MavenFacadeProcessCanceledException; + + @NotNull + List resolveTransitively(@NotNull List artifacts, + @NotNull List remoteRepositories) throws RemoteException, + MavenFacadeProcessCanceledException; + + Collection resolvePlugin(@NotNull MavenPlugin plugin, + @NotNull List repositories, + int nativeMavenProjectId, + boolean transitive) throws RemoteException, MavenFacadeProcessCanceledException; + + @NotNull + MavenWrapperExecutionResult execute(@NotNull File file, + @NotNull Collection activeProfiles, + @NotNull List goals) throws RemoteException, + MavenFacadeProcessCanceledException; + + void reset() throws RemoteException; + + void release() throws RemoteException; + + void clearCaches() throws RemoteException; + + void clearCachesFor(MavenId projectId) throws RemoteException; +} diff --git a/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeIndexer.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeIndexer.java new file mode 100644 index 000000000000..99e1511f0076 --- /dev/null +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeIndexer.java @@ -0,0 +1,59 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.facade; + +import org.apache.lucene.search.Query; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.idea.maven.model.MavenArchetype; +import org.jetbrains.idea.maven.model.MavenArtifactInfo; +import org.jetbrains.idea.maven.model.MavenId; + +import java.io.File; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.util.Collection; +import java.util.List; +import java.util.Set; + +public interface MavenFacadeIndexer extends Remote { + String SEARCH_TERM_COORDINATES = "u"; // see org.sonatype.nexus.index.ArtifactInfo + String SEARCH_TERM_CLASS_NAMES = "c"; + + int createIndex(@NotNull String indexId, + @Nullable String repositoryId, + @Nullable File file, + @Nullable String url, + @NotNull File indexDir) throws RemoteException, MavenFacadeIndexerException; + + void releaseIndex(int id) throws RemoteException, MavenFacadeIndexerException; + + int getIndexCount() throws RemoteException; + + void updateIndex(int id, MavenFacadeSettings settings, MavenFacadeProgressIndicator indicator) throws RemoteException, + MavenFacadeIndexerException, + MavenFacadeProcessCanceledException; + + List getAllArtifacts(int indexId) throws RemoteException, MavenFacadeIndexerException; + + MavenId addArtifact(int indexId, File artifactFile) throws RemoteException, MavenFacadeIndexerException; + + Set search(int indexId, Query query, int maxResult) throws RemoteException, MavenFacadeIndexerException; + + Collection getArchetypes() throws RemoteException; + + void release() throws RemoteException; +} diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/facade/remote/MavenFacadeManager.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeIndexerException.java similarity index 64% rename from plugins/maven/src/main/java/org/jetbrains/idea/maven/facade/remote/MavenFacadeManager.java rename to plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeIndexerException.java index 315333403fa7..a0cd581f5cee 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/facade/remote/MavenFacadeManager.java +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeIndexerException.java @@ -13,15 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.idea.maven.facade.remote; +package org.jetbrains.idea.maven.facade; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +public class MavenFacadeIndexerException extends Exception { + public MavenFacadeIndexerException(String message) { + super(message); + } -/** - * @author Gregory.Shrago - */ -public interface MavenFacadeManager { - MavenFacade getMavenFacade(@NotNull final Object key) throws Exception; - void releaseMavenFacade(@NotNull Object key); + public MavenFacadeIndexerException(Throwable cause) { + super(null, cause); + } } diff --git a/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeLogger.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeLogger.java new file mode 100644 index 000000000000..563492e56eed --- /dev/null +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeLogger.java @@ -0,0 +1,27 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.facade; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface MavenFacadeLogger extends Remote { + void info(Throwable e) throws RemoteException; + + void warn(Throwable e) throws RemoteException; + + void error(Throwable e) throws RemoteException; +} diff --git a/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeProcessCanceledException.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeProcessCanceledException.java new file mode 100644 index 000000000000..f0d0d4a68dcb --- /dev/null +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeProcessCanceledException.java @@ -0,0 +1,21 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.facade; + +import java.rmi.RemoteException; + +public class MavenFacadeProcessCanceledException extends Exception { +} diff --git a/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeProgressIndicator.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeProgressIndicator.java new file mode 100644 index 000000000000..48a400df6922 --- /dev/null +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeProgressIndicator.java @@ -0,0 +1,30 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.facade; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface MavenFacadeProgressIndicator extends Remote { + void setText(String text) throws RemoteException; + void setText2(String text) throws RemoteException; + + boolean isCanceled() throws RemoteException; + + void setIndeterminate(boolean value) throws RemoteException; + + void setFraction(double fraction) throws RemoteException; +} diff --git a/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeSettings.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeSettings.java new file mode 100644 index 000000000000..0253ede5222c --- /dev/null +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeSettings.java @@ -0,0 +1,107 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.facade; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.io.File; +import java.io.Serializable; + +public class MavenFacadeSettings implements Serializable { + public enum UpdatePolicy { + ALWAYS_UPDATE, DO_NOT_UPDATE + } + + private int myLoggingLevel; + @Nullable private File myMavenHome; + @Nullable private File myUserSettingsFile; + @Nullable private File myGlobalSettingsFile; + @Nullable private File myLocalRepository; + private boolean isOffline; + @NotNull private UpdatePolicy myPluginUpdatePolicy = UpdatePolicy.DO_NOT_UPDATE; + @NotNull private UpdatePolicy mySnapshotUpdatePolicy = UpdatePolicy.ALWAYS_UPDATE; + + public int getLoggingLevel() { + return myLoggingLevel; + } + + public void setLoggingLevel(int loggingLevel) { + myLoggingLevel = loggingLevel; + } + + @Nullable + public File getMavenHome() { + return myMavenHome; + } + + public void setMavenHome(@Nullable File mavenHome) { + myMavenHome = mavenHome; + } + + @Nullable + public File getUserSettingsFile() { + return myUserSettingsFile; + } + + public void setUserSettingsFile(@Nullable File userSettingsFile) { + myUserSettingsFile = userSettingsFile; + } + + @Nullable + public File getGlobalSettingsFile() { + return myGlobalSettingsFile; + } + + public void setGlobalSettingsFile(@Nullable File globalSettingsFile) { + myGlobalSettingsFile = globalSettingsFile; + } + + @Nullable + public File getLocalRepository() { + return myLocalRepository; + } + + public void setLocalRepository(@Nullable File localRepository) { + myLocalRepository = localRepository; + } + + public boolean isOffline() { + return isOffline; + } + + public void setOffline(boolean offline) { + isOffline = offline; + } + + @NotNull + public UpdatePolicy getPluginUpdatePolicy() { + return myPluginUpdatePolicy; + } + + public void setPluginUpdatePolicy(@NotNull UpdatePolicy pluginUpdatePolicy) { + myPluginUpdatePolicy = pluginUpdatePolicy; + } + + @NotNull + public UpdatePolicy getSnapshotUpdatePolicy() { + return mySnapshotUpdatePolicy; + } + + public void setSnapshotUpdatePolicy(@NotNull UpdatePolicy snapshotUpdatePolicy) { + mySnapshotUpdatePolicy = snapshotUpdatePolicy; + } +} diff --git a/plugins/maven/facade/org/jetbrains/idea/maven/facade/remote/RemoteTransferListener.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeTransferListener.java similarity index 96% rename from plugins/maven/facade/org/jetbrains/idea/maven/facade/remote/RemoteTransferListener.java rename to plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeTransferListener.java index 172c7a051476..42288d17f156 100644 --- a/plugins/maven/facade/org/jetbrains/idea/maven/facade/remote/RemoteTransferListener.java +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeTransferListener.java @@ -1,4 +1,4 @@ -package org.jetbrains.idea.maven.facade.remote; +package org.jetbrains.idea.maven.facade; import java.io.File; import java.io.Serializable; @@ -8,7 +8,7 @@ import java.rmi.RemoteException; /** * @author Gregory.Shrago */ -public interface RemoteTransferListener extends Remote { +public interface MavenFacadeTransferListener extends Remote { void transferInitiated(TransferEvent transferEvent) throws RemoteException; void transferStarted(TransferEvent transferEvent) throws RemoteException; @@ -21,9 +21,7 @@ public interface RemoteTransferListener extends Remote { void debug(String s) throws RemoteException; - class TransferEvent implements Serializable { - public enum EventType { INITIATED, STARTED, COMPLETED, PROGRESS, ERROR } public enum RequestType { PUT, GET } @@ -74,7 +72,6 @@ public interface RemoteTransferListener extends Remote { } class Resource implements Serializable { - private final String myResourceName; private final long myResourceLastModified; private final long myResourceContentLength; diff --git a/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeUtil.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeUtil.java new file mode 100644 index 000000000000..77964fbfb34d --- /dev/null +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenFacadeUtil.java @@ -0,0 +1,64 @@ +/* + * Copyright 2000-2009 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.facade; + +import java.util.HashSet; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +public class MavenFacadeUtil { + private static volatile Properties mySystemPropertiesCache; + + public static Properties collectSystemProperties() { + if (mySystemPropertiesCache == null) { + Properties result = new Properties(); + result.putAll(getSystemProperties()); + + Properties envVars = getEnvProperties(); + for (Map.Entry each : envVars.entrySet()) { + result.setProperty("env." + each.getKey().toString(), each.getValue().toString()); + } + mySystemPropertiesCache = result; + } + + return mySystemPropertiesCache; + } + + @SuppressWarnings({"unchecked"}) + private static Properties getSystemProperties() { + Properties result = (Properties)System.getProperties().clone(); + for (String each : new HashSet((Set)result.keySet())) { + if (each.startsWith("idea.")) { + result.remove(each); + } + } + return result; + } + + private static Properties getEnvProperties() { + Properties result = new Properties(); + for (Map.Entry each : System.getenv().entrySet()) { + if (isMagicalProperty(each.getKey())) continue; + result.put(each.getKey(), each.getValue()); + } + return result; + } + + private static boolean isMagicalProperty(String key) { + return key.startsWith("="); + } +} \ No newline at end of file diff --git a/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenWrapperExecutionResult.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenWrapperExecutionResult.java new file mode 100644 index 000000000000..c382aa546dc5 --- /dev/null +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/MavenWrapperExecutionResult.java @@ -0,0 +1,59 @@ +/* + * Copyright 2000-2009 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.facade; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.idea.maven.model.MavenId; +import org.jetbrains.idea.maven.model.MavenModel; +import org.jetbrains.idea.maven.model.MavenProfile; +import org.jetbrains.idea.maven.model.MavenProjectProblem; + +import java.io.Serializable; +import java.util.Collection; +import java.util.Map; +import java.util.Set; + +public class MavenWrapperExecutionResult implements Serializable { + @Nullable public final ProjectData projectData; + @NotNull public final Collection problems; + @NotNull public final Set unresolvedArtifacts; + + public MavenWrapperExecutionResult(ProjectData projectData, + Collection problems, + Set unresolvedArtifacts) { + this.projectData = projectData; + this.problems = problems; + this.unresolvedArtifacts = unresolvedArtifacts; + } + + public static class ProjectData implements Serializable { + public final MavenModel mavenModel; + public final Map mavenModelMap; + public final NativeMavenProjectHolder nativeMavenProject; + public final Collection activatedProfiles; + + public ProjectData(MavenModel mavenModel, + Map mavenModelMap, + NativeMavenProjectHolder nativeMavenProject, + Collection activatedProfiles) { + this.mavenModel = mavenModel; + this.mavenModelMap = mavenModelMap; + this.nativeMavenProject = nativeMavenProject; + this.activatedProfiles = activatedProfiles; + } + } +} diff --git a/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/NativeMavenProjectHolder.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/NativeMavenProjectHolder.java new file mode 100644 index 000000000000..8569f96507a6 --- /dev/null +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/NativeMavenProjectHolder.java @@ -0,0 +1,8 @@ +package org.jetbrains.idea.maven.facade; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface NativeMavenProjectHolder extends Remote { + int getId() throws RemoteException; +} diff --git a/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/ProfileApplicationResult.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/ProfileApplicationResult.java new file mode 100644 index 000000000000..8297c26cebba --- /dev/null +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/ProfileApplicationResult.java @@ -0,0 +1,40 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.facade; + +import org.jetbrains.idea.maven.model.MavenModel; +import org.jetbrains.idea.maven.model.MavenProfile; + +import java.io.Serializable; +import java.util.List; + +public class ProfileApplicationResult implements Serializable { + private final MavenModel myModel; + private final List myActivatedProfiles; + + public ProfileApplicationResult(MavenModel model, List activatedProfiles) { + myModel = model; + myActivatedProfiles = activatedProfiles; + } + + public MavenModel getModel() { + return myModel; + } + + public List getActivatedProfiles() { + return myActivatedProfiles; + } +} diff --git a/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/RemoteObject.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/RemoteObject.java new file mode 100644 index 000000000000..753532d18cfa --- /dev/null +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/facade/RemoteObject.java @@ -0,0 +1,88 @@ +package org.jetbrains.idea.maven.facade; + +import com.intellij.util.containers.ContainerUtil; + +import java.lang.ref.WeakReference; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.rmi.server.UnicastRemoteObject; +import java.rmi.server.Unreferenced; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public abstract class RemoteObject implements Remote, Unreferenced { + private final Map myChildren = new ConcurrentHashMap(); + private final WeakReference myWeakRef; + private RemoteObject myParent; + + public RemoteObject() { + myWeakRef = new WeakReference(this); + } + + public WeakReference getWeakRef() { + return myWeakRef; + } + + protected T export(final T child) throws RemoteException { + if (child == null) return null; + final T result = (T)UnicastRemoteObject.exportObject(child, 0); + myChildren.put((RemoteObject)child, result); + ((RemoteObject)child).myParent = this; + return result; + } + + public void unexportChildren() throws RemoteException { + final ArrayList childrenRefs = new ArrayList(myChildren.keySet()); + myChildren.clear(); + for (RemoteObject child : childrenRefs) { + child.unreferenced(); + } + } + + protected void unexportChildren(Collection> children) throws RemoteException { + if (children.isEmpty()) return; + final ArrayList list = new ArrayList(children.size()); + for (WeakReference child : children) { + ContainerUtil.addIfNotNull(child.get(), list); + } + myChildren.keySet().removeAll(list); + for (RemoteObject child : list) { + child.unreferenced(); + } + } + + public static Throwable wrapException(Throwable ex) { + boolean foreignException = false; + Throwable each = ex; + while(each != null) { + String name = each.getClass().getName(); + if (!name.startsWith("java") && !name.startsWith(RemoteObject.class.getPackage().getName())) { + foreignException = true; + break; + } + each = each.getCause(); + } + + if (foreignException) { + Throwable wrapper = new Throwable(ex.toString()); + wrapper.setStackTrace(ex.getStackTrace()); + ex = wrapper; + } + return ex; + } + + public void unreferenced() { + if (myParent != null) { + myParent.myChildren.remove(this); + myParent = null; + try { + unexportChildren(); + UnicastRemoteObject.unexportObject(this, false); + } + catch (RemoteException e) { + } + } + } +} diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/ArchetypeInfo.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenArchetype.java similarity index 82% rename from plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/ArchetypeInfo.java rename to plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenArchetype.java index 1cde3f65f138..25736abe5ce5 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/ArchetypeInfo.java +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenArchetype.java @@ -13,29 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.idea.maven.indices; +package org.jetbrains.idea.maven.model; import com.intellij.openapi.util.text.StringUtil; -import org.apache.maven.archetype.catalog.Archetype; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -public class ArchetypeInfo { +import java.io.Serializable; + +public class MavenArchetype implements Serializable { public final String groupId; public final String artifactId; public final String version; public final String repository; public final String description; - public ArchetypeInfo(Archetype archetype) { - this(archetype.getGroupId(), - archetype.getArtifactId(), - archetype.getVersion(), - archetype.getRepository(), - archetype.getDescription()); - } - - public ArchetypeInfo(@NotNull String groupId, + public MavenArchetype(@NotNull String groupId, @NotNull String artifactId, @NotNull String version, @Nullable String repository, @@ -52,7 +45,7 @@ public class ArchetypeInfo { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; - ArchetypeInfo that = (ArchetypeInfo)o; + MavenArchetype that = (MavenArchetype)o; if (groupId != null ? !groupId.equals(that.groupId) : that.groupId != null) return false; if (artifactId != null ? !artifactId.equals(that.artifactId) : that.artifactId != null) return false; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenArtifact.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenArtifact.java similarity index 64% rename from plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenArtifact.java rename to plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenArtifact.java index de4329cb7ca6..a24d163340ed 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenArtifact.java +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenArtifact.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2010 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,93 +14,59 @@ * limitations under the License. */ -package org.jetbrains.idea.maven.project; +package org.jetbrains.idea.maven.model; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.JarFileSystem; -import com.intellij.openapi.vfs.VirtualFileManager; -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.handler.ArtifactHandler; -import org.codehaus.plexus.component.repository.ComponentDependency; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.idea.maven.embedder.CustomArtifact; -import org.jetbrains.idea.maven.utils.MavenConstants; import java.io.File; import java.io.Serializable; import java.text.MessageFormat; -import static org.jetbrains.idea.maven.project.MavenId.append; - public class MavenArtifact implements Serializable { - private String myGroupId; - private String myArtifactId; - private String myVersion; - private String myBaseVersion; - private String myType; - private String myClassifier; + private final String myGroupId; + private final String myArtifactId; + private final String myVersion; + private final String myBaseVersion; + private final String myType; + private final String myClassifier; private String myScope; - private boolean myOptional; + private final boolean myOptional; - private String myExtension; + private final String myExtension; - private File myFile; - private boolean myResolved; - private boolean myStubbed; - - protected MavenArtifact() { - } - - public MavenArtifact(Artifact artifact, File localRepository) { - myGroupId = artifact.getGroupId(); - myArtifactId = artifact.getArtifactId(); - myVersion = artifact.getVersion(); - myBaseVersion = artifact.getBaseVersion(); - myType = artifact.getType(); - myClassifier = artifact.getClassifier(); - - myScope = artifact.getScope(); - myOptional = artifact.isOptional(); - - myExtension = getExtension(artifact); - - myFile = artifact.getFile(); - if (myFile == null) { - myFile = new File(localRepository, getRelativePath()); - } - - myResolved = artifact.isResolved(); - myStubbed = artifact instanceof CustomArtifact && ((CustomArtifact)artifact).isStub(); - } - - public MavenArtifact(ComponentDependency dependency, File localRepository, String scope) { - myGroupId = dependency.getGroupId(); - myArtifactId = dependency.getArtifactId(); - myVersion = dependency.getVersion(); - myBaseVersion = null; - myType = dependency.getType(); - myClassifier = null; + private final File myFile; + private final boolean myResolved; + private final boolean myStubbed; + public MavenArtifact(String groupId, + String artifactId, + String version, + String baseVersion, + String type, + String classifier, + String scope, + boolean optional, + String extension, + @Nullable File file, + File localRepository, + boolean resolved, + boolean stubbed) { + myGroupId = groupId; + myArtifactId = artifactId; + myVersion = version; + myBaseVersion = baseVersion; + myType = type; + myClassifier = classifier; myScope = scope; - myOptional = false; - - myExtension = myType; - - myFile = new File(localRepository, getRelativePath()); - - myResolved = true; - myStubbed = false; - } - - private String getExtension(Artifact artifact) { - ArtifactHandler handler = artifact.getArtifactHandler(); - String result = null; - if (handler != null) result = handler.getExtension(); - if (result == null) result = artifact.getType(); - return result; + myOptional = optional; + myExtension = extension; + myFile = file != null ? file : new File(localRepository, getRelativePath()); + myResolved = resolved; + myStubbed = stubbed; } public String getGroupId() { @@ -141,7 +107,7 @@ public class MavenArtifact implements Serializable { public boolean isExportable() { if (myOptional) return false; - return Artifact.SCOPE_COMPILE.equals(myScope) || Artifact.SCOPE_RUNTIME.equals(myScope); + return MavenConstants.SCOPE_COMPILE.equals(myScope) || MavenConstants.SCOPE_RUNTIME.equals(myScope); } public String getExtension() { @@ -195,11 +161,7 @@ public class MavenArtifact implements Serializable { return result.toString(); } - public String getUrl() { - return getUrlForExtraArtifact(null, null); - } - - public String getUrlForExtraArtifact(@Nullable String extraArtifactClassifier, @Nullable String customExtension) { + public String getPathForExtraArtifact(@Nullable String extraArtifactClassifier, @Nullable String customExtension) { String path = getPath(); if (!StringUtil.isEmptyOrSpaces(extraArtifactClassifier)) { @@ -221,15 +183,15 @@ public class MavenArtifact implements Serializable { path = repoPath + getRelativePathForExtraArtifact(extraArtifactClassifier, customExtension); } } - return VirtualFileManager.constructUrl(JarFileSystem.PROTOCOL, path) + JarFileSystem.JAR_SEPARATOR; + return path; } public String getDisplayStringSimple() { StringBuilder builder = new StringBuilder(); - append(builder, myGroupId); - append(builder, myArtifactId); - append(builder, myVersion); + MavenId.append(builder, myGroupId); + MavenId.append(builder, myArtifactId); + MavenId.append(builder, myVersion); return builder.toString(); } @@ -237,10 +199,10 @@ public class MavenArtifact implements Serializable { public String getDisplayStringWithType() { StringBuilder builder = new StringBuilder(); - append(builder, myGroupId); - append(builder, myArtifactId); - append(builder, myType); - append(builder, myVersion); + MavenId.append(builder, myGroupId); + MavenId.append(builder, myArtifactId); + MavenId.append(builder, myType); + MavenId.append(builder, myVersion); return builder.toString(); } @@ -248,11 +210,11 @@ public class MavenArtifact implements Serializable { public String getDisplayStringWithTypeAndClassifier() { StringBuilder builder = new StringBuilder(); - append(builder, myGroupId); - append(builder, myArtifactId); - append(builder, myType); - if (!StringUtil.isEmptyOrSpaces(myClassifier)) append(builder, myClassifier); - append(builder, myVersion); + MavenId.append(builder, myGroupId); + MavenId.append(builder, myArtifactId); + MavenId.append(builder, myType); + if (!StringUtil.isEmptyOrSpaces(myClassifier)) MavenId.append(builder, myClassifier); + MavenId.append(builder, myVersion); return builder.toString(); } @@ -260,12 +222,12 @@ public class MavenArtifact implements Serializable { public String getDisplayStringFull() { StringBuilder builder = new StringBuilder(); - append(builder, myGroupId); - append(builder, myArtifactId); - append(builder, myType); - if (!StringUtil.isEmptyOrSpaces(myClassifier)) append(builder, myClassifier); - append(builder, myVersion); - if (!StringUtil.isEmptyOrSpaces(myScope)) append(builder, myScope); + MavenId.append(builder, myGroupId); + MavenId.append(builder, myArtifactId); + MavenId.append(builder, myType); + if (!StringUtil.isEmptyOrSpaces(myClassifier)) MavenId.append(builder, myClassifier); + MavenId.append(builder, myVersion); + if (!StringUtil.isEmptyOrSpaces(myScope)) MavenId.append(builder, myScope); return builder.toString(); } @@ -273,14 +235,14 @@ public class MavenArtifact implements Serializable { public String getDisplayStringForLibraryName() { StringBuilder builder = new StringBuilder(); - append(builder, myGroupId); - append(builder, myArtifactId); + MavenId.append(builder, myGroupId); + MavenId.append(builder, myArtifactId); - if (!StringUtil.isEmptyOrSpaces(myType) && !MavenConstants.TYPE_JAR.equals(myType)) append(builder, myType); - if (!StringUtil.isEmptyOrSpaces(myClassifier)) append(builder, myClassifier); + if (!StringUtil.isEmptyOrSpaces(myType) && !MavenConstants.TYPE_JAR.equals(myType)) MavenId.append(builder, myType); + if (!StringUtil.isEmptyOrSpaces(myClassifier)) MavenId.append(builder, myClassifier); String version = !StringUtil.isEmptyOrSpaces(myBaseVersion) ? myBaseVersion : myVersion; - if (!StringUtil.isEmptyOrSpaces(version)) append(builder, version); + if (!StringUtil.isEmptyOrSpaces(version)) MavenId.append(builder, version); return builder.toString(); } diff --git a/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenArtifactInfo.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenArtifactInfo.java new file mode 100644 index 000000000000..04a025867119 --- /dev/null +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenArtifactInfo.java @@ -0,0 +1,86 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.model; + +import java.io.Serializable; + +public class MavenArtifactInfo implements Serializable { + private final String myGroupId; + private final String myArtifactId; + private final String myVersion; + private final String myPackaging; + private final String myClassifier; + private final String myClassNames; + private final String myRepositoryId; + + public MavenArtifactInfo(MavenId id, + String packaging, + String classifier) { + this(id.getGroupId(), id.getArtifactId(), id.getVersion(), packaging, classifier); + } + + public MavenArtifactInfo(String groupId, + String artifactId, + String version, + String packaging, + String classifier) { + this(groupId, artifactId, version, packaging, classifier, null, null); + } + + public MavenArtifactInfo(String groupId, + String artifactId, + String version, + String packaging, + String classifier, + String classNames, + String repositoryId) { + myGroupId = groupId; + myArtifactId = artifactId; + myVersion = version; + myPackaging = packaging; + myClassifier = classifier; + myClassNames = classNames; + myRepositoryId = repositoryId; + } + + public String getGroupId() { + return myGroupId; + } + + public String getArtifactId() { + return myArtifactId; + } + + public String getVersion() { + return myVersion; + } + + public String getPackaging() { + return myPackaging; + } + + public String getClassifier() { + return myClassifier; + } + + public String getClassNames() { + return myClassNames; + } + + public String getRepositoryId() { + return myRepositoryId; + } +} diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenArtifactNode.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenArtifactNode.java similarity index 82% rename from plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenArtifactNode.java rename to plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenArtifactNode.java index 27760ef3cf97..e7f87d623f69 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenArtifactNode.java +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenArtifactNode.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2010 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.idea.maven.project; +package org.jetbrains.idea.maven.model; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.Function; @@ -23,23 +23,19 @@ import java.io.Serializable; import java.util.List; public class MavenArtifactNode implements Serializable { + private final MavenArtifactNode myParent; - private MavenArtifactNode myParent; + private final MavenArtifact myArtifact; + private final MavenArtifactState myState; + private final MavenArtifact myRelatedArtifact; - private MavenArtifact myArtifact; - private MavenArtifactState myState; - private MavenArtifact myRelatedArtifact; + private final String myOriginalScope; - private String myOriginalScope; - - private String myPremanagedVersion; - private String myPremanagedScope; + private final String myPremanagedVersion; + private final String myPremanagedScope; private List myDependencies; - protected MavenArtifactNode() { - } - public MavenArtifactNode(MavenArtifactNode parent, MavenArtifact artifact, MavenArtifactState state, @@ -62,7 +58,6 @@ public class MavenArtifactNode implements Serializable { } - public MavenArtifact getArtifact() { return myArtifact; } @@ -101,8 +96,10 @@ public class MavenArtifactNode implements Serializable { @Override public String toString() { - String result =myArtifact.getDisplayStringWithTypeAndClassifier(); - if (myState != MavenArtifactState.ADDED) result += "[" + myState + ":" + myRelatedArtifact.getDisplayStringWithTypeAndClassifier() + "]"; + String result = myArtifact.getDisplayStringWithTypeAndClassifier(); + if (myState != MavenArtifactState.ADDED) { + result += "[" + myState + ":" + myRelatedArtifact.getDisplayStringWithTypeAndClassifier() + "]"; + } return result += "->(" + formatNodesList(myDependencies) + ")"; } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenArtifactState.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenArtifactState.java similarity index 94% rename from plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenArtifactState.java rename to plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenArtifactState.java index aabf184d7000..6f519c809895 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenArtifactState.java +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenArtifactState.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.idea.maven.project; +package org.jetbrains.idea.maven.model; /** * @author Konstantin Bulenkov diff --git a/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenBuild.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenBuild.java new file mode 100644 index 000000000000..e3143b3524f2 --- /dev/null +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenBuild.java @@ -0,0 +1,72 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.model; + +import com.intellij.util.SmartList; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class MavenBuild extends MavenBuildBase implements Serializable { + private String myOutputDirectory; + private String myTestOutputDirectory; + private List mySources; + private List myTestSources; + + public String getOutputDirectory() { + return myOutputDirectory; + } + + public void setOutputDirectory(String outputDirectory) { + myOutputDirectory = outputDirectory; + } + + public String getTestOutputDirectory() { + return myTestOutputDirectory; + } + + public void setTestOutputDirectory(String testOutputDirectory) { + myTestOutputDirectory = testOutputDirectory; + } + + public List getSources() { + return mySources == null ? Collections.emptyList() : mySources; + } + + public void setSources(List sources) { + mySources = new ArrayList(sources); + } + + public void addSource(String source) { + if (mySources == null) mySources = new ArrayList(); + mySources.add(source); + } + + public List getTestSources() { + return myTestSources == null ? Collections.emptyList() : myTestSources; + } + + public void setTestSources(List testSources) { + myTestSources = new ArrayList(testSources); + } + + public void addTestSource(String source) { + if (myTestSources == null) myTestSources = new ArrayList(); + myTestSources.add(source); + } +} \ No newline at end of file diff --git a/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenBuildBase.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenBuildBase.java new file mode 100644 index 000000000000..c4bf944a947c --- /dev/null +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenBuildBase.java @@ -0,0 +1,77 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.model; + +import java.io.Serializable; +import java.util.Collections; +import java.util.List; + +public class MavenBuildBase implements Serializable { + private String myFinalName; + private String myDefaultGoal; + private String myDirectory; + private List myResources; + private List myTestResources; + private List myFilters; + + public String getFinalName() { + return myFinalName; + } + + public void setFinalName(String finalName) { + myFinalName = finalName; + } + + public String getDefaultGoal() { + return myDefaultGoal; + } + + public void setDefaultGoal(String defaultGoal) { + myDefaultGoal = defaultGoal; + } + + public String getDirectory() { + return myDirectory; + } + + public void setDirectory(String directory) { + myDirectory = directory; + } + + public List getResources() { + return myResources == null ? Collections.emptyList() : myResources; + } + + public void setResources(List resources) { + myResources = resources; + } + + public List getTestResources() { + return myTestResources == null ? Collections.emptyList() : myTestResources; + } + + public void setTestResources(List testResources) { + myTestResources = testResources; + } + + public List getFilters() { + return myFilters == null ? Collections.emptyList() : myFilters; + } + + public void setFilters(List filters) { + myFilters = filters; + } +} \ No newline at end of file diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenConstants.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenConstants.java similarity index 58% rename from plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenConstants.java rename to plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenConstants.java index ec46dd7be7af..74e29dd5c1c4 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenConstants.java +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenConstants.java @@ -13,7 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.idea.maven.utils; +package org.jetbrains.idea.maven.model; + +import java.util.Arrays; +import java.util.List; public class MavenConstants { public static final String POM_EXTENSION = "pom"; @@ -22,6 +25,10 @@ public class MavenConstants { public static final String PROFILES_XML = "profiles.xml"; public static final String SETTINGS_XML = "settings.xml"; + public static final String PROFILE_FROM_POM = "pom"; + public static final String PROFILE_FROM_PROFILES_XML = "profiles.xml"; + public static final String PROFILE_FROM_SETTINGS_XML = "settings.xml"; + public static final String TYPE_POM = "pom"; public static final String TYPE_JAR = "jar"; public static final String TYPE_TEST_JAR = "test-jar"; @@ -33,4 +40,16 @@ public class MavenConstants { public static final String SCOPE_TEST = "test"; public static final String SCOPE_SYSTEM = "system"; public static final String SCOPE_IMPORT = "import"; + + public static final List PHASES = + Arrays.asList("clean", "validate", "generate-sources", "process-sources", "generate-resources", + "process-resources", "compile", "process-classes", "generate-test-sources", "process-test-sources", + "generate-test-resources", + "process-test-resources", "test-compile", "test", "prepare-package", "package", "pre-integration-test", + "integration-test", + "post-integration-test", + "verify", "install", "site", "deploy"); + public static final List BASIC_PHASES = + Arrays.asList("clean", "validate", "compile", "test", "package", "install", "deploy", "site"); + } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenId.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenId.java similarity index 84% rename from plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenId.java rename to plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenId.java index cb38c558d66f..7b354ceb9f48 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenId.java +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenId.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2010 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,10 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.idea.maven.project; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.model.Model; +package org.jetbrains.idea.maven.model; import java.io.Serializable; @@ -28,17 +25,9 @@ public class MavenId implements Serializable { private final String myVersion; public MavenId(String groupId, String artifactId, String version) { - this.myGroupId = groupId; - this.myArtifactId = artifactId; - this.myVersion = version; - } - - public MavenId(Model model) { - this(model.getGroupId(), model.getArtifactId(), model.getVersion()); - } - - public MavenId(Artifact artifact) { - this(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()); + myGroupId = groupId; + myArtifactId = artifactId; + myVersion = version; } public String getGroupId() { diff --git a/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenModel.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenModel.java new file mode 100644 index 000000000000..3eb8aa7d20d7 --- /dev/null +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenModel.java @@ -0,0 +1,73 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.model; + +import java.util.List; + +public class MavenModel extends MavenModelBase { + private MavenId myMavenId; + private MavenParent myParent; + private String myPackaging; + private String myName; + + private List myProfiles; + + private final MavenBuild myBuild = new MavenBuild(); + + public MavenId getMavenId() { + return myMavenId; + } + + public void setMavenId(MavenId mavenId) { + myMavenId = mavenId; + } + + public MavenParent getParent() { + return myParent; + } + + public void setParent(MavenParent parent) { + myParent = parent; + } + + public String getPackaging() { + return myPackaging; + } + + public void setPackaging(String packaging) { + myPackaging = packaging; + } + + public String getName() { + return myName; + } + + public void setName(String name) { + myName = name; + } + + public List getProfiles() { + return myProfiles; + } + + public void setProfiles(List profiles) { + myProfiles = profiles; + } + + public MavenBuild getBuild() { + return myBuild; + } +} diff --git a/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenModelBase.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenModelBase.java new file mode 100644 index 000000000000..6296b2971bf5 --- /dev/null +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenModelBase.java @@ -0,0 +1,88 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.model; + +import java.io.Serializable; +import java.util.List; +import java.util.Properties; + +public class MavenModelBase implements Serializable { + private Properties myProperties; + private List myPlugins; + private List myExtensions; + private List myDependencies; + private List myDependencyTree; + private List myRemoteRepositories; + + private List myModules; + + public Properties getProperties() { + if (myProperties == null) myProperties = new Properties(); + return myProperties; + } + + public void setProperties(Properties properties) { + myProperties = properties; + } + + public List getPlugins() { + return myPlugins; + } + + public void setPlugins(List plugins) { + myPlugins = plugins; + } + + public List getExtensions() { + return myExtensions; + } + + public void setExtensions(List extensions) { + myExtensions = extensions; + } + + public List getDependencies() { + return myDependencies; + } + + public void setDependencies(List dependencies) { + myDependencies = dependencies; + } + + public List getDependencyTree() { + return myDependencyTree; + } + + public void setDependencyTree(List dependencyTree) { + myDependencyTree = dependencyTree; + } + + public List getRemoteRepositories() { + return myRemoteRepositories; + } + + public void setRemoteRepositories(List remoteRepositories) { + myRemoteRepositories = remoteRepositories; + } + + public List getModules() { + return myModules; + } + + public void setModules(List modules) { + myModules = modules; + } +} diff --git a/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenParent.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenParent.java new file mode 100644 index 000000000000..b75d61e209f4 --- /dev/null +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenParent.java @@ -0,0 +1,36 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.model; + +import java.io.Serializable; + +public class MavenParent implements Serializable { + private final MavenId myMavenId; + private final String myRelativePath; + + public MavenParent(MavenId id, String relativePath) { + myMavenId = id; + myRelativePath = relativePath; + } + + public MavenId getMavenId() { + return myMavenId; + } + + public String getRelativePath() { + return myRelativePath; + } +} diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenPlugin.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenPlugin.java similarity index 63% rename from plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenPlugin.java rename to plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenPlugin.java index 3f9245830bac..9f6c8efb1e84 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenPlugin.java +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenPlugin.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2010 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,80 +14,43 @@ * limitations under the License. */ -package org.jetbrains.idea.maven.project; +package org.jetbrains.idea.maven.model; import com.intellij.openapi.util.JDOMUtil; -import com.intellij.xml.util.XmlUtil; -import org.apache.maven.model.Dependency; -import org.apache.maven.model.Plugin; -import org.apache.maven.model.PluginExecution; -import org.codehaus.plexus.util.xml.Xpp3Dom; import org.jdom.Element; -import org.jdom.IllegalNameException; import org.jetbrains.annotations.Nullable; -import org.jetbrains.idea.maven.utils.MavenLog; import java.io.Serializable; -import java.util.ArrayList; import java.util.List; -import static org.jetbrains.idea.maven.project.MavenId.append; +import static org.jetbrains.idea.maven.model.MavenId.append; public class MavenPlugin implements Serializable { - private String myGroupId; - private String myArtifactId; - private String myVersion; + private final String myGroupId; + private final String myArtifactId; + private final String myVersion; - private boolean myDefault; + private final boolean myDefault; - private Element myConfiguration; - private final List myExecutions = new ArrayList(); + private final Element myConfiguration; + private final List myExecutions; - private final List myDependencies = new ArrayList(); + private final List myDependencies; - protected MavenPlugin() { - } - - public MavenPlugin(Plugin plugin, boolean isDefault) { - myGroupId = plugin.getGroupId(); - myArtifactId = plugin.getArtifactId(); - myVersion = plugin.getVersion(); - - myDefault = isDefault; - - Xpp3Dom config = (Xpp3Dom)plugin.getConfiguration(); - myConfiguration = config == null ? null : xppToElement(config); - - for (PluginExecution each : plugin.getExecutions()) { - myExecutions.add(new Execution(each)); - } - - for (Dependency each : plugin.getDependencies()) { - myDependencies.add(new MavenId(each.getGroupId(), each.getArtifactId(), each.getVersion())); - } - } - - private static Element xppToElement(Xpp3Dom xpp) { - Element result = null; - try { - result = new Element(xpp.getName()); - } - catch (IllegalNameException e) { - MavenLog.LOG.warn("Cannot convert plugin configuration: " + xpp, e); - return null; - } - - Xpp3Dom[] children = xpp.getChildren(); - if (children == null || children.length == 0) { - result.setText(xpp.getValue()); - } - else { - for (Xpp3Dom each : children) { - Element child = xppToElement(each); - if (child != null) result.addContent(child); - } - } - return result; + public MavenPlugin(String groupId, + String artifactId, + String version, + boolean aDefault, + Element configuration, + List executions, + List dependencies) { + myGroupId = groupId; + myArtifactId = artifactId; + myVersion = version; + myDefault = aDefault; + myConfiguration = configuration; + myExecutions = executions; + myDependencies = dependencies; } public String getGroupId() { @@ -169,17 +132,12 @@ public class MavenPlugin implements Serializable { } public static class Execution implements Serializable { - private List myGoals; - private Element myConfiguration; + private final List myGoals; + private final Element myConfiguration; - public Execution() { - } - - public Execution(PluginExecution execution) { - myGoals = execution.getGoals(); - - Xpp3Dom config = (Xpp3Dom)execution.getConfiguration(); - myConfiguration = config == null ? null : xppToElement(config); + public Execution(List goals, Element configuration) { + myGoals = goals; + myConfiguration = configuration; } public List getGoals() { diff --git a/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenProfile.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenProfile.java new file mode 100644 index 000000000000..d4e08bf3cd61 --- /dev/null +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenProfile.java @@ -0,0 +1,54 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.model; + +import org.jetbrains.annotations.NotNull; + +import java.io.Serializable; +import java.util.List; + +public class MavenProfile extends MavenModelBase implements Serializable { + private final String myId; + private final String mySource; + private MavenProfileActivation myActivation; + private final MavenBuildBase myBuild = new MavenBuildBase(); + + public MavenProfile(String id, String source) { + myId = id; + mySource = source; + } + + @NotNull + public String getId() { + return myId; + } + + public String getSource() { + return mySource; + } + + public void setActivation(MavenProfileActivation activation) { + myActivation = activation; + } + + public MavenProfileActivation getActivation() { + return myActivation; + } + + public MavenBuildBase getBuild() { + return myBuild; + } +} diff --git a/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenProfileActivation.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenProfileActivation.java new file mode 100644 index 000000000000..3643f3f20f86 --- /dev/null +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenProfileActivation.java @@ -0,0 +1,66 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.model; + +import java.io.Serializable; + +public class MavenProfileActivation implements Serializable { + private boolean myActiveByDefault; + private MavenProfileActivationOS myOs; + private String myJdk; + private MavenProfileActivationProperty myProperty; + private MavenProfileActivationFile myFile; + + public boolean isActiveByDefault() { + return myActiveByDefault; + } + + public void setActiveByDefault(boolean activeByDefault) { + myActiveByDefault = activeByDefault; + } + + public MavenProfileActivationOS getOs() { + return myOs; + } + + public void setOs(MavenProfileActivationOS os) { + myOs = os; + } + + public String getJdk() { + return myJdk; + } + + public void setJdk(String jdk) { + myJdk = jdk; + } + + public MavenProfileActivationProperty getProperty() { + return myProperty; + } + + public void setProperty(MavenProfileActivationProperty property) { + myProperty = property; + } + + public MavenProfileActivationFile getFile() { + return myFile; + } + + public void setFile(MavenProfileActivationFile file) { + myFile = file; + } +} diff --git a/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenProfileActivationFile.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenProfileActivationFile.java new file mode 100644 index 000000000000..58ce8934cb1b --- /dev/null +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenProfileActivationFile.java @@ -0,0 +1,36 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.model; + +import java.io.Serializable; + +public class MavenProfileActivationFile implements Serializable { + private final String myExists; + private final String myMissing; + + public MavenProfileActivationFile(String exists, String missing) { + myExists = exists; + myMissing = missing; + } + + public String getExists() { + return myExists; + } + + public String getMissing() { + return myMissing; + } +} diff --git a/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenProfileActivationOS.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenProfileActivationOS.java new file mode 100644 index 000000000000..155cf3630b3f --- /dev/null +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenProfileActivationOS.java @@ -0,0 +1,48 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.model; + +import java.io.Serializable; + +public class MavenProfileActivationOS implements Serializable { + private final String myName; + private final String myFamily; + private final String myArch; + private final String myVersion; + + public MavenProfileActivationOS(String name, String family, String arch, String version) { + myName = name; + myFamily = family; + myArch = arch; + myVersion = version; + } + + public String getName() { + return myName; + } + + public String getFamily() { + return myFamily; + } + + public String getArch() { + return myArch; + } + + public String getVersion() { + return myVersion; + } +} diff --git a/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenProfileActivationProperty.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenProfileActivationProperty.java new file mode 100644 index 000000000000..1bd5aabef228 --- /dev/null +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenProfileActivationProperty.java @@ -0,0 +1,36 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.model; + +import java.io.Serializable; + +public class MavenProfileActivationProperty implements Serializable { + private final String myName; + private final String myValue; + + public MavenProfileActivationProperty(String name, String value) { + myName = name; + myValue = value; + } + + public String getName() { + return myName; + } + + public String getValue() { + return myValue; + } +} diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProfileState.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenProfileKind.java similarity index 83% rename from plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProfileState.java rename to plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenProfileKind.java index a28e0361b402..d42ef7d89251 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProfileState.java +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenProfileKind.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2010 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,8 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.idea.maven.project; +package org.jetbrains.idea.maven.model; -public enum MavenProfileState { +public enum MavenProfileKind { NONE, EXPLICIT, IMPLICIT } diff --git a/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenProjectProblem.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenProjectProblem.java new file mode 100644 index 000000000000..1511c142d9f2 --- /dev/null +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenProjectProblem.java @@ -0,0 +1,96 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.model; + +import java.io.File; +import java.io.Serializable; +import java.text.MessageFormat; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashSet; + +public class MavenProjectProblem implements Serializable { + public enum ProblemType { + SYNTAX, STRUCTURE, DEPENDENCY, PARENT, SETTINGS_OR_PROFILES + } + + private final String myPath; + private final String myDescription; + private final ProblemType myType; + + public static MavenProjectProblem createStructureProblem(String path, String description) { + return createProblem(path, description, MavenProjectProblem.ProblemType.STRUCTURE); + } + + public static MavenProjectProblem createSyntaxProblem(String path, MavenProjectProblem.ProblemType type) { + return createProblem(path, MessageFormat.format("''{0}'' has syntax errors", new File(path).getName()) , type); + } + + public static MavenProjectProblem createProblem(String path, String description, MavenProjectProblem.ProblemType type) { + return new MavenProjectProblem(path, description, type); + } + + public static Collection createProblemsList() { + return createProblemsList(Collections.emptySet()); + } + + public static Collection createProblemsList(Collection copyThis) { + return new LinkedHashSet(copyThis); + } + + public MavenProjectProblem(String path, String description, ProblemType type) { + myPath = path; + myDescription = description; + myType = type; + } + + public String getPath() { + return myPath; + } + + public String getDescription() { + return myDescription; + } + + public ProblemType getType() { + return myType; + } + + @Override + public String toString() { + return myType + ":" + myDescription + ":" + myPath; + } + + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + MavenProjectProblem that = (MavenProjectProblem)o; + + if (!myDescription.equals(that.myDescription)) return false; + if (myType != that.myType) return false; + if (!myPath.equals(that.myPath)) return false; + + return true; + } + + public int hashCode() { + int result = myPath.hashCode(); + result = 31 * result + myDescription.hashCode(); + result = 31 * result + myType.hashCode(); + return result; + } +} diff --git a/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenRemoteRepository.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenRemoteRepository.java new file mode 100644 index 000000000000..ade0b15278bd --- /dev/null +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenRemoteRepository.java @@ -0,0 +1,115 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.model; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.io.Serializable; + +public class MavenRemoteRepository implements Serializable { + private final String myId; + private final String myName; + private final String myUrl; + private final String myLayout; + private final Policy myReleasesPolicy; + private final Policy mySnapshotsPolicy; + + public MavenRemoteRepository(@NotNull String id, + @Nullable String name, + @NotNull String url, + @Nullable String layout, + @Nullable Policy releasesPolicy, + @Nullable Policy snapshotsPolicy) { + myId = id; + myName = name; + myUrl = url; + myLayout = layout; + myReleasesPolicy = releasesPolicy; + mySnapshotsPolicy = snapshotsPolicy; + } + + @NotNull + public String getId() { + return myId; + } + + @Nullable + public String getName() { + return myName; + } + + @NotNull + public String getUrl() { + return myUrl; + } + + @Nullable + public String getLayout() { + return myLayout; + } + + @Nullable + public Policy getReleasesPolicy() { + return myReleasesPolicy; + } + + @Nullable + public Policy getSnapshotsPolicy() { + return mySnapshotsPolicy; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + MavenRemoteRepository that = (MavenRemoteRepository)o; + + if (myId != null ? !myId.equals(that.myId) : that.myId != null) return false; + + return true; + } + + @Override + public int hashCode() { + return myId != null ? myId.hashCode() : 0; + } + + public static class Policy implements Serializable { + private final boolean myEnabled; + private final String myUpdatePolicy; + private final String myChecksumPolicy; + + public Policy(boolean enabled, String updatePolicy, String checksumPolicy) { + myEnabled = enabled; + myUpdatePolicy = updatePolicy; + myChecksumPolicy = checksumPolicy; + } + + public boolean isEnabled() { + return myEnabled; + } + + public String getUpdatePolicy() { + return myUpdatePolicy; + } + + public String getChecksumPolicy() { + return myChecksumPolicy; + } + } +} diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectModelProblem.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenRepositoryInfo.java similarity index 51% rename from plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectModelProblem.java rename to plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenRepositoryInfo.java index 64b378b79779..dd9fd21dc93b 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectModelProblem.java +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenRepositoryInfo.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2010 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,27 +13,30 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.idea.maven.project; +package org.jetbrains.idea.maven.model; -public class MavenProjectModelProblem { - private final String myDescription; - private final boolean isCritical; +import java.io.Serializable; - public MavenProjectModelProblem(String description, boolean critical) { - myDescription = description; - isCritical = critical; +public class MavenRepositoryInfo implements Serializable { + private final String myId; + private final String myName; + private final String myUrl; + + public MavenRepositoryInfo(String id, String name, String url) { + myId = id; + myName = name; + myUrl = url; } - public String getDescription() { - return myDescription; + public String getId() { + return myId; } - public boolean isCritical() { - return isCritical; + public String getName() { + return myName; } - @Override - public String toString() { - return (isCritical ? "!!!" : "") + myDescription; + public String getUrl() { + return myUrl; } } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenResource.java b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenResource.java similarity index 74% rename from plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenResource.java rename to plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenResource.java index 07f139c7cf6a..2f1485934a88 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenResource.java +++ b/plugins/maven/facade-api/src/org/jetbrains/idea/maven/model/MavenResource.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2010 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,33 +13,24 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.idea.maven.project; - -import org.apache.maven.model.Resource; +package org.jetbrains.idea.maven.model; import java.io.Serializable; -import java.util.Collections; import java.util.List; public class MavenResource implements Serializable { - private String myDirectory; - private boolean myFiltered; - private String myTargetPath; - private List myIncludes; - private List myExcludes; + private final String myDirectory; + private final boolean myFiltered; + private final String myTargetPath; + private final List myIncludes; + private final List myExcludes; - protected MavenResource() { - } - - public MavenResource(Resource resource) { - myDirectory = resource.getDirectory(); - myFiltered = resource.isFiltering(); - myTargetPath = resource.getTargetPath(); - myIncludes = resource.getIncludes(); - myExcludes = resource.getExcludes(); - - if (myIncludes == null) myIncludes = Collections.EMPTY_LIST; - if (myExcludes == null) myExcludes = Collections.EMPTY_LIST; + public MavenResource(String directory, boolean filtered, String targetPath, List includes, List excludes) { + myDirectory = directory; + myFiltered = filtered; + myTargetPath = targetPath; + myIncludes = includes; + myExcludes = excludes; } public String getDirectory() { diff --git a/plugins/maven/lib/activation-1.1.jar b/plugins/maven/facade-impl/lib/activation-1.1.jar similarity index 100% rename from plugins/maven/lib/activation-1.1.jar rename to plugins/maven/facade-impl/lib/activation-1.1.jar diff --git a/plugins/maven/lib/archetype-common-2.0-alpha-4-SNAPSHOT.jar b/plugins/maven/facade-impl/lib/archetype-common-2.0-alpha-4-SNAPSHOT.jar similarity index 100% rename from plugins/maven/lib/archetype-common-2.0-alpha-4-SNAPSHOT.jar rename to plugins/maven/facade-impl/lib/archetype-common-2.0-alpha-4-SNAPSHOT.jar diff --git a/plugins/maven/lib/classworlds-1.1.jar b/plugins/maven/facade-impl/lib/classworlds-1.1.jar similarity index 100% rename from plugins/maven/lib/classworlds-1.1.jar rename to plugins/maven/facade-impl/lib/classworlds-1.1.jar diff --git a/plugins/maven/lib/commons-beanutils.jar b/plugins/maven/facade-impl/lib/commons-beanutils.jar similarity index 100% rename from plugins/maven/lib/commons-beanutils.jar rename to plugins/maven/facade-impl/lib/commons-beanutils.jar diff --git a/plugins/maven/lib/commons-logging-1.1.1.jar b/plugins/maven/facade-impl/lib/commons-logging-1.1.1.jar similarity index 100% rename from plugins/maven/lib/commons-logging-1.1.1.jar rename to plugins/maven/facade-impl/lib/commons-logging-1.1.1.jar diff --git a/plugins/maven/lib/jaxb-api-2.1.jar b/plugins/maven/facade-impl/lib/jaxb-api-2.1.jar similarity index 100% rename from plugins/maven/lib/jaxb-api-2.1.jar rename to plugins/maven/facade-impl/lib/jaxb-api-2.1.jar diff --git a/plugins/maven/lib/jaxb-impl-2.1.10.jar b/plugins/maven/facade-impl/lib/jaxb-impl-2.1.10.jar similarity index 100% rename from plugins/maven/lib/jaxb-impl-2.1.10.jar rename to plugins/maven/facade-impl/lib/jaxb-impl-2.1.10.jar diff --git a/plugins/maven/lib/maven-2.2.1-uber.jar b/plugins/maven/facade-impl/lib/maven-2.2.1-uber.jar similarity index 100% rename from plugins/maven/lib/maven-2.2.1-uber.jar rename to plugins/maven/facade-impl/lib/maven-2.2.1-uber.jar diff --git a/plugins/maven/lib/maven-dependency-tree-1.2.jar b/plugins/maven/facade-impl/lib/maven-dependency-tree-1.2.jar similarity index 100% rename from plugins/maven/lib/maven-dependency-tree-1.2.jar rename to plugins/maven/facade-impl/lib/maven-dependency-tree-1.2.jar diff --git a/plugins/maven/facade-impl/lib/maven-embedder-1.0-SNAPSHOT.jar b/plugins/maven/facade-impl/lib/maven-embedder-1.0-SNAPSHOT.jar new file mode 100644 index 000000000000..259be18e5d66 Binary files /dev/null and b/plugins/maven/facade-impl/lib/maven-embedder-1.0-SNAPSHOT.jar differ diff --git a/plugins/maven/lib/mercury-artifact-1.0-alpha-6.jar b/plugins/maven/facade-impl/lib/mercury-artifact-1.0-alpha-6.jar similarity index 100% rename from plugins/maven/lib/mercury-artifact-1.0-alpha-6.jar rename to plugins/maven/facade-impl/lib/mercury-artifact-1.0-alpha-6.jar diff --git a/plugins/maven/lib/nexus-indexer-1.2.3.jar b/plugins/maven/facade-impl/lib/nexus-indexer-1.2.3.jar similarity index 100% rename from plugins/maven/lib/nexus-indexer-1.2.3.jar rename to plugins/maven/facade-impl/lib/nexus-indexer-1.2.3.jar diff --git a/plugins/maven/lib/plexus-utils-1.5.5.jar b/plugins/maven/facade-impl/lib/plexus-utils-1.5.5.jar similarity index 100% rename from plugins/maven/lib/plexus-utils-1.5.5.jar rename to plugins/maven/facade-impl/lib/plexus-utils-1.5.5.jar diff --git a/plugins/maven/lib/wadl-core.jar b/plugins/maven/facade-impl/lib/wadl-core.jar similarity index 100% rename from plugins/maven/lib/wadl-core.jar rename to plugins/maven/facade-impl/lib/wadl-core.jar diff --git a/plugins/maven/facade-impl/maven-facade-impl.iml b/plugins/maven/facade-impl/maven-facade-impl.iml new file mode 100644 index 000000000000..44f5bdc8b03c --- /dev/null +++ b/plugins/maven/facade-impl/maven-facade-impl.iml @@ -0,0 +1,185 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/MavenFacadeImpl.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/MavenFacadeImpl.java new file mode 100644 index 000000000000..a490b3cafbf2 --- /dev/null +++ b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/MavenFacadeImpl.java @@ -0,0 +1,141 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.facade; + +import org.jetbrains.annotations.Nullable; +import org.jetbrains.idea.maven.facade.embedder.MavenFacadeEmbedderImpl; +import org.jetbrains.idea.maven.facade.embedder.MavenFacadeIndexerImpl; +import org.jetbrains.idea.maven.facade.embedder.MavenModelConverter; +import org.jetbrains.idea.maven.facade.nexus.ArtifactType; +import org.jetbrains.idea.maven.facade.nexus.Endpoint; +import org.jetbrains.idea.maven.facade.nexus.RepositoryType; +import org.jetbrains.idea.maven.facade.nexus.SearchResults; +import org.jetbrains.idea.maven.model.MavenArtifactInfo; +import org.jetbrains.idea.maven.model.MavenModel; +import org.jetbrains.idea.maven.model.MavenRepositoryInfo; + +import java.io.File; +import java.math.BigInteger; +import java.rmi.RemoteException; +import java.rmi.server.UnicastRemoteObject; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; + +public class MavenFacadeImpl extends RemoteObject implements MavenFacade { + public void setLogger(MavenFacadeLogger logger) throws RemoteException { + try { + MavenFacadeLoggerManager.setLogger(logger); + } + catch (Exception e) { + throw new RuntimeException(wrapException(e)); + } + } + + public MavenFacadeEmbedder createEmbedder(MavenFacadeSettings settings) throws RemoteException { + try { + MavenFacadeEmbedderImpl result = MavenFacadeEmbedderImpl.create(settings); + UnicastRemoteObject.exportObject(result, 0); + return result; + } + catch (RemoteException e) { + throw new RuntimeException(wrapException(e)); + } + } + + public MavenFacadeIndexer createIndexer() throws RemoteException { + try { + MavenFacadeIndexerImpl result = new MavenFacadeIndexerImpl(); + UnicastRemoteObject.exportObject(result, 0); + return result; + } + catch (RemoteException e) { + throw new RuntimeException(wrapException(e)); + } + } + + public MavenModel interpolateAndAlignModel(MavenModel model, File basedir) { + try { + return MavenFacadeEmbedderImpl.interpolateAndAlignModel(model, basedir); + } + catch (Exception e) { + throw new RuntimeException(wrapException(e)); + } + } + + public MavenModel assembleInheritance(MavenModel model, MavenModel parentModel) { + try { + return MavenFacadeEmbedderImpl.assembleInheritance(model, parentModel); + } + catch (Exception e) { + throw new RuntimeException(wrapException(e)); + } + } + + public ProfileApplicationResult applyProfiles(MavenModel model, + File basedir, + Collection explicitProfiles, + Collection alwaysOnProfiles) { + try { + return MavenFacadeEmbedderImpl.applyProfiles(model, basedir, explicitProfiles, alwaysOnProfiles); + } + catch (Exception e) { + throw new RuntimeException(wrapException(e)); + } + } + + public List getRepositories(String nexusUrl) throws RemoteException { + try { + List repos = new Endpoint.Repositories(nexusUrl).getRepolistAsRepositories().getData().getRepositoriesItem(); + List result = new ArrayList(repos.size()); + for (RepositoryType repo : repos) { + if (!"maven2".equals(repo.getProvider())) continue; + result.add(MavenModelConverter.convertRepositoryInfo(repo)); + } + return result; + } + catch (Exception e) { + throw new RuntimeException(wrapException(e)); + } + } + + @Nullable + public List findArtifacts(MavenArtifactInfo template, String nexusUrl) throws RemoteException { + try { + SearchResults results = new Endpoint.DataIndex(nexusUrl) + .getArtifactlistAsSearchResults(null, template.getGroupId(), template.getArtifactId(), template.getVersion(), + template.getClassifier(), template.getClassNames()); + final boolean canTrySwitchGAV = template.getArtifactId() == null && template.getGroupId() != null; + final boolean tooManyResults = results.isTooManyResults(); + if (canTrySwitchGAV && (tooManyResults || BigInteger.ZERO.equals(results.getTotalCount()))) { + results = new Endpoint.DataIndex(nexusUrl) + .getArtifactlistAsSearchResults(null, null, template.getGroupId(), template.getVersion(), + template.getClassifier(), template.getClassNames()); + } + if (tooManyResults || results.isTooManyResults()) return null; + + ArrayList result = new ArrayList(); + for (ArtifactType each : results.getData().getArtifact()) { + result.add(MavenModelConverter.convertArtifactInfo(each)); + } + return result; + } + catch (Exception e) { + throw new RuntimeException(wrapException(e)); + } + } +} diff --git a/plugins/maven/facade/org/jetbrains/idea/maven/facade/remote/MavenFacadeLocator.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/MavenFacadeLocator.java similarity index 79% rename from plugins/maven/facade/org/jetbrains/idea/maven/facade/remote/MavenFacadeLocator.java rename to plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/MavenFacadeLocator.java index b6f8f052ea48..17a3c96670af 100644 --- a/plugins/maven/facade/org/jetbrains/idea/maven/facade/remote/MavenFacadeLocator.java +++ b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/MavenFacadeLocator.java @@ -1,14 +1,18 @@ -package org.jetbrains.idea.maven.facade.remote; +package org.jetbrains.idea.maven.facade; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Ref; -import org.jetbrains.idea.maven.facade.nexus.ArtifactType; +import org.jetbrains.idea.maven.model.MavenArtifactInfo; -import java.io.*; +import java.io.File; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; import java.net.URL; import java.net.URLClassLoader; import java.nio.CharBuffer; import java.rmi.registry.LocateRegistry; +import java.util.Collections; import java.util.List; /** @@ -43,8 +47,12 @@ public class MavenFacadeLocator { result.wait(); } } - if (result.isNull()) throw new RuntimeException(); - else return Pair.create((MavenFacade)LocateRegistry.getRegistry(result.get().first).lookup(result.get().second), process); + if (result.isNull()) { + throw new RuntimeException(); + } + else { + return Pair.create((MavenFacade)LocateRegistry.getRegistry(result.get().first).lookup(result.get().second), process); + } } private static void eatOutStreams(Process process, Ref> result) throws Exception { @@ -125,26 +133,23 @@ public class MavenFacadeLocator { final Pair pair = acquireFacade(new String[]{"java", "-cp", systemPath, debug1, debug2, RemoteMavenServer.class.getName()}, null, null); final MavenFacade facade = pair.first; - final MavenFacade.MavenFacadeSettings settings = new MavenFacade.MavenFacadeSettings(); - facade.setMavenSettings(settings); final String lookup = args.length > 0 ? args[0] : "hibernate"; - System.out.println("Looking up: "+lookup); - final List result = facade.findArtifacts(createTemplate(lookup), "http://oss.sonatype.org/service/local/"); - int i=1; - for (ArtifactType type : result) { - System.out.println((++i)+". "+type.getGroupId()+":"+type.getArtifactId()+":"+type.getVersion()); + System.out.println("Looking up: " + lookup); + final List result = facade.findArtifacts(createTemplate(lookup), "http://repository.sonatype.org/service/local/"); + int i = 1; + for (MavenArtifactInfo type : result) { + System.out.println((++i) + ". " + type.getGroupId() + ":" + type.getArtifactId() + ":" + type.getVersion()); } pair.second.destroy(); System.exit(0); } - private static ArtifactType createTemplate(String coord) { - final ArtifactType template = new ArtifactType(); + private static MavenArtifactInfo createTemplate(String coord) { final String[] parts = coord.split(":"); - template.setGroupId(parts.length > 0 ? parts[0] : null); - template.setArtifactId(parts.length > 1 ? parts[1] : null); - template.setVersion(parts.length > 2 ? parts[2] : null); - return template; + return new MavenArtifactInfo(parts.length > 0 ? parts[0] : null, + parts.length > 1 ? parts[1] : null, + parts.length > 2 ? parts[2] : null, + null, null, null, null); } } diff --git a/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/MavenFacadeLoggerManager.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/MavenFacadeLoggerManager.java new file mode 100644 index 000000000000..6f43c766686a --- /dev/null +++ b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/MavenFacadeLoggerManager.java @@ -0,0 +1,31 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.facade; + +import org.jetbrains.idea.maven.facade.embedder.MavenFacadeLoggerWrapper; + +public class MavenFacadeLoggerManager { + private static MavenFacadeLoggerWrapper myLogger; + + public static MavenFacadeLoggerWrapper getLogger() { + return myLogger; + } + + + public static void setLogger(MavenFacadeLogger logger) { + myLogger = new MavenFacadeLoggerWrapper(logger); + } +} diff --git a/plugins/maven/facade/org/jetbrains/idea/maven/facade/remote/RemoteMavenServer.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/RemoteMavenServer.java similarity index 93% rename from plugins/maven/facade/org/jetbrains/idea/maven/facade/remote/RemoteMavenServer.java rename to plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/RemoteMavenServer.java index bbb4223cdb72..dd53d5a269e4 100644 --- a/plugins/maven/facade/org/jetbrains/idea/maven/facade/remote/RemoteMavenServer.java +++ b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/RemoteMavenServer.java @@ -13,9 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.idea.maven.facade.remote; - -import org.jetbrains.idea.maven.facade.remote.impl.MavenFacadeImpl; +package org.jetbrains.idea.maven.facade; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/CustomArtifact.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/CustomArtifact.java similarity index 97% rename from plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/CustomArtifact.java rename to plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/CustomArtifact.java index d474223b4a0b..a9ec34ca7a93 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/CustomArtifact.java +++ b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/CustomArtifact.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.idea.maven.embedder; +package org.jetbrains.idea.maven.facade.embedder; import com.intellij.openapi.util.io.FileUtil; import gnu.trove.THashMap; @@ -25,7 +25,7 @@ import org.apache.maven.artifact.resolver.filter.ArtifactFilter; import org.apache.maven.artifact.versioning.ArtifactVersion; import org.apache.maven.artifact.versioning.OverConstrainedVersionException; import org.apache.maven.artifact.versioning.VersionRange; -import org.jetbrains.idea.maven.utils.MavenLog; +import org.jetbrains.idea.maven.facade.MavenFacadeLoggerManager; import java.io.File; import java.io.FileOutputStream; @@ -143,7 +143,7 @@ public class CustomArtifact implements Artifact { ourStubCache.put(getId(), f); } catch (IOException e) { - MavenLog.LOG.warn(e); + MavenFacadeLoggerManager.getLogger().warn(e); } finally { ourCacheWriteLock.unlock(); diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/CustomArtifactFactory.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/CustomArtifactFactory.java similarity index 99% rename from plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/CustomArtifactFactory.java rename to plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/CustomArtifactFactory.java index 2aacb9eda2a7..aaecc85738ab 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/CustomArtifactFactory.java +++ b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/CustomArtifactFactory.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.idea.maven.embedder; +package org.jetbrains.idea.maven.facade.embedder; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.versioning.VersionRange; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/CustomArtifactResolver.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/CustomArtifactResolver.java similarity index 84% rename from plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/CustomArtifactResolver.java rename to plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/CustomArtifactResolver.java index 7e8f8d425379..c7b578cd4e7f 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/CustomArtifactResolver.java +++ b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/CustomArtifactResolver.java @@ -13,26 +13,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.idea.maven.embedder; +package org.jetbrains.idea.maven.facade.embedder; -import com.intellij.openapi.vfs.VirtualFile; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.resolver.AbstractArtifactResolutionException; import org.apache.maven.artifact.resolver.ArtifactNotFoundException; import org.apache.maven.artifact.resolver.ArtifactResolutionException; import org.apache.maven.artifact.resolver.DefaultArtifactResolver; -import org.jetbrains.idea.maven.project.MavenId; +import org.jetbrains.idea.maven.model.MavenId; import java.io.File; import java.util.List; import java.util.Map; public class CustomArtifactResolver extends DefaultArtifactResolver { - private Map myProjectIdToFileMap; + private Map myProjectIdToFileMap; private UnresolvedArtifactsCollector myUnresolvedCollector; - public void customize(Map projectIdToFileMap, boolean failOnUnresolved) { + public void customize(Map projectIdToFileMap, boolean failOnUnresolved) { myProjectIdToFileMap = projectIdToFileMap; myUnresolvedCollector = new UnresolvedArtifactsCollector(failOnUnresolved); } @@ -71,15 +70,15 @@ public class CustomArtifactResolver extends DefaultArtifactResolver { } private boolean resolveAsModule(Artifact a) { - // method is called from different threads, so we have to copy the reference so ensure there is no race cconditions. - Map map = myProjectIdToFileMap; + // method is called from different threads, so we have to copy the reference so ensure there is no race conditions. + Map map = myProjectIdToFileMap; if (map == null) return false; - VirtualFile file = map.get(new MavenId(a)); + File file = map.get(MavenModelConverter.createMavenId(a)); if (file == null) return false; a.setResolved(true); - a.setFile(new File(file.getPath())); + a.setFile(file); return true; } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/CustomModelInterpolator.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/CustomModelInterpolator.java similarity index 97% rename from plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/CustomModelInterpolator.java rename to plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/CustomModelInterpolator.java index 154074a281d9..da173c05e560 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/CustomModelInterpolator.java +++ b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/CustomModelInterpolator.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.idea.maven.embedder; +package org.jetbrains.idea.maven.facade.embedder; import org.apache.maven.model.Model; import org.apache.maven.project.ProjectBuilderConfiguration; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/CustomWagonManager.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/CustomWagonManager.java similarity index 99% rename from plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/CustomWagonManager.java rename to plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/CustomWagonManager.java index bfb89a87c51e..73d4d8f8289d 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/CustomWagonManager.java +++ b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/CustomWagonManager.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.idea.maven.embedder; +package org.jetbrains.idea.maven.facade.embedder; import gnu.trove.THashMap; import org.apache.maven.artifact.Artifact; diff --git a/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/ExecutorManager.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/ExecutorManager.java new file mode 100644 index 000000000000..ad085bcb71de --- /dev/null +++ b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/ExecutorManager.java @@ -0,0 +1,27 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.facade.embedder; + +import java.util.concurrent.*; + +public class ExecutorManager { + private final static ExecutorService myExecutor = new ThreadPoolExecutor(3, Integer.MAX_VALUE, 30 * 60L, TimeUnit.SECONDS, + new SynchronousQueue()); + + public static Future execute(Runnable r) { + return myExecutor.submit(r); + } +} diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/FieldAccessor.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/FieldAccessor.java similarity index 96% rename from plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/FieldAccessor.java rename to plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/FieldAccessor.java index 72ad744ea383..5514a2fd9c5d 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/FieldAccessor.java +++ b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/FieldAccessor.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.idea.maven.embedder; +package org.jetbrains.idea.maven.facade.embedder; import java.lang.reflect.Field; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/MavenLogger.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/MavenFacadeConsoleWrapper.java similarity index 61% rename from plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/MavenLogger.java rename to plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/MavenFacadeConsoleWrapper.java index 10e869b059f1..c57d9fae1d56 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/MavenLogger.java +++ b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/MavenFacadeConsoleWrapper.java @@ -15,48 +15,58 @@ * ========================================================================= */ -package org.jetbrains.idea.maven.embedder; +package org.jetbrains.idea.maven.facade.embedder; import org.codehaus.plexus.logging.Logger; +import org.jetbrains.idea.maven.facade.MavenFacadeConsole; -public class MavenLogger implements Logger { - private MavenConsole myConsole; +import java.rmi.RemoteException; + +public class MavenFacadeConsoleWrapper implements Logger { + private static final String LINE_SEPARATOR = System.getProperty("line.separator"); + + private MavenFacadeConsole myWrappee; private int myThreshold; void doPrint(int level, String message, Throwable throwable) { if (level < myThreshold) return; - if (!message.endsWith(MavenConsole.LINE_SEPARATOR)) { - message += MavenConsole.LINE_SEPARATOR; + if (!message.endsWith(LINE_SEPARATOR)) { + message += LINE_SEPARATOR; } - if (myConsole != null) { - myConsole.printMessage(level, message, throwable); + if (myWrappee != null) { + try { + myWrappee.printMessage(level, message, throwable); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } } } - public void setConsole(MavenConsole console) { - myConsole = console; + public void setWrappee(MavenFacadeConsole wrappee) { + myWrappee = wrappee; } public void debug(String string, Throwable throwable) { - doPrint(MavenConsole.LEVEL_DEBUG, string, throwable); + doPrint(MavenFacadeConsole.LEVEL_DEBUG, string, throwable); } public void info(String string, Throwable throwable) { - doPrint(MavenConsole.LEVEL_INFO, string, throwable); + doPrint(MavenFacadeConsole.LEVEL_INFO, string, throwable); } public void warn(String string, Throwable throwable) { - doPrint(MavenConsole.LEVEL_WARN, string, throwable); + doPrint(MavenFacadeConsole.LEVEL_WARN, string, throwable); } public void error(String string, Throwable throwable) { - doPrint(MavenConsole.LEVEL_ERROR, string, throwable); + doPrint(MavenFacadeConsole.LEVEL_ERROR, string, throwable); } public void fatalError(String string, Throwable throwable) { - doPrint(MavenConsole.LEVEL_FATAL, string, throwable); + doPrint(MavenFacadeConsole.LEVEL_FATAL, string, throwable); } public void debug(String message) { @@ -64,7 +74,7 @@ public class MavenLogger implements Logger { } public boolean isDebugEnabled() { - return getThreshold() <= MavenConsole.LEVEL_DEBUG; + return getThreshold() <= MavenFacadeConsole.LEVEL_DEBUG; } public void info(String message) { @@ -72,7 +82,7 @@ public class MavenLogger implements Logger { } public boolean isInfoEnabled() { - return getThreshold() <= MavenConsole.LEVEL_INFO; + return getThreshold() <= MavenFacadeConsole.LEVEL_INFO; } public void warn(String message) { @@ -80,7 +90,7 @@ public class MavenLogger implements Logger { } public boolean isWarnEnabled() { - return getThreshold() <= MavenConsole.LEVEL_WARN; + return getThreshold() <= MavenFacadeConsole.LEVEL_WARN; } public void error(String message) { @@ -88,7 +98,7 @@ public class MavenLogger implements Logger { } public boolean isErrorEnabled() { - return getThreshold() <= MavenConsole.LEVEL_ERROR; + return getThreshold() <= MavenFacadeConsole.LEVEL_ERROR; } public void fatalError(String message) { @@ -96,7 +106,7 @@ public class MavenLogger implements Logger { } public boolean isFatalErrorEnabled() { - return getThreshold() <= MavenConsole.LEVEL_FATAL; + return getThreshold() <= MavenFacadeConsole.LEVEL_FATAL; } public void setThreshold(int threshold) { diff --git a/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/MavenFacadeEmbedderImpl.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/MavenFacadeEmbedderImpl.java new file mode 100644 index 000000000000..c4de158707c5 --- /dev/null +++ b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/MavenFacadeEmbedderImpl.java @@ -0,0 +1,640 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.facade.embedder; + +import com.intellij.openapi.progress.ProcessCanceledException; +import com.intellij.openapi.util.Ref; +import com.intellij.util.Function; +import gnu.trove.THashMap; +import gnu.trove.THashSet; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.InvalidRepositoryException; +import org.apache.maven.artifact.factory.ArtifactFactory; +import org.apache.maven.artifact.manager.WagonManager; +import org.apache.maven.artifact.repository.ArtifactRepository; +import org.apache.maven.artifact.repository.ArtifactRepositoryFactory; +import org.apache.maven.artifact.resolver.ArtifactNotFoundException; +import org.apache.maven.artifact.resolver.ArtifactResolutionException; +import org.apache.maven.artifact.resolver.ArtifactResolver; +import org.apache.maven.artifact.resolver.ResolutionListener; +import org.apache.maven.model.Activation; +import org.apache.maven.model.Model; +import org.apache.maven.model.Plugin; +import org.apache.maven.model.Profile; +import org.apache.maven.plugin.PluginManager; +import org.apache.maven.plugin.descriptor.PluginDescriptor; +import org.apache.maven.profiles.activation.*; +import org.apache.maven.project.*; +import org.apache.maven.project.artifact.ProjectArtifactFactory; +import org.apache.maven.project.inheritance.DefaultModelInheritanceAssembler; +import org.apache.maven.project.injection.DefaultProfileInjector; +import org.apache.maven.project.interpolation.AbstractStringBasedModelInterpolator; +import org.apache.maven.project.interpolation.ModelInterpolationException; +import org.apache.maven.project.interpolation.ModelInterpolator; +import org.apache.maven.project.path.DefaultPathTranslator; +import org.apache.maven.project.path.PathTranslator; +import org.apache.maven.project.validation.ModelValidationResult; +import org.apache.maven.shared.dependency.tree.DependencyNode; +import org.apache.maven.shared.dependency.tree.DependencyTreeResolutionListener; +import org.codehaus.plexus.PlexusContainer; +import org.codehaus.plexus.component.repository.ComponentDependency; +import org.codehaus.plexus.context.ContextException; +import org.codehaus.plexus.context.DefaultContext; +import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.idea.maven.facade.*; +import org.jetbrains.idea.maven.model.*; +import org.jetbrains.maven.embedder.MavenEmbedder; +import org.jetbrains.maven.embedder.MavenEmbedderSettings; +import org.jetbrains.maven.embedder.MavenExecutionResult; +import org.jetbrains.maven.embedder.PlexusComponentConfigurator; + +import java.io.File; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.rmi.RemoteException; +import java.rmi.server.RemoteObject; +import java.rmi.server.UnicastRemoteObject; +import java.util.*; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import static org.jetbrains.idea.maven.facade.RemoteObject.wrapException; + +public class MavenFacadeEmbedderImpl extends RemoteObject implements MavenFacadeEmbedder { + private final MavenEmbedder myImpl; + private final MavenFacadeConsoleWrapper myConsoleWrapper; + private volatile MavenFacadeProgressIndicatorWrapper myCurrentIndicatorWrapper; + + public static MavenFacadeEmbedderImpl create(MavenFacadeSettings facadeSettings) { + MavenEmbedderSettings settings = new MavenEmbedderSettings(); + + settings.setConfigurator(new PlexusComponentConfigurator() { + public void configureComponents(@NotNull PlexusContainer c) { + setupContainer(c); + } + }); + MavenFacadeConsoleWrapper consoleWrapper = new MavenFacadeConsoleWrapper(); + consoleWrapper.setThreshold(facadeSettings.getLoggingLevel()); + settings.setLogger(consoleWrapper); + settings.setRecursive(false); + + settings.setWorkOffline(facadeSettings.isOffline()); + settings.setUsePluginRegistry(false); + + settings.setMavenHome(facadeSettings.getMavenHome()); + settings.setUserSettingsFile(facadeSettings.getUserSettingsFile()); + settings.setGlobalSettingsFile(facadeSettings.getGlobalSettingsFile()); + settings.setLocalRepository(facadeSettings.getLocalRepository()); + + settings.setSnapshotUpdatePolicy(convertUpdatePolicy(facadeSettings.getSnapshotUpdatePolicy())); + settings.setPluginUpdatePolicy(convertUpdatePolicy(facadeSettings.getPluginUpdatePolicy())); + settings.setProperties(MavenFacadeUtil.collectSystemProperties()); + + return new MavenFacadeEmbedderImpl(MavenEmbedder.create(settings), consoleWrapper); + } + + private static MavenEmbedderSettings.UpdatePolicy convertUpdatePolicy(MavenFacadeSettings.UpdatePolicy policy) { + switch (policy) { + case ALWAYS_UPDATE: + return MavenEmbedderSettings.UpdatePolicy.ALWAYS_UPDATE; + case DO_NOT_UPDATE: + return MavenEmbedderSettings.UpdatePolicy.DO_NOT_UPDATE; + default: + MavenFacadeLoggerManager.getLogger().error(new Throwable("unexpected update policy")); + } + return MavenEmbedderSettings.UpdatePolicy.DO_NOT_UPDATE; + } + + private MavenFacadeEmbedderImpl(MavenEmbedder impl, MavenFacadeConsoleWrapper consoleWrapper) { + myImpl = impl; + myConsoleWrapper = consoleWrapper; + } + + @NotNull + public MavenWrapperExecutionResult resolveProject(@NotNull final File file, + @NotNull final Collection activeProfiles) + throws MavenFacadeProcessCanceledException { + return doExecute(new Executor() { + public MavenWrapperExecutionResult execute() throws Exception { + DependencyTreeResolutionListener listener = new DependencyTreeResolutionListener(myConsoleWrapper); + MavenExecutionResult result = myImpl.resolveProject(file, + new ArrayList(activeProfiles), + Arrays.asList(listener)); + return createExecutionResult(file, result, listener.getRootNode()); + } + }); + } + + @NotNull + private MavenWrapperExecutionResult createExecutionResult(File file, MavenExecutionResult result, DependencyNode rootNode) { + Collection problems = MavenProjectProblem.createProblemsList(); + THashSet unresolvedArtifacts = new THashSet(); + + validate(file, result.getExceptions(), problems, unresolvedArtifacts); + + MavenProject mavenProject = result.getMavenProject(); + if (mavenProject == null) return new MavenWrapperExecutionResult(null, problems, unresolvedArtifacts); + + MavenModel model = MavenModelConverter.convertModel(mavenProject.getModel(), + mavenProject.getCompileSourceRoots(), + mavenProject.getTestCompileSourceRoots(), + mavenProject.getArtifacts(), + (rootNode == null ? Collections.emptyList() : rootNode.getChildren()), + mavenProject.getExtensionArtifacts(), + getLocalRepositoryFile()); + + Collection activatedProfiles = MavenModelConverter.convertProfiles(mavenProject.getActiveProfiles()); + + RemoteNativeMavenProjectHolder holder = new RemoteNativeMavenProjectHolder(mavenProject); + try { + UnicastRemoteObject.exportObject(holder, 0); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + + MavenWrapperExecutionResult.ProjectData data = new MavenWrapperExecutionResult.ProjectData( + model, MavenModelConverter.convertToMap(mavenProject.getModel()), holder, activatedProfiles); + return new MavenWrapperExecutionResult(data, problems, unresolvedArtifacts); + } + + @NotNull + public MavenArtifact resolve(@NotNull final MavenArtifactInfo info, + @NotNull final List remoteRepositories) throws MavenFacadeProcessCanceledException { + return doExecute(new Executor() { + public MavenArtifact execute() throws Exception { + return doResolve(info, remoteRepositories); + } + }); + } + + @NotNull + public List resolveTransitively(@NotNull final List artifacts, + @NotNull final List remoteRepositories) { + try { + Set toResolve = new LinkedHashSet(); + for (MavenArtifactInfo each : artifacts) { + toResolve.add(createArtifact(each)); + } + + return MavenModelConverter.convertArtifacts(myImpl.resolveTransitively(toResolve, convertRepositories(remoteRepositories)), + new THashMap(), getLocalRepositoryFile()); + } + catch (ArtifactResolutionException e) { + MavenFacadeLoggerManager.getLogger().info(e); + } + catch (ArtifactNotFoundException e) { + MavenFacadeLoggerManager.getLogger().info(e); + } + catch (Exception e) { + throw new RuntimeException(wrapException(e)); + + } + return Collections.emptyList(); + } + + private MavenArtifact doResolve(MavenArtifactInfo info, List remoteRepositories) { + Artifact resolved = doResolve(createArtifact(info), convertRepositories(remoteRepositories)); + return MavenModelConverter.convertArtifact(resolved, getLocalRepositoryFile()); + } + + private Artifact createArtifact(MavenArtifactInfo info) { + return getComponent(ArtifactFactory.class).createArtifactWithClassifier(info.getGroupId(), + info.getArtifactId(), + info.getVersion(), + info.getPackaging(), + info.getClassifier()); + } + + private Artifact doResolve(Artifact artifact, List remoteRepositories) { + try { + myImpl.resolve(artifact, remoteRepositories); + return artifact; + } + catch (Exception e) { + MavenFacadeLoggerManager.getLogger().info(e); + } + return artifact; + } + + private List convertRepositories(List repositories) { + List result = new ArrayList(); + for (MavenRemoteRepository each : repositories) { + try { + ArtifactRepositoryFactory factory = getComponent(ArtifactRepositoryFactory.class); + result.add(ProjectUtils.buildArtifactRepository(MavenModelConverter.toNativeRepository(each), factory, getContainer())); + } + catch (InvalidRepositoryException e) { + MavenFacadeLoggerManager.getLogger().warn(e); + } + } + return result; + } + + public Collection resolvePlugin(@NotNull final MavenPlugin plugin, + @NotNull final List repositories, + final int nativeMavenProjectId, + final boolean transitive) throws MavenFacadeProcessCanceledException { + return doExecute(new Executor>() { + public Collection execute() throws Exception { + try { + Plugin mavenPlugin = new Plugin(); + mavenPlugin.setGroupId(plugin.getGroupId()); + mavenPlugin.setArtifactId(plugin.getArtifactId()); + mavenPlugin.setVersion(plugin.getVersion()); + MavenProject project = RemoteNativeMavenProjectHolder.findprojectById(nativeMavenProjectId); + PluginDescriptor result = getComponent(PluginManager.class).verifyPlugin(mavenPlugin, project, + myImpl.getSettings(), myImpl.getLocalRepository()); + if (!transitive) return Collections.emptyList(); + + // todo try to use parallel downloading + + Map resolvedArtifacts = new THashMap(); + for (Artifact each : (Iterable)result.getIntroducedDependencyArtifacts()) { + resolveIfNecessary(new MavenArtifactInfo(each.getGroupId(), each.getArtifactId(), each.getVersion(), each.getType(), null), + repositories, resolvedArtifacts); + } + for (ComponentDependency each : (List)result.getDependencies()) { + resolveIfNecessary(new MavenArtifactInfo(each.getGroupId(), each.getArtifactId(), each.getVersion(), each.getType(), null), + repositories, resolvedArtifacts); + } + return new THashSet(resolvedArtifacts.values()); + } + catch (Exception e) { + MavenFacadeLoggerManager.getLogger().info(e); + return Collections.emptyList(); + } + } + }); + } + + private void resolveIfNecessary(MavenArtifactInfo info, + List repos, + Map resolvedArtifacts) { + if (resolvedArtifacts.containsKey(info)) return; + resolvedArtifacts.put(info, doResolve(info, repos)); + } + + @NotNull + public MavenWrapperExecutionResult execute(@NotNull final File file, + @NotNull final Collection activeProfiles, + @NotNull final List goals) + throws MavenFacadeProcessCanceledException { + return doExecute(new Executor() { + public MavenWrapperExecutionResult execute() throws Exception { + MavenExecutionResult result = myImpl.execute(file, new ArrayList(activeProfiles), goals); + return createExecutionResult(file, result, null); + } + }); + } + + private void validate(File file, + Collection exceptions, + Collection problems, + Collection unresolvedArtifacts) { + for (Exception each : exceptions) { + MavenFacadeLoggerManager.getLogger().info(each); + + if (each instanceof InvalidProjectModelException) { + ModelValidationResult modelValidationResult = ((InvalidProjectModelException)each).getValidationResult(); + if (modelValidationResult != null) { + for (Object eachValidationProblem : modelValidationResult.getMessages()) { + problems.add(MavenProjectProblem.createStructureProblem(file.getPath(), (String)eachValidationProblem)); + } + } + else { + problems.add(MavenProjectProblem.createStructureProblem(file.getPath(), each.getCause().getMessage())); + } + } + else if (each instanceof ProjectBuildingException) { + String causeMessage = each.getCause() != null ? each.getCause().getMessage() : each.getMessage(); + problems.add(MavenProjectProblem.createStructureProblem(file.getPath(), causeMessage)); + } + else { + problems.add(MavenProjectProblem.createStructureProblem(file.getPath(), each.getMessage())); + } + } + unresolvedArtifacts.addAll(retrieveUnresolvedArtifactIds()); + } + + private Set retrieveUnresolvedArtifactIds() { + Set result = new THashSet(); + ((CustomWagonManager)getComponent(WagonManager.class)).getUnresolvedCollector().retrieveUnresolvedIds(result); + ((CustomArtifactResolver)getComponent(ArtifactResolver.class)).getUnresolvedCollector().retrieveUnresolvedIds(result); + return result; + } + + public static MavenModel interpolateAndAlignModel(MavenModel model, File basedir) { + Model result = MavenModelConverter.toNativeModel(model); + result = doInterpolate(result, basedir); + + PathTranslator pathTranslator = new DefaultPathTranslator(); + pathTranslator.alignToBaseDirectory(result, basedir); + + return MavenModelConverter.convertModel(result, null); + } + + private static Model doInterpolate(Model result, File basedir) { + try { + AbstractStringBasedModelInterpolator interpolator = new CustomModelInterpolator(new DefaultPathTranslator()); + interpolator.initialize(); + + Properties props = MavenFacadeUtil.collectSystemProperties(); + ProjectBuilderConfiguration config = new DefaultProjectBuilderConfiguration().setExecutionProperties(props); + result = interpolator.interpolate(result, basedir, config, false); + } + catch (ModelInterpolationException e) { + MavenFacadeLoggerManager.getLogger().warn(e); + } + catch (InitializationException e) { + MavenFacadeLoggerManager.getLogger().error(e); + } + return result; + } + + public static MavenModel assembleInheritance(MavenModel model, MavenModel parentModel) { + Model result = MavenModelConverter.toNativeModel(model); + new DefaultModelInheritanceAssembler().assembleModelInheritance(result, MavenModelConverter.toNativeModel(parentModel)); + return MavenModelConverter.convertModel(result, null); + } + + public static ProfileApplicationResult applyProfiles(MavenModel model, + File basedir, + Collection explicitProfiles, + Collection alwaysOnProfiles) { + Model nativeModel = MavenModelConverter.toNativeModel(model); + + List activatedPom = new ArrayList(); + List activatedExternal = new ArrayList(); + List activeByDefault = new ArrayList(); + + List rawProfiles = nativeModel.getProfiles(); + List expandedProfilesCache = null; + + for (int i = 0; i < rawProfiles.size(); i++) { + Profile eachRawProfile = rawProfiles.get(i); + + boolean shouldAdd = explicitProfiles.contains(eachRawProfile.getId()) || alwaysOnProfiles.contains(eachRawProfile.getId()); + + Activation activation = eachRawProfile.getActivation(); + if (activation != null) { + if (activation.isActiveByDefault()) { + activeByDefault.add(eachRawProfile); + } + + // expand only if necessary + if (expandedProfilesCache == null) expandedProfilesCache = doInterpolate(nativeModel, basedir).getProfiles(); + Profile eachExpandedProfile = expandedProfilesCache.get(i); + + for (ProfileActivator eachActivator : getProfileActivators()) { + try { + if (eachActivator.canDetermineActivation(eachExpandedProfile) && eachActivator.isActive(eachExpandedProfile)) { + shouldAdd = true; + break; + } + } + catch (ProfileActivationException e) { + MavenFacadeLoggerManager.getLogger().warn(e); + } + } + } + + if (shouldAdd) { + if (MavenConstants.PROFILE_FROM_POM.equals(eachRawProfile.getSource())) { + activatedPom.add(eachRawProfile); + } + else { + activatedExternal.add(eachRawProfile); + } + } + } + + List activatedProfiles = new ArrayList(activatedPom.isEmpty() ? activeByDefault : activatedPom); + activatedProfiles.addAll(activatedExternal); + + for (Profile each : activatedProfiles) { + new DefaultProfileInjector().inject(each, nativeModel); + } + + return new ProfileApplicationResult(MavenModelConverter.convertModel(nativeModel, null), + MavenModelConverter.convertProfiles(activatedProfiles)); + } + + private static ProfileActivator[] getProfileActivators() { + SystemPropertyProfileActivator sysPropertyActivator = new SystemPropertyProfileActivator(); + DefaultContext context = new DefaultContext(); + context.put("SystemProperties", MavenFacadeUtil.collectSystemProperties()); + try { + sysPropertyActivator.contextualize(context); + } + catch (ContextException e) { + MavenFacadeLoggerManager.getLogger().error(e); + return new ProfileActivator[0]; + } + + return new ProfileActivator[]{new FileProfileActivator(), + sysPropertyActivator, + new JdkPrefixProfileActivator(), + new OperatingSystemProfileActivator()}; + } + + @NotNull + public File getLocalRepositoryFile() { + return myImpl.getLocalRepositoryFile(); + } + + public T getComponent(Class clazz) { + return myImpl.getComponent(clazz); + } + + public T getComponent(Class clazz, String roleHint) { + return myImpl.getComponent(clazz, roleHint); + } + + public PlexusContainer getContainer() { + return myImpl.getContainer(); + } + + private interface Executor { + T execute() throws Exception; + } + + private T doExecute(final Executor executor) throws MavenFacadeProcessCanceledException { + final Ref result = new Ref(); + final boolean[] cancelled = new boolean[1]; + final Throwable[] exception = new Throwable[1]; + + Future future = ExecutorManager.execute(new Runnable() { + public void run() { + try { + result.set(executor.execute()); + } + catch (ProcessCanceledException e) { + cancelled[0] = true; + } + catch (Throwable e) { + exception[0] = e; + } + } + }); + + MavenFacadeProgressIndicatorWrapper indicator = myCurrentIndicatorWrapper; + while (true) { + if (indicator.isCanceled()) throw new MavenFacadeProcessCanceledException(); + + try { + future.get(50, TimeUnit.MILLISECONDS); + } + catch (TimeoutException ignore) { + } + catch (ExecutionException e) { + throw new RuntimeException(wrapException(e.getCause())); + } + catch (InterruptedException e) { + throw new MavenFacadeProcessCanceledException(); + } + + if (future.isDone()) break; + } + + if (cancelled[0]) throw new MavenFacadeProcessCanceledException(); + if (exception[0] != null) { + throw getRethrowable(exception[0]); + } + + return result.get(); + } + + private RuntimeException getRethrowable(Throwable throwable) { + if (throwable instanceof InvocationTargetException) throwable = throwable.getCause(); + return new RuntimeException(wrapException(throwable)); + } + + private static void setupContainer(PlexusContainer c) { + MavenEmbedder.setImplementation(c, ArtifactFactory.class, CustomArtifactFactory.class); + MavenEmbedder.setImplementation(c, ProjectArtifactFactory.class, CustomArtifactFactory.class); + MavenEmbedder.setImplementation(c, ArtifactResolver.class, CustomArtifactResolver.class); + MavenEmbedder.setImplementation(c, WagonManager.class, CustomWagonManager.class); + MavenEmbedder.setImplementation(c, ModelInterpolator.class, CustomModelInterpolator.class); + } + + public void customizeForResolve(MavenFacadeConsole console, MavenFacadeProgressIndicator process) { + doCustomize(null, false, console, process); + } + + public void customizeForResolve(Map projectIdToFileMap, MavenFacadeConsole console, MavenFacadeProgressIndicator process) { + doCustomize(projectIdToFileMap, false, console, process); + } + + public void customizeForStrictResolve(Map projectIdToFileMap, + MavenFacadeConsole console, + MavenFacadeProgressIndicator process) { + doCustomize(projectIdToFileMap, true, console, process); + } + + private void doCustomize(Map projectIdToFileMap, + boolean strict, + MavenFacadeConsole logger, + MavenFacadeProgressIndicator process) { + try { + ((CustomArtifactFactory)getComponent(ArtifactFactory.class)).customize(); + ((CustomArtifactFactory)getComponent(ProjectArtifactFactory.class)).customize(); + ((CustomArtifactResolver)getComponent(ArtifactResolver.class)).customize(projectIdToFileMap, strict); + ((CustomWagonManager)getComponent(WagonManager.class)).customize(strict); + + setConsoleAndLogger(logger, process); + } + catch (Exception e) { + throw new RuntimeException(wrapException(e)); + } + } + + private void setConsoleAndLogger(MavenFacadeConsole logger, MavenFacadeProgressIndicator process) { + myCurrentIndicatorWrapper = new MavenFacadeProgressIndicatorWrapper(process); + myConsoleWrapper.setWrappee(logger); + + WagonManager wagon = getComponent(WagonManager.class); + wagon.setDownloadMonitor(process == null ? null : new TransferListenerAdapter(new MavenFacadeProgressIndicatorWrapper(process))); + } + + public void reset() { + try { + setConsoleAndLogger(null, null); + + ((CustomArtifactFactory)getComponent(ProjectArtifactFactory.class)).reset(); + ((CustomArtifactFactory)getComponent(ArtifactFactory.class)).reset(); + ((CustomArtifactResolver)getComponent(ArtifactResolver.class)).reset(); + ((CustomWagonManager)getComponent(WagonManager.class)).reset(); + } + catch (Exception e) { + throw new RuntimeException(wrapException(e)); + } + } + + public void release() { + try { + myImpl.release(); + } + catch (Exception e) { + throw new RuntimeException(wrapException(e)); + } + } + + public void clearCaches() { + withProjectCachesDo(new Function() { + public Object fun(Map map) { + map.clear(); + return null; + } + }); + } + + public void clearCachesFor(final MavenId projectId) { + withProjectCachesDo(new Function() { + public Object fun(Map map) { + map.remove(projectId.getKey()); + return null; + } + }); + } + + private void withProjectCachesDo(Function func) { + MavenProjectBuilder builder = myImpl.getComponent(MavenProjectBuilder.class); + Field field; + try { + field = builder.getClass().getDeclaredField("rawProjectCache"); + field.setAccessible(true); + func.fun(((Map)field.get(builder))); + + field = builder.getClass().getDeclaredField("processedProjectCache"); + field.setAccessible(true); + func.fun(((Map)field.get(builder))); + } + catch (NoSuchFieldException e) { + MavenFacadeLoggerManager.getLogger().info(e); + } + catch (IllegalAccessException e) { + MavenFacadeLoggerManager.getLogger().info(e); + } + catch(Exception e) { + throw new RuntimeException(wrapException(e)); + } + } +} + diff --git a/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/MavenFacadeIndexerImpl.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/MavenFacadeIndexerImpl.java new file mode 100644 index 000000000000..4fb55e106bf8 --- /dev/null +++ b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/MavenFacadeIndexerImpl.java @@ -0,0 +1,297 @@ +/* +* Copyright 2000-2010 JetBrains s.r.o. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package org.jetbrains.idea.maven.facade.embedder; + +import com.intellij.openapi.util.text.StringUtil; +import gnu.trove.THashSet; +import gnu.trove.TIntObjectHashMap; +import org.apache.lucene.document.Document; +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.search.BooleanQuery; +import org.apache.lucene.search.Query; +import org.apache.lucene.search.TopDocs; +import org.apache.maven.archetype.catalog.Archetype; +import org.apache.maven.archetype.catalog.ArchetypeCatalog; +import org.apache.maven.archetype.source.ArchetypeDataSource; +import org.apache.maven.archetype.source.ArchetypeDataSourceException; +import org.apache.maven.artifact.manager.WagonManager; +import org.apache.maven.wagon.events.TransferEvent; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.idea.maven.facade.*; +import org.jetbrains.idea.maven.facade.RemoteObject; +import org.jetbrains.idea.maven.model.MavenArchetype; +import org.jetbrains.idea.maven.model.MavenArtifactInfo; +import org.jetbrains.idea.maven.model.MavenId; +import org.sonatype.nexus.index.*; +import org.sonatype.nexus.index.context.IndexUtils; +import org.sonatype.nexus.index.context.IndexingContext; +import org.sonatype.nexus.index.context.UnsupportedExistingLuceneIndexException; +import org.sonatype.nexus.index.updater.IndexUpdateRequest; +import org.sonatype.nexus.index.updater.IndexUpdater; + +import java.io.File; +import java.io.IOException; +import java.util.*; + +public class MavenFacadeIndexerImpl extends RemoteObject implements MavenFacadeIndexer { + private MavenFacadeEmbedderImpl myEmbedder; + private final NexusIndexer myIndexer; + private final IndexUpdater myUpdater; + private final ArtifactContextProducer myArtifactContextProducer; + + private final TIntObjectHashMap myIndices = new TIntObjectHashMap(); + + public MavenFacadeIndexerImpl() { + myEmbedder = MavenFacadeEmbedderImpl.create(new MavenFacadeSettings()); + + myIndexer = myEmbedder.getComponent(NexusIndexer.class); + myUpdater = myEmbedder.getComponent(IndexUpdater.class); + myArtifactContextProducer = myEmbedder.getComponent(ArtifactContextProducer.class); + } + + public int createIndex(@NotNull String indexId, + @Nullable String repositoryId, + @Nullable File file, + @Nullable String url, + @NotNull File indexDir) throws MavenFacadeIndexerException { + try { + IndexingContext context = myIndexer.addIndexingContext(indexId, + repositoryId, + file, + indexDir, + url, + null, // repo update url + NexusIndexer.FULL_INDEX); + int id = System.identityHashCode(context); + myIndices.put(id, context); + return id; + } + catch (Exception e) { + throw new MavenFacadeIndexerException(wrapException(e)); + } + } + + public void releaseIndex(int id) throws MavenFacadeIndexerException { + try { + myIndexer.removeIndexingContext(getIndex(id), false); + } + catch (Exception e) { + throw new MavenFacadeIndexerException(wrapException(e)); + } + } + + @NotNull + private IndexingContext getIndex(int id) { + IndexingContext index = myIndices.get(id); + if (index == null) throw new RuntimeException("Index not found for id: " + id); + return index; + } + + private String getRepositoryPathOrUrl(IndexingContext index) { + File file = index.getRepository(); + return file == null ? index.getRepositoryUrl() : file.getPath(); + } + + private boolean isLocal(IndexingContext index) { + return index.getRepository() != null; + } + + public int getIndexCount() { + return myIndexer.getIndexingContexts().size(); + } + + public void updateIndex(int id, MavenFacadeSettings settings, MavenFacadeProgressIndicator indicator) throws + MavenFacadeIndexerException, + MavenFacadeProcessCanceledException { + IndexingContext index = getIndex(id); + MavenFacadeProgressIndicatorWrapper indicatorWrapper = new MavenFacadeProgressIndicatorWrapper(indicator); + + try { + if (isLocal(index)) { + indicatorWrapper.setIndeterminate(true); + try { + myIndexer.scan(index, new MyScanningListener(indicatorWrapper), false); + } + finally { + indicatorWrapper.setIndeterminate(false); + } + } + else { + IndexUpdateRequest request = new IndexUpdateRequest(index); + MavenFacadeEmbedderImpl embedder = MavenFacadeEmbedderImpl.create(settings); + try { + request.setResourceFetcher(new MavenIndexFetcher(index.getRepositoryId(), + index.getRepositoryUrl(), + embedder.getComponent(WagonManager.class), + new TransferListenerAdapter(indicatorWrapper) { + @Override + protected void doUpdateProgress(long downloaded, long total) { + super.doUpdateProgress(downloaded, total); + myIndicator.setFraction(((double)downloaded) / total); + } + + @Override + public void transferCompleted(TransferEvent event) { + super.transferCompleted(event); + myIndicator.setText2("Processing indices..."); + } + })); + myUpdater.fetchAndUpdateIndex(request); + } + finally { + embedder.release(); + } + } + } + catch (MavenFacadeProgressIndicatorWrapper.RuntimeCanceledException e) { + throw new MavenFacadeProcessCanceledException(); + } + catch (Exception e) { + throw new MavenFacadeIndexerException(wrapException(e)); + } + } + + public List getAllArtifacts(int indexId) throws MavenFacadeIndexerException { + try { + List result = new ArrayList(); + IndexReader r = getIndex(indexId).getIndexReader(); + int total = r.numDocs(); + for (int i = 0; i < total; i++) { + if (r.isDeleted(i)) continue; + + Document doc = r.document(i); + String uinfo = doc.get(SEARCH_TERM_COORDINATES); + if (uinfo == null) continue; + List parts = StringUtil.split(uinfo, "|"); + String groupId = parts.get(0); + String artifactId = parts.get(1); + String version = parts.get(2); + if (groupId == null || artifactId == null || version == null) continue; + + result.add(new MavenId(groupId, artifactId, version)); + } + return result; + } + catch (Exception e) { + throw new MavenFacadeIndexerException(wrapException(e)); + } + } + + public MavenId addArtifact(int indexId, File artifactFile) throws MavenFacadeIndexerException { + try { + IndexingContext index = getIndex(indexId); + ArtifactContext artifactContext = myArtifactContextProducer.getArtifactContext(index, artifactFile); + if (artifactContext == null) return null; + + myIndexer.addArtifactToIndex(artifactContext, index); + + org.sonatype.nexus.index.ArtifactInfo a = artifactContext.getArtifactInfo(); + return new MavenId(a.groupId, a.artifactId, a.version); + } + catch (Exception e) { + throw new MavenFacadeIndexerException(wrapException(e)); + } + } + + public Set search(int indexId, Query query, int maxResult) throws MavenFacadeIndexerException { + try { + IndexingContext index = getIndex(indexId); + + TopDocs docs = null; + try { + BooleanQuery.setMaxClauseCount(Integer.MAX_VALUE); + docs = index.getIndexSearcher().search(query, null, maxResult); + } + catch (BooleanQuery.TooManyClauses ignore) { + // this exception occurs when too wide wildcard is used on too big data. + } + + if (docs == null || docs.scoreDocs.length == 0) return Collections.emptySet(); + + Set result = new THashSet(); + + for (int i = 0; i < docs.scoreDocs.length; i++) { + int docIndex = docs.scoreDocs[i].doc; + Document doc = index.getIndexReader().document(docIndex); + ArtifactInfo a = IndexUtils.constructArtifactInfo(doc, index); + if (a == null) continue; + + a.repository = getRepositoryPathOrUrl(index); + result.add(MavenModelConverter.convertArtifactInfo(a)); + } + return result; + } + catch (Exception e) { + throw new MavenFacadeIndexerException(wrapException(e)); + } + } + + public Collection getArchetypes() { + Set result = new THashSet(); + doCollectArchetypes("internal-catalog", result); + doCollectArchetypes("nexus", result); + return result; + } + + private void doCollectArchetypes(String roleHint, Set result) { + try { + ArchetypeDataSource source = myEmbedder.getComponent(ArchetypeDataSource.class, roleHint); + ArchetypeCatalog catalog = source.getArchetypeCatalog(new Properties()); + + for (Archetype each : (Iterable)catalog.getArchetypes()) { + result.add(MavenModelConverter.convertArchetype(each)); + } + } + catch (ArchetypeDataSourceException e) { + MavenFacadeLoggerManager.getLogger().warn(e); + } + } + + public void release() { + try { + myEmbedder.release(); + } + catch (Exception e) { + throw new RuntimeException(wrapException(e)); + } + } + + private static class MyScanningListener implements ArtifactScanningListener { + private final MavenFacadeProgressIndicatorWrapper p; + + public MyScanningListener(MavenFacadeProgressIndicatorWrapper indicator) { + p = indicator; + } + + public void scanningStarted(IndexingContext ctx) { + p.checkCanceled(); + } + + public void scanningFinished(IndexingContext ctx, ScanningResult result) { + p.checkCanceled(); + } + + public void artifactError(ArtifactContext ac, Exception e) { + } + + public void artifactDiscovered(ArtifactContext ac) { + p.checkCanceled(); + ArtifactInfo info = ac.getArtifactInfo(); + p.setText2(info.groupId + ":" + info.artifactId + ":" + info.version); + } + } +} diff --git a/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/MavenFacadeLoggerWrapper.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/MavenFacadeLoggerWrapper.java new file mode 100644 index 000000000000..1fdff7a724e5 --- /dev/null +++ b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/MavenFacadeLoggerWrapper.java @@ -0,0 +1,56 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.facade.embedder; + +import org.jetbrains.idea.maven.facade.MavenFacadeLogger; +import org.jetbrains.idea.maven.facade.RemoteObject; + +import java.rmi.RemoteException; + +public class MavenFacadeLoggerWrapper { + MavenFacadeLogger myWrappee; + + public MavenFacadeLoggerWrapper(MavenFacadeLogger wrappee) { + myWrappee = wrappee; + } + + public void info(Throwable e) { + try { + myWrappee.info(RemoteObject.wrapException(e)); + } + catch (RemoteException e1) { + throw new RuntimeException(e1); + } + } + + public void warn(Throwable e) { + try { + myWrappee.warn(RemoteObject.wrapException(e)); + } + catch (RemoteException e1) { + throw new RuntimeException(e1); + } + } + + public void error(Throwable e) { + try { + myWrappee.error(RemoteObject.wrapException(e)); + } + catch (RemoteException e1) { + throw new RuntimeException(e1); + } + } +} diff --git a/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/MavenFacadeProgressIndicatorWrapper.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/MavenFacadeProgressIndicatorWrapper.java new file mode 100644 index 000000000000..a4e0a06eb718 --- /dev/null +++ b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/MavenFacadeProgressIndicatorWrapper.java @@ -0,0 +1,80 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.facade.embedder; + +import org.jetbrains.idea.maven.facade.MavenFacadeProgressIndicator; + +import java.rmi.RemoteException; + +public class MavenFacadeProgressIndicatorWrapper { + private final MavenFacadeProgressIndicator myWrappee; + + public MavenFacadeProgressIndicatorWrapper(MavenFacadeProgressIndicator wrappee) { + myWrappee = wrappee; + } + + public void setText(String text) { + try { + myWrappee.setText(text); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + public void setText2(String text) { + try { + myWrappee.setText2(text); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + public boolean isCanceled() { + try { + return myWrappee.isCanceled(); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + public void checkCanceled() { + if (isCanceled()) throw new RuntimeCanceledException(); + } + + public void setIndeterminate(boolean value) { + try { + myWrappee.setIndeterminate(value); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + public void setFraction(double fraction) { + try { + myWrappee.setFraction(fraction); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + public static class RuntimeCanceledException extends RuntimeException { + } +} diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenIndexFetcher.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/MavenIndexFetcher.java similarity index 95% rename from plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenIndexFetcher.java rename to plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/MavenIndexFetcher.java index 341972ae56dc..1535cecf05c1 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenIndexFetcher.java +++ b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/MavenIndexFetcher.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.idea.maven.indices; +package org.jetbrains.idea.maven.facade.embedder; import org.apache.maven.artifact.manager.WagonManager; import org.apache.maven.artifact.repository.DefaultArtifactRepository; @@ -25,12 +25,13 @@ import org.apache.maven.wagon.authentication.AuthenticationException; import org.apache.maven.wagon.authorization.AuthorizationException; import org.apache.maven.wagon.events.TransferListener; import org.apache.maven.wagon.repository.Repository; -import org.jetbrains.idea.maven.utils.MavenLog; +import org.jetbrains.idea.maven.facade.MavenFacadeLoggerManager; import org.sonatype.nexus.index.updater.ResourceFetcher; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; +import java.rmi.RemoteException; public class MavenIndexFetcher implements ResourceFetcher { private final String myOriginalRepositoryId; @@ -80,7 +81,7 @@ public class MavenIndexFetcher implements ResourceFetcher { myWagon.disconnect(); } catch (ConnectionException ex) { - MavenLog.LOG.warn(ex); + MavenFacadeLoggerManager.getLogger().warn(ex); } } diff --git a/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/MavenModelConverter.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/MavenModelConverter.java new file mode 100644 index 000000000000..709df7b09d10 --- /dev/null +++ b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/MavenModelConverter.java @@ -0,0 +1,525 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.facade.embedder; + +import com.intellij.util.ReflectionUtil; +import gnu.trove.THashMap; +import gnu.trove.THashSet; +import org.apache.maven.archetype.catalog.Archetype; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.handler.ArtifactHandler; +import org.apache.maven.model.*; +import org.apache.maven.shared.dependency.tree.DependencyNode; +import org.codehaus.plexus.util.xml.Xpp3Dom; +import org.jdom.Element; +import org.jdom.IllegalNameException; +import org.jetbrains.idea.maven.facade.MavenFacadeLoggerManager; +import org.jetbrains.idea.maven.facade.nexus.ArtifactType; +import org.jetbrains.idea.maven.facade.nexus.RepositoryType; +import org.jetbrains.idea.maven.model.*; +import org.sonatype.nexus.index.ArtifactInfo; + +import java.io.File; +import java.lang.reflect.Field; +import java.util.*; + +public class MavenModelConverter { + public static MavenModel convertModel(Model model, File localRepository) { + Build build = model.getBuild(); + return convertModel(model, + asSourcesList(build.getSourceDirectory()), + asSourcesList(build.getTestSourceDirectory()), + Collections.emptyList(), + Collections.emptyList(), + Collections.emptyList(), + localRepository); + } + + private static List asSourcesList(String directory) { + return directory == null ? Collections.emptyList() : Collections.singletonList(directory); + } + + public static MavenModel convertModel(Model model, + List sources, + List testSources, + Collection dependencies, + Collection dependencyTree, + Collection extensions, + File localRepository) { + MavenModel result = new MavenModel(); + result.setMavenId(new MavenId(model.getGroupId(), model.getArtifactId(), model.getVersion())); + + Parent parent = model.getParent(); + if (parent != null) { + result.setParent(new MavenParent(new MavenId(parent.getGroupId(), parent.getArtifactId(), parent.getVersion()), + parent.getRelativePath())); + } + result.setPackaging(model.getPackaging()); + result.setName(model.getName()); + result.setProperties(model.getProperties() == null ? new Properties() : model.getProperties()); + result.setPlugins(convertPlugins(model)); + + Map convertedArtifacts = new THashMap(); + result.setExtensions(convertArtifacts(extensions, convertedArtifacts, localRepository)); + result.setDependencies(convertArtifacts(dependencies, convertedArtifacts, localRepository)); + result.setDependencyTree(convertDependencyNodes(null, dependencyTree, convertedArtifacts, localRepository)); + + result.setRemoteRepositories(convertRepositories(model.getRepositories())); + result.setProfiles(convertProfiles(model.getProfiles())); + result.setModules(model.getModules()); + + convertBuild(result.getBuild(), model.getBuild(), sources, testSources); + return result; + } + + private static void convertBuild(MavenBuild result, Build build, List sources, List testSources) { + convertBuildBase(result, build); + result.setOutputDirectory(build.getOutputDirectory()); + result.setTestOutputDirectory(build.getTestOutputDirectory()); + result.setSources(sources); + result.setTestSources(testSources); + } + + private static void convertBuildBase(MavenBuildBase result, BuildBase build) { + result.setFinalName(build.getFinalName()); + result.setDefaultGoal(build.getDefaultGoal()); + result.setDirectory(build.getDirectory()); + result.setResources(convertResources(build.getResources())); + result.setTestResources(convertResources(build.getTestResources())); + result.setFilters(build.getFilters() == null ? Collections.emptyList() : build.getFilters()); + } + + public static MavenId createMavenId(Artifact artifact) { + return new MavenId(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()); + } + + private static List convertResources(List resources) { + if (resources == null) return new ArrayList(); + + List result = new ArrayList(resources.size()); + for (Resource each : resources) { + result.add(new MavenResource(each.getDirectory(), + each.isFiltering(), + each.getTargetPath(), + ensurePatterns(each.getIncludes()), + ensurePatterns(each.getExcludes()))); + } + return result; + } + + private static List ensurePatterns(List patterns) { + return patterns == null ? Collections.EMPTY_LIST : patterns; + } + + private static List convertRepositories(List repositories) { + if (repositories == null) return new ArrayList(); + + List result = new ArrayList(repositories.size()); + for (Repository each : repositories) { + result.add(new MavenRemoteRepository(each.getId(), + each.getName(), + each.getUrl(), + each.getLayout(), + convertPolicy(each.getReleases()), + convertPolicy(each.getSnapshots()))); + } + return result; + } + + private static MavenRemoteRepository.Policy convertPolicy(RepositoryPolicy policy) { + return policy != null + ? new MavenRemoteRepository.Policy(policy.isEnabled(), policy.getUpdatePolicy(), policy.getChecksumPolicy()) + : null; + } + + public static List convertArtifacts(Collection artifacts, + Map nativeToConvertedMap, + File localRepository) { + if (artifacts == null) return new ArrayList(); + + List result = new ArrayList(artifacts.size()); + for (Artifact each : artifacts) { + result.add(convertArtifact(each, nativeToConvertedMap, localRepository)); + } + return result; + } + + public static List convertDependencyNodes(MavenArtifactNode parent, + Collection nodes, + Map nativeToConvertedMap, + File localRepository) { + List result = new ArrayList(nodes.size()); + for (DependencyNode each : nodes) { + Artifact a = each.getArtifact(); + MavenArtifact ma = convertArtifact(a, nativeToConvertedMap, localRepository); + + MavenArtifactState state = MavenArtifactState.ADDED; + switch (each.getState()) { + case DependencyNode.INCLUDED: + break; + case DependencyNode.OMITTED_FOR_CONFLICT: + state = MavenArtifactState.CONFLICT; + break; + case DependencyNode.OMITTED_FOR_DUPLICATE: + state = MavenArtifactState.DUPLICATE; + break; + case DependencyNode.OMITTED_FOR_CYCLE: + state = MavenArtifactState.CYCLE; + break; + default: + assert false : "unknown dependency node state: " + each.getState(); + } + MavenArtifact relatedMA = each.getRelatedArtifact() == null ? null + : convertArtifact(each.getRelatedArtifact(), nativeToConvertedMap, + localRepository); + MavenArtifactNode newNode = new MavenArtifactNode(parent, ma, state, relatedMA, each.getOriginalScope(), + each.getPremanagedVersion(), each.getPremanagedScope()); + newNode.setDependencies(convertDependencyNodes(newNode, each.getChildren(), nativeToConvertedMap, localRepository)); + result.add(newNode); + } + return result; + } + + private static MavenArtifact convertArtifact(Artifact artifact, Map nativeToConvertedMap, File localRepository) { + MavenArtifact result = nativeToConvertedMap.get(artifact); + if (result == null) { + result = convertArtifact(artifact, localRepository); + nativeToConvertedMap.put(artifact, result); + } + return result; + } + + public static MavenArtifact convertArtifact(Artifact artifact, File localRepository) { + return new MavenArtifact(artifact.getGroupId(), artifact.getArtifactId(), + artifact.getVersion(), + artifact.getBaseVersion(), + artifact.getType(), + artifact.getClassifier(), + + artifact.getScope(), + artifact.isOptional(), + + convertExtension(artifact), + + artifact.getFile(), + localRepository, + + artifact.isResolved(), + artifact instanceof CustomArtifact && ((CustomArtifact)artifact).isStub()); + } + + private static String convertExtension(Artifact artifact) { + ArtifactHandler handler = artifact.getArtifactHandler(); + String result = null; + if (handler != null) result = handler.getExtension(); + if (result == null) result = artifact.getType(); + return result; + } + + private static List convertPlugins(Model mavenModel) { + List result = new ArrayList(); + Set pluginKeys = new THashSet(); + Build build = mavenModel.getBuild(); + doConvertPlugins(build, false, result, pluginKeys); + if (build != null) doConvertPlugins(build.getPluginManagement(), true, result, pluginKeys); + return result; + } + + private static void doConvertPlugins(PluginContainer container, + boolean management, + List result, + Set pluginKeys) { + if (container == null) return; + + List plugins = container.getPlugins(); + if (plugins == null) return; + + for (Plugin each : plugins) { + String key = each.getGroupId() + ":" + each.getArtifactId(); + result.add(convertPlugin(management, each)); + pluginKeys.add(key); + } + } + + private static MavenPlugin convertPlugin(boolean isDefault, Plugin plugin) { + List executions = new ArrayList(plugin.getExecutions().size()); + for (PluginExecution each : plugin.getExecutions()) { + executions.add(convertExecution(each)); + } + + List deps = new ArrayList(plugin.getDependencies().size()); + for (Dependency each : plugin.getDependencies()) { + deps.add(new MavenId(each.getGroupId(), each.getArtifactId(), each.getVersion())); + } + + return new MavenPlugin(plugin.getGroupId(), + plugin.getArtifactId(), + plugin.getVersion(), + isDefault, + convertConfiguration(plugin.getConfiguration()), + executions, deps); + } + + public static MavenPlugin.Execution convertExecution(PluginExecution execution) { + return new MavenPlugin.Execution(execution.getGoals(), convertConfiguration(execution.getConfiguration())); + } + + private static Element convertConfiguration(Object config) { + return config == null ? null : xppToElement((Xpp3Dom)config); + } + + private static Element xppToElement(Xpp3Dom xpp) { + Element result = null; + try { + result = new Element(xpp.getName()); + } + catch (IllegalNameException e) { + MavenFacadeLoggerManager.getLogger().error(e); + return null; + } + + Xpp3Dom[] children = xpp.getChildren(); + if (children == null || children.length == 0) { + result.setText(xpp.getValue()); + } + else { + for (Xpp3Dom each : children) { + Element child = xppToElement(each); + if (child != null) result.addContent(child); + } + } + return result; + } + + public static List convertProfiles(Collection profiles) { + if (profiles == null) return Collections.emptyList(); + List result = new ArrayList(); + for (Profile each : profiles) { + String id = each.getId(); + if (id == null) continue; + MavenProfile profile = new MavenProfile(id, each.getSource()); + List modules = each.getModules(); + profile.setModules(modules == null ? Collections.emptyList() : modules); + if (each.getBuild() != null) convertBuildBase(profile.getBuild(), each.getBuild()); + result.add(profile); + } + return result; + } + + public static Map convertToMap(Object object) { + try { + Map result = new THashMap(); + doConvert(object, "", result); + return result; + } + catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } + + private static void doConvert(Object object, String prefix, Map result) throws IllegalAccessException { + for (Field each : ReflectionUtil.collectFields(object.getClass())) { + Class type = each.getType(); + if (shouldSkip(type)) continue; + + each.setAccessible(true); + Object value = each.get(object); + + String name = prefix + each.getName(); + result.put(name, String.valueOf(value)); + if (value != null) { + Package pack = type.getPackage(); + if (pack != null && Model.class.getPackage().getName().equals(pack.getName())) { + doConvert(value, name + ".", result); + } + } + } + } + + public static boolean shouldSkip(Class clazz) { + return clazz.isArray() + || Collection.class.isAssignableFrom(clazz) + || Map.class.isAssignableFrom(clazz) + || Xpp3Dom.class.isAssignableFrom(clazz); + } + + public static MavenArchetype convertArchetype(Archetype archetype) { + return new MavenArchetype(archetype.getGroupId(), + archetype.getArtifactId(), + archetype.getVersion(), + archetype.getRepository(), + archetype.getDescription()); + } + + public static Model toNativeModel(MavenModel model) { + Model result = new Model(); + result.setArtifactId(model.getMavenId().getArtifactId()); + result.setGroupId(model.getMavenId().getGroupId()); + result.setVersion(model.getMavenId().getVersion()); + result.setPackaging(model.getPackaging()); + result.setName(model.getName()); + + if (model.getParent() != null) { + Parent parent = new Parent(); + parent.setArtifactId(model.getParent().getMavenId().getArtifactId()); + parent.setGroupId(model.getParent().getMavenId().getGroupId()); + parent.setVersion(model.getParent().getMavenId().getVersion()); + parent.setRelativePath(model.getParent().getRelativePath()); + result.setParent(parent); + } + toNativeModelBase(model, result); + + result.setBuild(new Build()); + MavenBuild modelBuild = model.getBuild(); + toNativeBuildBase(modelBuild, result.getBuild()); + result.getBuild().setOutputDirectory(modelBuild.getOutputDirectory()); + result.getBuild().setTestOutputDirectory(modelBuild.getTestOutputDirectory()); + + if (modelBuild.getSources().size() > 1) throw new RuntimeException("too many source directories: " + modelBuild.getSources()); + if (modelBuild.getTestSources().size() > 1) throw new RuntimeException("too many test directories: " + modelBuild.getTestSources()); + + if (modelBuild.getSources().size() == 1) { + result.getBuild().setSourceDirectory(modelBuild.getSources().get(0)); + } + if (modelBuild.getTestSources().size() == 1) { + result.getBuild().setTestSourceDirectory(modelBuild.getTestSources().get(0)); + } + + result.setProfiles(toNativeProfiles(model.getProfiles())); + + return result; + } + + private static List toNativeProfiles(List profiles) { + List result = new ArrayList(profiles.size()); + for (MavenProfile each : profiles) { + Profile p = new Profile(); + p.setId(each.getId()); + p.setSource(each.getSource()); + p.setBuild(new Build()); + p.setActivation(toNativeActivation(each.getActivation())); + toNativeModelBase(each, p); + toNativeBuildBase(each.getBuild(), p.getBuild()); + result.add(p); + } + return result; + } + + private static Activation toNativeActivation(MavenProfileActivation activation) { + if (activation == null) return null; + Activation result = new Activation(); + result.setActiveByDefault(activation.isActiveByDefault()); + result.setJdk(activation.getJdk()); + result.setOs(toNativeOsActivation(activation.getOs())); + result.setFile(toNativeFileActivation(activation.getFile())); + result.setProperty(toNativePropertyActivation(activation.getProperty())); + return result; + } + + private static ActivationOS toNativeOsActivation(MavenProfileActivationOS os) { + if (os == null) return null; + ActivationOS result = new ActivationOS(); + result.setArch(os.getArch()); + result.setFamily(os.getFamily()); + result.setName(os.getName()); + result.setVersion(os.getVersion()); + return result; + } + + private static ActivationFile toNativeFileActivation(MavenProfileActivationFile file) { + if (file == null) return null; + ActivationFile result = new ActivationFile(); + result.setExists(file.getExists()); + result.setMissing(file.getMissing()); + return result; + } + + private static ActivationProperty toNativePropertyActivation(MavenProfileActivationProperty property) { + if (property == null) return null; + ActivationProperty result = new ActivationProperty(); + result.setName(property.getName()); + result.setValue(property.getValue()); + return result; + } + + private static void toNativeModelBase(MavenModelBase from, ModelBase to) { + to.setModules(from.getModules()); + to.setProperties(from.getProperties()); + } + + private static void toNativeBuildBase(MavenBuildBase from, BuildBase to) { + to.setFinalName(from.getFinalName()); + to.setDefaultGoal(from.getDefaultGoal()); + to.setDirectory(from.getDirectory()); + to.setFilters(from.getFilters()); + to.setResources(toNativeResources(from.getResources())); + to.setTestResources(toNativeResources(from.getTestResources())); + } + + private static List toNativeResources(List resources) { + List result = new ArrayList(resources.size()); + for (MavenResource each : resources) { + Resource r = new Resource(); + r.setDirectory(each.getDirectory()); + r.setTargetPath(each.getTargetPath()); + r.setFiltering(each.isFiltered()); + r.setIncludes(each.getIncludes()); + r.setExcludes(each.getExcludes()); + result.add(r); + } + return result; + } + + public static Repository toNativeRepository(MavenRemoteRepository r) { + Repository result = new Repository(); + result.setId(r.getId()); + result.setName(r.getName()); + result.setUrl(r.getUrl()); + result.setLayout(r.getLayout() == null ? "default" : r.getLayout()); + + if (r.getReleasesPolicy() != null) result.setReleases(toNativePolicy(r.getReleasesPolicy())); + if (r.getSnapshotsPolicy() != null) result.setSnapshots(toNativePolicy(r.getSnapshotsPolicy())); + + return result; + } + + private static RepositoryPolicy toNativePolicy(MavenRemoteRepository.Policy policy) { + RepositoryPolicy result = new RepositoryPolicy(); + result.setEnabled(policy.isEnabled()); + result.setUpdatePolicy(policy.getUpdatePolicy()); + result.setChecksumPolicy(policy.getChecksumPolicy()); + return result; + } + + public static MavenArtifactInfo convertArtifactInfo(ArtifactInfo a) { + return new MavenArtifactInfo(a.groupId, a.artifactId, a.version, a.packaging, a.classifier, a.classNames, a.repository); + } + + public static MavenArtifactInfo convertArtifactInfo(ArtifactType t) { + return new MavenArtifactInfo(t.getGroupId(), + t.getArtifactId(), + t.getVersion(), + t.getPackaging(), + t.getClassifier(), + null, + t.getRepoId()); + } + + public static MavenRepositoryInfo convertRepositoryInfo(RepositoryType repo) { + return new MavenRepositoryInfo(repo.getId(), repo.getName(), repo.getContentResourceURI()); + } +} + diff --git a/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/RemoteNativeMavenProjectHolder.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/RemoteNativeMavenProjectHolder.java new file mode 100644 index 000000000000..8b99bedf99e6 --- /dev/null +++ b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/RemoteNativeMavenProjectHolder.java @@ -0,0 +1,31 @@ +package org.jetbrains.idea.maven.facade.embedder; + +import com.intellij.util.containers.WeakValueHashMap; +import org.apache.maven.project.MavenProject; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.idea.maven.facade.NativeMavenProjectHolder; + +public class RemoteNativeMavenProjectHolder implements NativeMavenProjectHolder { + private static final WeakValueHashMap myMap = + new WeakValueHashMap(); + + private final MavenProject myMavenProject; + + public RemoteNativeMavenProjectHolder(@NotNull MavenProject mavenProject) { + myMavenProject = mavenProject; + myMap.put(getId(), this); + } + + public int getId() { + return System.identityHashCode(this); + } + + @NotNull + public static MavenProject findprojectById(int id) { + RemoteNativeMavenProjectHolder result = myMap.get(id); + if (result == null) { + throw new RuntimeException("NativeMavenProjectHolder not found for id: " + id); + } + return result.myMavenProject; + } +} diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/TransferListenerAdapter.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/TransferListenerAdapter.java similarity index 61% rename from plugins/maven/src/main/java/org/jetbrains/idea/maven/project/TransferListenerAdapter.java rename to plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/TransferListenerAdapter.java index 12008224ecca..e585869b5c0a 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/TransferListenerAdapter.java +++ b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/TransferListenerAdapter.java @@ -13,30 +13,31 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.idea.maven.project; +package org.jetbrains.idea.maven.facade.embedder; import org.apache.maven.wagon.events.TransferEvent; import org.apache.maven.wagon.events.TransferListener; -import org.jetbrains.idea.maven.indices.MavenIndicesManager; -import org.jetbrains.idea.maven.utils.MavenProgressIndicator; + +import java.text.MessageFormat; public class TransferListenerAdapter implements TransferListener { - protected final MavenProgressIndicator myIndicator; + protected final MavenFacadeProgressIndicatorWrapper myIndicator; private String myRepository; private String myResource; private long mySize; private long myProgress; - //private static long total; - //private long started; - - public TransferListenerAdapter(MavenProgressIndicator indicator) { + public TransferListenerAdapter(MavenFacadeProgressIndicatorWrapper indicator) { myIndicator = indicator; } public void transferInitiated(TransferEvent event) { - myIndicator.checkCanceledNative(); + checkCanceled(); + } + + private void checkCanceled() { + myIndicator.checkCanceled(); } public void transferStarted(TransferEvent event) { @@ -53,39 +54,31 @@ public class TransferListenerAdapter implements TransferListener { } protected void doUpdateProgress(long downloaded, long total) { - myIndicator.setText2(ProjectBundle.message("maven.transfer.progress", downloaded, total == 0 ? "?" : total, myRepository, myResource)); + myIndicator.setText2(MessageFormat.format("{0}/{1}Kb [{2}] {3}", downloaded, total == 0 ? "?" : total, myRepository, myResource)); } public void transferProgress(TransferEvent event, byte[] bytes, int i) { - myIndicator.checkCanceledNative(); + checkCanceled(); myProgress += i; updateProgress(); } public void transferCompleted(TransferEvent event) { addArtifactToIndex(event); - myIndicator.checkCanceledNative(); - updateTiming(true); + checkCanceled(); } public void transferError(TransferEvent event) { - myIndicator.checkCanceledNative(); - updateTiming(false); + checkCanceled(); } public void debug(String s) { - myIndicator.checkCanceledNative(); - } - - private void updateTiming(boolean ok) { - //long finished = System.currentTimeMillis(); - //long time = finished - started; - //total += time; - //System.out.println((ok ? "OK: " : "ERROR: ") + time + " (" + total + ")"); + checkCanceled(); } private void addArtifactToIndex(TransferEvent event) { - MavenIndicesManager.getInstance().addArtifact(event.getLocalFile(), - event.getResource().getName()); + // todo + //MavenIndicesManager.getInstance().addArtifact(event.getLocalFile(), + // event.getResource().getName()); } } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/UnresolvedArtifactsCollector.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/UnresolvedArtifactsCollector.java similarity index 88% rename from plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/UnresolvedArtifactsCollector.java rename to plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/UnresolvedArtifactsCollector.java index aab5d047aad9..99b65bf3c0d5 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/UnresolvedArtifactsCollector.java +++ b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/embedder/UnresolvedArtifactsCollector.java @@ -13,11 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.idea.maven.embedder; +package org.jetbrains.idea.maven.facade.embedder; import gnu.trove.THashSet; import org.apache.maven.artifact.Artifact; -import org.jetbrains.idea.maven.project.MavenId; +import org.jetbrains.idea.maven.model.MavenId; import java.util.Set; @@ -39,7 +39,7 @@ public class UnresolvedArtifactsCollector { public void collectAndSetResolved(Artifact artifact) { if (!artifact.isResolved()) { synchronized (myUnresolvedIds) { - myUnresolvedIds.add(new MavenId(artifact)); + myUnresolvedIds.add(MavenModelConverter.createMavenId(artifact)); } } if (!myFailOnUnresolved) artifact.setResolved(true); diff --git a/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/nexus/ArtifactType.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/nexus/ArtifactType.java new file mode 100644 index 000000000000..545cc617fb2f --- /dev/null +++ b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/nexus/ArtifactType.java @@ -0,0 +1,327 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.facade.nexus; + +import org.jetbrains.annotations.Nullable; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; +import java.io.Serializable; + + +/** + *

Java class for artifactType complex type. + *

+ *

The following schema fragment specifies the expected content contained within this class. + *

+ *

+ * <complexType name="artifactType">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="resourceUri" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="groupId" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="artifactId" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="version" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="classifier" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="packaging" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="extension" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="repoId" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="contextId" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="pomLink" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="artifactLink" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "artifactType", propOrder = { + "resourceUri", + "groupId", + "artifactId", + "version", + "classifier", + "packaging", + "extension", + "repoId", + "contextId", + "pomLink", + "artifactLink" +}) +public class ArtifactType implements Serializable { + + @XmlElement(required = true) + protected String resourceUri; + @XmlElement(required = true) + protected String groupId; + @XmlElement(required = true) + protected String artifactId; + @XmlElement(required = true) + protected String version; + @XmlElement(required = true) + protected String classifier; + @XmlElement(required = true) + protected String packaging; + @XmlElement(required = true) + protected String extension; + @XmlElement(required = true) + protected String repoId; + @XmlElement(required = true) + protected String contextId; + @XmlElement(required = true) + protected String pomLink; + @XmlElement(required = true) + protected String artifactLink; + + public ArtifactType() { + + } + + public ArtifactType(String groupId, String artifactId, String version) { + this.groupId = groupId; + this.artifactId = artifactId; + this.version = version; + } + + /** + * Gets the value of the resourceUri property. + * + * @return possible object is + * {@link String } + */ + public String getResourceUri() { + return resourceUri; + } + + /** + * Sets the value of the resourceUri property. + * + * @param value allowed object is + * {@link String } + */ + public void setResourceUri(String value) { + this.resourceUri = value; + } + + /** + * Gets the value of the groupId property. + * + * @return possible object is + * {@link String } + */ + public String getGroupId() { + return groupId; + } + + /** + * Sets the value of the groupId property. + * + * @param value allowed object is + * {@link String } + */ + public void setGroupId(String value) { + this.groupId = value; + } + + /** + * Gets the value of the artifactId property. + * + * @return possible object is + * {@link String } + */ + public String getArtifactId() { + return artifactId; + } + + /** + * Sets the value of the artifactId property. + * + * @param value allowed object is + * {@link String } + */ + public void setArtifactId(String value) { + this.artifactId = value; + } + + /** + * Gets the value of the version property. + * + * @return possible object is + * {@link String } + */ + public String getVersion() { + return version; + } + + /** + * Sets the value of the version property. + * + * @param value allowed object is + * {@link String } + */ + public void setVersion(String value) { + this.version = value; + } + + /** + * Gets the value of the classifier property. + * + * @return possible object is + * {@link String } + */ + public String getClassifier() { + return classifier; + } + + /** + * Sets the value of the classifier property. + * + * @param value allowed object is + * {@link String } + */ + public void setClassifier(String value) { + this.classifier = value; + } + + /** + * Gets the value of the packaging property. + * + * @return possible object is + * {@link String } + */ + public String getPackaging() { + return packaging; + } + + /** + * Sets the value of the packaging property. + * + * @param value allowed object is + * {@link String } + */ + public void setPackaging(String value) { + this.packaging = value; + } + + /** + * Gets the value of the extension property. + * + * @return possible object is + * {@link String } + */ + public String getExtension() { + return extension; + } + + /** + * Sets the value of the extension property. + * + * @param value allowed object is + * {@link String } + */ + public void setExtension(String value) { + this.extension = value; + } + + /** + * Gets the value of the repoId property. + * + * @return possible object is + * {@link String } + */ + public String getRepoId() { + return repoId; + } + + /** + * Sets the value of the repoId property. + * + * @param value allowed object is + * {@link String } + */ + public void setRepoId(String value) { + this.repoId = value; + } + + /** + * Gets the value of the contextId property. + * + * @return possible object is + * {@link String } + */ + public String getContextId() { + return contextId; + } + + /** + * Sets the value of the contextId property. + * + * @param value allowed object is + * {@link String } + */ + public void setContextId(String value) { + this.contextId = value; + } + + /** + * Gets the value of the pomLink property. + * + * @return possible object is + * {@link String } + */ + public String getPomLink() { + return pomLink; + } + + /** + * Sets the value of the pomLink property. + * + * @param value allowed object is + * {@link String } + */ + public void setPomLink(String value) { + this.pomLink = value; + } + + /** + * Gets the value of the artifactLink property. + * + * @return possible object is + * {@link String } + */ + public String getArtifactLink() { + return artifactLink; + } + + /** + * Sets the value of the artifactLink property. + * + * @param value allowed object is + * {@link String } + */ + public void setArtifactLink(String value) { + this.artifactLink = value; + } + + @Override + public String toString() { + return groupId + ":" + artifactId + ":" + version; + } +} diff --git a/plugins/maven/facade/org/jetbrains/idea/maven/facade/nexus/Endpoint.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/nexus/Endpoint.java similarity index 100% rename from plugins/maven/facade/org/jetbrains/idea/maven/facade/nexus/Endpoint.java rename to plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/nexus/Endpoint.java diff --git a/plugins/maven/facade/org/jetbrains/idea/maven/facade/nexus/ObjectFactory.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/nexus/ObjectFactory.java similarity index 90% rename from plugins/maven/facade/org/jetbrains/idea/maven/facade/nexus/ObjectFactory.java rename to plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/nexus/ObjectFactory.java index cd6d3df8eba7..ac8b88c44420 100644 --- a/plugins/maven/facade/org/jetbrains/idea/maven/facade/nexus/ObjectFactory.java +++ b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/nexus/ObjectFactory.java @@ -16,6 +16,9 @@ */ package org.jetbrains.idea.maven.facade.nexus; +import org.jetbrains.idea.maven.model.MavenArtifactInfo; +import org.jetbrains.idea.maven.model.MavenRepositoryInfo; + import javax.xml.bind.annotation.XmlRegistry; @@ -69,7 +72,7 @@ public class ObjectFactory { } /** - * Create an instance of {@link RepositoryType } + * Create an instance of {@link MavenRepositoryInfo } * */ public RepositoryType createRepositoryType() { @@ -77,7 +80,7 @@ public class ObjectFactory { } /** - * Create an instance of {@link ArtifactType } + * Create an instance of {@link org.jetbrains.idea.maven.model.MavenArtifactInfo } * */ public ArtifactType createArtifactType() { diff --git a/plugins/maven/facade/org/jetbrains/idea/maven/facade/nexus/Repositories.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/nexus/Repositories.java similarity index 97% rename from plugins/maven/facade/org/jetbrains/idea/maven/facade/nexus/Repositories.java rename to plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/nexus/Repositories.java index 178e258a0512..ef5f063d86ad 100644 --- a/plugins/maven/facade/org/jetbrains/idea/maven/facade/nexus/Repositories.java +++ b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/nexus/Repositories.java @@ -16,6 +16,8 @@ */ package org.jetbrains.idea.maven.facade.nexus; +import org.jetbrains.idea.maven.model.MavenRepositoryInfo; + import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; @@ -135,7 +137,7 @@ public class Repositories { * *

* Objects of the following type(s) are allowed in the list - * {@link RepositoryType } + * {@link MavenRepositoryInfo } * * */ diff --git a/plugins/maven/facade/org/jetbrains/idea/maven/facade/nexus/RepositoryMetaData.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/nexus/RepositoryMetaData.java similarity index 100% rename from plugins/maven/facade/org/jetbrains/idea/maven/facade/nexus/RepositoryMetaData.java rename to plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/nexus/RepositoryMetaData.java diff --git a/plugins/maven/facade/org/jetbrains/idea/maven/facade/nexus/RepositoryType.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/nexus/RepositoryType.java similarity index 100% rename from plugins/maven/facade/org/jetbrains/idea/maven/facade/nexus/RepositoryType.java rename to plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/nexus/RepositoryType.java diff --git a/plugins/maven/facade/org/jetbrains/idea/maven/facade/nexus/SearchResult.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/nexus/SearchResult.java similarity index 98% rename from plugins/maven/facade/org/jetbrains/idea/maven/facade/nexus/SearchResult.java rename to plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/nexus/SearchResult.java index 7e1c447f5f3c..acb063297260 100644 --- a/plugins/maven/facade/org/jetbrains/idea/maven/facade/nexus/SearchResult.java +++ b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/nexus/SearchResult.java @@ -16,6 +16,8 @@ */ package org.jetbrains.idea.maven.facade.nexus; +import org.jetbrains.idea.maven.model.MavenArtifactInfo; + import java.math.BigInteger; import java.util.ArrayList; import java.util.List; @@ -238,7 +240,7 @@ public class SearchResult { * *

* Objects of the following type(s) are allowed in the list - * {@link ArtifactType } + * {@link org.jetbrains.idea.maven.model.MavenArtifactInfo } * * */ diff --git a/plugins/maven/facade/org/jetbrains/idea/maven/facade/nexus/SearchResults.java b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/nexus/SearchResults.java similarity index 97% rename from plugins/maven/facade/org/jetbrains/idea/maven/facade/nexus/SearchResults.java rename to plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/nexus/SearchResults.java index 6cfe85d0c162..c2a03fa81e87 100644 --- a/plugins/maven/facade/org/jetbrains/idea/maven/facade/nexus/SearchResults.java +++ b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/nexus/SearchResults.java @@ -16,6 +16,8 @@ */ package org.jetbrains.idea.maven.facade.nexus; +import org.jetbrains.idea.maven.model.MavenArtifactInfo; + import java.math.BigInteger; import java.util.ArrayList; import java.util.List; @@ -217,7 +219,7 @@ public class SearchResults { }) public static class Data { - protected List artifact; + protected ArrayList artifact; /** * Gets the value of the artifact property. @@ -237,7 +239,7 @@ public class SearchResults { * *

* Objects of the following type(s) are allowed in the list - * {@link ArtifactType } + * {@link org.jetbrains.idea.maven.model.MavenArtifactInfo } * * */ diff --git a/plugins/maven/facade/org/jetbrains/idea/maven/facade/nexus/nexus.wadl b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/nexus/nexus.wadl similarity index 100% rename from plugins/maven/facade/org/jetbrains/idea/maven/facade/nexus/nexus.wadl rename to plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/nexus/nexus.wadl diff --git a/plugins/maven/facade/org/jetbrains/idea/maven/facade/nexus/nexus.xsd b/plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/nexus/nexus.xsd similarity index 100% rename from plugins/maven/facade/org/jetbrains/idea/maven/facade/nexus/nexus.xsd rename to plugins/maven/facade-impl/src/org/jetbrains/idea/maven/facade/nexus/nexus.xsd diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/embedder/MavenEmbedderWrapperTest.java b/plugins/maven/facade-impl/test/org/jetbrains/idea/maven/embedder/MavenFacadeEmbedderTest.java similarity index 80% rename from plugins/maven/src/test/java/org/jetbrains/idea/maven/embedder/MavenEmbedderWrapperTest.java rename to plugins/maven/facade-impl/test/org/jetbrains/idea/maven/embedder/MavenFacadeEmbedderTest.java index d1ec715a93ed..c622d30d69bd 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/embedder/MavenEmbedderWrapperTest.java +++ b/plugins/maven/facade-impl/test/org/jetbrains/idea/maven/embedder/MavenFacadeEmbedderTest.java @@ -17,20 +17,24 @@ package org.jetbrains.idea.maven.embedder; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VirtualFile; -import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.handler.ArtifactHandler; -import org.apache.maven.project.MavenProject; import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.jetbrains.idea.maven.MavenImportingTestCase; +import org.jetbrains.idea.maven.facade.MavenEmbedderWrapper; +import org.jetbrains.idea.maven.facade.MavenFacadeManager; +import org.jetbrains.idea.maven.facade.MavenWrapperExecutionResult; +import org.jetbrains.idea.maven.facade.embedder.MavenFacadeEmbedderImpl; +import org.jetbrains.idea.maven.model.MavenId; import org.jetbrains.idea.maven.execution.SoutMavenConsole; -import org.jetbrains.idea.maven.project.MavenId; +import org.jetbrains.idea.maven.model.MavenModel; import java.io.File; import java.util.Arrays; import java.util.Collections; -public class MavenEmbedderWrapperTest extends MavenImportingTestCase { +public class MavenFacadeEmbedderTest extends MavenImportingTestCase { private MavenEmbedderWrapper myEmbedder; + private MavenFacadeEmbedderImpl myEmbedderImpl; @Override protected void setUp() throws Exception { @@ -46,7 +50,9 @@ public class MavenEmbedderWrapperTest extends MavenImportingTestCase { private void initEmbedder() { if (myEmbedder != null) releaseEmbedder(); - myEmbedder = MavenEmbedderWrapper.create(getMavenGeneralSettings()); + + myEmbedderImpl = MavenFacadeEmbedderImpl.create(MavenFacadeManager.convertSettings(getMavenGeneralSettings())); + myEmbedder = new MavenEmbedderWrapper(myEmbedderImpl); } private void releaseEmbedder() { @@ -55,7 +61,13 @@ public class MavenEmbedderWrapperTest extends MavenImportingTestCase { } public void testSettingLocalRepository() throws Exception { - assertEquals(getRepositoryFile(), myEmbedder.getLocalRepositoryFile()); + assertEquals(getRepositoryFile(), myEmbedderImpl.getLocalRepositoryFile()); + + File repo = new File(myDir, "/repo"); + setRepositoryPath(repo.getPath()); + + initEmbedder(); + assertEquals(getRepositoryFile(), myEmbedderImpl.getLocalRepositoryFile()); } public void testReleasingTwice() throws Exception { @@ -73,14 +85,13 @@ public class MavenEmbedderWrapperTest extends MavenImportingTestCase { myEmbedder.customizeForResolve(new SoutMavenConsole(), EMPTY_MAVEN_PROCESS); MavenWrapperExecutionResult result = myEmbedder.execute(myProjectPom, Collections.EMPTY_LIST, Arrays.asList("compile")); + assertNotNull(result.projectData); assertNotNull(new File(getProjectPath(), "target").exists()); + assertOrderedElementsAreEqual(result.unresolvedArtifacts); - assertOrderedElementsAreEqual(result.getExceptions()); - assertOrderedElementsAreEqual(result.getUnresolvedArtifactIds()); - - MavenProject project = result.getMavenProject(); + MavenModel project = result.projectData.mavenModel; assertNotNull(project); - assertEquals("project", project.getArtifactId()); + assertEquals("project", project.getMavenId().getArtifactId()); } public void testResolvingProject() throws Exception { @@ -98,14 +109,13 @@ public class MavenEmbedderWrapperTest extends MavenImportingTestCase { myEmbedder.customizeForResolve(new SoutMavenConsole(), EMPTY_MAVEN_PROCESS); MavenWrapperExecutionResult result = myEmbedder.resolveProject(myProjectPom, Collections.EMPTY_LIST); + assertNotNull(result.projectData); + assertOrderedElementsAreEqual(result.unresolvedArtifacts); - assertOrderedElementsAreEqual(result.getExceptions()); - assertOrderedElementsAreEqual(result.getUnresolvedArtifactIds()); - - MavenProject project = result.getMavenProject(); + MavenModel project = result.projectData.mavenModel; assertNotNull(project); - assertEquals("project", project.getArtifactId()); - assertEquals(1, project.getArtifacts().size()); + assertEquals("project", project.getMavenId().getArtifactId()); + assertEquals(1, project.getDependencies().size()); } public void testResolvingProjectPropertiesInFolders() throws Exception { @@ -116,11 +126,11 @@ public class MavenEmbedderWrapperTest extends MavenImportingTestCase { myEmbedder.customizeForResolve(new SoutMavenConsole(), EMPTY_MAVEN_PROCESS); MavenWrapperExecutionResult result = myEmbedder.resolveProject(myProjectPom, Collections.EMPTY_LIST); - MavenProject project = result.getMavenProject(); + MavenModel project = result.projectData.mavenModel; assertNotNull(project); - assertEquals("project", project.getArtifactId()); + assertEquals("project", project.getMavenId().getArtifactId()); assertPathEquals(myProjectRoot.getPath() + "/target", project.getBuild().getDirectory()); - assertPathEquals(myProjectRoot.getPath() + "/src/main/java", (String)project.getCompileSourceRoots().get(0)); + assertPathEquals(myProjectRoot.getPath() + "/src/main/java", project.getBuild().getSources().get(0)); } public void testResolvingProjectWithExtensions() throws Exception { @@ -152,10 +162,12 @@ public class MavenEmbedderWrapperTest extends MavenImportingTestCase { myEmbedder.customizeForResolve(new SoutMavenConsole(), EMPTY_MAVEN_PROCESS); MavenWrapperExecutionResult result = myEmbedder.resolveProject(myProjectPom, Collections.EMPTY_LIST); - assertOrderedElementsAreEqual(result.getExceptions()); + assertNotNull(result.projectData); + assertOrderedElementsAreEqual(result.unresolvedArtifacts); - assertEquals(1, result.getMavenProject().getArtifacts().size()); - assertEquals("rb.swc", ((Artifact)result.getMavenProject().getArtifacts().iterator().next()).getArtifactHandler().getExtension()); + MavenModel p = result.projectData.mavenModel; + assertEquals(1, p.getDependencies().size()); + assertEquals("rb.swc", p.getDependencies().get(0).getExtension()); } public void testResolvingProjectWithRegisteredExtensions() throws Exception { @@ -163,7 +175,7 @@ public class MavenEmbedderWrapperTest extends MavenImportingTestCase { desc.setRole(ArtifactHandler.ROLE); desc.setRoleHint("foo"); desc.setImplementation(MyArtifactHandler.class.getName()); - myEmbedder.getContainer().addComponentDescriptor(desc); + myEmbedderImpl.getContainer().addComponentDescriptor(desc); createProjectPom("test" + "project" + @@ -182,11 +194,41 @@ public class MavenEmbedderWrapperTest extends MavenImportingTestCase { myEmbedder.customizeForResolve(new SoutMavenConsole(), EMPTY_MAVEN_PROCESS); MavenWrapperExecutionResult result = myEmbedder.resolveProject(myProjectPom, Collections.EMPTY_LIST); - assertOrderedElementsAreEqual(result.getExceptions()); - assertOrderedElementsAreEqual(result.getUnresolvedArtifactIds()); + assertNotNull(result.projectData); + assertOrderedElementsAreEqual(result.unresolvedArtifacts); - assertEquals(1, result.getMavenProject().getArtifacts().size()); - assertEquals("pom", ((Artifact)result.getMavenProject().getArtifacts().iterator().next()).getArtifactHandler().getExtension()); + MavenModel p = result.projectData.mavenModel; + assertEquals(1, p.getDependencies().size()); + assertEquals("pom", p.getDependencies().get(0).getExtension()); + } + public static class MyArtifactHandler implements ArtifactHandler { + public String getExtension() { + return "pom"; + } + + public String getDirectory() { + throw new UnsupportedOperationException(); + } + + public String getClassifier() { + return null; + } + + public String getPackaging() { + return "foo"; + } + + public boolean isIncludesDependencies() { + return false; + } + + public String getLanguage() { + return "java"; + } + + public boolean isAddedToClasspath() { + return true; + } } public void testUnresolvedArtifacts() throws Exception { @@ -205,8 +247,8 @@ public class MavenEmbedderWrapperTest extends MavenImportingTestCase { myEmbedder.customizeForResolve(new SoutMavenConsole(), EMPTY_MAVEN_PROCESS); MavenWrapperExecutionResult result = myEmbedder.resolveProject(myProjectPom, Collections.EMPTY_LIST); - assertOrderedElementsAreEqual(result.getExceptions()); - assertOrderedElementsAreEqual(result.getUnresolvedArtifactIds(), new MavenId("fff", "zzz", "666")); + assertNotNull(result.projectData); + assertOrderedElementsAreEqual(result.unresolvedArtifacts, new MavenId("fff", "zzz", "666")); } public void testUnresolvedSystemArtifacts() throws Exception { @@ -227,8 +269,8 @@ public class MavenEmbedderWrapperTest extends MavenImportingTestCase { myEmbedder.customizeForResolve(new SoutMavenConsole(), EMPTY_MAVEN_PROCESS); MavenWrapperExecutionResult result = myEmbedder.resolveProject(myProjectPom, Collections.EMPTY_LIST); - assertOrderedElementsAreEqual(result.getExceptions()); - assertOrderedElementsAreEqual(result.getUnresolvedArtifactIds(), new MavenId("fff", "zzz", "666")); + assertNotNull(result.projectData); + assertOrderedElementsAreEqual(result.unresolvedArtifacts, new MavenId("fff", "zzz", "666")); } public void testDependencyWithUnresolvedParent() throws Exception { @@ -280,8 +322,8 @@ public class MavenEmbedderWrapperTest extends MavenImportingTestCase { myEmbedder.customizeForResolve(new SoutMavenConsole(), EMPTY_MAVEN_PROCESS); MavenWrapperExecutionResult result = myEmbedder.resolveProject(myProjectPom, Collections.EMPTY_LIST); - assertOrderedElementsAreEqual(result.getExceptions()); - assertOrderedElementsAreEqual(result.getUnresolvedArtifactIds(), new MavenId("test", "foo-parent", "1")); + assertNotNull(result.projectData); + assertOrderedElementsAreEqual(result.unresolvedArtifacts, new MavenId("test", "foo-parent", "1")); } public void testUnresolvedSystemArtifactsWithoutPath() throws Exception { @@ -302,37 +344,7 @@ public class MavenEmbedderWrapperTest extends MavenImportingTestCase { myEmbedder.customizeForResolve(new SoutMavenConsole(), EMPTY_MAVEN_PROCESS); MavenWrapperExecutionResult result = myEmbedder.resolveProject(myProjectPom, Collections.EMPTY_LIST); - assertOrderedElementsAreEqual(result.getExceptions()); - assertOrderedElementsAreEqual(result.getUnresolvedArtifactIds(), new MavenId("fff", "zzz", "666")); - } - - public static class MyArtifactHandler implements ArtifactHandler { - public String getExtension() { - return "pom"; - } - - public String getDirectory() { - throw new UnsupportedOperationException(); - } - - public String getClassifier() { - return null; - } - - public String getPackaging() { - return "foo"; - } - - public boolean isIncludesDependencies() { - return false; - } - - public String getLanguage() { - return "java"; - } - - public boolean isAddedToClasspath() { - return true; - } + assertNotNull(result); + assertOrderedElementsAreEqual(result.unresolvedArtifacts, new MavenId("fff", "zzz", "666")); } } diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/NexusIndexerTest.java b/plugins/maven/facade-impl/test/org/jetbrains/idea/maven/embedder/NexusIndexerTest.java similarity index 91% rename from plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/NexusIndexerTest.java rename to plugins/maven/facade-impl/test/org/jetbrains/idea/maven/embedder/NexusIndexerTest.java index 4f3c1f68ca46..e2eaad4c3edd 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/NexusIndexerTest.java +++ b/plugins/maven/facade-impl/test/org/jetbrains/idea/maven/embedder/NexusIndexerTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.idea.maven.indices; +package org.jetbrains.idea.maven.embedder; import org.apache.lucene.document.Document; import org.apache.lucene.index.IndexReader; @@ -22,7 +22,11 @@ import org.apache.lucene.search.*; import org.apache.maven.artifact.manager.WagonManager; import org.apache.maven.wagon.events.TransferEvent; import org.apache.maven.wagon.events.TransferListener; -import org.jetbrains.idea.maven.embedder.MavenEmbedderWrapper; +import org.jetbrains.idea.maven.MavenCustomRepositoryHelper; +import org.jetbrains.idea.maven.facade.MavenFacadeManager; +import org.jetbrains.idea.maven.facade.embedder.MavenFacadeEmbedderImpl; +import org.jetbrains.idea.maven.facade.embedder.MavenIndexFetcher; +import org.jetbrains.idea.maven.indices.MavenIndicesTestCase; import org.sonatype.nexus.index.*; import org.sonatype.nexus.index.context.IndexingContext; import org.sonatype.nexus.index.updater.IndexUpdateRequest; @@ -35,8 +39,8 @@ import java.util.Collection; import java.util.List; public class NexusIndexerTest extends MavenIndicesTestCase { + private MavenFacadeEmbedderImpl myEmbedder; private MavenCustomRepositoryHelper myRepositoryHelper; - private MavenEmbedderWrapper myEmbedder; private NexusIndexer myIndexer; private IndexUpdater myUpdater; private File myIndexDir; @@ -46,7 +50,7 @@ public class NexusIndexerTest extends MavenIndicesTestCase { super.setUp(); myRepositoryHelper = new MavenCustomRepositoryHelper(myDir, "local1_index", "local1", "remote"); - myEmbedder = MavenEmbedderWrapper.create(getMavenGeneralSettings()); + myEmbedder = MavenFacadeEmbedderImpl.create(MavenFacadeManager.convertSettings(getMavenGeneralSettings())); myIndexer = myEmbedder.getComponent(NexusIndexer.class); myUpdater = myEmbedder.getComponent(IndexUpdater.class); @@ -153,7 +157,7 @@ public class NexusIndexerTest extends MavenIndicesTestCase { myIndexer.removeIndexingContext(i1, false); myIndexer.removeIndexingContext(i2, false); - + addContext("id", new File(myIndexDir, "one"), null, null); addContext("id", new File(myIndexDir, "two"), null, null); } @@ -171,13 +175,13 @@ public class NexusIndexerTest extends MavenIndicesTestCase { private IndexingContext addContext(String id, File indexDir, File repoDir, String repoUrl) throws Exception { return myIndexer.addIndexingContext( - id, - id, - repoDir, - indexDir, - repoUrl, - null, // repo update url - NexusIndexer.FULL_INDEX); + id, + id, + repoDir, + indexDir, + repoUrl, + null, // repo update url + NexusIndexer.FULL_INDEX); } private void assertSearchWorks() throws IOException { diff --git a/plugins/maven/facade/org/jetbrains/idea/maven/facade/nexus/ArtifactType.java b/plugins/maven/facade/org/jetbrains/idea/maven/facade/nexus/ArtifactType.java deleted file mode 100644 index 70ff84eaf0cf..000000000000 --- a/plugins/maven/facade/org/jetbrains/idea/maven/facade/nexus/ArtifactType.java +++ /dev/null @@ -1,371 +0,0 @@ - -/* - * Copyright 2000-2010 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.idea.maven.facade.nexus; - -import com.intellij.util.xmlb.annotations.Transient; - -import javax.xml.bind.annotation.*; -import java.io.Serializable; - - -/** - *

Java class for artifactType complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="artifactType">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <element name="resourceUri" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *         <element name="groupId" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *         <element name="artifactId" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *         <element name="version" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *         <element name="classifier" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *         <element name="packaging" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *         <element name="extension" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *         <element name="repoId" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *         <element name="contextId" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *         <element name="pomLink" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *         <element name="artifactLink" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *       </sequence>
- *     </restriction>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "artifactType", propOrder = { - "resourceUri", - "groupId", - "artifactId", - "version", - "classifier", - "packaging", - "extension", - "repoId", - "contextId", - "pomLink", - "artifactLink" -}) -public class ArtifactType implements Serializable { - - @XmlElement(required = true) - protected String resourceUri; - @XmlElement(required = true) - protected String groupId; - @XmlElement(required = true) - protected String artifactId; - @XmlElement(required = true) - protected String version; - @XmlElement(required = true) - protected String classifier; - @XmlElement(required = true) - protected String packaging; - @XmlElement(required = true) - protected String extension; - @XmlElement(required = true) - protected String repoId; - @XmlElement(required = true) - protected String contextId; - @XmlElement(required = true) - protected String pomLink; - @XmlElement(required = true) - protected String artifactLink; - - public ArtifactType() { - - } - - public ArtifactType(String groupId, String artifactId, String version) { - this.groupId = groupId; - this.artifactId = artifactId; - this.version = version; - } - - /** - * Gets the value of the resourceUri property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getResourceUri() { - return resourceUri; - } - - /** - * Sets the value of the resourceUri property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setResourceUri(String value) { - this.resourceUri = value; - } - - /** - * Gets the value of the groupId property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getGroupId() { - return groupId; - } - - /** - * Sets the value of the groupId property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setGroupId(String value) { - this.groupId = value; - } - - /** - * Gets the value of the artifactId property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getArtifactId() { - return artifactId; - } - - /** - * Sets the value of the artifactId property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setArtifactId(String value) { - this.artifactId = value; - } - - /** - * Gets the value of the version property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getVersion() { - return version; - } - - /** - * Sets the value of the version property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setVersion(String value) { - this.version = value; - } - - /** - * Gets the value of the classifier property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getClassifier() { - return classifier; - } - - /** - * Sets the value of the classifier property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setClassifier(String value) { - this.classifier = value; - } - - /** - * Gets the value of the packaging property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getPackaging() { - return packaging; - } - - /** - * Sets the value of the packaging property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setPackaging(String value) { - this.packaging = value; - } - - /** - * Gets the value of the extension property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getExtension() { - return extension; - } - - /** - * Sets the value of the extension property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setExtension(String value) { - this.extension = value; - } - - /** - * Gets the value of the repoId property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getRepoId() { - return repoId; - } - - /** - * Sets the value of the repoId property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setRepoId(String value) { - this.repoId = value; - } - - /** - * Gets the value of the contextId property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getContextId() { - return contextId; - } - - /** - * Sets the value of the contextId property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setContextId(String value) { - this.contextId = value; - } - - /** - * Gets the value of the pomLink property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getPomLink() { - return pomLink; - } - - /** - * Sets the value of the pomLink property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setPomLink(String value) { - this.pomLink = value; - } - - /** - * Gets the value of the artifactLink property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getArtifactLink() { - return artifactLink; - } - - /** - * Sets the value of the artifactLink property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setArtifactLink(String value) { - this.artifactLink = value; - } - - @Override - public String toString() { - return groupId +":"+artifactId+":"+version; - } -} diff --git a/plugins/maven/facade/org/jetbrains/idea/maven/facade/remote/MavenFacade.java b/plugins/maven/facade/org/jetbrains/idea/maven/facade/remote/MavenFacade.java deleted file mode 100644 index 77f698a89f4f..000000000000 --- a/plugins/maven/facade/org/jetbrains/idea/maven/facade/remote/MavenFacade.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright 2000-2010 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.idea.maven.facade.remote; - -import org.jetbrains.annotations.Nullable; -import org.jetbrains.idea.maven.facade.nexus.ArtifactType; -import org.jetbrains.idea.maven.facade.nexus.RepositoryType; - -import java.io.Serializable; -import java.rmi.Remote; -import java.rmi.RemoteException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * @author Gregory.Shrago - */ -public interface MavenFacade extends Remote { - - List getRepositories(String nexusUrl) throws RemoteException; - - @Nullable - List findArtifacts(ArtifactType template, String nexusUrl) throws RemoteException; - - Map> resolveDependencies(List artifacts) throws RemoteException; - - void setTransferListener(RemoteTransferListener listener) throws RemoteException; - - void setMavenSettings(MavenFacadeSettings settings) throws RemoteException; - - class MavenFacadeSettings implements Serializable { - private Repository myLocalRepository; - private final List myRemoteRepositories = new ArrayList(); - - public Repository getLocalRepository() { - return myLocalRepository; - } - - public void setLocalRepository(Repository localRepository) { - myLocalRepository = localRepository; - } - - public List getRemoteRepositories() { - return myRemoteRepositories; - } - } - - class Repository implements Serializable { - private String myId; - private String myUrl; - private String myLayout; - - public Repository(String id, String url, String layout) { - myUrl = url; - myId = id; - myLayout = layout; - } - - public String getId() { - return myId; - } - - public void setId(String id) { - myId = id; - } - - public String getUrl() { - return myUrl; - } - - public void setUrl(String url) { - myUrl = url; - } - - public String getLayout() { - return myLayout; - } - - public void setLayout(String layout) { - myLayout = layout; - } - } - -} diff --git a/plugins/maven/facade/org/jetbrains/idea/maven/facade/remote/impl/MavenFacadeImpl.java b/plugins/maven/facade/org/jetbrains/idea/maven/facade/remote/impl/MavenFacadeImpl.java deleted file mode 100644 index 90389f53cf7d..000000000000 --- a/plugins/maven/facade/org/jetbrains/idea/maven/facade/remote/impl/MavenFacadeImpl.java +++ /dev/null @@ -1,393 +0,0 @@ -/* - * Copyright 2000-2010 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.idea.maven.facade.remote.impl; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.DefaultArtifact; -import org.apache.maven.artifact.factory.ArtifactFactory; -import org.apache.maven.artifact.manager.WagonManager; -import org.apache.maven.artifact.metadata.ArtifactMetadataSource; -import org.apache.maven.artifact.repository.ArtifactRepository; -import org.apache.maven.artifact.repository.DefaultArtifactRepository; -import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; -import org.apache.maven.artifact.resolver.*; -import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter; -import org.apache.maven.artifact.versioning.VersionRange; -import org.apache.maven.settings.MavenSettingsBuilder; -import org.apache.maven.settings.RuntimeInfo; -import org.apache.maven.settings.Settings; -import org.apache.maven.artifact.versioning.ArtifactVersion; -import org.apache.maven.wagon.events.TransferEvent; -import org.apache.maven.wagon.events.TransferListener; -import org.codehaus.classworlds.ClassWorld; -import org.codehaus.plexus.DefaultPlexusContainer; -import org.codehaus.plexus.PlexusContainerException; -import org.codehaus.plexus.component.repository.exception.ComponentLookupException; -import org.codehaus.plexus.util.xml.pull.XmlPullParserException; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.idea.maven.facade.nexus.ArtifactType; -import org.jetbrains.idea.maven.facade.nexus.Endpoint; -import org.jetbrains.idea.maven.facade.nexus.RepositoryType; -import org.jetbrains.idea.maven.facade.nexus.SearchResults; -import org.jetbrains.idea.maven.facade.remote.MavenFacade; -import org.jetbrains.idea.maven.facade.remote.RemoteTransferListener; - -import java.io.IOException; -import java.math.BigInteger; -import java.net.MalformedURLException; -import java.rmi.RemoteException; -import java.util.*; - -/** - * @author Gregory.Shrago - */ -public class MavenFacadeImpl extends RemoteImpl implements MavenFacade { - - private static final DefaultPlexusContainer ourContainer = initializeMaven(); - private MavenFacadeSettings mySettings; - - public static DefaultPlexusContainer initializeMaven() { - DefaultPlexusContainer container; - try { - container = new DefaultPlexusContainer(); - } - catch (RuntimeException e) { - String s = "Cannot initialize Maven. Please make sure that your IDEA installation is correct and has no old libraries."; - throw new RuntimeException(s, e); - } - - container.setClassWorld(new ClassWorld("plexus.core", Thread.currentThread().getContextClassLoader())); -// CustomLoggerManager loggerManager = new CustomLoggerManager(generalSettings.getLoggingLevel()); -// container.setLoggerManager(loggerManager); - - try { - container.initialize(); - container.start(); - } - catch (PlexusContainerException e) { - throw new RuntimeException(e); - } - -// System.setProperty("maven.home", "<...>"); -// System.setProperty(MavenSettingsBuilder.ALT_GLOBAL_SETTINGS_XML_LOCATION, "<..>"); - - Settings settings = null; - - try { - MavenSettingsBuilder builder = (MavenSettingsBuilder)container.lookup(MavenSettingsBuilder.ROLE); -// File userSettingsFile = generalSettings.getEffectiveUserSettingsIoFile(); -// if (userSettingsFile != null && userSettingsFile.exists() && !userSettingsFile.isDirectory()) { -// settings = builder.buildSettings(userSettingsFile, false); -// } - if (settings == null) { - settings = builder.buildSettings(); - } - } - catch (ComponentLookupException e) { - e.printStackTrace(); - } - catch (IOException e) { - e.printStackTrace(); - } - catch (XmlPullParserException e) { - e.printStackTrace(); - } - - if (settings == null) { - settings = new Settings(); - } - -// settings.setLocalRepository("<...>"); - - settings.setOffline(false); - settings.setInteractiveMode(false); - settings.setUsePluginRegistry(false); - - RuntimeInfo runtimeInfo = new RuntimeInfo(settings); -// runtimeInfo.setPluginUpdateOverride(generalSettings.getPluginUpdatePolicy() == MavenExecutionOptions.PluginUpdatePolicy.UPDATE); - settings.setRuntimeInfo(runtimeInfo); - - return container; - - } - - public List getRepositories(String nexusUrl) throws RemoteException { - try { - return new Endpoint.Repositories(nexusUrl).getRepolistAsRepositories().getData().getRepositoriesItem(); - } - catch (Exception ex) { - handleException(ex); - throw new AssertionError(); - } - } - - @Nullable - public List findArtifacts(ArtifactType template, String nexusUrl) throws RemoteException { - try { - SearchResults results = new Endpoint.DataIndex(nexusUrl) - .getArtifactlistAsSearchResults(null, template.getGroupId(), template.getArtifactId(), template.getVersion(), - template.getClassifier(), template.getContextId()); - final boolean canTrySwitchGAV = template.getArtifactId() == null && template.getGroupId() != null; - final boolean tooManyResults = results.isTooManyResults(); - if (canTrySwitchGAV && (tooManyResults || BigInteger.ZERO.equals(results.getTotalCount()))) { - results = new Endpoint.DataIndex(nexusUrl) - .getArtifactlistAsSearchResults(null, null, template.getGroupId(), template.getVersion(), - template.getClassifier(), template.getContextId()); - } - if (tooManyResults || results.isTooManyResults()) return null; - return new ArrayList(results.getData().getArtifact()); - } - catch (Exception ex) { - handleException(ex); - throw new AssertionError(); - } - } - - private void addMissingVersions(final Map result) { - try { - final ArtifactMetadataSource metadataSource = (ArtifactMetadataSource)ourContainer.lookup(ArtifactMetadataSource.ROLE); - final ArtifactFactory artifactFactory = (ArtifactFactory)ourContainer.lookup(ArtifactFactory.ROLE); - final ArtifactRepository localRepo = getRepository(mySettings.getLocalRepository()); - final List remoteRepos = new ArrayList(); - for (Repository repository : mySettings.getRemoteRepositories()) { - remoteRepos.add(getRepository(repository)); - } - final HashSet visitedIds = new HashSet(); - for (ArtifactType artifactType : result.values()) { - if (!visitedIds.add(artifactType.getGroupId()+":"+artifactType.getArtifactId())) continue; - if (artifactType.getPackaging() == null) continue; - final Artifact artifact = createArtifact(artifactFactory, artifactType); - try { - final List list = metadataSource.retrieveAvailableVersions(artifact, localRepo, remoteRepos); - for (ArtifactVersion version : list) { - final String coord = artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + version; - if (!result.containsKey(coord)) { - final ArtifactType type = new ArtifactType(artifactType.getGroupId(), artifactType.getArtifactId(), version.toString()); - type.setPackaging(artifact.getType()); - result.put(coord, type); - } - } - } - catch (Exception ex) { - ex.printStackTrace(); - } - } - } - catch (Exception e) { - handleException(e); - throw new AssertionError(); - } - } - - public Map> resolveDependencies(List artifacts) throws RemoteException { - try { - return resolveDependenciesInner(artifacts); - } - catch (Exception e) { - handleException(e); - throw new AssertionError(); - } - } - - public void setTransferListener(final RemoteTransferListener listener) throws RemoteException { - try { - final WagonManager wagonManager = (WagonManager)ourContainer.lookup(WagonManager.ROLE); - if (listener == null) { - wagonManager.setDownloadMonitor(null); - return; - } - wagonManager.setDownloadMonitor(new TransferListener() { - public void transferInitiated(TransferEvent transferEvent) { - try { - listener.transferInitiated(convert(transferEvent)); - } - catch (RemoteException ignored) { } - } - - public void transferStarted(TransferEvent transferEvent) { - try { - listener.transferStarted(convert(transferEvent)); - } - catch (RemoteException ignored) { - } - } - - public void transferProgress(TransferEvent transferEvent, byte[] bytes, int i) { - try { - listener.transferProgress(convert(transferEvent), i); - } - catch (RemoteException ignored) { - } - } - - public void transferCompleted(TransferEvent transferEvent) { - try { - listener.transferCompleted(convert(transferEvent)); - } - catch (RemoteException ignored) { - } - } - - public void transferError(TransferEvent transferEvent) { - try { - listener.transferError(convert(transferEvent)); - } - catch (RemoteException ignored) { - } - } - - public void debug(String s) { - try { - listener.debug(s); - } - catch (RemoteException ignored) { - } - } - }); - } - catch (Exception e) { - handleException(e); - throw new AssertionError(); - } - } - - public void setMavenSettings(MavenFacadeSettings settings) throws RemoteException { - mySettings = settings; - } - - private static RemoteTransferListener.TransferEvent convert(TransferEvent transferEvent) { - final RemoteTransferListener.TransferEvent.EventType et; - switch (transferEvent.getEventType()) { - case TransferEvent.TRANSFER_INITIATED: et = RemoteTransferListener.TransferEvent.EventType.INITIATED; break; - case TransferEvent.TRANSFER_STARTED: et = RemoteTransferListener.TransferEvent.EventType.STARTED; break; - case TransferEvent.TRANSFER_PROGRESS: et = RemoteTransferListener.TransferEvent.EventType.PROGRESS; break; - case TransferEvent.TRANSFER_COMPLETED: et = RemoteTransferListener.TransferEvent.EventType.COMPLETED; break; - case TransferEvent.TRANSFER_ERROR: et = RemoteTransferListener.TransferEvent.EventType.ERROR; break; - default: throw new AssertionError(transferEvent.getEventType()); - } - final RemoteTransferListener.TransferEvent.RequestType reqType = transferEvent.getRequestType() == TransferEvent.REQUEST_GET - ? RemoteTransferListener.TransferEvent.RequestType.GET - : RemoteTransferListener.TransferEvent.RequestType.PUT; - final RemoteTransferListener.Resource resource = new RemoteTransferListener.Resource(transferEvent.getResource().getName(), - transferEvent.getResource().getLastModified(), - transferEvent.getResource().getContentLength()); - return new RemoteTransferListener.TransferEvent(transferEvent.getLocalFile(), et, reqType, resource, transferEvent.getException(), transferEvent.getWagon().getRepository().getUrl()); - } - - - private Map> resolveDependenciesInner(List artifactsToResolve) throws Exception { - final ArtifactResolver resolver = (ArtifactResolver)ourContainer.lookup(ArtifactResolver.ROLE); - final ArtifactFactory artifactFactory = (ArtifactFactory)ourContainer.lookup(ArtifactFactory.ROLE); - final ArtifactMetadataSource metadataSource = (ArtifactMetadataSource)ourContainer.lookup(ArtifactMetadataSource.ROLE); - - final ArtifactRepository localRepo = getRepository(mySettings.getLocalRepository()); - final List remoteRepos = new ArrayList(); - for (Repository repository : mySettings.getRemoteRepositories()) { - remoteRepos.add(getRepository(repository)); - } - - - final Artifact project = artifactFactory.createBuildArtifact("local", "project", "1.0", "pom"); - final Set toResolve = new HashSet(); - for (ArtifactType template : artifactsToResolve) { - toResolve.add(createArtifact(artifactFactory, template)); - } - - final Map> resultMap = new HashMap>(); - for (Artifact artifact : toResolve) { - try { - final ArtifactResolutionResult result = resolver.resolveTransitively( - Collections.singleton(artifact), project, Collections.EMPTY_MAP, localRepo, remoteRepos, - metadataSource, new ScopeArtifactFilter(DefaultArtifact.SCOPE_RUNTIME)); - resultMap.put(getCoordinate(artifact), toArtifactTypeList(result.getArtifacts())); - } - catch (MultipleArtifactsNotFoundException e) { - resultMap.put(getCoordinate(artifact), toArtifactTypeList(e.getResolvedArtifacts())); - //System.out.println("Missing: -------------------"); - //toArtifactTypeList(e.getMissingArtifacts()); - } - catch (ArtifactResolutionException e) { - //throw e; - } - catch (ArtifactNotFoundException e) { - //throw e; - //System.out.println("Missing: -------------------"); - //toArtifactTypeList(Collections.singletonList(e.getArtifact())); - } - } - return resultMap; - } - - private Artifact createArtifact(ArtifactFactory artifactFactory, ArtifactType template) { - return artifactFactory.createDependencyArtifact( - template.getGroupId(), - template.getArtifactId(), - template.getVersion() == null? null : VersionRange.createFromVersion(template.getVersion()), - template.getPackaging(), - null, - "runtime"); - } - - private static ArtifactRepository getRepository(Repository r) throws ComponentLookupException { - final ArtifactRepositoryLayout repoLayout = (ArtifactRepositoryLayout)ourContainer.lookup(ArtifactRepositoryLayout.ROLE, r.getLayout()); - return new DefaultArtifactRepository(r.getId(), r.getUrl(), repoLayout); - } - - private static Map> toArtifactTypeMap(Collection toResolve, Collection resolvedArtifacts) { - final Map> result = new HashMap>(); - final Map idMap = new HashMap(); - for (Artifact artifact : toResolve) { - idMap.put(artifact.getId(), getCoordinate(artifact)); - result.put(getCoordinate(artifact), new ArrayList()); - } - for (Artifact artifact : resolvedArtifacts) { - List list = null; - for (String s : artifact.getDependencyTrail()) { - list = result.get(idMap.get(s)); - if (list != null) { - list.add(toArtifactType(artifact)); - break; - } - } - if (list == null) { - throw new AssertionError(getCoordinate(artifact)); - } - } - return result; - } - - private static String getCoordinate(Artifact artifact) { - return artifact.getGroupId()+":"+artifact.getArtifactId()+":"+artifact.getVersion(); - } - - private static List toArtifactTypeList(Collection artifacts) throws MalformedURLException { - final ArrayList result = new ArrayList(artifacts.size()); - for (Artifact artifact : artifacts) { - result.add(toArtifactType(artifact)); - } - return result; - } - - private static ArtifactType toArtifactType(Artifact artifact) { - final ArtifactType type = new ArtifactType(); - type.setGroupId(artifact.getGroupId()); - type.setArtifactId(artifact.getArtifactId()); - type.setVersion(artifact.getVersion()); - type.setClassifier(artifact.getClassifier()); - type.setResourceUri(artifact.getFile().toURI().toASCIIString()); - return type; - } -} diff --git a/plugins/maven/facade/org/jetbrains/idea/maven/facade/remote/impl/RemoteImpl.java b/plugins/maven/facade/org/jetbrains/idea/maven/facade/remote/impl/RemoteImpl.java deleted file mode 100644 index 4f5b944710cb..000000000000 --- a/plugins/maven/facade/org/jetbrains/idea/maven/facade/remote/impl/RemoteImpl.java +++ /dev/null @@ -1,95 +0,0 @@ -package org.jetbrains.idea.maven.facade.remote.impl; - -import com.intellij.util.containers.ContainerUtil; - -import java.lang.ref.WeakReference; -import java.rmi.Remote; -import java.rmi.RemoteException; -import java.rmi.server.UnicastRemoteObject; -import java.rmi.server.Unreferenced; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * @author Gregory.Shrago - */ -public class RemoteImpl implements Remote, Unreferenced { - private final Map myChildren = new ConcurrentHashMap(); - private final WeakReference myWeakRef; - private RemoteImpl myParent; - - public RemoteImpl() { - myWeakRef = new WeakReference(this); - } - - public WeakReference getWeakRef() { - return myWeakRef; - } - - protected T export(final T child) throws RemoteException { - if (child == null) return null; - final T result = (T)UnicastRemoteObject.exportObject(child, 0); - myChildren.put((RemoteImpl)child, result); - ((RemoteImpl)child).myParent = this; - return result; - } - - protected T export2(final T child) throws RemoteException { - return export(child); - } - - public void unexportChildren() throws RemoteException { - final ArrayList childrenRefs = new ArrayList(myChildren.keySet()); - myChildren.clear(); - for (RemoteImpl child : childrenRefs) { - child.unreferenced(); - } - } - - protected void unexportChildren(Collection> children) throws RemoteException { - if (children.isEmpty()) return; - final ArrayList list = new ArrayList(children.size()); - for (WeakReference child : children) { - ContainerUtil.addIfNotNull(child.get(), list); - } - myChildren.keySet().removeAll(list); - for (RemoteImpl child : list) { - child.unreferenced(); - } - } - - protected static void handleException(Exception e) { - Throwable cause = e; - while (cause.getCause() != null) { - cause = cause.getCause(); - } - if (!cause.getClass().getName().startsWith("java")) { - final Throwable replaceWith = new RuntimeException(cause.toString()); - replaceWith.setStackTrace(cause.getStackTrace()); - cause = replaceWith; - } - throw cause instanceof RuntimeException ? (RuntimeException)cause : new RuntimeException(cause); - } - - public Object wrapIfNeeded(Object o) throws RemoteException { - if (o == null) return o; - if (o.getClass().getClassLoader() == null || - o.getClass().getName().startsWith("com.intellij")) return o; - return o.toString(); - } - - public void unreferenced() { - if (myParent != null) { - myParent.myChildren.remove(this); - myParent = null; - try { - unexportChildren(); - UnicastRemoteObject.unexportObject(this, false); - } - catch (RemoteException e) { - } - } - } -} diff --git a/plugins/maven/facade/org/jetbrains/idea/maven/facade/remote/impl/RemoteTransferListenerImpl.java b/plugins/maven/facade/org/jetbrains/idea/maven/facade/remote/impl/RemoteTransferListenerImpl.java deleted file mode 100644 index d418cc5ed90d..000000000000 --- a/plugins/maven/facade/org/jetbrains/idea/maven/facade/remote/impl/RemoteTransferListenerImpl.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.jetbrains.idea.maven.facade.remote.impl; - -import org.jetbrains.idea.maven.facade.remote.RemoteTransferListener; - -/** - * @author Gregory.Shrago - */ -public class RemoteTransferListenerImpl extends RemoteImpl implements RemoteTransferListener { - - public void transferInitiated(TransferEvent transferEvent) { - } - - public void transferStarted(TransferEvent transferEvent) { - } - - public void transferProgress(TransferEvent transferEvent, int length) { - } - - public void transferCompleted(TransferEvent transferEvent) { - } - - public void transferError(TransferEvent transferEvent) { - } - - public void debug(String s) { - } - -} diff --git a/plugins/maven/lib/maven-embedder-1.0-SNAPSHOT.jar b/plugins/maven/lib/maven-embedder-1.0-SNAPSHOT.jar deleted file mode 100644 index 0670771f4a8d..000000000000 Binary files a/plugins/maven/lib/maven-embedder-1.0-SNAPSHOT.jar and /dev/null differ diff --git a/plugins/maven/maven-facade.iml b/plugins/maven/maven-facade.iml deleted file mode 100644 index c7e166df27e9..000000000000 --- a/plugins/maven/maven-facade.iml +++ /dev/null @@ -1,103 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/maven/maven-plugin.iml b/plugins/maven/maven-plugin.iml deleted file mode 100644 index 3e0fe892aeb3..000000000000 --- a/plugins/maven/maven-plugin.iml +++ /dev/null @@ -1,78 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/maven/maven-plugin.ipr b/plugins/maven/maven-plugin.ipr deleted file mode 100644 index d2c4eae9a682..000000000000 --- a/plugins/maven/maven-plugin.ipr +++ /dev/null @@ -1,445 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/maven/maven.iml b/plugins/maven/maven.iml index 714f1b53190b..276526c316bf 100644 --- a/plugins/maven/maven.iml +++ b/plugins/maven/maven.iml @@ -10,110 +10,12 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + @@ -121,14 +23,13 @@ - + + - - diff --git a/plugins/maven/src/main/java/org/apache/maven/project/JBMavenProjectHelper.java b/plugins/maven/src/main/java/org/apache/maven/project/JBMavenProjectHelper.java deleted file mode 100644 index b771720203a7..000000000000 --- a/plugins/maven/src/main/java/org/apache/maven/project/JBMavenProjectHelper.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.maven.project; - -import java.util.List; - -public class JBMavenProjectHelper { - public static void setSourceRoots(MavenProject project, - List compileSourceRoots, - List testCompileSourceRoots, - List scriptSourceRoots) { - project.setCompileSourceRoots(compileSourceRoots); - project.setTestCompileSourceRoots(testCompileSourceRoots); - project.setScriptSourceRoots(scriptSourceRoots); - } -} diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/compiler/MavenResourceCompiler.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/compiler/MavenResourceCompiler.java index f674f9c1444e..55e25132e819 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/compiler/MavenResourceCompiler.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/compiler/MavenResourceCompiler.java @@ -44,7 +44,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.idea.maven.dom.MavenPropertyResolver; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.project.MavenProjectsManager; -import org.jetbrains.idea.maven.project.MavenResource; +import org.jetbrains.idea.maven.model.MavenResource; import org.jetbrains.idea.maven.utils.MavenJDOMUtil; import org.jetbrains.idea.maven.utils.MavenLog; import org.jetbrains.idea.maven.utils.MavenUtil; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomProjectProcessorUtils.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomProjectProcessorUtils.java index 72fe08125678..75d2cc0fae74 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomProjectProcessorUtils.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomProjectProcessorUtils.java @@ -26,6 +26,7 @@ import com.intellij.util.xml.DomUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.maven.dom.model.*; +import org.jetbrains.idea.maven.model.MavenId; import org.jetbrains.idea.maven.project.*; import org.jetbrains.idea.maven.utils.MavenUtil; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomUtil.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomUtil.java index 48315b78a55b..1bf3b6815219 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomUtil.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomUtil.java @@ -41,8 +41,11 @@ import com.intellij.util.xml.reflect.DomCollectionChildDescription; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.maven.dom.model.*; +import org.jetbrains.idea.maven.model.MavenArtifact; +import org.jetbrains.idea.maven.model.MavenConstants; +import org.jetbrains.idea.maven.model.MavenId; +import org.jetbrains.idea.maven.model.MavenResource; import org.jetbrains.idea.maven.project.*; -import org.jetbrains.idea.maven.utils.MavenConstants; import org.jetbrains.idea.maven.utils.MavenLog; import org.jetbrains.idea.maven.vfs.MavenPropertiesVirtualFileSystem; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenPropertyResolver.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenPropertyResolver.java index 385ac14d8797..060067ba2cda 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenPropertyResolver.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenPropertyResolver.java @@ -18,16 +18,13 @@ package org.jetbrains.idea.maven.dom; import com.intellij.openapi.module.Module; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.xml.XmlTag; -import org.apache.commons.beanutils.BeanAccessLanguageException; -import org.apache.commons.beanutils.BeanUtils; import org.jetbrains.idea.maven.dom.model.MavenDomProfile; import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; import org.jetbrains.idea.maven.dom.model.MavenDomProperties; -import org.jetbrains.idea.maven.embedder.MavenEmbedderWrapper; +import org.jetbrains.idea.maven.facade.MavenFacadeUtil; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.project.MavenProjectsManager; -import java.lang.reflect.InvocationTargetException; import java.util.Collection; import java.util.Properties; import java.util.Stack; @@ -137,7 +134,7 @@ public class MavenPropertyResolver { private static String doResolveProperty(String propName, MavenProject project, Properties additionalProperties) { String result; - result = MavenEmbedderWrapper.collectSystemProperties().getProperty(propName); + result = MavenFacadeUtil.collectSystemProperties().getProperty(propName); if (result != null) return result; if (propName.startsWith("project.") || propName.startsWith("pom.")) { @@ -151,19 +148,7 @@ public class MavenPropertyResolver { if (propName.equals("basedir")) return project.getDirectory(); - try { - result = BeanUtils.getNestedProperty(project.getMavenModel(), propName); - } - catch (IllegalAccessException e) { - } - catch (BeanAccessLanguageException e) { - } - catch (InvocationTargetException e) { - } - catch (NoSuchMethodException e) { - } - catch (IllegalArgumentException e) { - } + result = project.getModelMap().get(propName); if (result != null) return result; result = additionalProperties.getProperty(propName); diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/annotator/MavenDomAnnotator.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/annotator/MavenDomAnnotator.java index 6314cd034ae7..1227c5e913bc 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/annotator/MavenDomAnnotator.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/annotator/MavenDomAnnotator.java @@ -20,8 +20,8 @@ import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.lang.annotation.HighlightSeverity; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.project.Project; +import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.util.ArrayUtil; import com.intellij.util.xml.DomElement; import com.intellij.util.xml.DomUtil; import com.intellij.util.xml.highlighting.DomElementAnnotationHolder; @@ -31,8 +31,8 @@ import org.jetbrains.idea.maven.dom.MavenDomBundle; import org.jetbrains.idea.maven.dom.MavenDomUtil; import org.jetbrains.idea.maven.dom.model.MavenDomParent; import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; +import org.jetbrains.idea.maven.model.MavenProjectProblem; import org.jetbrains.idea.maven.project.MavenProject; -import org.jetbrains.idea.maven.project.MavenProjectProblem; import java.util.Arrays; @@ -56,7 +56,7 @@ public class MavenDomAnnotator implements DomElementsAnnotator { for (MavenProjectProblem each : mavenProject.getProblems()) { MavenProjectProblem.ProblemType type = each.getType(); if (!Arrays.asList(types).contains(type)) continue; - VirtualFile problemFile = each.findFile(); + VirtualFile problemFile = LocalFileSystem.getInstance().findFileByPath(each.getPath()); LocalQuickFix[] fixes = LocalQuickFix.EMPTY_ARRAY; if (problemFile != null && mavenProject.getFile() != problemFile) { diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesArtifactIdConverter.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesArtifactIdConverter.java index b0af15571625..ed8cc955fc80 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesArtifactIdConverter.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesArtifactIdConverter.java @@ -18,7 +18,7 @@ package org.jetbrains.idea.maven.dom.converters; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.xml.ConvertContext; import org.jetbrains.idea.maven.indices.MavenProjectIndicesManager; -import org.jetbrains.idea.maven.project.MavenId; +import org.jetbrains.idea.maven.model.MavenId; import java.util.Set; import java.util.Collections; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesConverter.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesConverter.java index 06164dc2818d..2d2b055af365 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesConverter.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesConverter.java @@ -36,7 +36,7 @@ import org.jetbrains.idea.maven.dom.model.*; import org.jetbrains.idea.maven.dom.MavenDomUtil; import org.jetbrains.idea.maven.dom.MavenDomBundle; import org.jetbrains.idea.maven.indices.MavenProjectIndicesManager; -import org.jetbrains.idea.maven.project.MavenId; +import org.jetbrains.idea.maven.model.MavenId; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.project.MavenProjectsManager; import org.jetbrains.idea.maven.utils.MavenArtifactUtil; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesGroupIdConverter.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesGroupIdConverter.java index ada8abd01195..6a471d5b7f53 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesGroupIdConverter.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesGroupIdConverter.java @@ -3,13 +3,10 @@ package org.jetbrains.idea.maven.dom.converters; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.containers.hash.HashSet; import com.intellij.util.xml.ConvertContext; -import com.intellij.util.xml.impl.ConvertContextImpl; -import org.jetbrains.idea.maven.dom.model.MavenDomShortArtifactCoordinates; import org.jetbrains.idea.maven.indices.MavenProjectIndicesManager; -import org.jetbrains.idea.maven.project.MavenId; +import org.jetbrains.idea.maven.model.MavenId; import java.util.Collection; -import java.util.Collections; import java.util.Set; public class MavenArtifactCoordinatesGroupIdConverter extends MavenArtifactCoordinatesConverter { diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesHelper.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesHelper.java index 7429a956ad35..9867a927256a 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesHelper.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesHelper.java @@ -19,7 +19,7 @@ import com.intellij.util.xml.ConvertContext; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.maven.dom.model.MavenDomArtifactCoordinates; import org.jetbrains.idea.maven.dom.model.MavenDomShortArtifactCoordinates; -import org.jetbrains.idea.maven.project.MavenId; +import org.jetbrains.idea.maven.model.MavenId; public class MavenArtifactCoordinatesHelper { public static MavenId getId(ConvertContext context) { diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesVersionConverter.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesVersionConverter.java index 9812834abde7..22194e67adeb 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesVersionConverter.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesVersionConverter.java @@ -18,7 +18,7 @@ package org.jetbrains.idea.maven.dom.converters; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.xml.ConvertContext; import org.jetbrains.idea.maven.indices.MavenProjectIndicesManager; -import org.jetbrains.idea.maven.project.MavenId; +import org.jetbrains.idea.maven.model.MavenId; import java.util.Collections; import java.util.Set; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenDependencyScopeConverter.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenDependencyScopeConverter.java index 92d2ebac7cdf..a37b2a0d6ba1 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenDependencyScopeConverter.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenDependencyScopeConverter.java @@ -16,9 +16,8 @@ package org.jetbrains.idea.maven.dom.converters; import com.intellij.util.xml.ConvertContext; -import com.intellij.util.xml.DomManager; import org.jetbrains.idea.maven.dom.model.MavenDomDependencyManagement; -import org.jetbrains.idea.maven.utils.MavenConstants; +import org.jetbrains.idea.maven.model.MavenConstants; import java.util.Arrays; import java.util.List; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenParentRelativePathConverter.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenParentRelativePathConverter.java index 8833a4c11af5..5401ea9a1104 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenParentRelativePathConverter.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenParentRelativePathConverter.java @@ -30,13 +30,12 @@ import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; -import org.jetbrains.idea.maven.dom.converters.MavenArtifactCoordinatesHelper; import org.jetbrains.idea.maven.dom.MavenDomUtil; import org.jetbrains.idea.maven.dom.MavenDomBundle; +import org.jetbrains.idea.maven.model.MavenId; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.project.MavenProjectsManager; -import org.jetbrains.idea.maven.utils.MavenConstants; -import org.jetbrains.idea.maven.project.MavenId; +import org.jetbrains.idea.maven.model.MavenConstants; import java.util.ArrayList; import java.util.Collection; @@ -47,7 +46,6 @@ public class MavenParentRelativePathConverter extends ResolvingConverter)result.getExceptions()) { - Throwable cause = each.getCause(); - printException(console, cause == null ? each : cause); - } - } -} diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/MavenEmbedderUtilEx.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/MavenEmbedderUtilEx.java deleted file mode 100644 index 33b55f186925..000000000000 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/MavenEmbedderUtilEx.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.idea.maven.embedder; - -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.JarFileSystem; -import com.intellij.openapi.vfs.LocalFileSystem; -import com.intellij.openapi.vfs.VfsUtil; -import com.intellij.openapi.vfs.VirtualFile; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.idea.maven.utils.MavenConstants; -import org.jetbrains.idea.maven.utils.MavenJDOMUtil; -import org.jetbrains.maven.embedder.MavenEmbedderUtil; - -import java.io.File; -import java.io.IOException; -import java.net.URL; -import java.util.Map; -import java.util.Properties; -import java.util.regex.Pattern; - -public class MavenEmbedderUtilEx extends MavenEmbedderUtil { - private static final String REPOSITORY_DIR = "repository"; - - private static final String LIB_DIR = "lib"; - private static final String SUPER_POM_PATH = "org/apache/maven/project/" + MavenConstants.SUPER_POM_XML; - - @NotNull - public static VirtualFile resolveSuperPomFile(@Nullable String overrideMavenHome) { - VirtualFile result = doResolveSuperPomFile(overrideMavenHome); - if (result == null) { - URL resource = MavenEmbedderUtilEx.class.getResource("/" + SUPER_POM_PATH); - return VfsUtil.findFileByURL(resource); - } - return result; - } - - @Nullable - private static VirtualFile doResolveSuperPomFile(String overrideMavenHome) { - File lib = resolveMavenLib(overrideMavenHome); - if (lib == null) return null; - - VirtualFile file = LocalFileSystem.getInstance().findFileByIoFile(lib); - if (file == null) return null; - - VirtualFile root = JarFileSystem.getInstance().getJarRootForLocalFile(file); - if (root == null) return null; - - return root.findFileByRelativePath(SUPER_POM_PATH); - } - - @Nullable - private static File resolveMavenLib(String overrideMavenHome) { - File directory = resolveMavenHomeDirectory(overrideMavenHome); - if (directory == null) return null; - File libs = new File(directory, LIB_DIR); - File[] files = libs.listFiles(); - if (files != null) { - Pattern pattern = Pattern.compile("maven-\\d+\\.\\d+\\.\\d+-uber\\.jar"); - for (File each : files) { - if (pattern.matcher(each.getName()).matches()) { - return each; - } - } - } - return null; - } - - @NotNull - public static File resolveLocalRepository(@Nullable String mavenHome, @Nullable String userSettings, @Nullable String override) { - File result = doResolveLocalRepository(mavenHome, userSettings, override); - try { - return result.getCanonicalFile(); - } - catch (IOException e) { - return result; - } - } - - @NotNull - private static File doResolveLocalRepository(String mavenHome, String userSettings, String override) { - if (!StringUtil.isEmpty(override)) { - return new File(override); - } - - final File userSettingsFile = resolveUserSettingsFile(userSettings); - if (userSettingsFile != null) { - final String fromUserSettings = getRepositoryFromSettings(userSettingsFile); - if (!StringUtil.isEmpty(fromUserSettings)) { - return new File(fromUserSettings); - } - } - - final File globalSettingsFile = resolveGlobalSettingsFile(mavenHome); - if (globalSettingsFile != null) { - final String fromGlobalSettings = getRepositoryFromSettings(globalSettingsFile); - if (!StringUtil.isEmpty(fromGlobalSettings)) { - return new File(fromGlobalSettings); - } - } - - return new File(resolveM2Dir(), REPOSITORY_DIR); - } - - @Nullable - private static String getRepositoryFromSettings(final File file) { - try { - byte[] bytes = FileUtil.loadFileBytes(file); - return expandProperties(MavenJDOMUtil.findChildValueByPath(MavenJDOMUtil.read(bytes, null), "localRepository", null)); - } - catch (IOException e) { - return null; - } - } - - private static String expandProperties(String text) { - if (StringUtil.isEmptyOrSpaces(text)) return text; - Properties props = MavenEmbedderWrapper.collectSystemProperties(); - for (Map.Entry each : props.entrySet()) { - text = text.replace("${" + each.getKey() + "}", (CharSequence)each.getValue()); - } - return text; - } -} \ No newline at end of file diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/MavenEmbedderWrapper.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/MavenEmbedderWrapper.java deleted file mode 100644 index 9e2bf2a1ee3c..000000000000 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/MavenEmbedderWrapper.java +++ /dev/null @@ -1,446 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.idea.maven.embedder; - -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.progress.ProcessCanceledException; -import com.intellij.openapi.util.Ref; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.util.Function; -import gnu.trove.THashSet; -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.InvalidRepositoryException; -import org.apache.maven.artifact.factory.ArtifactFactory; -import org.apache.maven.artifact.manager.WagonManager; -import org.apache.maven.artifact.repository.ArtifactRepository; -import org.apache.maven.artifact.repository.ArtifactRepositoryFactory; -import org.apache.maven.artifact.resolver.ArtifactResolver; -import org.apache.maven.artifact.resolver.ResolutionListener; -import org.apache.maven.model.Build; -import org.apache.maven.model.Model; -import org.apache.maven.model.Plugin; -import org.apache.maven.plugin.PluginManager; -import org.apache.maven.plugin.descriptor.PluginDescriptor; -import org.apache.maven.project.*; -import org.apache.maven.project.MavenProject; -import org.apache.maven.project.artifact.ProjectArtifactFactory; -import org.apache.maven.project.interpolation.AbstractStringBasedModelInterpolator; -import org.apache.maven.project.interpolation.ModelInterpolationException; -import org.apache.maven.project.interpolation.ModelInterpolator; -import org.apache.maven.project.path.DefaultPathTranslator; -import org.apache.maven.project.path.PathTranslator; -import org.apache.maven.shared.dependency.tree.DependencyNode; -import org.apache.maven.shared.dependency.tree.DependencyTreeResolutionListener; -import org.codehaus.plexus.PlexusContainer; -import org.codehaus.plexus.component.repository.ComponentDependency; -import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.idea.maven.project.*; -import org.jetbrains.idea.maven.utils.MavenLog; -import org.jetbrains.idea.maven.utils.MavenProcessCanceledException; -import org.jetbrains.idea.maven.utils.MavenProgressIndicator; -import org.jetbrains.maven.embedder.MavenEmbedder; -import org.jetbrains.maven.embedder.MavenEmbedderSettings; -import org.jetbrains.maven.embedder.MavenExecutionResult; -import org.jetbrains.maven.embedder.PlexusComponentConfigurator; - -import java.io.File; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.util.*; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -public class MavenEmbedderWrapper { - public static final List PHASES = - Arrays.asList("clean", "validate", "generate-sources", "process-sources", "generate-resources", - "process-resources", "compile", "process-classes", "generate-test-sources", "process-test-sources", - "generate-test-resources", - "process-test-resources", "test-compile", "test", "prepare-package", "package", "pre-integration-test", - "integration-test", - "post-integration-test", - "verify", "install", "site", "deploy"); - public static final List BASIC_PHASES = - Arrays.asList("clean", "validate", "compile", "test", "package", "install", "deploy", "site"); - - private final MavenEmbedder myImpl; - private final MavenLogger myLogger; - private volatile MavenProgressIndicator myCurrentIndicator; - - public static MavenEmbedderWrapper create(MavenGeneralSettings generalSettings) { - MavenEmbedderSettings settings = new MavenEmbedderSettings(); - - settings.setConfigurator(new PlexusComponentConfigurator() { - public void configureComponents(@NotNull PlexusContainer c) { - setupContainer(c); - } - }); - MavenLogger logger = new MavenLogger(); - logger.setThreshold(generalSettings.getLoggingLevel().getLevel()); - settings.setLogger(logger); - settings.setRecursive(false); - - settings.setWorkOffline(generalSettings.isWorkOffline()); - settings.setUsePluginRegistry(generalSettings.isUsePluginRegistry()); - - settings.setMavenHome(generalSettings.getMavenHome()); - settings.setMavenSettingsFile(generalSettings.getMavenSettingsFile()); - settings.setLocalRepository(generalSettings.getEffectiveLocalRepository().getPath()); - - settings.setSnapshotUpdatePolicy(generalSettings.getSnapshotUpdatePolicy().getEmbedderPolicy()); - settings.setPluginUpdatePolicy(generalSettings.getPluginUpdatePolicy().getEmbedderPolicy()); - - return new MavenEmbedderWrapper(MavenEmbedder.create(settings), logger); - } - - private MavenEmbedderWrapper(MavenEmbedder impl, MavenLogger logger) { - myImpl = impl; - myLogger = logger; - } - - public MavenWrapperResolutionResult resolveProject(@NotNull final VirtualFile file, - @NotNull final Collection activeProfiles) - throws MavenProcessCanceledException { - return doExecute(new Executor() { - public MavenWrapperResolutionResult execute() throws Exception { - DependencyTreeResolutionListener listener = new DependencyTreeResolutionListener(myLogger); - - MavenExecutionResult result = myImpl.resolveProject(new File(file.getPath()), - new ArrayList(activeProfiles), - Arrays.asList(listener)); - - DependencyNode rootNode = listener.getRootNode(); - Collection depsTree = rootNode == null ? Collections.emptyList() : rootNode.getChildren(); - return new MavenWrapperResolutionResult(result.getMavenProject(), - depsTree, retrieveUnresolvedArtifactIds(), result.getExceptions()); - } - }); - } - - public void resolve(@NotNull final Artifact artifact, @NotNull final List remoteRepositories) - throws MavenProcessCanceledException { - doExecute(new Executor() { - public Object execute() throws Exception { - doResolve(artifact, convertRepositories(remoteRepositories)); - return null; - } - }); - } - - public MavenArtifact resolve(@NotNull final MavenId id, - @NotNull final String type, - @Nullable final String classifier, - @NotNull final List remoteRepositories) - throws MavenProcessCanceledException { - return doExecute(new Executor() { - public MavenArtifact execute() throws Exception { - return new MavenArtifact(doResolve(id, type, classifier, convertRepositories(remoteRepositories)), getLocalRepositoryFile()); - } - }); - } - - private Artifact doResolve(MavenId id, String type, String classifier, List remoteRepositories) { - Artifact artifact = getComponent(ArtifactFactory.class).createArtifactWithClassifier(id.getGroupId(), - id.getArtifactId(), - id.getVersion(), - type, - classifier); - return doResolve(artifact, remoteRepositories); - } - - private Artifact doResolve(Artifact artifact, List remoteRepositories) { - try { - myImpl.resolve(artifact, remoteRepositories); - return artifact; - } - catch (Exception e) { - MavenLog.LOG.info(e); - } - return artifact; - } - - private List convertRepositories(List repositories) { - List result = new ArrayList(); - for (MavenRemoteRepository each : repositories) { - try { - ArtifactRepositoryFactory factory = getComponent(ArtifactRepositoryFactory.class); - result.add(ProjectUtils.buildArtifactRepository(each.toRepository(), factory, getContainer())); - } - catch (InvalidRepositoryException e) { - MavenLog.LOG.warn(e); - } - } - return result; - } - - public boolean resolvePlugin(@NotNull final MavenPlugin plugin, @NotNull final MavenProject nativeMavenProject, final boolean transitive) - throws MavenProcessCanceledException { - return doExecute(new Executor() { - public Boolean execute() throws Exception { - try { - Plugin mavenPlugin = new Plugin(); - mavenPlugin.setGroupId(plugin.getGroupId()); - mavenPlugin.setArtifactId(plugin.getArtifactId()); - mavenPlugin.setVersion(plugin.getVersion()); - PluginDescriptor result = - getComponent(PluginManager.class).verifyPlugin(mavenPlugin, nativeMavenProject, - myImpl.getSettings(), myImpl.getLocalRepository()); - if (!transitive) return true; - - // todo try to use parallel downloading - - List repos = nativeMavenProject.getRemoteArtifactRepositories(); - for (Artifact each : (Iterable)result.getIntroducedDependencyArtifacts()) { - doResolve(new MavenId(each.getGroupId(), each.getArtifactId(), each.getVersion()), each.getType(), null, repos); - } - for (ComponentDependency each : (List)result.getDependencies()) { - doResolve(new MavenId(each.getGroupId(), each.getArtifactId(), each.getVersion()), each.getType(), null, repos); - } - } - catch (Exception e) { - MavenLog.LOG.info(e); - return false; - } - return true; - } - }); - } - - @NotNull - public MavenWrapperExecutionResult execute(@NotNull final VirtualFile file, - @NotNull final Collection activeProfiles, - @NotNull final List goals) - throws MavenProcessCanceledException { - return doExecute(new Executor() { - public MavenWrapperExecutionResult execute() throws Exception { - MavenExecutionResult result = myImpl.execute(new File(file.getPath()), new ArrayList(activeProfiles), goals); - return new MavenWrapperExecutionResult(result.getMavenProject(), retrieveUnresolvedArtifactIds(), result.getExceptions()); - } - }); - } - - private Set retrieveUnresolvedArtifactIds() { - Set result = new THashSet(); - ((CustomWagonManager)getComponent(WagonManager.class)).getUnresolvedCollector().retrieveUnresolvedIds(result); - ((CustomArtifactResolver)getComponent(ArtifactResolver.class)).getUnresolvedCollector().retrieveUnresolvedIds(result); - return result; - } - - public static Model interpolate(Model model, File basedir) { - try { - AbstractStringBasedModelInterpolator interpolator = new CustomModelInterpolator(new DefaultPathTranslator()); - interpolator.initialize(); - - Properties context = collectSystemProperties(); - - ProjectBuilderConfiguration config = new DefaultProjectBuilderConfiguration().setExecutionProperties(context); - model = interpolator.interpolate(ModelUtils.cloneModel(model), basedir, config, false); - } - catch (ModelInterpolationException e) { - MavenLog.LOG.warn(e); - } - catch (InitializationException e) { - MavenLog.LOG.error(e); - } - - return model; - } - - public static void alignModel(Model model, File basedir) { - PathTranslator pathTranslator = new DefaultPathTranslator(); - pathTranslator.alignToBaseDirectory(model, basedir); - Build build = model.getBuild(); - build.setScriptSourceDirectory(pathTranslator.alignToBaseDirectory(build.getScriptSourceDirectory(), basedir)); - } - - @NotNull - public File getLocalRepositoryFile() { - return myImpl.getLocalRepositoryFile(); - } - - public T getComponent(Class clazz) { - return myImpl.getComponent(clazz); - } - - public T getComponent(Class clazz, String roleHint) { - return myImpl.getComponent(clazz, roleHint); - } - - public PlexusContainer getContainer() { - return myImpl.getContainer(); - } - - private interface Executor { - T execute() throws Exception; - } - - private T doExecute(final Executor executor) throws MavenProcessCanceledException { - final Ref result = new Ref(); - final boolean[] cancelled = new boolean[1]; - final Throwable[] exception = new Throwable[1]; - - Future future = ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - public void run() { - try { - result.set(executor.execute()); - } - catch (ProcessCanceledException e) { - cancelled[0] = true; - } - catch (Throwable e) { - exception[0] = e; - } - } - }); - - MavenProgressIndicator indicator = myCurrentIndicator; - while (true) { - indicator.checkCanceled(); - try { - future.get(50, TimeUnit.MILLISECONDS); - } - catch (TimeoutException ignore) { - } - catch (ExecutionException e) { - throw new RuntimeException(e.getCause()); - } - catch (InterruptedException e) { - throw new MavenProcessCanceledException(); - } - - if (future.isDone()) break; - } - - if (cancelled[0]) throw new MavenProcessCanceledException(); - if (exception[0] != null) { - throw getRethrowable(exception[0]); - } - - return result.get(); - } - - private RuntimeException getRethrowable(Throwable throwable) { - if (throwable instanceof InvocationTargetException) throwable = throwable.getCause(); - if (throwable instanceof RuntimeException) return (RuntimeException)throwable; - return new RuntimeException(throwable); - } - - private static void setupContainer(PlexusContainer c) { - MavenEmbedder.setImplementation(c, ArtifactFactory.class, CustomArtifactFactory.class); - MavenEmbedder.setImplementation(c, ProjectArtifactFactory.class, CustomArtifactFactory.class); - MavenEmbedder.setImplementation(c, ArtifactResolver.class, CustomArtifactResolver.class); - MavenEmbedder.setImplementation(c, WagonManager.class, CustomWagonManager.class); - MavenEmbedder.setImplementation(c, ModelInterpolator.class, CustomModelInterpolator.class); - } - - public void customizeForResolve(MavenConsole console, MavenProgressIndicator process) { - doCustomize(null, false, console, process); - } - - public void customizeForResolve(Map projectIdToFileMap, MavenConsole console, MavenProgressIndicator process) { - doCustomize(projectIdToFileMap, false, console, process); - } - - public void customizeForStrictResolve(Map projectIdToFileMap, - MavenConsole console, - MavenProgressIndicator process) { - doCustomize(projectIdToFileMap, true, console, process); - } - - private void doCustomize(Map projectIdToFileMap, - boolean strict, - MavenConsole console, - MavenProgressIndicator process) { - ((CustomArtifactFactory)getComponent(ArtifactFactory.class)).customize(); - ((CustomArtifactFactory)getComponent(ProjectArtifactFactory.class)).customize(); - ((CustomArtifactResolver)getComponent(ArtifactResolver.class)).customize(projectIdToFileMap, strict); - ((CustomWagonManager)getComponent(WagonManager.class)).customize(strict); - - setConsoleAndLogger(console, process); - } - - private void setConsoleAndLogger(MavenConsole console, MavenProgressIndicator process) { - myCurrentIndicator = process; - myLogger.setConsole(console); - - WagonManager wagon = getComponent(WagonManager.class); - wagon.setDownloadMonitor(process == null ? null : new TransferListenerAdapter(process)); - } - - public void reset() { - setConsoleAndLogger(null, null); - - ((CustomArtifactFactory)getComponent(ProjectArtifactFactory.class)).reset(); - ((CustomArtifactFactory)getComponent(ArtifactFactory.class)).reset(); - ((CustomArtifactResolver)getComponent(ArtifactResolver.class)).reset(); - ((CustomWagonManager)getComponent(WagonManager.class)).reset(); - } - - public void release() { - myImpl.release(); - } - - public void clearCaches() { - withProjectCachesDo(new Function() { - public Object fun(Map map) { - map.clear(); - return null; - } - }); - } - - public void clearCachesFor(final MavenId projectId) { - withProjectCachesDo(new Function() { - public Object fun(Map map) { - map.remove(projectId.getKey()); - return null; - } - }); - } - - private void withProjectCachesDo(Function func) { - MavenProjectBuilder builder = myImpl.getComponent(MavenProjectBuilder.class); - Field field; - try { - field = builder.getClass().getDeclaredField("rawProjectCache"); - field.setAccessible(true); - func.fun(((Map)field.get(builder))); - - field = builder.getClass().getDeclaredField("processedProjectCache"); - field.setAccessible(true); - func.fun(((Map)field.get(builder))); - } - catch (NoSuchFieldException e) { - MavenLog.LOG.error(e); - } - catch (IllegalAccessException e) { - MavenLog.LOG.error(e); - } - } - - public static Properties collectSystemProperties() { - return MavenEmbedder.collectSystemProperties(); - } - - public static void resetSystemPropertiesCacheInTests() { - MavenEmbedder.resetSystemPropertiesCache(); - } - -} - diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/MavenWrapperExecutionResult.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/MavenWrapperExecutionResult.java deleted file mode 100644 index a9232e87aa2a..000000000000 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/MavenWrapperExecutionResult.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.idea.maven.embedder; - -import org.apache.maven.project.MavenProject; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.idea.maven.project.MavenId; - -import java.util.List; -import java.util.Set; - -public class MavenWrapperExecutionResult { - private final MavenProject myMavenProject; - private final Set myUnresolvedArtifactIds; - private final List myExceptions; - - public MavenWrapperExecutionResult(MavenProject mavenProject, Set unresolvedArtifactIds, List exceptions) { - myMavenProject = mavenProject; - myUnresolvedArtifactIds = unresolvedArtifactIds; - myExceptions = exceptions; - } - - @Nullable - public MavenProject getMavenProject() { - return myMavenProject; - } - - public Set getUnresolvedArtifactIds() { - return myUnresolvedArtifactIds; - } - - public List getExceptions() { - return myExceptions; - } - - public boolean hasExceptions() { - return !myExceptions.isEmpty(); - } -} diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/MavenWrapperResolutionResult.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/MavenWrapperResolutionResult.java deleted file mode 100644 index 78ccf27a1ae1..000000000000 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/MavenWrapperResolutionResult.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2000-2010 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.idea.maven.embedder; - -import org.apache.maven.project.MavenProject; -import org.apache.maven.shared.dependency.tree.DependencyNode; -import org.jetbrains.idea.maven.project.MavenId; - -import java.util.Collection; -import java.util.List; -import java.util.Set; - -public class MavenWrapperResolutionResult extends MavenWrapperExecutionResult { - private final Collection myOriginalDependencyTree; - - public MavenWrapperResolutionResult(MavenProject mavenProject, - Collection originalDependencyTree, - Set unresolvedArtifactIds, - List exceptions) { - super(mavenProject, unresolvedArtifactIds, exceptions); - myOriginalDependencyTree = originalDependencyTree; - } - - public Collection getOriginalDependencyTree() { - return myOriginalDependencyTree; - } -} diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/MavenExecutionOptions.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExecutionOptions.java similarity index 68% rename from plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/MavenExecutionOptions.java rename to plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExecutionOptions.java index 05c4a909aa82..ffe9f3e31652 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/MavenExecutionOptions.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExecutionOptions.java @@ -13,19 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.idea.maven.embedder; +package org.jetbrains.idea.maven.execution; -import org.codehaus.plexus.logging.Logger; -import org.jetbrains.maven.embedder.MavenEmbedderSettings; +import org.jetbrains.idea.maven.facade.MavenFacadeConsole; +import org.jetbrains.idea.maven.facade.MavenFacadeSettings; public class MavenExecutionOptions { public enum LoggingLevel { - DEBUG("Debug", Logger.LEVEL_DEBUG), - INFO("Info", Logger.LEVEL_INFO), - WARN("Warn", Logger.LEVEL_WARN), - ERROR("Error", Logger.LEVEL_ERROR), - FATAL("Fatal", Logger.LEVEL_FATAL), - DISABLED("Disabled", Logger.LEVEL_DISABLED); + DEBUG("Debug", MavenFacadeConsole.LEVEL_DEBUG), + INFO("Info", MavenFacadeConsole.LEVEL_INFO), + WARN("Warn", MavenFacadeConsole.LEVEL_WARN), + ERROR("Error", MavenFacadeConsole.LEVEL_ERROR), + FATAL("Fatal", MavenFacadeConsole.LEVEL_FATAL), + DISABLED("Disabled", MavenFacadeConsole.LEVEL_DISABLED); private final String myDisplayString; private final int myLevel; @@ -87,17 +87,17 @@ public class MavenExecutionOptions { } public enum SnapshotUpdatePolicy { - ALWAYS_UPDATE("Always Update", "--update-snapshots", MavenEmbedderSettings.SnapshotUpdatePolicy.ALWAYS_UPDATE), - DO_NOT_UPDATE("Do Not Update", "", MavenEmbedderSettings.SnapshotUpdatePolicy.DO_NOT_UPDATE); + ALWAYS_UPDATE("Always Update", "--update-snapshots", MavenFacadeSettings.UpdatePolicy.ALWAYS_UPDATE), + DO_NOT_UPDATE("Do Not Update", "", MavenFacadeSettings.UpdatePolicy.DO_NOT_UPDATE); private final String myDisplayString; private final String myCommandLineOption; - private final MavenEmbedderSettings.SnapshotUpdatePolicy myEmbedderPolicy; + private final MavenFacadeSettings.UpdatePolicy myFacadePolicy; - private SnapshotUpdatePolicy(String displayString, String commandLineOption, MavenEmbedderSettings.SnapshotUpdatePolicy policy) { + private SnapshotUpdatePolicy(String displayString, String commandLineOption, MavenFacadeSettings.UpdatePolicy policy) { myDisplayString = displayString; myCommandLineOption = commandLineOption; - myEmbedderPolicy = policy; + myFacadePolicy = policy; } public String getDisplayString() { @@ -108,23 +108,23 @@ public class MavenExecutionOptions { return myCommandLineOption; } - public MavenEmbedderSettings.SnapshotUpdatePolicy getEmbedderPolicy() { - return myEmbedderPolicy; + public MavenFacadeSettings.UpdatePolicy getFacadePolicy() { + return myFacadePolicy; } } public enum PluginUpdatePolicy { - UPDATE("Check For Updates", "--check-plugin-updates", MavenEmbedderSettings.PluginUpdatePolicy.UPDATE), - DO_NOT_UPDATE("Do Not Update", "--no-plugin-updates", MavenEmbedderSettings.PluginUpdatePolicy.DO_NOT_UPDATE); + UPDATE("Check For Updates", "--check-plugin-updates", MavenFacadeSettings.UpdatePolicy.ALWAYS_UPDATE), + DO_NOT_UPDATE("Do Not Update", "--no-plugin-updates", MavenFacadeSettings.UpdatePolicy.DO_NOT_UPDATE); private final String myDisplayString; private final String myCommandLineOption; - private final MavenEmbedderSettings.PluginUpdatePolicy myEmbedderPolicy; + private final MavenFacadeSettings.UpdatePolicy myFacadePolicy; - private PluginUpdatePolicy(String displayString, String commandLineOption, MavenEmbedderSettings.PluginUpdatePolicy policy) { + private PluginUpdatePolicy(String displayString, String commandLineOption, MavenFacadeSettings.UpdatePolicy policy) { myDisplayString = displayString; myCommandLineOption = commandLineOption; - myEmbedderPolicy = policy; + myFacadePolicy = policy; } public String getDisplayString() { @@ -135,8 +135,8 @@ public class MavenExecutionOptions { return myCommandLineOption; } - public MavenEmbedderSettings.PluginUpdatePolicy getEmbedderPolicy() { - return myEmbedderPolicy; + public MavenFacadeSettings.UpdatePolicy getFacadePolicy() { + return myFacadePolicy; } } } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExecutor.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExecutor.java index 3861e55616ff..41f0ec94040d 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExecutor.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExecutor.java @@ -20,7 +20,8 @@ package org.jetbrains.idea.maven.execution; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; -import org.jetbrains.idea.maven.embedder.MavenConsole; +import org.jetbrains.idea.maven.facade.MavenFacadeConsole; +import org.jetbrains.idea.maven.project.MavenConsole; import org.jetbrains.idea.maven.project.MavenGeneralSettings; import java.text.MessageFormat; @@ -98,15 +99,15 @@ public abstract class MavenExecutor { protected boolean printExitSummary() { if (isCancelled()) { - myConsole.systemMessage(MavenConsole.LEVEL_INFO, RunnerBundle.message("maven.execution.aborted"), null); + myConsole.systemMessage(MavenFacadeConsole.LEVEL_INFO, RunnerBundle.message("maven.execution.aborted"), null); return false; } else if (exitCode == 0) { - myConsole.systemMessage(MavenConsole.LEVEL_INFO, RunnerBundle.message("maven.execution.finished"), null); + myConsole.systemMessage(MavenFacadeConsole.LEVEL_INFO, RunnerBundle.message("maven.execution.finished"), null); return true; } else { - myConsole.systemMessage(MavenConsole.LEVEL_ERROR, RunnerBundle.message("maven.execution.terminated.abnormally", exitCode), null); + myConsole.systemMessage(MavenFacadeConsole.LEVEL_ERROR, RunnerBundle.message("maven.execution.terminated.abnormally", exitCode), null); return false; } } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalExecutor.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalExecutor.java index aeaefbd5cadb..34001b661226 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalExecutor.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalExecutor.java @@ -25,8 +25,9 @@ import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.util.Key; import org.jetbrains.annotations.NonNls; +import org.jetbrains.idea.maven.facade.MavenFacadeConsole; +import org.jetbrains.idea.maven.project.MavenConsole; import org.jetbrains.idea.maven.project.MavenGeneralSettings; -import org.jetbrains.idea.maven.embedder.MavenConsole; public class MavenExternalExecutor extends MavenExecutor { @@ -60,7 +61,7 @@ public class MavenExternalExecutor extends MavenExecutor { myConsole.attachToProcess(myProcessHandler); } catch (ExecutionException e) { - myConsole.systemMessage(MavenConsole.LEVEL_FATAL, RunnerBundle.message("external.startup.failed", e.getMessage()), null); + myConsole.systemMessage(MavenFacadeConsole.LEVEL_FATAL, RunnerBundle.message("external.startup.failed", e.getMessage()), null); return false; } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalParameters.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalParameters.java index b80689fda03b..9abf973de823 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalParameters.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalParameters.java @@ -28,9 +28,9 @@ import com.intellij.openapi.projectRoots.impl.JavaAwareProjectJdkTableImpl; import com.intellij.openapi.util.text.StringUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; -import org.jetbrains.idea.maven.embedder.MavenEmbedderUtilEx; -import org.jetbrains.idea.maven.embedder.MavenExecutionOptions; +import org.jetbrains.idea.maven.facade.MavenFacadeUtil; import org.jetbrains.idea.maven.project.MavenGeneralSettings; +import org.jetbrains.idea.maven.utils.MavenUtil; import java.io.File; import java.io.IOException; @@ -123,7 +123,7 @@ public class MavenExternalParameters { addParameters(list, StringUtil.notNullize(System.getenv(MAVEN_OPTS))); - addProperty(list, "classworlds.conf", MavenEmbedderUtilEx.getMavenConfFile(new File(mavenHome)).getPath()); + addProperty(list, "classworlds.conf", MavenUtil.getMavenConfFile(new File(mavenHome)).getPath()); addProperty(list, "maven.home", mavenHome); @@ -180,7 +180,7 @@ public class MavenExternalParameters { } private static String resolveMavenHome(@NotNull MavenGeneralSettings coreSettings) throws ExecutionException { - final File file = MavenEmbedderUtilEx.resolveMavenHomeDirectory(coreSettings.getMavenHome()); + final File file = MavenUtil.resolveMavenHomeDirectory(coreSettings.getMavenHome()); if (file == null) { throw new ExecutionException(RunnerBundle.message("external.maven.home.no.default")); @@ -190,7 +190,7 @@ public class MavenExternalParameters { throw new ExecutionException(RunnerBundle.message("external.maven.home.does.not.exist", file.getPath())); } - if (!MavenEmbedderUtilEx.isValidMavenHome(file)) { + if (!MavenUtil.isValidMavenHome(file)) { throw new ExecutionException(RunnerBundle.message("external.maven.home.invalid", file.getPath())); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenJavaClasspathPolicyExtender.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenJavaClasspathPolicyExtender.java index 586f55bb7318..04ae3b1f4b9e 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenJavaClasspathPolicyExtender.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenJavaClasspathPolicyExtender.java @@ -20,10 +20,10 @@ import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.*; import org.jetbrains.annotations.NotNull; -import org.jetbrains.idea.maven.project.MavenArtifact; +import org.jetbrains.idea.maven.model.MavenArtifact; +import org.jetbrains.idea.maven.model.MavenConstants; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.project.MavenProjectsManager; -import org.jetbrains.idea.maven.utils.MavenConstants; import java.util.Collections; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunConfiguration.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunConfiguration.java index 4bcb75c40891..6b66d051ddca 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunConfiguration.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunConfiguration.java @@ -33,10 +33,10 @@ import com.intellij.openapi.util.WriteExternalException; import com.intellij.util.xmlb.XmlSerializer; import org.jdom.Element; import org.jetbrains.annotations.NotNull; -import org.jetbrains.idea.maven.embedder.MavenConsoleImpl; +import org.jetbrains.idea.maven.model.MavenConstants; +import org.jetbrains.idea.maven.project.MavenConsoleImpl; import org.jetbrains.idea.maven.project.MavenGeneralSettings; import org.jetbrains.idea.maven.project.MavenProjectsManager; -import org.jetbrains.idea.maven.utils.MavenConstants; import java.io.File; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunner.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunner.java index 94b9de4e86ba..50e13af90540 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunner.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunner.java @@ -28,9 +28,8 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.idea.maven.embedder.MavenConsole; -import org.jetbrains.idea.maven.embedder.MavenConsoleHelper; -import org.jetbrains.idea.maven.embedder.MavenConsoleImpl; +import org.jetbrains.idea.maven.project.MavenConsole; +import org.jetbrains.idea.maven.project.MavenConsoleImpl; import org.jetbrains.idea.maven.project.MavenGeneralSettings; import org.jetbrains.idea.maven.project.MavenProjectsManager; import org.jetbrains.idea.maven.utils.SimpleProjectComponent; @@ -108,7 +107,7 @@ public class MavenRunner extends SimpleProjectComponent implements PersistentSta }); } catch (Exception e) { - MavenConsoleHelper.printException(console, e); + console.printException(e); console.finish(); MavenLog.LOG.warn(e); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerParametersConfigurable.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerParametersConfigurable.java index 68fa448b7b3c..1857b7433e6f 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerParametersConfigurable.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerParametersConfigurable.java @@ -24,7 +24,7 @@ import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.maven.utils.Strings; -import org.jetbrains.idea.maven.utils.MavenConstants; +import org.jetbrains.idea.maven.model.MavenConstants; import javax.swing.*; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/SoutMavenConsole.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/SoutMavenConsole.java index a8ca698fd075..f2bde943581b 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/SoutMavenConsole.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/SoutMavenConsole.java @@ -19,8 +19,7 @@ import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.process.ProcessHandler; import com.intellij.openapi.util.Key; -import org.jetbrains.idea.maven.embedder.MavenConsole; -import org.jetbrains.idea.maven.embedder.MavenExecutionOptions; +import org.jetbrains.idea.maven.project.MavenConsole; public class SoutMavenConsole extends MavenConsole { public SoutMavenConsole() { diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/facade/MavenEmbedderWrapper.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/facade/MavenEmbedderWrapper.java new file mode 100644 index 000000000000..6891c7b43ba0 --- /dev/null +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/facade/MavenEmbedderWrapper.java @@ -0,0 +1,207 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.facade; + +import com.intellij.openapi.vfs.VirtualFile; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.idea.maven.model.*; +import org.jetbrains.idea.maven.project.MavenConsole; +import org.jetbrains.idea.maven.utils.MavenProcessCanceledException; +import org.jetbrains.idea.maven.utils.MavenProgressIndicator; + +import java.io.File; +import java.rmi.NoSuchObjectException; +import java.rmi.RemoteException; +import java.rmi.server.UnicastRemoteObject; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +public class MavenEmbedderWrapper { + private final MavenFacadeEmbedder myWrappee; + + private MavenFacadeConsole myConsole; + private MavenFacadeProgressIndicator myIndicator; + + public MavenEmbedderWrapper(MavenFacadeEmbedder wrappee) { + myWrappee = wrappee; + } + + public void customizeForResolve(MavenConsole console, MavenProgressIndicator indicator) { + try { + resetConsole(MavenFacadeManager.wrapAndExport(console)); + resetIndicator(MavenFacadeManager.wrapAndExport(indicator)); + + myWrappee.customizeForResolve(myConsole, myIndicator); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + public void customizeForResolve(Map projectIdToFileMap, MavenConsole console, MavenProgressIndicator indicator) { + try { + resetConsole(MavenFacadeManager.wrapAndExport(console)); + resetIndicator(MavenFacadeManager.wrapAndExport(indicator)); + + myWrappee.customizeForResolve(projectIdToFileMap, myConsole, myIndicator); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + public void customizeForStrictResolve(Map projectIdToFileMap, + MavenConsole console, + MavenProgressIndicator indicator) { + try { + resetConsole(MavenFacadeManager.wrapAndExport(console)); + resetIndicator(MavenFacadeManager.wrapAndExport(indicator)); + + myWrappee.customizeForStrictResolve(projectIdToFileMap, myConsole, myIndicator); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + @NotNull + public MavenWrapperExecutionResult resolveProject(@NotNull VirtualFile file, + @NotNull Collection activeProfiles) throws MavenProcessCanceledException { + try { + return myWrappee.resolveProject(new File(file.getPath()), activeProfiles); + } + catch (MavenFacadeProcessCanceledException e) { + throw new MavenProcessCanceledException(); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + @NotNull + public MavenArtifact resolve(@NotNull MavenArtifactInfo info, + @NotNull List remoteRepositories) throws MavenProcessCanceledException { + try { + return myWrappee.resolve(info, remoteRepositories); + } + catch (MavenFacadeProcessCanceledException e) { + throw new MavenProcessCanceledException(); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + @NotNull + public List resolveTransitively( + @NotNull List artifacts, + @NotNull List remoteRepositories) throws MavenProcessCanceledException { + try { + return myWrappee.resolveTransitively(artifacts, remoteRepositories); + } + catch (MavenFacadeProcessCanceledException e) { + throw new MavenProcessCanceledException(); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + public Collection resolvePlugin(@NotNull MavenPlugin plugin, + @NotNull List repositories, + @NotNull NativeMavenProjectHolder nativeMavenProject, + boolean transitive) throws MavenProcessCanceledException { + try { + return myWrappee.resolvePlugin(plugin, repositories, nativeMavenProject.getId(), transitive); + } + catch (MavenFacadeProcessCanceledException e) { + throw new MavenProcessCanceledException(); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + @NotNull + public MavenWrapperExecutionResult execute(@NotNull VirtualFile file, + @NotNull Collection activeProfiles, + @NotNull List goals) throws MavenProcessCanceledException { + try { + return myWrappee.execute(new File(file.getPath()), activeProfiles, goals); + } + catch (MavenFacadeProcessCanceledException e) { + throw new MavenProcessCanceledException(); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + public void reset() { + try { + myWrappee.reset(); + resetConsole(null); + resetIndicator(null); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + private void resetConsole(MavenFacadeConsole console) throws NoSuchObjectException { + if (myConsole != null) { + UnicastRemoteObject.unexportObject(myConsole, true); + } + myConsole = console; + } + + private void resetIndicator(MavenFacadeProgressIndicator indicator) throws NoSuchObjectException { + if (myIndicator != null) { + UnicastRemoteObject.unexportObject(myIndicator, true); + } + myIndicator = indicator; + } + + public void release() { + try { + myWrappee.release(); + resetConsole(null); + resetIndicator(null); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + public void clearCaches() { + try { + myWrappee.clearCaches(); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + public void clearCachesFor(MavenId projectId) { + try { + myWrappee.clearCachesFor(projectId); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } +} diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/facade/MavenFacadeManager.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/facade/MavenFacadeManager.java new file mode 100644 index 000000000000..bc629d64e3ca --- /dev/null +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/facade/MavenFacadeManager.java @@ -0,0 +1,370 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.facade; + +import com.intellij.execution.DefaultExecutionResult; +import com.intellij.execution.ExecutionException; +import com.intellij.execution.ExecutionResult; +import com.intellij.execution.Executor; +import com.intellij.execution.configurations.CommandLineState; +import com.intellij.execution.configurations.GeneralCommandLine; +import com.intellij.execution.configurations.RunProfileState; +import com.intellij.execution.configurations.SimpleJavaParameters; +import com.intellij.execution.process.OSProcessHandler; +import com.intellij.execution.process.ProcessHandler; +import com.intellij.execution.process.ProcessTerminatedListener; +import com.intellij.execution.rmi.RemoteProcessSupport; +import com.intellij.execution.runners.ProgramRunner; +import com.intellij.ide.DataManager; +import com.intellij.openapi.actionSystem.AnAction; +import com.intellij.openapi.actionSystem.PlatformDataKeys; +import com.intellij.openapi.application.PathManager; +import com.intellij.openapi.components.ServiceManager; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.projectRoots.JavaSdkType; +import com.intellij.openapi.projectRoots.JdkUtil; +import com.intellij.openapi.projectRoots.Sdk; +import com.intellij.openapi.projectRoots.SimpleJavaSdkType; +import com.intellij.openapi.util.Pair; +import com.intellij.openapi.util.ShutDownTracker; +import com.intellij.openapi.util.SystemInfo; +import com.intellij.openapi.util.text.StringUtil; +import com.intellij.util.PathUtil; +import com.intellij.util.SmartList; +import com.intellij.util.SystemProperties; +import com.intellij.util.containers.ContainerUtil; +import gnu.trove.THashSet; +import org.apache.lucene.search.Query; +import org.jdom.Element; +import org.jetbrains.annotations.NonNls; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.idea.maven.model.MavenArtifactInfo; +import org.jetbrains.idea.maven.model.MavenModel; +import org.jetbrains.idea.maven.model.MavenRepositoryInfo; +import org.jetbrains.idea.maven.project.MavenConsole; +import org.jetbrains.idea.maven.project.MavenGeneralSettings; +import org.jetbrains.idea.maven.project.MavenProjectsManager; +import org.jetbrains.idea.maven.utils.MavenLog; +import org.jetbrains.idea.maven.utils.MavenProgressIndicator; + +import java.io.File; +import java.nio.charset.Charset; +import java.rmi.RemoteException; +import java.rmi.server.UnicastRemoteObject; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +public class MavenFacadeManager { + @NonNls private static final String MAIN_CLASS = "org.jetbrains.idea.maven.facade.RemoteMavenServer"; + private final RemoteProcessSupport mySupport; + private MavenFacade myFacade; + private RemoteMavenFacadeLogger myLogger; + + public static MavenFacadeManager getInstance() { + return ServiceManager.getService(MavenFacadeManager.class); + } + + public MavenFacadeManager() throws RemoteException { + mySupport = new RemoteProcessSupport(MavenFacade.class) { + @Override + protected void fireModificationCountChanged() { + } + + @Override + protected String getName(Object file) { + return MavenFacadeManager.class.getSimpleName(); + } + + @Override + protected RunProfileState getRunProfileState(Object target, Object configuration, Executor executor) throws ExecutionException { + return createRunProfileState(); + } + }; + + ShutDownTracker.getInstance().registerShutdownTask(new Runnable() { + public void run() { + mySupport.stopAll(); + + if (myLogger != null) { + try { + UnicastRemoteObject.unexportObject(myLogger, true); + } + catch (RemoteException e) { + MavenLog.LOG.error(e); + } + } + } + }); + } + + private synchronized MavenFacade getFacade() { + if (myFacade == null) { + try { + myFacade = mySupport.acquire(this, ""); + + myLogger = new RemoteMavenFacadeLogger(); + UnicastRemoteObject.exportObject(myLogger, 0); + myFacade.setLogger(myLogger); + } + catch (Exception e) { + throw new RuntimeException(e); + } + } + return myFacade; + } + + + private RunProfileState createRunProfileState() { + return new CommandLineState(null) { + private SimpleJavaParameters createJavaParameters() throws ExecutionException { + final SimpleJavaParameters params = new SimpleJavaParameters(); + + final Sdk ideaJdk = new SimpleJavaSdkType().createJdk("tmp", SystemProperties.getJavaHome()); + params.setJdk(ideaJdk); + + params.setWorkingDirectory(PathManager.getBinPath()); + final ArrayList classPath = new ArrayList(); + ContainerUtil.addIfNotNull(PathUtil.getJarPathForClass(NotNull.class), classPath); + ContainerUtil.addIfNotNull(PathUtil.getJarPathForClass(StringUtil.class), classPath); + ContainerUtil.addIfNotNull(PathUtil.getJarPathForClass(THashSet.class), classPath); + ContainerUtil.addIfNotNull(PathUtil.getJarPathForClass(Element.class), classPath); + ContainerUtil.addIfNotNull(PathUtil.getJarPathForClass(Query.class), classPath); + params.getClassPath().addAll(classPath); + params.getClassPath().addAllFiles(collectClassPathAndLIbsFolder().first); + + params.setMainClass(MAIN_CLASS); + + // todo pass sensible parameters, MAVEN_OPTS? + if (SystemInfo.isMac) { + String arch = System.getProperty("sun.arch.data.model"); + if (arch != null) { + params.getVMParametersList().addParametersString("-d" + arch); + } + } + params.getVMParametersList().addParametersString("-Xmx512m"); + return params; + } + + @Override + public ExecutionResult execute(@NotNull Executor executor, @NotNull ProgramRunner runner) throws ExecutionException { + ProcessHandler processHandler = startProcess(); + return new DefaultExecutionResult(null, processHandler, AnAction.EMPTY_ARRAY); + } + + protected OSProcessHandler startProcess() throws ExecutionException { + SimpleJavaParameters params = createJavaParameters(); + Sdk sdk = params.getJdk(); + + final GeneralCommandLine commandLine = JdkUtil.setupJVMCommandLine(((JavaSdkType)sdk.getSdkType()).getVMExecutablePath(sdk), params, + JdkUtil.useDynamicClasspath(PlatformDataKeys + .PROJECT.getData( + DataManager.getInstance().getDataContext()))); + final OSProcessHandler processHandler = new OSProcessHandler(commandLine.createProcess(), commandLine.getCommandLineString()) { + @Override + public Charset getCharset() { + return commandLine.getCharset(); + } + }; + ProcessTerminatedListener.attach(processHandler); + return processHandler; + } + }; + } + + public static Pair, File> collectClassPathAndLIbsFolder() { + File pluginFileOrDir = new File(PathUtil.getJarPathForClass(MavenFacadeManager.class)); + + File libDir; + List classpath = new SmartList(); + + if (pluginFileOrDir.isDirectory()) { + classpath.add(new File(pluginFileOrDir.getParent(), "maven-facade-api")); + classpath.add(new File(pluginFileOrDir.getParent(), "maven-facade-impl")); + File luceneLib = new File(PathUtil.getJarPathForClass(Query.class)); + libDir = new File(luceneLib.getParentFile().getParentFile().getParentFile(), "facade-impl/lib"); + } + else { + libDir = pluginFileOrDir.getParentFile(); + } + MavenLog.LOG.assertTrue(libDir.exists() && libDir.isDirectory(), "Maven Facade libraries dir not found: " + libDir); + + File[] files = libDir.listFiles(); + for (File jar : files) { + if (jar.isFile() && jar.getName().endsWith(".jar") && !jar.equals(pluginFileOrDir)) { + classpath.add(jar); + } + } + return Pair.create(classpath, libDir); + } + + public MavenEmbedderWrapper createEmbedder(Project project) { + MavenFacade facade = getFacade(); + MavenGeneralSettings settings = MavenProjectsManager.getInstance(project).getGeneralSettings(); + try { + return new MavenEmbedderWrapper(facade.createEmbedder(convertSettings(settings))); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + public MavenIndexerWrapper createIndexer() { + try { + return new MavenIndexerWrapper(getFacade().createIndexer()); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + public List getRepositories(String nexusUrl) { + try { + return getFacade().getRepositories(nexusUrl); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + public List findArtifacts(MavenArtifactInfo template, String nexusUrl) { + try { + return getFacade().findArtifacts(template, nexusUrl); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + public MavenModel interpolateAndAlignModel(MavenModel model, File basedir) { + try { + return getFacade().interpolateAndAlignModel(model, basedir); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + public MavenModel assembleInheritance(MavenModel model, MavenModel parentModel) { + try { + return getFacade().assembleInheritance(model, parentModel); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + public ProfileApplicationResult applyProfiles(MavenModel model, + File basedir, + Collection explicitProfiles, + Collection alwaysOnProfiles) { + try { + return getFacade().applyProfiles(model, basedir, explicitProfiles, alwaysOnProfiles); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + public static MavenFacadeSettings convertSettings(MavenGeneralSettings settings) { + MavenFacadeSettings result = new MavenFacadeSettings(); + result.setLoggingLevel(settings.getLoggingLevel().getLevel()); + result.setOffline(settings.isWorkOffline()); + result.setMavenHome(settings.getEffectiveMavenHome()); + result.setUserSettingsFile(settings.getEffectiveUserSettingsIoFile()); + result.setGlobalSettingsFile(settings.getEffectiveGlobalSettingsIoFile()); + result.setLocalRepository(settings.getEffectiveLocalRepository()); + result.setPluginUpdatePolicy(settings.getPluginUpdatePolicy().getFacadePolicy()); + result.setSnapshotUpdatePolicy(settings.getSnapshotUpdatePolicy().getFacadePolicy()); + return result; + } + + public static MavenFacadeConsole wrapAndExport(final MavenConsole console) { + try { + RemoteMavenFacadeConsole result = new RemoteMavenFacadeConsole(console); + UnicastRemoteObject.exportObject(result, 0); + return result; + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + public static MavenFacadeProgressIndicator wrapAndExport(final MavenProgressIndicator process) { + try { + RemoteMavenFacadeProgressIndicator result = new RemoteMavenFacadeProgressIndicator(process); + UnicastRemoteObject.exportObject(result, 0); + return result; + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + private static class RemoteMavenFacadeLogger extends RemoteObject implements MavenFacadeLogger { + public void info(Throwable e) { + MavenLog.LOG.info(e); + } + + public void warn(Throwable e) { + MavenLog.LOG.warn(e); + } + + public void error(Throwable e) { + MavenLog.LOG.error(e); + } + } + + private static class RemoteMavenFacadeProgressIndicator extends RemoteObject implements MavenFacadeProgressIndicator { + private final MavenProgressIndicator myProcess; + + public RemoteMavenFacadeProgressIndicator(MavenProgressIndicator process) { + myProcess = process; + } + + public void setText(String text) { + myProcess.setText(text); + } + + public void setText2(String text) { + myProcess.setText2(text); + } + + public boolean isCanceled() { + return myProcess.isCanceled(); + } + + public void setIndeterminate(boolean value) { + myProcess.getIndicator().setIndeterminate(value); + } + + public void setFraction(double fraction) { + myProcess.setFraction(fraction); + } + } + + private static class RemoteMavenFacadeConsole extends RemoteObject implements MavenFacadeConsole { + private final MavenConsole myConsole; + + public RemoteMavenFacadeConsole(MavenConsole console) { + myConsole = console; + } + + public void printMessage(int level, String message, Throwable throwable) { + myConsole.printMessage(level, message, throwable); + } + } +} diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/facade/MavenIndexerWrapper.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/facade/MavenIndexerWrapper.java new file mode 100644 index 000000000000..22d518fe1cb0 --- /dev/null +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/facade/MavenIndexerWrapper.java @@ -0,0 +1,137 @@ +/* + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.idea.maven.facade; + +import org.apache.lucene.search.Query; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.idea.maven.model.MavenArchetype; +import org.jetbrains.idea.maven.model.MavenArtifactInfo; +import org.jetbrains.idea.maven.model.MavenId; +import org.jetbrains.idea.maven.project.MavenGeneralSettings; +import org.jetbrains.idea.maven.utils.MavenProcessCanceledException; +import org.jetbrains.idea.maven.utils.MavenProgressIndicator; + +import java.io.File; +import java.rmi.RemoteException; +import java.rmi.server.UnicastRemoteObject; +import java.util.Collection; +import java.util.List; +import java.util.Set; + +public class MavenIndexerWrapper { + private final MavenFacadeIndexer myWrappee; + + public MavenIndexerWrapper(MavenFacadeIndexer wrappee) { + myWrappee = wrappee; + } + + public int createIndex(@NotNull String indexId, + @Nullable String repositoryId, + @Nullable File file, + @Nullable String url, + @NotNull File indexDir) throws MavenFacadeIndexerException { + try { + return myWrappee.createIndex(indexId, repositoryId, file, url, indexDir); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + public void releaseIndex(int id) throws MavenFacadeIndexerException { + try { + myWrappee.releaseIndex(id); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + public int getIndexCount() { + try { + return myWrappee.getIndexCount(); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + public void updateIndex(int id, MavenGeneralSettings settings, MavenProgressIndicator indicator) throws MavenProcessCanceledException, + MavenFacadeIndexerException { + try { + MavenFacadeProgressIndicator indicatorWrapper = MavenFacadeManager.wrapAndExport(indicator); + try { + myWrappee.updateIndex(id, MavenFacadeManager.convertSettings(settings), indicatorWrapper); + } + finally { + UnicastRemoteObject.unexportObject(indicatorWrapper, true); + } + } + catch (MavenFacadeProcessCanceledException e) { + throw new MavenProcessCanceledException(); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + public List getAllArtifacts(int indexId) throws MavenFacadeIndexerException { + try { + return myWrappee.getAllArtifacts(indexId); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + public MavenId addArtifact(int indexId, File artifactFile) throws MavenFacadeIndexerException { + try { + return myWrappee.addArtifact(indexId, artifactFile); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + public Set search(int indexId, Query query, int maxResult) throws MavenFacadeIndexerException { + try { + return myWrappee.search(indexId, query, maxResult); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + public Collection getArchetypes() { + try { + return myWrappee.getArchetypes(); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + public void release() { + try { + myWrappee.release(); + } + catch (RemoteException e) { + throw new RuntimeException(e); + } + } +} + diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/facade/remote/MavenFacadeManagerImpl.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/facade/remote/MavenFacadeManagerImpl.java deleted file mode 100644 index 87186c62a9ac..000000000000 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/facade/remote/MavenFacadeManagerImpl.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright 2000-2010 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.idea.maven.facade.remote; - -import com.intellij.execution.DefaultExecutionResult; -import com.intellij.execution.ExecutionException; -import com.intellij.execution.ExecutionResult; -import com.intellij.execution.Executor; -import com.intellij.execution.configurations.*; -import com.intellij.execution.process.OSProcessHandler; -import com.intellij.execution.process.ProcessHandler; -import com.intellij.execution.process.ProcessTerminatedListener; -import com.intellij.execution.rmi.RemoteProcessSupport; -import com.intellij.execution.runners.ProgramRunner; -import com.intellij.ide.DataManager; -import com.intellij.openapi.Disposable; -import com.intellij.openapi.actionSystem.AnAction; -import com.intellij.openapi.actionSystem.PlatformDataKeys; -import com.intellij.openapi.application.PathManager; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.projectRoots.JavaSdkType; -import com.intellij.openapi.projectRoots.JdkUtil; -import com.intellij.openapi.projectRoots.Sdk; -import com.intellij.openapi.projectRoots.SimpleJavaSdkType; -import com.intellij.openapi.util.Disposer; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.encoding.EncodingProjectManager; -import com.intellij.psi.CommonClassNames; -import com.intellij.util.PathUtil; -import com.intellij.util.SystemProperties; -import com.intellij.util.containers.ContainerUtil; -import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.idea.maven.execution.MavenExternalParameters; -import org.jetbrains.idea.maven.execution.MavenRunner; -import org.jetbrains.idea.maven.execution.MavenRunnerParameters; -import org.jetbrains.idea.maven.execution.MavenRunnerSettings; -import org.jetbrains.idea.maven.project.MavenProjectsManager; - -import javax.xml.stream.XMLStreamException; -import java.io.File; -import java.nio.charset.Charset; -import java.util.ArrayList; - -/** - * @author Gregory.Shrago - */ -public class MavenFacadeManagerImpl implements MavenFacadeManager { - @NonNls private static final String MAIN_CLASS = "org.jetbrains.idea.maven.facade.remote.RemoteMavenServer"; - - private final RemoteProcessSupport mySupport; - - public MavenFacadeManagerImpl(final Project project) { - mySupport = new RemoteProcessSupport(project, MavenFacade.class) { - @Override - protected void fireModificationCountChanged() { - } - - @Override - protected String getName(Object file) { - return file.toString(); - } - - @Override - protected RunProfileState getRunProfileState(Object project, Object configuration, Executor executor) throws ExecutionException { - return createRunProfileState(); - } - }; - Disposer.register(project, new Disposable() { - public void dispose() { - mySupport.stopAll(); - } - }); - } - - public MavenFacade getMavenFacade(@NotNull final Object key) throws Exception { - return mySupport.acquire(key, ""); - } - - public void releaseMavenFacade(@NotNull Object key) { - mySupport.release(key, ""); - } - - private RunProfileState createRunProfileState() { - final CommandLineState state = new CommandLineState(null) { - private SimpleJavaParameters createJavaParameters() throws ExecutionException { - final SimpleJavaParameters params = new SimpleJavaParameters(); - - final Project project = mySupport.getProject(); - params.setCharset(EncodingProjectManager.getInstance(project).getDefaultCharset()); - - final MavenRunnerSettings runnerSettings = MavenRunner.getInstance(project).getState(); - MavenExternalParameters.configureSimpleJavaParameters(params, new MavenRunnerParameters(), - MavenProjectsManager.getInstance(project).getGeneralSettings(), - runnerSettings); - - - final Sdk ideaJdk = new SimpleJavaSdkType().createJdk("tmp", SystemProperties.getJavaHome()); - params.setJdk(ideaJdk); - - params.setWorkingDirectory(PathManager.getBinPath()); - final ArrayList classPath = new ArrayList(); - ContainerUtil.addIfNotNull(PathUtil.getJarPathForClass(StringUtil.class), classPath); - ContainerUtil.addIfNotNull(PathUtil.getJarPathForClass(NotNull.class), classPath); - ContainerUtil.addIfNotNull(PathUtil.getJarPathForClass(XMLStreamException.class), classPath); - - params.getClassPath().addAll(classPath); - params.setMainClass(MAIN_CLASS); - params.getClassPath().addFirst(getJarPath(MavenFacadeManagerImpl.this.getClass(), MAIN_CLASS)); - tuneParams(params); - return params; - } - - @Override - public ExecutionResult execute(@NotNull final Executor executor, @NotNull final ProgramRunner runner) throws ExecutionException { - final ProcessHandler processHandler = startProcess(); - return new DefaultExecutionResult(null, processHandler, AnAction.EMPTY_ARRAY); - } - - protected OSProcessHandler startProcess() throws ExecutionException { - final SimpleJavaParameters params = createJavaParameters(); - final Sdk sdk = params.getJdk(); - final GeneralCommandLine commandLine = JdkUtil.setupJVMCommandLine(((JavaSdkType)sdk.getSdkType()).getVMExecutablePath(sdk), params, - JdkUtil.useDynamicClasspath(PlatformDataKeys - .PROJECT.getData(DataManager.getInstance().getDataContext()))); - final OSProcessHandler processHandler = new OSProcessHandler(commandLine.createProcess(), commandLine.getCommandLineString()) { - @Override - public Charset getCharset() { - return commandLine.getCharset(); - } - }; - ProcessTerminatedListener.attach(processHandler); - return processHandler; - } - - }; - return state; - } - - private void tuneParams(SimpleJavaParameters params) { - final String path = getJarPath(getClass(), MAIN_CLASS); - File file = new File(path); - if (file.isDirectory()) { - params.getClassPath().add(file.getPath()); - file = new File(getJarPath(getClass(), "org.apache.maven.artifact.resolver.ArtifactNotFoundException")); - } - - if (file.isFile()) { - final File[] files = file.getParentFile().listFiles(); - for (File jar : files) { - if (jar.isFile() && jar.getName().endsWith(".jar") && !jar.getName().equals("maven.jar")) { - params.getClassPath().add(jar.getPath()); - } - } - } - } - - public static String getJarPath(@NotNull final Class context, @NotNull final String mainClassName) { - final String s = PathManager.getResourceRoot(context, "/" + mainClassName.replace('.', '/') + CommonClassNames.CLASS_FILE_EXTENSION); - return new File(s).getAbsoluteFile().getAbsolutePath(); - } -} diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/FacetImporter.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/FacetImporter.java index c7f0db91e427..f18e551e7bae 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/FacetImporter.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/FacetImporter.java @@ -21,7 +21,7 @@ import com.intellij.openapi.module.Module; import com.intellij.openapi.util.io.FileUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.PathUtil; -import org.jetbrains.annotations.NotNull; +import org.jetbrains.idea.maven.model.MavenArtifact; import org.jetbrains.idea.maven.project.*; import java.io.File; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/GroovyImporter.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/GroovyImporter.java index 47c884a902c9..159cf0c7f581 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/GroovyImporter.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/GroovyImporter.java @@ -2,6 +2,7 @@ package org.jetbrains.idea.maven.importing; import com.intellij.openapi.module.Module; import org.jdom.Element; +import org.jetbrains.idea.maven.model.MavenArtifact; import org.jetbrains.idea.maven.project.*; import org.jetbrains.idea.maven.utils.MavenJDOMUtil; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenFoldersImporter.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenFoldersImporter.java index e6ca55c6dc73..7c006e43f603 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenFoldersImporter.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenFoldersImporter.java @@ -21,10 +21,10 @@ import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModifiableRootModel; import com.intellij.openapi.roots.ProjectRootManager; +import org.jetbrains.idea.maven.model.MavenResource; import org.jetbrains.idea.maven.project.MavenImportingSettings; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.project.MavenProjectsManager; -import org.jetbrains.idea.maven.project.MavenResource; import java.io.File; import java.util.ArrayList; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenImporter.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenImporter.java index 9f0b9704a58c..880f46cd217e 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenImporter.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenImporter.java @@ -18,12 +18,12 @@ package org.jetbrains.idea.maven.importing; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.module.Module; import com.intellij.openapi.util.Pair; -import org.apache.maven.project.*; import org.jdom.Element; import org.jetbrains.annotations.Nullable; -import org.jetbrains.idea.maven.embedder.MavenEmbedderWrapper; +import org.jetbrains.idea.maven.facade.MavenEmbedderWrapper; +import org.jetbrains.idea.maven.facade.NativeMavenProjectHolder; +import org.jetbrains.idea.maven.model.MavenArtifact; import org.jetbrains.idea.maven.project.*; -import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.utils.MavenJDOMUtil; import org.jetbrains.idea.maven.utils.MavenProcessCanceledException; @@ -65,7 +65,7 @@ public abstract class MavenImporter { return null; } - public void resolve(MavenProject project, org.apache.maven.project.MavenProject nativeMavenProject, MavenEmbedderWrapper embedder) + public void resolve(MavenProject project, NativeMavenProjectHolder nativeMavenProject, MavenEmbedderWrapper embedder) throws MavenProcessCanceledException { } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenModuleImporter.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenModuleImporter.java index 0161d147559a..1b4e3e54ed60 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenModuleImporter.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenModuleImporter.java @@ -21,8 +21,9 @@ import com.intellij.openapi.roots.ModifiableRootModel; import com.intellij.openapi.util.Pair; import com.intellij.pom.java.LanguageLevel; import org.jetbrains.annotations.Nullable; +import org.jetbrains.idea.maven.model.MavenArtifact; +import org.jetbrains.idea.maven.model.MavenConstants; import org.jetbrains.idea.maven.project.*; -import org.jetbrains.idea.maven.utils.MavenConstants; import org.jetbrains.idea.maven.utils.MavenUtil; import java.util.List; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenModuleNameMapper.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenModuleNameMapper.java index 14836bc6fc94..90429eb9e831 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenModuleNameMapper.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenModuleNameMapper.java @@ -18,7 +18,7 @@ package org.jetbrains.idea.maven.importing; import com.intellij.ide.highlighter.ModuleFileType; import com.intellij.openapi.module.Module; import com.intellij.openapi.util.text.StringUtil; -import org.jetbrains.idea.maven.project.MavenId; +import org.jetbrains.idea.maven.model.MavenId; import org.jetbrains.idea.maven.project.MavenProject; import java.io.File; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenProjectImporter.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenProjectImporter.java index 58cb185187d0..b0ffdf219a63 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenProjectImporter.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenProjectImporter.java @@ -37,7 +37,7 @@ import com.intellij.util.Function; import com.intellij.util.containers.Stack; import gnu.trove.THashMap; import gnu.trove.THashSet; -import org.jetbrains.idea.maven.embedder.MavenConsole; +import org.jetbrains.idea.maven.model.MavenArtifact; import org.jetbrains.idea.maven.project.*; import org.jetbrains.idea.maven.utils.MavenLog; import org.jetbrains.idea.maven.utils.MavenProcessCanceledException; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenRootModelAdapter.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenRootModelAdapter.java index 5ebda0447bf8..e678d1a840b0 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenRootModelAdapter.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenRootModelAdapter.java @@ -23,17 +23,17 @@ import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.JarFileSystem; +import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.pom.java.LanguageLevel; import org.jetbrains.annotations.Nullable; -import org.jetbrains.idea.maven.project.MavenArtifact; +import org.jetbrains.idea.maven.model.MavenArtifact; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.project.MavenProjectsManager; -import org.jetbrains.idea.maven.utils.MavenConstants; +import org.jetbrains.idea.maven.model.MavenConstants; import org.jetbrains.idea.maven.utils.Path; import org.jetbrains.idea.maven.utils.Url; import java.io.File; -import java.util.List; public class MavenRootModelAdapter { private static final String MAVEN_LIB_PREFIX = "Maven: "; @@ -250,7 +250,9 @@ public class MavenRootModelAdapter { extension = result.second; } - String newUrl = artifact.getUrlForExtraArtifact(classifier, extension); + + String newPath = artifact.getPathForExtraArtifact(classifier, extension); + String newUrl = VirtualFileManager.constructUrl(JarFileSystem.PROTOCOL, newPath) + JarFileSystem.JAR_SEPARATOR; for (String url : library.getUrls(type)) { if (newUrl.equals(url)) return; if (clearAll || isRepositoryUrl(artifact, url, classifier, extension)) { diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenArchetypesProvider.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenArchetypesProvider.java index db8dde2246d4..adafd0b80517 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenArchetypesProvider.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenArchetypesProvider.java @@ -16,11 +16,12 @@ package org.jetbrains.idea.maven.indices; import com.intellij.openapi.extensions.ExtensionPointName; +import org.jetbrains.idea.maven.model.MavenArchetype; import java.util.Collection; public interface MavenArchetypesProvider { ExtensionPointName EP_NAME = ExtensionPointName.create("org.jetbrains.idea.maven.archetypesProvider"); - Collection getArchetypes(); + Collection getArchetypes(); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenArtifactSearchDialog.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenArtifactSearchDialog.java index ea7ebf7ddd60..034a16e657da 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenArtifactSearchDialog.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenArtifactSearchDialog.java @@ -18,7 +18,7 @@ package org.jetbrains.idea.maven.indices; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import gnu.trove.THashMap; -import org.jetbrains.idea.maven.project.MavenId; +import org.jetbrains.idea.maven.model.MavenId; import javax.swing.*; import javax.swing.event.ChangeEvent; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenArtifactSearchPanel.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenArtifactSearchPanel.java index 7c1b3d290b7d..dd69617045b4 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenArtifactSearchPanel.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenArtifactSearchPanel.java @@ -24,9 +24,9 @@ import com.intellij.ui.treeStructure.Tree; import com.intellij.util.Alarm; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.tree.TreeUtil; -import org.jetbrains.idea.maven.project.MavenId; +import org.jetbrains.idea.maven.model.MavenArtifactInfo; +import org.jetbrains.idea.maven.model.MavenId; import org.jetbrains.idea.maven.utils.MavenLog; -import org.sonatype.nexus.index.ArtifactInfo; import javax.swing.*; import javax.swing.event.DocumentEvent; @@ -171,15 +171,15 @@ public class MavenArtifactSearchPanel extends JPanel { public MavenId getResult() { Object sel = myResultList.getLastSelectedPathComponent(); - ArtifactInfo info; - if (sel instanceof ArtifactInfo) { - info = (ArtifactInfo)sel; + MavenArtifactInfo info; + if (sel instanceof MavenArtifactInfo) { + info = (MavenArtifactInfo)sel; } else { info = ((MavenArtifactSearchResult)sel).versions.get(0); } - return new MavenId(info.groupId, info.artifactId, info.version); + return new MavenId(info.getGroupId(), info.getArtifactId(), info.getVersion()); } private static class MyTreeModel implements TreeModel { @@ -260,9 +260,9 @@ public class MavenArtifactSearchPanel extends JPanel { else if (value instanceof MavenArtifactSearchResult) { formatSearchResult(tree, (MavenArtifactSearchResult)value); } - else if (value instanceof ArtifactInfo) { - ArtifactInfo info = (ArtifactInfo)value; - myLeftComponent.append(info.groupId + ":" + info.artifactId + ":" + info.version, + else if (value instanceof MavenArtifactInfo) { + MavenArtifactInfo info = (MavenArtifactInfo)value; + myLeftComponent.append(info.getGroupId() + ":" + info.getArtifactId() + ":" + info.getVersion(), SimpleTextAttributes.GRAY_ATTRIBUTES); } @@ -277,10 +277,10 @@ public class MavenArtifactSearchPanel extends JPanel { } protected void formatSearchResult(JTree tree, MavenArtifactSearchResult searchResult) { - ArtifactInfo first = searchResult.versions.get(0); - ArtifactInfo last = searchResult.versions.get(searchResult.versions.size() - 1); - myLeftComponent.append(first.groupId + ":" + first.artifactId, SimpleTextAttributes.REGULAR_ATTRIBUTES); - myLeftComponent.append(":" + last.version + "-" + first.version, SimpleTextAttributes.GRAY_ATTRIBUTES); + MavenArtifactInfo first = searchResult.versions.get(0); + MavenArtifactInfo last = searchResult.versions.get(searchResult.versions.size() - 1); + myLeftComponent.append(first.getGroupId() + ":" + first.getArtifactId(), SimpleTextAttributes.REGULAR_ATTRIBUTES); + myLeftComponent.append(":" + last.getVersion() + "-" + first.getVersion(), SimpleTextAttributes.GRAY_ATTRIBUTES); } } @@ -288,12 +288,12 @@ public class MavenArtifactSearchPanel extends JPanel { @Override protected void formatSearchResult(JTree tree, MavenArtifactSearchResult searchResult) { MavenClassSearchResult classResult = (MavenClassSearchResult)searchResult; - ArtifactInfo info = searchResult.versions.get(0); + MavenArtifactInfo info = searchResult.versions.get(0); myLeftComponent.append(classResult.className, SimpleTextAttributes.REGULAR_ATTRIBUTES); myLeftComponent.append(" (" + classResult.packageName + ")", SimpleTextAttributes.GRAY_ATTRIBUTES); - myRightComponent.append(" " + info.groupId + ":" + info.artifactId, + myRightComponent.append(" " + info.getGroupId() + ":" + info.getArtifactId(), SimpleTextAttributes.GRAY_ATTRIBUTES); } } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenArtifactSearchResult.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenArtifactSearchResult.java index 574bcc1907fb..93b2c328b0f2 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenArtifactSearchResult.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenArtifactSearchResult.java @@ -15,11 +15,12 @@ */ package org.jetbrains.idea.maven.indices; -import org.sonatype.nexus.index.ArtifactInfo; -import java.util.List; +import org.jetbrains.idea.maven.model.MavenArtifactInfo; + import java.util.ArrayList; +import java.util.List; public class MavenArtifactSearchResult { - public List versions = new ArrayList(); + public List versions = new ArrayList(); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenArtifactSearcher.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenArtifactSearcher.java index 3e28e44396c3..dd8893f3bb8d 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenArtifactSearcher.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenArtifactSearcher.java @@ -20,11 +20,14 @@ import com.intellij.openapi.util.text.StringUtil; import gnu.trove.THashMap; import org.apache.lucene.index.Term; import org.apache.lucene.search.*; -import org.sonatype.nexus.index.ArtifactInfo; +import org.jetbrains.idea.maven.facade.MavenFacadeIndexer; +import org.jetbrains.idea.maven.model.MavenArtifactInfo; import java.util.*; public class MavenArtifactSearcher extends MavenSearcher { + public static final String TERM = MavenFacadeIndexer.SEARCH_TERM_COORDINATES; + protected Pair preparePatternAndQuery(String pattern) { pattern = pattern.toLowerCase(); if (pattern.trim().length() == 0) return Pair.create(pattern, (Query)new MatchAllDocsQuery()); @@ -37,31 +40,28 @@ public class MavenArtifactSearcher extends MavenSearcher= 3) { String s = "*" + parts.get(0) + "*|*" + parts.get(1) + "*|" + parts.get(2) + "*|*"; - query.add(new WildcardQuery(new Term(ArtifactInfo.UINFO, s)), BooleanClause.Occur.MUST); + query.add(new WildcardQuery(new Term(TERM, s)), BooleanClause.Occur.MUST); } return Pair.create(pattern, (Query)query); } - protected Collection processResults(Set infos, String pattern, int maxResult) { + protected Collection processResults(Set infos, String pattern, int maxResult) { Map result = new THashMap(); - for (ArtifactInfo each : infos) { - if (!StringUtil.isEmptyOrSpaces(each.classifier)) continue; // todo skip for now - + for (MavenArtifactInfo each : infos) { + if (!StringUtil.isEmptyOrSpaces(each.getClassifier())) continue; // todo skip for now + String key = makeKey(each); MavenArtifactSearchResult searchResult = result.get(key); if (searchResult == null) { diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenClassSearcher.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenClassSearcher.java index 231e6afc5586..805d1a7166b4 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenClassSearcher.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenClassSearcher.java @@ -22,7 +22,8 @@ import org.apache.lucene.index.Term; import org.apache.lucene.search.MatchAllDocsQuery; import org.apache.lucene.search.Query; import org.apache.lucene.search.WildcardQuery; -import org.sonatype.nexus.index.ArtifactInfo; +import org.jetbrains.idea.maven.facade.MavenFacadeIndexer; +import org.jetbrains.idea.maven.model.MavenArtifactInfo; import java.util.*; import java.util.regex.Matcher; @@ -30,6 +31,8 @@ import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; public class MavenClassSearcher extends MavenSearcher { + public static final String TERM = MavenFacadeIndexer.SEARCH_TERM_CLASS_NAMES; + protected Pair preparePatternAndQuery(String pattern) { pattern = pattern.toLowerCase(); if (pattern.trim().length() == 0) { @@ -53,10 +56,10 @@ public class MavenClassSearcher extends MavenSearcher { pattern = newPattern.toString(); String queryPattern = "*/" + pattern.replaceAll("\\.", "/"); - return new Pair(pattern, new WildcardQuery(new Term(ArtifactInfo.NAMES, queryPattern))); + return new Pair(pattern, new WildcardQuery(new Term(TERM, queryPattern))); } - protected Collection processResults(Set infos, String pattern, int maxResult) { + protected Collection processResults(Set infos, String pattern, int maxResult) { if (pattern.length() == 0 || pattern.equals("*")) { pattern = "^/(.*)$"; } @@ -84,10 +87,10 @@ public class MavenClassSearcher extends MavenSearcher { } Map result = new THashMap(); - for (ArtifactInfo each : infos) { - if (each.classNames == null) continue; + for (MavenArtifactInfo each : infos) { + if (each.getClassNames() == null) continue; - Matcher matcher = p.matcher(each.classNames); + Matcher matcher = p.matcher(each.getClassNames()); while (matcher.find()) { String classFQName = matcher.group(1); classFQName = classFQName.replace("/", "."); @@ -124,7 +127,7 @@ public class MavenClassSearcher extends MavenSearcher { return makeKey(result.className, result.versions.get(0)); } - private String makeKey(String className, ArtifactInfo info) { + private String makeKey(String className, MavenArtifactInfo info) { return className + " " + super.makeKey(info); } } \ No newline at end of file diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenIndex.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenIndex.java index 0931a02e86b7..f20318243e41 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenIndex.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenIndex.java @@ -15,35 +15,22 @@ */ package org.jetbrains.idea.maven.indices; -import com.intellij.openapi.progress.EmptyProgressIndicator; -import com.intellij.openapi.progress.ProgressIndicator; -import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.io.*; import gnu.trove.THashMap; import gnu.trove.THashSet; -import org.apache.lucene.document.Document; -import org.apache.lucene.index.IndexReader; -import org.apache.lucene.search.BooleanQuery; -import org.apache.lucene.search.Filter; import org.apache.lucene.search.Query; -import org.apache.lucene.search.TopDocs; -import org.apache.maven.artifact.manager.WagonManager; -import org.apache.maven.wagon.events.TransferEvent; import org.jetbrains.annotations.TestOnly; -import org.jetbrains.idea.maven.embedder.MavenEmbedderWrapper; -import org.jetbrains.idea.maven.project.TransferListenerAdapter; +import org.jetbrains.idea.maven.facade.MavenFacadeIndexerException; +import org.jetbrains.idea.maven.facade.MavenIndexerWrapper; +import org.jetbrains.idea.maven.model.MavenArtifactInfo; +import org.jetbrains.idea.maven.model.MavenId; +import org.jetbrains.idea.maven.project.MavenGeneralSettings; import org.jetbrains.idea.maven.utils.MavenLog; +import org.jetbrains.idea.maven.utils.MavenProcessCanceledException; import org.jetbrains.idea.maven.utils.MavenProgressIndicator; -import org.sonatype.nexus.index.*; -import org.sonatype.nexus.index.context.IndexUtils; -import org.sonatype.nexus.index.context.IndexingContext; -import org.sonatype.nexus.index.context.UnsupportedExistingLuceneIndexException; -import org.sonatype.nexus.index.updater.IndexUpdateRequest; -import org.sonatype.nexus.index.updater.IndexUpdater; import java.io.*; import java.util.*; @@ -75,8 +62,7 @@ public class MavenIndex { LOCAL, REMOTE } - private final NexusIndexer myIndexer; - private final ArtifactContextProducer myArtifactContextProducer; + private final MavenIndexerWrapper myIndexer; private final File myDir; private final String myRepositoryId; @@ -92,15 +78,13 @@ public class MavenIndex { private volatile boolean isBroken; private final IndexListener myListener; - public MavenIndex(NexusIndexer indexer, - ArtifactContextProducer artifactContextProducer, + public MavenIndex(MavenIndexerWrapper indexer, File dir, String repositoryId, String repositoryPathOrUrl, Kind kind, IndexListener listener) throws MavenIndexException { myIndexer = indexer; - myArtifactContextProducer = artifactContextProducer; myDir = dir; myRepositoryId = repositoryId; myRepositoryPathOrUrl = normalizePathOrUrl(repositoryPathOrUrl); @@ -110,12 +94,10 @@ public class MavenIndex { open(); } - public MavenIndex(NexusIndexer indexer, - ArtifactContextProducer artifactContextProducer, + public MavenIndex(MavenIndexerWrapper indexer, File dir, IndexListener listener) throws MavenIndexException { myIndexer = indexer; - myArtifactContextProducer = artifactContextProducer; myDir = dir; myListener = listener; @@ -211,7 +193,7 @@ public class MavenIndex { try { if (myData != null) myData.close(); } - catch (IOException e) { + catch (MavenIndexException e) { MavenLog.LOG.warn(e); } myData = null; @@ -278,19 +260,17 @@ public class MavenIndex { return myFailureMessage; } - public void updateOrRepair(MavenEmbedderWrapper embedderToUse, - IndexUpdater updater, - boolean fullUpdate, - ProgressIndicator progress) { + public void updateOrRepair(boolean fullUpdate, MavenGeneralSettings settings, MavenProgressIndicator progress) + throws MavenProcessCanceledException { try { if (fullUpdate) { if (myKind == Kind.LOCAL) FileUtil.delete(getUpdateDir()); - IndexingContext context = createContext(getUpdateDir(), "update"); + int context = createContext(getUpdateDir(), "update"); try { - updateContext(embedderToUse, context, updater, progress); + updateContext(context, settings, progress); } finally { - myIndexer.removeIndexingContext(context, false); + myIndexer.releaseIndex(context); } } updateData(progress); @@ -298,10 +278,10 @@ public class MavenIndex { isBroken = false; myFailureMessage = null; } - catch (IOException e) { - handleUpdateException(e); + catch (MavenProcessCanceledException e) { + throw e; } - catch (UnsupportedExistingLuceneIndexException e) { + catch (Exception e) { handleUpdateException(e); } @@ -313,64 +293,37 @@ public class MavenIndex { MavenLog.LOG.info("Failed to update Maven indices for: [" + myRepositoryId + "] " + myRepositoryPathOrUrl, e); } - private IndexingContext createContext(File contextDir, String suffix) throws IOException, UnsupportedExistingLuceneIndexException { + private int createContext(File contextDir, String suffix) throws MavenFacadeIndexerException { String indexId = myDir.getName() + "-" + suffix; // Nexus cannot update index if the id does not equal to the stored one. String repoId = contextDir.exists() ? null : myDir.getName(); - return myIndexer.addIndexingContext(indexId, - repoId, - getRepositoryFile(), - contextDir, - getRepositoryUrl(), - null, // repo update url - NexusIndexer.FULL_INDEX); + return myIndexer.createIndex(indexId, + repoId, + getRepositoryFile(), + getRepositoryUrl(), + contextDir); } private File getUpdateDir() { return new File(myDir, UPDATE_DIR); } - private void updateContext(MavenEmbedderWrapper embedder, - IndexingContext context, - IndexUpdater updater, - ProgressIndicator progress) throws IOException, UnsupportedExistingLuceneIndexException { - if (Kind.LOCAL == myKind) { - progress.setIndeterminate(true); - try { - myIndexer.scan(context, new MyScanningListener(), false); - } - finally { - progress.setIndeterminate(false); - } - } - else { - IndexUpdateRequest request = new IndexUpdateRequest(context); - request.setResourceFetcher(new MavenIndexFetcher(myRepositoryId, - getRepositoryUrl(), - embedder.getComponent(WagonManager.class), - new TransferListenerAdapter(new MavenProgressIndicator(progress)) { - @Override - protected void doUpdateProgress(long downloaded, long total) { - super.doUpdateProgress(downloaded, total); - myIndicator.setFraction(((double)downloaded) / total); - } - - @Override - public void transferCompleted(TransferEvent event) { - super.transferCompleted(event); - myIndicator.setText2(IndicesBundle.message("maven.indices.updating.processing")); - } - })); - updater.fetchAndUpdateIndex(request); - } + private void updateContext(int indexId, MavenGeneralSettings settings, MavenProgressIndicator progress) + throws MavenFacadeIndexerException, MavenProcessCanceledException { + myIndexer.updateIndex(indexId, settings, progress); } - private void updateData(ProgressIndicator progress) throws IOException, UnsupportedExistingLuceneIndexException { + private void updateData(MavenProgressIndicator progress) throws MavenIndexException { String newDataDirName; IndexData newData; newDataDirName = findAvailableDataDirName(); - FileUtil.copyDir(getUpdateDir(), getDataContextDir(getDataDir(newDataDirName))); + try { + FileUtil.copyDir(getUpdateDir(), getDataContextDir(getDataDir(newDataDirName))); + } + catch (IOException e) { + throw new MavenIndexException(e); + } newData = openData(newDataDirName); try { @@ -381,7 +334,8 @@ public class MavenIndex { newData.close(); FileUtil.delete(getDataDir(newDataDirName)); - if (e instanceof IOException) throw (IOException)e; + if (e instanceof MavenFacadeIndexerException) throw new MavenIndexException(e); + if (e instanceof IOException) throw new MavenIndexException(e); throw new RuntimeException(e); } @@ -402,7 +356,7 @@ public class MavenIndex { } private void doUpdateIndexData(IndexData data, - ProgressIndicator progress) throws IOException { + MavenProgressIndicator progress) throws IOException, MavenFacadeIndexerException { Set groups = new THashSet(); Set groupsWithArtifacts = new THashSet(); Set groupsWithArtifactsWithVersions = new THashSet(); @@ -410,23 +364,15 @@ public class MavenIndex { Map> groupToArtifactMap = new THashMap>(); Map> groupWithArtifactToVersionMap = new THashMap>(); - IndexReader r = data.context.getIndexReader(); - int total = r.numDocs(); + List artifacts = myIndexer.getAllArtifacts(data.indexId); + int total = artifacts.size(); for (int i = 0; i < total; i++) { progress.setFraction(i / total); + MavenId each = artifacts.get(i); - if (r.isDeleted(i)) continue; - - Document doc = r.document(i); - String uinfo = doc.get(ArtifactInfo.UINFO); - if (uinfo == null) continue; - - List parts = StringUtil.split(uinfo, "|"); - String groupId = parts.get(0); - String artifactId = parts.get(1); - String version = parts.get(2); - - if (groupId == null || artifactId == null || version == null) continue; + String groupId = each.getGroupId(); + String artifactId = each.getArtifactId(); + String version = each.getVersion(); groups.add(groupId); groupsWithArtifacts.add(groupId + ":" + artifactId); @@ -465,7 +411,7 @@ public class MavenIndex { } } - private IndexData openData(String dataDir) throws IOException, UnsupportedExistingLuceneIndexException { + private IndexData openData(String dataDir) throws MavenIndexException { File dir = getDataDir(dataDir); dir.mkdirs(); return new IndexData(dir); @@ -506,18 +452,11 @@ public class MavenIndex { public synchronized void addArtifact(final File artifactFile) { doIndexTask(new IndexTask() { public Object doTask() throws Exception { - ArtifactContext artifactContext = myArtifactContextProducer.getArtifactContext(myData.context, artifactFile); - if (artifactContext == null) return null; + MavenId id = myIndexer.addArtifact(myData.indexId, artifactFile); - myIndexer.addArtifactToIndex(artifactContext, myData.context); - - ArtifactInfo artifactInfo = artifactContext.getArtifactInfo(); - - String groupId = artifactInfo.groupId; - String artifactId = artifactInfo.artifactId; - String version = artifactInfo.version; - - if (groupId == null || artifactId == null || version == null) return null; + String groupId = id.getGroupId(); + String artifactId = id.getArtifactId(); + String version = id.getVersion(); myData.groups.enumerate(groupId); myData.hasGroupCache.put(groupId, true); @@ -615,36 +554,12 @@ public class MavenIndex { return result; } - public synchronized Set search(final Query query, final int maxResult) { - return doIndexTask(new IndexTask>() { - public Set doTask() throws Exception { - TopDocs docs = null; - - try { - BooleanQuery.setMaxClauseCount(Integer.MAX_VALUE); - docs = myData.context.getIndexSearcher().search(query, (Filter)null, maxResult); - } - catch (BooleanQuery.TooManyClauses ignore) { - // this exception occurs when too wide wildcard is used on too big data. - } - - if (docs.scoreDocs.length == 0) return Collections.emptySet(); - - Set result = new THashSet(); - - for (int i = 0; i < docs.scoreDocs.length; i++) { - int docIndex = docs.scoreDocs[i].doc; - Document doc = myData.context.getIndexReader().document(docIndex); - ArtifactInfo artifactInfo = IndexUtils.constructArtifactInfo(doc, myData.context); - - if (artifactInfo == null) continue; - - artifactInfo.repository = myRepositoryPathOrUrl; - result.add(artifactInfo); - } - return result; + public synchronized Set search(final Query query, final int maxResult) { + return doIndexTask(new IndexTask>() { + public Set doTask() throws Exception { + return myIndexer.search(myData.indexId, query, maxResult); } - }, Collections.emptySet()); + }, Collections.emptySet()); } private T doIndexTask(IndexTask task, T defaultValue) { @@ -672,7 +587,7 @@ public class MavenIndex { return defaultValue; } - private static interface IndexTask { + private interface IndexTask { T doTask() throws Exception; } @@ -688,9 +603,9 @@ public class MavenIndex { final Map hasArtifactCache = new THashMap(); final Map hasVersionCache = new THashMap(); - final IndexingContext context; + final int indexId; - public IndexData(File dir) throws IOException, UnsupportedExistingLuceneIndexException { + public IndexData(File dir) throws MavenIndexException { try { groups = new PersistentStringEnumerator(new File(dir, GROUP_IDS_FILE)); groupsWithArtifacts = new PersistentStringEnumerator(new File(dir, ARTIFACT_IDS_FILE)); @@ -699,15 +614,15 @@ public class MavenIndex { groupToArtifactMap = createPersistentMap(new File(dir, ARTIFACT_IDS_MAP_FILE)); groupWithArtifactToVersionMap = createPersistentMap(new File(dir, VERSIONS_MAP_FILE)); - context = createContext(getDataContextDir(dir), dir.getName()); + indexId = createContext(getDataContextDir(dir), dir.getName()); } catch (IOException e) { close(); - throw e; + throw new MavenIndexException(e); } - catch (UnsupportedExistingLuceneIndexException e) { + catch (MavenFacadeIndexerException e) { close(); - throw e; + throw new MavenIndexException(e); } } @@ -715,15 +630,15 @@ public class MavenIndex { return new PersistentHashMap>(f, new EnumeratorStringDescriptor(), new SetDescriptor()); } - public void close() throws IOException { - IOException[] exceptions = new IOException[1]; + public void close() throws MavenIndexException { + MavenIndexException[] exceptions = new MavenIndexException[1]; try { - if (context!= null) myIndexer.removeIndexingContext(context, false); + if (indexId != 0) myIndexer.releaseIndex(indexId); } - catch (IOException e) { + catch (MavenFacadeIndexerException e) { MavenLog.LOG.info(e); - if (exceptions[0] == null) exceptions[0] = e; + if (exceptions[0] == null) exceptions[0] = new MavenIndexException(e); } safeClose(groups, exceptions); @@ -736,13 +651,13 @@ public class MavenIndex { if (exceptions[0] != null) throw exceptions[0]; } - private void safeClose(PersistentEnumerator enumerator, IOException[] exceptions) throws IOException { + private void safeClose(PersistentEnumerator enumerator, MavenIndexException[] exceptions) { try { if (enumerator != null) enumerator.close(); } catch (IOException e) { MavenLog.LOG.info(e); - if (exceptions[0] == null) exceptions[0] = e; + if (exceptions[0] == null) exceptions[0] = new MavenIndexException(e); } } @@ -774,35 +689,7 @@ public class MavenIndex { } } - private static class MyScanningListener implements ArtifactScanningListener { - private final ProgressIndicator p; - - public MyScanningListener() { - ProgressIndicator p = ProgressManager.getInstance().getProgressIndicator(); - if (p == null) p = new EmptyProgressIndicator(); - this.p = p; - } - - public void scanningStarted(IndexingContext ctx) { - p.checkCanceled(); - } - - public void scanningFinished(IndexingContext ctx, ScanningResult result) { - p.checkCanceled(); - } - - public void artifactError(ArtifactContext ac, Exception e) { - } - - public void artifactDiscovered(ArtifactContext ac) { - p.checkCanceled(); - ArtifactInfo info = ac.getArtifactInfo(); - String artifact = info.groupId + ":" + info.artifactId + ":" + info.version; - p.setText2(artifact); - } - } - - public static interface IndexListener { + public interface IndexListener { void indexIsBroken(MavenIndex index); } } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenIndices.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenIndices.java index 2517688fb621..62ea3dd5282c 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenIndices.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenIndices.java @@ -16,24 +16,19 @@ package org.jetbrains.idea.maven.indices; import com.intellij.openapi.progress.ProcessCanceledException; -import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.util.io.FileUtil; -import org.jetbrains.annotations.TestOnly; -import org.jetbrains.idea.maven.embedder.MavenEmbedderWrapper; +import org.jetbrains.idea.maven.facade.MavenIndexerWrapper; +import org.jetbrains.idea.maven.project.MavenGeneralSettings; import org.jetbrains.idea.maven.utils.MavenLog; -import org.sonatype.nexus.index.ArtifactContextProducer; -import org.sonatype.nexus.index.NexusIndexer; -import org.sonatype.nexus.index.updater.IndexUpdater; +import org.jetbrains.idea.maven.utils.MavenProcessCanceledException; +import org.jetbrains.idea.maven.utils.MavenProgressIndicator; import java.io.File; import java.util.ArrayList; import java.util.List; public class MavenIndices { - private final MavenEmbedderWrapper myEmbedder; - private final NexusIndexer myIndexer; - private final IndexUpdater myUpdater; - private final ArtifactContextProducer myArtifactContextProducer; + private final MavenIndexerWrapper myIndexer; private final File myIndicesDir; private final MavenIndex.IndexListener myListener; @@ -41,15 +36,11 @@ public class MavenIndices { private final List myIndices = new ArrayList(); private static final Object ourDirectoryLock = new Object(); - public MavenIndices(MavenEmbedderWrapper embedder, File indicesDir, MavenIndex.IndexListener listener) { - myEmbedder = embedder; + public MavenIndices(MavenIndexerWrapper indexer, File indicesDir, MavenIndex.IndexListener listener) { + myIndexer = indexer; myIndicesDir = indicesDir; myListener = listener; - myIndexer = myEmbedder.getComponent(NexusIndexer.class); - myUpdater = myEmbedder.getComponent(IndexUpdater.class); - myArtifactContextProducer = myEmbedder.getComponent(ArtifactContextProducer.class); - load(); } @@ -62,7 +53,7 @@ public class MavenIndices { if (!each.isDirectory()) continue; try { - MavenIndex index = new MavenIndex(myIndexer, myArtifactContextProducer, each, myListener); + MavenIndex index = new MavenIndex(myIndexer, each, myListener); if (find(index.getRepositoryId(), index.getRepositoryPathOrUrl(), index.getKind()) != null) { index.close(); FileUtil.delete(each); @@ -77,11 +68,6 @@ public class MavenIndices { } } - @TestOnly - public NexusIndexer getIndexer() { - return myIndexer; - } - public synchronized void close() { for (MavenIndex each : myIndices) { each.close(); @@ -98,7 +84,7 @@ public class MavenIndices { if (index != null) return index; File dir = getAvailableIndexDir(); - index = new MavenIndex(myIndexer, myArtifactContextProducer, dir, repositoryId, repositoryPathOrUrl, kind, myListener); + index = new MavenIndex(myIndexer, dir, repositoryId, repositoryPathOrUrl, kind, myListener); myIndices.add(index); return index; } @@ -129,10 +115,8 @@ public class MavenIndices { } } - public void updateOrRepair(MavenIndex index, - MavenEmbedderWrapper embedderToUse, - boolean fullUpdate, - ProgressIndicator progress)throws ProcessCanceledException { - index.updateOrRepair(embedderToUse, myUpdater, fullUpdate, progress); + public void updateOrRepair(MavenIndex index, boolean fullUpdate, MavenGeneralSettings settings, MavenProgressIndicator progress) + throws MavenProcessCanceledException { + index.updateOrRepair(fullUpdate, settings, progress); } } \ No newline at end of file diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenIndicesManager.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenIndicesManager.java index de3e7e9c4394..df4ff90b3d8d 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenIndicesManager.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenIndicesManager.java @@ -16,42 +16,39 @@ package org.jetbrains.idea.maven.indices; import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.application.ReadAction; -import com.intellij.openapi.application.Result; import com.intellij.openapi.components.ApplicationComponent; +import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.progress.BackgroundTaskQueue; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; +import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.util.JDOMUtil; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.ShutDownTracker; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import gnu.trove.THashSet; -import org.apache.maven.archetype.catalog.Archetype; -import org.apache.maven.archetype.catalog.ArchetypeCatalog; -import org.apache.maven.archetype.source.ArchetypeDataSource; -import org.apache.maven.archetype.source.ArchetypeDataSourceException; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.TestOnly; -import org.jetbrains.idea.maven.embedder.MavenEmbedderWrapper; +import org.jetbrains.idea.maven.facade.MavenFacadeIndexer; +import org.jetbrains.idea.maven.facade.MavenFacadeManager; +import org.jetbrains.idea.maven.facade.MavenIndexerWrapper; +import org.jetbrains.idea.maven.model.MavenArchetype; import org.jetbrains.idea.maven.project.MavenGeneralSettings; import org.jetbrains.idea.maven.project.MavenProjectsManager; -import org.jetbrains.idea.maven.utils.MavenLog; -import org.jetbrains.idea.maven.utils.MavenRehighlighter; -import org.jetbrains.idea.maven.utils.MavenUtil; +import org.jetbrains.idea.maven.utils.*; import java.io.File; import java.io.IOException; import java.util.*; -public class MavenIndicesManager implements ApplicationComponent { +public class MavenIndicesManager { private static final String ELEMENT_ARCHETYPES = "archetypes"; private static final String ELEMENT_ARCHETYPE = "archetype"; private static final String ELEMENT_GROUP_ID = "groupId"; @@ -68,7 +65,7 @@ public class MavenIndicesManager implements ApplicationComponent { private volatile File myTestIndicesDir; - private volatile MavenEmbedderWrapper myEmbedder; + private volatile MavenIndexerWrapper myIndexer = MavenFacadeManager.getInstance().createIndexer(); private volatile MavenIndices myIndices; private final Object myUpdatingIndicesLock = new Object(); @@ -76,18 +73,10 @@ public class MavenIndicesManager implements ApplicationComponent { private volatile MavenIndex myUpdatingIndex; private final BackgroundTaskQueue myUpdatingQueue = new BackgroundTaskQueue(IndicesBundle.message("maven.indices.updating")); - private volatile List myUserArchetypes = new ArrayList(); + private volatile List myUserArchetypes = new ArrayList(); public static MavenIndicesManager getInstance() { - return ApplicationManager.getApplication().getComponent(MavenIndicesManager.class); - } - - @NotNull - public String getComponentName() { - return getClass().getSimpleName(); - } - - public void initComponent() { + return ServiceManager.getService(MavenIndicesManager.class); } @TestOnly @@ -103,9 +92,8 @@ public class MavenIndicesManager implements ApplicationComponent { private synchronized void ensureInitialized() { if (myIndices != null) return; - MavenGeneralSettings defaultSettings = new MavenGeneralSettings(); - myEmbedder = MavenEmbedderWrapper.create(defaultSettings); - myIndices = new MavenIndices(myEmbedder, getIndicesDir(), new MavenIndex.IndexListener() { + myIndexer = MavenFacadeManager.getInstance().createIndexer(); + myIndices = new MavenIndices(myIndexer, getIndicesDir(), new MavenIndex.IndexListener() { public void indexIsBroken(MavenIndex index) { scheduleUpdate(null, Collections.singletonList(index), false); } @@ -144,14 +132,14 @@ public class MavenIndicesManager implements ApplicationComponent { myIndices = null; } - if (myEmbedder != null) { + if (myIndexer != null) { try { - myEmbedder.release(); + myIndexer.release(); } catch (Exception e) { MavenLog.LOG.error("", e); } - myEmbedder = null; + myIndexer = null; } } @@ -236,12 +224,19 @@ public class MavenIndicesManager implements ApplicationComponent { myUpdatingQueue.run(new Task.Backgroundable(projectOrNull, IndicesBundle.message("maven.indices.updating"), true) { public void run(@NotNull ProgressIndicator indicator) { - doUpdateIndices(projectOrNull, toSchedule, fullUpdate, indicator); + try { + doUpdateIndices(projectOrNull, toSchedule, fullUpdate, new MavenProgressIndicator(indicator)); + } + catch (MavenProcessCanceledException ignore) { + } } }); } - private void doUpdateIndices(final Project projectOrNull, List indices, boolean fullUpdate, ProgressIndicator indicator) { + private void doUpdateIndices(final Project projectOrNull, List indices, boolean fullUpdate, MavenProgressIndicator indicator) + throws MavenProcessCanceledException { + MavenLog.LOG.assertTrue(!fullUpdate || projectOrNull != null); + List remainingWaiting = new ArrayList(indices); try { @@ -259,28 +254,8 @@ public class MavenIndicesManager implements ApplicationComponent { } try { - MavenEmbedderWrapper embedderToUse = null; - if (fullUpdate) { - embedderToUse = new ReadAction() { - @Override - protected void run(Result result) throws Throwable { - if (!projectOrNull.isDisposed()) { - MavenGeneralSettings settings = MavenProjectsManager.getInstance(projectOrNull).getGeneralSettings(); - result.setResult(MavenEmbedderWrapper.create(settings)); - } - } - }.execute().getResultObject(); - if (embedderToUse == null /* project disposed */) throw new ProcessCanceledException(); - } - - try { - getIndicesObject().updateOrRepair(each, embedderToUse, fullUpdate, indicator); - } - finally { - if (embedderToUse != null) embedderToUse.release(); - } - - scheduleRehighlightAllPoms(projectOrNull); + getIndicesObject().updateOrRepair(each, fullUpdate, fullUpdate ? getMavenSettings(projectOrNull) : null, indicator); + if (projectOrNull != null) MavenRehighlighter.rehighlight(projectOrNull); } finally { synchronized (myUpdatingIndicesLock) { @@ -289,8 +264,6 @@ public class MavenIndicesManager implements ApplicationComponent { } } } - catch (ProcessCanceledException ignore) { - } finally { synchronized (myUpdatingIndicesLock) { myWaitingIndices.removeAll(remainingWaiting); @@ -298,6 +271,10 @@ public class MavenIndicesManager implements ApplicationComponent { } } + private MavenGeneralSettings getMavenSettings(Project project) { + return MavenProjectsManager.getInstance(project).getGeneralSettings(); + } + public IndexUpdatingState getUpdatingState(MavenIndex index) { synchronized (myUpdatingIndicesLock) { if (myUpdatingIndex == index) return IndexUpdatingState.UPDATING; @@ -306,16 +283,9 @@ public class MavenIndicesManager implements ApplicationComponent { } } - private void scheduleRehighlightAllPoms(final Project projectOrNull) { - if (projectOrNull == null) return; - MavenRehighlighter.rehighlight(projectOrNull); - } - - public synchronized Set getArchetypes() { + public synchronized Set getArchetypes() { ensureInitialized(); - Set result = new THashSet(); - result.addAll(getArchetypesFrom("internal-catalog")); - result.addAll(getArchetypesFrom("nexus")); + Set result = new THashSet(myIndexer.getArchetypes()); result.addAll(myUserArchetypes); for (MavenArchetypesProvider each : Extensions.getExtensions(MavenArchetypesProvider.EP_NAME)) { @@ -324,7 +294,7 @@ public class MavenIndicesManager implements ApplicationComponent { return result; } - public synchronized void addArchetype(ArchetypeInfo archetype) { + public synchronized void addArchetype(MavenArchetype archetype) { ensureInitialized(); myUserArchetypes.add(archetype); saveUserArchetypes(); @@ -338,7 +308,7 @@ public class MavenIndicesManager implements ApplicationComponent { Document doc = JDOMUtil.loadDocument(file); Element root = doc.getRootElement(); if (root == null) return; - List result = new ArrayList(); + List result = new ArrayList(); for (Element each : (Iterable)root.getChildren(ELEMENT_ARCHETYPE)) { String groupId = each.getAttributeValue(ELEMENT_GROUP_ID); String artifactId = each.getAttributeValue(ELEMENT_ARTIFACT_ID); @@ -352,7 +322,7 @@ public class MavenIndicesManager implements ApplicationComponent { continue; } - result.add(new ArchetypeInfo(groupId, artifactId, version, repository, description)); + result.add(new MavenArchetype(groupId, artifactId, version, repository, description)); } myUserArchetypes = result; @@ -367,7 +337,7 @@ public class MavenIndicesManager implements ApplicationComponent { private void saveUserArchetypes() { Element root = new Element(ELEMENT_ARCHETYPES); - for (ArchetypeInfo each : myUserArchetypes) { + for (MavenArchetype each : myUserArchetypes) { Element childElement = new Element(ELEMENT_ARCHETYPE); childElement.setAttribute(ELEMENT_GROUP_ID, each.groupId); childElement.setAttribute(ELEMENT_ARTIFACT_ID, each.artifactId); @@ -393,22 +363,4 @@ public class MavenIndicesManager implements ApplicationComponent { private File getUserArchetypesFile() { return new File(getIndicesDir(), "UserArchetypes.xml"); } - - private List getArchetypesFrom(String roleHint) { - try { - ArchetypeDataSource source = myEmbedder.getComponent(ArchetypeDataSource.class, roleHint); - ArchetypeCatalog catalog = source.getArchetypeCatalog(new Properties()); - - List result = new ArrayList(); - for (Archetype each : (Iterable)catalog.getArchetypes()) { - result.add(new ArchetypeInfo(each)); - } - - return result; - } - catch (ArchetypeDataSourceException e) { - MavenLog.LOG.warn(e); - } - return Collections.emptyList(); - } } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenProjectIndicesManager.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenProjectIndicesManager.java index 05c197ae05ea..5d9434c6fd0b 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenProjectIndicesManager.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenProjectIndicesManager.java @@ -23,11 +23,13 @@ import com.intellij.util.ui.update.MergingUpdateQueue; import com.intellij.util.ui.update.Update; import gnu.trove.THashSet; import org.apache.lucene.search.Query; +import org.jetbrains.idea.maven.facade.NativeMavenProjectHolder; +import org.jetbrains.idea.maven.model.MavenArtifactInfo; +import org.jetbrains.idea.maven.model.MavenId; +import org.jetbrains.idea.maven.model.MavenRemoteRepository; import org.jetbrains.idea.maven.project.*; -import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.utils.MavenMergingUpdateQueue; import org.jetbrains.idea.maven.utils.SimpleProjectComponent; -import org.sonatype.nexus.index.ArtifactInfo; import java.io.File; import java.util.ArrayList; @@ -75,7 +77,7 @@ public class MavenProjectIndicesManager extends SimpleProjectComponent { @Override public void projectResolved(Pair projectWithChanges, - org.apache.maven.project.MavenProject nativeMavenProject, + NativeMavenProjectHolder nativeMavenProject, Object message) { scheduleUpdateIndicesList(); } @@ -191,8 +193,8 @@ public class MavenProjectIndicesManager extends SimpleProjectComponent { return checkLocalRepository(groupId, artifactId, version); } - public Set search(Query query, int maxResult) { - Set result = new THashSet(); + public Set search(Query query, int maxResult) { + Set result = new THashSet(); for (MavenIndex each : myProjectIndices) { int remained = maxResult - result.size(); diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenSearcher.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenSearcher.java index d1a0d030408a..7b9771eaa048 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenSearcher.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenSearcher.java @@ -16,18 +16,21 @@ package org.jetbrains.idea.maven.indices; import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Pair; import org.apache.lucene.search.Query; -import org.sonatype.nexus.index.ArtifactInfo; +import org.jetbrains.idea.maven.model.MavenArtifactInfo; import java.util.*; public abstract class MavenSearcher { + public static final VersionComparator COMPARATOR = new VersionComparator(); + public List search(Project project, String pattern, int maxResult) { Pair patternAndQuery = preparePatternAndQuery(pattern); MavenProjectIndicesManager m = MavenProjectIndicesManager.getInstance(project); - Set infos = m.search(patternAndQuery.second, maxResult); + Set infos = m.search(patternAndQuery.second, maxResult); List result = new ArrayList(processResults(infos, patternAndQuery.first, maxResult)); sort(result); @@ -35,11 +38,12 @@ public abstract class MavenSearcher preparePatternAndQuery(String pattern); - protected abstract Collection processResults(Set infos, String pattern, int maxResult); + + protected abstract Collection processResults(Set infos, String pattern, int maxResult); private void sort(List result) { - for (RESULT_TYPE each : result) { - Collections.sort(each.versions, ArtifactInfo.VERSION_COMPARATOR); + for (RESULT_TYPE each : result) { + Collections.sort(each.versions, COMPARATOR); } Collections.sort(result, new Comparator() { @@ -53,7 +57,28 @@ public abstract class MavenSearcher { + public int compare(MavenArtifactInfo f1, MavenArtifactInfo f2) { + int result = f1.getGroupId().compareTo(f2.getGroupId()); + if (result != 0) return result; + + result = f1.getArtifactId().compareTo(f2.getArtifactId()); + if (result != 0) return result; + + result = f2.getVersion().compareTo(f1.getVersion()); + if (result != 0) return result; + + result = Comparing.compare(f1.getClassifier(), f2. getClassifier()); + if (result != 0) return result; + + result = Comparing.compare(f1.getPackaging(), f2.getPackaging()); + if (result != 0) return result; + + return Comparing.compare(f1.getRepositoryId(), f2.getGroupId()); + } } } \ No newline at end of file diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/MavenNavigationUtil.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/MavenNavigationUtil.java index 0977a7c4e440..e8bdb82fbace 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/MavenNavigationUtil.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/MavenNavigationUtil.java @@ -25,8 +25,8 @@ import com.intellij.psi.xml.XmlDocument; import com.intellij.psi.xml.XmlFile; import com.intellij.psi.xml.XmlTag; import org.jetbrains.annotations.Nullable; -import org.jetbrains.idea.maven.project.MavenArtifact; -import org.jetbrains.idea.maven.project.MavenId; +import org.jetbrains.idea.maven.model.MavenArtifact; +import org.jetbrains.idea.maven.model.MavenId; import org.jetbrains.idea.maven.project.MavenProjectsManager; import org.jetbrains.idea.maven.utils.MavenArtifactUtil; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/MavenProjectsNavigator.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/MavenProjectsNavigator.java index 2f9497a9ac23..2fed5ca3415d 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/MavenProjectsNavigator.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/MavenProjectsNavigator.java @@ -37,6 +37,7 @@ import com.intellij.ui.treeStructure.SimpleTree; import com.intellij.util.containers.ContainerUtil; import org.jdom.Element; import org.jetbrains.annotations.TestOnly; +import org.jetbrains.idea.maven.facade.NativeMavenProjectHolder; import org.jetbrains.idea.maven.project.*; import org.jetbrains.idea.maven.tasks.MavenShortcutsManager; import org.jetbrains.idea.maven.tasks.MavenTasksManager; @@ -348,7 +349,7 @@ public class MavenProjectsNavigator extends SimpleProjectComponent implements Pe } public void projectResolved(Pair projectWithChanges, - org.apache.maven.project.MavenProject nativeMavenProject, + NativeMavenProjectHolder nativeMavenProject, Object message) { scheduleUpdateProjects(Collections.singletonList(projectWithChanges.first), Collections.EMPTY_LIST); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/MavenProjectsNavigatorPanel.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/MavenProjectsNavigatorPanel.java index a746dc289a89..95252e187fab 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/MavenProjectsNavigatorPanel.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/MavenProjectsNavigatorPanel.java @@ -29,9 +29,9 @@ import gnu.trove.THashMap; import gnu.trove.THashSet; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; -import org.jetbrains.idea.maven.embedder.MavenEmbedderWrapper; import org.jetbrains.idea.maven.execution.MavenGoalLocation; -import org.jetbrains.idea.maven.project.MavenArtifact; +import org.jetbrains.idea.maven.model.MavenArtifact; +import org.jetbrains.idea.maven.model.MavenConstants; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.utils.MavenDataKeys; @@ -210,7 +210,8 @@ public class MavenProjectsNavigatorPanel extends SimpleToolWindowPanel implement for (MavenProjectsStructure.BaseDependenciesNode each : nodes) { if (each instanceof MavenProjectsStructure.DependenciesNode) { result.addAll(each.getMavenProject().getDependencies()); - } else { + } + else { result.add(((MavenProjectsStructure.DependencyNode)each).getArtifact()); } } @@ -242,7 +243,7 @@ public class MavenProjectsNavigatorPanel extends SimpleToolWindowPanel implement if (standardGoalOrder == null) { standardGoalOrder = new THashMap(); int i = 0; - for (String aGoal : MavenEmbedderWrapper.PHASES) { + for (String aGoal : MavenConstants.PHASES) { standardGoalOrder.put(aGoal, i++); } } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/MavenProjectsStructure.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/MavenProjectsStructure.java index fc0b30bd0703..366428862934 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/MavenProjectsStructure.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/MavenProjectsStructure.java @@ -30,7 +30,9 @@ import gnu.trove.THashMap; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; -import org.jetbrains.idea.maven.embedder.MavenEmbedderWrapper; +import org.jetbrains.idea.maven.facade.MavenEmbedderWrapper; +import org.jetbrains.idea.maven.importing.MavenRootModelAdapter; +import org.jetbrains.idea.maven.model.*; import org.jetbrains.idea.maven.project.*; import org.jetbrains.idea.maven.tasks.MavenShortcutsManager; import org.jetbrains.idea.maven.tasks.MavenTasksManager; @@ -48,8 +50,8 @@ import static org.jetbrains.idea.maven.project.ProjectBundle.message; public class MavenProjectsStructure extends SimpleTreeStructure { private static final URL ERROR_ICON_URL = MavenProjectsStructure.class.getResource("/images/error.png"); - private static final Collection BASIC_PHASES = MavenEmbedderWrapper.BASIC_PHASES; - private static final Collection PHASES = MavenEmbedderWrapper.PHASES; + private static final Collection BASIC_PHASES = MavenConstants.BASIC_PHASES; + private static final Collection PHASES = MavenConstants.PHASES; private static final Comparator NODE_COMPARATOR = new Comparator() { public int compare(MavenSimpleNode o1, MavenSimpleNode o2) { @@ -106,7 +108,7 @@ public class MavenProjectsStructure extends SimpleTreeStructure { } public MavenUIUtil.CheckBoxState getState(Object userObject) { - MavenProfileState state = ((ProfileNode)userObject).getState(); + MavenProfileKind state = ((ProfileNode)userObject).getState(); switch (state) { case NONE: return MavenUIUtil.CheckBoxState.UNCHECKED; case EXPLICIT: return MavenUIUtil.CheckBoxState.CHECKED; @@ -563,10 +565,10 @@ public class MavenProjectsStructure extends SimpleTreeStructure { } public void updateProfiles() { - Collection> profiles = myProjectsManager.getProfilesWithStates(); + Collection> profiles = myProjectsManager.getProfilesWithStates(); List newNodes = new ArrayList(profiles.size()); - for (Pair each : profiles) { + for (Pair each : profiles) { ProfileNode node = findOrCreateNodeFor(each.first); node.setState(each.second); newNodes.add(node); @@ -587,7 +589,7 @@ public class MavenProjectsStructure extends SimpleTreeStructure { public class ProfileNode extends MavenSimpleNode { private final String myProfileName; - private MavenProfileState myState; + private MavenProfileKind myState; public ProfileNode(ProfilesNode parent, String profileName) { super(parent); @@ -603,11 +605,11 @@ public class MavenProjectsStructure extends SimpleTreeStructure { return myProfileName; } - public MavenProfileState getState() { + public MavenProfileKind getState() { return myState; } - private void setState(MavenProfileState state) { + private void setState(MavenProfileKind state) { myState = state; } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenArtifactDownloader.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenArtifactDownloader.java index 05d8ba911168..cf5399ad8dec 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenArtifactDownloader.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenArtifactDownloader.java @@ -20,10 +20,10 @@ import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.LocalFileSystem; import gnu.trove.THashMap; import gnu.trove.THashSet; -import org.apache.maven.artifact.Artifact; import org.jetbrains.annotations.Nullable; -import org.jetbrains.idea.maven.embedder.MavenEmbedderWrapper; +import org.jetbrains.idea.maven.facade.MavenEmbedderWrapper; import org.jetbrains.idea.maven.importing.MavenExtraArtifactType; +import org.jetbrains.idea.maven.model.*; import org.jetbrains.idea.maven.utils.MavenLog; import org.jetbrains.idea.maven.utils.MavenProcessCanceledException; import org.jetbrains.idea.maven.utils.MavenProgressIndicator; @@ -115,7 +115,7 @@ public class MavenArtifactDownloader { for (MavenArtifact eachDependency : eachProject.getDependencies()) { if (myArtifacts != null && !myArtifacts.contains(eachDependency)) continue; - if (Artifact.SCOPE_SYSTEM.equalsIgnoreCase(eachDependency.getScope())) continue; + if (MavenConstants.SCOPE_SYSTEM.equalsIgnoreCase(eachDependency.getScope())) continue; if (myProjectsTree.findProject(eachDependency.getMavenId()) != null) continue; if (!eachProject.isSupportedDependency(eachDependency)) continue; @@ -164,8 +164,8 @@ public class MavenArtifactDownloader { myProgress.checkCanceled(); myProgress.setFraction(((double)downloaded.getAndIncrement()) / finalTotal); - MavenArtifact a = myEmbedder.resolve(id, eachElement.extension, eachElement.classifier, - new ArrayList(data.repositories)); + MavenArtifact a = myEmbedder.resolve(new MavenArtifactInfo(id, eachElement.extension, eachElement.classifier), + new ArrayList(data.repositories)); File file = a.getFile(); if (file.exists()) { synchronized (downloadedFiles) { diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/MavenConsole.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenConsole.java similarity index 62% rename from plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/MavenConsole.java rename to plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenConsole.java index 3aee5c9e4126..46fe999eff04 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/MavenConsole.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenConsole.java @@ -13,45 +13,37 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.idea.maven.embedder; +package org.jetbrains.idea.maven.project; import com.intellij.execution.process.ProcessHandler; import com.intellij.openapi.util.text.StringUtil; import gnu.trove.THashMap; -import org.apache.maven.plugin.AbstractMojoExecutionException; +import org.jetbrains.idea.maven.execution.MavenExecutionOptions; +import org.jetbrains.idea.maven.execution.RunnerBundle; +import org.jetbrains.idea.maven.facade.MavenFacadeConsole; import java.text.MessageFormat; import java.util.Map; public abstract class MavenConsole { - public static final int LEVEL_AUTO = -1; - public static final int LEVEL_DEBUG = 0; - public static final int LEVEL_INFO = 1; - public static final int LEVEL_WARN = 2; - public static final int LEVEL_ERROR = 3; - public static final int LEVEL_FATAL = 4; - public static final int LEVEL_DISABLED = 5; - public static final int LEVEL_ALWAYS = 6; - - public static final String LINE_SEPARATOR = System.getProperty("line.separator"); + private static final String LINE_SEPARATOR = System.getProperty("line.separator"); public enum OutputType { NORMAL, SYSTEM, ERROR } private final int myOutputLevel; - private final boolean myPrintStrackTrace; private boolean isFinished; private static final Map PREFIX_TO_LEVEL = new THashMap(); private static final Map LEVEL_TO_PREFIX = new THashMap(); static { - map("DEBUG", LEVEL_DEBUG); - map("INFO", LEVEL_INFO); - map("WARNING", LEVEL_WARN); - map("ERROR", LEVEL_ERROR); - map("FATAL_ERROR", LEVEL_FATAL); + map("DEBUG", MavenFacadeConsole.LEVEL_DEBUG); + map("INFO", MavenFacadeConsole.LEVEL_INFO); + map("WARNING", MavenFacadeConsole.LEVEL_WARN); + map("ERROR", MavenFacadeConsole.LEVEL_ERROR); + map("FATAL_ERROR", MavenFacadeConsole.LEVEL_FATAL); } private static void map(String prefix, int level) { @@ -61,7 +53,6 @@ public abstract class MavenConsole { public MavenConsole(MavenExecutionOptions.LoggingLevel outputLevel, boolean printStrackTrace) { myOutputLevel = outputLevel.getLevel(); - myPrintStrackTrace = printStrackTrace; } public boolean isSuppressed(int level) { @@ -88,6 +79,10 @@ public abstract class MavenConsole { public abstract void attachToProcess(ProcessHandler processHandler); + public void printException(Throwable throwable) { + systemMessage(MavenFacadeConsole.LEVEL_ERROR, RunnerBundle.message("embedded.build.failed"), throwable); + } + public void systemMessage(int level, String string, Throwable throwable) { printMessage(level, string, throwable); } @@ -96,51 +91,62 @@ public abstract class MavenConsole { if (isSuppressed(level)) return; OutputType type = OutputType.NORMAL; - if (throwable != null || level == LEVEL_WARN || level == LEVEL_ERROR || level == LEVEL_FATAL) { + if (throwable != null + || level == MavenFacadeConsole.LEVEL_WARN + || level == MavenFacadeConsole.LEVEL_ERROR + || level == MavenFacadeConsole.LEVEL_FATAL) { type = OutputType.ERROR; } doPrint(composeLine(level, string), type); - if (level == LEVEL_FATAL) { + if (level == MavenFacadeConsole.LEVEL_FATAL) { setOutputPaused(false); } if (throwable != null) { - String message = null; - - Throwable temp = throwable; - while (temp != null) { - if (temp instanceof AbstractMojoExecutionException) { - message = appendExecutionFailureMessage(message, temp.getMessage()); - message = appendExecutionFailureMessage(message, ((AbstractMojoExecutionException)temp).getLongMessage()); - - if (temp.getCause() != null) { - message = appendExecutionFailureMessage(message, temp.getCause().getMessage()); - } - break; - } - temp = temp.getCause(); - } - - if (message == null) message = throwable.getMessage(); - + String message = throwable.getMessage(); if (message != null) { message += LINE_SEPARATOR; - doPrint(LINE_SEPARATOR + composeLine(LEVEL_ERROR, message), type); - } - - if (myPrintStrackTrace) { - doPrint(LINE_SEPARATOR + StringUtil.getThrowableText(throwable), OutputType.ERROR); - } - else { - doPrint(LINE_SEPARATOR + - "To view full stack traces, please go to the Settings->Maven and check the 'Print Exception Stack Traces' box." + - LINE_SEPARATOR, - type); + doPrint(LINE_SEPARATOR + composeLine(MavenFacadeConsole.LEVEL_ERROR, message), type); } } } + // todo + // if (throwable != null) { + // String message = null; + // + // Throwable temp = throwable; + // while (temp != null) { + // if (temp instanceof AbstractMojoExecutionException) { + // message = appendExecutionFailureMessage(message, temp.getMessage()); + // message = appendExecutionFailureMessage(message, ((AbstractMojoExecutionException)temp).getLongMessage()); + // + // if (temp.getCause() != null) { + // message = appendExecutionFailureMessage(message, temp.getCause().getMessage()); + // } + // break; + // } + // temp = temp.getCause(); + // } + // + // if (message == null) message = throwable.getMessage(); + // + // if (message != null) { + // message += LINE_SEPARATOR; + // doPrint(LINE_SEPARATOR + composeLine(LEVEL_ERROR, message), type); + // } + // + // if (myPrintStrackTrace) { + // doPrint(LINE_SEPARATOR + StringUtil.getThrowableText(throwable), OutputType.ERROR); + // } + // else { + // doPrint(LINE_SEPARATOR + + // "To view full stack traces, please go to the Settings->Maven and check the 'Print Exception Stack Traces' box." + + // LINE_SEPARATOR, + // type); + // } + //} private String appendExecutionFailureMessage(String message, String newMessage) { if (message == null) return newMessage; @@ -166,7 +172,7 @@ public abstract class MavenConsole { private static int getLevelByPrefix(String prefix) { Integer level = PREFIX_TO_LEVEL.get(prefix); - return level != null ? level : LEVEL_ALWAYS; + return level != null ? level : MavenFacadeConsole.LEVEL_WARN; } private static String composeLine(int level, String message) { diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/MavenConsoleImpl.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenConsoleImpl.java similarity index 97% rename from plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/MavenConsoleImpl.java rename to plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenConsoleImpl.java index f14e66faf49d..7d04d8dba13b 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/embedder/MavenConsoleImpl.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenConsoleImpl.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.idea.maven.embedder; +package org.jetbrains.idea.maven.project; import com.intellij.execution.filters.*; import com.intellij.execution.process.ProcessAdapter; @@ -30,8 +30,6 @@ import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.ui.content.Content; import com.intellij.ui.content.ContentFactory; import com.intellij.ui.content.MessageView; -import org.jetbrains.idea.maven.project.MavenGeneralSettings; -import org.jetbrains.idea.maven.project.MavenProjectsManager; import org.jetbrains.idea.maven.execution.MavenRunnerParameters; import org.jetbrains.idea.maven.execution.MavenRunnerSettings; import org.jetbrains.idea.maven.utils.MavenUtil; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenEmbeddersManager.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenEmbeddersManager.java index a187b202b565..cf00a48dacad 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenEmbeddersManager.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenEmbeddersManager.java @@ -15,32 +15,36 @@ */ package org.jetbrains.idea.maven.project; +import com.intellij.openapi.Disposable; +import com.intellij.openapi.components.ServiceManager; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.Disposer; +import com.intellij.openapi.util.Key; import com.intellij.util.Function; import com.intellij.util.containers.SoftValueHashMap; import gnu.trove.THashSet; -import org.jetbrains.idea.maven.embedder.MavenEmbedderWrapper; +import org.jetbrains.idea.maven.facade.MavenEmbedderWrapper; +import org.jetbrains.idea.maven.facade.MavenFacadeManager; import org.jetbrains.idea.maven.utils.MavenLog; import java.util.Map; import java.util.Set; public class MavenEmbeddersManager { - public enum EmbedderKind { - FOR_DEPENDENCIES_RESOLVE, - FOR_PLUGINS_RESOLVE, - FOR_FOLDERS_RESOLVE, - FOR_DOWNLOAD, - FOR_POST_PROCESSING, - } + public static final Key FOR_DEPENDENCIES_RESOLVE = Key.create(MavenEmbeddersManager.class + ".FOR_DEPENDENCIES_RESOLVE"); + public static final Key FOR_PLUGINS_RESOLVE = Key.create(MavenEmbeddersManager.class + ".FOR_PLUGINS_RESOLVE"); + public static final Key FOR_FOLDERS_RESOLVE = Key.create(MavenEmbeddersManager.class + ".FOR_FOLDERS_RESOLVE"); + public static final Key FOR_DOWNLOAD = Key.create(MavenEmbeddersManager.class + ".FOR_DOWNLOAD"); + public static final Key FOR_POST_PROCESSING = Key.create(MavenEmbeddersManager.class + ".FOR_POST_PROCESSING"); - private final MavenGeneralSettings myGeneralSettings; + private final Project myProject; - private final Map myPool = new SoftValueHashMap(); + private final Map myPool = new SoftValueHashMap(); private final Set myEmbeddersInUse = new THashSet(); private final Set myEmbeddersToClear = new THashSet(); - public MavenEmbeddersManager(MavenGeneralSettings generalSettings) { - myGeneralSettings = generalSettings; + public MavenEmbeddersManager(Project project) { + myProject = project; } public synchronized void reset() { @@ -57,16 +61,16 @@ public class MavenEmbeddersManager { myEmbeddersToClear.addAll(myEmbeddersInUse); } - public synchronized MavenEmbedderWrapper getEmbedder(EmbedderKind kind) { + public synchronized MavenEmbedderWrapper getEmbedder(Key kind) { MavenEmbedderWrapper result = myPool.get(kind); if (result == null) { - result = MavenEmbedderWrapper.create(myGeneralSettings); + result = MavenFacadeManager.getInstance().createEmbedder(myProject); myPool.put(kind, result); } if (myEmbeddersInUse.contains(result)) { MavenLog.LOG.warn("embedder " + kind + " is already used"); - return MavenEmbedderWrapper.create(myGeneralSettings); + return MavenFacadeManager.getInstance().createEmbedder(myProject); } myEmbeddersInUse.add(result); @@ -80,7 +84,9 @@ public class MavenEmbeddersManager { return; } + embedder.reset(); myEmbeddersInUse.remove(embedder); + if (myEmbeddersToClear.contains(embedder)) { embedder.clearCaches(); myEmbeddersToClear.remove(embedder); @@ -111,7 +117,7 @@ public class MavenEmbeddersManager { } private void forEachPooled(boolean includeInUse, Function func) { - for (EmbedderKind each : myPool.keySet()) { + for (Key each : myPool.keySet()) { MavenEmbedderWrapper embedder = myPool.get(each); if (embedder == null) continue; // collected if (!includeInUse && myEmbeddersInUse.contains(embedder)) continue; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenEnvironmentForm.form b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenEnvironmentForm.form index fd0eca592c95..f972ad1dd8c4 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenEnvironmentForm.form +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenEnvironmentForm.form @@ -1,9 +1,9 @@ - + - + @@ -42,26 +42,9 @@ - - - - - - - - - - - - - - - - - - + diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenEnvironmentForm.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenEnvironmentForm.java index 37059c60ac3e..187501715362 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenEnvironmentForm.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenEnvironmentForm.java @@ -22,7 +22,7 @@ import com.intellij.openapi.ui.LabeledComponent; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.openapi.util.text.StringUtil; import org.jetbrains.annotations.Nullable; -import org.jetbrains.idea.maven.embedder.MavenEmbedderUtilEx; +import org.jetbrains.idea.maven.utils.MavenUtil; import javax.swing.*; import java.awt.event.ActionEvent; @@ -32,21 +32,18 @@ import java.io.File; public class MavenEnvironmentForm { private JPanel panel; private LabeledComponent mavenHomeComponent; - private LabeledComponent localRepositoryComponent; private LabeledComponent mavenSettingsFileComponent; private JCheckBox mavenHomeOverrideCheckBox; private JCheckBox mavenSettingsFileOverrideCheckBox; - private JCheckBox localRepositoryOverrideCheckBox; private final PathOverrider mavenHomeOverrider; private final PathOverrider mavenSettingsFileOverrider; - private final PathOverrider localRepositoryOverrider; public MavenEnvironmentForm() { mavenHomeOverrider = new PathOverrider(mavenHomeComponent, mavenHomeOverrideCheckBox, new PathOverrider.PathProvider() { @Nullable protected File getFile() { - return MavenEmbedderUtilEx.resolveMavenHomeDirectory(""); + return MavenUtil.resolveMavenHomeDirectory(""); } }); @@ -54,17 +51,7 @@ public class MavenEnvironmentForm { new PathOverrider(mavenSettingsFileComponent, mavenSettingsFileOverrideCheckBox, new PathOverrider.PathProvider() { @Nullable protected File getFile() { - return MavenEmbedderUtilEx.resolveUserSettingsFile(""); - } - }); - - localRepositoryOverrider = - new PathOverrider(localRepositoryComponent, localRepositoryOverrideCheckBox, new PathOverrider.PathProvider() { - @Nullable - protected File getFile() { - return MavenEmbedderUtilEx.resolveLocalRepository(mavenHomeOverrider.getText(), - mavenSettingsFileOverrider.getText(), - ""); + return MavenUtil.resolveUserSettingsFile(""); } }); } @@ -78,13 +65,11 @@ public class MavenEnvironmentForm { public void setData(MavenGeneralSettings data) { data.setMavenHome(mavenHomeOverrider.getText()); data.setMavenSettingsFile(mavenSettingsFileOverrider.getText()); - data.setLocalRepository(localRepositoryOverrider.getText()); } public void getData(MavenGeneralSettings data) { mavenHomeOverrider.setText(data.getMavenHome()); mavenSettingsFileOverrider.setText(data.getMavenSettingsFile()); - localRepositoryOverrider.setText(data.getLocalRepository()); } public JComponent createComponent() { @@ -93,9 +78,6 @@ public class MavenEnvironmentForm { new FileChooserDescriptor(false, true, false, false, false, false)); mavenSettingsFileComponent.getComponent().addBrowseFolderListener(ProjectBundle.message("maven.select.maven.settings.file"), "", null, new FileChooserDescriptor(true, false, false, false, false, false)); - localRepositoryComponent.getComponent().addBrowseFolderListener(ProjectBundle.message("maven.select.local.repository"), "", null, - new FileChooserDescriptor(false, true, false, false, false, false)); - return panel; } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenGeneralConfigurable.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenGeneralConfigurable.java index f20b862ef215..a2857989698e 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenGeneralConfigurable.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenGeneralConfigurable.java @@ -23,7 +23,7 @@ import com.intellij.util.Function; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; -import org.jetbrains.idea.maven.embedder.MavenExecutionOptions; +import org.jetbrains.idea.maven.execution.MavenExecutionOptions; import org.jetbrains.idea.maven.utils.ComboBoxUtil; import javax.swing.*; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenGeneralSettings.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenGeneralSettings.java index d3ab6ad2d966..8294bbeec711 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenGeneralSettings.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenGeneralSettings.java @@ -23,9 +23,9 @@ import gnu.trove.THashSet; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.idea.maven.embedder.MavenEmbedderUtilEx; -import org.jetbrains.idea.maven.embedder.MavenExecutionOptions; +import org.jetbrains.idea.maven.execution.MavenExecutionOptions; import org.jetbrains.idea.maven.utils.MavenJDOMUtil; +import org.jetbrains.idea.maven.utils.MavenUtil; import java.io.File; import java.util.ArrayList; @@ -37,7 +37,7 @@ public class MavenGeneralSettings implements Cloneable { private boolean workOffline = false; private String mavenHome = ""; private String mavenSettingsFile = ""; - private String localRepository = ""; + private String overridenLocalRepository = ""; private boolean printErrorStackTraces = false; private boolean usePluginRegistry = false; private boolean nonRecursive = false; @@ -52,7 +52,9 @@ public class MavenGeneralSettings implements Cloneable { private List myListeners = ContainerUtil.createEmptyCOWList(); - public @NotNull MavenExecutionOptions.PluginUpdatePolicy getPluginUpdatePolicy() { + public + @NotNull + MavenExecutionOptions.PluginUpdatePolicy getPluginUpdatePolicy() { return pluginUpdatePolicy; } @@ -81,7 +83,9 @@ public class MavenGeneralSettings implements Cloneable { this.failureBehavior = value; } - public @NotNull MavenExecutionOptions.LoggingLevel getLoggingLevel() { + public + @NotNull + MavenExecutionOptions.LoggingLevel getLoggingLevel() { return outputLevel; } @@ -90,7 +94,9 @@ public class MavenGeneralSettings implements Cloneable { this.outputLevel = value; } - public @NotNull MavenExecutionOptions.SnapshotUpdatePolicy getSnapshotUpdatePolicy() { + public + @NotNull + MavenExecutionOptions.SnapshotUpdatePolicy getSnapshotUpdatePolicy() { return snapshotUpdatePolicy; } @@ -108,23 +114,23 @@ public class MavenGeneralSettings implements Cloneable { } @NotNull - public String getLocalRepository() { - return localRepository; + public String getOverridenLocalRepository() { + return overridenLocalRepository; } public File getEffectiveLocalRepository() { File result = myEffectiveLocalRepositoryCache; if (result != null) return result; - result = MavenEmbedderUtilEx.resolveLocalRepository(mavenHome, mavenSettingsFile, localRepository); + result = MavenUtil.resolveLocalRepository(overridenLocalRepository, mavenHome, mavenSettingsFile); myEffectiveLocalRepositoryCache = result; return result; } - public void setLocalRepository(final @Nullable String localRepository) { - if (localRepository != null) { - if (!Comparing.equal(this.localRepository, localRepository)) { - this.localRepository = localRepository; + public void setOverridenLocalRepository(final @Nullable String overridenLocalRepository) { + if (overridenLocalRepository != null) { + if (!Comparing.equal(this.overridenLocalRepository, overridenLocalRepository)) { + this.overridenLocalRepository = overridenLocalRepository; localRepositoryChanged(); } @@ -147,7 +153,7 @@ public class MavenGeneralSettings implements Cloneable { @Nullable public File getEffectiveMavenHome() { - return MavenEmbedderUtilEx.resolveMavenHomeDirectory(getMavenHome()); + return MavenUtil.resolveMavenHomeDirectory(getMavenHome()); } @NotNull @@ -175,12 +181,12 @@ public class MavenGeneralSettings implements Cloneable { @Nullable public File getEffectiveUserSettingsIoFile() { - return MavenEmbedderUtilEx.resolveUserSettingsFile(getMavenSettingsFile()); + return MavenUtil.resolveUserSettingsFile(getMavenSettingsFile()); } @Nullable public File getEffectiveGlobalSettingsIoFile() { - return MavenEmbedderUtilEx.resolveGlobalSettingsFile(getMavenHome()); + return MavenUtil.resolveGlobalSettingsFile(getMavenHome()); } @Nullable @@ -206,7 +212,7 @@ public class MavenGeneralSettings implements Cloneable { @NotNull public VirtualFile getEffectiveSuperPom() { - return MavenEmbedderUtilEx.resolveSuperPomFile(getMavenHome()); + return MavenUtil.resolveSuperPomFile(getEffectiveMavenHome()); } public boolean isDefaultPlugin(String groupId, String artifactId) { @@ -269,7 +275,7 @@ public class MavenGeneralSettings implements Cloneable { if (workOffline != that.workOffline) return false; if (!checksumPolicy.equals(that.checksumPolicy)) return false; if (!failureBehavior.equals(that.failureBehavior)) return false; - if (!localRepository.equals(that.localRepository)) return false; + if (!overridenLocalRepository.equals(that.overridenLocalRepository)) return false; if (!mavenHome.equals(that.mavenHome)) return false; if (!mavenSettingsFile.equals(that.mavenSettingsFile)) return false; @@ -281,7 +287,7 @@ public class MavenGeneralSettings implements Cloneable { result = (workOffline ? 1 : 0); result = 31 * result + mavenHome.hashCode(); result = 31 * result + mavenSettingsFile.hashCode(); - result = 31 * result + localRepository.hashCode(); + result = 31 * result + overridenLocalRepository.hashCode(); result = 31 * result + (printErrorStackTraces ? 1 : 0); result = 31 * result + (usePluginRegistry ? 1 : 0); result = 31 * result + (nonRecursive ? 1 : 0); diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenParentDesc.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenParentDesc.java index 8080ce11ff7f..4a497b4fd8ca 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenParentDesc.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenParentDesc.java @@ -16,6 +16,7 @@ package org.jetbrains.idea.maven.project; import org.jetbrains.annotations.NotNull; +import org.jetbrains.idea.maven.model.MavenId; public class MavenParentDesc { private final MavenId myParentId; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenParentProjectFileProcessor.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenParentProjectFileProcessor.java index 543b71d587d9..6c243cbaa20d 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenParentProjectFileProcessor.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenParentProjectFileProcessor.java @@ -19,8 +19,9 @@ import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.idea.maven.model.MavenConstants; +import org.jetbrains.idea.maven.model.MavenId; import org.jetbrains.idea.maven.utils.MavenArtifactUtil; -import org.jetbrains.idea.maven.utils.MavenConstants; import java.io.File; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProject.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProject.java index b16a233d3891..92a679924f80 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProject.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProject.java @@ -26,17 +26,14 @@ import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import gnu.trove.THashMap; import gnu.trove.THashSet; -import gnu.trove.TObjectIdentityHashingStrategy; -import org.apache.maven.artifact.Artifact; -import org.apache.maven.model.*; -import org.apache.maven.shared.dependency.tree.DependencyNode; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.idea.maven.embedder.MavenConsole; -import org.jetbrains.idea.maven.embedder.MavenEmbedderWrapper; +import org.jetbrains.idea.maven.facade.MavenEmbedderWrapper; +import org.jetbrains.idea.maven.facade.NativeMavenProjectHolder; import org.jetbrains.idea.maven.importing.MavenExtraArtifactType; import org.jetbrains.idea.maven.importing.MavenImporter; +import org.jetbrains.idea.maven.model.*; import org.jetbrains.idea.maven.utils.*; import java.io.*; @@ -100,51 +97,44 @@ public class MavenProject { } private MavenProjectChanges set(MavenProjectReaderResult readerResult, + MavenGeneralSettings settings, boolean updateLastReadStamp, boolean resetArtifacts, boolean resetProfiles) { State newState = myState.clone(); - if (updateLastReadStamp) newState.myLastReadStamp++; - - org.apache.maven.project.MavenProject nativeMavenProject = readerResult.nativeMavenProject; + if (updateLastReadStamp) newState.myLastReadStamp = myState.myLastReadStamp + 1; newState.myReadingProblems = readerResult.readingProblems; - newState.myLocalRepository = readerResult.localRepository; + newState.myLocalRepository = settings.getEffectiveLocalRepository(); - Collection activeProfiles = collectActivateProfiles(nativeMavenProject); + Collection activeProfiles = readerResult.activatedProfiles; newState.myActiveProfilesIds = collectProfilesIds(activeProfiles); - Model model = nativeMavenProject.getModel(); + MavenModel model = readerResult.mavenModel; - newState.myMavenId = new MavenId(model.getGroupId(), - model.getArtifactId(), - model.getVersion()); - - Parent parent = model.getParent(); - newState.myParentId = parent != null - ? new MavenId(parent.getGroupId(), parent.getArtifactId(), parent.getVersion()) - : null; + newState.myMavenId = model.getMavenId(); + if (model.getParent() != null) { + newState.myParentId = model.getParent().getMavenId(); + } newState.myPackaging = model.getPackaging(); newState.myName = model.getName(); - Build build = model.getBuild(); + newState.myFinalName = model.getBuild().getFinalName(); + newState.myDefaultGoal = model.getBuild().getDefaultGoal(); - newState.myFinalName = build.getFinalName(); - newState.myDefaultGoal = build.getDefaultGoal(); - - newState.myBuildDirectory = build.getDirectory(); - newState.myOutputDirectory = build.getOutputDirectory(); - newState.myTestOutputDirectory = build.getTestOutputDirectory(); + newState.myBuildDirectory = model.getBuild().getDirectory(); + newState.myOutputDirectory = model.getBuild().getOutputDirectory(); + newState.myTestOutputDirectory = model.getBuild().getTestOutputDirectory(); doSetFolders(newState, readerResult); - newState.myFilters = build.getFilters() == null ? Collections.EMPTY_LIST : build.getFilters(); - newState.myProperties = model.getProperties() != null ? model.getProperties() : new Properties(); + newState.myFilters = model.getBuild().getFilters(); + newState.myProperties = model.getProperties(); - doSetResolvedAttributes(newState, readerResult, resetArtifacts); + doSetResolvedAttributes(newState, readerResult, settings, resetArtifacts); newState.myModulesPathsAndNames = collectModulePathsAndNames(model, getDirectory(), activeProfiles); Collection newProfiles = collectProfilesIds(model.getProfiles()); @@ -157,8 +147,7 @@ public class MavenProject { newState.myProfilesIds = new ArrayList(mergedProfiles); } - newState.myStrippedMavenModel = MavenUtil.cloneObject(model); - MavenUtil.stripDown(newState.myStrippedMavenModel); + newState.myModelMap = readerResult.nativeModelMap; return setState(newState); } @@ -169,9 +158,11 @@ public class MavenProject { return changes; } - private static void doSetResolvedAttributes(State state, MavenProjectReaderResult readerResult, boolean reset) { - org.apache.maven.project.MavenProject nativeMavenProject = readerResult.nativeMavenProject; - Model model = nativeMavenProject.getModel(); + private static void doSetResolvedAttributes(State state, + MavenProjectReaderResult readerResult, + MavenGeneralSettings settings, + boolean reset) { + MavenModel model = readerResult.mavenModel; Set newUnresolvedArtifacts = new THashSet(); LinkedHashSet newRepositories = new LinkedHashSet(); @@ -190,15 +181,11 @@ public class MavenProject { } newUnresolvedArtifacts.addAll(readerResult.unresolvedArtifactIds); - newRepositories.addAll(convertRepositories(model.getRepositories())); - - Map nativeToConvertedMap = - new THashMap(new TObjectIdentityHashingStrategy()); - newDependencyTree.addAll(convertDependencyNodes(null, readerResult.dependencyTree, nativeToConvertedMap, state.myLocalRepository)); - newDependencies.addAll(convertArtifacts(nativeMavenProject.getArtifacts(), nativeToConvertedMap, state.myLocalRepository)); - - newPlugins.addAll(collectPlugins(readerResult.settings, model)); - newExtensions.addAll(convertArtifacts(nativeMavenProject.getExtensionArtifacts(), nativeToConvertedMap, state.myLocalRepository)); + newRepositories.addAll(model.getRemoteRepositories()); + newDependencyTree.addAll(model.getDependencyTree()); + newDependencies.addAll(model.getDependencies()); + newPlugins.addAll(model.getPlugins()); + newExtensions.addAll(model.getExtensions()); state.myUnresolvedArtifactIds = newUnresolvedArtifacts; state.myRemoteRepositories = new ArrayList(newRepositories); @@ -215,123 +202,17 @@ public class MavenProject { } private static void doSetFolders(State newState, MavenProjectReaderResult readerResult) { - org.apache.maven.project.MavenProject nativeMavenProject = readerResult.nativeMavenProject; + MavenModel model = readerResult.mavenModel; + newState.mySources = model.getBuild().getSources(); + newState.myTestSources = model.getBuild().getTestSources(); - newState.mySources = new ArrayList(nativeMavenProject.getCompileSourceRoots()); - newState.myTestSources = new ArrayList(nativeMavenProject.getTestCompileSourceRoots()); - - newState.myResources = convertResources(nativeMavenProject.getResources()); - newState.myTestResources = convertResources(nativeMavenProject.getTestResources()); + newState.myResources = model.getBuild().getResources(); + newState.myTestResources = model.getBuild().getTestResources(); } - private static List convertResources(List resources) { - if (resources == null) return new ArrayList(); - - List result = new ArrayList(resources.size()); - for (Resource each : resources) { - result.add(new MavenResource(each)); - } - return result; - } - - private static List convertRepositories(List repositories) { - if (repositories == null) return new ArrayList(); - - List result = new ArrayList(repositories.size()); - for (Repository each : repositories) { - result.add(new MavenRemoteRepository(each)); - } - return result; - } - - private static List convertArtifacts(Collection artifacts, - Map nativeToConvertedMap, - File localRepository) { - if (artifacts == null) return new ArrayList(); - - List result = new ArrayList(artifacts.size()); - for (Artifact each : artifacts) { - result.add(convertArtifact(each, nativeToConvertedMap, localRepository)); - } - return result; - } - - private static List convertDependencyNodes(MavenArtifactNode parent, - Collection nodes, - Map nativeToConvertedMap, - File localRepository) { - List result = new ArrayList(nodes.size()); - for (DependencyNode each : nodes) { - Artifact a = each.getArtifact(); - MavenArtifact ma = convertArtifact(a, nativeToConvertedMap, localRepository); - - MavenArtifactState state = MavenArtifactState.ADDED; - switch (each.getState()) { - case DependencyNode.INCLUDED: - break; - case DependencyNode.OMITTED_FOR_CONFLICT: - state = MavenArtifactState.CONFLICT; - break; - case DependencyNode.OMITTED_FOR_DUPLICATE: - state = MavenArtifactState.DUPLICATE; - break; - case DependencyNode.OMITTED_FOR_CYCLE: - state = MavenArtifactState.CYCLE; - break; - default: - MavenLog.LOG.error("unknown dependency node state: " + each.getState()); - } - MavenArtifact relatedMA = each.getRelatedArtifact() == null ? null - : convertArtifact(each.getRelatedArtifact(), nativeToConvertedMap, localRepository); - MavenArtifactNode newNode = new MavenArtifactNode(parent, ma, state, relatedMA, each.getOriginalScope(), - each.getPremanagedVersion(), each.getPremanagedScope()); - newNode.setDependencies(convertDependencyNodes(newNode, each.getChildren(), nativeToConvertedMap, localRepository)); - result.add(newNode); - } - return result; - } - - private static MavenArtifact convertArtifact(Artifact artifact, Map nativeToConvertedMap, File localRepository) { - MavenArtifact ma = nativeToConvertedMap.get(artifact); - if (ma == null) { - ma = new MavenArtifact(artifact, localRepository); - nativeToConvertedMap.put(artifact, ma); - } - return ma; - } - - private static List collectPlugins(MavenGeneralSettings settings, Model mavenModel) { - List result = new ArrayList(); - Set pluginKeys = new THashSet(); - Build build = mavenModel.getBuild(); - doCollectPlugins(settings, build, false, result, pluginKeys); - if (build != null) doCollectPlugins(settings, build.getPluginManagement(), true, result, pluginKeys); - return result; - } - - private static void doCollectPlugins(MavenGeneralSettings settings, - PluginContainer container, - boolean management, - List result, - Set pluginKeys) { - if (container == null) return; - - List plugins = container.getPlugins(); - if (plugins == null) return; - - for (Plugin each : plugins) { - String key = each.getGroupId() + ":" + each.getArtifactId(); - if (management && (!isDefaultPlugin(settings, each) || pluginKeys.contains(key))) continue; - result.add(new MavenPlugin(each, management)); - pluginKeys.add(key); - } - } - - private static boolean isDefaultPlugin(MavenGeneralSettings settings, Plugin plugin) { - return settings.isDefaultPlugin(plugin.getGroupId(), plugin.getArtifactId()); - } - - private static Map collectModulePathsAndNames(Model mavenModel, String baseDir, Collection activeProfiles) { + private static Map collectModulePathsAndNames(MavenModel mavenModel, + String baseDir, + Collection activeProfiles) { String basePath = baseDir + "/"; Map result = new LinkedHashMap(); for (Map.Entry each : collectModulesRelativePathsAndNames(mavenModel, activeProfiles).entrySet()) { @@ -340,17 +221,17 @@ public class MavenProject { return result; } - private static Map collectModulesRelativePathsAndNames(Model mavenModel, Collection activeProfiles) { + private static Map collectModulesRelativePathsAndNames(MavenModel mavenModel, Collection activeProfiles) { LinkedHashMap result = new LinkedHashMap(); addModulesToList(mavenModel.getModules(), result); - for (Profile profile : activeProfiles) { + for (MavenProfile profile : activeProfiles) { addModulesToList(profile.getModules(), result); } return result; } - private static void addModulesToList(List moduleNames, LinkedHashMap result) { - for (String name : (List)moduleNames) { + private static void addModulesToList(List moduleNames, LinkedHashMap result) { + for (String name : moduleNames) { if (name.trim().length() == 0) continue; String originalName = name; @@ -364,18 +245,12 @@ public class MavenProject { } } - private static Collection collectActivateProfiles(org.apache.maven.project.MavenProject nativeMavenProject) { - Collection activatedProfiles = nativeMavenProject.getActiveProfiles(); - return activatedProfiles == null ? Collections.emptySet() : activatedProfiles; - } - - private static Collection collectProfilesIds(Collection profiles) { + private static Collection collectProfilesIds(Collection profiles) { if (profiles == null) return Collections.emptyList(); Set result = new THashSet(profiles.size()); - for (Profile each : profiles) { - String id = each.getId(); - if (id != null) result.add(id); + for (MavenProfile each : profiles) { + result.add(each.getId()); } return result; } @@ -427,8 +302,8 @@ public class MavenProject { return state.myName; } - public Model getMavenModel() { - return myState.myStrippedMavenModel; + public Map getModelMap() { + return myState.myModelMap; } public MavenId getMavenId() { @@ -491,34 +366,34 @@ public class MavenProject { Collection profiles, MavenProjectReader reader, MavenProjectReaderProjectLocator locator) { - return set(reader.readProject(generalSettings, myFile, profiles, locator), true, false, true); + return set(reader.readProject(generalSettings, myFile, profiles, locator), generalSettings, true, false, true); } - public Pair resolve(MavenGeneralSettings generalSettings, - MavenEmbedderWrapper embedder, - MavenProjectReader reader, - MavenProjectReaderProjectLocator locator) + public Pair resolve(MavenGeneralSettings generalSettings, + MavenEmbedderWrapper embedder, + MavenProjectReader reader, + MavenProjectReaderProjectLocator locator) throws MavenProcessCanceledException { MavenProjectReaderResult result = reader.resolveProject(generalSettings, embedder, getFile(), getActiveProfilesIds(), locator); - MavenProjectChanges changes = set(result, false, result.readingProblems.isEmpty(), false); + MavenProjectChanges changes = set(result, generalSettings, false, result.readingProblems.isEmpty(), false); - for (MavenImporter eachImporter : getSuitableImporters()) { - eachImporter.resolve(this, result.nativeMavenProject, embedder); + if (result.nativeMavenProject != null) { + for (MavenImporter eachImporter : getSuitableImporters()) { + eachImporter.resolve(this, result.nativeMavenProject, embedder); + } } return Pair.create(changes, result.nativeMavenProject); } public Pair resolveFolders(MavenEmbedderWrapper embedder, - MavenGeneralSettings generalSettings, MavenImportingSettings importingSettings, MavenProjectReader reader, MavenConsole console) throws MavenProcessCanceledException { MavenProjectReaderResult result = reader.generateSources(embedder, - generalSettings, importingSettings, getFile(), getActiveProfilesIds(), @@ -597,7 +472,7 @@ public class MavenProject { } private static MavenProjectProblem createDependencyProblem(VirtualFile file, String description) { - return new MavenProjectProblem(file, description, MavenProjectProblem.ProblemType.DEPENDENCY); + return new MavenProjectProblem(file.getPath(), description, MavenProjectProblem.ProblemType.DEPENDENCY); } private static boolean isParentResolved(State state) { @@ -892,12 +767,13 @@ public class MavenProject { List myDependencies; List myDependencyTree; + List myRemoteRepositories; + Map myModulesPathsAndNames; Collection myProfilesIds; - Model myStrippedMavenModel; - List myRemoteRepositories; + Map myModelMap; Collection myActiveProfilesIds; Collection myReadingProblems; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectProblem.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectProblem.java deleted file mode 100644 index 1c6636d9530b..000000000000 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectProblem.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.idea.maven.project; - -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.openapi.vfs.VirtualFileManager; - -import java.io.Serializable; - -public class MavenProjectProblem implements Serializable { - public enum ProblemType { - SYNTAX, STRUCTURE, DEPENDENCY, PARENT, SETTINGS_OR_PROFILES; - } - - private String myUrl; - private String myDescription; - private ProblemType myType; - - protected MavenProjectProblem() { - } - - public MavenProjectProblem(VirtualFile file, String description, ProblemType type) { - myUrl = file.getUrl(); - myDescription = description; - myType = type; - } - - public String getUrl() { - return myUrl; - } - - public String getDescription() { - return myDescription; - } - - public ProblemType getType() { - return myType; - } - - public VirtualFile findFile() { - return VirtualFileManager.getInstance().findFileByUrl(myUrl); - } - - @Override - public String toString() { - return myType + ":" + myDescription + ":" + myUrl; - } - - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - MavenProjectProblem that = (MavenProjectProblem)o; - - if (!myDescription.equals(that.myDescription)) return false; - if (myType != that.myType) return false; - if (!myUrl.equals(that.myUrl)) return false; - - return true; - } - - public int hashCode() { - int result = myUrl.hashCode(); - result = 31 * result + myDescription.hashCode(); - result = 31 * result + myType.hashCode(); - return result; - } -} diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectReader.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectReader.java index b9c5c1d5dcf6..928855b590e4 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectReader.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectReader.java @@ -21,22 +21,14 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import gnu.trove.THashMap; import gnu.trove.THashSet; -import org.apache.maven.model.*; -import org.apache.maven.profiles.activation.*; -import org.apache.maven.project.InvalidProjectModelException; -import org.apache.maven.project.JBMavenProjectHelper; -import org.apache.maven.project.MavenProject; -import org.apache.maven.project.ProjectBuildingException; -import org.apache.maven.project.inheritance.DefaultModelInheritanceAssembler; -import org.apache.maven.project.injection.DefaultProfileInjector; -import org.apache.maven.project.validation.ModelValidationResult; -import org.apache.maven.shared.dependency.tree.DependencyNode; -import org.codehaus.plexus.context.ContextException; -import org.codehaus.plexus.context.DefaultContext; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.idea.maven.embedder.*; +import org.jetbrains.idea.maven.facade.MavenEmbedderWrapper; +import org.jetbrains.idea.maven.facade.MavenFacadeManager; +import org.jetbrains.idea.maven.facade.MavenWrapperExecutionResult; +import org.jetbrains.idea.maven.facade.ProfileApplicationResult; +import org.jetbrains.idea.maven.model.*; import org.jetbrains.idea.maven.utils.MavenJDOMUtil; import org.jetbrains.idea.maven.utils.MavenLog; import org.jetbrains.idea.maven.utils.MavenProcessCanceledException; @@ -56,46 +48,35 @@ public class MavenProjectReader { private static final String PROFILE_FROM_SETTINGS_XML = "settings.xml"; private final Map myRawModelsCache = new THashMap(); - private Pair, Collection> mySettingsProfilesWithProblemsCache; + private Pair, Collection> mySettingsProfilesWithProblemsCache; public MavenProjectReaderResult readProject(MavenGeneralSettings generalSettings, VirtualFile file, Collection explicitProfiles, MavenProjectReaderProjectLocator locator) { - Pair> readResult = + Pair> readResult = doReadProjectModel(generalSettings, file, explicitProfiles, new THashSet(), locator); File basedir = getBaseDir(file); - Model model = expandProperties(readResult.first.model, basedir); - alignModel(model, basedir); + MavenModel model = MavenFacadeManager.getInstance().interpolateAndAlignModel(readResult.first.model, basedir); - Collection activeProfiles = readResult.second; - - MavenProject mavenProject = new MavenProject(model); - mavenProject.setFile(new File(file.getPath())); - mavenProject.setActiveProfiles(new ArrayList(activeProfiles)); - JBMavenProjectHelper.setSourceRoots(mavenProject, - Collections.singletonList(model.getBuild().getSourceDirectory()), - Collections.singletonList(model.getBuild().getTestSourceDirectory()), - Collections.singletonList(model.getBuild().getScriptSourceDirectory())); - - return new MavenProjectReaderResult(generalSettings, - mavenProject, - Collections.emptyList(), + return new MavenProjectReaderResult(model, + Collections.emptyMap(), + readResult.second, + null, readResult.first.problems, - Collections.emptySet(), - generalSettings.getEffectiveLocalRepository()); + new THashSet()); } private File getBaseDir(VirtualFile file) { return new File(file.getParent().getPath()); } - private Pair> doReadProjectModel(MavenGeneralSettings generalSettings, - VirtualFile file, - Collection explicitProfiles, - Set recursionGuard, - MavenProjectReaderProjectLocator locator) { + private Pair> doReadProjectModel(MavenGeneralSettings generalSettings, + VirtualFile file, + Collection explicitProfiles, + Set recursionGuard, + MavenProjectReaderProjectLocator locator) { RawModelReadResult cachedModel = myRawModelsCache.get(file); if (cachedModel == null) { cachedModel = doReadProjectModel(file, false); @@ -103,24 +84,25 @@ public class MavenProjectReader { } // todo modifying cached model and problems here?????? - Model model = cachedModel.model; - Collection alwaysOnProfiles = cachedModel.alwaysOnProfiles; + MavenModel model = cachedModel.model; + Set alwaysOnProfiles = cachedModel.alwaysOnProfiles; Collection problems = cachedModel.problems; - repairModelHeader(model); - resolveInheritance(generalSettings, model, file, explicitProfiles, recursionGuard, locator, problems); + model = resolveInheritance(generalSettings, model, file, explicitProfiles, recursionGuard, locator, problems); addSettingsProfiles(generalSettings, model, alwaysOnProfiles, problems); - Collection activatedProfiles = applyProfiles(model, getBaseDir(file), explicitProfiles, alwaysOnProfiles); + ProfileApplicationResult applied = applyProfiles(model, getBaseDir(file), explicitProfiles, alwaysOnProfiles); + model = applied.getModel(); repairModelBody(model); - return Pair.create(cachedModel, activatedProfiles); + return new Pair>(new RawModelReadResult(model, problems, alwaysOnProfiles), + applied.getActivatedProfiles()); } private RawModelReadResult doReadProjectModel(VirtualFile file, boolean headerOnly) { - Model result = new Model(); - LinkedHashSet problems = createProblemsList(); + MavenModel result = new MavenModel(); + Collection problems = MavenProjectProblem.createProblemsList(); Set alwaysOnProfiles = new THashSet(); Element xmlProject = readXml(file, problems, MavenProjectProblem.ProblemType.SYNTAX); @@ -128,43 +110,35 @@ public class MavenProjectReader { return new RawModelReadResult(result, problems, alwaysOnProfiles); } - result.setModelVersion(MavenJDOMUtil.findChildValueByPath(xmlProject, "modelVersion")); - result.setGroupId(MavenJDOMUtil.findChildValueByPath(xmlProject, "groupId")); - result.setArtifactId(MavenJDOMUtil.findChildValueByPath(xmlProject, "artifactId")); - result.setVersion(MavenJDOMUtil.findChildValueByPath(xmlProject, "version")); + MavenParent parent = new MavenParent(new MavenId(UNKNOWN, UNKNOWN, UNKNOWN), "../pom.xml"); + if (MavenJDOMUtil.hasChildByPath(xmlProject, "parent")) { + parent = new MavenParent(new MavenId(MavenJDOMUtil.findChildValueByPath(xmlProject, "parent.groupId", UNKNOWN), + MavenJDOMUtil.findChildValueByPath(xmlProject, "parent.artifactId", UNKNOWN), + MavenJDOMUtil.findChildValueByPath(xmlProject, "parent.version", UNKNOWN)), + MavenJDOMUtil.findChildValueByPath(xmlProject, "parent.relativePath", "../pom.xml")); + result.setParent(parent); + } + + result.setMavenId(new MavenId(MavenJDOMUtil.findChildValueByPath(xmlProject, "groupId", parent.getMavenId().getGroupId()), + MavenJDOMUtil.findChildValueByPath(xmlProject, "artifactId", UNKNOWN), + MavenJDOMUtil.findChildValueByPath(xmlProject, "version", parent.getMavenId().getVersion()))); if (headerOnly) return new RawModelReadResult(result, problems, alwaysOnProfiles); - result.setPackaging(MavenJDOMUtil.findChildValueByPath(xmlProject, "packaging")); + result.setPackaging(MavenJDOMUtil.findChildValueByPath(xmlProject, "packaging", "jar")); result.setName(MavenJDOMUtil.findChildValueByPath(xmlProject, "name")); - if (MavenJDOMUtil.hasChildByPath(xmlProject, "parent")) { - Parent parent = new Parent(); - - String groupId = MavenJDOMUtil.findChildValueByPath(xmlProject, "parent.groupId"); - String artifactId = MavenJDOMUtil.findChildValueByPath(xmlProject, "parent.artifactId"); - String version = MavenJDOMUtil.findChildValueByPath(xmlProject, "parent.version"); - - parent.setGroupId(groupId); - parent.setArtifactId(artifactId); - parent.setVersion(version); - parent.setRelativePath(MavenJDOMUtil.findChildValueByPath(xmlProject, "parent.relativePath")); - - result.setParent(parent); - } - result.setBuild(new Build()); - readModelAndBuild(result, result.getBuild(), xmlProject); + readModelBody(result, result.getBuild(), xmlProject); result.setProfiles(collectProfiles(file, xmlProject, problems, alwaysOnProfiles)); return new RawModelReadResult(result, problems, alwaysOnProfiles); } - private void readModelAndBuild(ModelBase mavenModelBase, BuildBase mavenBuildBase, Element xmlModel) { + private void readModelBody(MavenModelBase mavenModelBase, MavenBuildBase mavenBuildBase, Element xmlModel) { mavenModelBase.setModules(MavenJDOMUtil.findChildrenValuesByPath(xmlModel, "modules", "module")); collectProperties(MavenJDOMUtil.findChildByPath(xmlModel, "properties"), mavenModelBase); Element xmlBuild = MavenJDOMUtil.findChildByPath(xmlModel, "build"); - if (xmlBuild == null) return; mavenBuildBase.setFinalName(MavenJDOMUtil.findChildValueByPath(xmlBuild, "finalName")); mavenBuildBase.setDefaultGoal(MavenJDOMUtil.findChildValueByPath(xmlBuild, "defaultGoal")); @@ -172,36 +146,74 @@ public class MavenProjectReader { mavenBuildBase.setResources(collectResources(MavenJDOMUtil.findChildrenByPath(xmlBuild, "resources", "resource"))); mavenBuildBase.setTestResources(collectResources(MavenJDOMUtil.findChildrenByPath(xmlBuild, "testResources", "testResource"))); - if (mavenBuildBase instanceof Build) { - Build mavenBuild = (Build)mavenBuildBase; + if (mavenBuildBase instanceof MavenBuild) { + MavenBuild mavenBuild = (MavenBuild)mavenBuildBase; + + String source = MavenJDOMUtil.findChildValueByPath(xmlBuild, "sourceDirectory"); + if (!isEmptyOrSpaces(source)) mavenBuild.addSource(source); + String testSource = MavenJDOMUtil.findChildValueByPath(xmlBuild, "testSourceDirectory"); + if (!isEmptyOrSpaces(testSource)) mavenBuild.addTestSource(testSource); - mavenBuild.setSourceDirectory(MavenJDOMUtil.findChildValueByPath(xmlBuild, "sourceDirectory")); - mavenBuild.setTestSourceDirectory(MavenJDOMUtil.findChildValueByPath(xmlBuild, "testSourceDirectory")); - mavenBuild.setScriptSourceDirectory(MavenJDOMUtil.findChildValueByPath(xmlBuild, "scriptSourceDirectory")); mavenBuild.setOutputDirectory(MavenJDOMUtil.findChildValueByPath(xmlBuild, "outputDirectory")); mavenBuild.setTestOutputDirectory(MavenJDOMUtil.findChildValueByPath(xmlBuild, "testOutputDirectory")); } } - private List collectResources(List xmlResources) { - List result = new ArrayList(); + private List collectResources(List xmlResources) { + List result = new ArrayList(); for (Element each : xmlResources) { - Resource r = new Resource(); - r.setDirectory(MavenJDOMUtil.findChildValueByPath(each, "directory")); - r.setFiltering("true".equals(MavenJDOMUtil.findChildValueByPath(each, "filtering"))); - r.setTargetPath(MavenJDOMUtil.findChildValueByPath(each, "targetPath")); - r.setIncludes(MavenJDOMUtil.findChildrenValuesByPath(each, "includes", "include")); - r.setExcludes(MavenJDOMUtil.findChildrenValuesByPath(each, "excludes", "exclude")); - result.add(r); + result.add(new MavenResource(MavenJDOMUtil.findChildValueByPath(each, "directory"), + "true".equals(MavenJDOMUtil.findChildValueByPath(each, "filtering")), + MavenJDOMUtil.findChildValueByPath(each, "targetPath"), + MavenJDOMUtil.findChildrenValuesByPath(each, "includes", "include"), + MavenJDOMUtil.findChildrenValuesByPath(each, "excludes", "exclude"))); } return result; } - private List collectProfiles(VirtualFile projectFile, - Element xmlProject, - Collection problems, - Collection alwaysOnProfiles) { - List result = new ArrayList(); + private void repairModelBody(MavenModel model) { + MavenBuild build = model.getBuild(); + + if (isEmptyOrSpaces(build.getFinalName())) { + build.setFinalName("${project.artifactId}-${project.version}"); + } + + if (build.getSources().isEmpty()) build.addSource("src/main/java"); + if (build.getTestSources().isEmpty()) build.addTestSource("src/test/java"); + + build.setResources(repairResources(build.getResources(), "src/main/resources")); + build.setTestResources(repairResources(build.getTestResources(), "src/test/resources")); + + build.setDirectory(isEmptyOrSpaces(build.getDirectory()) ? "target" : build.getDirectory()); + build.setOutputDirectory(isEmptyOrSpaces(build.getOutputDirectory()) + ? "${project.build.directory}/classes" : build.getOutputDirectory()); + build.setTestOutputDirectory(isEmptyOrSpaces(build.getTestOutputDirectory()) + ? "${project.build.directory}/test-classes" : build.getTestOutputDirectory()); + } + + private List repairResources(List resources, String defaultDir) { + List result = new ArrayList(); + if (resources.isEmpty()) { + result.add(createResource(defaultDir)); + return result; + } + + for (MavenResource each : resources) { + if (isEmptyOrSpaces(each.getDirectory())) continue; + result.add(each); + } + return result; + } + + private MavenResource createResource(String directory) { + return new MavenResource(directory, false, null, Collections.emptyList(), Collections.emptyList()); + } + + private List collectProfiles(VirtualFile projectFile, + Element xmlProject, + Collection problems, + Collection alwaysOnProfiles) { + List result = new ArrayList(); collectProfiles(MavenJDOMUtil.findChildrenByPath(xmlProject, "profiles", "profile"), result, PROFILE_FROM_POM); VirtualFile profilesFile = MavenUtil.findProfilesXmlFile(projectFile); @@ -219,13 +231,13 @@ public class MavenProjectReader { } private void addSettingsProfiles(MavenGeneralSettings generalSettings, - Model model, + MavenModel model, Collection alwaysOnProfiles, Collection problems) { if (mySettingsProfilesWithProblemsCache == null) { - List settingsProfiles = new ArrayList(); - Collection settingsProblems = createProblemsList(); + List settingsProfiles = new ArrayList(); + Collection settingsProblems = MavenProjectProblem.createProblemsList(); for (VirtualFile each : generalSettings.getEffectiveSettingsFiles()) { collectProfilesFromSettingsXmlOrProfilesXml(each, @@ -239,8 +251,8 @@ public class MavenProjectReader { mySettingsProfilesWithProblemsCache = Pair.create(settingsProfiles, settingsProblems); } - List modelProfiles = model.getProfiles(); - for (Profile each : mySettingsProfilesWithProblemsCache.first) { + List modelProfiles = model.getProfiles(); + for (MavenProfile each : mySettingsProfilesWithProblemsCache.first) { addProfileIfDoesNotExist(each, modelProfiles); } problems.addAll(mySettingsProfilesWithProblemsCache.second); @@ -250,7 +262,7 @@ public class MavenProjectReader { String rootElementName, boolean wrapRootIfNecessary, String profilesSource, - List result, + List result, Collection alwaysOnProfiles, Collection problems) { Element rootElement = readXml(profilesFile, problems, MavenProjectProblem.ProblemType.SETTINGS_OR_PROFILES); @@ -268,66 +280,60 @@ public class MavenProjectReader { alwaysOnProfiles.addAll(MavenJDOMUtil.findChildrenValuesByPath(rootElement, "activeProfiles", "activeProfile")); } - private void collectProfiles(List xmlProfiles, List result, String source) { + private void collectProfiles(List xmlProfiles, List result, String source) { for (Element each : xmlProfiles) { String id = MavenJDOMUtil.findChildValueByPath(each, "id"); if (isEmptyOrSpaces(id)) continue; - Profile profile = new Profile(); - profile.setId(id); - profile.setSource(source); + MavenProfile profile = new MavenProfile(id, source); if (!addProfileIfDoesNotExist(profile, result)) continue; Element xmlActivation = MavenJDOMUtil.findChildByPath(each, "activation"); if (xmlActivation != null) { - Activation activation = new Activation(); + MavenProfileActivation activation = new MavenProfileActivation(); activation.setActiveByDefault("true".equals(MavenJDOMUtil.findChildValueByPath(xmlActivation, "activeByDefault"))); Element xmlOS = MavenJDOMUtil.findChildByPath(xmlActivation, "os"); if (xmlOS != null) { - ActivationOS activationOS = new ActivationOS(); - activationOS.setName(MavenJDOMUtil.findChildValueByPath(xmlOS, "name")); - activationOS.setFamily(MavenJDOMUtil.findChildValueByPath(xmlOS, "family")); - activationOS.setArch(MavenJDOMUtil.findChildValueByPath(xmlOS, "arch")); - activationOS.setVersion(MavenJDOMUtil.findChildValueByPath(xmlOS, "version")); - activation.setOs(activationOS); + activation.setOs(new MavenProfileActivationOS( + MavenJDOMUtil.findChildValueByPath(xmlOS, "name"), + MavenJDOMUtil.findChildValueByPath(xmlOS, "family"), + MavenJDOMUtil.findChildValueByPath(xmlOS, "arch"), + MavenJDOMUtil.findChildValueByPath(xmlOS, "version"))); } activation.setJdk(MavenJDOMUtil.findChildValueByPath(xmlActivation, "jdk")); Element xmlProperty = MavenJDOMUtil.findChildByPath(xmlActivation, "property"); if (xmlProperty != null) { - ActivationProperty activationProperty = new ActivationProperty(); - activationProperty.setName(MavenJDOMUtil.findChildValueByPath(xmlProperty, "name")); - activationProperty.setValue(MavenJDOMUtil.findChildValueByPath(xmlProperty, "value")); - activation.setProperty(activationProperty); + activation.setProperty(new MavenProfileActivationProperty( + MavenJDOMUtil.findChildValueByPath(xmlProperty, "name"), + MavenJDOMUtil.findChildValueByPath(xmlProperty, "value"))); } Element xmlFile = MavenJDOMUtil.findChildByPath(xmlActivation, "file"); if (xmlFile != null) { - ActivationFile activationFile = new ActivationFile(); - activationFile.setExists(MavenJDOMUtil.findChildValueByPath(xmlFile, "exists")); - activationFile.setMissing(MavenJDOMUtil.findChildValueByPath(xmlFile, "missing")); - activation.setFile(activationFile); + activation.setFile(new MavenProfileActivationFile( + MavenJDOMUtil.findChildValueByPath(xmlFile, "exists"), + MavenJDOMUtil.findChildValueByPath(xmlFile, "missing"))); } profile.setActivation(activation); } - profile.setBuild(new BuildBase()); - readModelAndBuild(profile, profile.getBuild(), each); + readModelBody(profile, profile.getBuild(), each); } } - private boolean addProfileIfDoesNotExist(Profile profile, List result) { - for (Profile each : result) { + private boolean addProfileIfDoesNotExist(MavenProfile profile, List result) { + for (MavenProfile each : result) { if (Comparing.equal(each.getId(), profile.getId())) return false; } result.add(profile); return true; } - private void collectProperties(Element xmlProperties, ModelBase mavenModelBase) { + private void collectProperties(Element xmlProperties, MavenModelBase mavenModelBase) { if (xmlProperties == null) return; Properties props = mavenModelBase.getProperties(); @@ -341,181 +347,37 @@ public class MavenProjectReader { } } - private List applyProfiles(Model model, File basedir, Collection explicitProfiles, Collection alwaysOnProfiles) { - List activatedPom = new ArrayList(); - List activatedExternal = new ArrayList(); - List activeByDefault = new ArrayList(); - - List rawProfiles = model.getProfiles(); - List expandedProfilesCache = null; - - for (int i = 0; i < rawProfiles.size(); i++) { - Profile eachRawProfile = rawProfiles.get(i); - - boolean shouldAdd = explicitProfiles.contains(eachRawProfile.getId()) || alwaysOnProfiles.contains(eachRawProfile.getId()); - - Activation activation = eachRawProfile.getActivation(); - if (activation != null) { - if (activation.isActiveByDefault()) { - activeByDefault.add(eachRawProfile); - } - - // expand only if necessary - if (expandedProfilesCache == null) expandedProfilesCache = expandProperties(model, basedir).getProfiles(); - Profile eachExpandedProfile = expandedProfilesCache.get(i); - - for (ProfileActivator eachActivator : getProfileActivators()) { - try { - if (eachActivator.canDetermineActivation(eachExpandedProfile) && eachActivator.isActive(eachExpandedProfile)) { - shouldAdd = true; - break; - } - } - catch (ProfileActivationException e) { - MavenLog.LOG.warn(e); - } - } - } - - if (shouldAdd) { - if (PROFILE_FROM_POM.equals(eachRawProfile.getSource())) { - activatedPom.add(eachRawProfile); - } - else { - activatedExternal.add(eachRawProfile); - } - } - } - - List activatedProfiles = new ArrayList(activatedPom.isEmpty() ? activeByDefault : activatedPom); - activatedProfiles.addAll(activatedExternal); - - for (Profile each : activatedProfiles) { - new DefaultProfileInjector().inject(each, model); - } - - return activatedProfiles; + private ProfileApplicationResult applyProfiles(MavenModel model, + File basedir, + Collection explicitProfiles, + Collection alwaysOnProfiles) { + return MavenFacadeManager.getInstance().applyProfiles(model, basedir, explicitProfiles, alwaysOnProfiles); } - private ProfileActivator[] getProfileActivators() { - SystemPropertyProfileActivator sysPropertyActivator = new SystemPropertyProfileActivator(); - DefaultContext context = new DefaultContext(); - context.put("SystemProperties", MavenEmbedderWrapper.collectSystemProperties()); - try { - sysPropertyActivator.contextualize(context); - } - catch (ContextException e) { - MavenLog.LOG.error(e); - return new ProfileActivator[0]; - } - - return new ProfileActivator[]{new FileProfileActivator(), sysPropertyActivator, new JdkPrefixProfileActivator(), - new OperatingSystemProfileActivator()}; - } - - private void repairModelHeader(Model model) { - if (isEmptyOrSpaces(model.getModelVersion())) model.setModelVersion("4.0.0"); - - Parent parent = model.getParent(); - if (parent != null) { - if (isEmptyOrSpaces(parent.getGroupId())) parent.setGroupId(UNKNOWN); - if (isEmptyOrSpaces(parent.getArtifactId())) parent.setArtifactId(UNKNOWN); - if (isEmptyOrSpaces(parent.getVersion())) parent.setVersion(UNKNOWN); - if (isEmptyOrSpaces(parent.getRelativePath())) parent.setRelativePath("../pom.xml"); - } - - if (isEmptyOrSpaces(model.getGroupId())) { - if (parent != null) { - model.setGroupId(parent.getGroupId()); - } - else { - model.setGroupId(UNKNOWN); - } - } - if (isEmptyOrSpaces(model.getArtifactId())) model.setArtifactId(UNKNOWN); - if (isEmptyOrSpaces(model.getVersion())) { - if (parent != null) { - model.setVersion(parent.getVersion()); - } - else { - model.setVersion(UNKNOWN); - } - } - - if (isEmptyOrSpaces(model.getPackaging())) model.setPackaging("jar"); - } - - private void repairModelBody(Model model) { - if (model.getBuild() == null) { - model.setBuild(new Build()); - } - Build build = model.getBuild(); - - if (isEmptyOrSpaces(build.getFinalName())) { - build.setFinalName("${project.artifactId}-${project.version}"); - } - - build.setSourceDirectory(isEmptyOrSpaces(build.getSourceDirectory()) ? "src/main/java" : build.getSourceDirectory()); - build.setTestSourceDirectory(isEmptyOrSpaces(build.getTestSourceDirectory()) ? "src/test/java" : build.getTestSourceDirectory()); - build - .setScriptSourceDirectory(isEmptyOrSpaces(build.getScriptSourceDirectory()) ? "src/main/scripts" : build.getScriptSourceDirectory()); - - build.setResources(repairResources(build.getResources(), "src/main/resources")); - build.setTestResources(repairResources(build.getTestResources(), "src/test/resources")); - - build.setDirectory(isEmptyOrSpaces(build.getDirectory()) ? "target" : build.getDirectory()); - build - .setOutputDirectory(isEmptyOrSpaces(build.getOutputDirectory()) ? "${project.build.directory}/classes" : build.getOutputDirectory()); - build.setTestOutputDirectory( - isEmptyOrSpaces(build.getTestOutputDirectory()) ? "${project.build.directory}/test-classes" : build.getTestOutputDirectory()); - } - - private List repairResources(List resources, String defaultDir) { - List result = new ArrayList(); - if (resources.isEmpty()) { - result.add(createResource(defaultDir)); - return result; - } - - for (Resource each : resources) { - if (isEmptyOrSpaces(each.getDirectory())) continue; - each.setDirectory(each.getDirectory()); - result.add(each); - } - return result; - } - - private Resource createResource(String directory) { - Resource result = new Resource(); - result.setDirectory(directory); - return result; - } - - private void resolveInheritance(final MavenGeneralSettings generalSettings, - final Model model, - final VirtualFile file, - final Collection explicitProfiles, - final Set recursionGuard, - final MavenProjectReaderProjectLocator locator, - Collection problems) { + private MavenModel resolveInheritance(final MavenGeneralSettings generalSettings, + MavenModel model, + final VirtualFile file, + final Collection explicitProfiles, + final Set recursionGuard, + final MavenProjectReaderProjectLocator locator, + Collection problems) { if (recursionGuard.contains(file)) { - problems.add(createProblem(file, ProjectBundle.message("maven.project.problem.recursiveInheritance"), - MavenProjectProblem.ProblemType.PARENT)); - return; + problems.add(MavenProjectProblem.createProblem(file.getPath(), ProjectBundle.message("maven.project.problem.recursiveInheritance"), + MavenProjectProblem.ProblemType.PARENT)); + return model; } recursionGuard.add(file); try { - Parent parent = model.getParent(); final MavenParentDesc[] parentDesc = new MavenParentDesc[1]; + MavenParent parent = model.getParent(); if (parent != null) { - MavenId parentId = new MavenId(parent.getGroupId(), parent.getArtifactId(), parent.getVersion()); - if (parentId.equals(model.getGroupId(), model.getArtifactId(), model.getVersion())) { - problems.add(createProblem(file, ProjectBundle.message("maven.project.problem.selfInheritance"), - MavenProjectProblem.ProblemType.PARENT)); - return; + if (model.getMavenId().equals(parent.getMavenId())) { + problems.add(MavenProjectProblem.createProblem(file.getPath(), ProjectBundle.message("maven.project.problem.selfInheritance"), + MavenProjectProblem.ProblemType.PARENT)); + return model; } - parentDesc[0] = new MavenParentDesc(parentId, parent.getRelativePath()); + parentDesc[0] = new MavenParentDesc(parent.getMavenId(), parent.getRelativePath()); } Pair parentModelWithProblems = @@ -528,9 +390,9 @@ public class MavenProjectReader { @Override @Nullable protected Pair processRelativeParent(VirtualFile parentFile) { - Model parentModel = doReadProjectModel(parentFile, true).model; + MavenModel parentModel = doReadProjectModel(parentFile, true).model; MavenId parentId = parentDesc[0].getParentId(); - if (!parentId.equals(new MavenId(parentModel))) return null; + if (!parentId.equals(parentModel.getMavenId())) return null; return super.processRelativeParent(parentFile); } @@ -547,165 +409,89 @@ public class MavenProjectReader { } }.process(generalSettings, file, parentDesc[0]); - if (parentModelWithProblems == null) return; // no parent or parent not found; + if (parentModelWithProblems == null) return model; // no parent or parent not found; - Model parentModel = parentModelWithProblems.second.model; + MavenModel parentModel = parentModelWithProblems.second.model; if (!parentModelWithProblems.second.problems.isEmpty()) { - problems.add(createProblem(parentModelWithProblems.first, - ProjectBundle.message("maven.project.problem.parentHasProblems", new MavenId(parentModel)), - MavenProjectProblem.ProblemType.PARENT)); + problems.add(MavenProjectProblem.createProblem(parentModelWithProblems.first.getPath(), + ProjectBundle.message("maven.project.problem.parentHasProblems", + parentModel.getMavenId()), + MavenProjectProblem.ProblemType.PARENT)); } - new DefaultModelInheritanceAssembler().assembleModelInheritance(model, parentModel); - - List profiles = model.getProfiles(); - for (Profile each : parentModel.getProfiles()) { + model = MavenFacadeManager.getInstance().assembleInheritance(model, parentModel); + List profiles = model.getProfiles(); + for (MavenProfile each : parentModel.getProfiles()) { addProfileIfDoesNotExist(each, profiles); } + return model; } finally { recursionGuard.remove(file); } } - private Model expandProperties(Model model, File basedir) { - return MavenEmbedderWrapper.interpolate(model, basedir); - } - - private void alignModel(Model model, File basedir) { - MavenEmbedderWrapper.alignModel(model, basedir); - } - - private MavenProjectProblem createStructureProblem(VirtualFile file, String description) { - return createProblem(file, description, MavenProjectProblem.ProblemType.STRUCTURE); - } - - private MavenProjectProblem createSyntaxProblem(VirtualFile file, MavenProjectProblem.ProblemType type) { - return createProblem(file, ProjectBundle.message("maven.project.problem.syntaxError", file.getName()), type); - } - - private MavenProjectProblem createProblem(VirtualFile file, String description, MavenProjectProblem.ProblemType type) { - return new MavenProjectProblem(file, description, type); - } - - private LinkedHashSet createProblemsList() { - return createProblemsList(Collections.emptySet()); - } - - private LinkedHashSet createProblemsList(Collection copyThis) { - return new LinkedHashSet(copyThis); - } - public MavenProjectReaderResult resolveProject(MavenGeneralSettings generalSettings, MavenEmbedderWrapper embedder, VirtualFile file, Collection explicitProfiles, MavenProjectReaderProjectLocator locator) throws MavenProcessCanceledException { - MavenProject mavenProject = null; - Collection problems = createProblemsList(); - Set unresolvedArtifactsIds = new THashSet(); - Collection dependencyTree = Collections.emptyList(); - try { - MavenWrapperResolutionResult result = doResolveProject(embedder, file, explicitProfiles, problems); - mavenProject = result.getMavenProject(); - unresolvedArtifactsIds = result.getUnresolvedArtifactIds(); - dependencyTree = result.getOriginalDependencyTree(); + MavenWrapperExecutionResult result = embedder.resolveProject(file, explicitProfiles); + if (result.projectData == null) { + MavenProjectReaderResult temp = readProject(generalSettings, file, explicitProfiles, locator); + temp.readingProblems.addAll(result.problems); + temp.unresolvedArtifactIds.addAll(result.unresolvedArtifacts); + return temp; + } + + return new MavenProjectReaderResult(result.projectData.mavenModel, + result.projectData.mavenModelMap, + result.projectData.activatedProfiles, + result.projectData.nativeMavenProject, + result.problems, + result.unresolvedArtifacts); } catch (MavenProcessCanceledException e) { throw e; } catch (Throwable e) { - String message = e.getMessage(); - - if (e instanceof RuntimeException && e.getCause() != null) { - message = e.getCause().getMessage(); - } - - if (message != null) { - problems.add(createStructureProblem(file, message)); - } MavenLog.LOG.info(e); MavenLog.printInTests(e); // print exception since we need to know if something wrong with our logic - } - if (mavenProject == null) { - if (problems.isEmpty()) { - problems.add(createSyntaxProblem(file, MavenProjectProblem.ProblemType.SYNTAX)); - } - mavenProject = readProject(generalSettings, file, explicitProfiles, locator).nativeMavenProject; - } - - return new MavenProjectReaderResult(generalSettings, mavenProject, dependencyTree, problems, unresolvedArtifactsIds, embedder.getLocalRepositoryFile()); - } - - private MavenWrapperResolutionResult doResolveProject(MavenEmbedderWrapper embedder, - VirtualFile file, - Collection profiles, - Collection problems) throws MavenProcessCanceledException { - MavenWrapperResolutionResult result = embedder.resolveProject(file, profiles); - validate(file, result, problems); - return result; - } - - private boolean validate(VirtualFile file, MavenWrapperExecutionResult r, Collection problems) { - for (Exception each : r.getExceptions()) { - MavenLog.LOG.info(each); - - if (each instanceof InvalidProjectModelException) { - ModelValidationResult modelValidationResult = ((InvalidProjectModelException)each).getValidationResult(); - if (modelValidationResult != null) { - for (Object eachValidationProblem : modelValidationResult.getMessages()) { - problems.add(createStructureProblem(file, (String)eachValidationProblem)); - } - } - else { - problems.add(createStructureProblem(file, each.getCause().getMessage())); - } - } - else if (each instanceof ProjectBuildingException) { - String causeMessage = each.getCause() != null ? each.getCause().getMessage() : each.getMessage(); - problems.add(createStructureProblem(file, causeMessage)); + MavenProjectReaderResult result = readProject(generalSettings, file, explicitProfiles, locator); + String message = e.getMessage(); + if (message != null) { + result.readingProblems.add(MavenProjectProblem.createStructureProblem(file.getPath(), message)); } else { - problems.add(createStructureProblem(file, each.getMessage())); + result.readingProblems.add(MavenProjectProblem.createSyntaxProblem(file.getPath(), MavenProjectProblem.ProblemType.SYNTAX)); } + return result; } - - return problems.isEmpty(); } public MavenProjectReaderResult generateSources(MavenEmbedderWrapper embedder, - MavenGeneralSettings generalSettings, MavenImportingSettings importingSettings, VirtualFile file, Collection profiles, MavenConsole console) throws MavenProcessCanceledException { try { - MavenWrapperExecutionResult result = embedder.execute(file, profiles, Arrays.asList(importingSettings.getUpdateFoldersOnImportPhase())); + List goals = Arrays.asList(importingSettings.getUpdateFoldersOnImportPhase()); + Collection problems = MavenProjectProblem.createProblemsList(); + Set unresolvedArtifacts = new THashSet(); + MavenWrapperExecutionResult result = embedder.execute(file, profiles, goals); + if (result.projectData == null) return null; - if (result.hasExceptions()) { - MavenConsoleHelper.printExecutionExceptions(console, result); - } - - Collection problems = createProblemsList(); - if (!validate(file, result, problems)) return null; - - MavenProject project = result.getMavenProject(); - if (project == null) return null; - - return new MavenProjectReaderResult(generalSettings, - project, - Collections.emptyList(), - problems, - result.getUnresolvedArtifactIds(), - embedder.getLocalRepositoryFile()); - } - catch (MavenProcessCanceledException e) { - throw e; + return new MavenProjectReaderResult(result.projectData.mavenModel, + result.projectData.mavenModelMap, + result.projectData.activatedProfiles, + result.projectData.nativeMavenProject, + result.problems, + result.unresolvedArtifacts); } catch (Throwable e) { - MavenConsoleHelper.printException(console, e); + console.printException(e); MavenLog.LOG.warn(e); return null; } @@ -717,21 +503,21 @@ public class MavenProjectReader { return MavenJDOMUtil.read(file, new MavenJDOMUtil.ErrorHandler() { public void onReadError(IOException e) { MavenLog.LOG.warn("Cannot read the pom file: " + e); - problems.add(createProblem(file, e.getMessage(), type)); + problems.add(MavenProjectProblem.createProblem(file.getPath(), e.getMessage(), type)); } public void onSyntaxError() { - problems.add(createSyntaxProblem(file, type)); + problems.add(MavenProjectProblem.createSyntaxProblem(file.getPath(), type)); } }); } private static class RawModelReadResult { - public Model model; + public MavenModel model; public Collection problems; public Set alwaysOnProfiles; - private RawModelReadResult(Model model, Collection problems, Set alwaysOnProfiles) { + private RawModelReadResult(MavenModel model, Collection problems, Set alwaysOnProfiles) { this.model = model; this.problems = problems; this.alwaysOnProfiles = alwaysOnProfiles; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectReaderProjectLocator.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectReaderProjectLocator.java index 08927dfbcbeb..3d88e3445d8d 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectReaderProjectLocator.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectReaderProjectLocator.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2010 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package org.jetbrains.idea.maven.project; import com.intellij.openapi.vfs.VirtualFile; -import org.jetbrains.idea.maven.project.MavenId; +import org.jetbrains.idea.maven.model.MavenId; public interface MavenProjectReaderProjectLocator { VirtualFile findProjectFile(MavenId coordinates); diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectReaderResult.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectReaderResult.java index aae7c5bc70be..c9af6eaf11b8 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectReaderResult.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectReaderResult.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2010 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,32 +15,33 @@ */ package org.jetbrains.idea.maven.project; -import org.apache.maven.project.MavenProject; -import org.apache.maven.shared.dependency.tree.DependencyNode; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.idea.maven.facade.NativeMavenProjectHolder; +import org.jetbrains.idea.maven.model.*; -import java.io.File; import java.util.Collection; +import java.util.Map; import java.util.Set; public class MavenProjectReaderResult { - final public MavenGeneralSettings settings; - final public MavenProject nativeMavenProject; - final public Collection dependencyTree; - final public Collection readingProblems; - final public Set unresolvedArtifactIds; - final public File localRepository; + public final MavenModel mavenModel; + public final Map nativeModelMap; + public final Collection activatedProfiles; + @Nullable public final NativeMavenProjectHolder nativeMavenProject; + public final Collection readingProblems; + public final Set unresolvedArtifactIds; - public MavenProjectReaderResult(MavenGeneralSettings settings, - MavenProject nativeMavenProject, - Collection dependencyTree, + public MavenProjectReaderResult(MavenModel mavenModel, + Map nativeModelMap, + Collection activatedProfiles, + @Nullable NativeMavenProjectHolder nativeMavenProject, Collection readingProblems, - Set unresolvedArtifactIds, - File localRepository) { - this.settings = settings; + Set unresolvedArtifactIds) { + this.mavenModel = mavenModel; + this.nativeModelMap = nativeModelMap; + this.activatedProfiles = activatedProfiles; this.nativeMavenProject = nativeMavenProject; - this.dependencyTree = dependencyTree; this.readingProblems = readingProblems; this.unresolvedArtifactIds = unresolvedArtifactIds; - this.localRepository = localRepository; } } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManager.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManager.java index 592b40514ed6..043196f086ee 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManager.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManager.java @@ -49,10 +49,12 @@ import org.jetbrains.idea.maven.dom.MavenDomUtil; import org.jetbrains.idea.maven.dom.model.MavenDomDependency; import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; import org.jetbrains.idea.maven.execution.SoutMavenConsole; +import org.jetbrains.idea.maven.facade.NativeMavenProjectHolder; import org.jetbrains.idea.maven.importing.MavenDefaultModifiableModelsProvider; import org.jetbrains.idea.maven.importing.MavenFoldersImporter; import org.jetbrains.idea.maven.importing.MavenModifiableModelsProvider; import org.jetbrains.idea.maven.importing.MavenProjectImporter; +import org.jetbrains.idea.maven.model.*; import org.jetbrains.idea.maven.utils.*; import java.io.File; @@ -237,7 +239,7 @@ public class MavenProjectsManager extends SimpleProjectComponent } private void initWorkers() { - myEmbeddersManager = new MavenEmbeddersManager(getGeneralSettings()); + myEmbeddersManager = new MavenEmbeddersManager(myProject); myReadingProcessor = new MavenProjectsProcessor(myProject, ProjectBundle.message("maven.reading"), false, myEmbeddersManager); myResolvingProcessor = new MavenProjectsProcessor(myProject, ProjectBundle.message("maven.resolving"), true, myEmbeddersManager); @@ -330,9 +332,9 @@ public class MavenProjectsManager extends SimpleProjectComponent @Override public void projectResolved(Pair projectWithChanges, - org.apache.maven.project.MavenProject nativeMavenProject, + @Nullable NativeMavenProjectHolder nativeMavenProject, Object message) { - if (shouldScheduleProject(projectWithChanges)) { + if (nativeMavenProject != null && shouldScheduleProject(projectWithChanges)) { if (projectWithChanges.first.hasUnresolvedPlugins()) { schedulePluginsResolving(projectWithChanges.first, nativeMavenProject); } @@ -392,16 +394,13 @@ public class MavenProjectsManager extends SimpleProjectComponent myArtifactsDownloadingProcessor.stop(); myPostProcessor.stop(); - myEmbeddersManager.release(); - if (isUnitTestMode()) { FileUtil.delete(getProjectsTreesDir()); } } } - @TestOnly - public MavenEmbeddersManager getEmbeddersManagerInTests() { + public MavenEmbeddersManager getEmbeddersManager() { return myEmbeddersManager; } @@ -478,7 +477,7 @@ public class MavenProjectsManager extends SimpleProjectComponent return myProjectsTree.getAvailableProfiles(); } - public Collection> getProfilesWithStates() { + public Collection> getProfilesWithStates() { if (!isInitialized()) return Collections.emptyList(); return myProjectsTree.getProfilesWithStates(); } @@ -679,7 +678,7 @@ public class MavenProjectsManager extends SimpleProjectComponent MavenProject each = it.next(); Object message = it.hasNext() ? null : FORCE_IMPORT_MESSAGE; myFoldersResolvingProcessor.scheduleTask( - new MavenProjectsProcessorFoldersResolvingTask(each, getGeneralSettings(), getImportingSettings(), myProjectsTree, message)); + new MavenProjectsProcessorFoldersResolvingTask(each, getImportingSettings(), myProjectsTree, message)); } } }); @@ -689,7 +688,7 @@ public class MavenProjectsManager extends SimpleProjectComponent scheduleFoldersResolving(getProjects()); } - private void schedulePluginsResolving(final MavenProject project, final org.apache.maven.project.MavenProject nativeMavenProject) { + private void schedulePluginsResolving(final MavenProject project, final NativeMavenProjectHolder nativeMavenProject) { runWhenFullyOpen(new Runnable() { public void run() { myPluginsResolvingProcessor diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManagerWatcher.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManagerWatcher.java index e7124afe2cb8..9ef1ca9b7de6 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManagerWatcher.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManagerWatcher.java @@ -36,7 +36,6 @@ import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.newvfs.BulkFileListener; import com.intellij.openapi.vfs.newvfs.NewVirtualFile; import com.intellij.openapi.vfs.newvfs.events.*; -import com.intellij.openapi.vfs.newvfs.impl.NullVirtualFile; import com.intellij.openapi.vfs.pointers.VirtualFilePointer; import com.intellij.openapi.vfs.pointers.VirtualFilePointerListener; import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager; @@ -47,7 +46,7 @@ import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.ui.update.Update; import gnu.trove.THashSet; import org.jetbrains.annotations.TestOnly; -import org.jetbrains.idea.maven.utils.MavenConstants; +import org.jetbrains.idea.maven.model.MavenConstants; import org.jetbrains.idea.maven.utils.MavenMergingUpdateQueue; import org.jetbrains.idea.maven.utils.MavenUtil; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessor.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessor.java index 2b0e4e505010..7d807fa7c2eb 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessor.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessor.java @@ -19,7 +19,6 @@ import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Condition; import com.intellij.util.concurrency.Semaphore; -import org.jetbrains.idea.maven.embedder.MavenConsole; import org.jetbrains.idea.maven.execution.SoutMavenConsole; import org.jetbrains.idea.maven.utils.*; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorArtifactsDownloadingTask.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorArtifactsDownloadingTask.java index 53460c30b4a1..d03b3763de5b 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorArtifactsDownloadingTask.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorArtifactsDownloadingTask.java @@ -20,7 +20,7 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ex.ProjectRootManagerEx; import com.intellij.openapi.util.AsyncResult; import com.intellij.openapi.util.EmptyRunnable; -import org.jetbrains.idea.maven.embedder.MavenConsole; +import org.jetbrains.idea.maven.model.MavenArtifact; import org.jetbrains.idea.maven.utils.MavenProcessCanceledException; import org.jetbrains.idea.maven.utils.MavenProgressIndicator; import org.jetbrains.idea.maven.utils.MavenUtil; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorEmptyTask.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorEmptyTask.java index b3217db42598..5361ad0e6234 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorEmptyTask.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorEmptyTask.java @@ -15,7 +15,6 @@ */ package org.jetbrains.idea.maven.project; -import org.jetbrains.idea.maven.embedder.MavenConsole; import org.jetbrains.idea.maven.utils.MavenProgressIndicator; import org.jetbrains.idea.maven.utils.MavenProcessCanceledException; import com.intellij.openapi.project.Project; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorFoldersResolvingTask.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorFoldersResolvingTask.java index 6700f041d23e..784709d26815 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorFoldersResolvingTask.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorFoldersResolvingTask.java @@ -16,28 +16,24 @@ package org.jetbrains.idea.maven.project; import com.intellij.openapi.project.Project; -import org.jetbrains.idea.maven.embedder.MavenConsole; import org.jetbrains.idea.maven.utils.MavenProcessCanceledException; import org.jetbrains.idea.maven.utils.MavenProgressIndicator; public class MavenProjectsProcessorFoldersResolvingTask extends MavenProjectsProcessorBasicTask { - private final MavenGeneralSettings myGeneralSettings; private final MavenImportingSettings myImportingSettings; private final Object myMessage; public MavenProjectsProcessorFoldersResolvingTask(MavenProject project, - MavenGeneralSettings generalSettings, MavenImportingSettings importingSettings, MavenProjectsTree tree, Object message) { super(project, tree); - myGeneralSettings = generalSettings; myImportingSettings = importingSettings; myMessage = message; } public void perform(Project project, MavenEmbeddersManager embeddersManager, MavenConsole console, MavenProgressIndicator indicator) throws MavenProcessCanceledException { - myTree.resolveFolders(myMavenProject, myGeneralSettings, myImportingSettings, embeddersManager, console, indicator, myMessage); + myTree.resolveFolders(myMavenProject, myImportingSettings, embeddersManager, console, indicator, myMessage); } } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorPluginsResolvingTask.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorPluginsResolvingTask.java index e62349522b6f..32d79f792ee3 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorPluginsResolvingTask.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorPluginsResolvingTask.java @@ -16,15 +16,15 @@ package org.jetbrains.idea.maven.project; import com.intellij.openapi.project.Project; -import org.jetbrains.idea.maven.embedder.MavenConsole; -import org.jetbrains.idea.maven.utils.MavenProgressIndicator; +import org.jetbrains.idea.maven.facade.NativeMavenProjectHolder; import org.jetbrains.idea.maven.utils.MavenProcessCanceledException; +import org.jetbrains.idea.maven.utils.MavenProgressIndicator; public class MavenProjectsProcessorPluginsResolvingTask extends MavenProjectsProcessorBasicTask { - private final org.apache.maven.project.MavenProject myNativeMavenProject; + private final NativeMavenProjectHolder myNativeMavenProject; public MavenProjectsProcessorPluginsResolvingTask(MavenProject project, - org.apache.maven.project.MavenProject nativeMavenProject, + NativeMavenProjectHolder nativeMavenProject, MavenProjectsTree tree) { super(project, tree); myNativeMavenProject = nativeMavenProject; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorReadingTask.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorReadingTask.java index 01b229f9501b..d896351bc87c 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorReadingTask.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorReadingTask.java @@ -17,7 +17,6 @@ package org.jetbrains.idea.maven.project; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; -import org.jetbrains.idea.maven.embedder.MavenConsole; import org.jetbrains.idea.maven.utils.MavenProcessCanceledException; import org.jetbrains.idea.maven.utils.MavenProgressIndicator; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorResolvingTask.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorResolvingTask.java index de1e98c1ef5a..08a45a7ce1ff 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorResolvingTask.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorResolvingTask.java @@ -16,7 +16,6 @@ package org.jetbrains.idea.maven.project; import com.intellij.openapi.project.Project; -import org.jetbrains.idea.maven.embedder.MavenConsole; import org.jetbrains.idea.maven.utils.MavenProcessCanceledException; import org.jetbrains.idea.maven.utils.MavenProgressIndicator; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorTask.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorTask.java index 7fbe3b0592cf..65f43c85beae 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorTask.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorTask.java @@ -16,7 +16,6 @@ package org.jetbrains.idea.maven.project; import com.intellij.openapi.project.Project; -import org.jetbrains.idea.maven.embedder.MavenConsole; import org.jetbrains.idea.maven.utils.MavenProcessCanceledException; import org.jetbrains.idea.maven.utils.MavenProgressIndicator; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsTree.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsTree.java index 5cc178611a5d..8bfb6b6ea0c3 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsTree.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsTree.java @@ -18,6 +18,7 @@ package org.jetbrains.idea.maven.project; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Computable; +import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.LocalFileSystem; @@ -29,11 +30,11 @@ import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.Stack; import gnu.trove.THashMap; import gnu.trove.THashSet; -import org.apache.maven.artifact.Artifact; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; -import org.jetbrains.idea.maven.embedder.MavenConsole; -import org.jetbrains.idea.maven.embedder.MavenEmbedderWrapper; +import org.jetbrains.idea.maven.facade.MavenEmbedderWrapper; +import org.jetbrains.idea.maven.facade.NativeMavenProjectHolder; +import org.jetbrains.idea.maven.model.*; import org.jetbrains.idea.maven.utils.*; import java.io.*; @@ -64,7 +65,7 @@ public class MavenProjectsTree { private final Map myTimestamps = new THashMap(); private final Map myVirtualFileToProjectMapping = new THashMap(); private final Map myMavenIdToProjectMapping = new THashMap(); - private final Map myMavenIdToFileMapping = new THashMap(); + private final Map myMavenIdToFileMapping = new THashMap(); private final Map> myAggregatorToModuleMapping = new THashMap>(); private final Map myModuleToAggregatorMapping = new THashMap(); @@ -138,7 +139,7 @@ public class MavenProjectsTree { tree.myTimestamps.put(project, timestamp); tree.myVirtualFileToProjectMapping.put(project.getFile(), project); tree.myMavenIdToProjectMapping.put(project.getMavenId(), project); - tree.myMavenIdToFileMapping.put(project.getMavenId(), project.getFile()); + tree.myMavenIdToFileMapping.put(project.getMavenId(), new File(project.getFile().getPath())); tree.myAggregatorToModuleMapping.put(project, modules); for (MavenProject eachModule : modules) { tree.myModuleToAggregatorMapping.put(eachModule, project); @@ -387,8 +388,8 @@ public class MavenProjectsTree { return Pair.create(available, active); } - public Collection> getProfilesWithStates() { - Collection> result = new ArrayListSet>(); + public Collection> getProfilesWithStates() { + Collection> result = new ArrayListSet>(); Pair, Collection> profiles = getAvailableAndActiveProfiles(true, true); Collection available = profiles.first; @@ -396,11 +397,11 @@ public class MavenProjectsTree { Collection explicitProfiles = getExplicitProfiles(); for (String each : available) { - MavenProfileState state = MavenProfileState.NONE; + MavenProfileKind state = MavenProfileKind.NONE; if (explicitProfiles.contains(each)) { - state = MavenProfileState.EXPLICIT; + state = MavenProfileKind.EXPLICIT; } - else if (active.contains(each)) state = MavenProfileState.IMPLICIT; + else if (active.contains(each)) state = MavenProfileKind.IMPLICIT; result.add(Pair.create(each, state)); } return result; @@ -541,7 +542,7 @@ public class MavenProjectsTree { try { myVirtualFileToProjectMapping.put(mavenProject.getFile(), mavenProject); myMavenIdToProjectMapping.put(mavenProject.getMavenId(), mavenProject); - myMavenIdToFileMapping.put(mavenProject.getMavenId(), mavenProject.getFile()); + myMavenIdToFileMapping.put(mavenProject.getMavenId(), new File(mavenProject.getFile().getPath())); } finally { writeUnlock(); @@ -891,14 +892,10 @@ public class MavenProjectsTree { return findProject(artifact.getMavenId()); } - public MavenProject findProject(Artifact artifact) { - return findProject(new MavenId(artifact)); - } - - private Map getProjectIdToFileMapping() { + private Map getProjectIdToFileMapping() { readLock(); try { - return new THashMap(myMavenIdToFileMapping); + return new THashMap(myMavenIdToFileMapping); } finally { readUnlock(); @@ -990,17 +987,17 @@ public class MavenProjectsTree { MavenConsole console, MavenProgressIndicator process, Object message) throws MavenProcessCanceledException { - MavenEmbedderWrapper embedder = embeddersManager.getEmbedder(MavenEmbeddersManager.EmbedderKind.FOR_DEPENDENCIES_RESOLVE); + MavenEmbedderWrapper embedder = embeddersManager.getEmbedder(MavenEmbeddersManager.FOR_DEPENDENCIES_RESOLVE); embedder.customizeForResolve(getProjectIdToFileMapping(), console, process); try { process.checkCanceled(); process.setText(ProjectBundle.message("maven.resolving.pom", mavenProject.getDisplayName())); process.setText2(""); - Pair resolveResult = mavenProject.resolve(generalSettings, - embedder, - new MavenProjectReader(), - myProjectLocator); + Pair resolveResult = mavenProject.resolve(generalSettings, + embedder, + new MavenProjectReader(), + myProjectLocator); fireProjectResolved(Pair.create(mavenProject, resolveResult.first), resolveResult.second, message); } @@ -1010,11 +1007,11 @@ public class MavenProjectsTree { } public void resolvePlugins(MavenProject mavenProject, - org.apache.maven.project.MavenProject nativeMavenProject, + NativeMavenProjectHolder nativeMavenProject, MavenEmbeddersManager embeddersManager, MavenConsole console, MavenProgressIndicator process) throws MavenProcessCanceledException { - MavenEmbedderWrapper embedder = embeddersManager.getEmbedder(MavenEmbeddersManager.EmbedderKind.FOR_PLUGINS_RESOLVE); + MavenEmbedderWrapper embedder = embeddersManager.getEmbedder(MavenEmbeddersManager.FOR_PLUGINS_RESOLVE); embedder.customizeForResolve(console, process); embedder.clearCachesFor(mavenProject.getMavenId()); @@ -1022,7 +1019,7 @@ public class MavenProjectsTree { for (MavenPlugin each : mavenProject.getDeclaredPlugins()) { process.checkCanceled(); process.setText(ProjectBundle.message("maven.downloading.pom.plugins", mavenProject.getDisplayName())); - embedder.resolvePlugin(each, nativeMavenProject, false); + embedder.resolvePlugin(each, mavenProject.getRemoteRepositories(), nativeMavenProject, false); } mavenProject.resetCache(); firePluginsResolved(mavenProject); @@ -1033,7 +1030,6 @@ public class MavenProjectsTree { } public void resolveFolders(final MavenProject mavenProject, - final MavenGeneralSettings generalSettings, final MavenImportingSettings importingSettings, final MavenEmbeddersManager embeddersManager, final MavenConsole console, @@ -1041,7 +1037,7 @@ public class MavenProjectsTree { final Object message) throws MavenProcessCanceledException { executeWithEmbedder(mavenProject, embeddersManager, - MavenEmbeddersManager.EmbedderKind.FOR_FOLDERS_RESOLVE, + MavenEmbeddersManager.FOR_FOLDERS_RESOLVE, console, process, new EmbedderTask() { @@ -1051,7 +1047,6 @@ public class MavenProjectsTree { process.setText2(""); Pair resolveResult = mavenProject.resolveFolders(embedder, - generalSettings, importingSettings, new MavenProjectReader(), console); @@ -1073,7 +1068,7 @@ public class MavenProjectsTree { MavenConsole console, MavenProgressIndicator process) throws MavenProcessCanceledException { - MavenEmbedderWrapper embedder = embeddersManager.getEmbedder(MavenEmbeddersManager.EmbedderKind.FOR_DOWNLOAD); + MavenEmbedderWrapper embedder = embeddersManager.getEmbedder(MavenEmbeddersManager.FOR_DOWNLOAD); embedder.customizeForResolve(console, process); try { @@ -1095,12 +1090,13 @@ public class MavenProjectsTree { MavenEmbeddersManager embeddersManager, MavenConsole console, MavenProgressIndicator process) throws MavenProcessCanceledException { - MavenEmbedderWrapper embedder = embeddersManager.getEmbedder(MavenEmbeddersManager.EmbedderKind.FOR_DOWNLOAD); + MavenEmbedderWrapper embedder = embeddersManager.getEmbedder(MavenEmbeddersManager.FOR_DOWNLOAD); embedder.customizeForResolve(console, process); try { - MavenArtifact result = embedder.resolve(id, MavenConstants.TYPE_JAR, null, mavenProject.getRemoteRepositories()); - result.setScope(Artifact.SCOPE_COMPILE); + MavenArtifact result = embedder.resolve(new MavenArtifactInfo(id, MavenConstants.TYPE_JAR, null), + mavenProject.getRemoteRepositories()); + result.setScope(MavenConstants.SCOPE_COMPILE); return result; } finally { @@ -1110,7 +1106,7 @@ public class MavenProjectsTree { public void executeWithEmbedder(MavenProject mavenProject, MavenEmbeddersManager embeddersManager, - MavenEmbeddersManager.EmbedderKind embedderKind, + Key embedderKind, MavenConsole console, MavenProgressIndicator process, EmbedderTask task) throws MavenProcessCanceledException { @@ -1183,7 +1179,7 @@ public class MavenProjectsTree { } private void fireProjectResolved(Pair projectWithChanges, - org.apache.maven.project.MavenProject nativeMavenProject, + NativeMavenProjectHolder nativeMavenProject, Object message) { for (Listener each : myListeners) { each.projectResolved(projectWithChanges, nativeMavenProject, message); @@ -1360,7 +1356,7 @@ public class MavenProjectsTree { void projectsUpdated(List> updated, List deleted, Object message); void projectResolved(Pair projectWithChanges, - org.apache.maven.project.MavenProject nativeMavenProject, + @Nullable NativeMavenProjectHolder nativeMavenProject, Object message); void pluginsResolved(MavenProject project); @@ -1381,7 +1377,7 @@ public class MavenProjectsTree { } public void projectResolved(Pair projectWithChanges, - org.apache.maven.project.MavenProject nativeMavenProject, + @Nullable NativeMavenProjectHolder nativeMavenProject, Object message) { } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenRemoteRepository.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenRemoteRepository.java deleted file mode 100644 index 1c530bbfcf34..000000000000 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenRemoteRepository.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.idea.maven.project; - -import org.apache.maven.model.Repository; -import org.apache.maven.model.RepositoryPolicy; - -import java.io.Serializable; - -public class MavenRemoteRepository implements Serializable { - private String myId; - private String myName; - private String myUrl; - private String myLayout; - private Policy myReleasesPolicy; - private Policy mySnapshotsPolicy; - - protected MavenRemoteRepository() { - } - - public MavenRemoteRepository(Repository repository) { - myId = repository.getId(); - myName = repository.getName(); - myUrl = repository.getUrl(); - myLayout = repository.getLayout(); - - if (repository.getReleases()!= null) myReleasesPolicy = new Policy(repository.getReleases()); - if (repository.getSnapshots() != null) mySnapshotsPolicy = new Policy(repository.getSnapshots()); - } - - public String getId() { - return myId; - } - - public String getName() { - return myName; - } - - public String getUrl() { - return myUrl; - } - - public String getLayout() { - return myLayout; - } - - public Policy getReleasesPolicy() { - return myReleasesPolicy; - } - - public Policy getSnapshotsPolicy() { - return mySnapshotsPolicy; - } - - public Repository toRepository() { - Repository result = new Repository(); - result.setId(myId); - result.setName(myName); - result.setUrl(myUrl); - result.setLayout(myLayout); - - if (myReleasesPolicy != null) result.setReleases(myReleasesPolicy.toRepositoryPolicy()); - if (mySnapshotsPolicy != null) result.setSnapshots(mySnapshotsPolicy.toRepositoryPolicy()); - - return result; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - MavenRemoteRepository that = (MavenRemoteRepository)o; - - if (myId != null ? !myId.equals(that.myId) : that.myId != null) return false; - - return true; - } - - @Override - public int hashCode() { - return myId != null ? myId.hashCode() : 0; - } - - public static class Policy implements Serializable { - private boolean myEnabled; - private String myUpdatePolicy; - private String myChecksumPolicy; - - protected Policy() { - } - - public Policy(RepositoryPolicy policy) { - myEnabled = policy.isEnabled(); - myUpdatePolicy = policy.getUpdatePolicy(); - myChecksumPolicy = policy.getChecksumPolicy(); - } - - public boolean isEnabled() { - return myEnabled; - } - - public String getUpdatePolicy() { - return myUpdatePolicy; - } - - public String getChecksumPolicy() { - return myChecksumPolicy; - } - - public RepositoryPolicy toRepositoryPolicy() { - RepositoryPolicy result =new RepositoryPolicy(); - result.setEnabled(myEnabled); - result.setUpdatePolicy(myUpdatePolicy); - result.setChecksumPolicy(myChecksumPolicy); - return result; - } - } -} diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/actions/DownloadSelectedSourcesAndDocsAction.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/actions/DownloadSelectedSourcesAndDocsAction.java index 33fb94ef3d27..696dd13120be 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/actions/DownloadSelectedSourcesAndDocsAction.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/actions/DownloadSelectedSourcesAndDocsAction.java @@ -16,12 +16,11 @@ package org.jetbrains.idea.maven.project.actions; import com.intellij.openapi.actionSystem.AnActionEvent; -import org.jetbrains.idea.maven.project.MavenArtifact; +import org.jetbrains.idea.maven.model.MavenArtifact; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.project.MavenProjectsManager; import org.jetbrains.idea.maven.utils.MavenDataKeys; -import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/tasks/MavenKeymapExtension.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/tasks/MavenKeymapExtension.java index 015d402bab32..8dd291d5e59b 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/tasks/MavenKeymapExtension.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/tasks/MavenKeymapExtension.java @@ -23,10 +23,11 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Pair; import org.jetbrains.annotations.TestOnly; -import org.jetbrains.idea.maven.embedder.MavenEmbedderWrapper; import org.jetbrains.idea.maven.execution.MavenRunConfigurationType; import org.jetbrains.idea.maven.execution.MavenRunnerParameters; -import org.jetbrains.idea.maven.project.MavenPlugin; +import org.jetbrains.idea.maven.facade.MavenEmbedderWrapper; +import org.jetbrains.idea.maven.model.MavenConstants; +import org.jetbrains.idea.maven.model.MavenPlugin; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.project.MavenProjectsManager; import org.jetbrains.idea.maven.utils.MavenArtifactUtil; @@ -142,7 +143,7 @@ public class MavenKeymapExtension implements KeymapExtension { private static List collectGoals(MavenProject project) { LinkedHashSet result = new LinkedHashSet(); // may contains similar plugins or somethig - result.addAll(MavenEmbedderWrapper.PHASES); + result.addAll(MavenConstants.PHASES); for (MavenPlugin each : project.getDeclaredPlugins()) { collectGoals(project.getLocalRepository(), each, result); diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/tasks/MavenShortcutsManager.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/tasks/MavenShortcutsManager.java index e670fe2ff671..4a0d284b1f23 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/tasks/MavenShortcutsManager.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/tasks/MavenShortcutsManager.java @@ -23,8 +23,8 @@ import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.openapi.keymap.ex.KeymapManagerEx; import com.intellij.openapi.project.DumbAwareRunnable; import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.Pair; +import com.intellij.openapi.util.io.FileUtil; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.update.MergingUpdateQueue; @@ -32,9 +32,12 @@ import com.intellij.util.ui.update.Update; import gnu.trove.THashMap; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; -import org.jetbrains.idea.maven.project.*; import org.jetbrains.idea.maven.execution.MavenRunner; +import org.jetbrains.idea.maven.facade.NativeMavenProjectHolder; import org.jetbrains.idea.maven.project.MavenProject; +import org.jetbrains.idea.maven.project.MavenProjectChanges; +import org.jetbrains.idea.maven.project.MavenProjectsManager; +import org.jetbrains.idea.maven.project.MavenProjectsTree; import org.jetbrains.idea.maven.utils.MavenMergingUpdateQueue; import org.jetbrains.idea.maven.utils.MavenUtil; import org.jetbrains.idea.maven.utils.SimpleProjectComponent; @@ -195,7 +198,7 @@ public class MavenShortcutsManager extends SimpleProjectComponent { @Override public void projectResolved(Pair projectWithChanges, - org.apache.maven.project.MavenProject nativeMavenProject, + NativeMavenProjectHolder nativeMavenProject, Object message) { scheduleKeymapUpdate(Collections.singletonList(projectWithChanges.first), true); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/FileFinder.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/FileFinder.java index 0e968753e55e..da81dba739fe 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/FileFinder.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/FileFinder.java @@ -20,7 +20,7 @@ import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.util.Computable; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; -import org.jetbrains.idea.maven.utils.MavenConstants; +import org.jetbrains.idea.maven.model.MavenConstants; import java.util.List; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenArtifactUtil.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenArtifactUtil.java index 5a269c709a6a..fdac7e4a6313 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenArtifactUtil.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenArtifactUtil.java @@ -21,7 +21,7 @@ import gnu.trove.THashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.maven.indices.IndicesBundle; -import org.jetbrains.idea.maven.project.MavenId; +import org.jetbrains.idea.maven.model.MavenId; import java.io.File; import java.io.IOException; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenAttachSourcesProvider.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenAttachSourcesProvider.java index 49467a4918ba..ab0ecace6d5f 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenAttachSourcesProvider.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenAttachSourcesProvider.java @@ -28,6 +28,8 @@ import com.intellij.openapi.util.AsyncResult; import com.intellij.psi.PsiFile; import gnu.trove.THashSet; import org.jetbrains.idea.maven.importing.MavenRootModelAdapter; +import org.jetbrains.idea.maven.model.MavenArtifact; +import org.jetbrains.idea.maven.model.MavenId; import org.jetbrains.idea.maven.project.*; import javax.swing.*; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenDataKeys.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenDataKeys.java index ee25e4f33ecc..70ea789a65aa 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenDataKeys.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenDataKeys.java @@ -16,7 +16,7 @@ package org.jetbrains.idea.maven.utils; import com.intellij.openapi.actionSystem.DataKey; -import org.jetbrains.idea.maven.project.MavenArtifact; +import org.jetbrains.idea.maven.model.MavenArtifact; import javax.swing.*; import java.util.Collection; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenEnvironmentRegistrar.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenEnvironmentRegistrar.java index 9fea46867b53..134029336e6e 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenEnvironmentRegistrar.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenEnvironmentRegistrar.java @@ -22,7 +22,7 @@ import com.intellij.openapi.application.PathMacros; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.fileTypes.FileTypeManager; import org.jetbrains.annotations.NotNull; -import org.jetbrains.idea.maven.embedder.MavenEmbedderUtilEx; +import org.jetbrains.idea.maven.model.MavenConstants; import java.io.File; @@ -46,7 +46,7 @@ public class MavenEnvironmentRegistrar implements ApplicationComponent { } private void registerPathVariable() { - File repository = MavenEmbedderUtilEx.resolveLocalRepository(null, null, null); + File repository = MavenUtil.resolveLocalRepository(null, null, null); PathMacros macros = PathMacros.getInstance(); for (String each : macros.getAllMacroNames()) { diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenPluginInfo.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenPluginInfo.java index 662f836c7c7b..e829725506d7 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenPluginInfo.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenPluginInfo.java @@ -16,9 +16,9 @@ package org.jetbrains.idea.maven.utils; import org.jdom.Element; -import org.jetbrains.idea.maven.project.MavenId; +import org.jetbrains.idea.maven.model.MavenId; -import static org.jetbrains.idea.maven.project.MavenId.append; +import static org.jetbrains.idea.maven.model.MavenId.append; import java.util.Collection; import java.util.LinkedHashMap; @@ -35,7 +35,7 @@ public class MavenPluginInfo { Element plugin = MavenJDOMUtil.read(text, null); myGroupId = MavenJDOMUtil.findChildValueByPath(plugin, "groupId", MavenId.UNKNOWN_VALUE); - myArtifactId = MavenJDOMUtil.findChildValueByPath(plugin, "artifactId",MavenId.UNKNOWN_VALUE); + myArtifactId = MavenJDOMUtil.findChildValueByPath(plugin, "artifactId", MavenId.UNKNOWN_VALUE); myVersion = MavenJDOMUtil.findChildValueByPath(plugin, "version", MavenId.UNKNOWN_VALUE); myGoalPrefix = MavenJDOMUtil.findChildValueByPath(plugin, "goalPrefix", "unknown"); diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenRehighlighter.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenRehighlighter.java index f319b0cf4f8d..f10ae32a24fd 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenRehighlighter.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenRehighlighter.java @@ -21,12 +21,11 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.psi.PsiManager; import com.intellij.psi.impl.PsiModificationTrackerImpl; +import org.jetbrains.idea.maven.facade.NativeMavenProjectHolder; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.project.MavenProjectChanges; import org.jetbrains.idea.maven.project.MavenProjectsManager; import org.jetbrains.idea.maven.project.MavenProjectsTree; -import org.jetbrains.idea.maven.utils.MavenUtil; -import org.jetbrains.idea.maven.utils.SimpleProjectComponent; import java.util.List; @@ -51,7 +50,7 @@ public class MavenRehighlighter extends SimpleProjectComponent { } public void projectResolved(Pair projectWithChanges, - org.apache.maven.project.MavenProject nativeMavenProject, + NativeMavenProjectHolder nativeMavenProject, Object message) { rehighlight(myProject); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenUIUtil.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenUIUtil.java index 41db66be556a..0fb0d4f53d39 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenUIUtil.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenUIUtil.java @@ -30,7 +30,9 @@ import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreePath; import java.awt.*; import java.awt.event.*; -import java.util.*; +import java.util.Collection; +import java.util.Comparator; +import java.util.TreeSet; public class MavenUIUtil { public static void executeAction(final String actionId, final InputEvent e) { @@ -38,7 +40,8 @@ public class MavenUIUtil { final AnAction action = actionManager.getAction(actionId); if (action != null) { final Presentation presentation = new Presentation(); - final AnActionEvent event = new AnActionEvent(e, DataManager.getInstance().getDataContext(e.getComponent()), "", presentation, actionManager, 0); + final AnActionEvent event = + new AnActionEvent(e, DataManager.getInstance().getDataContext(e.getComponent()), "", presentation, actionManager, 0); action.update(event); if (presentation.isEnabled()) { action.actionPerformed(event); @@ -46,13 +49,13 @@ public class MavenUIUtil { } } - public static void setElements(ElementsChooser chooser, Collection all, Collection selected, Comparator comparator){ + public static void setElements(ElementsChooser chooser, Collection all, Collection selected, Comparator comparator) { java.util.List selection = chooser.getSelectedElements(); chooser.clear(); Collection sorted = new TreeSet(comparator); sorted.addAll(all); for (E element : sorted) { - chooser.addElement( element, selected.contains(element)); + chooser.addElement(element, selected.contains(element)); } chooser.selectElements(selection); } @@ -86,7 +89,7 @@ public class MavenUIUtil { panel.setForeground(foreground); CheckBoxState state = handler.getState(userObject); - checkbox.setSelected(state != CheckBoxState.UNCHECKED); + checkbox.setSelected(state != CheckBoxState.UNCHECKED); checkbox.setEnabled(state != CheckBoxState.PARTIAL); checkbox.setBackground(UIUtil.getTreeTextBackground()); checkbox.setForeground(foreground); diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenUtil.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenUtil.java index 478a4d484da3..42e8ed885abd 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenUtil.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenUtil.java @@ -39,24 +39,24 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; +import com.intellij.openapi.util.text.StringUtil; +import com.intellij.openapi.vfs.JarFileSystem; +import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.Function; -import com.intellij.util.ReflectionUtil; import com.intellij.util.containers.ContainerUtil; import gnu.trove.THashSet; -import org.apache.commons.beanutils.BeanUtils; -import org.apache.maven.model.Model; -import org.codehaus.plexus.util.xml.Xpp3Dom; import org.jetbrains.annotations.NotNull; -import org.jetbrains.idea.maven.project.MavenId; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.idea.maven.facade.MavenFacadeManager; +import org.jetbrains.idea.maven.facade.MavenFacadeUtil; +import org.jetbrains.idea.maven.model.MavenConstants; +import org.jetbrains.idea.maven.model.MavenId; import org.jetbrains.idea.maven.project.MavenProject; import java.io.File; import java.io.IOException; -import java.io.Serializable; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.util.*; import java.util.concurrent.ExecutionException; @@ -67,6 +67,17 @@ import java.util.regex.PatternSyntaxException; public class MavenUtil { public static final String MAVEN_NOTIFICATION_GROUP = "Maven"; + public static final String SETTINGS_XML = "settings.xml"; + public static final String DOT_M2_DIR = ".m2"; + public static final String PROP_USER_HOME = "user.home"; + public static final String ENV_M2_HOME = "M2_HOME"; + public static final String M2_DIR = "m2"; + public static final String BIN_DIR = "bin"; + public static final String CONF_DIR = "conf"; + public static final String M2_CONF_FILE = "m2.conf"; + public static final String REPOSITORY_DIR = "repository"; + public static final String LIB_DIR = "lib"; + public static final String SUPER_POM_PATH = "org/apache/maven/project/" + MavenConstants.SUPER_POM_XML; public static void invokeLater(Project p, Runnable r) { invokeLater(p, ModalityState.defaultModalityState(), r); @@ -342,56 +353,6 @@ public class MavenUtil { return true; } - public static T cloneObject(T object) { - try { - return (T)BeanUtils.cloneBean(object); - } - catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - catch (InstantiationException e) { - throw new RuntimeException(e); - } - catch (InvocationTargetException e) { - throw new RuntimeException(e); - } - catch (NoSuchMethodException e) { - throw new RuntimeException(e); - } - } - - public static void stripDown(Object object) { - try { - for (Field each : ReflectionUtil.collectFields(object.getClass())) { - Class type = each.getType(); - each.setAccessible(true); - Object value = each.get(object); - if (shouldStrip(value)) { - each.set(object, null); - } - else { - if (value != null) { - Package pack = type.getPackage(); - if (pack != null && Model.class.getPackage().getName().equals(pack.getName())) { - stripDown(value); - } - } - } - } - } - catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - } - - public static boolean shouldStrip(Object value) { - if (value == null) return false; - return value.getClass().isArray() - || value instanceof Collection - || value instanceof Map - || value instanceof Xpp3Dom; - } - public static void run(Project project, String title, final MavenTask task) throws MavenProcessCanceledException { final Exception[] canceledEx = new Exception[1]; @@ -469,6 +430,159 @@ public class MavenUtil { } } + @Nullable + public static File resolveMavenHomeDirectory(@Nullable String overrideMavenHome) { + if (!isEmptyOrSpaces(overrideMavenHome)) { + return new File(overrideMavenHome); + } + + String m2home = System.getenv(ENV_M2_HOME); + if (!isEmptyOrSpaces(m2home)) { + final File homeFromEnv = new File(m2home); + if (isValidMavenHome(homeFromEnv)) { + return homeFromEnv; + } + } + + String userHome = System.getProperty(PROP_USER_HOME); + if (!isEmptyOrSpaces(userHome)) { + final File underUserHome = new File(userHome, M2_DIR); + if (isValidMavenHome(underUserHome)) { + return underUserHome; + } + } + + return null; + } + + public static boolean isEmptyOrSpaces(@Nullable String str) { + return str == null || str.length() == 0 || str.trim().length() == 0; + } + + public static boolean isValidMavenHome(File home) { + return getMavenConfFile(home).exists(); + } + + public static File getMavenConfFile(File mavenHome) { + return new File(new File(mavenHome, BIN_DIR), M2_CONF_FILE); + } + + @Nullable + public static File resolveGlobalSettingsFile(@Nullable String overriddenMavenHome) { + File directory = resolveMavenHomeDirectory(overriddenMavenHome); + if (directory == null) return null; + + return new File(new File(directory, CONF_DIR), SETTINGS_XML); + } + + @NotNull + public static File resolveUserSettingsFile(@Nullable String overriddenUserSettingsFile) { + if (!isEmptyOrSpaces(overriddenUserSettingsFile)) return new File(overriddenUserSettingsFile); + return new File(resolveM2Dir(), SETTINGS_XML); + } + + @NotNull + public static File resolveM2Dir() { + return new File(System.getProperty(PROP_USER_HOME), DOT_M2_DIR); + } + + @NotNull + public static File resolveLocalRepository(@Nullable String overridenLocalRepository, + @Nullable String overridenMavenHome, + @Nullable String overriddenUserSettingsFile) { + File result = null; + if (!isEmptyOrSpaces(overridenLocalRepository)) result = new File(overridenLocalRepository); + if (result == null) { + result = doResolveLocalRepository(resolveUserSettingsFile(overriddenUserSettingsFile), + resolveGlobalSettingsFile(overridenMavenHome)); + } + try { + return result.getCanonicalFile(); + } + catch (IOException e) { + return result; + } + } + + @NotNull + public static File doResolveLocalRepository(@Nullable File userSettingsFile, @Nullable File globalSettingsFile) { + if (userSettingsFile != null) { + final String fromUserSettings = getRepositoryFromSettings(userSettingsFile); + if (!StringUtil.isEmpty(fromUserSettings)) { + return new File(fromUserSettings); + } + } + + if (globalSettingsFile != null) { + final String fromGlobalSettings = getRepositoryFromSettings(globalSettingsFile); + if (!StringUtil.isEmpty(fromGlobalSettings)) { + return new File(fromGlobalSettings); + } + } + + return new File(resolveM2Dir(), REPOSITORY_DIR); + } + + @Nullable + public static String getRepositoryFromSettings(final File file) { + try { + byte[] bytes = FileUtil.loadFileBytes(file); + return expandProperties(MavenJDOMUtil.findChildValueByPath(MavenJDOMUtil.read(bytes, null), "localRepository", null)); + } + catch (IOException e) { + return null; + } + } + + public static String expandProperties(String text) { + if (StringUtil.isEmptyOrSpaces(text)) return text; + Properties props = MavenFacadeUtil.collectSystemProperties(); + for (Map.Entry each : props.entrySet()) { + text = text.replace("${" + each.getKey() + "}", (CharSequence)each.getValue()); + } + return text; + } + + @NotNull + public static VirtualFile resolveSuperPomFile(@Nullable File mavenHome) { + VirtualFile result = null; + if (mavenHome != null) { + result = doResolveSuperPomFile(new File(mavenHome, LIB_DIR)); + } + if (result == null) { + result = doResolveSuperPomFile(MavenFacadeManager.collectClassPathAndLIbsFolder().second); + } + return result; + } + + @Nullable + public static VirtualFile doResolveSuperPomFile(@Nullable File mavenHome) { + File lib = resolveMavenLib(mavenHome); + if (lib == null) return null; + + VirtualFile file = LocalFileSystem.getInstance().findFileByIoFile(lib); + if (file == null) return null; + + VirtualFile root = JarFileSystem.getInstance().getJarRootForLocalFile(file); + if (root == null) return null; + + return root.findFileByRelativePath(SUPER_POM_PATH); + } + + @Nullable + public static File resolveMavenLib(@NotNull File dir) { + File[] files = dir.listFiles(); + if (files != null) { + Pattern pattern = Pattern.compile("maven-\\d+\\.\\d+\\.\\d+-uber\\.jar"); + for (File each : files) { + if (pattern.matcher(each.getName()).matches()) { + return each; + } + } + } + return null; + } + public interface MavenTaskHandler { void waitFor(); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/RepositoryAttachDialog.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/RepositoryAttachDialog.java index 91820747dfcb..4362c507b2db 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/RepositoryAttachDialog.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/RepositoryAttachDialog.java @@ -25,6 +25,7 @@ import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Disposer; +import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; @@ -41,9 +42,8 @@ import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.AsyncProcessIcon; import gnu.trove.THashMap; import org.jetbrains.annotations.NotNull; -import org.jetbrains.idea.maven.facade.nexus.ArtifactType; -import org.jetbrains.idea.maven.facade.nexus.RepositoryType; -import org.jetbrains.idea.maven.facade.remote.MavenFacade; +import org.jetbrains.idea.maven.model.MavenArtifactInfo; +import org.jetbrains.idea.maven.model.MavenRepositoryInfo; import javax.swing.*; import javax.swing.event.DocumentEvent; @@ -63,8 +63,9 @@ public class RepositoryAttachDialog extends DialogWrapper { private final Project myProject; private final boolean myManaged; private final AsyncProcessIcon myProgressIcon; - private final THashMap myCoordinates = new THashMap(); - private final Map myRepositories = new TreeMap(); + private final THashMap> myCoordinates + = new THashMap>(); + private final Map myRepositories = new TreeMap(); private final ArrayList myShownItems = new ArrayList(); private final JComboBox myCombobox = new JComboBox(new CollectionComboBoxModel(myShownItems, null)); @@ -171,15 +172,16 @@ public class RepositoryAttachDialog extends DialogWrapper { if (myProgressIcon.isVisible()) return false; myProgressIcon.setVisible(true); myProgressIcon.resume(); - RepositoryAttachHandler.searchArtifacts(myProject, text, new PairProcessor, Boolean>() { - public boolean process(Collection artifactTypes, Boolean tooMany) { + RepositoryAttachHandler.searchArtifacts(myProject, text, new PairProcessor>, Boolean>() { + public boolean process(Collection> artifacts, Boolean tooMany) { if (myProgressIcon.isDisposed()) return true; myProgressIcon.suspend(); myProgressIcon.setVisible(false); final int prevSize = myCoordinates.size(); - for (ArtifactType artifactType : artifactTypes) { - myCoordinates.put(artifactType.getGroupId() + ":" + artifactType.getArtifactId() + ":" + artifactType.getVersion(), artifactType); + for (Pair each : artifacts) { + myCoordinates.put(each.first.getGroupId() + ":" + each.first.getArtifactId() + ":" + each.first.getVersion(), each); } + myRepositoryUrl.setModel(new CollectionComboBoxModel(new ArrayList(myRepositories.keySet()), myRepositoryUrl.getEditor().getItem())); if (Boolean.TRUE.equals(tooMany)) { final Point point = new Point(myCombobox.getWidth() / 2, 0); @@ -190,13 +192,11 @@ public class RepositoryAttachDialog extends DialogWrapper { updateComboboxSelection(prevSize != myCoordinates.size()); return true; } - }, new Processor>() { - public boolean process(Collection repositoryTypes) { - for (RepositoryType repositoryType : repositoryTypes) { - if (!myRepositories.containsKey(repositoryType.getContentResourceURI())) { - myRepositories.put( - repositoryType.getContentResourceURI(), - new MavenFacade.Repository(repositoryType.getId(), repositoryType.getContentResourceURI(), "default")); + }, new Processor>() { + public boolean process(Collection repos) { + for (MavenRepositoryInfo each : repos) { + if (!myRepositories.containsKey(each.getUrl())) { + myRepositories.put(each.getUrl(), each); } } return true; @@ -274,7 +274,7 @@ public class RepositoryAttachDialog extends DialogWrapper { final LabeledComponent repository = new LabeledComponent(); repository.getLabel().setText("Repository URL to Download From:"); myRepositories.put(DEFAULT_REPOSITORY, null); - for (MavenFacade.Repository repo : RepositoryAttachHandler.getDefaultRepositories()) { + for (MavenRepositoryInfo repo : RepositoryAttachHandler.getDefaultRepositories()) { myRepositories.put(repo.getUrl(), repo); } myRepositoryUrl = new JComboBox(new CollectionComboBoxModel(new ArrayList(myRepositories.keySet()), DEFAULT_REPOSITORY)); @@ -324,15 +324,14 @@ public class RepositoryAttachDialog extends DialogWrapper { } @NotNull - public List getRepositories() { + public List getRepositories() { final String selectedRepository = (String)myRepositoryUrl.getEditor().getItem(); if (StringUtil.isNotEmpty(selectedRepository) && !DEFAULT_REPOSITORY.equals(selectedRepository) && !myRepositories.containsKey(selectedRepository)) { - return Collections.singletonList(new MavenFacade.Repository("custom", selectedRepository, "default")); + return Collections.singletonList(new MavenRepositoryInfo("custom", null, selectedRepository)); } else { - final ArtifactType artifact = myCoordinates.get(getCoordinateText()); - final MavenFacade.Repository repository = - artifact != null && artifact.getResourceUri() != null ? myRepositories.get(artifact.getResourceUri()) : null; + final Pair artifactAndRepo = myCoordinates.get(getCoordinateText()); + final MavenRepositoryInfo repository = artifactAndRepo.second; return repository != null? Collections.singletonList(repository) : ContainerUtil.findAll(myRepositories.values(), Condition.NOT_NULL); } } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/RepositoryAttachHandler.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/RepositoryAttachHandler.java index fd8d0c66bacb..8b1dd138cff9 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/RepositoryAttachHandler.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/RepositoryAttachHandler.java @@ -21,7 +21,6 @@ import com.intellij.notification.NotificationType; import com.intellij.notification.Notifications; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; -import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.PerformInBackgroundOption; import com.intellij.openapi.progress.ProgressIndicator; @@ -33,33 +32,30 @@ import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.roots.ui.configuration.libraryEditor.LibraryTableAttachHandler; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; -import com.intellij.openapi.util.ActionCallback; -import com.intellij.openapi.util.NullableComputable; -import com.intellij.openapi.util.Ref; +import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.util.PairProcessor; import com.intellij.util.Processor; +import com.intellij.util.SmartList; +import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.idea.maven.dom.converters.repositories.MavenRepositoriesProvider; -import org.jetbrains.idea.maven.facade.nexus.ArtifactType; -import org.jetbrains.idea.maven.facade.nexus.RepositoryType; -import org.jetbrains.idea.maven.facade.remote.MavenFacade; -import org.jetbrains.idea.maven.facade.remote.MavenFacadeManager; -import org.jetbrains.idea.maven.facade.remote.RemoteTransferListener; -import org.jetbrains.idea.maven.facade.remote.impl.RemoteTransferListenerImpl; -import org.jetbrains.idea.maven.project.MavenGeneralSettings; +import org.jetbrains.idea.maven.execution.SoutMavenConsole; +import org.jetbrains.idea.maven.facade.MavenEmbedderWrapper; +import org.jetbrains.idea.maven.facade.MavenFacadeManager; +import org.jetbrains.idea.maven.model.MavenArtifact; +import org.jetbrains.idea.maven.model.MavenArtifactInfo; +import org.jetbrains.idea.maven.model.MavenRemoteRepository; +import org.jetbrains.idea.maven.model.MavenRepositoryInfo; +import org.jetbrains.idea.maven.project.MavenEmbeddersManager; import org.jetbrains.idea.maven.project.MavenProjectsManager; import javax.swing.*; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; -import java.net.URL; -import java.rmi.server.UnicastRemoteObject; import java.util.*; -import java.util.concurrent.ConcurrentHashMap; /** * @author Gregory.Shrago @@ -88,31 +84,31 @@ public class RepositoryAttachHandler implements LibraryTableAttachHandler { final ActionCallback callback = new ActionCallback(); final String copyTo = dialog.getDirectoryPath(); final String coord = dialog.getCoordinateText(); - resolveLibrary(project, Collections.singleton(coord), dialog.getRepositories(), false, new Processor>>() { - public boolean process(final Map> stringListMap) { - final List result = stringListMap.get(coord); + resolveLibrary(project, coord, dialog.getRepositories(), false, new Processor>() { + public boolean process(final List artifacts) { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { final Library.ModifiableModel modifiableModel = modelProvider.compute(); - if (modifiableModel == null || result == null) { + if (modifiableModel == null) { callback.setRejected(); } else { - replaceLibraryData(project, modifiableModel, result, copyTo); + replaceLibraryData(project, modifiableModel, artifacts, copyTo); callback.setDone(); } } }); - final boolean nothingRetrieved = result == null || result.isEmpty(); + final boolean nothingRetrieved = artifacts.isEmpty(); final StringBuilder sb = new StringBuilder(); - if (nothingRetrieved) sb.append("No files were downloaded for ").append(coord); + if (nothingRetrieved) { + sb.append("No files were downloaded for ").append(coord); + } else { sb.append("The following files were downloaded:
"); sb.append("
    "); - for (ArtifactType artifactType : result) { + for (MavenArtifact each : artifacts) { sb.append("
  1. "); - final String file = artifactType.getResourceUri(); - sb.append(file.substring(file.lastIndexOf('/') + 1)); + sb.append(each.getFile().getName()); sb.append("
  2. "); } sb.append("
"); @@ -123,7 +119,8 @@ public class RepositoryAttachHandler implements LibraryTableAttachHandler { } else { Notifications.Bus.notify(new Notification("Repository", sb.toString(), title, - nothingRetrieved? NotificationType.WARNING : NotificationType.INFORMATION), NotificationDisplayType.STICKY_BALLOON, project); + nothingRetrieved ? NotificationType.WARNING : NotificationType.INFORMATION), + NotificationDisplayType.STICKY_BALLOON, project); } return true; } @@ -140,11 +137,11 @@ public class RepositoryAttachHandler implements LibraryTableAttachHandler { public ActionCallback refreshLibrary(final Project project, final Library.ModifiableModel library) { final ActionCallback result = new ActionCallback(); final String coord = getMavenCoordinate(library.getName()); - resolveLibrary(project, Collections.singleton(coord), getDefaultRepositories(), true, new Processor>>() { - public boolean process(final Map> artifactTypes) { + resolveLibrary(project, coord, getDefaultRepositories(), true, new Processor>() { + public boolean process(final List artifacts) { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { - replaceLibraryData(project, library, artifactTypes.get(coord), null); + replaceLibraryData(project, library, artifacts, null); result.setDone(); } }); @@ -156,9 +153,9 @@ public class RepositoryAttachHandler implements LibraryTableAttachHandler { private static void replaceLibraryData(Project project, Library.ModifiableModel library, - Collection artifactTypes, + Collection artifacts, String copyTo) { - final String repoUrl = VfsUtil.pathToUrl(MavenProjectsManager.getInstance(project).getGeneralSettings().getEffectiveLocalRepository().getPath()); + final String repoUrl = getLocalRepositoryUrl(project); for (OrderRootType type : OrderRootType.getAllTypes()) { for (String url : library.getUrls(type)) { if (url.startsWith(repoUrl)) { @@ -166,20 +163,18 @@ public class RepositoryAttachHandler implements LibraryTableAttachHandler { } } } - for (ArtifactType type : artifactTypes) { + for (MavenArtifact each : artifacts) { try { - final String url = VfsUtil.convertFromUrl(new URL(type.getResourceUri())); - final String targetUrl; + File repoFile = each.getFile(); + File toFile = repoFile; if (copyTo != null) { - final File repoFile = new File(FileUtil.toSystemDependentName(VfsUtil.urlToPath(url))); - final File toFile = new File(copyTo, repoFile.getName()); + toFile = new File(copyTo, repoFile.getName()); if (repoFile.exists()) { FileUtil.copy(repoFile, toFile); } - targetUrl = VfsUtil.pathToUrl(FileUtil.toSystemIndependentName(toFile.getPath())); } - else targetUrl = url; - library.addRoot(targetUrl, OrderRootType.CLASSES); + String url = VfsUtil.pathToUrl(FileUtil.toSystemIndependentName(toFile.getPath())); + library.addRoot(url, OrderRootType.CLASSES); } catch (MalformedURLException e) { LOG.warn(e); @@ -190,45 +185,52 @@ public class RepositoryAttachHandler implements LibraryTableAttachHandler { } } - public static void searchArtifacts(final Project project, String coord, final PairProcessor, Boolean> resultProcessor, final Processor> repoProcessor) { + private static String getLocalRepositoryUrl(Project project) { + File file = MavenProjectsManager.getInstance(project).getGeneralSettings().getEffectiveLocalRepository(); + return VfsUtil.pathToUrl(FileUtil.toSystemIndependentName(file.getPath())); + } + + public static void searchArtifacts(final Project project, String coord, + final PairProcessor>, Boolean> resultProcessor, + final Processor> repoProcessor) { if (coord == null) return; - final ArtifactType template = createTemplate(coord); + final MavenArtifactInfo template = createTemplate(coord, null); ProgressManager.getInstance().run(new Task.Backgroundable(project, "Maven", false) { public void run(@NotNull ProgressIndicator indicator) { - final MavenFacadeManager mavenManager = ServiceManager.getService(project, MavenFacadeManager.class); - final Ref> result = Ref.create(Collections.emptyList()); - final Ref> result2 = Ref.create(Collections.emptyList()); + final Ref>> result + = Ref.create(Collections.>emptyList()); + final Ref> result2 = Ref.create(Collections.emptyList()); final Ref tooManyRef = Ref.create(Boolean.FALSE); try { - final MavenFacade mavenFacade = mavenManager.getMavenFacade(project); + MavenFacadeManager facade = MavenFacadeManager.getInstance(); + final String[] nexusUrls = getDefaultNexusUrls(); - final List resultList = new ArrayList(); - final List result2List = new ArrayList(); + final List> resultList + = new ArrayList>(); + final List result2List = new ArrayList(); for (String nexusUrl : nexusUrls) { - final List artifacts; + final List artifacts; try { - artifacts = mavenFacade.findArtifacts(template, nexusUrl); + artifacts = facade.findArtifacts(template, nexusUrl); } catch (Exception ex) { - LOG.warn("Accessing Nexus at: "+nexusUrl, ex); + LOG.warn("Accessing Nexus at: " + nexusUrl, ex); continue; } if (artifacts == null) { tooManyRef.set(Boolean.TRUE); } else if (!artifacts.isEmpty()) { - final List repositories = mavenFacade.getRepositories(nexusUrl); - final HashMap map = new HashMap(); - for (RepositoryType repository : repositories) { + final List repositories = facade.getRepositories(nexusUrl); + final HashMap map = new HashMap(); + for (MavenRepositoryInfo repository : repositories) { map.put(repository.getId(), repository); } result2List.addAll(repositories); - for (ArtifactType artifact : artifacts) { - final RepositoryType repoType = map.get(artifact.getRepoId()); - artifact.setResourceUri(repoType == null? null: repoType.getContentResourceURI()); + for (MavenArtifactInfo artifact : artifacts) { + resultList.add(Pair.create(artifact, map.get(artifact.getRepositoryId()))); } - resultList.addAll(artifacts); } } result.set(resultList); @@ -249,20 +251,19 @@ public class RepositoryAttachHandler implements LibraryTableAttachHandler { }); } - public static void searchRepositories(final Project project, final Processor> resultProcessor) { + public static void searchRepositories(final Project project, final Processor> resultProcessor) { ProgressManager.getInstance().run(new Task.Backgroundable(project, "Maven", false) { public void run(@NotNull ProgressIndicator indicator) { - final MavenFacadeManager mavenManager = ServiceManager.getService(project, MavenFacadeManager.class); - final Ref> result = Ref.create(Collections.emptyList()); + final Ref> result = Ref.create(Collections.emptyList()); try { final String[] nexusUrls = getDefaultNexusUrls(); - final MavenFacade mavenFacade = mavenManager.getMavenFacade(project); - final ArrayList repoList = new ArrayList(); + final MavenFacadeManager manager = MavenFacadeManager.getInstance(); + final ArrayList repoList = new ArrayList(); for (String nexusUrl : nexusUrls) { - final List repositories; + final List repositories; try { - repositories = mavenFacade.getRepositories(nexusUrl); + repositories = manager.getRepositories(nexusUrl); } catch (Exception ex) { LOG.warn("Accessing Nexus at: " + nexusUrl, ex); @@ -286,38 +287,18 @@ public class RepositoryAttachHandler implements LibraryTableAttachHandler { }); } - private static String[] getDefaultNexusUrls() { - return new String[] { - "http://oss.sonatype.org/service/local/", - "http://repository.sonatype.org/service/local/", - //"http://maven.labs.intellij.net:8081/nexus/service/local/" - }; - } - - public static List getDefaultRepositories() { - final List list = new ArrayList(); - final Set visited = new HashSet(); - final MavenRepositoriesProvider provider = MavenRepositoriesProvider.getInstance(); - for (String id : provider.getRepositoryIds()) { - final String url = provider.getRepositoryUrl(id); - if (!visited.add(url)) continue; - list.add(new MavenFacade.Repository(id, url, StringUtil.notNullize(provider.getRepositoryLayout(id), "default"))); - } - return list; - } - - private static ArtifactType createTemplate(String coord) { - final ArtifactType template = new ArtifactType(); + private static MavenArtifactInfo createTemplate(String coord, String packaging) { final String[] parts = coord.split(":"); if (parts.length == 1 && parts[0].length() > 0 && Character.isUpperCase(parts[0].charAt(0))) { - template.setContextId(parts[0]); + return new MavenArtifactInfo(null, null, null, packaging, null, parts[0], null); } else { - template.setGroupId(parts.length > 0 ? parts[0] : null); - template.setArtifactId(parts.length > 1 ? parts[1] : null); - template.setVersion(parts.length > 2 ? parts[2] : null); + return new MavenArtifactInfo(parts.length > 0 ? parts[0] : null, + parts.length > 1 ? parts[1] : null, + parts.length > 2 ? parts[2] : null, + packaging, + null); } - return template; } private static void handleError(String message, Exception e) { @@ -325,61 +306,58 @@ public class RepositoryAttachHandler implements LibraryTableAttachHandler { } public static void resolveLibrary(final Project project, - Collection libNames, - final Collection repositories, boolean modal, - final Processor>> resultProcessor) { - if (libNames.isEmpty()) return; - final ArrayList parameters = new ArrayList(); - for (String s : libNames) { - final ArtifactType template = createTemplate(s); - template.setPackaging("jar"); - parameters.add(template); + final String libName, + final Collection repositories, + boolean modal, + final Processor> resultProcessor) { + Task task; + if (modal) { + task = new Task.Modal(project, "Maven", false) { + public void run(@NotNull ProgressIndicator indicator) { + doResolveInner(project, createTemplate(libName, "jar"), repositories, resultProcessor, indicator); + } + }; } - ProgressManager.getInstance().run(modal ? new Task.Modal(project, "Maven", false) { + else { + task = new Task.Backgroundable(project, "Maven", false, PerformInBackgroundOption.DEAF) { + public void run(@NotNull ProgressIndicator indicator) { + doResolveInner(project, createTemplate(libName, "jar"), repositories, resultProcessor, indicator); + } - public void run(@NotNull ProgressIndicator indicator) { - doResolveInner(project, parameters, repositories, resultProcessor, indicator); - } - } : new Task.Backgroundable(project, "Maven", false, PerformInBackgroundOption.DEAF) { - - public void run(@NotNull ProgressIndicator indicator) { - doResolveInner(project, parameters, repositories, resultProcessor, indicator); - } + @Override + public boolean shouldStartInBackground() { + return false; + } + }; + } - @Override - public boolean shouldStartInBackground() { - return false; - } - }); + ProgressManager.getInstance().run(task); } private static void doResolveInner(Project project, - final ArrayList artifacts, - Collection repositories, - final Processor>> resultProcessor, + MavenArtifactInfo artifact, + Collection repositories, + final Processor> resultProcessor, ProgressIndicator indicator) { - final Ref>> result = Ref.create(Collections.>emptyMap()); - final MavenFacadeManager mavenManager = ServiceManager.getService(project, MavenFacadeManager.class); + final Ref> result = new Ref>(); + + MavenEmbeddersManager manager = MavenProjectsManager.getInstance(project).getEmbeddersManager(); + MavenEmbedderWrapper embedder = manager.getEmbedder(MavenEmbeddersManager.FOR_DOWNLOAD); try { - final MavenFacade mavenFacade = mavenManager.getMavenFacade(project); - final MavenFacade.MavenFacadeSettings settings = createMavenFacadeSettings(project); - settings.getRemoteRepositories().addAll(repositories); - mavenFacade.setMavenSettings(settings); - final RemoteTransferListener transferListener = fromProgressIndicator(indicator); - UnicastRemoteObject.exportObject(transferListener, 0); - mavenFacade.setTransferListener(transferListener); - try { - result.set(mavenFacade.resolveDependencies(artifacts)); - } - finally { - UnicastRemoteObject.unexportObject(transferListener, true); - mavenFacade.setTransferListener(null); - } + embedder.customizeForResolve(new SoutMavenConsole(), new MavenProgressIndicator(indicator)); + List resolved = embedder.resolveTransitively(Collections.singletonList(artifact), + convertRepositories(repositories)); + result.set(ContainerUtil.findAll(resolved, new Condition() { + public boolean value(MavenArtifact mavenArtifact) { + return mavenArtifact.isResolved(); + } + })); } - catch (Exception e) { - handleError("Error resolving: " + artifacts, e); + catch (MavenProcessCanceledException e) { + return; } finally { + manager.release(embedder); ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { resultProcessor.process(result.get()); @@ -388,6 +366,34 @@ public class RepositoryAttachHandler implements LibraryTableAttachHandler { } } + private static List convertRepositories(Collection infos) { + List result = new ArrayList(infos.size()); + for (MavenRepositoryInfo each : infos) { + result.add(new MavenRemoteRepository(each.getId(), each.getName(), each.getUrl(), null, null, null)); + } + return result; + } + + private static String[] getDefaultNexusUrls() { + return new String[]{ + "http://oss.sonatype.org/service/local/", + "http://repository.sonatype.org/service/local/", + //"http://maven.labs.intellij.net:8081/nexus/service/local/" + }; + } + + public static List getDefaultRepositories() { + List result = new SmartList(); + final MavenRepositoriesProvider provider = MavenRepositoriesProvider.getInstance(); + for (String id : provider.getRepositoryIds()) { + final String url = provider.getRepositoryUrl(id); + if (url != null) { + result.add(new MavenRepositoryInfo(id, provider.getRepositoryName(id), url)); + } + } + return result; + } + //public static void registerLibraryWatcher(final Project project) { // final Alarm alarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD, project); // final Runnable syncRunnable = new Runnable() { @@ -458,7 +464,7 @@ public class RepositoryAttachHandler implements LibraryTableAttachHandler { // syncRunnable.run(); //} - private void refreshLibraries(final Project project, final Map> map) { + private void refreshLibraries(final Project project, final Map> map) { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { for (Library library : map.keySet()) { @@ -470,102 +476,96 @@ public class RepositoryAttachHandler implements LibraryTableAttachHandler { }); } - private static MavenFacade.MavenFacadeSettings createMavenFacadeSettings(Project project) { - final MavenFacade.MavenFacadeSettings settings = new MavenFacade.MavenFacadeSettings(); - final MavenGeneralSettings generalSettings = MavenProjectsManager.getInstance(project).getGeneralSettings(); - settings.setLocalRepository(new MavenFacade.Repository("local", VfsUtil.pathToUrl(generalSettings.getEffectiveLocalRepository().getPath()), "default")); - return settings; - } - - public static RemoteTransferListener fromProgressIndicator(final ProgressIndicator indicator) { - return new RemoteTransferListenerImpl() { - - final Map myDownloads = new ConcurrentHashMap(); - @Override - public void transferInitiated(TransferEvent transferEvent) { - final String message = transferEvent.getRequestType() == TransferEvent.RequestType.PUT ? "Uploading" : "Downloading"; - final String url = transferEvent.getRepositoryUrl(); - indicator.setText(message + ": " + url + "/" + transferEvent.getResource().getResourceName()); - } - - @Override - public void transferStarted(TransferEvent transferEvent) { - // nothing - } - - @Override - public void transferProgress(TransferEvent transferEvent, int length) { - final Resource resource = transferEvent.getResource(); - final long curComplete; - if (!myDownloads.containsKey(resource)) { - curComplete = length; - } - else { - final long complete = myDownloads.get(resource).longValue(); - curComplete = complete + length; - } - myDownloads.put(resource, new Long(curComplete)); - - long curTotal = 0; - long curProgress = 0; - boolean unknown = false; - for (Resource res : myDownloads.keySet()) { - final long total = res.getResourceContentLength(); - final long complete = myDownloads.get(res).longValue(); - if (total == -1) unknown = true; - else curTotal += total; - curProgress += complete; - } - - final StringBuilder sb = new StringBuilder(); - if (curTotal >= 1024) { - sb.append((curProgress / 1024) + "/" + (curTotal == -1 ? "?" : (curTotal / 1024) + "K")); - } - else { - sb.append(curProgress + "/" + (curTotal == -1 ? "?" : curTotal + "b")); - } - if (unknown) { - indicator.setIndeterminate(true); - } - else { - indicator.setIndeterminate(false); - indicator.setFraction((double)curProgress / curTotal); - } - indicator.setText(sb.toString()); - indicator.setText2(transferEvent.getResource().getResourceName()); - } - - @Override - public void transferCompleted(TransferEvent transferEvent) { - transferProgress(transferEvent, 0); - if (true) return; - final StringBuilder sb = new StringBuilder(); - final long contentLength = transferEvent.getResource().getResourceContentLength(); - if (contentLength != -1) { - String type = - (transferEvent.getRequestType() == TransferEvent.RequestType.PUT ? "uploaded" : "downloaded"); - sb.append(contentLength >= 1024 ? (contentLength / 1024) + "K" : contentLength + "b"); - String name = transferEvent.getResource().getResourceName(); - name = name.substring(name.lastIndexOf('/') + 1, name.length()); - sb.append(" "); - sb.append(type); - sb.append(" ("); - sb.append(name); - sb.append(")"); - } - indicator.setText(sb.toString()); - //myDownloads.remove(transferEvent.getResource()); - } - - @Override - public void transferError(TransferEvent transferEvent) { - indicator.setText2(transferEvent.getException().getMessage()); - } - - @Override - public void debug(String s) { - indicator.setText2(s); - } - }; - } + // todo + //public static RemoteTransferListener fromProgressIndicator(final ProgressIndicator indicator) { + // return new RemoteTransferListenerImpl() { + // + // final Map myDownloads = new ConcurrentHashMap(); + // @Override + // public void transferInitiated(TransferEvent transferEvent) { + // final String message = transferEvent.getRequestType() == TransferEvent.RequestType.PUT ? "Uploading" : "Downloading"; + // final String url = transferEvent.getRepositoryUrl(); + // indicator.setText(message + ": " + url + "/" + transferEvent.getResource().getResourceName()); + // } + // + // @Override + // public void transferStarted(TransferEvent transferEvent) { + // // nothing + // } + // + // @Override + // public void transferProgress(TransferEvent transferEvent, int length) { + // final Resource resource = transferEvent.getResource(); + // final long curComplete; + // if (!myDownloads.containsKey(resource)) { + // curComplete = length; + // } + // else { + // final long complete = myDownloads.get(resource).longValue(); + // curComplete = complete + length; + // } + // myDownloads.put(resource, new Long(curComplete)); + // + // long curTotal = 0; + // long curProgress = 0; + // boolean unknown = false; + // for (Resource res : myDownloads.keySet()) { + // final long total = res.getResourceContentLength(); + // final long complete = myDownloads.get(res).longValue(); + // if (total == -1) unknown = true; + // else curTotal += total; + // curProgress += complete; + // } + // + // final StringBuilder sb = new StringBuilder(); + // if (curTotal >= 1024) { + // sb.append((curProgress / 1024) + "/" + (curTotal == -1 ? "?" : (curTotal / 1024) + "K")); + // } + // else { + // sb.append(curProgress + "/" + (curTotal == -1 ? "?" : curTotal + "b")); + // } + // if (unknown) { + // indicator.setIndeterminate(true); + // } + // else { + // indicator.setIndeterminate(false); + // indicator.setFraction((double)curProgress / curTotal); + // } + // indicator.setText(sb.toString()); + // indicator.setText2(transferEvent.getResource().getResourceName()); + // } + // + // @Override + // public void transferCompleted(TransferEvent transferEvent) { + // transferProgress(transferEvent, 0); + // if (true) return; + // final StringBuilder sb = new StringBuilder(); + // final long contentLength = transferEvent.getResource().getResourceContentLength(); + // if (contentLength != -1) { + // String type = + // (transferEvent.getRequestType() == TransferEvent.RequestType.PUT ? "uploaded" : "downloaded"); + // sb.append(contentLength >= 1024 ? (contentLength / 1024) + "K" : contentLength + "b"); + // String name = transferEvent.getResource().getResourceName(); + // name = name.substring(name.lastIndexOf('/') + 1, name.length()); + // sb.append(" "); + // sb.append(type); + // sb.append(" ("); + // sb.append(name); + // sb.append(")"); + // } + // indicator.setText(sb.toString()); + // //myDownloads.remove(transferEvent.getResource()); + // } + // + // @Override + // public void transferError(TransferEvent transferEvent) { + // indicator.setText2(transferEvent.getException().getMessage()); + // } + // + // @Override + // public void debug(String s) { + // indicator.setText2(s); + // } + // }; + //} } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/actions/MavenActionUtil.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/actions/MavenActionUtil.java index 1e41626f63a0..7a9557ff4d65 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/actions/MavenActionUtil.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/actions/MavenActionUtil.java @@ -24,7 +24,7 @@ import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.project.MavenProjectsManager; -import org.jetbrains.idea.maven.utils.MavenConstants; +import org.jetbrains.idea.maven.model.MavenConstants; import org.jetbrains.idea.maven.utils.MavenUtil; import java.util.*; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenAddArchetypeDialog.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenAddArchetypeDialog.java index 671eb6d3493c..128c4f078846 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenAddArchetypeDialog.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenAddArchetypeDialog.java @@ -18,7 +18,7 @@ package org.jetbrains.idea.maven.wizards; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.DocumentAdapter; -import org.jetbrains.idea.maven.indices.ArchetypeInfo; +import org.jetbrains.idea.maven.model.MavenArchetype; import javax.swing.*; import javax.swing.event.DocumentEvent; @@ -80,8 +80,8 @@ public class MavenAddArchetypeDialog extends DialogWrapper { getRootPane().revalidate(); } - public ArchetypeInfo getArchetype() { - return new ArchetypeInfo(myGroupIdField.getText(), + public MavenArchetype getArchetype() { + return new MavenArchetype(myGroupIdField.getText(), myArtifactIdField.getText(), myVersionField.getText(), myRepositoryField.getText(), diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenFrameworkSupportProvider.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenFrameworkSupportProvider.java index 8425493a4826..c02460547a75 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenFrameworkSupportProvider.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenFrameworkSupportProvider.java @@ -27,9 +27,9 @@ import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.idea.maven.project.MavenId; +import org.jetbrains.idea.maven.model.MavenId; import org.jetbrains.idea.maven.project.MavenProjectsManager; -import org.jetbrains.idea.maven.utils.MavenConstants; +import org.jetbrains.idea.maven.model.MavenConstants; import org.jetbrains.idea.maven.utils.MavenIcons; import javax.swing.*; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenModuleBuilder.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenModuleBuilder.java index 7e360866bf68..14c53b6175ef 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenModuleBuilder.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenModuleBuilder.java @@ -31,8 +31,8 @@ import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; -import org.jetbrains.idea.maven.indices.ArchetypeInfo; -import org.jetbrains.idea.maven.project.MavenId; +import org.jetbrains.idea.maven.model.MavenArchetype; +import org.jetbrains.idea.maven.model.MavenId; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.project.MavenProjectsManager; import org.jetbrains.idea.maven.utils.MavenUtil; @@ -54,7 +54,7 @@ public class MavenModuleBuilder extends ModuleBuilder implements SourcePathsBuil private boolean myInheritVersion; private MavenId myProjectId; - private ArchetypeInfo myArchetype; + private MavenArchetype myArchetype; public void setupRootModel(ModifiableRootModel rootModel) throws ConfigurationException { final Project project = rootModel.getProject(); @@ -173,11 +173,11 @@ public class MavenModuleBuilder extends ModuleBuilder implements SourcePathsBuil return myProjectId; } - public void setArchetype(ArchetypeInfo archetype) { + public void setArchetype(MavenArchetype archetype) { myArchetype = archetype; } - public ArchetypeInfo getArchetype() { + public MavenArchetype getArchetype() { return myArchetype; } } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenModuleBuilderHelper.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenModuleBuilderHelper.java index 0d49b15e446a..4493fb80522b 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenModuleBuilderHelper.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenModuleBuilderHelper.java @@ -34,11 +34,11 @@ import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; import org.jetbrains.idea.maven.execution.MavenRunner; import org.jetbrains.idea.maven.execution.MavenRunnerParameters; import org.jetbrains.idea.maven.execution.MavenRunnerSettings; -import org.jetbrains.idea.maven.indices.ArchetypeInfo; -import org.jetbrains.idea.maven.project.MavenId; +import org.jetbrains.idea.maven.model.MavenArchetype; +import org.jetbrains.idea.maven.model.MavenConstants; +import org.jetbrains.idea.maven.model.MavenId; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.project.MavenProjectsManager; -import org.jetbrains.idea.maven.utils.MavenConstants; import org.jetbrains.idea.maven.utils.MavenLog; import org.jetbrains.idea.maven.utils.MavenUtil; @@ -56,7 +56,7 @@ public class MavenModuleBuilderHelper { private final boolean myInheritGroupId; private final boolean myInheritVersion; - private final ArchetypeInfo myArchetype; + private final MavenArchetype myArchetype; private final String myCommandName; @@ -65,7 +65,7 @@ public class MavenModuleBuilderHelper { MavenProject parentProject, boolean inheritGroupId, boolean inheritVersion, - ArchetypeInfo archetype, + MavenArchetype archetype, String commaneName) { myProjectId = projectId; myAggregatorProject = aggregatorProject; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenModuleWizardStep.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenModuleWizardStep.java index c0c4f1c5eceb..7ea7c3e6546d 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenModuleWizardStep.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenModuleWizardStep.java @@ -18,7 +18,6 @@ package org.jetbrains.idea.maven.wizards; import com.intellij.ide.util.PropertiesComponent; import com.intellij.ide.util.projectWizard.ModuleWizardStep; import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.text.StringUtil; @@ -30,13 +29,12 @@ import com.intellij.util.ui.AsyncProcessIcon; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.tree.TreeUtil; import org.jetbrains.annotations.Nullable; -import org.jetbrains.idea.maven.indices.ArchetypeInfo; +import org.jetbrains.idea.maven.model.MavenArchetype; import org.jetbrains.idea.maven.indices.MavenIndicesManager; import org.jetbrains.idea.maven.navigator.SelectMavenProjectDialog; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.project.MavenProjectsManager; -import org.jetbrains.idea.maven.project.MavenId; -import org.jetbrains.idea.maven.utils.MavenUtil; +import org.jetbrains.idea.maven.model.MavenId; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; @@ -156,7 +154,7 @@ public class MavenModuleWizardStep extends ModuleWizardStep { new TreeSpeedSearch(myArchetypesTree, new Convertor() { public String convert(TreePath path) { - ArchetypeInfo info = getArchetypeInfoFromPathComponent(path.getLastPathComponent()); + MavenArchetype info = getArchetypeInfoFromPathComponent(path.getLastPathComponent()); return info.groupId + ":" + info.artifactId + ":" + info.version; } }).setComparator(new SpeedSearchBase.SpeedSearchComparator(false) { @@ -194,7 +192,7 @@ public class MavenModuleWizardStep extends ModuleWizardStep { dialog.show(); if (!dialog.isOK()) return; - ArchetypeInfo archetype = dialog.getArchetype(); + MavenArchetype archetype = dialog.getArchetype(); MavenIndicesManager.getInstance().addArchetype(archetype); updateArchetypesList(archetype); } @@ -222,7 +220,7 @@ public class MavenModuleWizardStep extends ModuleWizardStep { myBuilder.setArchetype(null); } else { - myBuilder.setArchetype(new ArchetypeInfo(archGroupId, archArtifactId, archVersion, null, null)); + myBuilder.setArchetype(new MavenArchetype(archGroupId, archArtifactId, archVersion, null, null)); } } @@ -230,7 +228,7 @@ public class MavenModuleWizardStep extends ModuleWizardStep { saveValue(INHERIT_GROUP_ID_KEY, myInheritGroupIdCheckBox.isSelected()); saveValue(INHERIT_VERSION_KEY, myInheritVersionCheckBox.isSelected()); - ArchetypeInfo arch = getSelectedArchetype(); + MavenArchetype arch = getSelectedArchetype(); saveValue(ARCHETYPE_GROUP_ID_KEY, arch == null ? null : arch.groupId); saveValue(ARCHETYPE_ARTIFACT_ID_KEY, arch == null ? null : arch.artifactId); saveValue(ARCHETYPE_VERSION_KEY, arch == null ? null : arch.version); @@ -273,7 +271,7 @@ public class MavenModuleWizardStep extends ModuleWizardStep { myInheritGroupIdCheckBox.setSelected(myBuilder.isInheritGroupId()); myInheritVersionCheckBox.setSelected(myBuilder.isInheritVersion()); - ArchetypeInfo selectedArch = getSelectedArchetype(); + MavenArchetype selectedArch = getSelectedArchetype(); if (selectedArch == null) { selectedArch = myBuilder.getArchetype(); } @@ -283,7 +281,7 @@ public class MavenModuleWizardStep extends ModuleWizardStep { updateComponents(); } - private void updateArchetypesList(final ArchetypeInfo selected) { + private void updateArchetypesList(final MavenArchetype selected) { myLoadingCancelled.set(true); myLoadingCancelled = new AtomicBoolean(); final AtomicBoolean currentStatus = myLoadingCancelled; @@ -298,7 +296,7 @@ public class MavenModuleWizardStep extends ModuleWizardStep { catch (InterruptedException e) { throw new RuntimeException(e); } - final Set archetypes = MavenIndicesManager.getInstance().getArchetypes(); + final Set archetypes = MavenIndicesManager.getInstance().getArchetypes(); SwingUtilities.invokeLater(new Runnable() { public void run() { @@ -325,7 +323,7 @@ public class MavenModuleWizardStep extends ModuleWizardStep { } private void updateArchetypeDescription() { - ArchetypeInfo sel = getSelectedArchetype(); + MavenArchetype sel = getSelectedArchetype(); String desc = sel == null ? null : sel.description; if (StringUtil.isEmptyOrSpaces(desc)) { myArchetypeDescriptionScrollPane.setVisible(false); @@ -336,7 +334,7 @@ public class MavenModuleWizardStep extends ModuleWizardStep { myMainPanel.revalidate(); } - private TreePath findNodePath(ArchetypeInfo object, TreeModel model, Object parent) { + private TreePath findNodePath(MavenArchetype object, TreeModel model, Object parent) { for (int i = 0; i < model.getChildCount(parent); i++) { DefaultMutableTreeNode each = (DefaultMutableTreeNode)model.getChild(parent, i); if (each.getUserObject().equals(object)) return new TreePath(each.getPath()); @@ -347,11 +345,11 @@ public class MavenModuleWizardStep extends ModuleWizardStep { return null; } - private TreeNode groupAndSortArchetypes(Set archetypes) { - List list = new ArrayList(archetypes); + private TreeNode groupAndSortArchetypes(Set archetypes) { + List list = new ArrayList(archetypes); - Collections.sort(list, new Comparator() { - public int compare(ArchetypeInfo o1, ArchetypeInfo o2) { + Collections.sort(list, new Comparator() { + public int compare(MavenArchetype o1, MavenArchetype o2) { String key1 = o1.groupId + ":" + o1.artifactId; String key2 = o2.groupId + ":" + o2.artifactId; @@ -362,23 +360,23 @@ public class MavenModuleWizardStep extends ModuleWizardStep { } }); - Map> map = new TreeMap>(); + Map> map = new TreeMap>(); - for (ArchetypeInfo each : list) { + for (MavenArchetype each : list) { String key = each.groupId + ":" + each.artifactId; - List versions = map.get(key); + List versions = map.get(key); if (versions == null) { - versions = new ArrayList(); + versions = new ArrayList(); map.put(key, versions); } versions.add(each); } DefaultMutableTreeNode result = new DefaultMutableTreeNode("root", true); - for (List each : map.values()) { - ArchetypeInfo eachArchetype = each.get(0); + for (List each : map.values()) { + MavenArchetype eachArchetype = each.get(0); DefaultMutableTreeNode node = new DefaultMutableTreeNode(eachArchetype, true); - for (ArchetypeInfo eachVersion : each) { + for (MavenArchetype eachVersion : each) { DefaultMutableTreeNode versionNode = new DefaultMutableTreeNode(eachVersion, false); node.add(versionNode); } @@ -455,13 +453,13 @@ public class MavenModuleWizardStep extends ModuleWizardStep { myBuilder.setArchetype(getSelectedArchetype()); } - private ArchetypeInfo getSelectedArchetype() { + private MavenArchetype getSelectedArchetype() { if (!myUseArchetypeCheckBox.isSelected() || myArchetypesTree.isSelectionEmpty()) return null; return getArchetypeInfoFromPathComponent(myArchetypesTree.getLastSelectedPathComponent()); } - private ArchetypeInfo getArchetypeInfoFromPathComponent(Object sel) { - return (ArchetypeInfo)((DefaultMutableTreeNode)sel).getUserObject(); + private MavenArchetype getArchetypeInfoFromPathComponent(Object sel) { + return (MavenArchetype)((DefaultMutableTreeNode)sel).getUserObject(); } @Override @@ -478,9 +476,9 @@ public class MavenModuleWizardStep extends ModuleWizardStep { int row, boolean hasFocus) { Object userObject = ((DefaultMutableTreeNode)value).getUserObject(); - if (!(userObject instanceof ArchetypeInfo)) return; + if (!(userObject instanceof MavenArchetype)) return; - ArchetypeInfo info = (ArchetypeInfo)userObject; + MavenArchetype info = (MavenArchetype)userObject; if (leaf) { append(info.artifactId, SimpleTextAttributes.GRAY_ATTRIBUTES); diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenProjectBuilder.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenProjectBuilder.java index 981e2f1b1e8c..4bf5503461f5 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenProjectBuilder.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenProjectBuilder.java @@ -31,6 +31,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.maven.importing.MavenDefaultModifiableModelsProvider; import org.jetbrains.idea.maven.importing.MavenUIModifiableModelsProvider; +import org.jetbrains.idea.maven.model.MavenId; import org.jetbrains.idea.maven.project.*; import org.jetbrains.idea.maven.utils.*; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenProjectOpenProcessor.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenProjectOpenProcessor.java index 1d0032c1a862..bff0d17a768b 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenProjectOpenProcessor.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenProjectOpenProcessor.java @@ -25,7 +25,7 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.projectImport.ProjectOpenProcessorBase; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.maven.project.MavenProject; -import org.jetbrains.idea.maven.utils.MavenConstants; +import org.jetbrains.idea.maven.model.MavenConstants; import java.util.ArrayList; import java.util.Arrays; diff --git a/plugins/maven/src/main/resources/IndicesBundle.properties b/plugins/maven/src/main/resources/IndicesBundle.properties index b239f68af9b7..a0e6b9e678b4 100644 --- a/plugins/maven/src/main/resources/IndicesBundle.properties +++ b/plugins/maven/src/main/resources/IndicesBundle.properties @@ -6,6 +6,5 @@ maven.index.updated.never=Never maven.index.updated.error=Error maven.indices.updating=Updating Maven Repository Indices... maven.indices.updating.index=Updating [{0}] {1} -maven.indices.updating.processing=Processing indices... repository.plugin.corrupt={0} not a Maven 2 plugin file repository.plugin.title=Opening Maven plugin file \ No newline at end of file diff --git a/plugins/maven/src/main/resources/META-INF/plugin.xml b/plugins/maven/src/main/resources/META-INF/plugin.xml index 7709f41d6afa..e5ee12fc523f 100644 --- a/plugins/maven/src/main/resources/META-INF/plugin.xml +++ b/plugins/maven/src/main/resources/META-INF/plugin.xml @@ -11,7 +11,7 @@ com.intellij.properties - org.intellij.groovy + org.intellij.groovy @@ -20,6 +20,9 @@ + + + @@ -70,17 +73,9 @@ - - - - - - - + + + @@ -103,9 +98,6 @@ - - org.jetbrains.idea.maven.indices.MavenIndicesManager - org.jetbrains.idea.maven.utils.MavenEnvironmentRegistrar @@ -399,10 +391,10 @@ + use-shortcut-of="IntroduceVariable"/> + class="org.jetbrains.idea.maven.dom.refactorings.extract.ExtractDependenciesAction"> diff --git a/plugins/maven/src/main/resources/ProjectBundle.properties b/plugins/maven/src/main/resources/ProjectBundle.properties index b1eb46f0898e..3a5fda1e6ab7 100644 --- a/plugins/maven/src/main/resources/ProjectBundle.properties +++ b/plugins/maven/src/main/resources/ProjectBundle.properties @@ -16,8 +16,6 @@ maven.downloading=Downloading Maven sources and documentation... maven.downloading.sources=Downloading Maven sources... maven.downloading.docs=Downloading Maven documentation... maven.downloading.finished=Finished downloading -maven.transfer.progress={0}/{1}K [{2}] {3} -maven.transfer.start=Checking [{0}] {1} maven.action.download.sources=Download Sources maven.action.download.sources.busy.text=Download sources... @@ -69,7 +67,6 @@ maven.ignore.edit=Edit Ignored Files... maven.profile.activate=Activate maven.profile.deactivate=Deactivate -maven.project.problem.syntaxError=''{0}'' has syntax errors maven.project.problem.recursiveInheritance=Recursive inheritance found maven.project.problem.selfInheritance=Self-inheritance found maven.project.problem.parentHasProblems=Parent ''{0}'' has problems diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenCustomRepositoryHelper.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenCustomRepositoryHelper.java similarity index 98% rename from plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenCustomRepositoryHelper.java rename to plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenCustomRepositoryHelper.java index 0c432d998727..191bbb1539fc 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenCustomRepositoryHelper.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenCustomRepositoryHelper.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.idea.maven.indices; +package org.jetbrains.idea.maven; import com.intellij.openapi.application.PluginPathManager; import com.intellij.openapi.util.io.FileUtil; diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenImportingTestCase.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenImportingTestCase.java index fda2567350e4..4d3b982135f4 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenImportingTestCase.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenImportingTestCase.java @@ -38,6 +38,7 @@ import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ArrayUtil; import com.intellij.util.PathUtil; +import org.jetbrains.idea.maven.model.MavenArtifact; import org.jetbrains.idea.maven.project.*; import org.jetbrains.idea.maven.execution.*; diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenTestCase.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenTestCase.java index 838e9ca5f258..6b05726cdc30 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenTestCase.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenTestCase.java @@ -33,7 +33,6 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.testFramework.UsefulTestCase; import com.intellij.testFramework.fixtures.IdeaProjectTestFixture; import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory; -import org.jetbrains.idea.maven.embedder.MavenConsole; import org.jetbrains.idea.maven.project.*; import org.jetbrains.idea.maven.utils.MavenProgressIndicator; @@ -202,7 +201,7 @@ public abstract class MavenTestCase extends UsefulTestCase { } protected void setRepositoryPath(String path) { - getMavenGeneralSettings().setLocalRepository(path); + getMavenGeneralSettings().setOverridenLocalRepository(path); } protected String getProjectPath() { diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/NullMavenConsole.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/NullMavenConsole.java index 1975b8da15b5..2bd3950452e8 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/NullMavenConsole.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/NullMavenConsole.java @@ -15,9 +15,9 @@ */ package org.jetbrains.idea.maven; -import org.jetbrains.idea.maven.embedder.MavenConsole; -import org.jetbrains.idea.maven.embedder.MavenExecutionOptions; import com.intellij.execution.process.ProcessHandler; +import org.jetbrains.idea.maven.execution.MavenExecutionOptions; +import org.jetbrains.idea.maven.project.MavenConsole; public class NullMavenConsole extends MavenConsole { public NullMavenConsole() { @@ -38,6 +38,6 @@ public class NullMavenConsole extends MavenConsole { public void attachToProcess(ProcessHandler processHandler) { } - protected void doPrint(String text, OutputType type) { + protected void doPrint(String text, MavenConsole.OutputType type) { } } diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/AddingDependencyTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/AddingDependencyTest.java index 9ca0a037b7cc..8e6a55766770 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/AddingDependencyTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/AddingDependencyTest.java @@ -16,10 +16,10 @@ package org.jetbrains.idea.maven.importing; import com.intellij.util.io.ReadOnlyAttributeUtil; +import org.jetbrains.idea.maven.MavenCustomRepositoryHelper; import org.jetbrains.idea.maven.MavenImportingTestCase; -import org.jetbrains.idea.maven.indices.MavenCustomRepositoryHelper; -import org.jetbrains.idea.maven.project.MavenArtifact; -import org.jetbrains.idea.maven.project.MavenId; +import org.jetbrains.idea.maven.model.MavenArtifact; +import org.jetbrains.idea.maven.model.MavenId; import java.io.File; import java.util.List; diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/ArtifactsDownloadingTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/ArtifactsDownloadingTest.java index f2bdd1982bf0..6eeba7af237d 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/ArtifactsDownloadingTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/ArtifactsDownloadingTest.java @@ -17,11 +17,11 @@ package org.jetbrains.idea.maven.importing; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VfsUtil; +import org.jetbrains.idea.maven.MavenCustomRepositoryHelper; import org.jetbrains.idea.maven.MavenImportingTestCase; -import org.jetbrains.idea.maven.indices.MavenCustomRepositoryHelper; -import org.jetbrains.idea.maven.project.MavenArtifact; +import org.jetbrains.idea.maven.model.MavenArtifact; +import org.jetbrains.idea.maven.model.MavenId; import org.jetbrains.idea.maven.project.MavenArtifactDownloader; -import org.jetbrains.idea.maven.project.MavenId; import org.jetbrains.idea.maven.project.MavenProject; import java.io.File; diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/DependenciesImportingTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/DependenciesImportingTest.java index 0fa9553d59e7..3f94e53655f2 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/DependenciesImportingTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/DependenciesImportingTest.java @@ -23,8 +23,8 @@ import com.intellij.openapi.roots.libraries.LibraryTable; import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VirtualFile; +import org.jetbrains.idea.maven.MavenCustomRepositoryHelper; import org.jetbrains.idea.maven.MavenImportingTestCase; -import org.jetbrains.idea.maven.indices.MavenCustomRepositoryHelper; import org.jetbrains.idea.maven.project.MavenProject; import java.io.File; @@ -1352,7 +1352,7 @@ public class DependenciesImportingTest extends MavenImportingTestCase { "jar://" + getRepositoryPath() + "/junit/junit/4.0/junit-4.0-javadoc.jar!/"); setRepositoryPath(new File(myDir, "__repo").getPath()); - myProjectsManager.getEmbeddersManagerInTests().reset(); // to recognize repository change + myProjectsManager.getEmbeddersManager().reset(); // to recognize repository change scheduleResolveAll(); resolveDependenciesAndImport(); @@ -1384,7 +1384,7 @@ public class DependenciesImportingTest extends MavenImportingTestCase { "jar://" + getRepositoryPath() + "/org/testng/testng/5.8/testng-5.8-javadoc.jar!/"); setRepositoryPath(new File(myDir, "__repo").getPath()); - myProjectsManager.getEmbeddersManagerInTests().reset(); // to recognize repository change + myProjectsManager.getEmbeddersManager().reset(); // to recognize repository change scheduleResolveAll(); diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/DependenciesManagementTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/DependenciesManagementTest.java index dd7d576b11e6..c886494cc88c 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/DependenciesManagementTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/DependenciesManagementTest.java @@ -122,7 +122,7 @@ public class DependenciesManagementTest extends MavenImportingTestCase { // reset embedders and try to resolve project from scratch in specific order - imported one goes first // to make maven cache it. we have to ensure that dependent project will be resolved correctly after that - myProjectsManager.getEmbeddersManagerInTests().releaseForcefullyInTests(); + myProjectsManager.getEmbeddersManager().releaseForcefullyInTests(); myProjectsManager.scheduleResolveInTests(Arrays.asList(myProjectsManager.findProject(bom), myProjectsManager.findProject(project))); myProjectsManager.waitForResolvingCompletion(); @@ -181,7 +181,7 @@ public class DependenciesManagementTest extends MavenImportingTestCase { assertModuleLibDeps("project", "Maven: junit:junit:4.0"); - myProjectsManager.getEmbeddersManagerInTests().reset(); + myProjectsManager.getEmbeddersManager().reset(); myProjectsManager.scheduleResolveInTests(Arrays.asList(myProjectsManager.findProject(parent), myProjectsManager.findProject(project))); myProjectsManager.waitForResolvingCompletion(); diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/FoldersImportingTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/FoldersImportingTest.java index e2e8c0fe4ae4..dc553b513a9b 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/FoldersImportingTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/FoldersImportingTest.java @@ -19,9 +19,7 @@ import com.intellij.openapi.roots.CompilerModuleExtension; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.idea.maven.MavenImportingTestCase; -import org.jetbrains.idea.maven.importing.MavenDefaultModifiableModelsProvider; -import org.jetbrains.idea.maven.importing.MavenRootModelAdapter; -import org.jetbrains.idea.maven.indices.MavenCustomRepositoryHelper; +import org.jetbrains.idea.maven.MavenCustomRepositoryHelper; import org.jetbrains.idea.maven.utils.Path; import java.io.File; diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/InvalidProjectImportingTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/InvalidProjectImportingTest.java index 5189db5dd78c..d35a13b1f4a8 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/InvalidProjectImportingTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/InvalidProjectImportingTest.java @@ -15,10 +15,10 @@ */ package org.jetbrains.idea.maven.importing; +import org.jetbrains.idea.maven.MavenCustomRepositoryHelper; import org.jetbrains.idea.maven.MavenImportingTestCase; -import org.jetbrains.idea.maven.indices.MavenCustomRepositoryHelper; import org.jetbrains.idea.maven.project.MavenProject; -import org.jetbrains.idea.maven.project.MavenProjectProblem; +import org.jetbrains.idea.maven.model.MavenProjectProblem; import java.util.ArrayList; import java.util.List; diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/MiscImportingTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/MiscImportingTest.java index 6f18da54b66e..a81fb83caeb4 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/MiscImportingTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/MiscImportingTest.java @@ -21,10 +21,9 @@ import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.roots.ModuleRootEvent; import com.intellij.openapi.roots.ModuleRootListener; +import org.jetbrains.idea.maven.MavenCustomRepositoryHelper; import org.jetbrains.idea.maven.MavenImportingTestCase; -import org.jetbrains.idea.maven.importing.MavenDefaultModifiableModelsProvider; -import org.jetbrains.idea.maven.indices.MavenCustomRepositoryHelper; -import org.jetbrains.idea.maven.project.MavenProjectProblem; +import org.jetbrains.idea.maven.model.MavenProjectProblem; import java.io.File; import java.util.List; diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenIndicesManagerTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenIndicesManagerTest.java index 8c111a958d0b..ad4c0e9a93e2 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenIndicesManagerTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenIndicesManagerTest.java @@ -16,6 +16,7 @@ package org.jetbrains.idea.maven.indices; import com.intellij.openapi.util.Pair; +import org.jetbrains.idea.maven.model.MavenArchetype; import java.io.File; import java.util.ArrayList; @@ -98,7 +99,7 @@ public class MavenIndicesManagerTest extends MavenIndicesTestCase { } public void testAddingArchetypes() throws Exception { - myIndicesFixture.getIndicesManager().addArchetype(new ArchetypeInfo("myGroup", + myIndicesFixture.getIndicesManager().addArchetype(new MavenArchetype("myGroup", "myArtifact", "666", null, @@ -113,9 +114,9 @@ public class MavenIndicesManagerTest extends MavenIndicesTestCase { } private void assertArchetypeExists(String archetypeId) { - Set achetypes = myIndicesFixture.getIndicesManager().getArchetypes(); + Set achetypes = myIndicesFixture.getIndicesManager().getArchetypes(); List actualNames = new ArrayList(); - for (ArchetypeInfo each : achetypes) { + for (MavenArchetype each : achetypes) { actualNames.add(each.groupId + ":" + each.artifactId + ":" + each.version); } assertTrue(actualNames.toString(), actualNames.contains(archetypeId)); diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenIndicesStressTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenIndicesStressTest.java index b51c2eaa5af6..3386520b7bef 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenIndicesStressTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenIndicesStressTest.java @@ -17,7 +17,10 @@ package org.jetbrains.idea.maven.indices; import com.intellij.openapi.progress.EmptyProgressIndicator; import com.intellij.openapi.progress.ProcessCanceledException; -import org.jetbrains.idea.maven.embedder.MavenEmbedderWrapper; +import org.jetbrains.idea.maven.MavenCustomRepositoryHelper; +import org.jetbrains.idea.maven.facade.MavenFacadeManager; +import org.jetbrains.idea.maven.facade.MavenIndexerWrapper; +import org.jetbrains.idea.maven.utils.MavenProcessCanceledException; import java.io.File; import java.util.Random; @@ -33,10 +36,10 @@ public abstract class MavenIndicesStressTest extends MavenIndicesTestCase implem helper.copy("local2", "local1"); //setRepositoryPath(fixture.getTestDataPath("local1")); - final MavenEmbedderWrapper embedder = MavenEmbedderWrapper.create(getMavenGeneralSettings()); + final MavenIndexerWrapper indexer = MavenFacadeManager.getInstance().createIndexer(); File indicesDir = new File(myDir, "indices"); - final MavenIndices indices = new MavenIndices(embedder, indicesDir, this); + final MavenIndices indices = new MavenIndices(indexer, indicesDir, this); final MavenIndex index = indices.add("id", getRepositoryPath(), MavenIndex.Kind.LOCAL); final AtomicBoolean isFinished = new AtomicBoolean(false); @@ -46,10 +49,10 @@ public abstract class MavenIndicesStressTest extends MavenIndicesTestCase implem try { for (int i = 0; i < 3; i++) { System.out.println("INDEXING #" + i); - indices.updateOrRepair(index, embedder, true, new EmptyProgressIndicator()); + indices.updateOrRepair(index, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); } } - catch (ProcessCanceledException e) { + catch (MavenProcessCanceledException e) { throw new RuntimeException(e); } finally { @@ -93,18 +96,18 @@ public abstract class MavenIndicesStressTest extends MavenIndicesTestCase implem helper.copy("local2", "local1"); setRepositoryPath(helper.getTestDataPath("local1")); - MavenEmbedderWrapper embedder = MavenEmbedderWrapper.create(getMavenGeneralSettings()); + final MavenIndexerWrapper indexer = MavenFacadeManager.getInstance().createIndexer(); File indicesDir = new File(myDir, "indices"); - MavenIndices indices = new MavenIndices(embedder, indicesDir, this); + MavenIndices indices = new MavenIndices(indexer, indicesDir, this); MavenIndex index = indices.add("id", getRepositoryPath(), MavenIndex.Kind.LOCAL); //index.addArtifact(new MavenId("group1", "artifact1", "1")); fail(); indices.close(); - MavenIndices indices1 = new MavenIndices(embedder, indicesDir, this); - MavenIndices indices2 = new MavenIndices(embedder, indicesDir, this); + MavenIndices indices1 = new MavenIndices(indexer, indicesDir, this); + MavenIndices indices2 = new MavenIndices(indexer, indicesDir, this); AtomicInteger finishedCount = new AtomicInteger(0); diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenIndicesTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenIndicesTest.java index 2ef5eaee4ee1..5b95798475fa 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenIndicesTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenIndicesTest.java @@ -19,10 +19,12 @@ import com.intellij.openapi.progress.EmptyProgressIndicator; import com.intellij.openapi.util.io.FileUtil; import org.apache.lucene.index.Term; import org.apache.lucene.search.Query; -import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.WildcardQuery; -import org.jetbrains.idea.maven.embedder.MavenEmbedderWrapper; -import org.sonatype.nexus.index.ArtifactInfo; +import org.jetbrains.idea.maven.MavenCustomRepositoryHelper; +import org.jetbrains.idea.maven.facade.MavenFacadeIndexer; +import org.jetbrains.idea.maven.facade.MavenFacadeManager; +import org.jetbrains.idea.maven.facade.MavenIndexerWrapper; +import org.jetbrains.idea.maven.model.MavenArtifactInfo; import java.io.File; import java.io.FileWriter; @@ -33,7 +35,7 @@ import java.util.List; public class MavenIndicesTest extends MavenIndicesTestCase { private MavenCustomRepositoryHelper myRepositoryHelper; private MavenIndices myIndices; - private MavenEmbedderWrapper myEmbedder; + private MavenIndexerWrapper myIndexer; private File myIndicesDir; private boolean isBroken; @@ -55,9 +57,9 @@ public class MavenIndicesTest extends MavenIndicesTestCase { } private void initIndices(String relativeDir) { - myEmbedder = MavenEmbedderWrapper.create(getMavenGeneralSettings()); + myIndexer = MavenFacadeManager.getInstance().createIndexer(); myIndicesDir = new File(myDir, relativeDir); - myIndices = new MavenIndices(myEmbedder, myIndicesDir, new MavenIndex.IndexListener() { + myIndices = new MavenIndices(myIndexer, myIndicesDir, new MavenIndex.IndexListener() { public void indexIsBroken(MavenIndex index) { isBroken = true; } @@ -66,12 +68,12 @@ public class MavenIndicesTest extends MavenIndicesTestCase { private void shutdownIndices() throws Exception { myIndices.close(); - myEmbedder.release(); + myIndexer.release(); } public void testCreatingAndUpdatingLocal() throws Exception { MavenIndex i = myIndices.add("id", myRepositoryHelper.getTestDataPath("local1"), MavenIndex.Kind.LOCAL); - myIndices.updateOrRepair(i, myEmbedder, true, new EmptyProgressIndicator()); + myIndices.updateOrRepair(i, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); assertUnorderedElementsAreEqual(i.getGroupIds(), "junit"); } @@ -79,8 +81,8 @@ public class MavenIndicesTest extends MavenIndicesTestCase { public void testCreatingSeveral() throws Exception { MavenIndex i1 = myIndices.add("id1", myRepositoryHelper.getTestDataPath("local1"), MavenIndex.Kind.LOCAL); MavenIndex i2 = myIndices.add("id2", myRepositoryHelper.getTestDataPath("local2"), MavenIndex.Kind.LOCAL); - myIndices.updateOrRepair(i1, myEmbedder, true, new EmptyProgressIndicator()); - myIndices.updateOrRepair(i2, myEmbedder, true, new EmptyProgressIndicator()); + myIndices.updateOrRepair(i1, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); + myIndices.updateOrRepair(i2, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); assertUnorderedElementsAreEqual(i1.getGroupIds(), "junit"); assertUnorderedElementsAreEqual(i2.getGroupIds(), "jmock"); @@ -90,8 +92,8 @@ public class MavenIndicesTest extends MavenIndicesTestCase { MavenIndex i1 = myIndices.add("id", myRepositoryHelper.getTestDataPath("local1"), MavenIndex.Kind.LOCAL); MavenIndex i2 = myIndices.add("id", myRepositoryHelper.getTestDataPath("local2"), MavenIndex.Kind.LOCAL); assertNotSame(i1, i2); - myIndices.updateOrRepair(i1, myEmbedder, true, new EmptyProgressIndicator()); - myIndices.updateOrRepair(i2, myEmbedder, true, new EmptyProgressIndicator()); + myIndices.updateOrRepair(i1, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); + myIndices.updateOrRepair(i2, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); assertUnorderedElementsAreEqual(i1.getGroupIds(), "junit"); assertUnorderedElementsAreEqual(i2.getGroupIds(), "jmock"); @@ -101,9 +103,9 @@ public class MavenIndicesTest extends MavenIndicesTestCase { MavenIndex i1 = myIndices.add("id1", myRepositoryHelper.getTestDataPath("local1"), MavenIndex.Kind.LOCAL); MavenIndex i2 = myIndices.add("id2", myRepositoryHelper.getTestDataPath("local1"), MavenIndex.Kind.LOCAL); assertNotSame(i1, i2); - myIndices.updateOrRepair(i1, myEmbedder, true, new EmptyProgressIndicator()); - myIndices.updateOrRepair(i2, myEmbedder, true, new EmptyProgressIndicator()); - + myIndices.updateOrRepair(i1, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); + myIndices.updateOrRepair(i2, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); + assertUnorderedElementsAreEqual(i1.getGroupIds(), "junit"); assertUnorderedElementsAreEqual(i2.getGroupIds(), "junit"); } @@ -116,13 +118,13 @@ public class MavenIndicesTest extends MavenIndicesTestCase { public void testUpdatingLocalClearsPreviousIndex() throws Exception { MavenIndex i = myIndices.add("id", myRepositoryHelper.getTestDataPath("local1"), MavenIndex.Kind.LOCAL); - myIndices.updateOrRepair(i, myEmbedder, true, new EmptyProgressIndicator()); + myIndices.updateOrRepair(i, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); assertUnorderedElementsAreEqual(i.getGroupIds(), "junit"); myRepositoryHelper.delete("local1"); myRepositoryHelper.copy("local2", "local1"); - myIndices.updateOrRepair(i, myEmbedder, true, new EmptyProgressIndicator()); + myIndices.updateOrRepair(i, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); assertUnorderedElementsAreEqual(i.getGroupIds(), "jmock"); } @@ -138,17 +140,17 @@ public class MavenIndicesTest extends MavenIndicesTestCase { public void testAddingRemote() throws Exception { MavenIndex i = myIndices.add("id", "file:///" + myRepositoryHelper.getTestDataPath("remote"), MavenIndex.Kind.REMOTE); - myIndices.updateOrRepair(i, myEmbedder, true, new EmptyProgressIndicator()); + myIndices.updateOrRepair(i, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); assertUnorderedElementsAreEqual(i.getGroupIds(), "junit"); } public void testUpdatingRemote() throws Exception { MavenIndex i = myIndices.add("id", "file:///" + myRepositoryHelper.getTestDataPath("remote"), MavenIndex.Kind.REMOTE); - myIndices.updateOrRepair(i, myEmbedder, true, new EmptyProgressIndicator()); + myIndices.updateOrRepair(i, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); //shouldn't throw 'The existing index is for repository [remote] and not for repository [xxx]' - myIndices.updateOrRepair(i, myEmbedder, true, new EmptyProgressIndicator()); + myIndices.updateOrRepair(i, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); assertUnorderedElementsAreEqual(i.getGroupIds(), "junit"); } @@ -173,19 +175,19 @@ public class MavenIndicesTest extends MavenIndicesTestCase { } public void testAddingCorrectlyToIndexer() throws Exception { - assertEquals(0, myIndices.getIndexer().getIndexingContexts().size()); + assertEquals(0, myIndexer.getIndexCount()); MavenIndex i1 = myIndices.add("local", myRepositoryHelper.getTestDataPath("local1"), MavenIndex.Kind.LOCAL); - assertEquals(1, myIndices.getIndexer().getIndexingContexts().size()); + assertEquals(1, myIndexer.getIndexCount()); MavenIndex i2 = myIndices.add("local", myRepositoryHelper.getTestDataPath("local2"), MavenIndex.Kind.LOCAL); - assertEquals(2, myIndices.getIndexer().getIndexingContexts().size()); + assertEquals(2, myIndexer.getIndexCount()); - myIndices.updateOrRepair(i1, myEmbedder, true, new EmptyProgressIndicator()); - assertEquals(2, myIndices.getIndexer().getIndexingContexts().size()); + myIndices.updateOrRepair(i1, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); + assertEquals(2, myIndexer.getIndexCount()); - myIndices.updateOrRepair(i2, myEmbedder, true, new EmptyProgressIndicator()); - assertEquals(2, myIndices.getIndexer().getIndexingContexts().size()); + myIndices.updateOrRepair(i2, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); + assertEquals(2, myIndexer.getIndexCount()); } public void testClearingIndexDirOnLoadError() throws Exception { @@ -220,8 +222,8 @@ public class MavenIndicesTest extends MavenIndicesTestCase { public void testLoadingIndexIfCachesAreBroken() throws Exception { MavenIndex i1 = myIndices.add("id", myRepositoryHelper.getTestDataPath("local1"), MavenIndex.Kind.LOCAL); MavenIndex i2 = myIndices.add("id", myRepositoryHelper.getTestDataPath("local2"), MavenIndex.Kind.LOCAL); - myIndices.updateOrRepair(i1, myEmbedder, true, new EmptyProgressIndicator()); - myIndices.updateOrRepair(i2, myEmbedder, true, new EmptyProgressIndicator()); + myIndices.updateOrRepair(i1, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); + myIndices.updateOrRepair(i2, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); assertUnorderedElementsAreEqual(i1.getGroupIds(), "junit"); assertUnorderedElementsAreEqual(i2.getGroupIds(), "jmock"); @@ -235,7 +237,7 @@ public class MavenIndicesTest extends MavenIndicesTestCase { assertTrue(myIndices.getIndices().get(0).getGroupIds().isEmpty()); assertUnorderedElementsAreEqual(myIndices.getIndices().get(1).getGroupIds(), "jmock"); - myIndices.updateOrRepair(myIndices.getIndices().get(0), myEmbedder, false, new EmptyProgressIndicator()); + myIndices.updateOrRepair(myIndices.getIndices().get(0), false, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); assertUnorderedElementsAreEqual(myIndices.getIndices().get(0).getGroupIds(), "junit"); } @@ -255,18 +257,18 @@ public class MavenIndicesTest extends MavenIndicesTestCase { public void testAddingIndexWithExistingDirectoryDoesNotThrowException() throws Exception { MavenIndex i = myIndices.add("id", myRepositoryHelper.getTestDataPath("local1"), MavenIndex.Kind.LOCAL); - myIndices.updateOrRepair(i, myEmbedder, true, new EmptyProgressIndicator()); + myIndices.updateOrRepair(i, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); shutdownIndices(); initIndices(); i = myIndices.add("id", myRepositoryHelper.getTestDataPath("local1"), MavenIndex.Kind.LOCAL); - myIndices.updateOrRepair(i, myEmbedder, true, new EmptyProgressIndicator()); + myIndices.updateOrRepair(i, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); } public void testSavingFailureMessage() throws Exception { MavenIndex i = myIndices.add("id", "xxx", MavenIndex.Kind.REMOTE); - myIndices.updateOrRepair(i, myEmbedder, true, new EmptyProgressIndicator()); + myIndices.updateOrRepair(i, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); String message = i.getFailureMessage(); assertNotNull(message); @@ -279,7 +281,7 @@ public class MavenIndicesTest extends MavenIndicesTestCase { public void testRepairingIndicesOnReadError() throws Exception { MavenIndex index = myIndices.add("id", myRepositoryHelper.getTestDataPath("local1"), MavenIndex.Kind.LOCAL); - myIndices.updateOrRepair(index, myEmbedder, true, new EmptyProgressIndicator()); + myIndices.updateOrRepair(index, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); shutdownIndices(); damageFile(index, "groupIds.dat", false); @@ -292,13 +294,13 @@ public class MavenIndicesTest extends MavenIndicesTestCase { assertTrue(index.getGroupIds().isEmpty()); - myIndices.updateOrRepair(myIndices.getIndices().get(0), myEmbedder, false, new EmptyProgressIndicator()); + myIndices.updateOrRepair(myIndices.getIndices().get(0), false, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); assertUnorderedElementsAreEqual(index.getGroupIds(), "junit"); } public void testRepairingIndicesOnReadWhileAddingArtifact() throws Exception { MavenIndex index = myIndices.add("id", myRepositoryHelper.getTestDataPath("local1"), MavenIndex.Kind.LOCAL); - myIndices.updateOrRepair(index, myEmbedder, true, new EmptyProgressIndicator()); + myIndices.updateOrRepair(index, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); shutdownIndices(); damageFile(index, "artifactIds-map.dat", false); @@ -311,7 +313,7 @@ public class MavenIndicesTest extends MavenIndicesTestCase { assertTrue(index.getGroupIds().isEmpty()); - myIndices.updateOrRepair(myIndices.getIndices().get(0), myEmbedder, false, new EmptyProgressIndicator()); + myIndices.updateOrRepair(myIndices.getIndices().get(0), false, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); assertUnorderedElementsAreEqual(index.getGroupIds(), "junit"); } @@ -337,7 +339,7 @@ public class MavenIndicesTest extends MavenIndicesTestCase { public void testGettingArtifactInfos() throws Exception { myRepositoryHelper.copy("local2", "local1"); MavenIndex i = myIndices.add("id", myRepositoryHelper.getTestDataPath("local1"), MavenIndex.Kind.LOCAL); - myIndices.updateOrRepair(i, myEmbedder, true, new EmptyProgressIndicator()); + myIndices.updateOrRepair(i, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); assertUnorderedElementsAreEqual(i.getGroupIds(), "junit", "jmock"); @@ -357,9 +359,8 @@ public class MavenIndicesTest extends MavenIndicesTestCase { public void testGettingArtifactInfosAfterReload() throws Exception { myIndices.updateOrRepair(myIndices.add("id", myRepositoryHelper.getTestDataPath("local1"), MavenIndex.Kind.LOCAL), - myEmbedder, true, - new EmptyProgressIndicator()); + getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); shutdownIndices(); initIndices(); @@ -370,7 +371,7 @@ public class MavenIndicesTest extends MavenIndicesTestCase { public void testHasArtifactInfo() throws Exception { myRepositoryHelper.copy("local2", "local1"); MavenIndex i = myIndices.add("id", myRepositoryHelper.getTestDataPath("local1"), MavenIndex.Kind.LOCAL); - myIndices.updateOrRepair(i, myEmbedder, true, new EmptyProgressIndicator()); + myIndices.updateOrRepair(i, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); assertTrue(i.hasGroupId("junit")); assertTrue(i.hasGroupId("jmock")); @@ -387,45 +388,42 @@ public class MavenIndicesTest extends MavenIndicesTestCase { public void testSearching() throws Exception { MavenIndex i = myIndices.add("id", myRepositoryHelper.getTestDataPath("local1"), MavenIndex.Kind.LOCAL); - myIndices.updateOrRepair(i, myEmbedder, true, new EmptyProgressIndicator()); + myIndices.updateOrRepair(i, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); - assertSearchResults(i, new TermQuery(new Term(ArtifactInfo.GROUP_ID, "junit")), + assertSearchResults(i, new WildcardQuery(new Term(MavenFacadeIndexer.SEARCH_TERM_COORDINATES, "*junit*")), "junit:junit:3.8.1", "junit:junit:3.8.2", "junit:junit:4.0"); } public void testSearchingAfterArtifactAddition() throws Exception { MavenIndex i = myIndices.add("id", myRepositoryHelper.getTestDataPath("local1"), MavenIndex.Kind.LOCAL); - myIndices.updateOrRepair(i, myEmbedder, true, new EmptyProgressIndicator()); + myIndices.updateOrRepair(i, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); i.addArtifact(new File(myRepositoryHelper.getTestDataPath("local2/jmock/jmock/1.0.0/jmock-1.0.0.jar"))); - assertSearchResults(i, new TermQuery(new Term(ArtifactInfo.GROUP_ID, "jmock")), - "jmock:jmock:1.0.0"); + assertSearchResults(i, new WildcardQuery(new Term(MavenFacadeIndexer.SEARCH_TERM_COORDINATES, "*jmock*")), "jmock:jmock:1.0.0"); } private void assertSearchResults(MavenIndex i, Query query, String... expectedArtifacts) { List actualArtifacts = new ArrayList(); - for (ArtifactInfo each : i.search(query, 100)) { - actualArtifacts.add(each.groupId + ":" + each.artifactId + ":" + each.version); + for (MavenArtifactInfo each : i.search(query, 100)) { + actualArtifacts.add(each.getGroupId() + ":" + each.getArtifactId() + ":" + each.getVersion()); } assertUnorderedElementsAreEqual(actualArtifacts, expectedArtifacts); } public void testSearchingForClasses() throws Exception { MavenIndex i = myIndices.add("id", myRepositoryHelper.getTestDataPath("local1"), MavenIndex.Kind.LOCAL); - myIndices.updateOrRepair(i, myEmbedder, true, new EmptyProgressIndicator()); + myIndices.updateOrRepair(i, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); - assertSearchResults(i, new WildcardQuery(new Term(ArtifactInfo.NAMES, "*runwith*")), - "junit:junit:4.0"); + assertSearchResults(i, new WildcardQuery(new Term(MavenFacadeIndexer.SEARCH_TERM_CLASS_NAMES, "*runwith*")), "junit:junit:4.0"); } public void testSearchingForClassesAfterArtifactAddition() throws Exception { MavenIndex i = myIndices.add("id", myRepositoryHelper.getTestDataPath("local1"), MavenIndex.Kind.LOCAL); - myIndices.updateOrRepair(i, myEmbedder, true, new EmptyProgressIndicator()); + myIndices.updateOrRepair(i, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); i.addArtifact(new File(myRepositoryHelper.getTestDataPath("local2/jmock/jmock/1.0.0/jmock-1.0.0.jar"))); - assertSearchResults(i, new WildcardQuery(new Term(ArtifactInfo.NAMES, "*mock*")), - "jmock:jmock:1.0.0"); + assertSearchResults(i, new WildcardQuery(new Term(MavenFacadeIndexer.SEARCH_TERM_CLASS_NAMES, "*mock*")), "jmock:jmock:1.0.0"); } } diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenIndicesTestFixture.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenIndicesTestFixture.java index bb99d5dcfcbd..32acbc98daa2 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenIndicesTestFixture.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenIndicesTestFixture.java @@ -17,6 +17,7 @@ package org.jetbrains.idea.maven.indices; import com.intellij.openapi.project.Project; import com.intellij.util.ArrayUtil; +import org.jetbrains.idea.maven.MavenCustomRepositoryHelper; import org.jetbrains.idea.maven.project.MavenProjectsManager; import java.io.File; @@ -49,7 +50,7 @@ public class MavenIndicesTestFixture { addToRepository(each); } - MavenProjectsManager.getInstance(myProject).getGeneralSettings().setLocalRepository(myRepositoryHelper.getTestDataPath(myLocalRepoDir)); + MavenProjectsManager.getInstance(myProject).getGeneralSettings().setOverridenLocalRepository(myRepositoryHelper.getTestDataPath(myLocalRepoDir)); getIndicesManager().setTestIndexDir(new File(myDir, "MavenIndices")); myIndicesManager = MavenProjectIndicesManager.getInstance(myProject); diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenPluginInfoReaderTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenPluginInfoReaderTest.java index 8dfc5ed8f59f..f397347e4e64 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenPluginInfoReaderTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenPluginInfoReaderTest.java @@ -15,8 +15,9 @@ */ package org.jetbrains.idea.maven.indices; +import org.jetbrains.idea.maven.MavenCustomRepositoryHelper; import org.jetbrains.idea.maven.MavenTestCase; -import org.jetbrains.idea.maven.project.MavenId; +import org.jetbrains.idea.maven.model.MavenId; import org.jetbrains.idea.maven.utils.MavenPluginInfo; import org.jetbrains.idea.maven.utils.MavenArtifactUtil; diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenSearcherTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenSearcherTest.java index 2aef5165cab6..8ee0e5599192 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenSearcherTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenSearcherTest.java @@ -15,7 +15,7 @@ */ package org.jetbrains.idea.maven.indices; -import org.sonatype.nexus.index.ArtifactInfo; +import org.jetbrains.idea.maven.model.MavenArtifactInfo; import java.util.ArrayList; import java.util.List; @@ -114,9 +114,9 @@ public class MavenSearcherTest extends MavenIndicesTestCase { List actualArtifacts = new ArrayList(); for (MavenClassSearchResult eachResult : new MavenClassSearcher().search(myProject, pattern, 100)) { String s = eachResult.className + "(" + eachResult.packageName + ")"; - for (ArtifactInfo eachVersion : eachResult.versions) { + for (MavenArtifactInfo eachVersion : eachResult.versions) { if (s.length() > 0) s += " "; - s += eachVersion.groupId + ":" + eachVersion.artifactId + ":" + eachVersion.version; + s += eachVersion.getGroupId() + ":" + eachVersion.getArtifactId()+ ":" + eachVersion.getVersion(); } actualArtifacts.add(s); } @@ -127,9 +127,9 @@ public class MavenSearcherTest extends MavenIndicesTestCase { List actual = new ArrayList(); for (MavenArtifactSearchResult eachResult : new MavenArtifactSearcher().search(myProject, pattern, 100)) { String s = ""; - for (ArtifactInfo eachVersion : eachResult.versions) { + for (MavenArtifactInfo eachVersion : eachResult.versions) { if (s.length() > 0) s += " "; - s += eachVersion.groupId + ":" + eachVersion.artifactId + ":" + eachVersion.version; + s += eachVersion.getGroupId() + ":" + eachVersion.getArtifactId()+ ":" + eachVersion.getVersion(); } actual.add(s); } diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenEmbeddersManagerTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenEmbeddersManagerTest.java index a7b2bc63c3cf..fa95be7dc646 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenEmbeddersManagerTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenEmbeddersManagerTest.java @@ -16,7 +16,7 @@ package org.jetbrains.idea.maven.project; import org.jetbrains.idea.maven.MavenTestCase; -import org.jetbrains.idea.maven.embedder.MavenEmbedderWrapper; +import org.jetbrains.idea.maven.facade.MavenEmbedderWrapper; public class MavenEmbeddersManagerTest extends MavenTestCase { private MavenEmbeddersManager myManager; @@ -24,7 +24,7 @@ public class MavenEmbeddersManagerTest extends MavenTestCase { @Override protected void setUp() throws Exception { super.setUp(); - myManager = new MavenEmbeddersManager(getMavenGeneralSettings()); + myManager = new MavenEmbeddersManager(myProject); } @Override @@ -34,52 +34,52 @@ public class MavenEmbeddersManagerTest extends MavenTestCase { } public void testBasics() throws Exception { - MavenEmbedderWrapper one = myManager.getEmbedder(MavenEmbeddersManager.EmbedderKind.FOR_FOLDERS_RESOLVE); - MavenEmbedderWrapper two = myManager.getEmbedder(MavenEmbeddersManager.EmbedderKind.FOR_DEPENDENCIES_RESOLVE); + MavenEmbedderWrapper one = myManager.getEmbedder(MavenEmbeddersManager.FOR_FOLDERS_RESOLVE); + MavenEmbedderWrapper two = myManager.getEmbedder(MavenEmbeddersManager.FOR_DEPENDENCIES_RESOLVE); assertNotSame(one, two); } public void testForSameId() throws Exception { - MavenEmbedderWrapper one1 = myManager.getEmbedder(MavenEmbeddersManager.EmbedderKind.FOR_DEPENDENCIES_RESOLVE); - MavenEmbedderWrapper one2 = myManager.getEmbedder(MavenEmbeddersManager.EmbedderKind.FOR_DEPENDENCIES_RESOLVE); + MavenEmbedderWrapper one1 = myManager.getEmbedder(MavenEmbeddersManager.FOR_DEPENDENCIES_RESOLVE); + MavenEmbedderWrapper one2 = myManager.getEmbedder(MavenEmbeddersManager.FOR_DEPENDENCIES_RESOLVE); assertNotSame(one1, one2); myManager.release(one1); - MavenEmbedderWrapper one3 = myManager.getEmbedder(MavenEmbeddersManager.EmbedderKind.FOR_DEPENDENCIES_RESOLVE); + MavenEmbedderWrapper one3 = myManager.getEmbedder(MavenEmbeddersManager.FOR_DEPENDENCIES_RESOLVE); assertSame(one1, one3); } public void testCachingOnlyOne() throws Exception { - MavenEmbedderWrapper one1 = myManager.getEmbedder(MavenEmbeddersManager.EmbedderKind.FOR_DEPENDENCIES_RESOLVE); - MavenEmbedderWrapper one2 = myManager.getEmbedder(MavenEmbeddersManager.EmbedderKind.FOR_DEPENDENCIES_RESOLVE); + MavenEmbedderWrapper one1 = myManager.getEmbedder(MavenEmbeddersManager.FOR_DEPENDENCIES_RESOLVE); + MavenEmbedderWrapper one2 = myManager.getEmbedder(MavenEmbeddersManager.FOR_DEPENDENCIES_RESOLVE); assertNotSame(one1, one2); myManager.release(one1); myManager.release(one2); - MavenEmbedderWrapper one11 = myManager.getEmbedder(MavenEmbeddersManager.EmbedderKind.FOR_DEPENDENCIES_RESOLVE); - MavenEmbedderWrapper one22 = myManager.getEmbedder(MavenEmbeddersManager.EmbedderKind.FOR_DEPENDENCIES_RESOLVE); + MavenEmbedderWrapper one11 = myManager.getEmbedder(MavenEmbeddersManager.FOR_DEPENDENCIES_RESOLVE); + MavenEmbedderWrapper one22 = myManager.getEmbedder(MavenEmbeddersManager.FOR_DEPENDENCIES_RESOLVE); assertSame(one1, one11); assertNotSame(one2, one22); } public void testResettingAllCachedAndInUse() throws Exception { - MavenEmbedderWrapper one1 = myManager.getEmbedder(MavenEmbeddersManager.EmbedderKind.FOR_DEPENDENCIES_RESOLVE); - MavenEmbedderWrapper one2 = myManager.getEmbedder(MavenEmbeddersManager.EmbedderKind.FOR_FOLDERS_RESOLVE); + MavenEmbedderWrapper one1 = myManager.getEmbedder(MavenEmbeddersManager.FOR_DEPENDENCIES_RESOLVE); + MavenEmbedderWrapper one2 = myManager.getEmbedder(MavenEmbeddersManager.FOR_FOLDERS_RESOLVE); myManager.release(one1); myManager.reset(); myManager.release(one2); - MavenEmbedderWrapper one11 = myManager.getEmbedder(MavenEmbeddersManager.EmbedderKind.FOR_DEPENDENCIES_RESOLVE); - MavenEmbedderWrapper one22 = myManager.getEmbedder(MavenEmbeddersManager.EmbedderKind.FOR_FOLDERS_RESOLVE); + MavenEmbedderWrapper one11 = myManager.getEmbedder(MavenEmbeddersManager.FOR_DEPENDENCIES_RESOLVE); + MavenEmbedderWrapper one22 = myManager.getEmbedder(MavenEmbeddersManager.FOR_FOLDERS_RESOLVE); assertNotSame(one1, one11); assertNotSame(one2, one22); diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectReaderTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectReaderTest.java index efd4e6bf6b91..639a61f6926e 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectReaderTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectReaderTest.java @@ -21,12 +21,9 @@ import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; -import org.apache.maven.model.Build; -import org.apache.maven.model.Parent; -import org.apache.maven.model.Profile; -import org.apache.maven.model.Resource; import org.jetbrains.idea.maven.MavenTestCase; -import org.jetbrains.idea.maven.embedder.MavenEmbedderWrapper; +import org.jetbrains.idea.maven.facade.MavenFacadeUtil; +import org.jetbrains.idea.maven.model.*; import org.jetbrains.idea.maven.utils.MavenUtil; import java.io.File; @@ -41,10 +38,7 @@ public class MavenProjectReaderTest extends MavenTestCase { "project" + "1"); - org.apache.maven.project.MavenProject p = readProject(myProjectPom); - - assertEquals(new File(myProjectPom.getPath()), p.getFile()); - assertEquals(new File(myProjectRoot.getPath()), p.getBasedir()); + MavenId p = readProject(myProjectPom).getMavenId(); assertEquals("test", p.getGroupId()); assertEquals("project", p.getArtifactId()); @@ -67,10 +61,7 @@ public class MavenProjectReaderTest extends MavenTestCase { MavenProjectReaderResult result = readProject(myProjectPom, new NullProjectLocator()); assertProblems(result, "'pom.xml' has syntax errors"); - org.apache.maven.project.MavenProject p = result.nativeMavenProject; - - assertEquals(new File(myProjectPom.getPath()), p.getFile()); - assertEquals(new File(myProjectRoot.getPath()), p.getBasedir()); + MavenId p = result.mavenModel.getMavenId(); assertEquals("test", p.getGroupId()); assertEquals("project", p.getArtifactId()); @@ -88,7 +79,7 @@ public class MavenProjectReaderTest extends MavenTestCase { MavenProjectReaderResult result = readProject(myProjectPom, new NullProjectLocator()); assertProblems(result, "'pom.xml' has syntax errors"); - org.apache.maven.project.MavenProject p = result.nativeMavenProject; + MavenModel p = result.mavenModel; assertEquals("a0x0a", p.getName()); } @@ -158,14 +149,11 @@ public class MavenProjectReaderTest extends MavenTestCase { MavenProjectReaderResult readResult = readProject(myProjectPom, new NullProjectLocator()); assertProblems(readResult, "'pom.xml' has syntax errors"); - org.apache.maven.project.MavenProject p = readResult.nativeMavenProject; + MavenModel p = readResult.mavenModel; - assertEquals(new File(myProjectPom.getPath()), p.getFile()); - assertEquals(new File(myProjectRoot.getPath()), p.getBasedir()); - - assertEquals("test", p.getGroupId()); - assertEquals("project", p.getArtifactId()); - assertEquals("Unknown", p.getVersion()); + assertEquals("test", p.getMavenId().getGroupId()); + assertEquals("project", p.getMavenId().getArtifactId()); + assertEquals("Unknown", p.getMavenId().getVersion()); assertEquals("foo", p.getName()); } @@ -179,38 +167,35 @@ public class MavenProjectReaderTest extends MavenTestCase { MavenProjectReaderResult readResult = readProject(myProjectPom, new NullProjectLocator()); assertProblems(readResult, "'pom.xml' has syntax errors"); - org.apache.maven.project.MavenProject p = readResult.nativeMavenProject; + MavenModel p = readResult.mavenModel; - assertEquals(new File(myProjectPom.getPath()), p.getFile()); - assertEquals(new File(myProjectRoot.getPath()), p.getBasedir()); - - assertEquals("test", p.getGroupId()); - assertEquals("project", p.getArtifactId()); - assertEquals("1", p.getVersion()); + assertEquals("test", p.getMavenId().getGroupId()); + assertEquals("project", p.getMavenId().getArtifactId()); + assertEquals("1", p.getMavenId().getVersion()); assertEquals("foo", p.getName()); } public void testEmpty() throws Exception { createProjectPom(""); - org.apache.maven.project.MavenProject p = readProject(myProjectPom); + MavenModel p = readProject(myProjectPom); - assertEquals("Unknown", p.getGroupId()); - assertEquals("Unknown", p.getArtifactId()); - assertEquals("Unknown", p.getVersion()); + assertEquals("Unknown", p.getMavenId().getGroupId()); + assertEquals("Unknown", p.getMavenId().getArtifactId()); + assertEquals("Unknown", p.getMavenId().getVersion()); } public void testSpacesInTest() throws Exception { createProjectPom("foo bar"); - org.apache.maven.project.MavenProject p = readProject(myProjectPom); + MavenModel p = readProject(myProjectPom); assertEquals("foo bar", p.getName()); } public void testTextInContainerTag() throws Exception { createProjectPom("foo name bar"); - org.apache.maven.project.MavenProject p = readProject(myProjectPom); + MavenModel p = readProject(myProjectPom); assertEquals("name", p.getName()); } @@ -222,30 +207,27 @@ public class MavenProjectReaderTest extends MavenTestCase { " 1" + ""); - org.apache.maven.project.MavenProject p = readProject(file); + MavenModel p = readProject(file); - assertEquals("4.0.0", p.getModelVersion()); assertEquals("jar", p.getPackaging()); - assertNull(p.getModel().getName()); + assertNull(p.getName()); assertNull(p.getParent()); - assertNull(p.getParentArtifact()); - Build build = p.getBuild(); - assertNotNull(build); - assertEquals("project-1", build.getFinalName()); - assertEquals(null, build.getDefaultGoal()); - assertPathEquals(pathFromBasedir("src/main/java"), build.getSourceDirectory()); - assertPathEquals(pathFromBasedir("src/test/java"), build.getTestSourceDirectory()); - assertPathEquals(pathFromBasedir("src/main/scripts"), build.getScriptSourceDirectory()); - assertEquals(1, build.getResources().size()); - assertResource((Resource)build.getResources().get(0), pathFromBasedir("src/main/resources"), + assertEquals("project-1", p.getBuild().getFinalName()); + assertEquals(null, p.getBuild().getDefaultGoal()); + assertSize(1, p.getBuild().getSources()); + assertPathEquals(pathFromBasedir("src/main/java"), p.getBuild().getSources().get(0)); + assertSize(1, p.getBuild().getTestSources()); + assertPathEquals(pathFromBasedir("src/test/java"), p.getBuild().getTestSources().get(0)); + assertEquals(1, p.getBuild().getResources().size()); + assertResource(p.getBuild().getResources().get(0), pathFromBasedir("src/main/resources"), false, null, Collections.EMPTY_LIST, Collections.EMPTY_LIST); - assertEquals(1, build.getTestResources().size()); - assertResource((Resource)build.getTestResources().get(0), pathFromBasedir("src/test/resources"), + assertEquals(1, p.getBuild().getTestResources().size()); + assertResource(p.getBuild().getTestResources().get(0), pathFromBasedir("src/test/resources"), false, null, Collections.EMPTY_LIST, Collections.EMPTY_LIST); - assertPathEquals(pathFromBasedir("target"), build.getDirectory()); - assertPathEquals(pathFromBasedir("target/classes"), build.getOutputDirectory()); - assertPathEquals(pathFromBasedir("target/test-classes"), build.getTestOutputDirectory()); + assertPathEquals(pathFromBasedir("target"), p.getBuild().getDirectory()); + assertPathEquals(pathFromBasedir("target/classes"), p.getBuild().getOutputDirectory()); + assertPathEquals(pathFromBasedir("target/test-classes"), p.getBuild().getTestOutputDirectory()); } public void testDefaultsForParent() throws Exception { @@ -257,9 +239,9 @@ public class MavenProjectReaderTest extends MavenTestCase { " dummy" + ""); - org.apache.maven.project.MavenProject p = readProject(myProjectPom); + MavenModel p = readProject(myProjectPom); - assertParent(p, "Unknown", "Unknown", "Unknown", "../pom.xml"); + assertParent(p, "Unknown", "Unknown", "Unknown"); } public void testTakingCoordinatesFromParent() throws Exception { @@ -269,11 +251,11 @@ public class MavenProjectReaderTest extends MavenTestCase { " 1" + ""); - org.apache.maven.project.MavenProject p = readProject(myProjectPom); + MavenId id = readProject(myProjectPom).getMavenId(); - assertEquals("test", p.getGroupId()); - assertEquals("Unknown", p.getArtifactId()); - assertEquals("1", p.getVersion()); + assertEquals("test", id.getGroupId()); + assertEquals("Unknown", id.getArtifactId()); + assertEquals("1", id.getVersion()); } public void testCustomSettings() throws Exception { @@ -320,30 +302,28 @@ public class MavenProjectReaderTest extends MavenTestCase { " " + ""); - org.apache.maven.project.MavenProject p = readProject(file); + MavenModel p = readProject(file); - assertEquals("1.2.3", p.getModelVersion()); assertEquals("pom", p.getPackaging()); assertEquals("foo", p.getName()); - assertParent(p, "testParent", "projectParent", "2", "../parent/pom.xml"); + assertParent(p, "testParent", "projectParent", "2"); - Build build = p.getBuild(); - assertNotNull(build); - assertEquals("xxx", build.getFinalName()); - assertEquals("someGoal", build.getDefaultGoal()); - assertPathEquals(pathFromBasedir("mySrc"), build.getSourceDirectory()); - assertPathEquals(pathFromBasedir("myTestSrc"), build.getTestSourceDirectory()); - assertPathEquals(pathFromBasedir("myScriptSrc"), build.getScriptSourceDirectory()); - assertEquals(1, build.getResources().size()); - assertResource((Resource)build.getResources().get(0), pathFromBasedir("myRes"), + assertEquals("xxx", p.getBuild().getFinalName()); + assertEquals("someGoal", p.getBuild().getDefaultGoal()); + assertSize(1, p.getBuild().getSources()); + assertPathEquals(pathFromBasedir("mySrc"), p.getBuild().getSources().get(0)); + assertSize(1, p.getBuild().getTestSources()); + assertPathEquals(pathFromBasedir("myTestSrc"), p.getBuild().getTestSources().get(0)); + assertEquals(1, p.getBuild().getResources().size()); + assertResource(p.getBuild().getResources().get(0), pathFromBasedir("myRes"), true, "dir", Collections.singletonList("**.properties"), Collections.singletonList("**.xml")); - assertEquals(1, build.getTestResources().size()); - assertResource((Resource)build.getTestResources().get(0), pathFromBasedir("myTestRes"), + assertEquals(1, p.getBuild().getTestResources().size()); + assertResource(p.getBuild().getTestResources().get(0), pathFromBasedir("myTestRes"), false, null, Collections.singletonList("**.properties"), Collections.EMPTY_LIST); - assertPathEquals(pathFromBasedir("myOutput"), build.getDirectory()); - assertPathEquals(pathFromBasedir("myClasses"), build.getOutputDirectory()); - assertPathEquals(pathFromBasedir("myTestClasses"), build.getTestOutputDirectory()); + assertPathEquals(pathFromBasedir("myOutput"), p.getBuild().getDirectory()); + assertPathEquals(pathFromBasedir("myClasses"), p.getBuild().getOutputDirectory()); + assertPathEquals(pathFromBasedir("myTestClasses"), p.getBuild().getTestOutputDirectory()); } public void testOutputPathsAreBasedOnTargetPath() throws Exception { @@ -354,13 +334,11 @@ public class MavenProjectReaderTest extends MavenTestCase { " my-target" + ""); - org.apache.maven.project.MavenProject p = readProject(myProjectPom); + MavenModel p = readProject(myProjectPom); - Build build = p.getBuild(); - assertNotNull(build); - assertPathEquals(pathFromBasedir("my-target"), build.getDirectory()); - assertPathEquals(pathFromBasedir("my-target/classes"), build.getOutputDirectory()); - assertPathEquals(pathFromBasedir("my-target/test-classes"), build.getTestOutputDirectory()); + assertPathEquals(pathFromBasedir("my-target"), p.getBuild().getDirectory()); + assertPathEquals(pathFromBasedir("my-target/classes"), p.getBuild().getOutputDirectory()); + assertPathEquals(pathFromBasedir("my-target/test-classes"), p.getBuild().getTestOutputDirectory()); } public void testDoesNotIncludeResourcesWithoutDirectory() throws Exception { @@ -377,11 +355,10 @@ public class MavenProjectReaderTest extends MavenTestCase { " " + ""); - org.apache.maven.project.MavenProject p = readProject(myProjectPom); + MavenModel p = readProject(myProjectPom); - Build build = p.getBuild(); - assertEquals(0, build.getResources().size()); - assertEquals(0, build.getTestResources().size()); + assertEquals(0, p.getBuild().getResources().size()); + assertEquals(0, p.getBuild().getTestResources().size()); } public void testPathsWithProperties() throws Exception { @@ -407,21 +384,21 @@ public class MavenProjectReaderTest extends MavenTestCase { " ${foo}/myTestClasses" + ""); - org.apache.maven.project.MavenProject p = readProject(myProjectPom); + MavenModel p = readProject(myProjectPom); - Build build = p.getBuild(); - assertPathEquals(pathFromBasedir("subDir/mySrc"), build.getSourceDirectory()); - assertPathEquals(pathFromBasedir("subDir/myTestSrc"), build.getTestSourceDirectory()); - assertPathEquals(pathFromBasedir("subDir/myScriptSrc"), build.getScriptSourceDirectory()); - assertEquals(1, build.getResources().size()); - assertResource((Resource)build.getResources().get(0), pathFromBasedir("subDir/myRes"), + assertSize(1, p.getBuild().getSources()); + assertPathEquals(pathFromBasedir("subDir/mySrc"), p.getBuild().getSources().get(0)); + assertSize(1, p.getBuild().getTestSources()); + assertPathEquals(pathFromBasedir("subDir/myTestSrc"), p.getBuild().getTestSources().get(0)); + assertEquals(1, p.getBuild().getResources().size()); + assertResource(p.getBuild().getResources().get(0), pathFromBasedir("subDir/myRes"), false, null, Collections.EMPTY_LIST, Collections.EMPTY_LIST); - assertEquals(1, build.getTestResources().size()); - assertResource((Resource)build.getTestResources().get(0), pathFromBasedir("subDir/myTestRes"), + assertEquals(1, p.getBuild().getTestResources().size()); + assertResource(p.getBuild().getTestResources().get(0), pathFromBasedir("subDir/myTestRes"), false, null, Collections.EMPTY_LIST, Collections.EMPTY_LIST); - assertPathEquals(pathFromBasedir("subDir/myOutput"), build.getDirectory()); - assertPathEquals(pathFromBasedir("subDir/myClasses"), build.getOutputDirectory()); - assertPathEquals(pathFromBasedir("subDir/myTestClasses"), build.getTestOutputDirectory()); + assertPathEquals(pathFromBasedir("subDir/myOutput"), p.getBuild().getDirectory()); + assertPathEquals(pathFromBasedir("subDir/myClasses"), p.getBuild().getOutputDirectory()); + assertPathEquals(pathFromBasedir("subDir/myTestClasses"), p.getBuild().getTestOutputDirectory()); } public void testExpandingProperties() throws Exception { @@ -432,7 +409,7 @@ public class MavenProjectReaderTest extends MavenTestCase { "${prop1}" + "${prop2}"); - org.apache.maven.project.MavenProject p = readProject(myProjectPom); + MavenModel p = readProject(myProjectPom); assertEquals("value1", p.getName()); assertEquals("value2", p.getPackaging()); @@ -446,7 +423,7 @@ public class MavenProjectReaderTest extends MavenTestCase { "${prop1}" + "${prop2}"); - org.apache.maven.project.MavenProject p = readProject(myProjectPom); + MavenModel p = readProject(myProjectPom); assertEquals("value1", p.getName()); assertEquals("value12", p.getPackaging()); @@ -460,7 +437,7 @@ public class MavenProjectReaderTest extends MavenTestCase { "${prop1}" + "${prop2}"); - org.apache.maven.project.MavenProject p = readProject(myProjectPom); + MavenModel p = readProject(myProjectPom); assertEquals("${prop1}", p.getName()); assertEquals("${prop2}", p.getPackaging()); @@ -532,7 +509,7 @@ public class MavenProjectReaderTest extends MavenTestCase { createProjectPom("${java.home}" + "${env." + getEnvVar() + "}"); - org.apache.maven.project.MavenProject p = readProject(myProjectPom); + MavenModel p = readProject(myProjectPom); assertEquals(System.getProperty("java.home"), p.getName()); assertEquals(System.getenv(getEnvVar()), p.getPackaging()); } @@ -559,7 +536,7 @@ public class MavenProjectReaderTest extends MavenTestCase { "
" + ""); - org.apache.maven.project.MavenProject p = readProject(myProjectPom); + MavenModel p = readProject(myProjectPom); assertEquals("value1", p.getName()); assertEquals("${prop2}", p.getPackaging()); } @@ -586,7 +563,7 @@ public class MavenProjectReaderTest extends MavenTestCase { "
" + ""); - org.apache.maven.project.MavenProject p = readProject(myProjectPom, "two"); + MavenModel p = readProject(myProjectPom, "two"); assertEquals("${prop1}", p.getName()); assertEquals("value2", p.getPackaging()); } @@ -608,7 +585,7 @@ public class MavenProjectReaderTest extends MavenTestCase { "" + "${prop}"); - org.apache.maven.project.MavenProject p = readProject(module); + MavenModel p = readProject(module); assertEquals("value", p.getName()); } @@ -629,7 +606,7 @@ public class MavenProjectReaderTest extends MavenTestCase { "" + "${prop}"); - org.apache.maven.project.MavenProject p = readProject(module); + MavenModel p = readProject(module); assertEquals("${prop}", p.getName()); } @@ -651,7 +628,7 @@ public class MavenProjectReaderTest extends MavenTestCase { "" + "${prop}"); - org.apache.maven.project.MavenProject p = readProject(module); + MavenModel p = readProject(module); assertEquals("value", p.getName()); } @@ -683,7 +660,7 @@ public class MavenProjectReaderTest extends MavenTestCase { "" + "${prop}"); - org.apache.maven.project.MavenProject p = readProject(subModule); + MavenModel p = readProject(subModule); assertEquals("value", p.getName()); } @@ -706,7 +683,7 @@ public class MavenProjectReaderTest extends MavenTestCase { "" + "${prop}"); - org.apache.maven.project.MavenProject p = readProject(module); + MavenModel p = readProject(module); assertEquals("value", p.getName()); } @@ -729,7 +706,7 @@ public class MavenProjectReaderTest extends MavenTestCase { "" + "${prop}"); - org.apache.maven.project.MavenProject p = readProject(module); + MavenModel p = readProject(module); assertEquals("value", p.getName()); } @@ -755,7 +732,7 @@ public class MavenProjectReaderTest extends MavenTestCase { "" + "${prop}"); - org.apache.maven.project.MavenProject p = readProject(myProjectPom); + MavenModel p = readProject(myProjectPom); assertEquals("value", p.getName()); } @@ -777,11 +754,11 @@ public class MavenProjectReaderTest extends MavenTestCase { "" + "${prop}"); - org.apache.maven.project.MavenProject p = readProject(module, new MavenProjectReaderProjectLocator() { + MavenModel p = readProject(module, new MavenProjectReaderProjectLocator() { public VirtualFile findProjectFile(MavenId coordinates) { return new MavenId("test", "parent", "1").equals(coordinates) ? parent : null; } - }).nativeMavenProject; + }).mavenModel; assertEquals("value", p.getName()); } @@ -803,8 +780,8 @@ public class MavenProjectReaderTest extends MavenTestCase { "" + "module"); - org.apache.maven.project.MavenProject p = readProject(module); - assertEquals("test:module:1", p.getGroupId() + ":" + p.getArtifactId() + ":" + p.getVersion()); + MavenId id = readProject(module).getMavenId(); + assertEquals("test:module:1", id.getGroupId() + ":" + id.getArtifactId() + ":" + id.getVersion()); } public void testInheritingSettingsFromParentAndAlignCorrectly() throws Exception { @@ -822,7 +799,7 @@ public class MavenProjectReaderTest extends MavenTestCase { " 1" + ""); - org.apache.maven.project.MavenProject p = readProject(module); + MavenModel p = readProject(module); assertPathEquals(pathFromBasedir(module.getParent(), "custom"), p.getBuild().getDirectory()); } @@ -845,7 +822,7 @@ public class MavenProjectReaderTest extends MavenTestCase { " 1" + ""); - org.apache.maven.project.MavenProject p = readProject(module); + MavenModel p = readProject(module); assertPathEquals(pathFromBasedir(module.getParent(), "subDir/custom"), p.getBuild().getDirectory()); } @@ -873,7 +850,7 @@ public class MavenProjectReaderTest extends MavenTestCase { " 1" + ""); - org.apache.maven.project.MavenProject p = readProject(module, "one"); + MavenModel p = readProject(module, "one"); assertPathEquals(pathFromBasedir(module.getParent(), "subDir/custom"), p.getBuild().getDirectory()); } @@ -886,7 +863,7 @@ public class MavenProjectReaderTest extends MavenTestCase { " " + "
"); - org.apache.maven.project.MavenProject mavenProject = readProject(myProjectPom); + MavenModel mavenProject = readProject(myProjectPom); assertEquals("${prop}", mavenProject.getName()); mavenProject = readProject(myProjectPom, "one"); @@ -902,7 +879,7 @@ public class MavenProjectReaderTest extends MavenTestCase { " " + "
"); - org.apache.maven.project.MavenProject mavenProject = readProject(myProjectPom); + MavenModel mavenProject = readProject(myProjectPom); assertEquals("${prop}", mavenProject.getName()); mavenProject = readProject(myProjectPom, "one"); @@ -920,7 +897,7 @@ public class MavenProjectReaderTest extends MavenTestCase { "
" + ""); - org.apache.maven.project.MavenProject mavenProject = readProject(myProjectPom); + MavenModel mavenProject = readProject(myProjectPom); assertEquals("${prop}", mavenProject.getName()); mavenProject = readProject(myProjectPom, "one"); @@ -943,7 +920,7 @@ public class MavenProjectReaderTest extends MavenTestCase { " 1" + ""); - org.apache.maven.project.MavenProject p = readProject(module, "one"); + MavenModel p = readProject(module, "one"); assertEquals("module-2", p.getBuild().getFinalName()); } @@ -967,7 +944,7 @@ public class MavenProjectReaderTest extends MavenTestCase { " 1" + ""); - org.apache.maven.project.MavenProject p = readProject(module, "one"); + MavenModel p = readProject(module, "one"); assertEquals("xxx", p.getBuild().getFinalName()); } @@ -1000,9 +977,9 @@ public class MavenProjectReaderTest extends MavenTestCase { "
" + ""); - org.apache.maven.project.MavenProject p = readProject(module); - assertOrderedElementsAreEqual(ContainerUtil.map(p.getModel().getProfiles(), new Function() { - public Object fun(Profile profile) { + MavenModel p = readProject(module); + assertOrderedElementsAreEqual(ContainerUtil.map(p.getProfiles(), new Function() { + public Object fun(MavenProfile profile) { return profile.getId(); } }), "profileFromChild", "profileFromParent"); @@ -1016,13 +993,13 @@ public class MavenProjectReaderTest extends MavenTestCase { "" + " " + " profile" + - " parent" + + " parent" + " " + ""); VirtualFile parentProfiles = createProfilesXml("" + " profile" + - " parentProfiles" + + " parentProfiles" + ""); VirtualFile module = createModulePom("module", @@ -1039,27 +1016,27 @@ public class MavenProjectReaderTest extends MavenTestCase { "" + " " + " profile" + - " pom" + + " pom" + " " + ""); updateSettingsXml("" + " " + " profile" + - " settings" + + " settings" + " " + ""); VirtualFile profiles = createProfilesXml("module", "" + " profile" + - " profiles" + + " profiles" + ""); - org.apache.maven.project.MavenProject p = readProject(module); - assertEquals(1, p.getModel().getProfiles().size()); - assertEquals("pom", p.getModel().getProfiles().get(0).getProperties().getProperty("prop")); - assertEquals("pom", p.getModel().getProfiles().get(0).getSource()); + MavenModel p = readProject(module); + assertEquals(1, p.getProfiles().size()); + assertEquals("pom", p.getProfiles().get(0).getModules().get(0)); + assertEquals("pom", p.getProfiles().get(0).getSource()); createModulePom("module", "test" + @@ -1073,32 +1050,32 @@ public class MavenProjectReaderTest extends MavenTestCase { ""); p = readProject(module); - assertEquals(1, p.getModel().getProfiles().size()); - assertEquals("profiles", p.getModel().getProfiles().get(0).getProperties().getProperty("prop")); - assertEquals("profiles.xml", p.getModel().getProfiles().get(0).getSource()); + assertEquals(1, p.getProfiles().size()); + assertEquals("profiles", p.getProfiles().get(0).getModules().get(0)); + assertEquals("profiles.xml", p.getProfiles().get(0).getSource()); profiles.delete(this); p = readProject(module); - assertEquals(1, p.getModel().getProfiles().size()); - assertEquals("parent", p.getModel().getProfiles().get(0).getProperties().getProperty("prop")); - assertEquals("pom", p.getModel().getProfiles().get(0).getSource()); + assertEquals(1, p.getProfiles().size()); + assertEquals("parent", p.getProfiles().get(0).getModules().get(0)); + assertEquals("pom", p.getProfiles().get(0).getSource()); createProjectPom("test" + "parent" + "1"); p = readProject(module); - assertEquals(1, p.getModel().getProfiles().size()); - assertEquals("parentProfiles", p.getModel().getProfiles().get(0).getProperties().getProperty("prop")); - assertEquals("profiles.xml", p.getModel().getProfiles().get(0).getSource()); + assertEquals(1, p.getProfiles().size()); + assertEquals("parentProfiles", p.getProfiles().get(0).getModules().get(0)); + assertEquals("profiles.xml", p.getProfiles().get(0).getSource()); parentProfiles.delete(null); p = readProject(module); - assertEquals(1, p.getModel().getProfiles().size()); - assertEquals("settings", p.getModel().getProfiles().get(0).getProperties().getProperty("prop")); - assertEquals("settings.xml", p.getModel().getProfiles().get(0).getSource()); + assertEquals(1, p.getProfiles().size()); + assertEquals("settings", p.getProfiles().get(0).getModules().get(0)); + assertEquals("settings.xml", p.getProfiles().get(0).getSource()); } public void testActivatingProfilesByOS() throws Exception { @@ -1155,16 +1132,13 @@ public class MavenProjectReaderTest extends MavenTestCase { } public void testActivatingProfilesByProperty() throws Exception { - System.setProperty("maven.test.property", "foo"); - MavenEmbedderWrapper.resetSystemPropertiesCacheInTests(); - createProjectPom("" + " " + " one" + " " + " " + - " maven.test.property" + - " foo" + + " os.name" + + " " + System.getProperty("os.name") + "" + " " + " " + " " + @@ -1172,8 +1146,8 @@ public class MavenProjectReaderTest extends MavenTestCase { " two" + " " + " " + - " maven.test.property" + - " bar" + + " os.name" + + " xxx" + " " + " " + "
" + @@ -1411,10 +1385,10 @@ public class MavenProjectReaderTest extends MavenTestCase { assertActiveProfiles("default", "profiles"); } - private org.apache.maven.project.MavenProject readProject(VirtualFile file, String... profiles) { + private MavenModel readProject(VirtualFile file, String... profiles) { MavenProjectReaderResult readResult = readProject(file, new NullProjectLocator(), profiles); assertProblems(readResult); - return readResult.nativeMavenProject; + return readResult.mavenModel; } private MavenProjectReaderResult readProject(VirtualFile file, @@ -1427,27 +1401,24 @@ public class MavenProjectReaderTest extends MavenTestCase { return result; } - private void assertParent(org.apache.maven.project.MavenProject p, + private void assertParent(MavenModel p, String groupId, String artifactId, - String version, - String relativePath) { - Parent parent = p.getModel().getParent(); - assertNotNull(parent); + String version) { + MavenId parent = p.getParent().getMavenId(); assertEquals(groupId, parent.getGroupId()); assertEquals(artifactId, parent.getArtifactId()); assertEquals(version, parent.getVersion()); - assertEquals(relativePath, parent.getRelativePath()); } - private void assertResource(Resource resource, + private void assertResource(MavenResource resource, String dir, boolean filtered, String targetPath, List includes, List excludes) { assertPathEquals(dir, resource.getDirectory()); - assertEquals(filtered, resource.isFiltering()); + assertEquals(filtered, resource.isFiltered()); assertPathEquals(targetPath, resource.getTargetPath()); assertOrderedElementsAreEqual(resource.getIncludes(), includes); assertOrderedElementsAreEqual(resource.getExcludes(), excludes); @@ -1466,9 +1437,10 @@ public class MavenProjectReaderTest extends MavenTestCase { } private void assertActiveProfiles(List explicitProfiles, String... expected) { - org.apache.maven.project.MavenProject p = readProject(myProjectPom, explicitProfiles.toArray(new String[explicitProfiles.size()])); - assertUnorderedElementsAreEqual(ContainerUtil.map((List)p.getActiveProfiles(), new Function() { - public String fun(Profile profile) { + MavenProjectReaderResult result = + readProject(myProjectPom, new NullProjectLocator(), explicitProfiles.toArray(new String[explicitProfiles.size()])); + assertUnorderedElementsAreEqual(ContainerUtil.map(result.activatedProfiles, new Function() { + public String fun(MavenProfile profile) { return profile.getId(); } }), expected); diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectTest.java index 700ee3a1a070..a393b9b226df 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectTest.java @@ -18,11 +18,15 @@ package org.jetbrains.idea.maven.project; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VirtualFile; -import org.jdom.Element; import org.jetbrains.idea.maven.MavenImportingTestCase; +import org.jetbrains.idea.maven.model.MavenArtifactNode; +import org.jetbrains.idea.maven.model.MavenPlugin; +import org.jetbrains.idea.maven.model.MavenRemoteRepository; import org.jetbrains.idea.maven.utils.MavenJDOMUtil; +import java.io.File; import java.util.List; +import java.util.Map; public class MavenProjectTest extends MavenImportingTestCase { public void testCollectingPlugins() throws Exception { @@ -51,7 +55,7 @@ public class MavenProjectTest extends MavenImportingTestCase { assertDeclaredPlugins(p("group1", "id1"), p("group1", "id2"), p("group2", "id1")); } - + public void testPluginsContainDefaultPlugins() throws Exception { importProject("test" + "project" + @@ -616,11 +620,12 @@ public class MavenProjectTest extends MavenImportingTestCase { assertEquals("central", result.get(2).getId()); } - public void testStrippingDownMavenModel() throws Exception { + public void testMavenModelMap() throws Exception { importProject("test" + "project" + "1" + "" + + " foo" + " " + " " + " group1" + @@ -630,8 +635,15 @@ public class MavenProjectTest extends MavenImportingTestCase { " " + ""); - assertTrue(getMavenProject().getMavenModel().getBuild().getPlugins().isEmpty()); - assertTrue(getMavenProject().getMavenModel().getBuild().getPluginsAsMap().isEmpty()); + MavenProject p = getMavenProject(); + Map map = p.getModelMap(); + + assertEquals("test", map.get("groupId")); + assertTrue(map.get("build"), map.get("build").startsWith("org.apache.maven.model.Build@")); + assertEquals("foo", map.get("build.finalName")); + assertEquals(new File(p.getDirectory(), "target").toString(), map.get("build.directory")); + assertEquals(null, map.get("build.plugins")); + assertEquals(null, map.get("build.pluginMap")); } public void testDependenciesTree() throws Exception { diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectsManagerTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectsManagerTest.java index 4d759370bde5..2e7b7544fc6d 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectsManagerTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectsManagerTest.java @@ -23,6 +23,7 @@ import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.idea.maven.MavenImportingTestCase; +import org.jetbrains.idea.maven.facade.NativeMavenProjectHolder; import org.jetbrains.idea.maven.importing.MavenRootModelAdapter; import java.io.File; @@ -816,7 +817,7 @@ public class MavenProjectsManagerTest extends MavenImportingTestCase { myProjectsManager.addProjectsTreeListener(new MavenProjectsTree.ListenerAdapter() { @Override public void projectResolved(Pair projectWithChanges, - org.apache.maven.project.MavenProject nativeMavenProject, Object message) { + NativeMavenProjectHolder nativeMavenProject, Object message) { called[0] = true; } }); diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectsTreeReadingTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectsTreeReadingTest.java index 48f9ae4e156a..2f06395edd15 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectsTreeReadingTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectsTreeReadingTest.java @@ -20,9 +20,11 @@ import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.Function; +import org.jetbrains.idea.maven.facade.NativeMavenProjectHolder; import org.jetbrains.idea.maven.utils.MavenUtil; import java.io.File; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -582,14 +584,14 @@ public class MavenProjectsTreeReadingTest extends MavenProjectsTreeTestCase { myTree.addListener(listener); MavenProject project = myTree.findProject(myProjectPom); - MavenEmbeddersManager embeddersManager = new MavenEmbeddersManager(getMavenGeneralSettings()); - final org.apache.maven.project.MavenProject[] nativeProject = new org.apache.maven.project.MavenProject[1]; + MavenEmbeddersManager embeddersManager = new MavenEmbeddersManager(myProject); + final List nativeProject = new ArrayList(); try { myTree.addListener(new MavenProjectsTree.ListenerAdapter() { @Override public void projectResolved(Pair projectWithChanges, - org.apache.maven.project.MavenProject nativeMavenProject, Object message) { - nativeProject[0] = nativeMavenProject; + NativeMavenProjectHolder nativeMavenProject, Object message) { + nativeProject.add(nativeMavenProject); } }); myTree.resolve(project, @@ -604,8 +606,9 @@ public class MavenProjectsTreeReadingTest extends MavenProjectsTreeTestCase { } assertEquals("resolved: project ", listener.log); - assertNotNull(nativeProject[0]); assertTrue(project.hasReadingProblems()); + assertSize(1, nativeProject); + assertNull(nativeProject.get(0)); } public void testDoNotUpdateChildAfterParentWasResolved() throws Exception { @@ -631,13 +634,13 @@ public class MavenProjectsTreeReadingTest extends MavenProjectsTreeTestCase { MavenProject parentProject = myTree.findProject(myProjectPom); - MavenEmbeddersManager embeddersManager = new MavenEmbeddersManager(getMavenGeneralSettings()); + MavenEmbeddersManager embeddersManager = new MavenEmbeddersManager(myProject); try { - final org.apache.maven.project.MavenProject[] nativeProject = new org.apache.maven.project.MavenProject[1]; + final NativeMavenProjectHolder[] nativeProject = new NativeMavenProjectHolder[1]; myTree.addListener(new MavenProjectsTree.ListenerAdapter() { @Override public void projectResolved(Pair projectWithChanges, - org.apache.maven.project.MavenProject nativeMavenProject, + NativeMavenProjectHolder nativeMavenProject, Object message) { nativeProject[0] = nativeMavenProject; } @@ -649,8 +652,7 @@ public class MavenProjectsTreeReadingTest extends MavenProjectsTreeTestCase { EMPTY_MAVEN_PROCESS, null); myTree.resolvePlugins(parentProject, nativeProject[0], embeddersManager, NULL_MAVEN_CONSOLE, EMPTY_MAVEN_PROCESS); - myTree.resolveFolders(parentProject, getMavenGeneralSettings(), getMavenImporterSettings(), embeddersManager, NULL_MAVEN_CONSOLE, - EMPTY_MAVEN_PROCESS, null); + myTree.resolveFolders(parentProject, getMavenImporterSettings(), embeddersManager, NULL_MAVEN_CONSOLE, EMPTY_MAVEN_PROCESS, null); } finally { embeddersManager.release(); @@ -1821,7 +1823,7 @@ public class MavenProjectsTreeReadingTest extends MavenProjectsTreeTestCase { MavenProject parentProject = myTree.findProject(myProjectPom); - MavenEmbeddersManager embeddersManager = new MavenEmbeddersManager(getMavenGeneralSettings()); + MavenEmbeddersManager embeddersManager = new MavenEmbeddersManager(myProject); try { myTree.resolve(parentProject, getMavenGeneralSettings(), embeddersManager, NULL_MAVEN_CONSOLE, EMPTY_MAVEN_PROCESS, null); } @@ -1894,7 +1896,7 @@ public class MavenProjectsTreeReadingTest extends MavenProjectsTreeTestCase { updateAll(myProjectPom); - MavenEmbeddersManager embeddersManager = new MavenEmbeddersManager(getMavenGeneralSettings()); + MavenEmbeddersManager embeddersManager = new MavenEmbeddersManager(myProject); try { myTree.resolve(myTree.getRootProjects().get(0), getMavenGeneralSettings(), @@ -2019,7 +2021,7 @@ public class MavenProjectsTreeReadingTest extends MavenProjectsTreeTestCase { assertPathEquals(pathFromBasedir("my-target/classes"), project.getOutputDirectory()); assertPathEquals(pathFromBasedir("my-target/test-classes"), project.getTestOutputDirectory()); - MavenEmbeddersManager embeddersManager = new MavenEmbeddersManager(getMavenGeneralSettings()); + MavenEmbeddersManager embeddersManager = new MavenEmbeddersManager(myProject); try { myTree.resolve(project, getMavenGeneralSettings(), embeddersManager, NULL_MAVEN_CONSOLE, EMPTY_MAVEN_PROCESS, null); } @@ -2056,7 +2058,7 @@ public class MavenProjectsTreeReadingTest extends MavenProjectsTreeTestCase { @Override public void projectResolved(Pair projectWithChanges, - org.apache.maven.project.MavenProject nativeMavenProject, + NativeMavenProjectHolder nativeMavenProject, Object message) { log += "resolved: " + projectWithChanges.first.getMavenId().getArtifactId() + " "; } diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/wizards/MavenModuleBuilderTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/wizards/MavenModuleBuilderTest.java index 0bc3bf083d10..f2cde0eb915d 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/wizards/MavenModuleBuilderTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/wizards/MavenModuleBuilderTest.java @@ -23,12 +23,11 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.idea.maven.MavenImportingTestCase; +import org.jetbrains.idea.maven.model.MavenArchetype; +import org.jetbrains.idea.maven.model.MavenId; import org.jetbrains.idea.maven.project.MavenProjectsManager; -import org.jetbrains.idea.maven.indices.ArchetypeInfo; import org.jetbrains.idea.maven.project.MavenProject; -import org.jetbrains.idea.maven.project.MavenId; -import java.io.File; import java.util.List; public class MavenModuleBuilderTest extends MavenImportingTestCase { @@ -77,7 +76,7 @@ public class MavenModuleBuilderTest extends MavenImportingTestCase { public void testCreatingFromArchetype() throws Exception { if (!hasMavenInstallation()) return; - setArchetype(new ArchetypeInfo("org.apache.maven.archetypes", "maven-archetype-quickstart", "1.0", null, null)); + setArchetype(new MavenArchetype("org.apache.maven.archetypes", "maven-archetype-quickstart", "1.0", null, null)); MavenId id = new MavenId("org.foo", "module", "1.0"); createNewModule(id); @@ -220,7 +219,7 @@ public class MavenModuleBuilderTest extends MavenImportingTestCase { setModuleNameAndRoot("module", getProjectPath() + "/module"); setParentProject(myProjectPom); setInheritedOptions(true, true); - setArchetype(new ArchetypeInfo("org.apache.maven.archetypes", "maven-archetype-quickstart", "1.0", null, null)); + setArchetype(new MavenArchetype("org.apache.maven.archetypes", "maven-archetype-quickstart", "1.0", null, null)); createNewModule(new MavenId("org.foo", "module", "1.0")); assertEquals(" changeListList = committedChangesProvider.getCommittedChanges(committedChangesProvider.createDefaultSettings(), new SvnRepositoryLocation(myRepoUrl), 0); - checkList(changeListList, 2, new Data[] {new Data(absPath(d1), FileStatus.MODIFIED, "- moved from ..\\d1"), + checkList(changeListList, 2, new Data[] {new Data(absPath(d1), FileStatus.MODIFIED, "- moved from .." + File.separatorChar + "d1"), new Data(oldPath, FileStatus.DELETED, null)}); } @@ -159,7 +159,7 @@ public class SvnCommittedViewTest extends SvnTestCase { final List changeListList = committedChangesProvider.getCommittedChanges(committedChangesProvider.createDefaultSettings(), new SvnRepositoryLocation(myRepoUrl), 0); - checkList(changeListList, 2, new Data[] {new Data(absPath(d1), FileStatus.MODIFIED, "- moved from ..\\d1"), + checkList(changeListList, 2, new Data[] {new Data(absPath(d1), FileStatus.MODIFIED, "- moved from .." + File.separatorChar + "d1"), new Data(oldPath, FileStatus.DELETED, null), new Data(absPath(f11), FileStatus.MODIFIED, "- moved from " + oldF11Path)}); } @@ -270,7 +270,7 @@ public class SvnCommittedViewTest extends SvnTestCase { } } - private String printChanges(final Data data, final Collection changes) { + private static String printChanges(final Data data, final Collection changes) { final StringBuilder sb = new StringBuilder("Data: ").append(data.myLocalPath).append(" exists: "). append(new File(data.myLocalPath).exists()).append(" Changes: "); for (Change change : changes) { diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnDeleteTest.java b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnDeleteTest.java index b71a2e9b3a68..76766634ab4d 100644 --- a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnDeleteTest.java +++ b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnDeleteTest.java @@ -12,6 +12,7 @@ import org.jetbrains.idea.svn.integrate.AlienDirtyScope; import org.junit.Assert; import org.junit.Test; +import java.io.File; import java.util.Collection; import java.util.List; @@ -27,11 +28,11 @@ public class SvnDeleteTest extends SvnTestCase { VirtualFile dir = createDirInCommand(myWorkingCopyDir, "child"); createFileInCommand(dir, "a.txt", "content"); - verify(runSvn("status"), "A child", "A child\\a.txt"); + verify(runSvn("status"), "A child", "A child" + File.separatorChar + "a.txt"); checkin(); deleteFileInCommand(dir); - verify(runSvn("status"), "D child", "D child\\a.txt"); + verify(runSvn("status"), "D child", "D child" + File.separatorChar + "a.txt"); LocalFileSystem.getInstance().refresh(false); @@ -49,4 +50,4 @@ public class SvnDeleteTest extends SvnTestCase { final Collection changes = lists.get(0).getChanges(); Assert.assertEquals(2, changes.size()); } -} \ No newline at end of file +} diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnRenameTest.java b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnRenameTest.java index e82d0cade4bf..c5ab4a63da75 100644 --- a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnRenameTest.java +++ b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnRenameTest.java @@ -26,7 +26,7 @@ import java.util.List; * @author yole */ public class SvnRenameTest extends SvnTestCase { - @NonNls private static final String LOG_SEPARATOR = "------------------------------------------------------------------------\r\n"; + @NonNls private static final String LOG_SEPARATOR = "------------------------------------------------------------------------\n"; @Test public void testSimpleRename() throws Exception { @@ -59,7 +59,7 @@ public class SvnRenameTest extends SvnTestCase { final VirtualFile dir = createDirInCommand(myWorkingCopyDir, "child"); createFileInCommand(dir, "a.txt", "content"); renameFileInCommand(dir, "newchild"); - verify(runSvn("status"), "A newchild", "A newchild\\a.txt"); + verify(runSvn("status"), "A newchild", "A newchild" + File.separatorChar + "a.txt"); } // IDEADEV-8091 @@ -81,7 +81,7 @@ public class SvnRenameTest extends SvnTestCase { renameFileInCommand(child, "childnew"); final ProcessOutput result = runSvn("status"); - verify(result, "D child", "D child\\grandChild", "D child\\grandChild\\b.txt", "D child\\a.txt", "A + childnew"); + verify(result, "D child", "D child" + File.separatorChar + "grandChild", "D child" + File.separatorChar + "grandChild" + File.separatorChar + "b.txt", "D child" + File.separatorChar + "a.txt", "A + childnew"); LocalFileSystem.getInstance().refresh(false); // wait for end of refresh operations initiated from SvnFileSystemListener final ChangeListManager changeListManager = ChangeListManager.getInstance(myProject); @@ -90,9 +90,9 @@ public class SvnRenameTest extends SvnTestCase { Assert.assertEquals(4, changes.size()); sortChanges(changes); verifyChange(changes.get(0), "child", "childnew"); - verifyChange(changes.get(1), "child\\a.txt", "childnew\\a.txt"); - verifyChange(changes.get(2), "child\\grandChild", "childnew\\grandChild"); - verifyChange(changes.get(3), "child\\grandChild\\b.txt", "childnew\\grandChild\\b.txt"); + verifyChange(changes.get(1), "child" + File.separatorChar + "a.txt", "childnew" + File.separatorChar + "a.txt"); + verifyChange(changes.get(2), "child" + File.separatorChar + "grandChild", "childnew" + File.separatorChar + "grandChild"); + verifyChange(changes.get(3), "child" + File.separatorChar + "grandChild" + File.separatorChar + "b.txt", "childnew" + File.separatorChar + "grandChild" + File.separatorChar + "b.txt"); VirtualFile oldChild = myWorkingCopyDir.findChild("child"); Assert.assertEquals(FileStatus.DELETED, changeListManager.getStatus(oldChild)); @@ -159,8 +159,8 @@ public class SvnRenameTest extends SvnTestCase { final List changes = new ArrayList(changeListManager.getDefaultChangeList().getChanges()); Assert.assertEquals(listToString(changes), 2, changes.size()); sortChanges(changes); - verifyChange(changes.get(0), "child\\grandChild", "grandChild"); - verifyChange(changes.get(1), "child\\grandChild\\a.txt", "grandChild\\a.txt"); + verifyChange(changes.get(0), "child" + File.separatorChar + "grandChild", "grandChild"); + verifyChange(changes.get(1), "child" + File.separatorChar + "grandChild" + File.separatorChar + "a.txt", "grandChild" + File.separatorChar + "a.txt"); } private String listToString(final List changes) { @@ -226,8 +226,8 @@ public class SvnRenameTest extends SvnTestCase { renameFileInCommand(f, "anew.txt"); renameFileInCommand(child, "newchild"); - verifySorted(runSvn("status"), "A + newchild", "A + newchild\\anew.txt", - "D child", "D child\\a.txt", "D child\\grandChild", "D child\\grandChild\\b.txt", "D + newchild\\a.txt"); + verifySorted(runSvn("status"), "A + newchild", "A + newchild" + File.separatorChar + "anew.txt", + "D child", "D child" + File.separatorChar + "a.txt", "D child" + File.separatorChar + "grandChild", "D child" + File.separatorChar + "grandChild" + File.separatorChar + "b.txt", "D + newchild" + File.separatorChar + "a.txt"); final ChangeListManager changeListManager = ChangeListManager.getInstance(myProject); LocalFileSystem.getInstance().refresh(false); // wait for end of refresh operations initiated from SvnFileSystemListener @@ -283,7 +283,7 @@ public class SvnRenameTest extends SvnTestCase { checkin(); undo(); - verifySorted(runSvn("status"), "A + parent1\\child", "D parent2\\child", "D parent2\\child\\a.txt"); + verifySorted(runSvn("status"), "A + parent1" + File.separatorChar + "child", "D parent2" + File.separatorChar + "child", "D parent2" + File.separatorChar + "child" + File.separatorChar + "a.txt"); }*/ @Test @@ -291,7 +291,7 @@ public class SvnRenameTest extends SvnTestCase { enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD); final VirtualFile file = createFileInCommand(myWorkingCopyDir, "a.txt", "A"); moveToNewPackage(file, "child"); - verifySorted(runSvn("status"), "A child", "A child\\a.txt"); + verifySorted(runSvn("status"), "A child", "A child" + File.separatorChar + "a.txt"); } @Test @@ -300,7 +300,7 @@ public class SvnRenameTest extends SvnTestCase { final VirtualFile file = createFileInCommand(myWorkingCopyDir, "a.txt", "A"); checkin(); moveToNewPackage(file, "child"); - verifySorted(runSvn("status"), "A child", "A + child\\a.txt", "D a.txt"); + verifySorted(runSvn("status"), "A child", "A + child" + File.separatorChar + "a.txt", "D a.txt"); } private void moveToNewPackage(final VirtualFile file, final String packageName) throws Throwable { diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnTestCase.java b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnTestCase.java index 16acb4db96ab..fb12e414c72f 100644 --- a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnTestCase.java +++ b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnTestCase.java @@ -19,6 +19,7 @@ import com.intellij.openapi.vcs.changes.*; import com.intellij.openapi.vcs.changes.pending.MockChangeListManagerGate; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.testFramework.AbstractVcsTestCase; +import com.intellij.testFramework.PlatformTestCase; import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory; import com.intellij.testFramework.fixtures.TempDirTestFixture; import com.intellij.testFramework.vcs.MockChangelistBuilder; @@ -40,6 +41,10 @@ public abstract class SvnTestCase extends AbstractVcsTestCase { private ChangeListManagerGate myGate; protected AtomicSectionsAware myRefreshCopiesStub; + protected SvnTestCase() { + PlatformTestCase.initPlatformLangPrefix(); + } + @Before public void setUp() throws Exception { final IdeaTestFixtureFactory fixtureFactory = IdeaTestFixtureFactory.getFixtureFactory(); diff --git a/xml/impl/src/com/intellij/codeInsight/template/zencoding/XmlZenCodingInterpreter.java b/xml/impl/src/com/intellij/codeInsight/template/zencoding/XmlZenCodingInterpreter.java index 21274dd639f9..5ad53eec3a94 100644 --- a/xml/impl/src/com/intellij/codeInsight/template/zencoding/XmlZenCodingInterpreter.java +++ b/xml/impl/src/com/intellij/codeInsight/template/zencoding/XmlZenCodingInterpreter.java @@ -17,6 +17,7 @@ package com.intellij.codeInsight.template.zencoding; import com.intellij.codeInsight.template.CustomTemplateCallback; import com.intellij.codeInsight.template.impl.TemplateImpl; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.util.Pair; @@ -306,21 +307,19 @@ class XmlZenCodingInterpreter { private static void invokeTemplate(TemplateToken token, final CustomTemplateCallback callback, - int numberInIteration, + final int numberInIteration, String filter) { if (token instanceof XmlTemplateToken && token.getTemplate() != null) { XmlTemplateToken xmlTemplateToken = (XmlTemplateToken)token; - List> attr2value = new ArrayList>(xmlTemplateToken.getAttribute2Value()); + final List> attr2value = new ArrayList>(xmlTemplateToken.getAttribute2Value()); TemplateImpl modifiedTemplate = token.getTemplate().copy(); - XmlTag tag = xmlTemplateToken.getTag(); + final XmlTag tag = xmlTemplateToken.getTag(); if (tag != null) { - for (Iterator> iterator = attr2value.iterator(); iterator.hasNext();) { - Pair pair = iterator.next(); - if (tag.getAttribute(pair.first) != null) { - tag.setAttribute(pair.first, ZenCodingUtil.getValue(pair, numberInIteration)); - iterator.remove(); + ApplicationManager.getApplication().runWriteAction(new Runnable() { + public void run() { + setAttributeValues(tag, attr2value, numberInIteration); } - } + }); String s = filterXml(tag, callback, filter); assert s != null; if (HtmlUtil.isHtmlBlockTagL(tag.getName())) { @@ -350,6 +349,16 @@ class XmlZenCodingInterpreter { } } + private static void setAttributeValues(XmlTag tag, List> attr2value, int numberInIteration) { + for (Iterator> iterator = attr2value.iterator(); iterator.hasNext();) { + Pair pair = iterator.next(); + if (tag.getAttribute(pair.first) != null) { + tag.setAttribute(pair.first, ZenCodingUtil.getValue(pair, numberInIteration)); + iterator.remove(); + } + } + } + @Nullable private static String filterXml(XmlTag tag, CustomTemplateCallback callback, String filterSuffix) { PsiElement context = callback.getContext(); diff --git a/xml/impl/src/com/intellij/codeInsight/template/zencoding/XmlZenCodingTemplate.java b/xml/impl/src/com/intellij/codeInsight/template/zencoding/XmlZenCodingTemplate.java index 080397ba94f5..27bff77fc33b 100644 --- a/xml/impl/src/com/intellij/codeInsight/template/zencoding/XmlZenCodingTemplate.java +++ b/xml/impl/src/com/intellij/codeInsight/template/zencoding/XmlZenCodingTemplate.java @@ -20,6 +20,7 @@ import com.intellij.codeInsight.template.CustomTemplateCallback; import com.intellij.codeInsight.template.TemplateInvokationListener; import com.intellij.codeInsight.template.impl.TemplateImpl; import com.intellij.lang.xml.XMLLanguage; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.StdFileTypes; @@ -191,7 +192,7 @@ public class XmlZenCodingTemplate extends ZenCodingTemplate { if (template == null && !isXML11ValidQName(prefix)) { return null; } - XmlTemplateToken token = parseSelectors(key); + final XmlTemplateToken token = parseSelectors(key); if (token == null) { return null; } @@ -203,13 +204,17 @@ public class XmlZenCodingTemplate extends ZenCodingTemplate { } assert prefix.equals(token.getKey()); token.setTemplate(template); - XmlTag tag = parseXmlTagInTemplate(template.getString(), callback, true); + final XmlTag tag = parseXmlTagInTemplate(template.getString(), callback, true); if (token.getAttribute2Value().size() > 0 && tag == null) { return null; } if (tag != null) { if (!XmlZenCodingInterpreter.containsAttrsVar(template) && token.getAttribute2Value().size() > 0) { - addMissingAttributes(tag, token.getAttribute2Value()); + ApplicationManager.getApplication().runWriteAction(new Runnable() { + public void run() { + addMissingAttributes(tag, token.getAttribute2Value()); + } + }); } token.setTag(tag); }