Search in sources :

Example 36 with Function

use of com.intellij.util.Function in project intellij-community by JetBrains.

the class TestObject method addClassesListToJavaParameters.

protected <T> void addClassesListToJavaParameters(Collection<? extends T> elements, Function<T, String> nameFunction, String packageName, boolean createTempFile, JavaParameters javaParameters) throws CantRunException {
    try {
        if (createTempFile) {
            createTempFiles(javaParameters);
        }
        final Map<Module, List<String>> perModule = forkPerModule() ? new TreeMap<>((o1, o2) -> StringUtil.compare(o1.getName(), o2.getName(), true)) : null;
        final List<String> testNames = new ArrayList<>();
        for (final T element : elements) {
            final String name = nameFunction.fun(element);
            if (name == null) {
                continue;
            }
            final PsiElement psiElement = retrievePsiElement(element);
            if (perModule != null && psiElement != null) {
                final Module module = ModuleUtilCore.findModuleForPsiElement(psiElement);
                if (module != null) {
                    List<String> list = perModule.get(module);
                    if (list == null) {
                        list = new ArrayList<>();
                        perModule.put(module, list);
                    }
                    list.add(name);
                }
            } else {
                testNames.add(name);
            }
        }
        final JUnitConfiguration.Data data = getConfiguration().getPersistentData();
        if (perModule != null) {
            for (List<String> perModuleClasses : perModule.values()) {
                Collections.sort(perModuleClasses);
                testNames.addAll(perModuleClasses);
            }
        } else if (JUnitConfiguration.TEST_PACKAGE.equals(data.TEST_OBJECT)) {
            //sort tests in FQN order
            Collections.sort(testNames);
        }
        final String category = JUnitConfiguration.TEST_CATEGORY.equals(data.TEST_OBJECT) ? data.getCategory() : "";
        JUnitStarter.printClassesList(testNames, packageName, category, myTempFile);
        writeClassesPerModule(packageName, javaParameters, perModule);
    } catch (IOException e) {
        LOG.error(e);
    }
}
Also used : java.util(java.util) CharsetToolkit(com.intellij.openapi.vfs.CharsetToolkit) PathsList(com.intellij.util.PathsList) RuntimeConfigurationException(com.intellij.execution.configurations.RuntimeConfigurationException) OSProcessHandler(com.intellij.execution.process.OSProcessHandler) RefactoringElementListener(com.intellij.refactoring.listeners.RefactoringElementListener) TestEngine(org.junit.platform.engine.TestEngine) NonNls(org.jetbrains.annotations.NonNls) JupiterTestEngine(org.junit.jupiter.engine.JupiterTestEngine) TestBySource(com.intellij.execution.junit.testDiscovery.TestBySource) ProgramParametersUtil(com.intellij.execution.util.ProgramParametersUtil) ExecutionEnvironment(com.intellij.execution.runners.ExecutionEnvironment) ParametersList(com.intellij.execution.configurations.ParametersList) SourceScope(com.intellij.execution.testframework.SourceScope) RepeatCount(com.intellij.rt.execution.junit.RepeatCount) SearchForTestsTask(com.intellij.execution.testframework.SearchForTestsTask) JUnit5IdeaTestRunner(com.intellij.junit5.JUnit5IdeaTestRunner) Project(com.intellij.openapi.project.Project) FileUtil(com.intellij.openapi.util.io.FileUtil) Logger(com.intellij.openapi.diagnostic.Logger) Module(com.intellij.openapi.module.Module) IDEAJUnitListener(com.intellij.rt.execution.junit.IDEAJUnitListener) ProcessTerminatedListener(com.intellij.execution.process.ProcessTerminatedListener) ModuleUtilCore(com.intellij.openapi.module.ModuleUtilCore) TestsByChanges(com.intellij.execution.junit.testDiscovery.TestsByChanges) KillableColoredProcessHandler(com.intellij.execution.process.KillableColoredProcessHandler) StringUtil(com.intellij.openapi.util.text.StringUtil) ForkedDebuggerHelper(com.intellij.rt.execution.testFrameworks.ForkedDebuggerHelper) JUnitException(org.junit.platform.commons.JUnitException) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) JavaParametersUtil(com.intellij.execution.util.JavaParametersUtil) IOException(java.io.IOException) File(java.io.File) VintageTestEngine(org.junit.vintage.engine.VintageTestEngine) com.intellij.execution(com.intellij.execution) Nullable(org.jetbrains.annotations.Nullable) Function(com.intellij.util.Function) JavaParameters(com.intellij.execution.configurations.JavaParameters) TestSearchScope(com.intellij.execution.testframework.TestSearchScope) com.intellij.psi(com.intellij.psi) PathUtil(com.intellij.util.PathUtil) JUnitPlatform(org.junit.platform.runner.JUnitPlatform) NotNull(org.jetbrains.annotations.NotNull) JUnitStarter(com.intellij.rt.execution.junit.JUnitStarter) TestExecutionListener(org.junit.platform.launcher.TestExecutionListener) IOException(java.io.IOException) PathsList(com.intellij.util.PathsList) ParametersList(com.intellij.execution.configurations.ParametersList) Module(com.intellij.openapi.module.Module)

Example 37 with Function

use of com.intellij.util.Function in project intellij-community by JetBrains.

the class MavenProjectReaderTest method testInheritingParentProfiles.

public void testInheritingParentProfiles() throws Exception {
    createProjectPom("<groupId>test</groupId>" + "<artifactId>parent</artifactId>" + "<version>1</version>" + "<profiles>" + "  <profile>" + "    <id>profileFromParent</id>" + "  </profile>" + "</profiles>");
    VirtualFile module = createModulePom("module", "<groupId>test</groupId>" + "<artifactId>module</artifactId>" + "<version>1</version>" + "<parent>" + "  <groupId>test</groupId>" + "  <artifactId>parent</artifactId>" + "  <version>1</version>" + "</parent>" + "<profiles>" + "  <profile>" + "    <id>profileFromChild</id>" + "  </profile>" + "</profiles>");
    MavenModel p = readProject(module);
    assertOrderedElementsAreEqual(ContainerUtil.map(p.getProfiles(), (Function<MavenProfile, Object>) profile -> profile.getId()), "profileFromChild", "profileFromParent");
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Function(com.intellij.util.Function)

Example 38 with Function

use of com.intellij.util.Function in project intellij-community by JetBrains.

the class ExternalProjectDataCache method getRootExternalProject.

@Nullable
public ExternalProject getRootExternalProject(@NotNull ProjectSystemId systemId, @NotNull File projectRootDir) {
    ExternalProject externalProject = myExternalRootProjects.get(Pair.create(systemId, projectRootDir));
    if (LOG.isDebugEnabled()) {
        LOG.debug("Can not find data for project at: " + projectRootDir);
        LOG.debug("Existing imported projects paths: " + ContainerUtil.map(myExternalRootProjects.entrySet(), (Function<Map.Entry<Pair<ProjectSystemId, File>, ExternalProject>, Object>) entry -> {
            if (!(entry.getValue() instanceof ExternalProject))
                return null;
            return Pair.create(entry.getKey(), entry.getValue().getProjectDir());
        }));
    }
    return externalProject;
}
Also used : ContainerUtil(com.intellij.util.containers.ContainerUtil) ExternalSourceSet(org.jetbrains.plugins.gradle.model.ExternalSourceSet) File(java.io.File) ExternalSystemUtil(com.intellij.openapi.externalSystem.util.ExternalSystemUtil) Nullable(org.jetbrains.annotations.Nullable) ExternalSystemApiUtil(com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil) ServiceManager(com.intellij.openapi.components.ServiceManager) DefaultExternalProject(org.jetbrains.plugins.gradle.model.DefaultExternalProject) ExternalProject(org.jetbrains.plugins.gradle.model.ExternalProject) Function(com.intellij.util.Function) Map(java.util.Map) Pair(com.intellij.openapi.util.Pair) ProjectSystemId(com.intellij.openapi.externalSystem.model.ProjectSystemId) Project(com.intellij.openapi.project.Project) ConcurrentFactoryMap(com.intellij.util.containers.ConcurrentFactoryMap) Queue(java.util.Queue) Logger(com.intellij.openapi.diagnostic.Logger) Module(com.intellij.openapi.module.Module) NotNull(org.jetbrains.annotations.NotNull) Collections(java.util.Collections) DefaultExternalProject(org.jetbrains.plugins.gradle.model.DefaultExternalProject) ExternalProject(org.jetbrains.plugins.gradle.model.ExternalProject) ProjectSystemId(com.intellij.openapi.externalSystem.model.ProjectSystemId) File(java.io.File) Nullable(org.jetbrains.annotations.Nullable)

Example 39 with Function

use of com.intellij.util.Function in project intellij-community by JetBrains.

the class GradleTaskManager method executeTasks.

@Override
public void executeTasks(@NotNull final ExternalSystemTaskId id, @NotNull final List<String> taskNames, @NotNull String projectPath, @Nullable GradleExecutionSettings settings, @Nullable final String jvmAgentSetup, @NotNull final ExternalSystemTaskNotificationListener listener) throws ExternalSystemException {
    // TODO add support for external process mode
    if (ExternalSystemApiUtil.isInProcessMode(GradleConstants.SYSTEM_ID)) {
        for (GradleTaskManagerExtension gradleTaskManagerExtension : GradleTaskManagerExtension.EP_NAME.getExtensions()) {
            if (gradleTaskManagerExtension.executeTasks(id, taskNames, projectPath, settings, jvmAgentSetup, listener)) {
                return;
            }
        }
    }
    GradleExecutionSettings effectiveSettings = settings == null ? new GradleExecutionSettings(null, null, DistributionType.BUNDLED, false) : settings;
    Function<ProjectConnection, Void> f = connection -> {
        final List<String> initScripts = ContainerUtil.newArrayList();
        final GradleProjectResolverExtension projectResolverChain = GradleProjectResolver.createProjectResolverChain(effectiveSettings);
        for (GradleProjectResolverExtension resolverExtension = projectResolverChain; resolverExtension != null; resolverExtension = resolverExtension.getNext()) {
            final String resolverClassName = resolverExtension.getClass().getName();
            resolverExtension.enhanceTaskProcessing(taskNames, jvmAgentSetup, script -> {
                if (StringUtil.isNotEmpty(script)) {
                    ContainerUtil.addAllNotNull(initScripts, "//-- Generated by " + resolverClassName, script, "//");
                }
            });
        }
        final String initScript = effectiveSettings.getUserData(INIT_SCRIPT_KEY);
        if (StringUtil.isNotEmpty(initScript)) {
            ContainerUtil.addAll(initScripts, "//-- Additional script", initScript, "//");
        }
        if (!initScripts.isEmpty()) {
            try {
                File tempFile = GradleExecutionHelper.writeToFileGradleInitScript(StringUtil.join(initScripts, SystemProperties.getLineSeparator()));
                effectiveSettings.withArguments(GradleConstants.INIT_SCRIPT_CMD_OPTION, tempFile.getAbsolutePath());
            } catch (IOException e) {
                throw new ExternalSystemException(e);
            }
        }
        GradleVersion gradleVersion = GradleExecutionHelper.getGradleVersion(connection);
        if (gradleVersion != null && gradleVersion.compareTo(GradleVersion.version("2.5")) < 0) {
            listener.onStatusChange(new ExternalSystemTaskExecutionEvent(id, new ExternalSystemProgressEventUnsupportedImpl(gradleVersion + " does not support executions view")));
        }
        for (GradleBuildParticipant buildParticipant : effectiveSettings.getExecutionWorkspace().getBuildParticipants()) {
            effectiveSettings.withArguments(GradleConstants.INCLUDE_BUILD_CMD_OPTION, buildParticipant.getProjectPath());
        }
        BuildLauncher launcher = myHelper.getBuildLauncher(id, connection, effectiveSettings, listener);
        launcher.forTasks(ArrayUtil.toStringArray(taskNames));
        if (gradleVersion != null && gradleVersion.compareTo(GradleVersion.version("2.1")) < 0) {
            myCancellationMap.put(id, new UnsupportedCancellationToken());
        } else {
            final CancellationTokenSource cancellationTokenSource = GradleConnector.newCancellationTokenSource();
            launcher.withCancellationToken(cancellationTokenSource.token());
            myCancellationMap.put(id, cancellationTokenSource);
        }
        try {
            launcher.run();
        } finally {
            myCancellationMap.remove(id);
        }
        return null;
    };
    myHelper.execute(projectPath, effectiveSettings, f);
}
Also used : GradleExecutionSettings(org.jetbrains.plugins.gradle.settings.GradleExecutionSettings) ExternalSystemTaskNotificationListener(com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListener) ArrayUtil(com.intellij.util.ArrayUtil) GradleExecutionSettings(org.jetbrains.plugins.gradle.settings.GradleExecutionSettings) GradleProjectResolver(org.jetbrains.plugins.gradle.service.project.GradleProjectResolver) ContainerUtil(com.intellij.util.containers.ContainerUtil) GradleExecutionHelper(org.jetbrains.plugins.gradle.service.execution.GradleExecutionHelper) ExternalSystemApiUtil(com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil) UnsupportedCancellationToken(org.jetbrains.plugins.gradle.service.execution.UnsupportedCancellationToken) Map(java.util.Map) GradleConnector(org.gradle.tooling.GradleConnector) GradleBuildParticipant(org.jetbrains.plugins.gradle.settings.GradleBuildParticipant) GradleProjectResolverExtension(org.jetbrains.plugins.gradle.service.project.GradleProjectResolverExtension) GradleVersion(org.gradle.util.GradleVersion) BuildLauncher(org.gradle.tooling.BuildLauncher) ExternalSystemTaskManager(com.intellij.openapi.externalSystem.task.ExternalSystemTaskManager) StringUtil(com.intellij.openapi.util.text.StringUtil) ExternalSystemTaskExecutionEvent(com.intellij.openapi.externalSystem.model.task.event.ExternalSystemTaskExecutionEvent) Key(com.intellij.openapi.util.Key) ExternalSystemException(com.intellij.openapi.externalSystem.model.ExternalSystemException) IOException(java.io.IOException) File(java.io.File) Nullable(org.jetbrains.annotations.Nullable) ExternalSystemTaskId(com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId) CancellationTokenSource(org.gradle.tooling.CancellationTokenSource) DistributionType(org.jetbrains.plugins.gradle.settings.DistributionType) List(java.util.List) SystemProperties(com.intellij.util.SystemProperties) Function(com.intellij.util.Function) ExternalSystemProgressEventUnsupportedImpl(com.intellij.openapi.externalSystem.model.task.event.ExternalSystemProgressEventUnsupportedImpl) GradleConstants(org.jetbrains.plugins.gradle.util.GradleConstants) ProjectConnection(org.gradle.tooling.ProjectConnection) NotNull(org.jetbrains.annotations.NotNull) GradleProjectResolverExtension(org.jetbrains.plugins.gradle.service.project.GradleProjectResolverExtension) UnsupportedCancellationToken(org.jetbrains.plugins.gradle.service.execution.UnsupportedCancellationToken) ProjectConnection(org.gradle.tooling.ProjectConnection) ExternalSystemTaskExecutionEvent(com.intellij.openapi.externalSystem.model.task.event.ExternalSystemTaskExecutionEvent) IOException(java.io.IOException) ExternalSystemException(com.intellij.openapi.externalSystem.model.ExternalSystemException) BuildLauncher(org.gradle.tooling.BuildLauncher) CancellationTokenSource(org.gradle.tooling.CancellationTokenSource) List(java.util.List) GradleVersion(org.gradle.util.GradleVersion) File(java.io.File) GradleBuildParticipant(org.jetbrains.plugins.gradle.settings.GradleBuildParticipant) ExternalSystemProgressEventUnsupportedImpl(com.intellij.openapi.externalSystem.model.task.event.ExternalSystemProgressEventUnsupportedImpl)

Example 40 with Function

use of com.intellij.util.Function in project intellij-community by JetBrains.

the class PropertiesCopyHandler method copyPropertyToAnotherBundle.

private static void copyPropertyToAnotherBundle(@NotNull Collection<IProperty> properties, @NotNull final String newName, @NotNull ResourceBundle targetResourceBundle) {
    final Map<IProperty, PropertiesFile> propertiesFileMapping = new HashMap<>();
    for (IProperty property : properties) {
        final PropertiesFile containingFile = property.getPropertiesFile();
        final PropertiesFile matched = findWithMatchedSuffix(containingFile, targetResourceBundle);
        if (matched != null) {
            propertiesFileMapping.put(property, matched);
        }
    }
    final Project project = targetResourceBundle.getProject();
    if (properties.size() != propertiesFileMapping.size() && Messages.NO == Messages.showYesNoDialog(project, "Source and target resource bundles properties files are not matched correctly. Copy properties anyway?", "Resource Bundles Are not Matched", null)) {
        return;
    }
    if (!propertiesFileMapping.isEmpty()) {
        WriteCommandAction.runWriteCommandAction(project, () -> {
            if (!FileModificationService.getInstance().preparePsiElementsForWrite(ContainerUtil.map(propertiesFileMapping.values(), (Function<PropertiesFile, PsiElement>) PropertiesFile::getContainingFile)))
                return;
            for (Map.Entry<IProperty, PropertiesFile> entry : propertiesFileMapping.entrySet()) {
                final String value = entry.getKey().getValue();
                final PropertiesFile target = entry.getValue();
                target.addProperty(newName, value);
            }
        });
        final IProperty representativeFromSourceBundle = ContainerUtil.getFirstItem(properties);
        LOG.assertTrue(representativeFromSourceBundle != null);
        final ResourceBundle sourceResourceBundle = representativeFromSourceBundle.getPropertiesFile().getResourceBundle();
        if (sourceResourceBundle.equals(targetResourceBundle)) {
            DataManager.getInstance().getDataContextFromFocus().doWhenDone((Consumer<DataContext>) context -> {
                final FileEditor fileEditor = PlatformDataKeys.FILE_EDITOR.getData(context);
                if (fileEditor instanceof ResourceBundleEditor) {
                    final ResourceBundleEditor resourceBundleEditor = (ResourceBundleEditor) fileEditor;
                    resourceBundleEditor.updateTreeRoot();
                    resourceBundleEditor.selectProperty(newName);
                }
            });
        } else {
            for (FileEditor editor : FileEditorManager.getInstance(project).openFile(new ResourceBundleAsVirtualFile(targetResourceBundle), true)) {
                ((ResourceBundleEditor) editor).updateTreeRoot();
                ((ResourceBundleEditor) editor).selectProperty(newName);
            }
        }
    }
}
Also used : UIUtil(com.intellij.util.ui.UIUtil) AllIcons(com.intellij.icons.AllIcons) VirtualFile(com.intellij.openapi.vfs.VirtualFile) CopyHandlerDelegateBase(com.intellij.refactoring.copy.CopyHandlerDelegateBase) ItemListener(java.awt.event.ItemListener) PsiManager(com.intellij.psi.PsiManager) JBTextField(com.intellij.ui.components.JBTextField) Map(java.util.Map) WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) Messages(com.intellij.openapi.ui.Messages) FileUtil(com.intellij.openapi.util.io.FileUtil) Logger(com.intellij.openapi.diagnostic.Logger) ValidationInfo(com.intellij.openapi.ui.ValidationInfo) ItemEvent(java.awt.event.ItemEvent) SyntheticFileSystemItem(com.intellij.psi.impl.SyntheticFileSystemItem) FileModificationService(com.intellij.codeInsight.FileModificationService) GotoFileCellRenderer(com.intellij.ide.util.gotoByName.GotoFileCellRenderer) Collection(java.util.Collection) NullableFunction(com.intellij.util.NullableFunction) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) FileEditor(com.intellij.openapi.fileEditor.FileEditor) Collectors(java.util.stream.Collectors) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) ComboboxSpeedSearch(com.intellij.ui.ComboboxSpeedSearch) Function(com.intellij.util.Function) PsiDirectory(com.intellij.psi.PsiDirectory) ProjectScope(com.intellij.psi.search.ProjectScope) NotNull(org.jetbrains.annotations.NotNull) PsiFileSystemItem(com.intellij.psi.PsiFileSystemItem) DocumentAdapter(com.intellij.ui.DocumentAdapter) FormBuilder(com.intellij.util.ui.FormBuilder) Consumer(com.intellij.util.Consumer) PropertiesFile(com.intellij.lang.properties.psi.PropertiesFile) DataContext(com.intellij.openapi.actionSystem.DataContext) PsiElementProcessor(com.intellij.psi.search.PsiElementProcessor) ContainerUtil(com.intellij.util.containers.ContainerUtil) ArrayList(java.util.ArrayList) FileEditorManager(com.intellij.openapi.fileEditor.FileEditorManager) PlatformDataKeys(com.intellij.openapi.actionSystem.PlatformDataKeys) Comparing(com.intellij.openapi.util.Comparing) DialogWrapper(com.intellij.openapi.ui.DialogWrapper) PsiElement(com.intellij.psi.PsiElement) Project(com.intellij.openapi.project.Project) DocumentEvent(javax.swing.event.DocumentEvent) DataManager(com.intellij.ide.DataManager) HashMap(com.intellij.util.containers.hash.HashMap) ComboBox(com.intellij.openapi.ui.ComboBox) StringUtil(com.intellij.openapi.util.text.StringUtil) com.intellij.lang.properties(com.intellij.lang.properties) java.awt(java.awt) javax.swing(javax.swing) FileEditor(com.intellij.openapi.fileEditor.FileEditor) HashMap(com.intellij.util.containers.hash.HashMap) Project(com.intellij.openapi.project.Project) DataContext(com.intellij.openapi.actionSystem.DataContext) PropertiesFile(com.intellij.lang.properties.psi.PropertiesFile) Map(java.util.Map) HashMap(com.intellij.util.containers.hash.HashMap) PsiElement(com.intellij.psi.PsiElement)

Aggregations

Function (com.intellij.util.Function)53 NotNull (org.jetbrains.annotations.NotNull)32 Nullable (org.jetbrains.annotations.Nullable)24 Project (com.intellij.openapi.project.Project)23 Logger (com.intellij.openapi.diagnostic.Logger)19 VirtualFile (com.intellij.openapi.vfs.VirtualFile)15 ContainerUtil (com.intellij.util.containers.ContainerUtil)15 List (java.util.List)15 StringUtil (com.intellij.openapi.util.text.StringUtil)12 Module (com.intellij.openapi.module.Module)11 com.intellij.psi (com.intellij.psi)11 java.util (java.util)10 ArrayList (java.util.ArrayList)10 GlobalSearchScope (com.intellij.psi.search.GlobalSearchScope)9 ApplicationManager (com.intellij.openapi.application.ApplicationManager)8 PsiElement (com.intellij.psi.PsiElement)7 File (java.io.File)7 Messages (com.intellij.openapi.ui.Messages)6 PsiTreeUtil (com.intellij.psi.util.PsiTreeUtil)6 IOException (java.io.IOException)6