From 6bb63385b8f390d90c83353e280a92973d8fbde4 Mon Sep 17 00:00:00 2001 From: Attila Kelemen Date: Wed, 5 Jul 2017 02:01:06 +0200 Subject: [PATCH] Using lambda wherever possible. --- .../DefaultGlobalSettingsFileManager.java | 83 ++++---- .../gradle/project/GradleHomeRegistry.java | 52 ++--- .../project/ModelCacheSizeAutoUpdater.java | 16 +- .../gradle/project/NbGradleProject.java | 23 +-- .../project/NbGradleProjectLookups.java | 7 +- .../gradle/project/ProjectDisplayInfo.java | 16 +- .../gradle/project/ProjectModelManager.java | 15 +- .../gradle/project/ProjectModelUpdater.java | 23 +-- .../gradle/project/RootProjectRegistry.java | 40 ++-- .../project/api/config/PropertyReference.java | 7 +- .../coverage/GradleCoverageProvider.java | 24 ++- .../event/GenericChangeListenerManager.java | 42 +---- .../project/extensions/ExtensionLoader.java | 9 +- .../gradle/project/extensions/ModelNeeds.java | 53 +++--- .../GradleTemplateWizardPanel.java | 18 +- .../gradle/project/java/JavaExtension.java | 39 ++-- .../java/model/JavaProjectDependencies.java | 41 +--- .../project/java/model/NamedSourceRoot.java | 22 +-- .../model/ProjectDependencyCandidate.java | 36 ++-- .../java/nodes/JavaDependenciesNode.java | 25 +-- .../java/nodes/JavaExtensionNodes.java | 15 +- .../java/nodes/JavaProjectContextActions.java | 21 +-- .../project/java/nodes/JavaSourceSetNode.java | 14 +- .../java/properties/JavaDebuggingPanel.java | 9 +- .../query/GradleBinaryForSourceQuery.java | 11 +- .../java/query/GradleClassPathProvider.java | 57 ++---- .../java/query/GradleProjectSources.java | 32 +--- .../query/GradleSourceForBinaryQuery.java | 9 +- .../ProjectClassPathResourceBuilder.java | 8 +- .../java/tasks/DebuggerServiceFactory.java | 43 ++--- .../java/tasks/GradleJavaBuiltInCommands.java | 165 +++++----------- .../tasks/JavaGradleTaskVariableQuery.java | 50 ++--- .../java/test/JavaCallstackFrameNode.java | 15 +- .../project/java/test/JavaTestMethodNode.java | 35 ++-- .../project/java/test/JavaTestsuiteNode.java | 15 +- .../project/java/test/ShowTestUtils.java | 49 +++-- .../project/java/test/TestXmlDisplayer.java | 10 +- .../project/license/LicenseManager.java | 65 +++---- .../project/license/LicenseManagers.java | 33 +--- .../gradle/project/lookups/LookupsEx.java | 7 +- .../model/DefaultGradleModelLoader.java | 162 ++++++---------- .../LazyPersistentModelStoreFactory.java | 7 +- .../model/issue/IssueDetailsPanel.java | 8 +- .../model/issue/ModelLoadIssueReporter.java | 28 +-- .../project/newproject/NewProjectUtils.java | 141 +++++++------- .../project/others/ReflectionHelper.java | 9 +- .../gradle/project/output/IOTabs.java | 11 +- .../project/output/OutputUrlConsumer.java | 8 +- .../project/output/StackTraceConsumer.java | 7 +- .../project/output/SubPathConsumer.java | 15 +- .../gradle/project/output/TaskTabAction.java | 7 +- .../ActiveSettingsQueryExProxy.java | 23 +-- .../project/properties/ConfigXmlUtils.java | 34 +--- .../DefaultProjectSettingsProvider.java | 7 +- .../ExtensionProjectSettingsPageDefs.java | 13 +- .../properties/GenericProfileSettings.java | 21 +-- .../project/properties/GradleCustomizer.java | 46 ++--- .../properties/MultiProfileProperties.java | 16 +- .../properties/NbGradleConfigProvider.java | 42 ++--- .../properties/NbGradleConfiguration.java | 19 +- .../NbGradleSingleProjectConfigProvider.java | 24 +-- .../project/properties/NbProperties.java | 79 ++------ .../properties/ProfileBasedCustomizer.java | 18 +- .../project/properties/ProfileSettings.java | 39 +--- .../properties/ProfileSettingsContainer.java | 26 +-- .../properties/ProjectProfileLoader.java | 8 +- .../properties/PropertyOfProperty.java | 26 +-- .../SwingPropertyChangeForwarder.java | 38 +--- .../global/GlobalProfileSettings.java | 8 +- .../global/GlobalSettingsUtils.java | 17 +- .../properties/global/NbGlobalPreference.java | 9 +- .../standard/BuiltInTasksProperty.java | 21 +-- .../standard/CustomTasksProperty.java | 25 ++- .../standard/JavaPlatformUtils.java | 16 +- .../standard/ScriptPlatformProperty.java | 8 +- .../properties/ui/AppearancePanel.java | 48 ++--- .../ui/CommonProjectPropertiesPanel.java | 9 +- .../properties/ui/CustomVariablesPanel.java | 8 +- .../project/properties/ui/EnumCombo.java | 9 +- .../ui/GlobalGradleSettingsPanel.java | 29 +-- .../properties/ui/GradleLocationPanel.java | 14 +- .../properties/ui/LicenseHeaderPanel.java | 47 ++--- .../ui/ManageBuiltInTasksPanel.java | 53 ++---- .../properties/ui/ManageTasksPanel.java | 27 +-- .../properties/ui/PlatformPriorityPanel.java | 17 +- .../properties/ui/ProfileBasedPanel.java | 178 +++++++----------- .../GradleCacheBinaryForSourceQuery.java | 8 +- .../GradleCacheJavadocForBinaryQuery.java | 13 +- .../GradleCacheSourceForBinaryQuery.java | 16 +- .../query/GradleFilesClassPathProvider.java | 33 +--- .../query/GradleHomeClassPathProvider.java | 16 +- .../query/GradleHomeSourceForBinaryQuery.java | 7 +- .../script/DefaultScriptFileProvider.java | 9 +- .../gradle/project/tasks/AsyncGradleTask.java | 29 +-- .../project/tasks/AttacherListener.java | 24 +-- .../tasks/DefaultGradleCommandExecutor.java | 17 +- .../gradle/project/tasks/GradleArguments.java | 14 +- .../project/tasks/GradleDaemonFailures.java | 9 +- .../project/tasks/GradleDaemonManager.java | 95 ++++------ .../gradle/project/tasks/GradleTaskDef.java | 28 +-- .../gradle/project/tasks/GradleTasks.java | 17 +- .../project/tasks/PriorityAwareExecutor.java | 65 +++---- .../tasks/vars/DisplayedTaskVariable.java | 9 +- .../tasks/vars/StandardTaskVariable.java | 150 ++++++--------- .../project/tasks/vars/TaskVariableMaps.java | 7 +- .../tasks/vars/TaskVariableQueryDialog.java | 76 ++------ .../gradle/project/util/CloseableAction.java | 6 +- .../util/CloseableActionContainer.java | 130 +++++-------- .../project/util/FileSystemWatcher.java | 102 ++++------ .../gradle/project/util/GlassPanes.java | 37 ++-- .../gradle/project/util/GradleFileUtils.java | 7 +- .../gradle/project/util/NbFileUtils.java | 15 +- .../gradle/project/util/NbGuiUtils.java | 11 +- .../gradle/project/util/NbPredicate.java | 15 +- .../gradle/project/util/UrlFactory.java | 14 +- .../project/validate/BackgroundValidator.java | 50 ++--- .../gradle/project/validate/Validators.java | 171 ++++++++--------- .../project/view/AnnotationChildNodes.java | 64 ++----- .../gradle/project/view/BadgeAwareNode.java | 63 ++----- .../gradle/project/view/BuildScriptsNode.java | 32 +--- .../project/view/CustomActionPanel.java | 7 +- .../project/view/DeleteProjectAction.java | 26 +-- .../project/view/DisplayableTaskVariable.java | 75 +++----- .../project/view/GlobalErrorReporter.java | 31 ++- .../project/view/GradleActionProvider.java | 37 ++-- .../gradle/project/view/GradleFolderNode.java | 43 ++--- .../gradle/project/view/GradleHomeNode.java | 45 +---- .../view/GradleProjectChildFactory.java | 56 ++---- .../GradleProjectLogicalViewProvider.java | 73 ++----- .../gradle/project/view/NodeUtils.java | 9 +- .../project/view/OpenAlwaysFileAction.java | 38 +--- .../project/view/OpenProjectsAction.java | 11 +- .../view/ProjectContextActionProvider.java | 31 +-- .../project/view/ProjectScriptFilesNode.java | 15 +- .../project/view/SubProjectsChildFactory.java | 31 +-- .../project/api/entry/FakeSubProjectTest.java | 7 +- .../project/api/entry/SampleProjectRule.java | 21 +-- .../api/entry/SimpleJavaProjectTest.java | 8 +- .../properties/JavaDebuggingPanelTest.java | 15 +- .../query/GradleBinaryForSourceQueryTest.java | 9 +- .../query/GradleSourceForBinaryQueryTest.java | 9 +- .../license/DefaultLicenseStoreTest.java | 24 +-- .../project/license/LicenseManagerTest.java | 18 +- .../LazyProjectModelPersisterFactoryTest.java | 10 +- .../model/MultiFileModelCacheTest.java | 8 +- .../others/PluginClassImplementationTest.java | 7 +- .../project/output/IOTabMaintainerTest.java | 7 +- .../project/properties/NbPropertiesTest.java | 9 +- .../properties/PredefinedTaskTest.java | 15 +- .../properties/PropertyOfPropertyTest.java | 8 +- .../properties/ui/AppearancePanelTest.java | 35 +--- .../ui/BuildScriptParsingPanelTest.java | 30 +-- .../ui/CustomVariablesPanelTest.java | 30 +-- .../ui/GlobalSettingsPanelTestUtils.java | 53 ++---- .../properties/ui/GradleDaemonPanelTest.java | 17 +- .../ui/GradleInstallationPanelTest.java | 45 ++--- .../properties/ui/LicenseHeaderPanelTest.java | 45 ++--- .../properties/ui/ManageTasksPanelTest.java | 15 +- .../properties/ui/OtherOptionsPanelTest.java | 31 +-- .../ui/PlatformPriorityPanelTest.java | 27 +-- .../ui/ScriptAndTasksPanelTest.java | 31 +-- .../properties/ui/TaskExecutionPanelTest.java | 54 ++---- .../GradleCacheSourceForBinaryQueryTest.java | 8 +- .../GradleHomeSourceForBinaryQueryTest.java | 8 +- .../util/CustomGlobalSettingsRule.java | 17 +- .../project/util/FileSystemWatcherTest.java | 82 +++----- .../gradle/project/util/SwingTestsRule.java | 13 +- .../view/AnnotationChildNodesTest.java | 17 +- 168 files changed, 1608 insertions(+), 3691 deletions(-) diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/DefaultGlobalSettingsFileManager.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/DefaultGlobalSettingsFileManager.java index 7138094f..b441bd1e 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/DefaultGlobalSettingsFileManager.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/DefaultGlobalSettingsFileManager.java @@ -117,12 +117,7 @@ public void updateSettingsFile(NbGradleModel model) { ExceptionHelper.checkNotNullArgument(model, "model"); setAllSettingsDef(model, getStamp()); - settingsDefPersistor.execute(new Runnable() { - @Override - public void run() { - persistSettingsDefsNow(); - } - }); + settingsDefPersistor.execute(this::persistSettingsDefsNow); } private void persistSettingsDefsNow() { @@ -146,33 +141,30 @@ private void persistSettingsDefsNow0() throws IOException { outstandingDefsLock.unlock(); } - getLocker().doWrite(new IoTask() { - @Override - public Void run() throws IOException { - MessageDigest hashCalculator = getNameHasher(); - for (SettingsDef def: toSave) { - Path savePath = tryGetProjectSaveFile(def.projectDir, hashCalculator); - if (savePath == null) { - LOGGER.log(Level.WARNING, "Cannot save settings.gradle location for projects."); - break; - } - - Path settingsGradle = def.settingsGradleDef.getSettingsGradle(); - - Properties output = new Properties(); - output.put("projectDir", def.projectDir.toString()); - output.put("rootProjectDir", def.rootProjectDir.toString()); - output.put("maySearchUpwards", Boolean.toString(def.settingsGradleDef.isMaySearchUpwards())); - output.put("settingsGradle", settingsGradle != null ? settingsGradle.toString() : ""); - output.put("stamp", def.stamp); - - Files.createDirectories(savePath.getParent()); - try (OutputStream outputStream = Files.newOutputStream(savePath)) { - output.store(outputStream, null); - } + getLocker().doWrite(() -> { + MessageDigest hashCalculator = getNameHasher(); + for (SettingsDef def: toSave) { + Path savePath = tryGetProjectSaveFile(def.projectDir, hashCalculator); + if (savePath == null) { + LOGGER.log(Level.WARNING, "Cannot save settings.gradle location for projects."); + break; + } + + Path settingsGradle = def.settingsGradleDef.getSettingsGradle(); + + Properties output = new Properties(); + output.put("projectDir", def.projectDir.toString()); + output.put("rootProjectDir", def.rootProjectDir.toString()); + output.put("maySearchUpwards", Boolean.toString(def.settingsGradleDef.isMaySearchUpwards())); + output.put("settingsGradle", settingsGradle != null ? settingsGradle.toString() : ""); + output.put("stamp", def.stamp); + + Files.createDirectories(savePath.getParent()); + try (OutputStream outputStream = Files.newOutputStream(savePath)) { + output.store(outputStream, null); } - return null; } + return null; }); outstandingDefsLock.lock(); @@ -222,25 +214,22 @@ private SettingsDef tryGetStoredSettingsDef(File projectDir) { } private SettingsDef tryGetStoredSettingsDef0(final File projectDir) throws IOException { - return getLocker().doRead(new IoTask() { - @Override - public SettingsDef run() throws IOException { - SettingsDef result = tryGetStoredSettingsDefUnsafe(projectDir); - if (result == null) { - return null; - } - - if (Objects.equals(projectDir, result.projectDir)) { - return result; - } + return getLocker().doRead(() -> { + SettingsDef result = tryGetStoredSettingsDefUnsafe(projectDir); + if (result == null) { + return null; + } - SettingsDef rootDef = tryGetStoredSettingsDefUnsafe(projectDir); - if (rootDef == null) { - return null; - } + if (Objects.equals(projectDir, result.projectDir)) { + return result; + } - return Objects.equals(result.stamp, rootDef.stamp) ? result : null; + SettingsDef rootDef = tryGetStoredSettingsDefUnsafe(projectDir); + if (rootDef == null) { + return null; } + + return Objects.equals(result.stamp, rootDef.stamp) ? result : null; }); } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/GradleHomeRegistry.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/GradleHomeRegistry.java index 38336ca8..9abff137 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/GradleHomeRegistry.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/GradleHomeRegistry.java @@ -70,13 +70,7 @@ private static PropertySource gradleLocation() { public static void requireGradlePaths() { if (USING_GLOBAL_PATHS.compareAndSet(false, true)) { - gradleLocation().addChangeListener(new Runnable() { - @Override - public void run() { - updateGradleHome(); - } - }); - + gradleLocation().addChangeListener(GradleHomeRegistry::updateGradleHome); updateGradleHome(); } } @@ -91,31 +85,25 @@ private static void updateGradleHome() { private static void setGradleHome(final FileObject gradleHome) { ExceptionHelper.checkNotNullArgument(gradleHome, "gradleHome"); - GRADLE_HOME_UPDATER.execute(new Runnable() { - @Override - public void run() { - URL[] urls = GradleHomeClassPathProvider.getAllGradleLibs(gradleHome); - if (urls.length == 0) { - // Keep the previous classpaths if there are non found. - return; - } - - if (gradleHome.equals(GRADLE_HOME_BINARIES.get().getHomePath())) { - return; - } - - GRADLE_HOME_BINARIES.set(new GradleHomePaths(gradleHome, urls)); - - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - CHANGES.firePropertyChange(ClassPathImplementation.PROP_RESOURCES, null, null); - } - }); - - if (REGISTERED_GLOBAL_PATH.compareAndSet(false, true)) { - doRegisterGlobalClassPath(); - } + GRADLE_HOME_UPDATER.execute(() -> { + URL[] urls = GradleHomeClassPathProvider.getAllGradleLibs(gradleHome); + if (urls.length == 0) { + // Keep the previous classpaths if there are non found. + return; + } + + if (gradleHome.equals(GRADLE_HOME_BINARIES.get().getHomePath())) { + return; + } + + GRADLE_HOME_BINARIES.set(new GradleHomePaths(gradleHome, urls)); + + SwingUtilities.invokeLater(() -> { + CHANGES.firePropertyChange(ClassPathImplementation.PROP_RESOURCES, null, null); + }); + + if (REGISTERED_GLOBAL_PATH.compareAndSet(false, true)) { + doRegisterGlobalClassPath(); } }); } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/ModelCacheSizeAutoUpdater.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/ModelCacheSizeAutoUpdater.java index 8d01e1b0..11f30eea 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/ModelCacheSizeAutoUpdater.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/ModelCacheSizeAutoUpdater.java @@ -19,12 +19,9 @@ import org.netbeans.gradle.project.util.NbTaskExecutors; public final class ModelCacheSizeAutoUpdater implements ProjectModelChangeListener { - private static final ModelCacheSizeAutoUpdater DEFAULT = new ModelCacheSizeAutoUpdater(NbTaskExecutors.newDefaultUpdateExecutor(), new NbConsumer() { - @Override - public void accept(Integer requiredCacheSize) { - DefaultGradleModelLoader.ensureCacheSize(requiredCacheSize); - } - }); + private static final ModelCacheSizeAutoUpdater DEFAULT = new ModelCacheSizeAutoUpdater( + NbTaskExecutors.newDefaultUpdateExecutor(), + DefaultGradleModelLoader::ensureCacheSize); private final UpdateTaskExecutor cacheSizeCheckExecutor; private final NbConsumer cacheSizeUpdater; @@ -47,12 +44,7 @@ public static ModelCacheSizeAutoUpdater getDefault() { @Override public void onModelChanged() { - cacheSizeCheckExecutor.execute(new Runnable() { - @Override - public void run() { - checkCacheSize(); - } - }); + cacheSizeCheckExecutor.execute(this::checkCacheSize); } private void checkCacheSize() { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/NbGradleProject.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/NbGradleProject.java index 7f036a2f..c531904b 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/NbGradleProject.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/NbGradleProject.java @@ -26,7 +26,6 @@ import org.netbeans.gradle.project.license.LicenseSource; import org.netbeans.gradle.project.lookups.LookupsEx; import org.netbeans.gradle.project.model.DefaultGradleModelLoader; -import org.netbeans.gradle.project.model.ModelRetrievedListener; import org.netbeans.gradle.project.model.NbGradleModel; import org.netbeans.gradle.project.model.SettingsGradleDef; import org.netbeans.gradle.project.model.issue.ModelLoadIssue; @@ -325,17 +324,12 @@ public ServiceObjects(NbGradleProject project, ProjectState state) { this.modelManager = new ProjectModelManager(project, DefaultGradleModelLoader.createEmptyModel(projectDir, scriptFileProvider)); - ModelRetrievedListener modelUpdateListener = new ModelRetrievedListener() { - @Override - public void updateModel(NbGradleModel model, Throwable error) { - modelManager.updateModel(model, error); - if (model != null && error == null) { - SETTINGS_FILE_MANAGER.updateSettingsFile(model); - } + this.modelUpdater = new ProjectModelUpdater<>(createModelLoader(project), (model, error) -> { + modelManager.updateModel(model, error); + if (model != null && error == null) { + SETTINGS_FILE_MANAGER.updateSettingsFile(model); } - }; - - this.modelUpdater = new ProjectModelUpdater<>(createModelLoader(project), modelUpdateListener); + }); this.settingsFileManager = new SettingsFileManager(projectDirAsFile, SETTINGS_FILE_MANAGER); this.projectDisplayInfo = new ProjectDisplayInfo( modelManager.currentModel(), @@ -411,12 +405,7 @@ private static ProjectOpenedHook createOpenHook( ROOT_PROJECT_REGISTRY.forProject(currentModel) ); - return GenericOpenHook.create(actionProperties, new Runnable() { - @Override - public void run() { - modelUpdater.reloadProjectMayUseCache(); - } - }); + return GenericOpenHook.create(actionProperties, modelUpdater::reloadProjectMayUseCache); } } } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/NbGradleProjectLookups.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/NbGradleProjectLookups.java index bc51a301..99cb78ab 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/NbGradleProjectLookups.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/NbGradleProjectLookups.java @@ -91,12 +91,7 @@ private static List moveToLookupProvider(List lookups) { private static LookupProvider moveToLookupProvider(final Lookup lookup) { ExceptionHelper.checkNotNullArgument(lookup, "lookup"); - return new LookupProvider() { - @Override - public Lookup createAdditionalLookup(Lookup baseContext) { - return lookup; - } - }; + return (baseContext) -> lookup; } private static List extractLookupsFromProviders( diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/ProjectDisplayInfo.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/ProjectDisplayInfo.java index 34252028..8cbae294 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/ProjectDisplayInfo.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/ProjectDisplayInfo.java @@ -2,11 +2,9 @@ import org.jtrim.property.PropertyFactory; import org.jtrim.property.PropertySource; -import org.jtrim.property.ValueConverter; import org.jtrim.utils.ExceptionHelper; import org.netbeans.gradle.project.model.NbGradleModel; import org.netbeans.gradle.project.properties.NbProperties; -import org.netbeans.gradle.project.util.NbBiFunction; public final class ProjectDisplayInfo { private final PropertySource displayName; @@ -18,18 +16,8 @@ public ProjectDisplayInfo( ExceptionHelper.checkNotNullArgument(currentModel, "currentModel"); ExceptionHelper.checkNotNullArgument(displayNamePattern, "displayNamePattern"); - this.displayName = NbProperties.combine(currentModel, displayNamePattern, new NbBiFunction() { - @Override - public String apply(NbGradleModel model, String pattern) { - return model.getDisplayName(pattern); - } - }); - this.description = PropertyFactory.convert(currentModel, new ValueConverter() { - @Override - public String convert(NbGradleModel input) { - return input.getDescription(); - } - }); + this.displayName = NbProperties.combine(currentModel, displayNamePattern, NbGradleModel::getDisplayName); + this.description = PropertyFactory.convert(currentModel, NbGradleModel::getDescription); } public PropertySource displayName() { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/ProjectModelManager.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/ProjectModelManager.java index da392957..892ff738 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/ProjectModelManager.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/ProjectModelManager.java @@ -23,7 +23,6 @@ import org.netbeans.gradle.project.query.GradleCacheBinaryForSourceQuery; import org.netbeans.gradle.project.query.GradleCacheByBinaryLookup; import org.netbeans.gradle.project.util.LazyValue; -import org.netbeans.gradle.project.util.NbSupplier; final class ProjectModelManager implements ModelRetrievedListener { private static final Logger LOGGER = Logger.getLogger(ProjectModelManager.class.getName()); @@ -45,18 +44,8 @@ public ProjectModelManager(final NbGradleProject project, final NbGradleModel in this.currentModelRef = new AtomicReference<>(initialModel); this.currentModel = NbProperties.atomicValueView(currentModelRef, modelChangeListeners); this.modelUpdater = new SwingUpdateTaskExecutor(true); - this.modelUpdateDispatcher = new Runnable() { - @Override - public void run() { - onModelChange(); - } - }; - this.loadErrorRef = new LazyValue<>(new NbSupplier() { - @Override - public ProjectIssueRef get() { - return project.getProjectIssueManager().createIssueRef(); - } - }); + this.modelUpdateDispatcher = this::onModelChange; + this.loadErrorRef = new LazyValue<>(() -> project.getProjectIssueManager().createIssueRef()); } private void onModelChange() { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/ProjectModelUpdater.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/ProjectModelUpdater.java index eb69d3ae..dc65faa4 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/ProjectModelUpdater.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/ProjectModelUpdater.java @@ -26,19 +26,17 @@ public ProjectModelUpdater( ExceptionHelper.checkNotNullArgument(modelUpdater, "modelUpdater"); this.modelLoader = modelLoader; - this.modelUpdaterWrapper = new ModelRetrievedListener() { - @Override - public void updateModel(M model, Throwable error) { - try { - modelUpdater.updateModel(model, error); - } finally { - loadedAtLeastOnceSignal.signal(); - } + this.loadedAtLeastOnceSignal = new WaitableSignal(); + + this.modelUpdaterWrapper = (M model, Throwable error) -> { + try { + modelUpdater.updateModel(model, error); + } finally { + loadedAtLeastOnceSignal.signal(); } }; this.hasModelBeenLoaded = new AtomicBoolean(false); - this.loadedAtLeastOnceSignal = new WaitableSignal(); this.lastInProgressRef = new AtomicReference<>(null); } @@ -82,11 +80,8 @@ private void loadProject(final boolean onlyIfNotLoaded, final boolean mayUseCach lastInProgressRef.set(progressRef); } - modelLoader.fetchModel(mayUseCache, modelUpdaterWrapper, new Runnable() { - @Override - public void run() { - lastInProgressRef.compareAndSet(progressRef, null); - } + modelLoader.fetchModel(mayUseCache, modelUpdaterWrapper, () -> { + lastInProgressRef.compareAndSet(progressRef, null); }); } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/RootProjectRegistry.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/RootProjectRegistry.java index 55d14ea7..256cd6bb 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/RootProjectRegistry.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/RootProjectRegistry.java @@ -17,7 +17,6 @@ import java.util.concurrent.locks.ReentrantLock; import org.jtrim.property.PropertyFactory; import org.jtrim.property.PropertySource; -import org.jtrim.property.ValueConverter; import org.jtrim.utils.ExceptionHelper; import org.netbeans.gradle.project.model.NbGradleModel; import org.netbeans.gradle.project.model.NbGradleProjectTree; @@ -51,22 +50,12 @@ private CloseableAction.Ref registerAndUpdateProjects(NbGradleModel input) { return registerRootProjectModel(input); } - private CloseableAction registerAsCloseableAction(final NbGradleModel input) { - return new CloseableAction() { - @Override - public CloseableAction.Ref open() { - return registerAndUpdateProjects(input); - } - }; + private CloseableAction registerAsCloseableAction(NbGradleModel input) { + return () -> registerAndUpdateProjects(input); } public PropertySource forProject(PropertySource currentModel) { - return PropertyFactory.convert(currentModel, new ValueConverter() { - @Override - public CloseableAction convert(NbGradleModel input) { - return registerAsCloseableAction(input); - } - }); + return PropertyFactory.convert(currentModel, this::registerAsCloseableAction); } public CloseableAction.Ref registerRootProjectModel(NbGradleModel model) { @@ -82,20 +71,17 @@ public CloseableAction.Ref registerRootProjectModel(NbGradleModel model) { } final List safeRefs = new ArrayList<>(); - CloseableAction.Ref result = new CloseableAction.Ref() { - @Override - public void close() { - mainLock.lock(); - try { - RegisteredProjects value = rootProjects.get(key); - if (value != null && value.id == regId) { - rootProjects.remove(key); - } - - Closeables.closeAll(safeRefs); - } finally { - mainLock.unlock(); + CloseableAction.Ref result = () -> { + mainLock.lock(); + try { + RegisteredProjects value = rootProjects.get(key); + if (value != null && value.id == regId) { + rootProjects.remove(key); } + + Closeables.closeAll(safeRefs); + } finally { + mainLock.unlock(); } }; diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/api/config/PropertyReference.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/api/config/PropertyReference.java index b8389f79..0ff868c5 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/api/config/PropertyReference.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/api/config/PropertyReference.java @@ -74,12 +74,7 @@ private static PropertySource mergeProperties( assert fallback != null; assert valueMerger != null; - final ValueReference parentValueRef = new ValueReference() { - @Override - public ValueType getValue() { - return fallback.getValue(); - } - }; + final ValueReference parentValueRef = fallback::getValue; return new PropertySource() { @Override diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/coverage/GradleCoverageProvider.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/coverage/GradleCoverageProvider.java index f7005fd6..937f911d 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/coverage/GradleCoverageProvider.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/coverage/GradleCoverageProvider.java @@ -34,7 +34,6 @@ import org.openide.xml.XMLUtil; import org.w3c.dom.Element; import org.w3c.dom.NodeList; -import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; @@ -175,18 +174,17 @@ private void fire() { return null; } try { - org.w3c.dom.Document report = XMLUtil.parse(new InputSource(r.toURI().toString()), true, false, XMLUtil.defaultErrorHandler(), new EntityResolver() { - public @Override - InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { - if (systemId.equals("http://cobertura.sourceforge.net/xml/coverage-04.dtd")) { - return new InputSource(GradleCoverageProvider.class.getResourceAsStream("coverage-04.dtd")); // NOI18N - } - else if (publicId.equals("-//JACOCO//DTD Report 1.0//EN")) { - return new InputSource(GradleCoverageProvider.class.getResourceAsStream("jacoco-1.0.dtd")); - } - else { - return null; - } + org.w3c.dom.Document report; + InputSource inputSource = new InputSource(r.toURI().toString()); + report = XMLUtil.parse(inputSource, true, false, XMLUtil.defaultErrorHandler(), (publicId, systemId) -> { + if (systemId.equals("http://cobertura.sourceforge.net/xml/coverage-04.dtd")) { + return new InputSource(GradleCoverageProvider.class.getResourceAsStream("coverage-04.dtd")); // NOI18N + } + else if (publicId.equals("-//JACOCO//DTD Report 1.0//EN")) { + return new InputSource(GradleCoverageProvider.class.getResourceAsStream("jacoco-1.0.dtd")); + } + else { + return null; } }); LOG.log(Level.FINE, "parsed {0}", r); diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/event/GenericChangeListenerManager.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/event/GenericChangeListenerManager.java index 55eeaca2..1a9cf309 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/event/GenericChangeListenerManager.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/event/GenericChangeListenerManager.java @@ -35,31 +35,17 @@ public GenericChangeListenerManager(ChangeListenerManager wrapped, TaskExecutor this(wrapped, new GenericUpdateTaskExecutor(eventExecutor)); } - private GenericChangeListenerManager(ChangeListenerManager wrapped, final UpdateTaskExecutor executor) { + private GenericChangeListenerManager(ChangeListenerManager wrapped, UpdateTaskExecutor executor) { ExceptionHelper.checkNotNullArgument(wrapped, "wrapped"); this.wrapped = wrapped; this.pauseCount = new AtomicInteger(0); this.hasUnfired = new AtomicBoolean(false); - final Runnable forwarder = new Runnable() { - @Override - public void run() { - fireEventNow(); - } - }; - - if (executor != null) { - dispatcher = new Runnable() { - @Override - public void run() { - executor.execute(forwarder); - } - }; - } - else { - dispatcher = forwarder; - } + Runnable forwarder = this::fireEventNow; + this.dispatcher = executor != null + ? () -> executor.execute(forwarder) + : forwarder; } private static ChangeListenerManager newDefaultListenerManager() { @@ -88,24 +74,16 @@ public static GenericChangeListenerManager getSwingNotifier() { @Override public PauseRef pauseManager() { - final Runnable unpauseTask = Tasks.runOnceTask(new Runnable() { - @Override - public void run() { - if (pauseCount.decrementAndGet() == 0) { - if (hasUnfired.getAndSet(false)) { - fireEventually(); - } + final Runnable unpauseTask = Tasks.runOnceTask(() -> { + if (pauseCount.decrementAndGet() == 0) { + if (hasUnfired.getAndSet(false)) { + fireEventually(); } } }, false); pauseCount.incrementAndGet(); - return new PauseRef() { - @Override - public void unpause() { - unpauseTask.run(); - } - }; + return unpauseTask::run; } private void fireEventNow() { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/extensions/ExtensionLoader.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/extensions/ExtensionLoader.java index 126b568c..6060364e 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/extensions/ExtensionLoader.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/extensions/ExtensionLoader.java @@ -50,12 +50,9 @@ private static NbGradleExtensionRef createExtensionRef( GradleProjectExtensionDef def, GradleProjectExtension2 extension) { - return new NbGradleExtensionRef(def, extension, new DeducedExtensionServicesProvider() { - @Override - public Lookup getDeducedLookup(NbGradleExtensionRef extensionRef, Lookup... lookups) { - String extensionName = extensionRef.getName(); - return Lookups.fixed(new ExtensionProjectSettingsPageDefs(project, extensionName, lookups)); - } + return new NbGradleExtensionRef(def, extension, (NbGradleExtensionRef extensionRef, Lookup... lookups) -> { + String extensionName = extensionRef.getName(); + return Lookups.fixed(new ExtensionProjectSettingsPageDefs(project, extensionName, lookups)); }); } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/extensions/ModelNeeds.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/extensions/ModelNeeds.java index c0c234b6..9ef2db40 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/extensions/ModelNeeds.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/extensions/ModelNeeds.java @@ -51,16 +51,13 @@ private static GradleModelDefQuery1 createQuery1( return queries.iterator().next(); } - return new GradleModelDefQuery1() { - @Override - public Collection> getToolingModels(GradleTarget gradleTarget) { - List> result = new ArrayList<>(); - for (GradleModelDefQuery1 query: queries) { - Collection> models = safelyReturn(query.getToolingModels(gradleTarget), query); - result.addAll(models); - } - return result; + return (GradleTarget gradleTarget) -> { + List> result = new ArrayList<>(); + for (GradleModelDefQuery1 query: queries) { + Collection> models = safelyReturn(query.getToolingModels(gradleTarget), query); + result.addAll(models); } + return result; }; } @@ -69,18 +66,15 @@ private static GradleModelDefQuery1 createQuery1(final GradleProjectExtensionDef } private static GradleModelDefQuery2 query1AsQuery2(final GradleModelDefQuery1 query1) { - return new GradleModelDefQuery2() { - @Override - public GradleModelDef getModelDef(GradleTarget gradleTarget) { - Collection> toolinModels = query1.getToolingModels(gradleTarget); - if (toolinModels.isEmpty()) { - return GradleModelDef.EMPTY; - } - - return GradleModelDef.create( - toolinModels, - Collections.>emptyList()); + return (GradleTarget gradleTarget) -> { + Collection> toolinModels = query1.getToolingModels(gradleTarget); + if (toolinModels.isEmpty()) { + return GradleModelDef.EMPTY; } + + return GradleModelDef.create( + toolinModels, + Collections.>emptyList()); }; } @@ -98,20 +92,17 @@ private static GradleModelDefQuery2 createQuery2( return queries.iterator().next(); } - return new GradleModelDefQuery2() { - @Override - public GradleModelDef getModelDef(GradleTarget gradleTarget) { - List> projectInfoQueries = new ArrayList<>(); - List> toolingModels = new ArrayList<>(); + return (GradleTarget gradleTarget) -> { + List> projectInfoQueries = new ArrayList<>(); + List> toolingModels = new ArrayList<>(); - for (GradleModelDefQuery2 query: queries) { - GradleModelDef modelDef = safelyReturn(query.getModelDef(gradleTarget), query); + for (GradleModelDefQuery2 query: queries) { + GradleModelDef modelDef = safelyReturn(query.getModelDef(gradleTarget), query); - projectInfoQueries.addAll(modelDef.getProjectInfoQueries2()); - toolingModels.addAll(modelDef.getToolingModels()); - } - return GradleModelDef.create(toolingModels, projectInfoQueries); + projectInfoQueries.addAll(modelDef.getProjectInfoQueries2()); + toolingModels.addAll(modelDef.getToolingModels()); } + return GradleModelDef.create(toolingModels, projectInfoQueries); }; } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/filesupport/GradleTemplateWizardPanel.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/filesupport/GradleTemplateWizardPanel.java index c9da8be6..85134aab 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/filesupport/GradleTemplateWizardPanel.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/filesupport/GradleTemplateWizardPanel.java @@ -45,12 +45,7 @@ public GradleTemplateWizardPanel(TemplateWizard wizard) { this.jDestDirEdit.setText(getDisplayNameOfTargetDir(targetDir)); this.fileNameStr = trimmedText(jFileNameEdit); - this.fileNameStr.addChangeListener(new Runnable() { - @Override - public void run() { - updateDestFileEdit(); - } - }); + this.fileNameStr.addChangeListener(this::updateDestFileEdit); updateDestFileEdit(); } @@ -86,14 +81,11 @@ public void startValidation() { NewProjectStrings.getInvalidFileName()); bckgValidator.addValidator(fileNameValidator, fileNameStr); - Validator hasTargetDirValidator = new Validator() { - @Override - public Problem validateInput(Object inputType) { - if (inputType != null) { - return null; - } - return Problem.severe(NewProjectStrings.getTargetFolderNotAvailable()); + Validator hasTargetDirValidator = (Object inputType) -> { + if (inputType != null) { + return null; } + return Problem.severe(NewProjectStrings.getTargetFolderNotAvailable()); }; bckgValidator.addValidator(hasTargetDirValidator, PropertyFactory.constSource(targetDir)); diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/JavaExtension.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/JavaExtension.java index 3fef49a9..b1cfb1ae 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/JavaExtension.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/JavaExtension.java @@ -1,6 +1,5 @@ package org.netbeans.gradle.project.java; -import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.IOException; @@ -17,7 +16,6 @@ import org.jtrim.property.MutableProperty; import org.jtrim.property.PropertyFactory; import org.jtrim.property.PropertySource; -import org.jtrim.property.swing.SwingForwarderFactory; import org.jtrim.property.swing.SwingProperties; import org.jtrim.property.swing.SwingPropertySource; import org.jtrim.swing.concurrent.SwingTaskExecutor; @@ -66,7 +64,6 @@ import org.netbeans.gradle.project.script.ScriptFileProvider; import org.netbeans.gradle.project.util.CloseableAction; import org.netbeans.gradle.project.util.CloseableActionContainer; -import org.netbeans.gradle.project.util.NbFunction; import org.netbeans.spi.project.support.LookupProviderSupport; import org.netbeans.spi.project.ui.ProjectOpenedHook; import org.openide.filesystems.FileObject; @@ -137,13 +134,10 @@ public static PropertySource extensionOfProject(Project project) public static PropertySource javaModelOfProject(Project project) { PropertySource extRef = extensionOfProject(project); - return NbProperties.propertyOfProperty(extRef, new NbFunction>() { - @Override - public PropertySource apply(JavaExtension ext) { - return ext != null - ? ext.currentModel - : PropertyFactory.constSource(null); - } + return NbProperties.propertyOfProperty(extRef, (JavaExtension ext) -> { + return ext != null + ? ext.currentModel + : PropertyFactory.constSource(null); }); } @@ -499,16 +493,8 @@ private static PropertySource classPathProviderProperty( String... classPathTypes) { ClassPathProviderProperty src = new ClassPathProviderProperty(javaExt, classPathTypes); - return SwingProperties.fromSwingSource(src, new SwingForwarderFactory() { - @Override - public PropertyChangeListener createForwarder(final Runnable listener) { - return new PropertyChangeListener() { - @Override - public void propertyChange(PropertyChangeEvent evt) { - listener.run(); - } - }; - } + return SwingProperties.fromSwingSource(src, (Runnable listener) -> { + return evt -> listener.run(); }); } @@ -592,14 +578,11 @@ public Ref open() { new Object[]{type, javaExt.getProjectDirectoryAsFile()}); registry.register(type, paths); - return new Ref() { - @Override - public void close() { - registry.unregister(type, paths); - LOGGER.log(Level.FINE, - "Unregistered ClassPath ({0}) for project: {1}", - new Object[]{type, javaExt.getProjectDirectoryAsFile()}); - } + return () -> { + registry.unregister(type, paths); + LOGGER.log(Level.FINE, + "Unregistered ClassPath ({0}) for project: {1}", + new Object[]{type, javaExt.getProjectDirectoryAsFile()}); }; } } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/model/JavaProjectDependencies.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/model/JavaProjectDependencies.java index ad54ddd6..b55249fa 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/model/JavaProjectDependencies.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/model/JavaProjectDependencies.java @@ -1,7 +1,5 @@ package org.netbeans.gradle.project.java.model; -import com.google.common.base.Function; -import com.google.common.base.Predicate; import com.google.common.collect.Maps; import java.io.File; import java.net.URI; @@ -20,7 +18,6 @@ import org.jtrim.property.MutableProperty; import org.jtrim.property.PropertyFactory; import org.jtrim.property.PropertySource; -import org.jtrim.property.ValueConverter; import org.jtrim.swing.concurrent.SwingTaskExecutor; import org.jtrim.utils.ExceptionHelper; import org.netbeans.api.project.FileOwnerQuery; @@ -30,7 +27,6 @@ import org.netbeans.gradle.project.java.JavaExtension; import org.netbeans.gradle.project.properties.NbProperties; import org.netbeans.gradle.project.util.NbConsumer; -import org.netbeans.gradle.project.util.NbFunction; import org.netbeans.gradle.project.util.NbTaskExecutors; import org.openide.util.Utilities; @@ -55,24 +51,13 @@ public JavaProjectDependencies(JavaExtension javaExt, TaskExecutor executor) { this.updateExecutor = new GenericUpdateTaskExecutor(TaskExecutors.inOrderSimpleExecutor(executor)); this.translatedDependencies = PropertyFactory .memPropertyConcurrent(null, true, SwingTaskExecutor.getStrictExecutor(true)); - this.translatedJavaDependenciesMap = NbProperties.propertyOfProperty(translatedDependencies, new NbFunction>>() { - @Override - public PropertySource> apply(TranslatedDependencies src) { - return src != null - ? new ProjectDepedencyDefProperty(src.translatedDependencies) - : NO_DEPENDENCIES; - } + this.translatedJavaDependenciesMap = NbProperties.propertyOfProperty(translatedDependencies, (TranslatedDependencies src) -> { + return src != null + ? new ProjectDepedencyDefProperty(src.translatedDependencies) + : NO_DEPENDENCIES; }); - this.filteredTranslatedJavaDependenciesMap = PropertyFactory.convert(translatedJavaDependenciesMap, new ValueConverter, Map>() { - @Override - public Map convert(Map input) { - return Maps.filterValues(input, new Predicate() { - @Override - public boolean apply(JavaProjectDependencyDef input) { - return input != null; - } - }); - } + this.filteredTranslatedJavaDependenciesMap = PropertyFactory.convert(translatedJavaDependenciesMap, (input) -> { + return Maps.filterValues(input, dependencyDef -> dependencyDef != null); }); } @@ -89,12 +74,7 @@ public ProjectDepedencyDefProperty(Map src) { @Override public Map getValue() { - return Maps.transformValues(src, new Function() { - @Override - public JavaProjectDependencyDef apply(ProjectDependencyCandidate input) { - return input.projectDependency().getValue(); - } - }); + return Maps.transformValues(src, input -> input.projectDependency().getValue()); } @Override @@ -108,12 +88,7 @@ public ListenerRef addChangeListener(Runnable listener) { } public void updateDependencies() { - updateExecutor.execute(new Runnable() { - @Override - public void run() { - updateDependenciesNow(); - } - }); + updateExecutor.execute(this::updateDependenciesNow); } public PropertySource> translatedDependencies() { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/model/NamedSourceRoot.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/model/NamedSourceRoot.java index 5b3a2f15..2d667c14 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/model/NamedSourceRoot.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/model/NamedSourceRoot.java @@ -5,7 +5,6 @@ import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.Comparator; import java.util.List; import java.util.Locale; import java.util.Map; @@ -159,21 +158,18 @@ else if (nonResourceCount == 1) { private static List sortNamedSourceRoots(Collection namedRoots) { NamedSourceRoot[] orderedRoots = namedRoots.toArray(new NamedSourceRoot[namedRoots.size()]); - Arrays.sort(orderedRoots, new Comparator() { - @Override - public int compare(NamedSourceRoot root1, NamedSourceRoot root2) { - JavaSourceGroupID groupID1 = root1.getGroupID(); - JavaSourceGroupID groupID2 = root2.getGroupID(); + Arrays.sort(orderedRoots, (NamedSourceRoot root1, NamedSourceRoot root2) -> { + JavaSourceGroupID groupID1 = root1.getGroupID(); + JavaSourceGroupID groupID2 = root2.getGroupID(); - String sourceSetName1 = groupID1.getSourceSetName(); - String sourceSetName2 = groupID2.getSourceSetName(); + String sourceSetName1 = groupID1.getSourceSetName(); + String sourceSetName2 = groupID2.getSourceSetName(); - if (sourceSetName1.equals(sourceSetName2)) { - return compareGroups(groupID1.getGroupName(), groupID2.getGroupName()); - } - - return compareSourceSetNames(sourceSetName1, sourceSetName2); + if (sourceSetName1.equals(sourceSetName2)) { + return compareGroups(groupID1.getGroupName(), groupID2.getGroupName()); } + + return compareSourceSetNames(sourceSetName1, sourceSetName2); }); return Arrays.asList(orderedRoots); diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/model/ProjectDependencyCandidate.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/model/ProjectDependencyCandidate.java index 005e4f7b..a32752a2 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/model/ProjectDependencyCandidate.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/model/ProjectDependencyCandidate.java @@ -4,13 +4,11 @@ import java.util.List; import org.jtrim.property.PropertyFactory; import org.jtrim.property.PropertySource; -import org.jtrim.property.ValueConverter; import org.jtrim.utils.ExceptionHelper; import org.netbeans.api.project.Project; import org.netbeans.gradle.model.java.JavaSourceSet; import org.netbeans.gradle.project.java.JavaExtension; import org.netbeans.gradle.project.properties.NbProperties; -import org.netbeans.gradle.project.util.NbFunction; public final class ProjectDependencyCandidate { private static final PropertySource NO_DEPENDENCY @@ -34,13 +32,10 @@ private static PropertySource javaModelOfProject( final File dependency, PropertySource extRef) { - return NbProperties.propertyOfProperty(extRef, new NbFunction>() { - @Override - public PropertySource apply(JavaExtension ext) { - return ext != null - ? asProjectDepedencyDef(dependency, ext, ext.currentModel()) - : NO_DEPENDENCY; - } + return NbProperties.propertyOfProperty(extRef, (JavaExtension ext) -> { + return ext != null + ? asProjectDepedencyDef(dependency, ext, ext.currentModel()) + : NO_DEPENDENCY; }); } @@ -48,21 +43,18 @@ private static PropertySource asProjectDepedencyDef( final File dependency, final JavaExtension ext, final PropertySource modelRef) { - return PropertyFactory.convert(modelRef, new ValueConverter() { - @Override - public JavaProjectDependencyDef convert(NbJavaModel input) { - if (input == null) { - return null; - } - - NbJavaModule module = input.getMainModule(); - List sourceSets = module.getSourceSetsForOutput(dependency); - if (sourceSets.isEmpty()) { - return null; - } + return PropertyFactory.convert(modelRef, (NbJavaModel input) -> { + if (input == null) { + return null; + } - return new JavaProjectDependencyDef(ext, sourceSets); + NbJavaModule module = input.getMainModule(); + List sourceSets = module.getSourceSetsForOutput(dependency); + if (sourceSets.isEmpty()) { + return null; } + + return new JavaProjectDependencyDef(ext, sourceSets); }); } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/nodes/JavaDependenciesNode.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/nodes/JavaDependenciesNode.java index 0b1debe2..57300ee4 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/nodes/JavaDependenciesNode.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/nodes/JavaDependenciesNode.java @@ -7,7 +7,6 @@ import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -30,7 +29,6 @@ import org.netbeans.gradle.project.NbIcons; import org.netbeans.gradle.project.NbStrings; import org.netbeans.gradle.project.api.nodes.SingleNodeFactory; -import org.netbeans.gradle.project.api.task.CommandCompleteListener; import org.netbeans.gradle.project.java.JavaExtension; import org.netbeans.gradle.project.java.model.JavaProjectDependencies; import org.netbeans.gradle.project.java.model.JavaProjectDependencyDef; @@ -178,12 +176,7 @@ protected void addNotify() { // One way to do this is to calculate all the nodes in the background and then check if it is the // same as the one currently being displayed. lastModule.set(javaExt.getCurrentModel().getMainModule()); - listenerRefs.add(javaExt.addModelChangeListener(new Runnable() { - @Override - public void run() { - modelChanged(); - } - })); + listenerRefs.add(javaExt.addModelChangeListener(this::modelChanged)); } @Override @@ -326,12 +319,7 @@ else if (node1 instanceof FileDependency && node2 instanceof FileDependency) { private static List sortDependencyNodes(List nodes) { SingleNodeFactory[] nodesArray = nodes.toArray(new SingleNodeFactory[nodes.size()]); - Arrays.sort(nodesArray, new Comparator() { - @Override - public int compare(SingleNodeFactory o1, SingleNodeFactory o2) { - return compareDependencyNodes(o1, o2); - } - }); + Arrays.sort(nodesArray, DependenciesChildFactory::compareDependencyNodes); return Arrays.asList(nodesArray); } @@ -716,12 +704,9 @@ public DownloadSourcesAction(NbGradleProject project) { @Override public void actionPerformed(ActionEvent e) { DaemonTaskDef taskDef = DownloadSourcesTask.createTaskDef(project); - GradleDaemonManager.submitGradleTask(SOURCES_DOWNLOADER, taskDef, new CommandCompleteListener() { - @Override - public void onComplete(Throwable error) { - if (error != null) { - project.displayError(NbStrings.getDownloadSourcesFailure(), error); - } + GradleDaemonManager.submitGradleTask(SOURCES_DOWNLOADER, taskDef, (Throwable error) -> { + if (error != null) { + project.displayError(NbStrings.getDownloadSourcesFailure(), error); } }); } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/nodes/JavaExtensionNodes.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/nodes/JavaExtensionNodes.java index d5112037..85337bff 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/nodes/JavaExtensionNodes.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/nodes/JavaExtensionNodes.java @@ -25,7 +25,6 @@ import org.netbeans.gradle.project.view.NodeUtils; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; -import org.openide.nodes.Node; @ManualRefreshedNodes public final class JavaExtensionNodes @@ -90,12 +89,7 @@ private void addListedDirs(List toPopulate) { } private void addDependencies(List toPopulate) { - toPopulate.add(new SingleNodeFactory() { - @Override - public Node createNode() { - return new JavaDependenciesNode(javaExt); - } - }); + toPopulate.add(() -> new JavaDependenciesNode(javaExt)); } private NbJavaModule getCurrentModel() { @@ -104,12 +98,7 @@ private NbJavaModule getCurrentModel() { private static JavaSourceSet[] sortSourceSets(List sourceSets) { JavaSourceSet[] result = sourceSets.toArray(new JavaSourceSet[sourceSets.size()]); - Arrays.sort(result, new Comparator() { - @Override - public int compare(JavaSourceSet o1, JavaSourceSet o2) { - return NamedSourceRoot.compareSourceSetNames(o1.getName(), o2.getName()); - } - }); + Arrays.sort(result, Comparator.comparing(JavaSourceSet::getName, NamedSourceRoot::compareSourceSetNames)); return result; } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/nodes/JavaProjectContextActions.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/nodes/JavaProjectContextActions.java index 4ceed572..e68971b3 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/nodes/JavaProjectContextActions.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/nodes/JavaProjectContextActions.java @@ -140,29 +140,18 @@ private class SourceDirsAction extends SubmenuParentAction { @Override protected JMenu createMenu() { JMenu menu = new JMenu(NbStrings.getSourceDirsActionGroup()); - menu.add(backgroundTaskMenuItem(NbStrings.getCreateSourceDirsAction(), new Runnable() { - @Override - public void run() { - javaExt.getSourceDirsHandler().createDirectories(); - } + menu.add(backgroundTaskMenuItem(NbStrings.getCreateSourceDirsAction(), () -> { + javaExt.getSourceDirsHandler().createDirectories(); })); - menu.add(backgroundTaskMenuItem(NbStrings.getDeleteEmptySourceDirsAction(), new Runnable() { - @Override - public void run() { - javaExt.getSourceDirsHandler().deleteEmptyDirectories(); - } + menu.add(backgroundTaskMenuItem(NbStrings.getDeleteEmptySourceDirsAction(), () -> { + javaExt.getSourceDirsHandler().deleteEmptyDirectories(); })); return menu; } } private static void sortTestActions(List actions) { - Collections.sort(actions, new Comparator() { - @Override - public int compare(CustomTestAction o1, CustomTestAction o2) { - return StringUtils.STR_CMP.compare(o1.getDisplayName(), o2.getDisplayName()); - } - }); + Collections.sort(actions, Comparator.comparing(CustomTestAction::getDisplayName, StringUtils.STR_CMP::compare)); } @SuppressWarnings("serial") // don't care about serialization diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/nodes/JavaSourceSetNode.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/nodes/JavaSourceSetNode.java index 0cb60e29..29e48806 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/nodes/JavaSourceSetNode.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/nodes/JavaSourceSetNode.java @@ -116,12 +116,7 @@ public void refreshChildren() { @Override protected void addNotify() { listenerRegs.unregisterAll(); - listenerRegs.add(javaExt.addModelChangeListener(new Runnable() { - @Override - public void run() { - refresh(false); - } - })); + listenerRegs.add(javaExt.addModelChangeListener(() -> refresh(false))); } @Override @@ -155,12 +150,7 @@ private static int compareGroupNames(JavaSourceGroupName groupName1, JavaSourceG private static JavaSourceGroup[] sortGroups(Collection sourceGroups) { JavaSourceGroup[] result = sourceGroups.toArray(new JavaSourceGroup[sourceGroups.size()]); - Arrays.sort(result, new Comparator() { - @Override - public int compare(JavaSourceGroup o1, JavaSourceGroup o2) { - return compareGroupNames(o1.getGroupName(), o2.getGroupName()); - } - }); + Arrays.sort(result, Comparator.comparing(JavaSourceGroup::getGroupName, JavaSourceSetNodeChildFactory::compareGroupNames)); return result; } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/properties/JavaDebuggingPanel.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/properties/JavaDebuggingPanel.java index c738cd0d..3084b8e1 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/properties/JavaDebuggingPanel.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/properties/JavaDebuggingPanel.java @@ -8,8 +8,6 @@ import org.netbeans.gradle.project.api.config.PropertyReference; import org.netbeans.gradle.project.api.config.ui.CustomizerCategoryId; import org.netbeans.gradle.project.api.config.ui.ProfileBasedSettingsCategory; -import org.netbeans.gradle.project.api.config.ui.ProfileBasedSettingsPage; -import org.netbeans.gradle.project.api.config.ui.ProfileBasedSettingsPageFactory; import org.netbeans.gradle.project.api.config.ui.ProfileEditor; import org.netbeans.gradle.project.api.config.ui.ProfileEditorFactory; import org.netbeans.gradle.project.api.config.ui.ProfileInfo; @@ -60,12 +58,7 @@ private static CustomizerCategoryId getCategoryId() { } public static ProfileBasedSettingsCategory createDebuggingCustomizer(final boolean allowInherit) { - return new ProfileBasedSettingsCategory(getCategoryId(), new ProfileBasedSettingsPageFactory() { - @Override - public ProfileBasedSettingsPage createSettingsPage() { - return JavaDebuggingPanel.createSettingsPage(allowInherit); - } - }); + return new ProfileBasedSettingsCategory(getCategoryId(), () -> JavaDebuggingPanel.createSettingsPage(allowInherit)); } public static GlobalSettingsPage createSettingsPage(boolean allowInherit) { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/query/GradleBinaryForSourceQuery.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/query/GradleBinaryForSourceQuery.java index 8a3722f3..5c310e7e 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/query/GradleBinaryForSourceQuery.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/query/GradleBinaryForSourceQuery.java @@ -33,15 +33,10 @@ public final class GradleBinaryForSourceQuery private final NbSupplier moduleProvider; private final LazyChangeSupport changes; - public GradleBinaryForSourceQuery(final JavaExtension javaExt) { - this(new NbSupplier() { - @Override - public NbJavaModule get() { - return javaExt.getCurrentModel().getMainModule(); - } - }); + public GradleBinaryForSourceQuery(JavaExtension javaExt) { + this(() -> javaExt.getCurrentModel().getMainModule()); - ExceptionHelper.checkNotNullArgument(javaExt, "javaExt"); + Objects.requireNonNull(javaExt, "javaExt"); } public GradleBinaryForSourceQuery(NbSupplier moduleProvider) { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/query/GradleClassPathProvider.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/query/GradleClassPathProvider.java index e495f6a3..56f541f8 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/query/GradleClassPathProvider.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/query/GradleClassPathProvider.java @@ -52,9 +52,7 @@ import org.netbeans.gradle.project.util.ExcludeIncludeRules; import org.netbeans.gradle.project.util.LazyValue; import org.netbeans.gradle.project.util.ListenerRegistrations; -import org.netbeans.gradle.project.util.NbConsumer; import org.netbeans.gradle.project.util.NbFileUtils; -import org.netbeans.gradle.project.util.NbSupplier; import org.netbeans.gradle.project.util.NbTaskExecutors; import org.netbeans.spi.java.classpath.ClassPathFactory; import org.netbeans.spi.java.classpath.ClassPathImplementation; @@ -97,12 +95,7 @@ public GradleClassPathProvider(final JavaExtension javaExt) { this.currentPlatformRef = new AtomicReference<>(null); this.infoRefRef = new AtomicReference<>(null); this.loadedOnce = false; - this.scriptFileProviderRef = new LazyValue<>(new NbSupplier() { - @Override - public ScriptFileProvider get() { - return javaExt.getProject().getLookup().lookup(ScriptFileProvider.class); - } - }); + this.scriptFileProviderRef = new LazyValue<>(() -> javaExt.getProject().getLookup().lookup(ScriptFileProvider.class)); this.classpathResourcesRef = new AtomicReference<>(Collections.>emptyMap()); this.classpaths = new ConcurrentHashMap<>(); @@ -171,11 +164,8 @@ public ClassPath getClassPaths(String type) { } private void scheduleReloadPathResources() { - classpathUpdateExecutor.execute(new Runnable() { - @Override - public void run() { - loadPathResources(javaExt.getCurrentModel()); - } + classpathUpdateExecutor.execute(() -> { + loadPathResources(javaExt.getCurrentModel()); }); } @@ -207,32 +197,17 @@ private GradleProperty.BuildPlatform getPlatformProperty() { @Override public void onInitProject() { PropertySource platformProperty = NbProperties.weakListenerProperty(getPlatformProperty()); - propertyListenerRefs.add(platformProperty.addChangeListener(new Runnable() { - @Override - public void run() { - onPlatformChange(); - } - })); + propertyListenerRefs.add(platformProperty.addChangeListener(this::onPlatformChange)); PropertyReference detectProjectDependenciesByJarNameRef = CommonGlobalSettings.getDefault() .detectProjectDependenciesByJarName(); PropertySource detectProjectDependenciesByJarName = NbProperties.weakListenerProperty(PropertyFactory.lazilyNotifiedProperty(detectProjectDependenciesByJarNameRef.getForActiveProfile())); - propertyListenerRefs.add(detectProjectDependenciesByJarName.addChangeListener(new Runnable() { - @Override - public void run() { - scheduleReloadPathResources(); - } - })); + propertyListenerRefs.add(detectProjectDependenciesByJarName.addChangeListener(this::scheduleReloadPathResources)); PropertySource translatedDependencies = NbProperties.weakListenerProperty(javaExt.getProjectDependencies().translatedDependencies()); - propertyListenerRefs.add(translatedDependencies.addChangeListener(new Runnable() { - @Override - public void run() { - scheduleReloadPathResources(); - } - })); + propertyListenerRefs.add(translatedDependencies.addChangeListener(this::scheduleReloadPathResources)); } // These PropertyChangeListener methods are declared because @@ -328,7 +303,7 @@ private static void addSourcesOfModule( ExcludeIncludeRules includeRules = ExcludeIncludeRules.create(sourceGroup); Set sourceRoots = sourceGroup.getSourceRoots(); - result.addAll(getPathResources(sourceRoots, new HashSet(), includeRules)); + result.addAll(getPathResources(sourceRoots, new HashSet<>(), includeRules)); } } } @@ -358,13 +333,10 @@ public static List getPathResources( private void loadPathResources(NbJavaModel projectModel) { JavaProjectDependencies projectDependencies = javaExt.getProjectDependencies(); - projectDependencies.forAllCandidates(new NbConsumer() { - @Override - public void accept(ProjectDependencyCandidate candidate) { - NbGradleProject gradleProject = candidate.getProject().getLookup().lookup(NbGradleProject.class); - if (gradleProject != null) { - gradleProject.ensureLoadRequested(); - } + projectDependencies.forAllCandidates((ProjectDependencyCandidate candidate) -> { + NbGradleProject gradleProject = candidate.getProject().getLookup().lookup(NbGradleProject.class); + if (gradleProject != null) { + gradleProject.ensureLoadRequested(); } }); @@ -400,11 +372,8 @@ public void accept(ProjectDependencyCandidate candidate) { boolean changed = !prevClasspathResources.equals(newClasspathResources); if (changed) { - changesNotifier.execute(new Runnable() { - @Override - public void run() { - changes.firePropertyChange(ClassPathImplementation.PROP_RESOURCES, null, null); - } + changesNotifier.execute(() -> { + changes.firePropertyChange(ClassPathImplementation.PROP_RESOURCES, null, null); }); } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/query/GradleProjectSources.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/query/GradleProjectSources.java index 4723e379..84f29af8 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/query/GradleProjectSources.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/query/GradleProjectSources.java @@ -64,12 +64,7 @@ public GradleProjectSources(JavaExtension javaExt) { this.hasScanned = new AtomicBoolean(false); this.scanSourcesExecutor = NbTaskExecutors.newDefaultUpdateExecutor(); - javaExt.getSourceDirsHandler().addDirsCreatedListener(new Runnable() { - @Override - public void run() { - scanForSources(); - } - }); + javaExt.getSourceDirsHandler().addDirsCreatedListener(this::scanForSources); } public static SingleNodeFactory tryCreateSourceGroupNodeFactory(NamedSourceRoot root) { @@ -164,12 +159,7 @@ private Map findSourceGroups(JavaExtension javaExt) { @Override public void onModelChange() { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - scanForSources(); - } - }); + SwingUtilities.invokeLater(this::scanForSources); } public void scanForSources() { @@ -187,21 +177,13 @@ private void scanForSources(boolean initialScan) { } } - scanSourcesExecutor.execute(new Runnable() { - @Override - public void run() { - Map groups = findSourceGroups(javaExt); + scanSourcesExecutor.execute(() -> { + Map groups = findSourceGroups(javaExt); - currentGroups = groups; - LOGGER.log(Level.FINE, "Location of the sources of {0} has been updated.", javaExt.getName()); + currentGroups = groups; + LOGGER.log(Level.FINE, "Location of the sources of {0} has been updated.", javaExt.getName()); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - changeSupport.fireChange(); - } - }); - } + SwingUtilities.invokeLater(changeSupport::fireChange); }); } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/query/GradleSourceForBinaryQuery.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/query/GradleSourceForBinaryQuery.java index e8bce5fd..3d4bd471 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/query/GradleSourceForBinaryQuery.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/query/GradleSourceForBinaryQuery.java @@ -46,14 +46,9 @@ public final class GradleSourceForBinaryQuery private final LazyChangeSupport changes; public GradleSourceForBinaryQuery(final JavaExtension javaExt) { - this(new NbSupplier() { - @Override - public NbJavaModule get() { - return javaExt.getCurrentModel().getMainModule(); - } - }); + this(() -> javaExt.getCurrentModel().getMainModule()); - ExceptionHelper.checkNotNullArgument(javaExt, "javaExt"); + Objects.requireNonNull(javaExt, "javaExt"); } public GradleSourceForBinaryQuery(NbSupplier moduleProvider) { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/query/ProjectClassPathResourceBuilder.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/query/ProjectClassPathResourceBuilder.java index e57bb486..a9219e5b 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/query/ProjectClassPathResourceBuilder.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/query/ProjectClassPathResourceBuilder.java @@ -264,7 +264,7 @@ private void loadAllRuntimeClassPath(NbJavaModule mainModule) { setClassPathResources( SpecialClassPath.ALL_RUNTIME, - getPathResources(classPaths, new HashSet())); + getPathResources(classPaths, new HashSet<>())); } private void loadRuntimeForGlobalClassPath(NbJavaModel projectModel) { @@ -279,7 +279,7 @@ private void loadRuntimeForGlobalClassPath(NbJavaModel projectModel) { setClassPathResources( SpecialClassPath.RUNTIME_FOR_GLOBAL, - getPathResources(classPaths, new HashSet())); + getPathResources(classPaths, new HashSet<>())); } private void loadCompileForGlobalClassPath(NbJavaModel projectModel) { @@ -294,7 +294,7 @@ private void loadCompileForGlobalClassPath(NbJavaModel projectModel) { setClassPathResources( SpecialClassPath.COMPILE_FOR_GLOBAL, - getPathResources(classPaths, new HashSet())); + getPathResources(classPaths, new HashSet<>())); } private void removeOtherBuildOutputDirs(NbJavaModel projectModel, Set classPaths) { @@ -320,7 +320,7 @@ private void loadAllBuildOutputClassPath(NbJavaModel projectModel) { setClassPathResources( SpecialClassPath.ALL_BUILD_OUTPUT, - getPathResources(classPaths, new HashSet())); + getPathResources(classPaths, new HashSet<>())); } private void setClassPathResources( diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/tasks/DebuggerServiceFactory.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/tasks/DebuggerServiceFactory.java index 43c629f7..37aee71c 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/tasks/DebuggerServiceFactory.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/tasks/DebuggerServiceFactory.java @@ -6,11 +6,11 @@ import com.sun.jdi.connect.ListeningConnector; import com.sun.jdi.connect.Transport; import java.io.IOException; +import java.util.Collections; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.jtrim.cancel.CancellationToken; -import org.jtrim.concurrent.CancelableTask; import org.jtrim.concurrent.MonitorableTaskExecutorService; import org.jtrim.event.ListenerRef; import org.jtrim.utils.ExceptionHelper; @@ -74,24 +74,16 @@ private void startListening( final Map defaultArgs) { final Map services = AttacherListener.getJpdaServiceObjects(javaExt); - DEBUGGER_ATTACH_LISTENER.execute(cancelToken, new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) throws Exception { - final Thread currentThread = Thread.currentThread(); - ListenerRef cancelRef = cancelToken.addCancellationListener(new Runnable() { - @Override - public void run() { - currentThread.interrupt(); - } - }); - try { - JPDADebugger.startListening(connector, defaultArgs, new Object[]{services}); - LOGGER.log(Level.INFO, "JPDADebugger.startListening has successfully connected to the debugee."); - } catch (DebuggerStartException ex) { - LOGGER.log(Level.INFO, "JPDADebugger.startListening failed.", ex); - }finally { - cancelRef.unregister(); - } + DEBUGGER_ATTACH_LISTENER.execute(cancelToken, (CancellationToken taskCancelToken) -> { + Thread currentThread = Thread.currentThread(); + ListenerRef cancelRef = taskCancelToken.addCancellationListener(currentThread::interrupt); + try { + JPDADebugger.startListening(connector, defaultArgs, new Object[]{services}); + LOGGER.log(Level.INFO, "JPDADebugger.startListening has successfully connected to the debugee."); + } catch (DebuggerStartException ex) { + LOGGER.log(Level.INFO, "JPDADebugger.startListening failed.", ex); + }finally { + cancelRef.unregister(); } }, null); } @@ -143,16 +135,7 @@ private static String extractPort(String addr) { return addr.substring(sepIndex + 1); } - private static TaskVariableMap singleVar(final TaskVariable mapVar, final String mapValue) { - // TODO: In Java 8 this could be: - // return Collections.singletonMap(mapVar, mapValue)::get; - - assert mapVar != null; - return new TaskVariableMap() { - @Override - public String tryGetValueForVariable(TaskVariable variable) { - return mapVar.equals(variable) ? mapValue : null; - } - }; + private static TaskVariableMap singleVar(TaskVariable mapVar, String mapValue) { + return Collections.singletonMap(mapVar, mapValue)::get; } } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/tasks/GradleJavaBuiltInCommands.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/tasks/GradleJavaBuiltInCommands.java index 0435bb8d..58cfeed3 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/tasks/GradleJavaBuiltInCommands.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/tasks/GradleJavaBuiltInCommands.java @@ -25,18 +25,14 @@ import org.netbeans.gradle.project.api.config.ProfileDef; import org.netbeans.gradle.project.api.modelquery.GradleTarget; import org.netbeans.gradle.project.api.task.BuiltInGradleCommandQuery; -import org.netbeans.gradle.project.api.task.CommandExceptionHider; -import org.netbeans.gradle.project.api.task.ContextAwareCommandAction; import org.netbeans.gradle.project.api.task.ContextAwareCommandCompleteAction; import org.netbeans.gradle.project.api.task.ContextAwareCommandCompleteListener; import org.netbeans.gradle.project.api.task.ContextAwareCommandFinalizer; import org.netbeans.gradle.project.api.task.CustomCommandActions; import org.netbeans.gradle.project.api.task.ExecutedCommandContext; import org.netbeans.gradle.project.api.task.GradleCommandTemplate; -import org.netbeans.gradle.project.api.task.GradleTargetVerifier; import org.netbeans.gradle.project.api.task.SingleExecutionOutputProcessor; import org.netbeans.gradle.project.api.task.TaskKind; -import org.netbeans.gradle.project.api.task.TaskOutputProcessor; import org.netbeans.gradle.project.api.task.TaskVariable; import org.netbeans.gradle.project.api.task.TaskVariableMap; import org.netbeans.gradle.project.java.JavaExtension; @@ -260,35 +256,24 @@ private static String gradlePropertyArg(String propertyName, String value) { } private static CommandSelector newSingleTestArgSelector() { - return new CommandSelector() { - @Override - public Boolean choose(JavaExtension javaExt) { - GradleTarget env = javaExt.getCurrentModel().getEvaluationEnvironment(); - env.getGradleVersion(); - return GradleVersions.VERSION_2_3.compareTo(env.getGradleVersion()) <= 0; - } + return (JavaExtension javaExt) -> { + GradleTarget env = javaExt.getCurrentModel().getEvaluationEnvironment(); + env.getGradleVersion(); + return GradleVersions.VERSION_2_3.compareTo(env.getGradleVersion()) <= 0; }; } private static CommandSelector debugTestModeSelector() { final CommandSelector debugModeSelector = debugModeSelector(); final CommandSelector newSingleTestArgSelector = newSingleTestArgSelector(); - return new CommandSelector() { - @Override - public DebugTestMode choose(JavaExtension javaExt) { - return new DebugTestMode( - newSingleTestArgSelector.choose(javaExt), - debugModeSelector.choose(javaExt)); - } + return (JavaExtension javaExt) -> { + return new DebugTestMode(newSingleTestArgSelector.choose(javaExt), debugModeSelector.choose(javaExt)); }; } private static CommandSelector debugModeSelector() { - return new CommandSelector() { - @Override - public DebugMode choose(JavaExtension javaExt) { - return javaExt.getProjectProperties().debugMode().getActiveValue(); - } + return (JavaExtension javaExt) -> { + return javaExt.getProjectProperties().debugMode().getActiveValue(); }; } @@ -300,27 +285,19 @@ private static void addToDefaults( ExceptionHelper.checkNotNullArgument(selector, "selector"); ExceptionHelper.checkNotNullElements(choicesCopy, "choices"); - DEFAULT_TASKS.put(command, new CommandWithActionsRef() { - @Override - public CommandWithActions get(JavaExtension javaExt) { - ChoiceType choice = selector.choose(javaExt); - for (CommandChoice candidate: choicesCopy) { - if (Objects.equals(candidate.getChoice(), choice)) { - return candidate.getCommandWithActions(); - } + DEFAULT_TASKS.put(command, (JavaExtension javaExt) -> { + ChoiceType choice = selector.choose(javaExt); + for (CommandChoice candidate: choicesCopy) { + if (Objects.equals(candidate.getChoice(), choice)) { + return candidate.getCommandWithActions(); } - return choicesCopy.get(0).getCommandWithActions(); } + return choicesCopy.get(0).getCommandWithActions(); }); } - private static void addToDefaults(String command, final CommandWithActions task) { - DEFAULT_TASKS.put(command, new CommandWithActionsRef() { - @Override - public CommandWithActions get(JavaExtension javaExt) { - return task; - } - }); + private static void addToDefaults(String command, CommandWithActions task) { + DEFAULT_TASKS.put(command, javaExt -> task); } private static List debuggeeAttachesArguments(String taskName, String... additionalArgs) { @@ -430,21 +407,9 @@ private static boolean isTestFailureException(Throwable taskError) { return message.contains("there were failing tests"); } - private static CommandExceptionHider testFailureHider() { - return new CommandExceptionHider() { - @Override - public boolean hideException(Throwable taskError) { - return isTestFailureException(taskError); - } - }; - } - private static CustomCommandAdjuster hideTestFailures() { - return new CustomCommandAdjuster() { - @Override - public void adjust(JavaExtension javaExt, CustomCommandActions.Builder customActions) { - customActions.setCommandExceptionHider(testFailureHider()); - } + return (JavaExtension javaExt, CustomCommandActions.Builder customActions) -> { + customActions.setCommandExceptionHider(GradleJavaBuiltInCommands::isTestFailureException); }; } @@ -514,11 +479,8 @@ private static ContextAwareCommandCompleteListener displayTestResults( final Project project, final JavaExtension javaExt, final Lookup startContext) { - return new ContextAwareCommandCompleteListener() { - @Override - public void onComplete(ExecutedCommandContext executedCommandContext, Throwable error) { - displayTestReports(project, javaExt, executedCommandContext, startContext, error); - } + return (ExecutedCommandContext executedCommandContext, Throwable error) -> { + displayTestReports(project, javaExt, executedCommandContext, startContext, error); }; } @@ -549,45 +511,28 @@ private static void displayTestReports( } } - private static ContextAwareCommandCompleteAction displayTestAction(final JavaExtension javaExt) { - return new ContextAwareCommandCompleteAction() { - @Override - public ContextAwareCommandCompleteListener startCommand(Project project, Lookup commandContext) { - return displayTestResults(project, javaExt, commandContext); - } - }; + private static ContextAwareCommandCompleteAction displayTestAction(JavaExtension javaExt) { + return (Project project, Lookup commandContext) -> displayTestResults(project, javaExt, commandContext); } private static CustomCommandAdjuster displayTestResults() { - return new CustomCommandAdjuster() { - @Override - public void adjust(JavaExtension javaExt, CustomCommandActions.Builder customActions) { - customActions.setContextAwareFinalizer(displayTestAction(javaExt)); - } + return (JavaExtension javaExt, CustomCommandActions.Builder customActions) -> { + customActions.setContextAwareFinalizer(displayTestAction(javaExt)); }; } private static CustomCommandAdjuster needsGradle(String minGradleVersionStr) { final GradleVersion minGradleVersion = GradleVersion.version(minGradleVersionStr); - return new CustomCommandAdjuster() { - @Override - public void adjust(JavaExtension javaExt, CustomCommandActions.Builder customActions) { - customActions.setGradleTargetVerifier(new GradleTargetVerifier() { - @Override - public boolean checkTaskExecutable( - GradleTarget gradleTarget, - OutputWriter output, - OutputWriter errOutput) { - if (gradleTarget.getGradleVersion().compareTo(minGradleVersion) < 0) { - errOutput.println(NbStrings.getNeedsMinGradleVersion(minGradleVersion)); - return false; - } - - return true; - } - }); - } + return (JavaExtension javaExt, CustomCommandActions.Builder customActions) -> { + customActions.setGradleTargetVerifier((gradleTarget, output, errOutput) -> { + if (gradleTarget.getGradleVersion().compareTo(minGradleVersion) < 0) { + errOutput.println(NbStrings.getNeedsMinGradleVersion(minGradleVersion)); + return false; + } + + return true; + }); }; } @@ -597,53 +542,33 @@ private static SingleExecutionOutputProcessor attachDebuggerListener( final CancellationSource cancel = Cancellation.createCancellationSource(); customActions.setCancelToken(cancel.getToken()); - return new SingleExecutionOutputProcessor() { - @Override - public TaskOutputProcessor startExecution(Project project) { - return new DebugTextListener(new AttacherListener(javaExt, cancel.getController())); - } - }; + return (project) -> new DebugTextListener(new AttacherListener(javaExt, cancel.getController())); } private static CustomCommandAdjuster listenDebugger() { - return new CustomCommandAdjuster() { - @Override - public void adjust(JavaExtension javaExt, CustomCommandActions.Builder customActions) { - customActions.setCommandServiceFactory(new DebuggerServiceFactory(javaExt)); - } + return (JavaExtension javaExt, CustomCommandActions.Builder customActions) -> { + customActions.setCommandServiceFactory(new DebuggerServiceFactory(javaExt)); }; } private static CustomCommandAdjuster attachDebugger() { - return new CustomCommandAdjuster() { - @Override - public void adjust(JavaExtension javaExt, CustomCommandActions.Builder customActions) { - customActions.setSingleExecutionStdOutProcessor(attachDebuggerListener(javaExt, customActions)); - } + return (JavaExtension javaExt, CustomCommandActions.Builder customActions) -> { + customActions.setSingleExecutionStdOutProcessor(attachDebuggerListener(javaExt, customActions)); }; } private static ContextAwareCommandFinalizer applyClassesFinalizer(final Project project, final String className) { - return new ContextAwareCommandFinalizer() { - @Override - public void finalizeSuccessfulCommand(OutputWriter output, OutputWriter errOutput) { - DebugUtils.applyChanges(project, output, className); - } + return (OutputWriter output, OutputWriter errOutput) -> { + DebugUtils.applyChanges(project, output, className); }; } private static CustomCommandAdjuster applyClassesActions() { - return new CustomCommandAdjuster() { - @Override - public void adjust(JavaExtension javaExt, CustomCommandActions.Builder customActions) { - customActions.setContextAwareAction(new ContextAwareCommandAction() { - @Override - public ContextAwareCommandFinalizer startCommand(Project project, Lookup commandContext) { - String className = DebugUtils.getActiveClassName(project, commandContext); - return applyClassesFinalizer(project, className); - } - }); - } + return (JavaExtension javaExt, CustomCommandActions.Builder customActions) -> { + customActions.setContextAwareAction((Project project, Lookup commandContext) -> { + String className = DebugUtils.getActiveClassName(project, commandContext); + return applyClassesFinalizer(project, className); + }); }; } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/tasks/JavaGradleTaskVariableQuery.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/tasks/JavaGradleTaskVariableQuery.java index 4b8ded72..1570cb84 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/tasks/JavaGradleTaskVariableQuery.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/tasks/JavaGradleTaskVariableQuery.java @@ -95,41 +95,26 @@ private static VariableValue getCapitalized(TaskVariableMap variables, TaskVaria } private static void defineVariables(Map> varMap) { - addVariable(varMap, SOURCE_SET_NAME, new ValueGetter() { - @Override - public VariableValue getValue(TaskVariableMap variables, JavaExtension project, Lookup actionContext) { - return new VariableValue(getSourceSetName(project, actionContext)); - } + addVariable(varMap, SOURCE_SET_NAME, (TaskVariableMap variables, JavaExtension project, Lookup actionContext) -> { + return new VariableValue(getSourceSetName(project, actionContext)); }); - addVariable(varMap, SOURCE_SET_NAME_CAPITAL, new ValueGetter() { - @Override - public VariableValue getValue(TaskVariableMap variables, JavaExtension project, Lookup actionContext) { - return getCapitalized(variables, SOURCE_SET_NAME); - } + addVariable(varMap, SOURCE_SET_NAME_CAPITAL, (TaskVariableMap variables, JavaExtension project, Lookup actionContext) -> { + return getCapitalized(variables, SOURCE_SET_NAME); }); - addVariable(varMap, TEST_TASK_NAME, new ValueGetter() { - @Override - public VariableValue getValue(TaskVariableMap variables, JavaExtension project, Lookup actionContext) { - return new VariableValue(getTestTaskName(variables, project, actionContext)); - } + addVariable(varMap, TEST_TASK_NAME, (TaskVariableMap variables, JavaExtension project, Lookup actionContext) -> { + return new VariableValue(getTestTaskName(variables, project, actionContext)); }); - addVariable(varMap, TEST_TASK_NAME_CAPITAL, new ValueGetter() { - @Override - public VariableValue getValue(TaskVariableMap variables, JavaExtension project, Lookup actionContext) { - return getCapitalized(variables, TEST_TASK_NAME); - } + addVariable(varMap, TEST_TASK_NAME_CAPITAL, (TaskVariableMap variables, JavaExtension project, Lookup actionContext) -> { + return getCapitalized(variables, TEST_TASK_NAME); }); - addVariable(varMap, COVERAGE_REPORT_TASK_NAME, new ValueGetter() { - @Override - public VariableValue getValue(TaskVariableMap variables, JavaExtension project, Lookup actionContext) { - boolean hasCodeCoverage = project.getCurrentModel().getMainModule().getCodeCoverage().hasCodeCoverage(); - // TODO: It should be somehow determined by the build script - return new VariableValue(hasCodeCoverage ? "jacocoTestReport" : ""); - } + addVariable(varMap, COVERAGE_REPORT_TASK_NAME, (TaskVariableMap variables, JavaExtension project, Lookup actionContext) -> { + boolean hasCodeCoverage = project.getCurrentModel().getMainModule().getCodeCoverage().hasCodeCoverage(); + // TODO: It should be somehow determined by the build script + return new VariableValue(hasCodeCoverage ? "jacocoTestReport" : ""); }); } @@ -143,16 +128,9 @@ private static VariableDefMap getVariableDefMap() { } private static VariableDefMap createVariableDefMap() { - final Map> varMap - = new HashMap<>(); + Map> varMap = new HashMap<>(); defineVariables(varMap); - - return new VariableDefMap() { - @Override - public VariableDef tryGetDef(TaskVariable variable) { - return varMap.get(variable); - } - }; + return varMap::get; } private static void addVariable( diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/test/JavaCallstackFrameNode.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/test/JavaCallstackFrameNode.java index d9fcfaaa..64677c2f 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/test/JavaCallstackFrameNode.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/test/JavaCallstackFrameNode.java @@ -7,7 +7,6 @@ import javax.swing.SwingUtilities; import org.jtrim.cancel.Cancellation; import org.jtrim.cancel.CancellationToken; -import org.jtrim.concurrent.CancelableTask; import org.jtrim.utils.ExceptionHelper; import org.netbeans.api.project.Project; import org.netbeans.gradle.project.NbStrings; @@ -66,22 +65,16 @@ private void doActionNow(final ActionEvent e) { final ActionListener action = tryGetOpenLocationAction(javaExt.getProject(), frameInfo); if (action != null) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - action.actionPerformed(e); - } + SwingUtilities.invokeLater(() -> { + action.actionPerformed(e); }); } } @Override public void actionPerformed(final ActionEvent e) { - NbTaskExecutors.DEFAULT_EXECUTOR.execute(Cancellation.UNCANCELABLE_TOKEN, new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) { - doActionNow(e); - } + NbTaskExecutors.DEFAULT_EXECUTOR.execute(Cancellation.UNCANCELABLE_TOKEN, (CancellationToken cancelToken) -> { + doActionNow(e); }, null); } } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/test/JavaTestMethodNode.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/test/JavaTestMethodNode.java index d53d69fa..58e963a0 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/test/JavaTestMethodNode.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/test/JavaTestMethodNode.java @@ -8,7 +8,6 @@ import org.jtrim.cancel.Cancellation; import org.jtrim.cancel.CancellationSource; import org.jtrim.cancel.CancellationToken; -import org.jtrim.concurrent.CancelableTask; import org.jtrim.utils.ExceptionHelper; import org.netbeans.api.progress.ProgressHandle; import org.netbeans.api.project.Project; @@ -20,7 +19,6 @@ import org.netbeans.modules.gsf.testrunner.api.Trouble; import org.netbeans.modules.gsf.testrunner.ui.api.TestMethodNode; import org.netbeans.spi.project.SingleMethod; -import org.openide.util.Cancellable; import org.openide.util.Lookup; import org.openide.util.lookup.Lookups; @@ -165,12 +163,9 @@ private void doActionNow(final CancellationToken cancelToken, final ActionEvent if (!openTestMethod(cancelToken)) { final ActionListener openInEditorAction = tryGetOpenEditorActionAtFailure(); if (openInEditorAction != null) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (!cancelToken.isCanceled()) { - openInEditorAction.actionPerformed(e); - } + SwingUtilities.invokeLater(() -> { + if (!cancelToken.isCanceled()) { + openInEditorAction.actionPerformed(e); } }); } @@ -180,23 +175,17 @@ public void run() { @Override public void actionPerformed(final ActionEvent e) { final CancellationSource cancel = Cancellation.createCancellationSource(); - final ProgressHandle progress = ProgressHandle.createHandle(NbStrings.getJumpToSource(), new Cancellable() { - @Override - public boolean cancel() { - cancel.getController().cancel(); - return true; - } + final ProgressHandle progress = ProgressHandle.createHandle(NbStrings.getJumpToSource(), () -> { + cancel.getController().cancel(); + return true; }); - NbTaskExecutors.DEFAULT_EXECUTOR.execute(cancel.getToken(), new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) { - progress.start(); - try { - doActionNow(cancelToken, e); - } finally { - progress.finish(); - } + NbTaskExecutors.DEFAULT_EXECUTOR.execute(cancel.getToken(), (CancellationToken cancelToken) -> { + progress.start(); + try { + doActionNow(cancelToken, e); + } finally { + progress.finish(); } }, null); } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/test/JavaTestsuiteNode.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/test/JavaTestsuiteNode.java index 94c1dba8..4e07f187 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/test/JavaTestsuiteNode.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/test/JavaTestsuiteNode.java @@ -7,7 +7,6 @@ import javax.swing.SwingUtilities; import org.jtrim.cancel.Cancellation; import org.jtrim.cancel.CancellationToken; -import org.jtrim.concurrent.CancelableTask; import org.jtrim.utils.ExceptionHelper; import org.netbeans.api.project.Project; import org.netbeans.gradle.model.java.JavaSourceGroup; @@ -129,11 +128,8 @@ private void jumpToSourcesNow() { return; } - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - OpenEditorOutputListener.tryOpenFile(testFile, -1); - } + SwingUtilities.invokeLater(() -> { + OpenEditorOutputListener.tryOpenFile(testFile, -1); }); } @@ -145,11 +141,8 @@ public JumpToSourcesAction() { @Override public void actionPerformed(ActionEvent e) { - NbTaskExecutors.DEFAULT_EXECUTOR.execute(Cancellation.UNCANCELABLE_TOKEN, new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) { - jumpToSourcesNow(); - } + NbTaskExecutors.DEFAULT_EXECUTOR.execute(Cancellation.UNCANCELABLE_TOKEN, (CancellationToken cancelToken) -> { + jumpToSourcesNow(); }, null); } } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/test/ShowTestUtils.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/test/ShowTestUtils.java index 15c0b1e2..0fe9a863 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/test/ShowTestUtils.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/test/ShowTestUtils.java @@ -16,7 +16,6 @@ import org.jtrim.utils.ExceptionHelper; import org.netbeans.api.java.source.CompilationController; import org.netbeans.api.java.source.JavaSource; -import org.netbeans.api.java.source.Task; import org.netbeans.gradle.project.java.JavaExtension; import org.netbeans.gradle.project.output.OpenEditorOutputListener; import org.netbeans.gradle.project.util.StringUtils; @@ -53,30 +52,27 @@ public static boolean openTestMethod( cancelToken.checkCanceled(); try { - javaSource.runUserActionTask(new Task() { - @Override - public void run(CompilationController compilationController) throws Exception { - compilationController.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED); - Trees trees = compilationController.getTrees(); - CompilationUnitTree compilationUnitTree = compilationController.getCompilationUnit(); - List typeDecls = compilationUnitTree.getTypeDecls(); - for (Tree tree: typeDecls) { - Element element = trees.getElement(trees.getPath(compilationUnitTree, tree)); - if (element != null && element.getKind() == ElementKind.CLASS && element.getSimpleName().contentEquals(fo2open[0].getName())) { - List methodElements = ElementFilter.methodsIn(element.getEnclosedElements()); - for (Element child: methodElements) { - if (cancelToken.isCanceled()) { - return; - } + javaSource.runUserActionTask((CompilationController compilationController) -> { + compilationController.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED); + Trees trees = compilationController.getTrees(); + CompilationUnitTree compilationUnitTree = compilationController.getCompilationUnit(); + List typeDecls = compilationUnitTree.getTypeDecls(); + for (Tree tree: typeDecls) { + Element element = trees.getElement(trees.getPath(compilationUnitTree, tree)); + if (element != null && element.getKind() == ElementKind.CLASS && element.getSimpleName().contentEquals(fo2open[0].getName())) { + List methodElements = ElementFilter.methodsIn(element.getEnclosedElements()); + for (Element child: methodElements) { + if (cancelToken.isCanceled()) { + return; + } - if (child.getSimpleName().contentEquals(specificTestcase.getTestMethodName())) { - long pos = trees.getSourcePositions().getStartPosition(compilationUnitTree, trees.getTree(child)); - line[0] = compilationUnitTree.getLineMap().getLineNumber(pos); - break; - } + if (child.getSimpleName().contentEquals(specificTestcase.getTestMethodName())) { + long pos = trees.getSourcePositions().getStartPosition(compilationUnitTree, trees.getTree(child)); + line[0] = compilationUnitTree.getLineMap().getLineNumber(pos); + break; } - break; } + break; } } }, true); @@ -87,12 +83,9 @@ public void run(CompilationController compilationController) throws Exception { cancelToken.checkCanceled(); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (!cancelToken.isCanceled()) { - OpenEditorOutputListener.tryOpenFile(fo2open[0], (int)line[0]); - } + SwingUtilities.invokeLater(() -> { + if (!cancelToken.isCanceled()) { + OpenEditorOutputListener.tryOpenFile(fo2open[0], (int)line[0]); } }); diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/test/TestXmlDisplayer.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/test/TestXmlDisplayer.java index b46970ad..74ea955e 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/test/TestXmlDisplayer.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/java/test/TestXmlDisplayer.java @@ -1,7 +1,6 @@ package org.netbeans.gradle.project.java.test; import java.io.File; -import java.io.FilenameFilter; import java.util.ArrayList; import java.util.List; import java.util.Locale; @@ -82,12 +81,9 @@ private File[] getTestReportFiles() { return NO_FILES; } - File[] result = reportDir.listFiles(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - String normName = name.toLowerCase(Locale.ROOT); - return normName.startsWith("test-") && normName.endsWith(".xml"); - } + File[] result = reportDir.listFiles((File dir, String name) -> { + String normName = name.toLowerCase(Locale.ROOT); + return normName.startsWith("test-") && normName.endsWith(".xml"); }); return result != null ? result : NO_FILES; diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/license/LicenseManager.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/license/LicenseManager.java index f94e74a9..faa72396 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/license/LicenseManager.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/license/LicenseManager.java @@ -3,12 +3,12 @@ import java.io.IOException; import java.util.HashMap; import java.util.Map; +import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import org.jtrim.cancel.Cancellation; import org.jtrim.cancel.CancellationToken; -import org.jtrim.concurrent.CancelableTask; import org.jtrim.concurrent.MonitorableTaskExecutor; import org.jtrim.concurrent.TaskExecutor; import org.jtrim.concurrent.TaskExecutors; @@ -41,25 +41,16 @@ public PropertySource getRegisterListenerAction( ExceptionHelper.checkNotNullArgument(modelProperty, "modelProperty"); ExceptionHelper.checkNotNullArgument(headerProperty, "headerProperty"); - return NbProperties.combine(headerProperty, modelProperty, new NbBiFunction() { - @Override - public CloseableAction apply(LicenseHeaderInfo headerInfo, T model) { - return getRegisterListenerAction(model, headerInfo); - } + return NbProperties.combine(headerProperty, modelProperty, (LicenseHeaderInfo headerInfo, T model) -> { + return getRegisterListenerAction(model, headerInfo); }); } private CloseableAction getRegisterListenerAction( - final T ownerModel, - final LicenseHeaderInfo header) { - ExceptionHelper.checkNotNullArgument(ownerModel, "ownerModel"); - - return new CloseableAction() { - @Override - public CloseableAction.Ref open() { - return impl.registerLicense(ownerModel, header); - } - }; + T ownerModel, + LicenseHeaderInfo header) { + Objects.requireNonNull(ownerModel, "ownerModel"); + return () -> impl.registerLicense(ownerModel, header); } private static final class Impl { @@ -116,36 +107,30 @@ private void addLicense(RegisteredLicense registration) throws IOException { } private void doUnregister(final LK key) { - syncExecutor.execute(Cancellation.UNCANCELABLE_TOKEN, new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) throws IOException { - RegisteredLicense registration = licenseRegistartions.get(key); - if (registration == null) { - LOGGER.log(Level.WARNING, "Too many unregister call to LicenseManager.", new Exception()); - return; - } + syncExecutor.execute(Cancellation.UNCANCELABLE_TOKEN, (CancellationToken cancelToken) -> { + RegisteredLicense registration = licenseRegistartions.get(key); + if (registration == null) { + LOGGER.log(Level.WARNING, "Too many unregister call to LicenseManager.", new Exception()); + return; + } - if (registration.release()) { - licenseRegistartions.remove(key); - removeLicense(registration); - } + if (registration.release()) { + licenseRegistartions.remove(key); + removeLicense(registration); } }, null); } private void doRegister(final T ownerModel, final LK key) { - syncExecutor.execute(Cancellation.UNCANCELABLE_TOKEN, new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) throws IOException { - RegisteredLicense registration = licenseRegistartions.get(key); - if (registration == null) { - registration = new RegisteredLicense<>(getLicenseDef(ownerModel, key)); - licenseRegistartions.put(key, registration); - addLicense(registration); - } - else { - registration.use(); - } + syncExecutor.execute(Cancellation.UNCANCELABLE_TOKEN, (CancellationToken cancelToken) -> { + RegisteredLicense registration = licenseRegistartions.get(key); + if (registration == null) { + registration = new RegisteredLicense<>(getLicenseDef(ownerModel, key)); + licenseRegistartions.put(key, registration); + addLicense(registration); + } + else { + registration.use(); } }, null); } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/license/LicenseManagers.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/license/LicenseManagers.java index 4ab0e0ce..e9727f2d 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/license/LicenseManagers.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/license/LicenseManagers.java @@ -11,23 +11,10 @@ public final class LicenseManagers { public static LicenseManager createProjectLicenseManager(LicenseStore licenseStore) { - NbFunction licenseRootProvider = new NbFunction() { - @Override - public Path apply(NbGradleModel ownerModel) { - return ownerModel.getSettingsDir(); - } - }; - - NbFunction modelNameProvider = new NbFunction() { - @Override - public String apply(NbGradleModel ownerModel) { - return NbFileUtils.getFileNameStr(ownerModel.getSettingsDir()); - } - }; - TaskExecutor executor = NbTaskExecutors.DEFAULT_EXECUTOR; - - return createLicenseManager(executor, licenseStore, licenseRootProvider, modelNameProvider); + return createLicenseManager(executor, licenseStore, NbGradleModel::getSettingsDir, (NbGradleModel ownerModel) -> { + return NbFileUtils.getFileNameStr(ownerModel.getSettingsDir()); + }); } public static LicenseManager createLicenseManager( @@ -40,18 +27,12 @@ public static LicenseManager createLicenseManager( ExceptionHelper.checkNotNullArgument(licenseRootProvider, "licenseRootProvider"); ExceptionHelper.checkNotNullArgument(modelNameProvider, "modelNameProvider"); - NbBiFunction licenseKeyFactory = new NbBiFunction() { - @Override - public DefaultLicenseKey apply(T ownerModel, LicenseHeaderInfo licenseHeader) { - return tryCreateLicenseKey(ownerModel, licenseHeader, licenseRootProvider); - } + NbBiFunction licenseKeyFactory = (T ownerModel, LicenseHeaderInfo licenseHeader) -> { + return tryCreateLicenseKey(ownerModel, licenseHeader, licenseRootProvider); }; - NbBiFunction licenseDefFactory = new NbBiFunction() { - @Override - public DefaultLicenseDef apply(T ownerModel, DefaultLicenseKey licenseKey) { - return createLicenseDef(ownerModel, licenseKey, modelNameProvider); - } + NbBiFunction licenseDefFactory = (T ownerModel, DefaultLicenseKey licenseKey) -> { + return createLicenseDef(ownerModel, licenseKey, modelNameProvider); }; return new LicenseManager<>(executor, licenseStore, licenseKeyFactory, licenseDefFactory); diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/lookups/LookupsEx.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/lookups/LookupsEx.java index 57db14ae..2544a911 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/lookups/LookupsEx.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/lookups/LookupsEx.java @@ -10,12 +10,7 @@ public static NbSupplier> asSupplier(final Lookup sr ExceptionHelper.checkNotNullArgument(src, "src"); ExceptionHelper.checkNotNullArgument(type, "type"); - return new NbSupplier>() { - @Override - public Collection get() { - return src.lookupAll(type); - } - }; + return () -> src.lookupAll(type); } private LookupsEx() { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/model/DefaultGradleModelLoader.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/model/DefaultGradleModelLoader.java index f01ccad8..368b2a8d 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/model/DefaultGradleModelLoader.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/model/DefaultGradleModelLoader.java @@ -2,6 +2,7 @@ import java.io.File; import java.io.IOException; +import java.io.UncheckedIOException; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; @@ -28,7 +29,6 @@ import org.gradle.util.GradleVersion; import org.jtrim.cancel.Cancellation; import org.jtrim.cancel.CancellationToken; -import org.jtrim.concurrent.CancelableTask; import org.jtrim.concurrent.MonitorableTaskExecutorService; import org.jtrim.concurrent.TaskExecutor; import org.jtrim.concurrent.Tasks; @@ -57,7 +57,6 @@ import org.netbeans.gradle.project.properties.NbGradleCommonProperties; import org.netbeans.gradle.project.properties.global.CommonGlobalSettings; import org.netbeans.gradle.project.script.ScriptFileProvider; -import org.netbeans.gradle.project.tasks.DaemonTask; import org.netbeans.gradle.project.tasks.GradleArguments; import org.netbeans.gradle.project.tasks.GradleDaemonFailures; import org.netbeans.gradle.project.tasks.GradleDaemonManager; @@ -65,7 +64,6 @@ import org.netbeans.gradle.project.tasks.vars.StringResolver; import org.netbeans.gradle.project.tasks.vars.StringResolvers; import org.netbeans.gradle.project.util.GradleVersions; -import org.netbeans.gradle.project.util.NbFunction; import org.netbeans.gradle.project.util.NbSupplier; import org.netbeans.gradle.project.util.NbTaskExecutors; import org.netbeans.gradle.project.view.GlobalErrorReporter; @@ -122,19 +120,11 @@ private static GradleModelCache getDefaultCache() { result = new GradleModelCache(cacheSize.getValue()); if (DEFAULT_CACHE_REF.compareAndSet(null, result)) { final GradleModelCache cache = result; - cacheSize.addChangeListener(new Runnable() { - @Override - public void run() { - cache.setMaxCapacity(cacheSize.getValue()); - } + cacheSize.addChangeListener(() -> { + cache.setMaxCapacity(cacheSize.getValue()); }); cache.setMaxCapacity(cacheSize.getValue()); - cache.addModelUpdateListener(new ProjectModelUpdatedListener() { - @Override - public void onUpdateProject(NbGradleModel newModel) { - updateProjectFromCacheIfNeeded(newModel); - } - }); + cache.addModelUpdateListener(DefaultGradleModelLoader::updateProjectFromCacheIfNeeded); } else { result = DEFAULT_CACHE_REF.get(); @@ -261,11 +251,8 @@ private void onModelLoaded( listener.updateModel(model, error); } else { - modelLoadNotifier.execute(Cancellation.UNCANCELABLE_TOKEN, new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) { - listener.updateModel(model, error); - } + modelLoadNotifier.execute(Cancellation.UNCANCELABLE_TOKEN, (CancellationToken cancelToken) -> { + listener.updateModel(model, error); }, null); } } @@ -316,26 +303,23 @@ public void fetchModel( return; } - modelLoadNotifier.execute(Cancellation.UNCANCELABLE_TOKEN, new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) { - NbGradleModel model = null; - boolean needLoadFromScripts = true; + modelLoadNotifier.execute(Cancellation.UNCANCELABLE_TOKEN, (CancellationToken cancelToken) -> { + NbGradleModel model = null; + boolean needLoadFromScripts = true; - try { - ProjectLoadRequest projectLoadKey = getProjectLoadKey(project); - model = mayFetchFromCache ? tryGetFromCache(projectLoadKey) : null; - if (model == null || hasUnloadedExtension(model)) { - model = tryGetFromPersistentCache(projectLoadKey); - } - else { - needLoadFromScripts = false; - } - } finally { - onModelLoaded(model, null, listener); - if (needLoadFromScripts) { - fetchModelWithoutPersistentCache(mayFetchFromCache, listener, aboutToCompleteListener); - } + try { + ProjectLoadRequest projectLoadKey = getProjectLoadKey(project); + model = mayFetchFromCache ? tryGetFromCache(projectLoadKey) : null; + if (model == null || hasUnloadedExtension(model)) { + model = tryGetFromPersistentCache(projectLoadKey); + } + else { + needLoadFromScripts = false; + } + } finally { + onModelLoaded(model, null, listener); + if (needLoadFromScripts) { + fetchModelWithoutPersistentCache(mayFetchFromCache, listener, aboutToCompleteListener); } } }, null); @@ -410,14 +394,11 @@ private static boolean isUpToDateModel(NbGradleModel rootModel, Path dir) { } private CommandCompleteListener projectTaskCompleteListener(final Runnable loadCompletedListener) { - return new CommandCompleteListener() { - @Override - public void onComplete(Throwable error) { - try { - GradleTasks.projectTaskCompleteListener(project).onComplete(error); - } finally { - loadCompletedListener.run(); - } + return (Throwable error) -> { + try { + GradleTasks.projectTaskCompleteListener(project).onComplete(error); + } finally { + loadCompletedListener.run(); } }; } @@ -430,35 +411,32 @@ private void fetchModelWithoutPersistentCache( final Runnable safeCompleteListener = Tasks.runOnceTask(aboutToCompleteListener, false); String caption = NbStrings.getLoadingProjectText(project.getDisplayName()); - GradleDaemonManager.submitGradleTask(projectLoader, caption, new DaemonTask() { - @Override - public void run(CancellationToken cancelToken, ProgressHandle progress) { - ProjectLoadRequest projectLoadKey = getProjectLoadKey(project); - - NbGradleModel model = null; - Throwable error = null; - try { - ProjectLoadRequest fixedLoadKey = fixProjectLoadKey(cancelToken, projectLoadKey, progress); - if (mayFetchFromCache) { - model = tryGetFromCache(fixedLoadKey); - } - if (model == null || hasUnloadedExtension(model)) { - model = loadModelWithProgress(cancelToken, fixedLoadKey, progress, model); - } - } catch (IOException | BuildException ex) { - error = ex; - } catch (GradleConnectionException ex) { - error = ex; - } catch (GradleModelLoadError ex) { - error = ex; - reportModelLoadError(project, ex); - } finally { - safeCompleteListener.run(); - onModelLoaded(model, error, listener); - - if (error != null) { - GradleDaemonFailures.getDefaultHandler().tryHandleFailure(error); - } + GradleDaemonManager.submitGradleTask(projectLoader, caption, (CancellationToken cancelToken, ProgressHandle progress) -> { + ProjectLoadRequest projectLoadKey = getProjectLoadKey(project); + + NbGradleModel model = null; + Throwable error = null; + try { + ProjectLoadRequest fixedLoadKey = fixProjectLoadKey(cancelToken, projectLoadKey, progress); + if (mayFetchFromCache) { + model = tryGetFromCache(fixedLoadKey); + } + if (model == null || hasUnloadedExtension(model)) { + model = loadModelWithProgress(cancelToken, fixedLoadKey, progress, model); + } + } catch (IOException | BuildException ex) { + error = ex; + } catch (GradleConnectionException ex) { + error = ex; + } catch (GradleModelLoadError ex) { + error = ex; + reportModelLoadError(project, ex); + } finally { + safeCompleteListener.run(); + onModelLoaded(model, error, listener); + + if (error != null) { + GradleDaemonFailures.getDefaultHandler().tryHandleFailure(error); } } }, true, projectTaskCompleteListener(safeCompleteListener)); @@ -690,28 +668,15 @@ public Builder(NbGradleProject project) { this.projectLoader = DEFAULT_PROJECT_LOADER; this.modelLoadNotifier = DEFAULT_MODEL_LOAD_NOTIFIER; this.loadedProjectManager = LoadedProjectManager.getDefault(); - this.persistentCache = new MultiFileModelCache<>(defaultModelPersister(project), new NbFunction() { - @Override - public PersistentModelKey apply(NbGradleModel arg) { - try { - return new PersistentModelKey(arg).normalize(); - } catch (IOException ex) { - throw new RuntimeException(ex); - } + this.persistentCache = new MultiFileModelCache<>(defaultModelPersister(project), (NbGradleModel model) -> { + try { + return new PersistentModelKey(model).normalize(); + } catch (IOException ex) { + throw new UncheckedIOException(ex); } }); - this.cacheRef = new NbSupplier() { - @Override - public GradleModelCache get() { - return getDefaultCache(); - } - }; - this.cacheSizeIncreaser = new CacheSizeIncreaser() { - @Override - public void requiresCacheSize(GradleModelCache cache, int minimumCacheSize) { - ensureCacheSize(cache, minimumCacheSize); - } - }; + this.cacheRef = DefaultGradleModelLoader::getDefaultCache; + this.cacheSizeIncreaser = DefaultGradleModelLoader::ensureCacheSize; } private static PersistentModelStore defaultModelPersister(NbGradleProject project) { @@ -740,12 +705,7 @@ public void setPersistentCache(PersistentModelCache persistentCac public void setCacheRef(final GradleModelCache cache) { ExceptionHelper.checkNotNullArgument(cache, "cache"); - this.cacheRef = new NbSupplier() { - @Override - public GradleModelCache get() { - return cache; - } - }; + this.cacheRef = () -> cache; } public DefaultGradleModelLoader create() { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/model/LazyPersistentModelStoreFactory.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/model/LazyPersistentModelStoreFactory.java index 2276183c..b1d75b9d 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/model/LazyPersistentModelStoreFactory.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/model/LazyPersistentModelStoreFactory.java @@ -61,12 +61,7 @@ public void persistModel(T model, Path dest) throws IOException { queueLock.unlock(); } - persisterExecutor.execute(new Runnable() { - @Override - public void run() { - persistQueue(); - } - }); + persisterExecutor.execute(this::persistQueue); } private void fixEmptyQueue() { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/model/issue/IssueDetailsPanel.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/model/issue/IssueDetailsPanel.java index 2e316c46..5fc72488 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/model/issue/IssueDetailsPanel.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/model/issue/IssueDetailsPanel.java @@ -5,7 +5,6 @@ import java.awt.Toolkit; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import javax.swing.JButton; import org.netbeans.gradle.project.NbStrings; import org.openide.DialogDescriptor; @@ -22,11 +21,8 @@ public IssueDetailsPanel(String detailsContent) { public static JButton createShowStackTraceButton(final String caption, final String detailsContent) { JButton button = new JButton(NbStrings.getShowStackTrace()); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - showModalDialog(caption, detailsContent); - } + button.addActionListener((ActionEvent e) -> { + showModalDialog(caption, detailsContent); }); return button; } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/model/issue/ModelLoadIssueReporter.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/model/issue/ModelLoadIssueReporter.java index 5a5c51c4..1a886cbe 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/model/issue/ModelLoadIssueReporter.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/model/issue/ModelLoadIssueReporter.java @@ -154,11 +154,8 @@ public static void reportAllIssues( ExceptionHelper.checkNotNullElements(issues, "issues"); final List issuesCopy = CollectionUtils.copyNullSafeList(issues); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - reportAllIssuesNow(message, issuesCopy); - } + SwingUtilities.invokeLater(() -> { + reportAllIssuesNow(message, issuesCopy); }); } @@ -203,11 +200,8 @@ public static void reportAllIssues(Collection issues) String extensionName = setToString(getExtensionNames(issuesCopy)); final String message = NbStrings.getInternalExtensionErrorInProject(extensionName, projectName); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - reportAllIssuesNow(message, issuesCopy); - } + SwingUtilities.invokeLater(() -> { + reportAllIssuesNow(message, issuesCopy); }); } @@ -237,11 +231,8 @@ public static void reportBuildScriptError(final NbGradleProject project, final T ExceptionHelper.checkNotNullArgument(project, "project"); ExceptionHelper.checkNotNullArgument(error, "error"); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - reportBuildScriptErrorNow(project, error); - } + SwingUtilities.invokeLater(() -> { + reportBuildScriptErrorNow(project, error); }); } @@ -318,11 +309,8 @@ private static void reportDependencyResolutionFailures(List issues) { final List issuesCopy = CollectionUtils.copyNullSafeList(issues); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - reportDependencyResolutionFailures(issuesCopy); - } + SwingUtilities.invokeLater(() -> { + reportDependencyResolutionFailures(issuesCopy); }); } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/newproject/NewProjectUtils.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/newproject/NewProjectUtils.java index 40bd94ba..a9999016 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/newproject/NewProjectUtils.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/newproject/NewProjectUtils.java @@ -141,13 +141,10 @@ public static Validator createProjectNameValidator() { createPatternValidator(RECOMMENDED_PROJECTNAME_PATTERN, Problem.Level.WARNING, NewProjectStrings.getNotRecommendedProjectName())); - Validator notEmptyValidator = new Validator() { - @Override - public Problem validateInput(String inputType) { - return inputType.isEmpty() - ? Problem.severe(NewProjectStrings.getProjectNameMustNotBeEmpty()) - : null; - } + Validator notEmptyValidator = (String inputType) -> { + return inputType.isEmpty() + ? Problem.severe(NewProjectStrings.getProjectNameMustNotBeEmpty()) + : null; }; return merge(notEmptyValidator, patternValidators); @@ -168,92 +165,83 @@ public static Validator createVersionValidator() { } public static Validator createNewFolderValidator() { - return new Validator() { - @Override - public Problem validateInput(String inputType) { - String projectDirStr = inputType.trim(); - if (projectDirStr.isEmpty()) { - return Problem.severe(NewProjectStrings.getInvalidPath()); - } + return (String inputType) -> { + String projectDirStr = inputType.trim(); + if (projectDirStr.isEmpty()) { + return Problem.severe(NewProjectStrings.getInvalidPath()); + } - File projectDir = FileUtil.normalizeFile(new File(projectDirStr)); - if (projectDir == null) { - return Problem.severe(NewProjectStrings.getInvalidPath()); - } + File projectDir = FileUtil.normalizeFile(new File(projectDirStr)); + if (projectDir == null) { + return Problem.severe(NewProjectStrings.getInvalidPath()); + } - // This check is required because checking these kind of paths - // can be extremly slow. - if (Utilities.isWindows() && projectDir.getAbsolutePath().startsWith("\\\\")) { - return Problem.severe(NewProjectStrings.getCannotCreateFolderHere()); - } + // This check is required because checking these kind of paths + // can be extremly slow. + if (Utilities.isWindows() && projectDir.getAbsolutePath().startsWith("\\\\")) { + return Problem.severe(NewProjectStrings.getCannotCreateFolderHere()); + } - if (projectDir.exists()) { - return Problem.severe(NewProjectStrings.getDirectoryAlreadyExists()); - } + if (projectDir.exists()) { + return Problem.severe(NewProjectStrings.getDirectoryAlreadyExists()); + } - File rootPath = projectDir; - while (rootPath != null && !rootPath.exists()) { - rootPath = rootPath.getParentFile(); - } + File rootPath = projectDir; + while (rootPath != null && !rootPath.exists()) { + rootPath = rootPath.getParentFile(); + } - if (rootPath == null || !rootPath.canWrite() || !rootPath.isDirectory()) { - return Problem.severe(NewProjectStrings.getCannotCreateFolderHere()); - } - return null; + if (rootPath == null || !rootPath.canWrite() || !rootPath.isDirectory()) { + return Problem.severe(NewProjectStrings.getCannotCreateFolderHere()); } + return null; }; } public static Validator createVariableNameValidator() { - return new Validator() { - @Override - public Problem validateInput(String inputType) { - if (inputType.isEmpty()) { - return Problem.severe(NewProjectStrings.getIllegalIdentifier()); - } + return (String inputType) -> { + if (inputType.isEmpty()) { + return Problem.severe(NewProjectStrings.getIllegalIdentifier()); + } - if (!Character.isJavaIdentifierStart(inputType.charAt(0))) { - return Problem.severe(NewProjectStrings.getIllegalIdentifier()); - } + if (!Character.isJavaIdentifierStart(inputType.charAt(0))) { + return Problem.severe(NewProjectStrings.getIllegalIdentifier()); + } - for (int i = 1; i < inputType.length(); i++) { - if (!Character.isJavaIdentifierPart(inputType.charAt(i))) { - return Problem.severe(NewProjectStrings.getIllegalIdentifier()); - } + for (int i = 1; i < inputType.length(); i++) { + if (!Character.isJavaIdentifierPart(inputType.charAt(i))) { + return Problem.severe(NewProjectStrings.getIllegalIdentifier()); } - return null; } + return null; }; } public static Validator createClassNameValidator(final boolean optional) { - final Validator varNameValidator = createVariableNameValidator(); + Validator varNameValidator = createVariableNameValidator(); - return new Validator() { - @Override - public Problem validateInput(String inputType) { - if (optional && inputType.isEmpty()) { - return null; - } + return (String inputType) -> { + if (optional && inputType.isEmpty()) { + return null; + } - if (inputType.endsWith(".")) { - return Problem.severe(NewProjectStrings.getIllegalIdentifier()); - } + if (inputType.endsWith(".")) { + return Problem.severe(NewProjectStrings.getIllegalIdentifier()); + } - String[] parts = inputType.split(Pattern.quote(".")); - for (String part: parts) { - Problem problem = varNameValidator.validateInput(part); - if (problem != null) { - assert problem.getLevel() == Problem.Level.SEVERE; - return problem; - } + String[] parts = inputType.split(Pattern.quote(".")); + for (String part: parts) { + Problem problem = varNameValidator.validateInput(part); + if (problem != null) { + assert problem.getLevel() == Problem.Level.SEVERE; + return problem; } - if (parts.length == 1) { - return Problem.warning(NewProjectStrings.getShouldNotUseDefaultPackage()); - } - - return null; } + if (parts.length == 1) { + return Problem.warning(NewProjectStrings.getShouldNotUseDefaultPackage()); + } + + return null; }; } @@ -301,14 +289,11 @@ public static ListenerRef setupNewProjectValidators( NewProjectUtils.createNewFolderValidator(), projectFolder)); - Runnable projectFolderUpdater = new Runnable() { - @Override - public void run() { - File location = new File( - jProjectLocationEdit.getText().trim(), - jProjectNameEdit.getText().trim()); - jProjectFolderEdit.setText(location.getPath()); - } + Runnable projectFolderUpdater = () -> { + File location = new File( + jProjectLocationEdit.getText().trim(), + jProjectNameEdit.getText().trim()); + jProjectFolderEdit.setText(location.getPath()); }; refs.add(projectName.addChangeListener(projectFolderUpdater)); diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/others/ReflectionHelper.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/others/ReflectionHelper.java index 3dc81bb6..129dc3d4 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/others/ReflectionHelper.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/others/ReflectionHelper.java @@ -102,13 +102,8 @@ public static Object tryInvoke(Method method, Object obj, Object... args) { return null; } - public static ClassFinder constClassFinder(final Class type) { - return new ClassFinder() { - @Override - public Class tryGetClass() { - return type; - } - }; + public static ClassFinder constClassFinder(Class type) { + return () -> type; } public static ClassFinder[] constClassFinders(Class... types) { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/output/IOTabs.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/output/IOTabs.java index c1b333df..fea402d6 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/output/IOTabs.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/output/IOTabs.java @@ -29,13 +29,10 @@ public final class IOTabs { = new IOTabMaintainer<>(createTaskIOTabFactory()); private static IOTabFactory createTaskIOTabFactory() { - return new IOTabFactory() { - @Override - public TaskIOTab create(String caption) { - TaskTabAction[] actions = createActions(caption); - InputOutput io = IOProvider.getDefault().getIO(caption, actions); - return new TaskIOTab(io, actions); - } + return (String caption) -> { + TaskTabAction[] actions = createActions(caption); + InputOutput io = IOProvider.getDefault().getIO(caption, actions); + return new TaskIOTab(io, actions); }; } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/output/OutputUrlConsumer.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/output/OutputUrlConsumer.java index b19f2d8c..385f4f7d 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/output/OutputUrlConsumer.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/output/OutputUrlConsumer.java @@ -52,13 +52,7 @@ public OutputLinkDef tryFindLink(String line) { public static Runnable getUrlOpenTask(final URL url) { ExceptionHelper.checkNotNullArgument(url, "url"); - - return new Runnable() { - @Override - public void run() { - HtmlBrowser.URLDisplayer.getDefault().showURLExternal(url); - } - }; + return () -> HtmlBrowser.URLDisplayer.getDefault().showURLExternal(url); } public static OutputListener getUrlListener(final URL url) { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/output/StackTraceConsumer.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/output/StackTraceConsumer.java index c197e949..de7a58fc 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/output/StackTraceConsumer.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/output/StackTraceConsumer.java @@ -69,12 +69,7 @@ private OpenEditorOutputListener tryCreateLinkListener( public ActionListener tryGetOpenEditorAction(String line) { final OutputLinkDef linkDef = tryFindLink(line); if (linkDef != null) { - return new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - linkDef.getAction().run(); - } - }; + return (ActionEvent e) -> linkDef.getAction().run(); } else { return null; diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/output/SubPathConsumer.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/output/SubPathConsumer.java index 46b3f2b3..7c462db1 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/output/SubPathConsumer.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/output/SubPathConsumer.java @@ -56,17 +56,14 @@ public static OutputLinkFinder pathLinks(Collection roots) { return linkFinders.get(0); } - return new OutputLinkFinder() { - @Override - public OutputLinkDef tryFindLink(String line) { - for (OutputLinkFinder linkFinder: linkFinders) { - OutputLinkDef result = linkFinder.tryFindLink(line); - if (result != null) { - return result; - } + return (String line) -> { + for (OutputLinkFinder linkFinder: linkFinders) { + OutputLinkDef result = linkFinder.tryFindLink(line); + if (result != null) { + return result; } - return null; } + return null; }; } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/output/TaskTabAction.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/output/TaskTabAction.java index cbd8577d..0015a2e0 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/output/TaskTabAction.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/output/TaskTabAction.java @@ -59,11 +59,6 @@ protected final AsyncGradleTask getLastTask() { } public final void setEnableAction(final boolean enabled) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - setEnabled(enabled); - } - }); + SwingUtilities.invokeLater(() -> setEnabled(enabled)); } } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ActiveSettingsQueryExProxy.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ActiveSettingsQueryExProxy.java index 13e5752f..922e1cc5 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ActiveSettingsQueryExProxy.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ActiveSettingsQueryExProxy.java @@ -2,9 +2,9 @@ import org.jtrim.property.PropertySource; import org.jtrim.utils.ExceptionHelper; +import org.netbeans.gradle.project.api.config.ActiveSettingsQuery; import org.netbeans.gradle.project.api.config.PropertyDef; import org.netbeans.gradle.project.api.config.SingleProfileSettings; -import org.netbeans.gradle.project.util.NbFunction; import org.w3c.dom.Element; public final class ActiveSettingsQueryExProxy implements ActiveSettingsQueryEx { @@ -18,18 +18,8 @@ public ActiveSettingsQueryExProxy(PropertySource wrapped) this.wrappedRef = wrapped; - this.currentProfileSettingsEx = NbProperties.propertyOfProperty(wrapped, new NbFunction>() { - @Override - public PropertySource apply(ActiveSettingsQueryEx arg) { - return arg.currentProfileSettingsEx(); - } - }); - this.currentProfileSettings = NbProperties.propertyOfProperty(wrapped, new NbFunction>() { - @Override - public PropertySource apply(ActiveSettingsQueryEx arg) { - return arg.currentProfileSettings(); - } - }); + this.currentProfileSettingsEx = NbProperties.propertyOfProperty(wrapped, ActiveSettingsQueryEx::currentProfileSettingsEx); + this.currentProfileSettings = NbProperties.propertyOfProperty(wrapped, ActiveSettingsQuery::currentProfileSettings); } private ActiveSettingsQueryEx getWrapped() { @@ -50,12 +40,7 @@ public PropertySource currentProfileSettingsEx() { public PropertySource getProperty(final PropertyDef propertyDef) { ExceptionHelper.checkNotNullArgument(propertyDef, "propertyDef"); - return NbProperties.propertyOfProperty(wrappedRef, new NbFunction>() { - @Override - public PropertySource apply(ActiveSettingsQueryEx arg) { - return arg.getProperty(propertyDef); - } - }); + return NbProperties.propertyOfProperty(wrappedRef, arg -> arg.getProperty(propertyDef)); } @Override diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ConfigXmlUtils.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ConfigXmlUtils.java index 45853917..132fe80a 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ConfigXmlUtils.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ConfigXmlUtils.java @@ -9,7 +9,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; -import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -362,12 +361,7 @@ private static Set addAttributeChildrenToXml( // order, so that any sensible implementation will save them in the // same order every time (avoiding unnecessary differences in the // properties file). - Collections.sort(attributes, new Comparator() { - @Override - public int compare(KeyValuePair o1, KeyValuePair o2) { - return nodeSorter.compare(o1.key, o1.key); - } - }); + Collections.sort(attributes, (o1, o2) -> nodeSorter.compare(o1.key, o2.key)); Set result = CollectionsEx.newHashSet(attributes.size()); for (KeyValuePair keyValue: attributes) { @@ -426,12 +420,7 @@ else if (!ignoreValue) { parent.setAttribute(KEYWORD_VALUE, value); } - Collections.sort(childEntries, new Comparator() { - @Override - public int compare(NamedNode o1, NamedNode o2) { - return nodeProperties.compare(o1.name, o2.name); - } - }); + Collections.sort(childEntries, (o1, o2) -> nodeProperties.compare(o1.name, o2.name)); for (NamedNode child: childEntries) { String xmlKey = toElementName(child.name); @@ -494,18 +483,15 @@ public static void addAuxiliary(Document document, Element... auxElements) { } Element[] sortedAuxElements = auxElements.clone(); - Arrays.sort(sortedAuxElements, new Comparator() { - @Override - public int compare(Element o1, Element o2) { - String uri1 = o1.getNamespaceURI(); - String uri2 = o2.getNamespaceURI(); - int uriCmp = nullSafeStrCmp(uri1, uri2); - if (uriCmp != 0) { - return uriCmp; - } - - return nullSafeStrCmp(o1.getNodeName(), o2.getNodeName()); + Arrays.sort(sortedAuxElements, (Element o1, Element o2) -> { + String uri1 = o1.getNamespaceURI(); + String uri2 = o2.getNamespaceURI(); + int uriCmp = nullSafeStrCmp(uri1, uri2); + if (uriCmp != 0) { + return uriCmp; } + + return nullSafeStrCmp(o1.getNodeName(), o2.getNodeName()); }); Element auxRoot = document.createElement(AUXILIARY_NODE_NAME); diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/DefaultProjectSettingsProvider.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/DefaultProjectSettingsProvider.java index b26c3c66..0ae5098d 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/DefaultProjectSettingsProvider.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/DefaultProjectSettingsProvider.java @@ -108,11 +108,8 @@ public void loadSettingsForProfile(CancellationToken cancelToken, ProfileKey pro ExceptionHelper.checkNotNullArgument(cancelToken, "cancelToken"); ExceptionHelper.checkNotNullArgument(settingsQueryListener, "settingsQueryListener"); - profileLoader.loadActiveSettingsForProfile(profile, new ActiveSettingsQueryListener() { - @Override - public void onLoad(ActiveSettingsQuery settings) { - settingsQueryListener.onLoad(new ExtensionActiveSettingsQuery(settings, extensionName)); - } + profileLoader.loadActiveSettingsForProfile(profile, (ActiveSettingsQuery settings) -> { + settingsQueryListener.onLoad(new ExtensionActiveSettingsQuery(settings, extensionName)); }); } } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ExtensionProjectSettingsPageDefs.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ExtensionProjectSettingsPageDefs.java index 2776f5dc..713cdfbf 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ExtensionProjectSettingsPageDefs.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ExtensionProjectSettingsPageDefs.java @@ -50,15 +50,10 @@ public static ProjectCustomizer.CompositeCategoryProvider createProfileBasedCust ExceptionHelper.checkNotNullArgument(extensionSettings, "extensionSettings"); ExceptionHelper.checkNotNullArgument(pageFactory, "pageFactory"); - ProfileBasedCustomizer.PanelFactory panelFactory = new ProfileBasedCustomizer.PanelFactory() { - @Override - public ProfileBasedPanel createPanel() { - ProfileBasedSettingsPage settingsPage = pageFactory.createSettingsPage(); - return ProfileBasedPanel.createPanel(project, extensionSettings, settingsPage); - } - }; - - return new ProfileBasedCustomizer(categoryId.getCategoryName(), categoryId.getDisplayName(), panelFactory); + return new ProfileBasedCustomizer(categoryId.getCategoryName(), categoryId.getDisplayName(), () -> { + ProfileBasedSettingsPage settingsPage = pageFactory.createSettingsPage(); + return ProfileBasedPanel.createPanel(project, extensionSettings, settingsPage); + }); } private ProjectSettingsProvider.ExtensionSettings getExtensionSettings() { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/GenericProfileSettings.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/GenericProfileSettings.java index c0f7acb8..3aced290 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/GenericProfileSettings.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/GenericProfileSettings.java @@ -96,12 +96,7 @@ public void ensureLoaded() { return; } - loadExecutor.execute(new Runnable() { - @Override - public void run() { - loadNowIfNotLoaded(); - } - }); + loadExecutor.execute(this::loadNowIfNotLoaded); } @Override @@ -110,12 +105,7 @@ public void ensureLoadedAndWait() { } public void loadEventually() { - loadExecutor.execute(new Runnable() { - @Override - public void run() { - loadNowAlways(); - } - }); + loadExecutor.execute(this::loadNowAlways); } public void loadAndWait() { @@ -171,12 +161,7 @@ private void saveEventually() { return; } - saveExecutor.execute(new Runnable() { - @Override - public void run() { - saveAndWait(); - } - }); + saveExecutor.execute(this::saveAndWait); } @Override diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/GradleCustomizer.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/GradleCustomizer.java index 159ec800..c2ae1e3a 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/GradleCustomizer.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/GradleCustomizer.java @@ -1,8 +1,6 @@ package org.netbeans.gradle.project.properties; import java.awt.Dialog; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -11,7 +9,6 @@ import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; -import javax.swing.JComponent; import javax.swing.JPanel; import org.jtrim.utils.ExceptionHelper; import org.netbeans.gradle.model.util.CollectionUtils; @@ -67,12 +64,9 @@ private static ProfileBasedCustomizer toCustomizer( CustomizerCategoryId categoryId = settingsCategory.getCategoryId(); final ProfileBasedSettingsPageFactory pageFactory = settingsCategory.getSettingsPageFactory(); - return new ProfileBasedCustomizer(categoryId.getCategoryName(), categoryId.getDisplayName(), new ProfileBasedCustomizer.PanelFactory() { - @Override - public ProfileBasedPanel createPanel() { - ProfileBasedSettingsPage settingsPage = pageFactory.createSettingsPage(); - return ProfileBasedPanel.createPanel(project, settingsPage); - } + return new ProfileBasedCustomizer(categoryId.getCategoryName(), categoryId.getDisplayName(), () -> { + ProfileBasedSettingsPage settingsPage = pageFactory.createSettingsPage(); + return ProfileBasedPanel.createPanel(project, settingsPage); }); } @@ -156,37 +150,27 @@ public void showCustomizer() { } } - ProjectCustomizer.CategoryComponentProvider panelProvider = new ProjectCustomizer.CategoryComponentProvider() { - @Override - public JComponent create(ProjectCustomizer.Category category) { - String name = category.getName(); - if (name == null) { - LOGGER.log(Level.WARNING, "null category name."); - return new JPanel(); - } - - ProjectCustomizer.CompositeCategoryProvider customizer = customizersByName.get(name); - if (customizer == null) { - LOGGER.log(Level.WARNING, "Requested category cannot be found {0}.", name); - return new JPanel(); - } - - return customizer.createComponent(category, lookup); + ProjectCustomizer.CategoryComponentProvider panelProvider = (ProjectCustomizer.Category category) -> { + String name = category.getName(); + if (name == null) { + LOGGER.log(Level.WARNING, "null category name."); + return new JPanel(); } - }; - ActionListener okListener = new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - // no-op + ProjectCustomizer.CompositeCategoryProvider customizer = customizersByName.get(name); + if (customizer == null) { + LOGGER.log(Level.WARNING, "Requested category cannot be found {0}.", name); + return new JPanel(); } + + return customizer.createComponent(category, lookup); }; Dialog dlg = ProjectCustomizer.createCustomizerDialog( categories, panelProvider, CommonProjectPropertiesPanel.CATEGORY_ID.getCategoryName(), - okListener, + e -> { }, HelpCtx.DEFAULT_HELP); dlg.setTitle(NbStrings.getProjectPropertiesDlgTitle(project.getDisplayName())); diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/MultiProfileProperties.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/MultiProfileProperties.java index 167b6852..b83e1e3a 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/MultiProfileProperties.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/MultiProfileProperties.java @@ -10,13 +10,11 @@ import org.jtrim.property.MutableProperty; import org.jtrim.property.PropertyFactory; import org.jtrim.property.PropertySource; -import org.jtrim.property.ValueConverter; import org.jtrim.swing.concurrent.SwingTaskExecutor; import org.jtrim.utils.ExceptionHelper; import org.netbeans.gradle.project.api.config.PropertyDef; import org.netbeans.gradle.project.api.config.SingleProfileSettings; import org.netbeans.gradle.project.api.config.ValueMerger; -import org.netbeans.gradle.project.api.config.ValueReference; import org.netbeans.gradle.project.event.ChangeListenerManager; import org.netbeans.gradle.project.event.GenericChangeListenerManager; import org.netbeans.gradle.project.util.NbFunction; @@ -47,12 +45,7 @@ public ListenerRef addChangeListener(Runnable listener) { }; // Just for type safety. An unsafe cast would do because of type erasure. - this.currentProfileSettings = PropertyFactory.convert(currentProfileSettingsEx, new ValueConverter() { - @Override - public SingleProfileSettings convert(SingleProfileSettingsEx input) { - return input; - } - }); + this.currentProfileSettings = PropertyFactory.convert(currentProfileSettingsEx, input -> input); } @Override @@ -120,11 +113,8 @@ private static ValueType mergePropertyValues( return childValue; } - return valueMerger.mergeValues(childValue, new ValueReference() { - @Override - public ValueType getValue() { - return mergePropertyValues(settingsIndex + 1, valueMerger, properties); - } + return valueMerger.mergeValues(childValue, () -> { + return mergePropertyValues(settingsIndex + 1, valueMerger, properties); }); } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/NbGradleConfigProvider.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/NbGradleConfigProvider.java index e770d3d8..2dff87b5 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/NbGradleConfigProvider.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/NbGradleConfigProvider.java @@ -19,7 +19,6 @@ import org.jtrim.cancel.Cancellation; import org.jtrim.cancel.CancellationToken; import org.jtrim.collections.CollectionsEx; -import org.jtrim.concurrent.CancelableTask; import org.jtrim.concurrent.GenericUpdateTaskExecutor; import org.jtrim.concurrent.MonitorableTaskExecutor; import org.jtrim.concurrent.TaskExecutor; @@ -203,28 +202,21 @@ public void removeConfiguration(final NbGradleConfiguration config) { return; } - profileIOExecutor.execute(Cancellation.UNCANCELABLE_TOKEN, new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) throws IOException { - removeFromConfig(config); - Path profileFile = SettingsFiles.getFilesForProfile(rootDirectory, config.getProfileDef())[0]; - if (!Files.deleteIfExists(profileFile)) { - LOGGER.log(Level.INFO, "Profile was deleted but no profile file was found: {0}", profileFile); - } - - fireConfigurationListChange(); - + profileIOExecutor.execute(Cancellation.UNCANCELABLE_TOKEN, (CancellationToken cancelToken) -> { + removeFromConfig(config); + Path profileFile = SettingsFiles.getFilesForProfile(rootDirectory, config.getProfileDef())[0]; + if (!Files.deleteIfExists(profileFile)) { + LOGGER.log(Level.INFO, "Profile was deleted but no profile file was found: {0}", profileFile); } + + fireConfigurationListChange(); }, null); } public void addConfiguration(final NbGradleConfiguration config) { - executeOnEdt(new Runnable() { - @Override - public void run() { - addToConfig(Collections.singleton(config)); - fireConfigurationListChange(); - } + executeOnEdt(() -> { + addToConfig(Collections.singleton(config)); + fireConfigurationListChange(); }); } @@ -317,11 +309,8 @@ private void saveActiveProfileNow() throws IOException { } private void saveActiveProfile() { - profileIOExecutor.execute(Cancellation.UNCANCELABLE_TOKEN, new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) throws IOException { - saveActiveProfileNow(); - } + profileIOExecutor.execute(Cancellation.UNCANCELABLE_TOKEN, (CancellationToken cancelToken) -> { + saveActiveProfileNow(); }, null); } @@ -361,12 +350,7 @@ private void updateByKeyNow(ProfileKey profileKey) { } private void updateByKey(final ProfileKey profileKey) { - profileApplierExecutor.execute(new Runnable() { - @Override - public void run() { - updateByKeyNow(profileKey); - } - }); + profileApplierExecutor.execute(() -> updateByKeyNow(profileKey)); } public void setActiveConfiguration(final NbGradleConfiguration configuration) { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/NbGradleConfiguration.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/NbGradleConfiguration.java index a5cbe13e..38d3b220 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/NbGradleConfiguration.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/NbGradleConfiguration.java @@ -14,18 +14,15 @@ public final class NbGradleConfiguration implements ProjectConfiguration { public static final NbGradleConfiguration DEFAULT_CONFIG = new NbGradleConfiguration(null); - private static final Comparator ALPHABETICAL_ORDER = new Comparator() { - @Override - public int compare(NbGradleConfiguration o1, NbGradleConfiguration o2) { - if (DEFAULT_CONFIG.equals(o1)) { - return DEFAULT_CONFIG.equals(o2) ? 0 : -1; - } - if (DEFAULT_CONFIG.equals(o2)) { - return DEFAULT_CONFIG.equals(o1) ? 0 : 1; - } - - return StringUtils.STR_CMP.compare(o1.getDisplayName(), o2.getDisplayName()); + private static final Comparator ALPHABETICAL_ORDER = (o1, o2) -> { + if (DEFAULT_CONFIG.equals(o1)) { + return DEFAULT_CONFIG.equals(o2) ? 0 : -1; } + if (DEFAULT_CONFIG.equals(o2)) { + return DEFAULT_CONFIG.equals(o1) ? 0 : 1; + } + + return StringUtils.STR_CMP.compare(o1.getDisplayName(), o2.getDisplayName()); }; private final ProfileDef profileDef; diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/NbGradleSingleProjectConfigProvider.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/NbGradleSingleProjectConfigProvider.java index e55d83a5..cbbae36d 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/NbGradleSingleProjectConfigProvider.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/NbGradleSingleProjectConfigProvider.java @@ -15,7 +15,6 @@ import org.jtrim.property.MutableProperty; import org.jtrim.property.PropertyFactory; import org.jtrim.property.PropertySource; -import org.jtrim.property.ValueConverter; import org.jtrim.swing.concurrent.SwingTaskExecutor; import org.jtrim.utils.ExceptionHelper; import org.netbeans.gradle.model.util.CollectionUtils; @@ -26,7 +25,6 @@ import org.netbeans.gradle.project.api.config.ProfileKey; import org.netbeans.gradle.project.model.NbGradleModel; import org.netbeans.gradle.project.model.ProjectModelChangeListener; -import org.netbeans.gradle.project.util.NbFunction; import org.netbeans.spi.project.ProjectConfigurationProvider; import org.netbeans.spi.project.ui.CustomizerProvider; @@ -57,27 +55,11 @@ private NbGradleSingleProjectConfigProvider( this.commonConfigRef = PropertyFactory.memPropertyConcurrent(multiProjectProvider, SwingTaskExecutor.getStrictExecutor(false)); this.extensionProfiles = Collections.emptySet(); - this.activeConfig = NbProperties.propertyOfProperty(commonConfigRef, new NbFunction>() { - @Override - public PropertySource apply(NbGradleConfigProvider arg) { - return arg.activeConfiguration(); - } - }); - - this.configs = NbProperties.propertyOfProperty(commonConfigRef, new NbFunction>>() { - @Override - public PropertySource> apply(NbGradleConfigProvider arg) { - return arg.configurations(); - } - }); + this.activeConfig = NbProperties.propertyOfProperty(commonConfigRef, NbGradleConfigProvider::activeConfiguration); + this.configs = NbProperties.propertyOfProperty(commonConfigRef, NbGradleConfigProvider::configurations); PropertySource activeSettingsQueryRef; - activeSettingsQueryRef = PropertyFactory.convert(commonConfigRef, new ValueConverter() { - @Override - public ActiveSettingsQueryEx convert(NbGradleConfigProvider arg) { - return arg.getActiveSettingsQuery(); - } - }); + activeSettingsQueryRef = PropertyFactory.convert(commonConfigRef, NbGradleConfigProvider::getActiveSettingsQuery); this.activeSettingsQuery = new ActiveSettingsQueryExProxy(activeSettingsQueryRef); this.propertyChangeForwarder = createPropertyChanges(); diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/NbProperties.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/NbProperties.java index 8a25f7b2..b8914346 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/NbProperties.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/NbProperties.java @@ -6,17 +6,13 @@ import javax.swing.JList; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; -import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; -import org.jtrim.event.EventDispatcher; import org.jtrim.event.ListenerRef; import org.jtrim.event.ListenerRegistries; import org.jtrim.event.SimpleListenerRegistry; import org.jtrim.event.UnregisteredListenerRef; import org.jtrim.property.PropertyFactory; import org.jtrim.property.PropertySource; -import org.jtrim.property.ValueConverter; -import org.jtrim.property.swing.SwingForwarderFactory; import org.jtrim.property.swing.SwingProperties; import org.jtrim.property.swing.SwingPropertySource; import org.jtrim.utils.ExceptionHelper; @@ -24,7 +20,6 @@ import org.netbeans.gradle.project.util.NbBiFunction; import org.netbeans.gradle.project.util.NbFunction; import org.openide.util.Lookup; -import org.openide.util.LookupEvent; import org.openide.util.LookupListener; public final class NbProperties { @@ -32,16 +27,8 @@ public static PropertySource weakListenerProperty(PropertySource< return new WeakListenerProperty<>(src); } - public static SimpleListenerRegistry asChangeListenerRegistry( - final PropertySource property) { - ExceptionHelper.checkNotNullArgument(property, "property"); - - return new SimpleListenerRegistry() { - @Override - public ListenerRef registerListener(Runnable listener) { - return property.addChangeListener(listener); - } - }; + public static SimpleListenerRegistry asChangeListenerRegistry(PropertySource property) { + return property::addChangeListener; } public static PropertySource atomicValueView( @@ -68,12 +55,9 @@ public static PropertySource between( final int minValue, final int maxValue) { - return PropertyFactory.convert(wrapped, new ValueConverter() { - @Override - public Boolean convert(Integer input) { - if (input == null) return null; - return input <= maxValue && input >= minValue; - } + return PropertyFactory.convert(wrapped, (Integer input) -> { + if (input == null) return null; + return input <= maxValue && input >= minValue; }); } @@ -96,12 +80,7 @@ public static PropertySource propertyOfProperty( } public static PropertySource isNotNull(PropertySource src) { - return PropertyFactory.convert(src, new ValueConverter() { - @Override - public Boolean convert(Object input) { - return input != null; - } - }); + return PropertyFactory.convert(src, input -> input != null); } public static PropertySource combine( @@ -124,19 +103,11 @@ public Value getValue() { public ListenerRef addChangeListener(final Runnable listener) { ExceptionHelper.checkNotNullArgument(listener, "listener"); - final ListSelectionListener swingListener = new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - listener.run(); - } - }; + ListSelectionListener swingListener = e -> listener.run(); list.addListSelectionListener(swingListener); - return NbListenerRefs.fromRunnable(new Runnable() { - @Override - public void run() { - list.removeListSelectionListener(swingListener); - } + return NbListenerRefs.fromRunnable(() -> { + list.removeListSelectionListener(swingListener); }); } }; @@ -153,11 +124,8 @@ public static SwingPropertySource toOldProperty( ExceptionHelper.checkNotNullArgument(property, "property"); final ChangeEvent event = new ChangeEvent(src); - return SwingProperties.toSwingSource(property, new EventDispatcher() { - @Override - public void onEvent(ChangeListener eventListener, Void arg) { - eventListener.stateChanged(event); - } + return SwingProperties.toSwingSource(property, (ChangeListener eventListener, Void arg) -> { + eventListener.stateChanged(event); }); } @@ -171,16 +139,8 @@ public static PropertySource lookupProperty(Lookup lookup, Class lookupResult = lookup.lookupResult(type); LookupResultProperty oldProperty = new LookupResultProperty<>(lookupResult); - return SwingProperties.fromSwingSource(oldProperty, new SwingForwarderFactory() { - @Override - public LookupListener createForwarder(final Runnable listener) { - return new LookupListener() { - @Override - public void resultChanged(LookupEvent ev) { - listener.run(); - } - }; - } + return SwingProperties.fromSwingSource(oldProperty, (Runnable listener) -> { + return ev -> listener.run(); }); } @@ -301,17 +261,14 @@ public Value getValue() { } @Override - public ListenerRef addChangeListener(final Runnable listener) { + public ListenerRef addChangeListener(Runnable listener) { ExceptionHelper.checkNotNullArgument(listener, "listener"); final WeakReference listenerRef = new WeakReference<>(listener); - ListenerRef result = src.addChangeListener(new Runnable() { - @Override - public void run() { - Runnable listener = listenerRef.get(); - if (listener != null) { - listener.run(); - } + ListenerRef result = src.addChangeListener(() -> { + Runnable currentListener = listenerRef.get(); + if (currentListener != null) { + currentListener.run(); } }); diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ProfileBasedCustomizer.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ProfileBasedCustomizer.java index 7086c246..2eed94a1 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ProfileBasedCustomizer.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ProfileBasedCustomizer.java @@ -1,7 +1,5 @@ package org.netbeans.gradle.project.properties; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import javax.swing.JComponent; import org.jtrim.utils.ExceptionHelper; import org.netbeans.gradle.project.properties.ui.ProfileBasedPanel; @@ -14,12 +12,7 @@ public final class ProfileBasedCustomizer implements ProjectCustomizer.Composite private final PanelFactory panelFactory; public ProfileBasedCustomizer(String categoryName, String displayName, final ProfileBasedPanel panel) { - this(categoryName, displayName, new PanelFactory() { - @Override - public ProfileBasedPanel createPanel() { - return panel; - } - }); + this(categoryName, displayName, () -> panel); ExceptionHelper.checkNotNullArgument(panel, "panel"); } @@ -41,13 +34,8 @@ public ProjectCustomizer.Category createCategory(Lookup context) { @Override public JComponent createComponent(ProjectCustomizer.Category category, Lookup context) { - final ProfileBasedPanel panel = panelFactory.createPanel(); - category.setOkButtonListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - panel.saveProperties(); - } - }); + ProfileBasedPanel panel = panelFactory.createPanel(); + category.setOkButtonListener(e -> panel.saveProperties()); return panel; } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ProfileSettings.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ProfileSettings.java index c3011991..44f62e96 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ProfileSettings.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ProfileSettings.java @@ -26,7 +26,6 @@ import org.jtrim.collections.EqualityComparator; import org.jtrim.concurrent.UpdateTaskExecutor; import org.jtrim.event.CopyOnTriggerListenerManager; -import org.jtrim.event.EventDispatcher; import org.jtrim.event.ListenerManager; import org.jtrim.event.ListenerRef; import org.jtrim.event.ListenerRegistries; @@ -53,7 +52,6 @@ public final class ProfileSettings { private static final Document EXPORT_DOCUMENT = tryCreateDocument(); private final ListenerManager configUpdateListeners; - private final EventDispatcher> configUpdateDispatcher; private final ReentrantLock configLock; private volatile Object configStateKey; @@ -75,28 +73,15 @@ public ProfileSettings() { this.configUpdateListeners = new CopyOnTriggerListenerManager<>(); this.configStateKey = new Object(); this.auxConfigs = new HashMap<>(); - - this.configUpdateDispatcher = new EventDispatcher>() { - @Override - public void onEvent(ConfigUpdateListener eventListener, Collection arg) { - eventListener.configUpdated(arg); - } - }; } public static boolean isEventThread() { return SwingUtilities.isEventDispatchThread(); } - ListenerRef addDocumentChangeListener(final Runnable listener) { + ListenerRef addDocumentChangeListener(Runnable listener) { ExceptionHelper.checkNotNullArgument(listener, "listener"); - - return configUpdateListeners.registerListener(new ConfigUpdateListener() { - @Override - public void configUpdated(Collection changedPaths) { - listener.run(); - } - }); + return configUpdateListeners.registerListener(changedPaths -> listener.run()); } private static DocumentBuilder getDocumentBuilder() { @@ -196,8 +181,8 @@ public void saveToFile(Path xmlFile, ConfigSaveOptions saveOptions) throws IOExc ConfigXmlUtils.saveXmlTo(document, xmlFile, saveOptions); } - private void fireDocumentUpdate(final Collection path) { - configUpdateListeners.onEvent(configUpdateDispatcher, path); + private void fireDocumentUpdate(Collection path) { + configUpdateListeners.onEvent(ConfigUpdateListener::configUpdated, path); } private Object newConfigState() { @@ -626,21 +611,13 @@ private void updateFromConfig() { public ListenerRef addChangeListener(final Runnable listener) { ExceptionHelper.checkNotNullArgument(listener, "listener"); - ListenerRef ref1 = configUpdateListeners.registerListener(new ConfigUpdateListener() { - @Override - public void configUpdated(Collection changedPaths) { - if (affectsThis(changedPaths)) { - updateFromConfig(); - } + ListenerRef ref1 = configUpdateListeners.registerListener((Collection changedPaths) -> { + if (affectsThis(changedPaths)) { + updateFromConfig(); } }); - ListenerRef ref2 = source.addChangeListener(new Runnable() { - @Override - public void run() { - eventThread.execute(listener); - } - }); + ListenerRef ref2 = source.addChangeListener(() -> eventThread.execute(listener)); return ListenerRegistries.combineListenerRefs(ref1, ref2); } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ProfileSettingsContainer.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ProfileSettingsContainer.java index 78aa0b92..3526e897 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ProfileSettingsContainer.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ProfileSettingsContainer.java @@ -33,13 +33,7 @@ public static ProfileSettingsContainer getDefault() { if (!TestDetectUtils.isRunningTests()) { // We must not add this shutdown hook when running tests because // it would cause a dead-lock in NetBeans. - final ProfileSettingsContainer toPersistBeforeTerminate = result; - Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { - @Override - public void run() { - toPersistBeforeTerminate.saveAllProfilesNow(); - } - })); + Runtime.getRuntime().addShutdownHook(new Thread(result::saveAllProfilesNow)); } } else { @@ -93,13 +87,10 @@ public ListenerRef loadProfileSettings( final NbConsumer listener) { ExceptionHelper.checkNotNullArgument(listener, "listener"); - final LoadableSingleProfileSettingsEx result = getUnloadedProfileSettings(key); + LoadableSingleProfileSettingsEx result = getUnloadedProfileSettings(key); result.ensureLoaded(); - return result.notifyWhenLoaded(new Runnable() { - @Override - public void run() { - listener.accept(result); - } + return result.notifyWhenLoaded(() -> { + listener.accept(result); }); } @@ -119,12 +110,9 @@ public ListenerRef loadAllProfileSettings( final AtomicInteger loadCount = new AtomicInteger(result.size()); for (LoadableSingleProfileSettingsEx settings: result) { settings.ensureLoaded(); - ListenerRef notifyRef = settings.notifyWhenLoaded(Tasks.runOnceTask(new Runnable() { - @Override - public void run() { - if (loadCount.decrementAndGet() == 0) { - listener.accept(new ArrayList(result)); - } + ListenerRef notifyRef = settings.notifyWhenLoaded(Tasks.runOnceTask(() -> { + if (loadCount.decrementAndGet() == 0) { + listener.accept(new ArrayList<>(result)); } }, false)); resultRefs.add(notifyRef); diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ProjectProfileLoader.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ProjectProfileLoader.java index 2dbdd3da..caf2b063 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ProjectProfileLoader.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ProjectProfileLoader.java @@ -6,7 +6,6 @@ import org.netbeans.gradle.project.api.config.ActiveSettingsQuery; import org.netbeans.gradle.project.api.config.ActiveSettingsQueryListener; import org.netbeans.gradle.project.api.config.ProfileKey; -import org.netbeans.gradle.project.util.NbConsumer; public final class ProjectProfileLoader { private final NbGradleSingleProjectConfigProvider configProvider; @@ -39,11 +38,8 @@ public ListenerRef loadActiveSettingsForProfile(ProfileKey profileKey, final Act ProfileSettingsContainer settingsContainer = configProvider.getProfileSettingsContainer(); List combinedKeys = keysWithFallbacks(profileKey); - return settingsContainer.loadAllProfileSettings(combinedKeys, new NbConsumer>() { - @Override - public void accept(List settings) { - listener.onLoad(new MultiProfileProperties(settings)); - } + return settingsContainer.loadAllProfileSettings(combinedKeys, (List settings) -> { + listener.onLoad(new MultiProfileProperties(settings)); }); } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/PropertyOfProperty.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/PropertyOfProperty.java index 5cf2df0f..c2f395c1 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/PropertyOfProperty.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/PropertyOfProperty.java @@ -47,33 +47,25 @@ private void registerWithSubListener(Runnable listener, AtomicReference subListenerRef - = new AtomicReference(UnregisteredListenerRef.INSTANCE); + AtomicReference subListenerRef = new AtomicReference<>(UnregisteredListenerRef.INSTANCE); // subListenerRef.get() == null means that the the client // unregistered its listener and therefore, we must no longer // register listeners. That is, once this property is null, we may // never set it. - final ListenerRef listenerRef = rootSrc.addChangeListener(new Runnable() { - @Override - public void run() { - registerWithSubListener(listener, subListenerRef); - listener.run(); - } + final ListenerRef listenerRef = rootSrc.addChangeListener(() -> { + registerWithSubListener(listener, subListenerRef); + listener.run(); }); registerWithSubListener(listener, subListenerRef); - return NbListenerRefs.fromRunnable(new Runnable() { - @Override - public void run() { - listenerRef.unregister(); - ListenerRef subRef = subListenerRef.getAndSet(null); - if (subRef != null) { - subRef.unregister(); - } + return NbListenerRefs.fromRunnable(() -> { + listenerRef.unregister(); + ListenerRef subRef = subListenerRef.getAndSet(null); + if (subRef != null) { + subRef.unregister(); } }); } - } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/SwingPropertyChangeForwarder.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/SwingPropertyChangeForwarder.java index ad0ee73a..8e84ea65 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/SwingPropertyChangeForwarder.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/SwingPropertyChangeForwarder.java @@ -16,7 +16,6 @@ import org.jtrim.cancel.Cancellation; import org.jtrim.cancel.CancellationToken; import org.jtrim.collections.CollectionsEx; -import org.jtrim.concurrent.CancelableTask; import org.jtrim.concurrent.GenericUpdateTaskExecutor; import org.jtrim.concurrent.TaskExecutor; import org.jtrim.concurrent.UpdateTaskExecutor; @@ -113,19 +112,13 @@ public void firePropertyChange(final PropertyChangeEvent changeEvent) { } else { if (addedAll) { - eventExecutor.execute(new Runnable() { - @Override - public void run() { - fireListeners(changeEvent, toCall); - } + eventExecutor.execute(() -> { + fireListeners(changeEvent, toCall); }); } else { - eventExecutorSrc.execute(Cancellation.UNCANCELABLE_TOKEN, new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) { - fireListeners(changeEvent, toCall); - } + eventExecutorSrc.execute(Cancellation.UNCANCELABLE_TOKEN, (CancellationToken cancelToken) -> { + fireListeners(changeEvent, toCall); }, null); } } @@ -302,31 +295,16 @@ public Runnable forwarderTask(final UpdateTaskExecutor eventExecutor, PropertyCh return forwardNowTask; } - return new Runnable() { - @Override - public void run() { - eventExecutor.execute(forwardNowTask); - } - }; + return () -> eventExecutor.execute(forwardNowTask); } public Runnable directForwarderTask(final PropertyChangeListener listener) { if (forwardValue) { - return new Runnable() { - @Override - public void run() { - listener.propertyChange(getChangeEventWithValue()); - } - }; + return () -> listener.propertyChange(getChangeEventWithValue()); } else { - final PropertyChangeEvent event = new PropertyChangeEvent(source, name, null, null); - return new Runnable() { - @Override - public void run() { - listener.propertyChange(event); - } - }; + PropertyChangeEvent event = new PropertyChangeEvent(source, name, null, null); + return () -> listener.propertyChange(event); } } } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/global/GlobalProfileSettings.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/global/GlobalProfileSettings.java index e796c853..f8bb1131 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/global/GlobalProfileSettings.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/global/GlobalProfileSettings.java @@ -15,7 +15,6 @@ import org.netbeans.gradle.project.properties.ProfileLocationProvider; import org.netbeans.gradle.project.util.LazyValue; import org.netbeans.gradle.project.util.NbFileUtils; -import org.netbeans.gradle.project.util.NbSupplier; import org.w3c.dom.Element; final class GlobalProfileSettings implements LoadableSingleProfileSettingsEx { @@ -82,12 +81,7 @@ private static final class GlobalProfileLocationProvider implements ProfileLocat private final LazyValue outputPathRef; public GlobalProfileLocationProvider() { - this.outputPathRef = new LazyValue<>(new NbSupplier() { - @Override - public Path get() { - return GlobalSettingsUtils.tryGetGlobalConfigPath(BASE_FILE_NAME); - } - }); + this.outputPathRef = new LazyValue<>(() -> GlobalSettingsUtils.tryGetGlobalConfigPath(BASE_FILE_NAME)); } @Override diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/global/GlobalSettingsUtils.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/global/GlobalSettingsUtils.java index cdd57329..920d6bf0 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/global/GlobalSettingsUtils.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/global/GlobalSettingsUtils.java @@ -7,7 +7,6 @@ import java.util.logging.Level; import java.util.logging.Logger; import org.netbeans.gradle.project.util.LazyValue; -import org.netbeans.gradle.project.util.NbSupplier; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.modules.Places; @@ -15,20 +14,12 @@ public final class GlobalSettingsUtils { private static final Logger LOGGER = Logger.getLogger(GlobalSettingsUtils.class.getName()); - private static final LazyValue CONFIG_ROOT_REF = new LazyValue<>(new NbSupplier() { - @Override - public Path get() { - File rootFile = tryGetConfigRoot(); - return rootFile != null ? rootFile.toPath() : null; - } + private static final LazyValue CONFIG_ROOT_REF = new LazyValue<>(() -> { + File rootFile = tryGetConfigRoot(); + return rootFile != null ? rootFile.toPath() : null; }); - private static final LazyValue CACHE_ROOT_REF = new LazyValue<>(new NbSupplier() { - @Override - public Path get() { - return tryGetCacheRoot(); - } - }); + private static final LazyValue CACHE_ROOT_REF = new LazyValue<>(GlobalSettingsUtils::tryGetCacheRoot); public static Path tryGetGlobalConfigPath(List subPaths) { Path result = tryGetGlobalConfigPath0(); diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/global/NbGlobalPreference.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/global/NbGlobalPreference.java index 39bd0709..461e99f1 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/global/NbGlobalPreference.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/global/NbGlobalPreference.java @@ -30,15 +30,12 @@ public String get(String key) { } @Override - public ListenerRef addPreferenceChangeListener(final PreferenceChangeListener pcl) { + public ListenerRef addPreferenceChangeListener(PreferenceChangeListener pcl) { final Preferences preferences = getPreferences(); // To be super safe, we could wrap the listener preferences.addPreferenceChangeListener(pcl); - return NbListenerRefs.fromRunnable(new Runnable() { - @Override - public void run() { - preferences.removePreferenceChangeListener(pcl); - } + return NbListenerRefs.fromRunnable(() -> { + preferences.removePreferenceChangeListener(pcl); }); } } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/standard/BuiltInTasksProperty.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/standard/BuiltInTasksProperty.java index 997ce9f3..5629eb2c 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/standard/BuiltInTasksProperty.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/standard/BuiltInTasksProperty.java @@ -148,20 +148,17 @@ public PredefinedTasks getKeyFromValue(BuiltInTasks value) { } private static ValueMerger getValueMerger() { - return new ValueMerger() { - @Override - public BuiltInTasks mergeValues(BuiltInTasks child, ValueReference parent) { - if (child == null) { - return parent.getValue(); - } - - BuiltInTasks parentValue = parent.getValue(); - if (parentValue == null) { - return child; - } + return (BuiltInTasks child, ValueReference parent) -> { + if (child == null) { + return parent.getValue(); + } - return new InheritingBuiltInTask(child, parentValue); + BuiltInTasks parentValue = parent.getValue(); + if (parentValue == null) { + return child; } + + return new InheritingBuiltInTask(child, parentValue); }; } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/standard/CustomTasksProperty.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/standard/CustomTasksProperty.java index f58fe7c7..dc6d5371 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/standard/CustomTasksProperty.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/standard/CustomTasksProperty.java @@ -146,23 +146,20 @@ public ConfigTree encode(PredefinedTasks value) { } private static ValueMerger getValueMerger() { - return new ValueMerger() { - @Override - public PredefinedTasks mergeValues(PredefinedTasks child, ValueReference parent) { - if (child == null) { - return parent.getValue(); - } + return (PredefinedTasks child, ValueReference parent) -> { + if (child == null) { + return parent.getValue(); + } - PredefinedTasks parentValue = parent.getValue(); - if (parentValue == null) { - return child; - } + PredefinedTasks parentValue = parent.getValue(); + if (parentValue == null) { + return child; + } - List tasks1 = child.getTasks(); - List tasks2 = parentValue.getTasks(); + List tasks1 = child.getTasks(); + List tasks2 = parentValue.getTasks(); - return new PredefinedTasks(CollectionsEx.viewConcatList(tasks1, tasks2)); - } + return new PredefinedTasks(CollectionsEx.viewConcatList(tasks1, tasks2)); }; } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/standard/JavaPlatformUtils.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/standard/JavaPlatformUtils.java index 3de82bc5..4439a1ae 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/standard/JavaPlatformUtils.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/standard/JavaPlatformUtils.java @@ -175,21 +175,15 @@ public JavaPlatform[] getValue() { public ListenerRef addChangeListener(final Runnable listener) { ExceptionHelper.checkNotNullArgument(listener, "listener"); - final PropertyChangeListener propertyChangeListener = new PropertyChangeListener() { - @Override - public void propertyChange(PropertyChangeEvent evt) { - if (JavaPlatformManager.PROP_INSTALLED_PLATFORMS.equals(evt.getPropertyName())) { - listener.run(); - } + final PropertyChangeListener propertyChangeListener = (PropertyChangeEvent evt) -> { + if (JavaPlatformManager.PROP_INSTALLED_PLATFORMS.equals(evt.getPropertyName())) { + listener.run(); } }; JavaPlatformManager.getDefault().addPropertyChangeListener(propertyChangeListener); - return NbListenerRefs.fromRunnable(new Runnable() { - @Override - public void run() { - JavaPlatformManager.getDefault().removePropertyChangeListener(propertyChangeListener); - } + return NbListenerRefs.fromRunnable(() -> { + JavaPlatformManager.getDefault().removePropertyChangeListener(propertyChangeListener); }); } } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/standard/ScriptPlatformProperty.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/standard/ScriptPlatformProperty.java index fc55af1a..e2546c97 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/standard/ScriptPlatformProperty.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/standard/ScriptPlatformProperty.java @@ -3,7 +3,6 @@ import java.util.Arrays; import org.jtrim.property.PropertyFactory; import org.jtrim.property.PropertySource; -import org.jtrim.property.ValueConverter; import org.jtrim.utils.ExceptionHelper; import org.netbeans.api.java.platform.JavaPlatform; import org.netbeans.gradle.project.api.config.ConfigPath; @@ -60,11 +59,8 @@ private static PropertySource javaPlatform( return PropertyFactory.constSource(null); } - return PropertyFactory.convert(installedPlatforms(), new ValueConverter() { - @Override - public ScriptPlatform convert(JavaPlatform[] input) { - return selector.selectPlatform(Arrays.asList(input), orderRef.getValue()); - } + return PropertyFactory.convert(installedPlatforms(), (JavaPlatform[] input) -> { + return selector.selectPlatform(Arrays.asList(input), orderRef.getValue()); }); } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/AppearancePanel.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/AppearancePanel.java index 5104cc67..707ff22e 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/AppearancePanel.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/AppearancePanel.java @@ -1,10 +1,7 @@ package org.netbeans.gradle.project.properties.ui; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; import java.net.URL; import java.util.Arrays; -import java.util.Comparator; import java.util.Objects; import javax.swing.JCheckBox; import javax.swing.JComponent; @@ -14,8 +11,6 @@ import org.netbeans.gradle.project.api.config.PropertyReference; import org.netbeans.gradle.project.api.config.ui.CustomizerCategoryId; import org.netbeans.gradle.project.api.config.ui.ProfileBasedSettingsCategory; -import org.netbeans.gradle.project.api.config.ui.ProfileBasedSettingsPage; -import org.netbeans.gradle.project.api.config.ui.ProfileBasedSettingsPageFactory; import org.netbeans.gradle.project.api.config.ui.ProfileEditor; import org.netbeans.gradle.project.api.config.ui.ProfileEditorFactory; import org.netbeans.gradle.project.api.config.ui.ProfileInfo; @@ -64,22 +59,12 @@ private void setupEnableDisable() { setupInheritCheck(jSourcesDisplayModeInheritCheck, jSourcesDisplayMode); setupInheritCheck(jProjectNodeNameInheritCheck, jDisplayNameCombo, jCustomDisplayNameEdit); - jDisplayNameCombo.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - updateCustomEditVisibility(); - } - }); + jDisplayNameCombo.addItemListener(e -> updateCustomEditVisibility()); updateCustomEditVisibility(); } public static ProfileBasedSettingsCategory createSettingsCategory(final boolean allowInherit) { - return new ProfileBasedSettingsCategory(CATEGORY_ID, new ProfileBasedSettingsPageFactory() { - @Override - public ProfileBasedSettingsPage createSettingsPage() { - return AppearancePanel.createSettingsPage(allowInherit); - } - }); + return new ProfileBasedSettingsCategory(CATEGORY_ID, () -> AppearancePanel.createSettingsPage(allowInherit)); } public static GlobalSettingsPage createSettingsPage(boolean allowInherit) { @@ -128,23 +113,20 @@ private void fillJavaSourcesDisplayModeCombo() { items[i] = new SourcesDisplayModeItem(displayModes[i]); } - Arrays.sort(items, new Comparator() { - @Override - public int compare(SourcesDisplayModeItem o1, SourcesDisplayModeItem o2) { - JavaSourcesDisplayMode mode1 = o1.displayMode; - JavaSourcesDisplayMode mode2 = o2.displayMode; - if (mode1 == mode2) { - return 0; - } - if (mode1 == JavaSourcesDisplayMode.DEFAULT_MODE) { - return -1; - } - if (mode2 == JavaSourcesDisplayMode.DEFAULT_MODE) { - return 1; - } - - return StringUtils.STR_CMP.compare(o1.toString(), o2.toString()); + Arrays.sort(items, (SourcesDisplayModeItem o1, SourcesDisplayModeItem o2) -> { + JavaSourcesDisplayMode mode1 = o1.displayMode; + JavaSourcesDisplayMode mode2 = o2.displayMode; + if (mode1 == mode2) { + return 0; } + if (mode1 == JavaSourcesDisplayMode.DEFAULT_MODE) { + return -1; + } + if (mode2 == JavaSourcesDisplayMode.DEFAULT_MODE) { + return 1; + } + + return StringUtils.STR_CMP.compare(o1.toString(), o2.toString()); }); for (SourcesDisplayModeItem item: items) { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/CommonProjectPropertiesPanel.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/CommonProjectPropertiesPanel.java index 666c2c0f..cbac338e 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/CommonProjectPropertiesPanel.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/CommonProjectPropertiesPanel.java @@ -24,7 +24,6 @@ import org.netbeans.gradle.project.api.config.ui.CustomizerCategoryId; import org.netbeans.gradle.project.api.config.ui.ProfileBasedSettingsCategory; import org.netbeans.gradle.project.api.config.ui.ProfileBasedSettingsPage; -import org.netbeans.gradle.project.api.config.ui.ProfileBasedSettingsPageFactory; import org.netbeans.gradle.project.api.config.ui.ProfileEditor; import org.netbeans.gradle.project.api.config.ui.ProfileEditorFactory; import org.netbeans.gradle.project.api.config.ui.ProfileInfo; @@ -79,13 +78,7 @@ private CommonProjectPropertiesPanel(NbGradleProject project) { public static ProfileBasedSettingsCategory createSettingsCategory(final NbGradleProject project) { ExceptionHelper.checkNotNullArgument(project, "project"); - - return new ProfileBasedSettingsCategory(CATEGORY_ID, new ProfileBasedSettingsPageFactory() { - @Override - public ProfileBasedSettingsPage createSettingsPage() { - return CommonProjectPropertiesPanel.createSettingsPage(project); - } - }); + return new ProfileBasedSettingsCategory(CATEGORY_ID, () -> CommonProjectPropertiesPanel.createSettingsPage(project)); } public static ProfileBasedSettingsPage createSettingsPage(NbGradleProject project) { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/CustomVariablesPanel.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/CustomVariablesPanel.java index d4efae35..12b7bba6 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/CustomVariablesPanel.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/CustomVariablesPanel.java @@ -11,7 +11,6 @@ import org.netbeans.gradle.project.api.config.ui.CustomizerCategoryId; import org.netbeans.gradle.project.api.config.ui.ProfileBasedSettingsCategory; import org.netbeans.gradle.project.api.config.ui.ProfileBasedSettingsPage; -import org.netbeans.gradle.project.api.config.ui.ProfileBasedSettingsPageFactory; import org.netbeans.gradle.project.api.config.ui.ProfileEditor; import org.netbeans.gradle.project.api.config.ui.ProfileEditorFactory; import org.netbeans.gradle.project.api.config.ui.ProfileInfo; @@ -33,12 +32,7 @@ private CustomVariablesPanel() { } public static ProfileBasedSettingsCategory createSettingsCategory() { - return new ProfileBasedSettingsCategory(CATEGORY_ID, new ProfileBasedSettingsPageFactory() { - @Override - public ProfileBasedSettingsPage createSettingsPage() { - return CustomVariablesPanel.createSettingsPage(); - } - }); + return new ProfileBasedSettingsCategory(CATEGORY_ID, CustomVariablesPanel::createSettingsPage); } public static ProfileBasedSettingsPage createSettingsPage() { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/EnumCombo.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/EnumCombo.java index 1875763a..e6032216 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/EnumCombo.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/EnumCombo.java @@ -2,7 +2,6 @@ import java.text.Collator; import java.util.ArrayList; -import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Objects; @@ -48,12 +47,8 @@ private void fillCombo() { for (EnumType value: values) { entries.add(new Item<>(value)); } - Collections.sort(entries, new Comparator>() { - @Override - public int compare(Item a, Item b) { - return STR_CMP.compare(a.toString(), b.toString()); - } - }); + + entries.sort(Comparator.comparing(Object::toString, STR_CMP::compare)); combo.removeAllItems(); for (Item entry: entries) { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/GlobalGradleSettingsPanel.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/GlobalGradleSettingsPanel.java index 07aaddbd..7c6f19fe 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/GlobalGradleSettingsPanel.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/GlobalGradleSettingsPanel.java @@ -9,7 +9,6 @@ import org.jtrim.property.BoolProperties; import org.jtrim.property.PropertyFactory; import org.jtrim.property.PropertySource; -import org.jtrim.property.ValueConverter; import org.netbeans.gradle.project.NbStrings; import org.netbeans.gradle.project.api.config.ActiveSettingsQuery; import org.netbeans.gradle.project.api.config.ui.ProfileEditor; @@ -68,19 +67,11 @@ public GlobalGradleSettingsPanel() { jCategoriesList.setSelectedIndex(0); categorySelection = listSelection(jCategoriesList); - selectedHelpUrl = PropertyFactory.convert(categorySelection, new ValueConverter() { - @Override - public URL convert(CategoryItem input) { - return input != null ? input.getHelpUrl() : null; - } + selectedHelpUrl = PropertyFactory.convert(categorySelection, (CategoryItem input) -> { + return input != null ? input.getHelpUrl() : null; }); - categorySelection.addChangeListener(new Runnable() { - @Override - public void run() { - showSelectedEditor(); - } - }); + categorySelection.addChangeListener(this::showSelectedEditor); showSelectedEditor(); setupEnableDisable(); @@ -140,21 +131,11 @@ public void saveSettings() { } private StoredSettings readCombinedFromSettings(List editors) { - return combineSettings(editors, new NbFunction() { - @Override - public StoredSettings apply(ProfileEditor editor) { - return editor.readFromSettings(); - } - }); + return combineSettings(editors, ProfileEditor::readFromSettings); } private StoredSettings readCombinedFromGui(List editors) { - return combineSettings(editors, new NbFunction() { - @Override - public StoredSettings apply(ProfileEditor editor) { - return editor.readFromGui(); - } - }); + return combineSettings(editors, ProfileEditor::readFromGui); } @Override diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/GradleLocationPanel.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/GradleLocationPanel.java index 4a349c95..bafcc0d1 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/GradleLocationPanel.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/GradleLocationPanel.java @@ -89,11 +89,8 @@ public static GradleLocationRef tryChooseLocation( final PropertySource validLocation = panel.validLocation(); dlgDescriptor.setValid(validLocation.getValue()); - validLocation.addChangeListener(new Runnable() { - @Override - public void run() { - dlgDescriptor.setValid(validLocation.getValue()); - } + validLocation.addChangeListener(() -> { + dlgDescriptor.setValid(validLocation.getValue()); }); Dialog dlg = DialogDisplayer.getDefault().createDialog(dlgDescriptor); @@ -109,12 +106,7 @@ public void run() { } private void setupLocationChangeListeners() { - Runnable fireEventTask = new Runnable() { - @Override - public void run() { - fireLocationChangeEvent(); - } - }; + Runnable fireEventTask = this::fireLocationChangeEvent; SwingProperties.buttonSelected(jDefaultCheck).addChangeListener(fireEventTask); SwingProperties.buttonSelected(jDistCheck).addChangeListener(fireEventTask); diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/LicenseHeaderPanel.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/LicenseHeaderPanel.java index a6b8997b..a6059a3b 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/LicenseHeaderPanel.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/LicenseHeaderPanel.java @@ -24,7 +24,6 @@ import org.netbeans.gradle.project.api.config.ui.CustomizerCategoryId; import org.netbeans.gradle.project.api.config.ui.ProfileBasedSettingsCategory; import org.netbeans.gradle.project.api.config.ui.ProfileBasedSettingsPage; -import org.netbeans.gradle.project.api.config.ui.ProfileBasedSettingsPageFactory; import org.netbeans.gradle.project.api.config.ui.ProfileEditor; import org.netbeans.gradle.project.api.config.ui.ProfileEditorFactory; import org.netbeans.gradle.project.api.config.ui.ProfileInfo; @@ -92,11 +91,8 @@ public static ProfileBasedSettingsCategory createSettingsCategory( ExceptionHelper.checkNotNullArgument(defaultDirProvider, "defaultDirProvider"); ExceptionHelper.checkNotNullArgument(licenseSource, "licenseSource"); - return new ProfileBasedSettingsCategory(CATEGORY_ID, new ProfileBasedSettingsPageFactory() { - @Override - public ProfileBasedSettingsPage createSettingsPage() { - return LicenseHeaderPanel.createSettingsPage(defaultDirProvider, licenseSource); - } + return new ProfileBasedSettingsCategory(CATEGORY_ID, () -> { + return LicenseHeaderPanel.createSettingsPage(defaultDirProvider, licenseSource); }); } @@ -109,12 +105,7 @@ public static ProfileBasedSettingsPage createSettingsPage( private static NbSupplier toDefaultDirProvider(final NbGradleProject project) { ExceptionHelper.checkNotNullArgument(project, "project"); - return new NbSupplier() { - @Override - public Path get() { - return project.currentModel().getValue().getSettingsDir(); - } - }; + return () -> project.currentModel().getValue().getSettingsDir(); } @Override @@ -129,28 +120,21 @@ private List getAllNonDynamicLicenses() throws IOException { result.add(new LicenseComboItem(ref)); } } - Collections.sort(result, new Comparator() { - @Override - public int compare(LicenseComboItem o1, LicenseComboItem o2) { - return StringUtils.STR_CMP.compare(o1.toString(), o2.toString()); - } - }); + + result.sort(Comparator.comparing(Object::toString, StringUtils.STR_CMP::compare)); return result; } private CancelableFunction asyncInitTask() { - return new CancelableFunction() { - @Override - public Runnable execute(CancellationToken cancelToken) throws Exception { - List builtInLicenses = getAllNonDynamicLicenses(); + return (CancellationToken cancelToken) -> { + List builtInLicenses = getAllNonDynamicLicenses(); - List items = new ArrayList<>(builtInLicenses.size() + 2); - items.add(LicenseComboItem.NO_LICENSE); - items.add(LicenseComboItem.CUSTOM_LICENSE); - items.addAll(builtInLicenses); + List items = new ArrayList<>(builtInLicenses.size() + 2); + items.add(LicenseComboItem.NO_LICENSE); + items.add(LicenseComboItem.CUSTOM_LICENSE); + items.addAll(builtInLicenses); - return updateComboTask(items); - } + return updateComboTask(items); }; } @@ -167,12 +151,7 @@ private void updateCombo(List items) { } private Runnable updateComboTask(final List items) { - return new Runnable() { - @Override - public void run() { - updateCombo(items); - } - }; + return () -> updateCombo(items); } private void displayLicenseHeaderInfo(final LicenseHeaderInfo info) { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/ManageBuiltInTasksPanel.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/ManageBuiltInTasksPanel.java index 0715d516..142d0e17 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/ManageBuiltInTasksPanel.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/ManageBuiltInTasksPanel.java @@ -3,7 +3,6 @@ import java.awt.Component; import java.awt.Container; import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -20,7 +19,6 @@ import javax.swing.JScrollPane; import javax.swing.JViewport; import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; import org.jtrim.utils.ExceptionHelper; import org.netbeans.gradle.model.util.CollectionUtils; import org.netbeans.gradle.project.NbGradleProject; @@ -30,7 +28,6 @@ import org.netbeans.gradle.project.api.config.ui.CustomizerCategoryId; import org.netbeans.gradle.project.api.config.ui.ProfileBasedSettingsCategory; import org.netbeans.gradle.project.api.config.ui.ProfileBasedSettingsPage; -import org.netbeans.gradle.project.api.config.ui.ProfileBasedSettingsPageFactory; import org.netbeans.gradle.project.api.config.ui.ProfileEditor; import org.netbeans.gradle.project.api.config.ui.ProfileEditorFactory; import org.netbeans.gradle.project.api.config.ui.ProfileInfo; @@ -41,7 +38,6 @@ import org.netbeans.gradle.project.properties.standard.BuiltInTasksProperty; import org.netbeans.gradle.project.properties.standard.PredefinedTasks; import org.netbeans.gradle.project.tasks.DefaultBuiltInTasks; -import org.netbeans.gradle.project.util.NbSupplier; import org.netbeans.gradle.project.util.StringUtils; import org.netbeans.gradle.project.view.CustomActionPanel; @@ -68,20 +64,14 @@ private ManageBuiltInTasksPanel(NbGradleProject project) { initComponents(); jActionPanel = new CustomActionPanel(); jTaskConfigHolder.add(jActionPanel); - jInheritCheck.getModel().addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - setEnabledDisabledState(); - } + jInheritCheck.getModel().addChangeListener((ChangeEvent e) -> { + setEnabledDisabledState(); }); fillTaskCombo(); - jTaskCombo.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - if (e.getStateChange() == ItemEvent.SELECTED) { - showSelectedItem(); - } + jTaskCombo.addItemListener((ItemEvent e) -> { + if (e.getStateChange() == ItemEvent.SELECTED) { + showSelectedItem(); } }); showSelectedItem(); @@ -90,12 +80,7 @@ public void itemStateChanged(ItemEvent e) { public static ProfileBasedSettingsCategory createSettingsCategory(final NbGradleProject project) { ExceptionHelper.checkNotNullArgument(project, "project"); - return new ProfileBasedSettingsCategory(CATEGORY_ID, new ProfileBasedSettingsPageFactory() { - @Override - public ProfileBasedSettingsPage createSettingsPage() { - return ManageBuiltInTasksPanel.createSettingsPage(project); - } - }); + return new ProfileBasedSettingsCategory(CATEGORY_ID, () -> ManageBuiltInTasksPanel.createSettingsPage(project)); } public static ProfileBasedSettingsPage createSettingsPage(NbGradleProject project) { @@ -137,12 +122,9 @@ private void fillTaskCombo() { for (String command: commands) { items.add(new BuiltInTaskItem(command, getDisplayNameOfCommand(command))); } - Collections.sort(items, new Comparator() { - @Override - public int compare(BuiltInTaskItem o1, BuiltInTaskItem o2) { - return StringUtils.STR_CMP.compare(o1.getDisplayName(), o2.getDisplayName()); - } - }); + + items.sort(Comparator.comparing(BuiltInTaskItem::getDisplayName, StringUtils.STR_CMP::compare)); + jTaskCombo.setModel(new DefaultComboBoxModel<>(items.toArray(new BuiltInTaskItem[items.size()]))); jTaskCombo.getModel().setSelectedItem(items.get(0)); } @@ -211,16 +193,13 @@ private SavedTask getLastShownTask() { final String command = lastShownItem.getCommand(); jActionPanel.setTasksMustExist(false); - PredefinedTask resultTask = jActionPanel.tryGetPredefinedTask(command, new NbSupplier>() { - @Override - public List get() { - SavedTask lastValue = toSaveTasks.get(command); - if (lastValue == null) { - return getCurrentValue(command).getTaskNames(); - } - else { - return lastValue.getTaskDef().getTaskNames(); - } + PredefinedTask resultTask = jActionPanel.tryGetPredefinedTask(command, () -> { + SavedTask lastValue = toSaveTasks.get(command); + if (lastValue == null) { + return getCurrentValue(command).getTaskNames(); + } + else { + return lastValue.getTaskDef().getTaskNames(); } }); diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/ManageTasksPanel.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/ManageTasksPanel.java index 8cb520c8..4688b3f8 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/ManageTasksPanel.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/ManageTasksPanel.java @@ -8,8 +8,6 @@ import java.util.List; import javax.swing.DefaultListModel; import javax.swing.ListModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; import org.jtrim.utils.ExceptionHelper; import org.netbeans.gradle.project.NbStrings; import org.netbeans.gradle.project.api.config.ActiveSettingsQuery; @@ -17,7 +15,6 @@ import org.netbeans.gradle.project.api.config.ui.CustomizerCategoryId; import org.netbeans.gradle.project.api.config.ui.ProfileBasedSettingsCategory; import org.netbeans.gradle.project.api.config.ui.ProfileBasedSettingsPage; -import org.netbeans.gradle.project.api.config.ui.ProfileBasedSettingsPageFactory; import org.netbeans.gradle.project.api.config.ui.ProfileEditor; import org.netbeans.gradle.project.api.config.ui.ProfileEditorFactory; import org.netbeans.gradle.project.api.config.ui.ProfileInfo; @@ -47,21 +44,11 @@ private ManageTasksPanel() { currentlyShown = null; showSelected(); - jDefinedTasks.getSelectionModel().addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - showSelected(); - } - }); + jDefinedTasks.getSelectionModel().addListSelectionListener(e -> showSelected()); } public static ProfileBasedSettingsCategory createSettingsCategory() { - return new ProfileBasedSettingsCategory(CATEGORY_ID, new ProfileBasedSettingsPageFactory() { - @Override - public ProfileBasedSettingsPage createSettingsPage() { - return ManageTasksPanel.createSettingsPage(); - } - }); + return new ProfileBasedSettingsCategory(CATEGORY_ID, ManageTasksPanel::createSettingsPage); } public static ProfileBasedSettingsPage createSettingsPage() { @@ -83,14 +70,8 @@ private void sortTasks() { for (int i = 0; i < elementCount; i++) { elements[i] = model.get(i); } - Arrays.sort(elements, new Comparator() { - @Override - public int compare(PredefinedTaskItem o1, PredefinedTaskItem o2) { - String name1 = o1.toString(); - String name2 = o2.toString(); - return StringUtils.STR_CMP.compare(name1, name2); - } - }); + Arrays.sort(elements, Comparator.comparing(Object::toString, StringUtils.STR_CMP::compare)); + for (int i = 0; i < elementCount; i++) { model.set(i, elements[i]); } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/PlatformPriorityPanel.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/PlatformPriorityPanel.java index 05b57bbf..f3515346 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/PlatformPriorityPanel.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/PlatformPriorityPanel.java @@ -15,10 +15,8 @@ import javax.swing.JList; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; -import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.jtrim.property.PropertySource; -import org.jtrim.property.swing.SwingForwarderFactory; import org.jtrim.property.swing.SwingProperties; import org.jtrim.property.swing.SwingPropertySource; import org.netbeans.api.java.platform.JavaPlatform; @@ -182,18 +180,9 @@ public void removeChangeListener(ListSelectionListener listener) { selectionModel.removeListSelectionListener(listener); } }; - SwingForwarderFactory listenerForwarder = new SwingForwarderFactory() { - @Override - public ListSelectionListener createForwarder(final Runnable listener) { - return new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - listener.run(); - } - }; - } - }; - return SwingProperties.fromSwingSource(swingSource, listenerForwarder); + return SwingProperties.fromSwingSource(swingSource, (Runnable listener) -> { + return e -> listener.run(); + }); } private void closeWindow() { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/ProfileBasedPanel.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/ProfileBasedPanel.java index 1a6fc16c..53096729 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/ProfileBasedPanel.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/properties/ui/ProfileBasedPanel.java @@ -5,7 +5,6 @@ import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -31,16 +30,12 @@ import org.jtrim.cancel.Cancellation; import org.jtrim.cancel.CancellationToken; import org.jtrim.concurrent.CancelableFunction; -import org.jtrim.concurrent.CancelableTask; -import org.jtrim.concurrent.CleanupTask; import org.jtrim.property.PropertySource; -import org.jtrim.property.ValueConverter; import org.jtrim.swing.concurrent.SwingTaskExecutor; import org.jtrim.utils.ExceptionHelper; import org.netbeans.gradle.project.NbGradleProject; import org.netbeans.gradle.project.NbStrings; import org.netbeans.gradle.project.api.config.ActiveSettingsQuery; -import org.netbeans.gradle.project.api.config.ActiveSettingsQueryListener; import org.netbeans.gradle.project.api.config.ProfileDef; import org.netbeans.gradle.project.api.config.ProfileKey; import org.netbeans.gradle.project.api.config.ProjectSettingsProvider; @@ -98,22 +93,18 @@ private ProfileBasedPanel( initComponents(); final JScrollPane customPanelScroller = new JScrollPane(customPanelLayer); - final Runnable layerSizeUpdater = new Runnable() { - @Override - public void run() { - Dimension containerSize = customPanelScroller.getViewport().getExtentSize(); - int containerWidth = containerSize.width; - int containerHeight = containerSize.height; - - Dimension contentSize = customPanel.getMinimumSize(); - int contentWidth = contentSize.width; - int contentHeight = contentSize.height; - - int width = Math.max(contentWidth, containerWidth); - int height = Math.max(contentHeight, containerHeight); - - customPanelLayer.setPreferredSize(new Dimension(width, height)); - } + final Runnable layerSizeUpdater = () -> { + Dimension containerSize = customPanelScroller.getViewport().getExtentSize(); + int containerWidth = containerSize.width; + int containerHeight = containerSize.height; + + Dimension contentSize = customPanel.getMinimumSize(); + int contentWidth = contentSize.width; + int contentHeight = contentSize.height; + + int normWidth = Math.max(contentWidth, containerWidth); + int normHeight = Math.max(contentHeight, containerHeight); + customPanelLayer.setPreferredSize(new Dimension(normWidth, normHeight)); }; customPanelScroller.addComponentListener(new ComponentAdapter() { @Override @@ -124,12 +115,9 @@ public void componentResized(ComponentEvent e) { layerSizeUpdater.run(); jCustomPanelContainer.add(customPanelScroller); - jProfileCombo.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - if (e.getStateChange() == ItemEvent.SELECTED) { - loadSelectedProfile(); - } + jProfileCombo.addItemListener((ItemEvent e) -> { + if (e.getStateChange() == ItemEvent.SELECTED) { + loadSelectedProfile(); } }); @@ -175,12 +163,7 @@ public void saveProperties() { } private PropertySource selectedRemovable() { - return convert(comboBoxSelection(jProfileCombo), new ValueConverter() { - @Override - public Boolean convert(ProfileItem input) { - return input != null && input.isRemovable(); - } - }); + return convert(comboBoxSelection(jProfileCombo), input -> input != null && input.isRemovable()); } private void setupEnableDisable() { @@ -202,33 +185,22 @@ private List getProfileItems() { } private CancelableFunction initProfileComboTask() { - return new CancelableFunction() { - @Override - public Runnable execute(CancellationToken cancelToken) throws Exception { - List profileItems = getProfileItems(); - return fillProfileComboTask(profileItems); - } + return (CancellationToken cancelToken) -> { + List profileItems = getProfileItems(); + return fillProfileComboTask(profileItems); }; } - private Runnable fillProfileComboTask(final List profileItems) { - return new Runnable() { - @Override - public void run() { - fillProfileCombo(profileItems); - } - }; + private Runnable fillProfileComboTask(List profileItems) { + return () -> fillProfileCombo(profileItems); } private Runnable toReleaseTask(final PanelLockRef taskLock, final Runnable task) { - return new Runnable() { - @Override - public void run() { - try { - task.run(); - } finally { - taskLock.release(); - } + return () -> { + try { + task.run(); + } finally { + taskLock.release(); } }; } @@ -239,23 +211,17 @@ private void fetchProfilesAndSelect(CancelableFunction async initProfileComboTask()); final PanelLockRef mainLockRef = lockPanel(); - NbTaskExecutors.DEFAULT_EXECUTOR.execute(Cancellation.UNCANCELABLE_TOKEN, new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) throws Exception { - for (CancelableFunction initTask: initTasks) { - Runnable uiUpdateTask = initTask.execute(cancelToken); - if (uiUpdateTask != null) { - PanelLockRef taskLock = lockPanel(); - SwingUtilities.invokeLater(toReleaseTask(taskLock, uiUpdateTask)); - } + NbTaskExecutors.DEFAULT_EXECUTOR.execute(Cancellation.UNCANCELABLE_TOKEN, (CancellationToken cancelToken) -> { + for (CancelableFunction initTask: initTasks) { + Runnable uiUpdateTask = initTask.execute(cancelToken); + if (uiUpdateTask != null) { + PanelLockRef taskLock = lockPanel(); + SwingUtilities.invokeLater(toReleaseTask(taskLock, uiUpdateTask)); } } - }, new CleanupTask() { - @Override - public void cleanup(boolean canceled, Throwable error) throws Exception { - NbTaskExecutors.defaultCleanup(canceled, error); - mainLockRef.release(); - } + }, (boolean canceled, Throwable error) -> { + NbTaskExecutors.defaultCleanup(canceled, error); + mainLockRef.release(); }); } @@ -311,27 +277,21 @@ private void loadSelectedProfile() { final ProfileKey profileKey = selected.getProfileKey(); final PanelLockRef lock = lockPanel(); - extensionSettings.loadSettingsForProfile(Cancellation.UNCANCELABLE_TOKEN, profileKey, new ActiveSettingsQueryListener() { - @Override - public void onLoad(final ActiveSettingsQuery settings) { - String displayName = selected.toString(); - ProfileInfo profileInfo = new ProfileInfo(profileKey, displayName); - ProfileEditor editor = snapshotCreator.startEditingProfile(profileInfo, settings); - final Snapshot snapshot = new Snapshot(editor); - snapshots.put(selected, snapshot); - - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - try { - currentlyShownProfile = selected; - snapshot.displayValues(); - } finally { - lock.release(); - } - } - }); - } + extensionSettings.loadSettingsForProfile(Cancellation.UNCANCELABLE_TOKEN, profileKey, (ActiveSettingsQuery settings) -> { + String displayName = selected.toString(); + ProfileInfo profileInfo = new ProfileInfo(profileKey, displayName); + ProfileEditor editor = snapshotCreator.startEditingProfile(profileInfo, settings); + final Snapshot snapshot = new Snapshot(editor); + snapshots.put(selected, snapshot); + + SwingUtilities.invokeLater(() -> { + try { + currentlyShownProfile = selected; + snapshot.displayValues(); + } finally { + lock.release(); + } + }); }); } @@ -385,25 +345,22 @@ private static final class ProfileItem { private static final ProfileItem GLOBAL_DEFAULT = new ProfileItem(new ProfileDef(ProfileKey.GLOBAL_PROFILE, NbStrings.getGlobalProfileName())); - private static final Comparator ALPHABETICAL_ORDER = new Comparator() { - @Override - public int compare(ProfileItem o1, ProfileItem o2) { - if (GLOBAL_DEFAULT.equals(o1)) { - return GLOBAL_DEFAULT.equals(o2) ? 0 : -1; - } - if (GLOBAL_DEFAULT.equals(o2)) { - return GLOBAL_DEFAULT.equals(o1) ? 0 : 1; - } - - if (DEFAULT.equals(o1)) { - return DEFAULT.equals(o2) ? 0 : -1; - } - if (DEFAULT.equals(o2)) { - return DEFAULT.equals(o1) ? 0 : 1; - } + private static final Comparator ALPHABETICAL_ORDER = (ProfileItem o1, ProfileItem o2) -> { + if (GLOBAL_DEFAULT.equals(o1)) { + return GLOBAL_DEFAULT.equals(o2) ? 0 : -1; + } + if (GLOBAL_DEFAULT.equals(o2)) { + return GLOBAL_DEFAULT.equals(o1) ? 0 : 1; + } - return StringUtils.STR_CMP.compare(o1.toString(), o2.toString()); + if (DEFAULT.equals(o1)) { + return DEFAULT.equals(o2) ? 0 : -1; } + if (DEFAULT.equals(o2)) { + return DEFAULT.equals(o1) ? 0 : 1; + } + + return StringUtils.STR_CMP.compare(o1.toString(), o2.toString()); }; private final ProfileDef profileDef; @@ -551,11 +508,8 @@ private void jAddProfileButtonActionPerformed(java.awt.event.ActionEvent evt) {/ null); final PropertySource validProfileName = panel.validProfileName(); - validProfileName.addChangeListener(new Runnable() { - @Override - public void run() { - dlgDescriptor.setValid(validProfileName.getValue()); - } + validProfileName.addChangeListener(() -> { + dlgDescriptor.setValid(validProfileName.getValue()); }); dlgDescriptor.setValid(validProfileName.getValue()); diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/query/GradleCacheBinaryForSourceQuery.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/query/GradleCacheBinaryForSourceQuery.java index 2cb65c19..9aa637f2 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/query/GradleCacheBinaryForSourceQuery.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/query/GradleCacheBinaryForSourceQuery.java @@ -20,13 +20,7 @@ public final class GradleCacheBinaryForSourceQuery extends AbstractBinaryForSour static { CHANGES = LazyChangeSupport.createSwing(new EventSource()); - - GradleFileUtils.GRADLE_USER_HOME.addChangeListener(new Runnable() { - @Override - public void run() { - notifyCacheChange(); - } - }); + GradleFileUtils.GRADLE_USER_HOME.addChangeListener(GradleCacheBinaryForSourceQuery::notifyCacheChange); } public GradleCacheBinaryForSourceQuery() { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/query/GradleCacheJavadocForBinaryQuery.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/query/GradleCacheJavadocForBinaryQuery.java index 88d9dacb..1017dfb0 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/query/GradleCacheJavadocForBinaryQuery.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/query/GradleCacheJavadocForBinaryQuery.java @@ -5,7 +5,6 @@ import javax.swing.event.ChangeListener; import org.netbeans.api.java.queries.JavadocForBinaryQuery; import org.netbeans.gradle.project.util.GradleFileUtils; -import org.netbeans.gradle.project.util.NbFunction; import org.netbeans.gradle.project.util.NbSupplier; import org.netbeans.spi.java.queries.JavadocForBinaryQueryImplementation; import org.netbeans.spi.java.queries.SourceForBinaryQueryImplementation2; @@ -26,13 +25,11 @@ public GradleCacheJavadocForBinaryQuery(NbSupplier gradleUserHomeProvider) this.sourceForBinary = new GradleCacheByBinaryLookup( GradleFileUtils.SOURCE_DIR_NAME, gradleUserHomeProvider, - GradleCacheSourceForBinaryQuery.binaryToSourceName()); - this.javadocForBinary = new GradleCacheByBinaryLookup(GradleFileUtils.JAVADOC_DIR_NAME, gradleUserHomeProvider, new NbFunction() { - @Override - public String apply(FileObject arg) { - return GradleFileUtils.binaryToJavadocName(arg); - } - }); + GradleFileUtils::binaryToSourceName); + this.javadocForBinary = new GradleCacheByBinaryLookup( + GradleFileUtils.JAVADOC_DIR_NAME, + gradleUserHomeProvider, + GradleFileUtils::binaryToJavadocName); } private boolean hasSources(File binaryRootFile) { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/query/GradleCacheSourceForBinaryQuery.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/query/GradleCacheSourceForBinaryQuery.java index eeee0fec..cfbc749f 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/query/GradleCacheSourceForBinaryQuery.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/query/GradleCacheSourceForBinaryQuery.java @@ -2,11 +2,9 @@ import java.io.File; import org.netbeans.gradle.project.util.GradleFileUtils; -import org.netbeans.gradle.project.util.NbFunction; import org.netbeans.gradle.project.util.NbSupplier; import org.netbeans.spi.java.queries.SourceForBinaryQueryImplementation; import org.netbeans.spi.java.queries.SourceForBinaryQueryImplementation2; -import org.openide.filesystems.FileObject; import org.openide.util.lookup.ServiceProvider; import org.openide.util.lookup.ServiceProviders; @@ -21,16 +19,10 @@ public GradleCacheSourceForBinaryQuery() { } public GradleCacheSourceForBinaryQuery(NbSupplier gradleUserHomeProvider) { - this.sourceLookup = new GradleCacheByBinaryLookup(GradleFileUtils.SOURCE_DIR_NAME, gradleUserHomeProvider, binaryToSourceName()); - } - - public static NbFunction binaryToSourceName() { - return new NbFunction() { - @Override - public String apply(FileObject arg) { - return GradleFileUtils.binaryToSourceName(arg); - } - }; + this.sourceLookup = new GradleCacheByBinaryLookup( + GradleFileUtils.SOURCE_DIR_NAME, + gradleUserHomeProvider, + GradleFileUtils::binaryToSourceName); } @Override diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/query/GradleFilesClassPathProvider.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/query/GradleFilesClassPathProvider.java index 295e7b79..113ffdc6 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/query/GradleFilesClassPathProvider.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/query/GradleFilesClassPathProvider.java @@ -3,7 +3,6 @@ import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.File; -import java.io.FilenameFilter; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; @@ -88,12 +87,9 @@ private static URL[] getGradleBinaries() { return new URL[0]; } - return GradleHomeClassPathProvider.getGradleLibs(gradleHome, new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - String lowerCaseName = name.toLowerCase(Locale.US); - return !lowerCaseName.startsWith("groovy-") && lowerCaseName.endsWith(".jar"); - } + return GradleHomeClassPathProvider.getGradleLibs(gradleHome, (File dir, String name) -> { + String lowerCaseName = name.toLowerCase(Locale.US); + return !lowerCaseName.startsWith("groovy-") && lowerCaseName.endsWith(".jar"); }); } @@ -149,29 +145,18 @@ private void init() { } private void scheduleUpdateClassPath() { - classpathUpdateExecutor.execute(new Runnable() { - @Override - public void run() { - updateClassPathResources(); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - changes.firePropertyChange(ClassPathImplementation.PROP_RESOURCES, null, null); - } - }); - } + classpathUpdateExecutor.execute(() -> { + updateClassPathResources(); + SwingUtilities.invokeLater(() -> { + changes.firePropertyChange(ClassPathImplementation.PROP_RESOURCES, null, null); + }); }); } private void unsafeInit() { assert initLock.isHeldByCurrentThread(); - Runnable changeListener = new Runnable() { - @Override - public void run() { - scheduleUpdateClassPath(); - } - }; + Runnable changeListener = this::scheduleUpdateClassPath; CommonGlobalSettings defaultSettings = CommonGlobalSettings.getDefault(); defaultSettings.gradleLocation().getActiveSource().addChangeListener(changeListener); diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/query/GradleHomeClassPathProvider.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/query/GradleHomeClassPathProvider.java index 7c5ef12b..e34610cf 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/query/GradleHomeClassPathProvider.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/query/GradleHomeClassPathProvider.java @@ -94,21 +94,15 @@ public static URL[] getGradleLibs(FileObject gradleHomeObj, FilenameFilter filte } public static URL[] getAllGradleLibs(FileObject gradleHomeObj) { - return getGradleLibs(gradleHomeObj, new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return name.toLowerCase(Locale.US).endsWith(".jar"); - } + return getGradleLibs(gradleHomeObj, (File dir, String name) -> { + return name.toLowerCase(Locale.US).endsWith(".jar"); }); } public static URL[] getGradleBinaries(FileObject gradleHomeObj) { - return getGradleLibs(gradleHomeObj, new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - String lowerCaseName = name.toLowerCase(Locale.US); - return lowerCaseName.startsWith("gradle-") && lowerCaseName.endsWith(".jar"); - } + return getGradleLibs(gradleHomeObj, (File dir, String name) -> { + String lowerCaseName = name.toLowerCase(Locale.US); + return lowerCaseName.startsWith("gradle-") && lowerCaseName.endsWith(".jar"); }); } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/query/GradleHomeSourceForBinaryQuery.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/query/GradleHomeSourceForBinaryQuery.java index 99f3f601..6d46e354 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/query/GradleHomeSourceForBinaryQuery.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/query/GradleHomeSourceForBinaryQuery.java @@ -20,12 +20,7 @@ public final class GradleHomeSourceForBinaryQuery extends AbstractSourceForBinar private final NbSupplier gradleHomeProvider; public GradleHomeSourceForBinaryQuery() { - this(new NbSupplier() { - @Override - public FileObject get() { - return CommonGlobalSettings.getDefault().tryGetGradleInstallation(); - } - }); + this(() -> CommonGlobalSettings.getDefault().tryGetGradleInstallation()); } public GradleHomeSourceForBinaryQuery(NbSupplier gradleHomeProvider) { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/script/DefaultScriptFileProvider.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/script/DefaultScriptFileProvider.java index 254f1b73..9e48c671 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/script/DefaultScriptFileProvider.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/script/DefaultScriptFileProvider.java @@ -59,13 +59,8 @@ public Collection findScriptFiles( Path baseDir, NbPredicate baseNameFilter) throws IOException { - final List result = new ArrayList<>(); - findScriptFiles(baseDir, baseNameFilter, new NbConsumer() { - @Override - public void accept(Path script) { - result.add(script); - } - }); + List result = new ArrayList<>(); + findScriptFiles(baseDir, baseNameFilter, result::add); return result; } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/AsyncGradleTask.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/AsyncGradleTask.java index 7ccb6533..a50249de 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/AsyncGradleTask.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/AsyncGradleTask.java @@ -34,7 +34,6 @@ import org.jtrim.cancel.Cancellation; import org.jtrim.cancel.CancellationSource; import org.jtrim.cancel.CancellationToken; -import org.jtrim.concurrent.CancelableTask; import org.jtrim.concurrent.TaskExecutor; import org.jtrim.event.ListenerRef; import org.jtrim.utils.ExceptionHelper; @@ -363,11 +362,8 @@ private DefaultModelBuilderSetup createTargetSetup( } private static void scheduleCancel(final DefaultCancellationTokenSource cancelSource) { - CANCEL_EXECUTOR.execute(Cancellation.UNCANCELABLE_TOKEN, new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) throws Exception { - cancelSource.cancel(); - } + CANCEL_EXECUTOR.execute(Cancellation.UNCANCELABLE_TOKEN, (CancellationToken cancelToken) -> { + cancelSource.cancel(); }, null); } @@ -378,11 +374,8 @@ private void runBuild(CancellationToken cancelToken, BuildLauncher buildLauncher final DefaultCancellationTokenSource cancelSource = new DefaultCancellationTokenSource(); buildLauncher.withCancellationToken(cancelSource.token()); - ListenerRef cancelListenerRef = cancelToken.addCancellationListener(new Runnable() { - @Override - public void run() { - scheduleCancel(cancelSource); - } + ListenerRef cancelListenerRef = cancelToken.addCancellationListener(() -> { + scheduleCancel(cancelSource); }); try { buildLauncher.run(); @@ -591,11 +584,8 @@ private static TaskVariableMap queryVariablesNow(List tas private static TaskVariableMap queryVariables(final List taskVars) { final AtomicReference result = new AtomicReference<>(null); try { - SwingUtilities.invokeAndWait(new Runnable() { - @Override - public void run() { - result.set(queryVariablesNow(taskVars)); - } + SwingUtilities.invokeAndWait(() -> { + result.set(queryVariablesNow(taskVars)); }); return result.get(); } catch (InterruptedException ex) { @@ -789,11 +779,8 @@ public BuildExecutionItem(ProcessedCommandSpec processedCommandSpec) { String progressCaption = processedCommandSpec.getProgressCaption(); boolean nonBlocking = processedCommandSpec.getProcessedTaskDef().isNonBlocking(); - this.daemonTaskDef = new DaemonTaskDef(progressCaption, nonBlocking, new DaemonTask() { - @Override - public void run(CancellationToken cancelToken, ProgressHandle progress) { - doGradleTasksWithProgress(cancelToken, progress, BuildExecutionItem.this); - } + this.daemonTaskDef = new DaemonTaskDef(progressCaption, nonBlocking, (cancelToken, progress) -> { + doGradleTasksWithProgress(cancelToken, progress, BuildExecutionItem.this); }); this.running = true; } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/AttacherListener.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/AttacherListener.java index 664b0a0a..31ca24aa 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/AttacherListener.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/AttacherListener.java @@ -1,7 +1,6 @@ package org.netbeans.gradle.project.tasks; import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; import java.io.File; import java.net.URL; import java.util.Arrays; @@ -16,7 +15,6 @@ import org.jtrim.cancel.Cancellation; import org.jtrim.cancel.CancellationController; import org.jtrim.cancel.CancellationToken; -import org.jtrim.concurrent.CancelableTask; import org.jtrim.utils.ExceptionHelper; import org.netbeans.api.debugger.jpda.DebuggerStartException; import org.netbeans.api.debugger.jpda.JPDADebugger; @@ -132,26 +130,20 @@ private void doAttach(int port) throws DebuggerStartException { Map services = getJpdaServiceObjects(javaExt); final JPDADebugger debugger = JPDADebugger.attach("127.0.0.1", port, new Object[]{services}); - debugger.addPropertyChangeListener("state", new PropertyChangeListener() { - @Override - public void propertyChange(PropertyChangeEvent evt) { - if (debugger.getState() == JPDADebugger.STATE_DISCONNECTED) { - buildCancel.cancel(); - } + debugger.addPropertyChangeListener("state", (PropertyChangeEvent evt) -> { + if (debugger.getState() == JPDADebugger.STATE_DISCONNECTED) { + buildCancel.cancel(); } }); } @Override public void onDebugeeListening(final int port) { - NbTaskExecutors.DEFAULT_EXECUTOR.execute(Cancellation.UNCANCELABLE_TOKEN, new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) { - try { - doAttach(port); - } catch (DebuggerStartException ex) { - LOGGER.log(Level.INFO, "Failed to attach to debugee.", ex); - } + NbTaskExecutors.DEFAULT_EXECUTOR.execute(Cancellation.UNCANCELABLE_TOKEN, (CancellationToken cancelToken) -> { + try { + doAttach(port); + } catch (DebuggerStartException ex) { + LOGGER.log(Level.INFO, "Failed to attach to debugee.", ex); } }, null); } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/DefaultGradleCommandExecutor.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/DefaultGradleCommandExecutor.java index a1f82fd9..eafcffa2 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/DefaultGradleCommandExecutor.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/DefaultGradleCommandExecutor.java @@ -41,17 +41,14 @@ public GradleTaskDef tryCreateTaskDef(CancellationToken cancelToken) { Set actionContexts = Collections.emptySet(); - Runnable asyncTask = GradleTasks.createAsyncGradleTask(project, taskDefFactory, actionContexts, new CommandCompleteListener() { - @Override - public void onComplete(Throwable error) { - try { - CommandCompleteListener completeListener = customActions.getCommandCompleteListener(); - if (completeListener != null) { - completeListener.onComplete(error); - } - } finally { - GradleTasks.projectTaskCompleteListener(project).onComplete(error); + Runnable asyncTask = GradleTasks.createAsyncGradleTask(project, taskDefFactory, actionContexts, (Throwable error) -> { + try { + CommandCompleteListener completeListener = customActions.getCommandCompleteListener(); + if (completeListener != null) { + completeListener.onComplete(error); } + } finally { + GradleTasks.projectTaskCompleteListener(project).onComplete(error); } }); asyncTask.run(); diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/GradleArguments.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/GradleArguments.java index 8e6b8589..699e455d 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/GradleArguments.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/GradleArguments.java @@ -68,21 +68,11 @@ private static void addExtensionArgs( } private static void addExtensionArgs(DaemonTaskContext context, List result) { - addExtensionArgs(context, result, new ArgGetter() { - @Override - public List getArgs(GradleArgumentQuery query, DaemonTaskContext context) { - return query.getExtraArgs(context); - } - }); + addExtensionArgs(context, result, GradleArgumentQuery::getExtraArgs); } private static void addExtensionJvmArgs(DaemonTaskContext context, List result) { - addExtensionArgs(context, result, new ArgGetter() { - @Override - public List getArgs(GradleArgumentQuery query, DaemonTaskContext context) { - return query.getExtraJvmArgs(context); - } - }); + addExtensionArgs(context, result, GradleArgumentQuery::getExtraJvmArgs); } private static Path tryGetUserInitScript(Project project) { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/GradleDaemonFailures.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/GradleDaemonFailures.java index 6ce7a520..02ee799f 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/GradleDaemonFailures.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/GradleDaemonFailures.java @@ -19,12 +19,9 @@ public static DaemonFailureHandler getDefaultHandler() { private static DaemonFailureHandler failureDueToJarCachingHandler() { String pattern = "JAR entry .*BuildAction.*\\.class not found in .*\\.jar"; - return new RootCauseMessagePatternHandler(pattern, new DaemonFailureHandler() { - @Override - public boolean tryHandleFailure(Throwable failure) { - GlobalErrorReporter.showIssue(NbStrings.getCachedJarIssueMessage()); - return true; - } + return new RootCauseMessagePatternHandler(pattern, (Throwable failure) -> { + GlobalErrorReporter.showIssue(NbStrings.getCachedJarIssueMessage()); + return true; }); } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/GradleDaemonManager.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/GradleDaemonManager.java index e1775745..70f1e112 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/GradleDaemonManager.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/GradleDaemonManager.java @@ -11,13 +11,10 @@ import org.jtrim.cancel.CancellationController; import org.jtrim.cancel.CancellationSource; import org.jtrim.cancel.CancellationToken; -import org.jtrim.concurrent.CancelableTask; -import org.jtrim.concurrent.CleanupTask; import org.jtrim.concurrent.TaskExecutor; import org.jtrim.utils.ExceptionHelper; import org.netbeans.api.progress.ProgressHandle; import org.netbeans.gradle.project.api.task.CommandCompleteListener; -import org.openide.util.Cancellable; public final class GradleDaemonManager { private static final Logger LOGGER = Logger.getLogger(GradleDaemonManager.class.getName()); @@ -85,63 +82,54 @@ public static void submitGradleTask( final ReplaceableProgressHandle progress = new ReplaceableProgressHandle(cancel.getController()); final AtomicBoolean inProgress = new AtomicBoolean(false); - cancel.getToken().addCancellationListener(new Runnable() { - @Override - public void run() { - if (!inProgress.get()) { - progress.finish(); - } + cancel.getToken().addCancellationListener(() -> { + if (!inProgress.get()) { + progress.finish(); } }); progress.start(origDisplayName); - executor.execute(cancel.getToken(), new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) throws Exception { - inProgress.set(true); - cancelToken.checkCanceled(); - - DaemonTaskDef taskDef; - try { - taskDef = taskDefFactory.tryCreateTaskDef(cancelToken); - } catch (Exception ex) { - LOGGER.log(Level.SEVERE, "Failed to create DaemonTaskDef.", ex); - return; - } + executor.execute(cancel.getToken(), (CancellationToken cancelToken) -> { + inProgress.set(true); + cancelToken.checkCanceled(); + + DaemonTaskDef taskDef; + try { + taskDef = taskDefFactory.tryCreateTaskDef(cancelToken); + } catch (Exception ex) { + LOGGER.log(Level.SEVERE, "Failed to create DaemonTaskDef.", ex); + return; + } - if (taskDef == null) { - return; - } + if (taskDef == null) { + return; + } - String displayName = taskDef.getCaption(); - boolean nonBlocking = taskDef.isNonBlocking(); - DaemonTask task = taskDef.getTask(); + String displayName = taskDef.getCaption(); + boolean nonBlocking = taskDef.isNonBlocking(); + DaemonTask task = taskDef.getTask(); - if (!Objects.equals(displayName, origDisplayName)) { - progress.start(displayName); - } + if (!Objects.equals(displayName, origDisplayName)) { + progress.start(displayName); + } - if (nonBlocking) { - runNonBlockingGradleTask(cancelToken, task, progress.getCurrentHandle()); - } - else { - runBlockingGradleTask(cancelToken, task, progress.getCurrentHandle()); - } + if (nonBlocking) { + runNonBlockingGradleTask(cancelToken, task, progress.getCurrentHandle()); + } + else { + runBlockingGradleTask(cancelToken, task, progress.getCurrentHandle()); } - }, new CleanupTask() { - @Override - public void cleanup(boolean canceled, Throwable error) throws Exception { - try { - if (!canceled) { - listener.onComplete(error); - } - } finally { - progress.finish(); + }, (boolean canceled, Throwable error) -> { + try { + if (!canceled) { + listener.onComplete(error); } + } finally { + progress.finish(); + } - if (canceled) { - LOGGER.log(Level.INFO, "Canceled task: {0}", origDisplayName); - } + if (canceled) { + LOGGER.log(Level.INFO, "Canceled task: {0}", origDisplayName); } }); } @@ -158,12 +146,9 @@ public ReplaceableProgressHandle(CancellationController cancelController) { } public void start(String displayName) { - ProgressHandle newHandle = ProgressHandle.createHandle(displayName, new Cancellable() { - @Override - public boolean cancel() { - cancelController.cancel(); - return true; - } + ProgressHandle newHandle = ProgressHandle.createHandle(displayName, () -> { + cancelController.cancel(); + return true; }); newHandle.start(); diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/GradleTaskDef.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/GradleTaskDef.java index 6be38695..c8c6a59c 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/GradleTaskDef.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/GradleTaskDef.java @@ -469,23 +469,15 @@ private static SingleExecutionOutputProcessor outputProcessor( return nullSafeProcessorFactory; } - return new SingleExecutionOutputProcessor() { - @Override - public TaskOutputProcessor startExecution(Project project) { - return mergedOutputProcessor( - processor, - nullSafeProcessorFactory.startExecution(project)); - } + return (Project project) -> { + return mergedOutputProcessor(processor, nullSafeProcessorFactory.startExecution(project)); }; } private static TaskOutputProcessor mergedOutputProcessor(TaskOutputProcessor... processors) { final TaskOutputProcessor[] wrappedProcessors = processors.clone(); - return new TaskOutputProcessor() { - @Override - public void processLine(String line) { - processByAll(wrappedProcessors, line); - } + return (String line) -> { + processByAll(wrappedProcessors, line); }; } @@ -560,15 +552,9 @@ private static GradleTargetVerifier getGradleTargetVerifier( if (verifier1 == null) return verifier2; if (verifier2 == null) return verifier1; - return new GradleTargetVerifier() { - @Override - public boolean checkTaskExecutable( - GradleTarget gradleTarget, - OutputWriter output, - OutputWriter errOutput) { - return verifier1.checkTaskExecutable(gradleTarget, output, errOutput) - && verifier2.checkTaskExecutable(gradleTarget, output, errOutput); - } + return (GradleTarget gradleTarget, OutputWriter output, OutputWriter errOutput) -> { + return verifier1.checkTaskExecutable(gradleTarget, output, errOutput) + && verifier2.checkTaskExecutable(gradleTarget, output, errOutput); }; } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/GradleTasks.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/GradleTasks.java index 6656f351..926cb46c 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/GradleTasks.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/GradleTasks.java @@ -51,17 +51,14 @@ public static Runnable createAsyncGradleTaskFromSpec( public static CommandCompleteListener projectTaskCompleteListener(final NbGradleProject project) { ExceptionHelper.checkNotNullArgument(project, "project"); - return new CommandCompleteListener() { - @Override - public void onComplete(Throwable error) { - if (error != null) { - LOGGER.log(error instanceof Exception ? Level.INFO : Level.SEVERE, - "Gradle build failure.", - error); + return (Throwable error) -> { + if (error != null) { + LOGGER.log(error instanceof Exception ? Level.INFO : Level.SEVERE, + "Gradle build failure.", + error); - String buildFailureMessage = NbStrings.getGradleTaskFailure(); - project.displayError(buildFailureMessage, error); - } + String buildFailureMessage = NbStrings.getGradleTaskFailure(); + project.displayError(buildFailureMessage, error); } }; } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/PriorityAwareExecutor.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/PriorityAwareExecutor.java index 68302874..8d4e8a3f 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/PriorityAwareExecutor.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/PriorityAwareExecutor.java @@ -36,43 +36,31 @@ private void executeForPriority( RefCollection.ElementRef queueRef = taskQueue.addTask(priority, taskDef); taskDef.init(queueRef); - final AtomicReference taskDefRef = new AtomicReference<>(null); - CancelableTask forwarderTask = new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) throws Exception { - TaskDef task = taskQueue.pollTask(); - taskDefRef.set(task); - task.doTask(cancelToken); + AtomicReference taskDefRef = new AtomicReference<>(null); + + wrapped.execute(Cancellation.UNCANCELABLE_TOKEN, (CancellationToken taskCancelToken) -> { + TaskDef nextTask = taskQueue.pollTask(); + taskDefRef.set(nextTask); + nextTask.doTask(taskCancelToken); + }, (boolean canceled, Throwable error) -> { + TaskDef def = taskDefRef.get(); + if (def != null) { + def.cleanup(canceled, error); } - }; - - CleanupTask forwarderCleanupTask = new CleanupTask() { - @Override - public void cleanup(boolean canceled, Throwable error) throws Exception { - TaskDef def = taskDefRef.get(); - if (def != null) { - def.cleanup(canceled, error); - } - else if (canceled) { - // This means, that the executor has been terminated - // so poll one cleanup task and execute it. - TaskDef task = taskQueue.pollTask(); - if (task != null) { - task.cleanup(canceled, error); - } + else if (canceled) { + // This means, that the executor has been terminated + // so poll one cleanup task and execute it. + TaskDef task1 = taskQueue.pollTask(); + if (task1 != null) { + task1.cleanup(canceled, error); } } - }; - - wrapped.execute(Cancellation.UNCANCELABLE_TOKEN, forwarderTask, forwarderCleanupTask); + }); } private TaskExecutor getExecutor(final Priority priority) { - return new TaskExecutor() { - @Override - public void execute(CancellationToken cancelToken, CancelableTask task, CleanupTask cleanupTask) { - executeForPriority(cancelToken, priority, task, cleanupTask); - } + return (CancellationToken cancelToken, CancelableTask task, CleanupTask cleanupTask) -> { + executeForPriority(cancelToken, priority, task, cleanupTask); }; } @@ -183,17 +171,14 @@ public TaskDef(CancellationToken cancelToken, CancelableTask task, CleanupTask c public void init(final RefCollection.ElementRef queueRef) { final InitLaterListenerRef cancelRefRef = new InitLaterListenerRef(); - cancelRefRef.init(cancelToken.addCancellationListener(new Runnable() { - @Override - public void run() { - removeTask(); - - if (cleanupTask == null) { - queueRef.remove(); - } + cancelRefRef.init(cancelToken.addCancellationListener(() -> { + removeTask(); - cancelRefRef.unregister(); + if (cleanupTask == null) { + queueRef.remove(); } + + cancelRefRef.unregister(); })); if (!this.cancelRef.compareAndSet(null, cancelRefRef)) { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/vars/DisplayedTaskVariable.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/vars/DisplayedTaskVariable.java index 7b710196..630016fb 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/vars/DisplayedTaskVariable.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/vars/DisplayedTaskVariable.java @@ -74,16 +74,11 @@ public String toString() { } public static TaskVariableMap variableMap(Map map) { - final Map appliedMap = new HashMap<>(); + Map appliedMap = new HashMap<>(); for (Map.Entry entry: map.entrySet()) { appliedMap.put(entry.getKey().getVariable(), entry.getValue()); } - return new TaskVariableMap() { - @Override - public String tryGetValueForVariable(TaskVariable variable) { - return appliedMap.get(variable); - } - }; + return appliedMap::get; } } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/vars/StandardTaskVariable.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/vars/StandardTaskVariable.java index 2f4eb780..52c919aa 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/vars/StandardTaskVariable.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/vars/StandardTaskVariable.java @@ -28,116 +28,77 @@ import org.openide.util.Lookup; public enum StandardTaskVariable { - PROJECT_PATH_NOT_NORMALIZED("project-path", new ValueGetter() { - @Override - public VariableValue getValue(TaskVariableMap variables, NbGradleProject project, Lookup actionContext) { - String uniqueName = project.currentModel().getValue().getMainProject().getProjectFullName(); - return new VariableValue(uniqueName); - } + PROJECT_PATH_NOT_NORMALIZED("project-path", (variables, project, actionContext) -> { + String uniqueName = project.currentModel().getValue().getMainProject().getProjectFullName(); + return new VariableValue(uniqueName); }), - PROJECT_PATH_NORMALIZED("project", new ValueGetter() { - @Override - public VariableValue getValue(TaskVariableMap variables, NbGradleProject project, Lookup actionContext) { - String uniqueName = project.currentModel().getValue().getMainProject().getProjectFullName(); - if (":".equals(uniqueName)) { // This is the root project. - uniqueName = ""; - } - return new VariableValue(uniqueName); + PROJECT_PATH_NORMALIZED("project", (variables, project, actionContext) -> { + String uniqueName = project.currentModel().getValue().getMainProject().getProjectFullName(); + if (":".equals(uniqueName)) { // This is the root project. + uniqueName = ""; } + return new VariableValue(uniqueName); }), - SELECTED_CLASS("selected-class", new ValueGetter() { - @Override - public VariableValue getValue(TaskVariableMap variables, NbGradleProject project, Lookup actionContext) { - SpecificTestClass testClass = actionContext.lookup(SpecificTestClass.class); - if (testClass != null) { - return new VariableValue(testClass.getTestClassName()); - } - - FileObject file = getFileOfContext(actionContext); - if (file == null) { - return VariableValue.NULL_VALUE; - } - - return getClassNameForFile(project, file); + SELECTED_CLASS("selected-class", (variables, project, actionContext) -> { + SpecificTestClass testClass = actionContext.lookup(SpecificTestClass.class); + if (testClass != null) { + return new VariableValue(testClass.getTestClassName()); } - }), - SELECTED_FILE("selected-file", new ValueGetter() { - @Override - public VariableValue getValue(TaskVariableMap variables, NbGradleProject project, Lookup actionContext) { - FileObject fileObject = getFileOfContext(actionContext); - if (fileObject == null) { - return VariableValue.NULL_VALUE; - } - File file = FileUtil.toFile(fileObject); - if (file == null) { - return VariableValue.NULL_VALUE; - } - - return new VariableValue(file.getPath()); + FileObject file = getFileOfContext(actionContext); + if (file == null) { + return VariableValue.NULL_VALUE; } + + return getClassNameForFile(project, file); }), - TEST_FILE_PATH("test-file-path", new ValueGetter() { - @Override - public VariableValue getValue(TaskVariableMap variables, NbGradleProject project, Lookup actionContext) { - String selectedClass = variables.tryGetValueForVariable(SELECTED_CLASS.getVariable()); - return new VariableValue(deduceFromClass(selectedClass)); + SELECTED_FILE("selected-file", (variables, project, actionContext) -> { + FileObject fileObject = getFileOfContext(actionContext); + if (fileObject == null) { + return VariableValue.NULL_VALUE; } - private String deduceFromClass(String selectedClass) { - return selectedClass != null - ? selectedClass.replace('.', '/') - : null; - } - }), - TEST_METHOD("test-method", new ValueGetter() { - @Override - public VariableValue getValue(TaskVariableMap variables, NbGradleProject project, Lookup actionContext) { - return getMethodReplaceVariable(variables, project, actionContext); + File file = FileUtil.toFile(fileObject); + if (file == null) { + return VariableValue.NULL_VALUE; } + + return new VariableValue(file.getPath()); }), - PLATFORM_DIR("platform-dir", new ValueGetter() { - @Override - public VariableValue getValue(TaskVariableMap variables, NbGradleProject project, Lookup actionContext) { - ProjectPlatform targetPlatform = project.getCommonProperties().targetPlatform().getActiveValue(); - FileObject rootFolder = targetPlatform != null ? targetPlatform.getRootFolder() : null; - return new VariableValue(rootFolder != null - ? FileUtil.getFileDisplayName(rootFolder) - : null); - } + TEST_FILE_PATH("test-file-path", (variables, project, actionContext) -> { + String selectedClass = variables.tryGetValueForVariable(SELECTED_CLASS.getVariable()); + return new VariableValue(deducePathFromClass(selectedClass)); }), - TEST_TASK_NAME("test-task-name", new ValueGetter() { - @Override - public VariableValue getValue(TaskVariableMap variables, NbGradleProject project, Lookup actionContext) { - return new VariableValue(TestTaskName.getTaskName(actionContext)); - } + TEST_METHOD("test-method", StandardTaskVariable::getMethodReplaceVariable), + PLATFORM_DIR("platform-dir", (variables, project, actionContext) -> { + ProjectPlatform targetPlatform = project.getCommonProperties().targetPlatform().getActiveValue(); + FileObject rootFolder = targetPlatform != null ? targetPlatform.getRootFolder() : null; + return new VariableValue(rootFolder != null + ? FileUtil.getFileDisplayName(rootFolder) + : null); }), - TEST_TASK_NAME_CAPITAL("test-task-name-capital", new ValueGetter() { - @Override - public VariableValue getValue(TaskVariableMap variables, NbGradleProject project, Lookup actionContext) { - String value = variables.tryGetValueForVariable(TEST_TASK_NAME.getVariable()); - return new VariableValue(value != null - ? StringUtils.capitalizeFirstCharacter(value) - : null); - } + TEST_TASK_NAME("test-task-name", (variables, project, actionContext) -> { + return new VariableValue(TestTaskName.getTaskName(actionContext)); }), - CMD_LINE_ARGS("cmd-line-args", new ValueGetter() { - @Override - public VariableValue getValue(TaskVariableMap variables, NbGradleProject project, Lookup actionContext) { - return VariableValue.EMPTY_VALUE; - } + TEST_TASK_NAME_CAPITAL("test-task-name-capital", (variables, project, actionContext) -> { + String value = variables.tryGetValueForVariable(TEST_TASK_NAME.getVariable()); + return new VariableValue(value != null + ? StringUtils.capitalizeFirstCharacter(value) + : null); }), - JVM_LINE_ARGS("jvm-line-args", new ValueGetter() { - @Override - public VariableValue getValue(TaskVariableMap variables, NbGradleProject project, Lookup actionContext) { - return VariableValue.EMPTY_VALUE; - } - }); + CMD_LINE_ARGS("cmd-line-args", (variables, project, actionContext) -> VariableValue.EMPTY_VALUE), + JVM_LINE_ARGS("jvm-line-args", (variables, project, actionContext) -> VariableValue.EMPTY_VALUE); private static final Logger LOGGER = Logger.getLogger(StandardTaskVariable.class.getName()); private static final CachingVariableMap.VariableDefMap TASK_VARIABLE_MAP = createStandardMap(); + private static String deducePathFromClass(String selectedClass) { + return selectedClass != null + ? selectedClass.replace('.', '/') + : null; + } + private static VariableValue getClassNameForFile(NbGradleProject project, FileObject file) { SourceGroup[] sourceGroups = ProjectUtils.getSources(project) .getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA); @@ -252,19 +213,14 @@ public String getScriptReplaceConstant() { private static CachingVariableMap.VariableDefMap createStandardMap() { StandardTaskVariable[] variables = StandardTaskVariable.values(); - final Map> result + Map> result = CollectionUtils.newHashMap(variables.length); for (StandardTaskVariable variable: variables) { result.put(variable.getVariable(), variable.asVariableDef()); } - return new CachingVariableMap.VariableDefMap() { - @Override - public CachingVariableMap.VariableDef tryGetDef(TaskVariable variable) { - return result.get(variable); - } - }; + return result::get; } private VariableDef asVariableDef() { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/vars/TaskVariableMaps.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/vars/TaskVariableMaps.java index f31349b8..8d4ca27b 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/vars/TaskVariableMaps.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/vars/TaskVariableMaps.java @@ -40,12 +40,7 @@ private static TaskVariableMap asTaskVariableMap(PropertySource vars.tryGetValue(variable.getVariableName()); } private static void addAsTaskVariableMap( diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/vars/TaskVariableQueryDialog.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/vars/TaskVariableQueryDialog.java index f51ee483..c754456f 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/vars/TaskVariableQueryDialog.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/tasks/vars/TaskVariableQueryDialog.java @@ -2,13 +2,10 @@ import java.awt.FlowLayout; import java.awt.Frame; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -49,9 +46,9 @@ private TaskVariableQueryDialog(Collection variablesToQue private static Map variableFactoryMap() { Map result = new HashMap<>(); - result.put(VariableTypeDescription.TYPE_NAME_BOOL, BoolVariable.FACTORY); - result.put(VariableTypeDescription.TYPE_NAME_ENUM, EnumVariable.FACTORY); - result.put(VariableTypeDescription.TYPE_NAME_STRING, StringVariable.FACTORY); + result.put(VariableTypeDescription.TYPE_NAME_BOOL, BoolVariable::new); + result.put(VariableTypeDescription.TYPE_NAME_ENUM, EnumVariable::new); + result.put(VariableTypeDescription.TYPE_NAME_STRING, StringVariable::new); return Collections.unmodifiableMap(result); } @@ -78,26 +75,23 @@ private static List toUserVariables(Collection() { - @Override - public int compare(UserVariable o1, UserVariable o2) { - DisplayedTaskVariable var1 = o1.getDisplayedVariable(); - DisplayedTaskVariable var2 = o2.getDisplayedVariable(); + result.sort((UserVariable o1, UserVariable o2) -> { + DisplayedTaskVariable var1 = o1.getDisplayedVariable(); + DisplayedTaskVariable var2 = o2.getDisplayedVariable(); - int typeOrder1 = getTypeOrder(var1); - int typeOrder2 = getTypeOrder(var2); - if (typeOrder1 != typeOrder2) { - return typeOrder1 < typeOrder2 ? -1 : 1; - } - - return StringUtils.STR_CMP.compare(var1.getDisplayName(), var2.getDisplayName()); + int typeOrder1 = getTypeOrder(var1); + int typeOrder2 = getTypeOrder(var2); + if (typeOrder1 != typeOrder2) { + return typeOrder1 < typeOrder2 ? -1 : 1; } + + return StringUtils.STR_CMP.compare(var1.getDisplayName(), var2.getDisplayName()); }); return result; @@ -171,19 +165,11 @@ private Map queryVariables() { getRootPane().setDefaultButton(okButton); final AtomicBoolean okPressed = new AtomicBoolean(false); - okButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - okPressed.set(true); - dispose(); - } - }); - cancelButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - dispose(); - } + okButton.addActionListener(e -> { + okPressed.set(true); + dispose(); }); + cancelButton.addActionListener(e -> dispose()); GroupLayout layout = new GroupLayout(getContentPane()); getContentPane().setLayout(layout); @@ -217,13 +203,6 @@ public void actionPerformed(ActionEvent e) { } private static final class BoolVariable implements UserVariable { - public static final UserVariableFactory FACTORY = new UserVariableFactory() { - @Override - public UserVariable createVariable(DisplayedTaskVariable variable) { - return new BoolVariable(variable); - } - }; - private final DisplayedTaskVariable variable; private final JCheckBox checkBox; private final String[] possibleValues; @@ -279,13 +258,6 @@ public String getValue() { } private static final class EnumVariable implements UserVariable { - public static final UserVariableFactory FACTORY = new UserVariableFactory() { - @Override - public UserVariable createVariable(DisplayedTaskVariable variable) { - return new EnumVariable(variable); - } - }; - private final DisplayedTaskVariable variable; private final JLabel label; private final JComboBox value; @@ -316,11 +288,8 @@ private static void parseComboValues(String valuesDef, JComboBox com } ComboValue selected = comboValues[selectedIndex]; - Arrays.sort(comboValues, new Comparator() { - @Override - public int compare(ComboValue o1, ComboValue o2) { - return StringUtils.STR_CMP.compare(o1.displayValue, o2.displayValue); - } + Arrays.sort(comboValues, (o1, o2) -> { + return StringUtils.STR_CMP.compare(o1.displayValue, o2.displayValue); }); combo.setModel(new DefaultComboBoxModel<>(comboValues)); @@ -366,13 +335,6 @@ public String getValue() { } private static final class StringVariable implements UserVariable { - public static final UserVariableFactory FACTORY = new UserVariableFactory() { - @Override - public UserVariable createVariable(DisplayedTaskVariable variable) { - return new StringVariable(variable); - } - }; - private final DisplayedTaskVariable variable; private final JLabel label; private final JTextField value; diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/CloseableAction.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/CloseableAction.java index 78cac199..3010dd7f 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/CloseableAction.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/CloseableAction.java @@ -6,11 +6,7 @@ public static interface Ref extends AutoCloseable { public void close(); } - public static CloseableAction.Ref CLOSED_REF = new Ref() { - @Override - public void close() { - } - }; + public static CloseableAction.Ref CLOSED_REF = () -> { }; public Ref open(); } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/CloseableActionContainer.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/CloseableActionContainer.java index 4864ccd4..98123d3c 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/CloseableActionContainer.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/CloseableActionContainer.java @@ -43,28 +43,22 @@ public static CloseableAction mergeActions(CloseableAction... actions) { final CloseableAction[] actionsCopy = actions.clone(); ExceptionHelper.checkNotNullElements(actionsCopy, "actions"); - return new CloseableAction() { - @Override - public Ref open() { - Ref[] result = new Ref[actionsCopy.length]; - for (int i = 0; i < result.length; i++) { - result[i] = actionsCopy[i].open(); - } - return mergeActionRefs(result); + return () -> { + CloseableAction.Ref[] result = new CloseableAction.Ref[actionsCopy.length]; + for (int i = 0; i < result.length; i++) { + result[i] = actionsCopy[i].open(); } + return mergeActionRefs(result); }; } private static CloseableAction.Ref mergeActionRefs(final CloseableAction.Ref[] refs) { - return new CloseableAction.Ref() { - @Override - public void close() { - for (CloseableAction.Ref ref: refs) { - try { - ref.close(); - } catch (Throwable ex) { - LOGGER.log(Level.SEVERE, "Unexpected close exception.", ex); - } + return () -> { + for (CloseableAction.Ref ref: refs) { + try { + ref.close(); + } catch (Throwable ex) { + LOGGER.log(Level.SEVERE, "Unexpected close exception.", ex); } } }; @@ -101,23 +95,12 @@ public CloseableAction.Ref defineEventAction( ExceptionHelper.checkNotNullArgument(listenerRegistry, "listenerRegistry"); ExceptionHelper.checkNotNullArgument(listener, "listener"); - CloseableAction action = new CloseableAction() { - @Override - public CloseableAction.Ref open() { - return toActionRef(listenerRegistry.registerListener(listener)); - } - }; + CloseableAction action = () -> toActionRef(listenerRegistry.registerListener(listener)); return defineAction(PropertyFactory.constSource(action), executor); } - private static CloseableAction.Ref toActionRef(final ListenerRef ref) { - ExceptionHelper.checkNotNullArgument(ref, "ref"); - return new CloseableAction.Ref() { - @Override - public void close() { - ref.unregister(); - } - }; + private static CloseableAction.Ref toActionRef(ListenerRef ref) { + return ref::unregister; } public CloseableAction.Ref defineAction(CloseableAction action) { @@ -144,27 +127,21 @@ public CloseableAction.Ref defineAction(PropertySource { + if (opened) { + actionDef.open(); } }); - return new CloseableAction.Ref() { - @Override - public void close() { - actionsLock.lock(); - try { - elementRef.remove(); - } finally { - actionsLock.unlock(); - } - - actionDef.closeForGood(); + return () -> { + actionsLock.lock(); + try { + elementRef.remove(); + } finally { + actionsLock.unlock(); } + + actionDef.closeForGood(); }; } @@ -202,21 +179,15 @@ private void closeNow() { } public void open() { - executeSync(new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) throws Exception { - openNow(); - } + executeSync((CancellationToken cancelToken) -> { + openNow(); }); } public void close() { - executeSync(new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) throws Exception { - if (opened) { - closeNow(); - } + executeSync((CancellationToken cancelToken) -> { + if (opened) { + closeNow(); } }); } @@ -253,12 +224,9 @@ private void executeSync(CancelableTask task) { } public void replaceAction() { - executeSync(new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) throws Exception { - closeNow(); - openNow(); - } + executeSync((CancellationToken cancelToken) -> { + closeNow(); + openNow(); }); } @@ -274,24 +242,16 @@ private void openNow() { prevActionChangeRef.unregister(); } - actionChangeRef = actionProperty.addChangeListener(new Runnable() { - @Override - public void run() { - replaceAction(); - } - }); + actionChangeRef = actionProperty.addChangeListener(this::replaceAction); CloseableAction action = actionProperty.getValue(); openedActionRef = action != null ? action.open() : null; } public void open() { - executeSync(new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) throws Exception { - if (openedActionRef == null) { - openNow(); - } + executeSync((CancellationToken cancelToken) -> { + if (openedActionRef == null) { + openNow(); } }); } @@ -313,21 +273,15 @@ private void closeNow() { } public void close() { - executeSync(new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) throws Exception { - closeNow(); - } + executeSync((CancellationToken cancelToken) -> { + closeNow(); }); } public void closeForGood() { - executeSync(new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) throws Exception { - closedForGood = true; - closeNow(); - } + executeSync((CancellationToken cancelToken) -> { + closedForGood = true; + closeNow(); }); } } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/FileSystemWatcher.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/FileSystemWatcher.java index 2eabb3a2..56a225aa 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/FileSystemWatcher.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/FileSystemWatcher.java @@ -28,8 +28,6 @@ import org.jtrim.cancel.CancellationToken; import org.jtrim.collections.RefLinkedList; import org.jtrim.collections.RefList; -import org.jtrim.concurrent.CancelableTask; -import org.jtrim.concurrent.CleanupTask; import org.jtrim.concurrent.GenericUpdateTaskExecutor; import org.jtrim.concurrent.MonitorableTaskExecutorService; import org.jtrim.concurrent.TaskExecutor; @@ -192,44 +190,35 @@ private static Path keyContext(WatchKey key) { } private void startPolling(final WatchService watchService) { - pollExecutor.execute(Cancellation.UNCANCELABLE_TOKEN, new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) throws Exception { - ListenerRef cancelRef = null; - try { - cancelRef = cancelToken.addCancellationListener(new Runnable() { - @Override - public void run() { - cancelWatchService(watchService); - } - }); - - while (!cancelToken.isCanceled() && hasCheckedPaths()) { - WatchKey key = watchService.take(); - Path keyContext = keyContext(key); - - List> events = key.pollEvents(); - for (WatchEvent event : events) { - notifyPath(keyContext, event); - } - - resetWatchKey(watchService, key, events); - } - } catch (ClosedWatchServiceException ex) { - // Canceled - } finally { - if (cancelRef != null) { - cancelRef.unregister(); + pollExecutor.execute(Cancellation.UNCANCELABLE_TOKEN, (CancellationToken cancelToken) -> { + ListenerRef cancelRef = null; + try { + cancelRef = cancelToken.addCancellationListener(() -> { + cancelWatchService(watchService); + }); + + while (!cancelToken.isCanceled() && hasCheckedPaths()) { + WatchKey key = watchService.take(); + Path keyContext = keyContext(key); + + List> events = key.pollEvents(); + for (WatchEvent event : events) { + notifyPath(keyContext, event); } - stopPolling(watchService); + + resetWatchKey(watchService, key, events); } + } catch (ClosedWatchServiceException ex) { + // Canceled + } finally { + if (cancelRef != null) { + cancelRef.unregister(); + } + stopPolling(watchService); } - }, new CleanupTask() { - @Override - public void cleanup(boolean canceled, Throwable error) throws Exception { - NbTaskExecutors.defaultCleanup(canceled, error); - watchService.close(); - } + }, (boolean canceled, Throwable error) -> { + NbTaskExecutors.defaultCleanup(canceled, error); + watchService.close(); }); } @@ -278,11 +267,8 @@ private ListenerRef watchPathUnsafe(final Path path, Runnable listener) throws I startWatching(currentWatchService, path, listeners); - return NbListenerRefs.fromRunnable(new Runnable() { - @Override - public void run() { - unregisterPath(path, listenerRemover); - } + return NbListenerRefs.fromRunnable(() -> { + unregisterPath(path, listenerRemover); }); } @@ -496,16 +482,13 @@ public ElementRemover addListener(Runnable listener) { listenersLock.unlock(); } - return new ElementRemover() { - @Override - public int removeAndGetRemainingCount() { - listenersLock.lock(); - try { - elementRef.remove(); - return listeners.size(); - } finally { - listenersLock.unlock(); - } + return () -> { + listenersLock.lock(); + try { + elementRef.remove(); + return listeners.size(); + } finally { + listenersLock.unlock(); } }; } @@ -531,15 +514,12 @@ public void notifyIfChanged() { return; } - executor.execute(new Runnable() { - @Override - public void run() { - for (Runnable listener: getListenersSnapshot()) { - try { - listener.run(); - } catch (Throwable ex) { - LOGGER.log(Level.WARNING, "Path change listener has thrown an unexpected exception.", ex); - } + executor.execute(() -> { + for (Runnable listener: getListenersSnapshot()) { + try { + listener.run(); + } catch (Throwable ex) { + LOGGER.log(Level.WARNING, "Path change listener has thrown an unexpected exception.", ex); } } }); diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/GlassPanes.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/GlassPanes.java index 75a6621c..14692f8d 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/GlassPanes.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/GlassPanes.java @@ -36,32 +36,29 @@ public static GlassPaneFactory loadingPanel( ExceptionHelper.checkNotNullArgument(loadingCaption, "loadingCaption"); - return new GlassPaneFactory() { - @Override - public JPanel createGlassPane() { - JPanel result = new JPanel(new GridBagLayout()); - registerInputBlockers(result); + return () -> { + JPanel result = new JPanel(new GridBagLayout()); + registerInputBlockers(result); - result.setBackground(LOADING_PANEL_BCKG); - result.setOpaque(false); + result.setBackground(LOADING_PANEL_BCKG); + result.setOpaque(false); - TextWithCancelPanel panel = new TextWithCancelPanel(loadingCaption, cancelTask); - panel.setOpaque(true); - panel.setBackground(LOADING_PANEL_BASE_BCKG); + TextWithCancelPanel panel = new TextWithCancelPanel(loadingCaption, cancelTask); + panel.setOpaque(true); + panel.setBackground(LOADING_PANEL_BASE_BCKG); - JLabel loadingLabel = panel.getPanelTextComponent(); + JLabel loadingLabel = panel.getPanelTextComponent(); - Font font = loadingLabel.getFont().deriveFont(24.0f); - loadingLabel.setBackground(LOADING_PANEL_BCKG); - loadingLabel.setFont(font); - loadingLabel.setHorizontalAlignment(SwingConstants.CENTER); - loadingLabel.setHorizontalTextPosition(SwingConstants.CENTER); - loadingLabel.setVerticalTextPosition(SwingConstants.CENTER); + Font font = loadingLabel.getFont().deriveFont(24.0f); + loadingLabel.setBackground(LOADING_PANEL_BCKG); + loadingLabel.setFont(font); + loadingLabel.setHorizontalAlignment(SwingConstants.CENTER); + loadingLabel.setHorizontalTextPosition(SwingConstants.CENTER); + loadingLabel.setVerticalTextPosition(SwingConstants.CENTER); - result.add(panel, new GridBagConstraints()); + result.add(panel, new GridBagConstraints()); - return result; - } + return result; }; } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/GradleFileUtils.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/GradleFileUtils.java index 809dfd55..abc05745 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/GradleFileUtils.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/GradleFileUtils.java @@ -23,12 +23,7 @@ public final class GradleFileUtils { private static final File NORM_USER_HOME = getUserHome(); public static final PropertySource GRADLE_USER_HOME = getGradleUserHome(); - public static final NbSupplier GRADLE_USER_HOME_PROVIDER = new NbSupplier() { - @Override - public File get() { - return GRADLE_USER_HOME.getValue(); - } - }; + public static final NbSupplier GRADLE_USER_HOME_PROVIDER = GRADLE_USER_HOME::getValue; public static final Set BINARY_DIR_NAMES = Collections.unmodifiableSet( new HashSet<>(Arrays.asList("jar", "bundle"))); diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/NbFileUtils.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/NbFileUtils.java index 90f467ae..e20eeced 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/NbFileUtils.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/NbFileUtils.java @@ -2,7 +2,6 @@ import java.io.BufferedOutputStream; import java.io.File; -import java.io.FileFilter; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; @@ -149,11 +148,8 @@ public void fileDataCreated(FileEvent fe) { } }; dir.addFileChangeListener(fileChangeListener); - return NbListenerRefs.fromRunnable(new Runnable() { - @Override - public void run() { - dir.removeFileChangeListener(fileChangeListener); - } + return NbListenerRefs.fromRunnable(() -> { + dir.removeFileChangeListener(fileChangeListener); }); } @@ -194,12 +190,7 @@ public static FileObject getFileFromASubDir(FileObject root, String fileName) { return null; } - File[] subDirs = rootDir.listFiles(new FileFilter() { - @Override - public boolean accept(File pathname) { - return pathname.isDirectory(); - } - }); + File[] subDirs = rootDir.listFiles(File::isDirectory); if (subDirs == null) { return null; } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/NbGuiUtils.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/NbGuiUtils.java index aedcb00b..115f81d3 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/NbGuiUtils.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/NbGuiUtils.java @@ -16,13 +16,10 @@ public static void enableBasedOnCheck( final JComponent[] componentsSnapshot = components.clone(); ExceptionHelper.checkNotNullElements(componentsSnapshot, "components"); - ChangeListener changeListener = new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - boolean enable = check.isSelected() == enableValue; - for (JComponent component: componentsSnapshot) { - component.setEnabled(enable); - } + ChangeListener changeListener = (ChangeEvent e) -> { + boolean enable = check.isSelected() == enableValue; + for (JComponent component: componentsSnapshot) { + component.setEnabled(enable); } }; diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/NbPredicate.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/NbPredicate.java index be98588c..2db2d377 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/NbPredicate.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/NbPredicate.java @@ -1,19 +1,8 @@ package org.netbeans.gradle.project.util; public interface NbPredicate { - public static final NbPredicate TRUE = new NbPredicate() { - @Override - public boolean test(Object t) { - return true; - } - }; - - public static final NbPredicate FALSE = new NbPredicate() { - @Override - public boolean test(Object t) { - return false; - } - }; + public static final NbPredicate TRUE = arg -> true; + public static final NbPredicate FALSE = arg -> false; public boolean test(T t); } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/UrlFactory.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/UrlFactory.java index 50268b42..e019db8c 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/UrlFactory.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/util/UrlFactory.java @@ -10,23 +10,13 @@ import org.openide.filesystems.FileUtil; public final class UrlFactory { - private static final NbSupplier5 DEFAULT_REF = new ConstructableWeakRef<>(new NbSupplier5() { - @Override - public UrlFactory get() { - return new UrlFactory(); - } - }); + private static final NbSupplier5 DEFAULT_REF = new ConstructableWeakRef<>(UrlFactory::new); private final NbFunction urlCreator; private final ConcurrentMap cache; public UrlFactory() { - this(new NbFunction() { - @Override - public URL apply(File entry) { - return FileUtil.urlForArchiveOrDir(entry); - } - }); + this(FileUtil::urlForArchiveOrDir); } public UrlFactory(NbFunction urlCreator) { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/validate/BackgroundValidator.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/validate/BackgroundValidator.java index df1dba57..2cbadf38 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/validate/BackgroundValidator.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/validate/BackgroundValidator.java @@ -13,12 +13,10 @@ import org.jtrim.concurrent.GenericUpdateTaskExecutor; import org.jtrim.concurrent.TaskExecutor; import org.jtrim.concurrent.UpdateTaskExecutor; -import org.jtrim.event.EventDispatcher; import org.jtrim.event.ListenerRef; import org.jtrim.event.ListenerRegistries; import org.jtrim.property.MutableProperty; import org.jtrim.property.PropertySource; -import org.jtrim.property.ValueConverter; import org.jtrim.property.swing.SwingProperties; import org.jtrim.property.swing.SwingPropertySource; import org.jtrim.swing.concurrent.SwingTaskExecutor; @@ -41,18 +39,10 @@ public BackgroundValidator() { this.validator = new MostSevereValidator(); this.currentProblem = lazilySetProperty(memProperty((Problem)null, true), Equality.referenceEquality()); - this.currentProblemForSwing = SwingProperties.toSwingSource(currentProblem, new EventDispatcher() { - @Override - public void onEvent(ChangeListener eventListener, Void arg) { - eventListener.stateChanged(new ChangeEvent(BackgroundValidator.this)); - } - }); - this.valid = convert(currentProblem, new ValueConverter() { - @Override - public Boolean convert(Problem input) { - return input == null || input.getLevel() != Problem.Level.SEVERE; - } + this.currentProblemForSwing = SwingProperties.toSwingSource(currentProblem, (ChangeListener eventListener, Void arg) -> { + eventListener.stateChanged(new ChangeEvent(BackgroundValidator.this)); }); + this.valid = convert(currentProblem, input -> input == null || input.getLevel() != Problem.Level.SEVERE); } public ListenerRef addValidator( @@ -73,27 +63,16 @@ public ListenerRef addValidator( final UpdateTaskExecutor updateReader = new GenericUpdateTaskExecutor(inputReaderExecutor); - final AtomicReference valueRef = new AtomicReference<>(input.getValue()); - final Runnable updateValueTask = new Runnable() { - @Override - public void run() { - valueRef.set(input.getValue()); - performValidation(); - } + AtomicReference valueRef = new AtomicReference<>(input.getValue()); + Runnable updateValueTask = () -> { + valueRef.set(input.getValue()); + performValidation(); }; - ListenerRef ref1 = input.addChangeListener(new Runnable() { - @Override - public void run() { - updateReader.execute(updateValueTask); - } - }); - ListenerRef ref2 = this.validator.addValidator(new Validator() { - @Override - public Problem validateInput(Void inputType) { - return validator.validateInput(valueRef.get()); - } + ListenerRef ref1 = input.addChangeListener(() -> { + updateReader.execute(updateValueTask); }); + ListenerRef ref2 = this.validator.addValidator((Void inputType) -> validator.validateInput(valueRef.get())); performValidation(); @@ -121,12 +100,9 @@ public SwingPropertySource currentProblemForSwing() { } private void performValidation() { - validationExecutor.execute(new Runnable() { - @Override - public void run() { - Problem problem = validator.validateInput(null); - currentProblem.setValue(problem); - } + validationExecutor.execute(() -> { + Problem problem = validator.validateInput(null); + currentProblem.setValue(problem); }); } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/validate/Validators.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/validate/Validators.java index 45ceb326..ff498bd0 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/validate/Validators.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/validate/Validators.java @@ -9,7 +9,6 @@ import org.jtrim.property.MutableProperty; import org.jtrim.property.PropertyFactory; import org.jtrim.property.PropertySource; -import org.jtrim.property.ValueConverter; import org.jtrim.property.swing.SwingProperties; import org.jtrim.utils.ExceptionHelper; import org.netbeans.gradle.project.NbStrings; @@ -21,12 +20,7 @@ public final class Validators { public static PropertySource trimmedText(JTextComponent component) { MutableProperty property = SwingProperties.textProperty(component); - return PropertyFactory.convert(property, new ValueConverter() { - @Override - public String convert(String input) { - return input != null ? input.trim() : ""; - } - }); + return PropertyFactory.convert(property, input -> input != null ? input.trim() : ""); } public static Validator createNonEmptyValidator( @@ -35,13 +29,10 @@ public static Validator createNonEmptyValidator( ExceptionHelper.checkNotNullArgument(severity, "severity"); ExceptionHelper.checkNotNullArgument(errorMessage, "errorMessage"); - return new Validator() { - @Override - public Problem validateInput(String inputType) { - return inputType.isEmpty() - ? new Problem(severity, errorMessage) - : null; - } + return (String inputType) -> { + return inputType.isEmpty() + ? new Problem(severity, errorMessage) + : null; }; } @@ -65,14 +56,11 @@ public static Validator createPatternValidator( ExceptionHelper.checkNotNullArgument(severity, "severity"); ExceptionHelper.checkNotNullArgument(errorMessage, "errorMessage"); - return new Validator() { - @Override - public Problem validateInput(String inputType) { - if (!pattern.matcher(inputType).matches()) { - return new Problem(severity, errorMessage); - } - return null; + return (String inputType) -> { + if (!pattern.matcher(inputType).matches()) { + return new Problem(severity, errorMessage); } + return null; }; } @@ -80,23 +68,20 @@ public static Validator merge( final Validator validator1, final Validator validator2) { - return new Validator() { - @Override - public Problem validateInput(InputType inputType) { - Problem problem1 = validator1.validateInput(inputType); - Problem problem2 = validator2.validateInput(inputType); - - if (problem1 == null) { - return problem2; - } - if (problem2 == null) { - return problem1; - } + return (InputType inputType) -> { + Problem problem1 = validator1.validateInput(inputType); + Problem problem2 = validator2.validateInput(inputType); - return problem1.getLevel().getIntValue() >= problem2.getLevel().getIntValue() - ? problem1 - : problem2; + if (problem1 == null) { + return problem2; } + if (problem2 == null) { + return problem1; + } + + return problem1.getLevel().getIntValue() >= problem2.getLevel().getIntValue() + ? problem1 + : problem2; }; } @@ -109,40 +94,37 @@ public static ListenerRef connectLabelToProblems( jLabel.setText(""); final PropertySource validatorProblem = validator.currentProblem(); - return validatorProblem.addChangeListener(new Runnable() { - @Override - public void run() { - Problem currentProblem = validatorProblem.getValue(); - String message = currentProblem != null - ? currentProblem.getMessage() - : ""; - if (message.isEmpty()) { - jLabel.setText(""); - } - else { - assert currentProblem != null; - String title; - Color labelColor; - switch (currentProblem.getLevel()) { - case INFO: - labelColor = Color.BLACK; - title = NbStrings.getInfoCaption(); - break; - case WARNING: - labelColor = Color.ORANGE.darker(); - title = NbStrings.getWarningCaption(); - break; - case SEVERE: - labelColor = Color.RED; - title = NbStrings.getErrorCaption(); - break; - default: - throw new AssertionError(currentProblem.getLevel().name()); - } - - jLabel.setForeground(labelColor); - jLabel.setText(title + ": " + message); + return validatorProblem.addChangeListener(() -> { + Problem currentProblem = validatorProblem.getValue(); + String message = currentProblem != null + ? currentProblem.getMessage() + : ""; + if (message.isEmpty()) { + jLabel.setText(""); + } + else { + assert currentProblem != null; + String title; + Color labelColor; + switch (currentProblem.getLevel()) { + case INFO: + labelColor = Color.BLACK; + title = NbStrings.getInfoCaption(); + break; + case WARNING: + labelColor = Color.ORANGE.darker(); + title = NbStrings.getWarningCaption(); + break; + case SEVERE: + labelColor = Color.RED; + title = NbStrings.getErrorCaption(); + break; + default: + throw new AssertionError(currentProblem.getLevel().name()); } + + jLabel.setForeground(labelColor); + jLabel.setText(title + ": " + message); } }); } @@ -156,34 +138,31 @@ public static ListenerRef connectWizardDescriptorToProblems( wizard.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, null); final PropertySource validatorProblem = validator.currentProblem(); - return validatorProblem.addChangeListener(new Runnable() { - @Override - public void run() { - Problem currentProblem = validatorProblem.getValue(); - String message = currentProblem != null - ? currentProblem.getMessage() - : ""; - if (message.isEmpty()) { - wizard.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, null); - } - else { - assert currentProblem != null; - String level; - switch (currentProblem.getLevel()) { - case INFO: - level = WizardDescriptor.PROP_INFO_MESSAGE; - break; - case WARNING: - level = WizardDescriptor.PROP_WARNING_MESSAGE; - break; - case SEVERE: - level = WizardDescriptor.PROP_ERROR_MESSAGE; - break; - default: - throw new AssertionError(currentProblem.getLevel().name()); - } - wizard.putProperty(level, message); + return validatorProblem.addChangeListener(() -> { + Problem currentProblem = validatorProblem.getValue(); + String message = currentProblem != null + ? currentProblem.getMessage() + : ""; + if (message.isEmpty()) { + wizard.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, null); + } + else { + assert currentProblem != null; + String level; + switch (currentProblem.getLevel()) { + case INFO: + level = WizardDescriptor.PROP_INFO_MESSAGE; + break; + case WARNING: + level = WizardDescriptor.PROP_WARNING_MESSAGE; + break; + case SEVERE: + level = WizardDescriptor.PROP_ERROR_MESSAGE; + break; + default: + throw new AssertionError(currentProblem.getLevel().name()); } + wizard.putProperty(level, message); } }); diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/AnnotationChildNodes.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/AnnotationChildNodes.java index bcf8429f..da7d3317 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/AnnotationChildNodes.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/AnnotationChildNodes.java @@ -12,7 +12,6 @@ import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import java.util.logging.Logger; -import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.jtrim.concurrent.UpdateTaskExecutor; import org.jtrim.event.CopyOnTriggerListenerManager; @@ -21,7 +20,6 @@ import org.jtrim.event.ListenerRef; import org.jtrim.property.PropertyFactory; import org.jtrim.property.PropertySource; -import org.jtrim.property.swing.SwingForwarderFactory; import org.jtrim.property.swing.SwingProperties; import org.jtrim.property.swing.SwingPropertySource; import org.jtrim.swing.concurrent.SwingUpdateTaskExecutor; @@ -32,14 +30,11 @@ import org.netbeans.gradle.project.api.event.NbListenerRefs; import org.netbeans.gradle.project.api.nodes.SingleNodeFactory; import org.netbeans.gradle.project.properties.NbProperties; -import org.netbeans.gradle.project.util.NbBiFunction; -import org.netbeans.gradle.project.util.NbFunction; import org.netbeans.gradle.project.util.NbSupplier; import org.netbeans.spi.project.ui.support.NodeFactory; import org.netbeans.spi.project.ui.support.NodeList; import org.openide.nodes.Node; import org.openide.util.Lookup; -import org.openide.util.LookupEvent; import org.openide.util.LookupListener; import org.openide.util.lookup.Lookups; @@ -59,12 +54,7 @@ public final class AnnotationChildNodes { private Set> currentNodeLists; public AnnotationChildNodes(Project project) { - this(project, new NbSupplier() { - @Override - public Lookup get() { - return Lookups.forPath("Projects/" + GradleProjectIDs.MODULE_NAME + "/Nodes"); - } - }); + this(project, () -> Lookups.forPath("Projects/" + GradleProjectIDs.MODULE_NAME + "/Nodes")); } public AnnotationChildNodes(Project project, NbSupplier factoryLookupProvider) { @@ -77,18 +67,11 @@ public AnnotationChildNodes(Project project, NbSupplier factor this.removeChildrenRef = new RemovedChildrenProperty(); this.currentNodeLists = Collections.emptySet(); - this.nodeFactories = NbProperties.combine(new NodeFactories(factoryLookupProvider), this.removeChildrenRef, new NbBiFunction, Boolean, Collection>() { - @Override - public Collection apply(Collection factories, Boolean removedChildren) { - return removedChildren ? null : factories; - } - }); - this.singleNodeFactories = NbProperties.propertyOfProperty(nodeFactories, new NbFunction, PropertySource>>() { - @Override - public PropertySource> apply(Collection arg) { - return convertFactories(arg); - } - }); + this.nodeFactories = NbProperties.combine( + new NodeFactories(factoryLookupProvider), + this.removeChildrenRef, + (factories, isRemovedChildren) -> isRemovedChildren ? null : factories); + this.singleNodeFactories = NbProperties.propertyOfProperty(nodeFactories, this::convertFactories); } private void createAll( @@ -177,17 +160,9 @@ public void removeChangeListener(ChangeListener listener) { } }; - final UpdateTaskExecutor listenerExecutor = new SwingUpdateTaskExecutor(false); - return SwingProperties.fromSwingSource(result, new SwingForwarderFactory() { - @Override - public ChangeListener createForwarder(final Runnable listener) { - return new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - listenerExecutor.execute(listener); - } - }; - } + UpdateTaskExecutor listenerExecutor = new SwingUpdateTaskExecutor(false); + return SwingProperties.fromSwingSource(result, (Runnable listener) -> { + return e -> listenerExecutor.execute(listener); }); } @@ -254,11 +229,8 @@ public RemovedChildrenProperty() { this.changeListeners = new CopyOnTriggerListenerManager<>(); final UpdateTaskExecutor listenerExecutor = new SwingUpdateTaskExecutor(false); - this.listenerDispatcher = new EventDispatcher() { - @Override - public void onEvent(Runnable eventListener, Void arg) { - listenerExecutor.execute(eventListener); - } + this.listenerDispatcher = (Runnable eventListener, Void arg) -> { + listenerExecutor.execute(eventListener); }; } @@ -314,20 +286,12 @@ public Collection getValue() { @Override public ListenerRef addChangeListener(final Runnable listener) { - final LookupListener wrapper = new LookupListener() { - @Override - public void resultChanged(LookupEvent ev) { - listenerExecutor.execute(listener); - } - }; + LookupListener wrapper = ev -> listenerExecutor.execute(listener); final Lookup.Result nodeLists = getNodeListsResult(); nodeLists.addLookupListener(wrapper); - return NbListenerRefs.fromRunnable(new Runnable() { - @Override - public void run() { - nodeLists.removeLookupListener(wrapper); - } + return NbListenerRefs.fromRunnable(() -> { + nodeLists.removeLookupListener(wrapper); }); } } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/BadgeAwareNode.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/BadgeAwareNode.java index a35d1705..1206f381 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/BadgeAwareNode.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/BadgeAwareNode.java @@ -13,7 +13,6 @@ import org.jtrim.concurrent.UpdateTaskExecutor; import org.jtrim.property.MutableProperty; import org.jtrim.property.PropertySource; -import org.jtrim.property.swing.SwingForwarderFactory; import org.jtrim.property.swing.SwingProperties; import org.jtrim.property.swing.SwingPropertySource; import org.jtrim.swing.concurrent.SwingUpdateTaskExecutor; @@ -21,7 +20,6 @@ import org.netbeans.gradle.model.util.CollectionUtils; import org.netbeans.gradle.project.properties.NbProperties; import org.netbeans.gradle.project.util.ListenerRegistrations; -import org.netbeans.gradle.project.util.NbFunction; import org.netbeans.gradle.project.util.NbTaskExecutors; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileStateInvalidException; @@ -56,13 +54,7 @@ private BadgeAwareNode(Node original, PropertySource> this.fileObjs = lazilySetProperty(memProperty(new FileObjects())); this.fileUpdater = NbTaskExecutors.newDefaultUpdateExecutor(); this.iconChangeNotifier = new SwingUpdateTaskExecutor(true); - - this.statusProperty = NbProperties.propertyOfProperty(fileObjs, new NbFunction>() { - @Override - public PropertySource apply(FileObjects arg) { - return new FileSystemStatusProperty(arg).toStandard(); - } - }); + this.statusProperty = NbProperties.propertyOfProperty(fileObjs, arg -> new FileSystemStatusProperty(arg).toStandard()); } public static Node makeBadgeAware(Node original, PropertySource> files) { @@ -91,22 +83,14 @@ private void updateFilesNow(Collection currentFiles) { } private void updateFiles() { - fileUpdater.execute(new Runnable() { - @Override - public void run() { - Collection currentFiles = files.getValue(); - updateFilesNow(currentFiles != null ? currentFiles : Collections.emptySet()); - } + fileUpdater.execute(() -> { + Collection currentFiles = files.getValue(); + updateFilesNow(currentFiles != null ? currentFiles : Collections.emptySet()); }); } private void updateIcons() { - iconChangeNotifier.execute(new Runnable() { - @Override - public void run() { - updateIconsNow(); - } - }); + iconChangeNotifier.execute(this::updateIconsNow); } private void updateIconsNow() { @@ -115,20 +99,9 @@ private void updateIconsNow() { } public void init() { - listenerRegs.add(NbProperties.weakListenerProperty(files).addChangeListener(new Runnable() { - @Override - public void run() { - updateFiles(); - } - })); + listenerRegs.add(NbProperties.weakListenerProperty(files).addChangeListener(this::updateFiles)); updateFiles(); - - listenerRegs.add(NbProperties.weakListenerProperty(statusProperty).addChangeListener(new Runnable() { - @Override - public void run() { - updateIcons(); - } - })); + listenerRegs.add(NbProperties.weakListenerProperty(statusProperty).addChangeListener(this::updateIcons)); } private Image annotate(Image src) { @@ -202,20 +175,14 @@ public FileSystemStatusProperty(FileObjects fileObjects) { } public PropertySource toStandard() { - return SwingProperties.fromSwingSource(this, new SwingForwarderFactory() { - @Override - public FileStatusListener createForwarder(final Runnable listener) { - ExceptionHelper.checkNotNullArgument(listener, "listener"); - - return new FileStatusListener() { - @Override - public void annotationChanged(FileStatusEvent ev) { - if (anythingChanged(ev)) { - listener.run(); - } - } - }; - } + return SwingProperties.fromSwingSource(this, (Runnable listener) -> { + ExceptionHelper.checkNotNullArgument(listener, "listener"); + + return (FileStatusEvent ev) -> { + if (anythingChanged(ev)) { + listener.run(); + } + }; }); } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/BuildScriptsNode.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/BuildScriptsNode.java index 57986b06..7564ede8 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/BuildScriptsNode.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/BuildScriptsNode.java @@ -16,8 +16,6 @@ import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import org.jtrim.cancel.Cancellation; -import org.jtrim.cancel.CancellationToken; -import org.jtrim.concurrent.CancelableTask; import org.jtrim.utils.ExceptionHelper; import org.netbeans.gradle.project.NbGradleProject; import org.netbeans.gradle.project.NbGradleProjectFactory; @@ -154,12 +152,7 @@ public void refreshChildren() { @Override protected void addNotify() { - listenerRefs.add(project.currentModel().addChangeListener(new Runnable() { - @Override - public void run() { - refreshChildren(); - } - })); + listenerRefs.add(project.currentModel().addChangeListener(this::refreshChildren)); } @Override @@ -275,12 +268,9 @@ private void confirmAndCreateProject(final Path buildSrcDir) { JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION; if (confirmed) { - NbTaskExecutors.DEFAULT_EXECUTOR.execute(Cancellation.UNCANCELABLE_TOKEN, new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) throws Exception { - createBuildSrc(buildSrcDir); - openProjectNow(buildSrcDir); - } + NbTaskExecutors.DEFAULT_EXECUTOR.execute(Cancellation.UNCANCELABLE_TOKEN, (cancelToken) -> { + createBuildSrc(buildSrcDir); + openProjectNow(buildSrcDir); }, null); } } @@ -290,22 +280,16 @@ private void doActionNow(final Path buildSrcDir) { openProjectNow(buildSrcDir); } else { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - confirmAndCreateProject(buildSrcDir); - } + SwingUtilities.invokeLater(() -> { + confirmAndCreateProject(buildSrcDir); }); } } @Override public void actionPerformed(ActionEvent e) { - NbTaskExecutors.DEFAULT_EXECUTOR.execute(Cancellation.UNCANCELABLE_TOKEN, new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) throws Exception { - doActionNow(getBuildSrcDir(project)); - } + NbTaskExecutors.DEFAULT_EXECUTOR.execute(Cancellation.UNCANCELABLE_TOKEN, (cancelToken) -> { + doActionNow(getBuildSrcDir(project)); }, null); } } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/CustomActionPanel.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/CustomActionPanel.java index a9d82675..2b5b9ac0 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/CustomActionPanel.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/CustomActionPanel.java @@ -152,12 +152,7 @@ private static List splitLinesIgnoreVars(String text) { } public PredefinedTask tryGetPredefinedTask(String displayName) { - return tryGetPredefinedTask(displayName, new NbSupplier>() { - @Override - public List get() { - return Collections.emptyList(); - } - }); + return tryGetPredefinedTask(displayName, Collections::emptyList); } public PredefinedTask tryGetPredefinedTask( diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/DeleteProjectAction.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/DeleteProjectAction.java index 6211bfb7..6642b096 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/DeleteProjectAction.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/DeleteProjectAction.java @@ -11,8 +11,6 @@ import org.jtrim.cancel.CancellationController; import org.jtrim.cancel.CancellationSource; import org.jtrim.cancel.CancellationToken; -import org.jtrim.concurrent.CancelableTask; -import org.jtrim.concurrent.CleanupTask; import org.jtrim.utils.ExceptionHelper; import org.netbeans.api.progress.ProgressHandle; import org.netbeans.api.project.Project; @@ -23,7 +21,6 @@ import org.netbeans.gradle.project.util.NbTaskExecutors; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; -import org.openide.util.Cancellable; public final class DeleteProjectAction extends AbstractAction { private static final long serialVersionUID = -386797460711624644L; @@ -69,12 +66,9 @@ private void doRemoveProject(CancellationToken cancelToken) { private ProgressHandle createProgress(final CancellationController cancelController) { String caption = NbStrings.getDeleteProjectProgress(project.getDisplayName()); - return ProgressHandle.createHandle(caption, new Cancellable() { - @Override - public boolean cancel() { - cancelController.cancel(); - return true; - } + return ProgressHandle.createHandle(caption, () -> { + cancelController.cancel(); + return true; }); } @@ -91,17 +85,9 @@ public void actionPerformed(ActionEvent e) { final ProgressHandle progress = createProgress(cancel.getController()); progress.start(); - NbTaskExecutors.DEFAULT_EXECUTOR.execute(cancel.getToken(), new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) { - doRemoveProject(cancelToken); - } - }, new CleanupTask() { - @Override - public void cleanup(boolean canceled, Throwable error) throws Exception { - NbTaskExecutors.defaultCleanup(canceled, error); - progress.finish(); - } + NbTaskExecutors.DEFAULT_EXECUTOR.execute(cancel.getToken(), this::doRemoveProject, (canceled, error) -> { + NbTaskExecutors.defaultCleanup(canceled, error); + progress.finish(); }); } } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/DisplayableTaskVariable.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/DisplayableTaskVariable.java index 825ab20d..4d47cb82 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/DisplayableTaskVariable.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/DisplayableTaskVariable.java @@ -17,57 +17,33 @@ import org.openide.util.Lookup; public enum DisplayableTaskVariable { - PROJECT_PATH("project.path", new ValueGetter() { - @Override - public VariableValue getValue(TaskVariableMap variables, NbGradleModel model, Lookup actionContext) { - return new VariableValue(getSafeProjectPath(model)); - } + PROJECT_PATH("project.path", (TaskVariableMap variables, NbGradleModel model, Lookup actionContext) -> { + return new VariableValue(getSafeProjectPath(model)); }), - PROJECT_GROUP("project.group", new ValueGetter() { - @Override - public VariableValue getValue(TaskVariableMap variables, NbGradleModel model, Lookup actionContext) { - ProjectId projectId = model.getProjectId(); - return new VariableValue(projectId.getGroup()); - } + PROJECT_GROUP("project.group", (TaskVariableMap variables, NbGradleModel model, Lookup actionContext) -> { + ProjectId projectId = model.getProjectId(); + return new VariableValue(projectId.getGroup()); }), - PROJECT_NAME("project.name", new ValueGetter() { - @Override - public VariableValue getValue(TaskVariableMap variables, NbGradleModel model, Lookup actionContext) { - return new VariableValue(getSafeProjectName(model)); - } + PROJECT_NAME("project.name", (TaskVariableMap variables, NbGradleModel model, Lookup actionContext) -> { + return new VariableValue(getSafeProjectName(model)); }), - PROJECT_VERSION("project.version", new ValueGetter() { - @Override - public VariableValue getValue(TaskVariableMap variables, NbGradleModel model, Lookup actionContext) { - ProjectId projectId = model.getProjectId(); - return new VariableValue(projectId.getVersion()); - } + PROJECT_VERSION("project.version", (TaskVariableMap variables, NbGradleModel model, Lookup actionContext) -> { + ProjectId projectId = model.getProjectId(); + return new VariableValue(projectId.getVersion()); }), - PARENT_PATH("parent.path", new ValueGetter() { - @Override - public VariableValue getValue(TaskVariableMap variables, NbGradleModel model, Lookup actionContext) { - return new VariableValue(getProjectPath(parent(model))); - } + PARENT_PATH("parent.path", (TaskVariableMap variables, NbGradleModel model, Lookup actionContext) -> { + return new VariableValue(getProjectPath(parent(model))); }), - PARENT_GROUP("parent.group", new ValueGetter() { - @Override - public VariableValue getValue(TaskVariableMap variables, NbGradleModel model, Lookup actionContext) { - ProjectId projectId = parentId(model); - return new VariableValue(projectId != null ? projectId.getGroup() : ""); - } + PARENT_GROUP("parent.group", (TaskVariableMap variables, NbGradleModel model, Lookup actionContext) -> { + ProjectId projectId = parentId(model); + return new VariableValue(projectId != null ? projectId.getGroup() : ""); }), - PARENT_NAME("parent.name", new ValueGetter() { - @Override - public VariableValue getValue(TaskVariableMap variables, NbGradleModel model, Lookup actionContext) { - return new VariableValue(getProjectName(parent(model))); - } + PARENT_NAME("parent.name", (TaskVariableMap variables, NbGradleModel model, Lookup actionContext) -> { + return new VariableValue(getProjectName(parent(model))); }), - PARENT_VERSION("parent.version", new ValueGetter() { - @Override - public VariableValue getValue(TaskVariableMap variables, NbGradleModel model, Lookup actionContext) { - ProjectId projectId = parentId(model); - return new VariableValue(projectId != null ? projectId.getVersion() : ""); - } + PARENT_VERSION("parent.version", (TaskVariableMap variables, NbGradleModel model, Lookup actionContext) -> { + ProjectId projectId = parentId(model); + return new VariableValue(projectId != null ? projectId.getVersion() : ""); }); private static NbGradleProjectTree parent(NbGradleModel model) { @@ -139,19 +115,12 @@ private static String getSafeProjectPath(NbGradleModel model) { private static VariableDefMap createStandardMap() { DisplayableTaskVariable[] variables = DisplayableTaskVariable.values(); - final Map> result - = CollectionUtils.newHashMap(variables.length); - + Map> result = CollectionUtils.newHashMap(variables.length); for (DisplayableTaskVariable variable: variables) { result.put(variable.getVariable(), variable.asVariableDef()); } - return new VariableDefMap() { - @Override - public VariableDef tryGetDef(TaskVariable variable) { - return result.get(variable); - } - }; + return result::get; } public static TaskVariableMap createVarReplaceMap(NbGradleModel project) { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/GlobalErrorReporter.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/GlobalErrorReporter.java index 28a5dcef..1a688803 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/GlobalErrorReporter.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/GlobalErrorReporter.java @@ -15,23 +15,20 @@ public final class GlobalErrorReporter { public static void showIssue(final String message, final Icon icon) { ExceptionHelper.checkNotNullArgument(message, "message"); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - NotificationDisplayer displayer = NotificationDisplayer.getDefault(); - JLabel messageLabel = new JLabel( - message, - icon, - SwingConstants.LEADING); - JLabel lineLabel = new JLabel(message); - - displayer.notify( - NbStrings.getGlobalErrorReporterTitle(), - ERROR_ICON, - messageLabel, - lineLabel, - NotificationDisplayer.Priority.HIGH); - } + SwingUtilities.invokeLater(() -> { + NotificationDisplayer displayer = NotificationDisplayer.getDefault(); + JLabel messageLabel = new JLabel( + message, + icon, + SwingConstants.LEADING); + JLabel lineLabel = new JLabel(message); + + displayer.notify( + NbStrings.getGlobalErrorReporterTitle(), + ERROR_ICON, + messageLabel, + lineLabel, + NotificationDisplayer.Priority.HIGH); }); } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/GradleActionProvider.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/GradleActionProvider.java index 54e120fa..0c6ca3d8 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/GradleActionProvider.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/GradleActionProvider.java @@ -175,19 +175,9 @@ private Runnable createAction(final String command, Lookup context) { switch (command) { case COMMAND_RELOAD: - return new Runnable() { - @Override - public void run() { - project.reloadProject(); - } - }; + return project::reloadProject; case COMMAND_SET_AS_MAIN_PROJECT: - return new Runnable() { - @Override - public void run() { - OpenProjects.getDefault().setMainProject(project); - } - }; + return () -> OpenProjects.getDefault().setMainProject(project); } final Lookup appliedContext = getAppliedContext(command, context); @@ -251,21 +241,18 @@ public GradleTaskDef tryCreateTaskDef(CancellationToken cancelToken) throws Exce Set actionContexts = EnumSet.noneOf(GradleActionProviderContext.class); actionContexts.addAll(appliedContext.lookupAll(GradleActionProviderContext.class)); - return GradleTasks.createAsyncGradleTask(project, taskDefFactory, actionContexts, new CommandCompleteListener() { - @Override - public void onComplete(Throwable error) { - try { - CustomCommandActions customActions = customActionsRef.get(); - if (customActions != null) { - CommandCompleteListener completeListener - = customActions.getCommandCompleteListener(); - if (completeListener != null) { - completeListener.onComplete(error); - } + return GradleTasks.createAsyncGradleTask(project, taskDefFactory, actionContexts, (Throwable error) -> { + try { + CustomCommandActions customActions = customActionsRef.get(); + if (customActions != null) { + CommandCompleteListener completeListener + = customActions.getCommandCompleteListener(); + if (completeListener != null) { + completeListener.onComplete(error); } - } finally { - GradleTasks.projectTaskCompleteListener(project).onComplete(error); } + } finally { + GradleTasks.projectTaskCompleteListener(project).onComplete(error); } }); } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/GradleFolderNode.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/GradleFolderNode.java index a9b21fd7..279fce24 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/GradleFolderNode.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/GradleFolderNode.java @@ -12,7 +12,6 @@ import javax.swing.SwingUtilities; import org.jtrim.cancel.Cancellation; import org.jtrim.cancel.CancellationToken; -import org.jtrim.concurrent.CancelableTask; import org.jtrim.concurrent.TaskExecutor; import org.jtrim.utils.ExceptionHelper; import org.netbeans.gradle.project.NbIcons; @@ -121,24 +120,18 @@ public void actionPerformed(ActionEvent e) { template.setTargetFolder(targetFolder); template.setTemplatesFolder(DataFolder.findFolder(GradleTemplateConsts.getTemplateFolder())); - GRADLE_FOLDER_CREATOR.execute(Cancellation.UNCANCELABLE_TOKEN, new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) throws Exception { - Set dataObjs = template.instantiate(DataFolder.find(GradleTemplateRegistration.getTemplateFileObj())); - if (dataObjs == null) { - return; - } + GRADLE_FOLDER_CREATOR.execute(Cancellation.UNCANCELABLE_TOKEN, (CancellationToken cancelToken) -> { + Set dataObjs = template.instantiate(DataFolder.find(GradleTemplateRegistration.getTemplateFileObj())); + if (dataObjs == null) { + return; + } - for (DataObject dataObj: dataObjs) { - final FileObject fileObj = dataObj.getPrimaryFile(); - if (fileObj != null) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - OpenEditorOutputListener.tryOpenFile(fileObj, -1); - } - }); - } + for (DataObject dataObj: dataObjs) { + final FileObject fileObj = dataObj.getPrimaryFile(); + if (fileObj != null) { + SwingUtilities.invokeLater(() -> { + OpenEditorOutputListener.tryOpenFile(fileObj, -1); + }); } } }, null); @@ -174,12 +167,7 @@ public void refreshChildren() { @Override protected void addNotify() { - listenerRegistrations.add(NbFileUtils.addDirectoryContentListener(dir, new Runnable() { - @Override - public void run() { - refreshChildren(); - } - })); + listenerRegistrations.add(NbFileUtils.addDirectoryContentListener(dir, this::refreshChildren)); } @Override @@ -193,12 +181,7 @@ private static SingleNodeFactory tryGetGradleNode(FileObject child) { private void readKeys(List toPopulate) { FileObject[] children = dir.getChildren(); - Arrays.sort(children, new Comparator() { - @Override - public int compare(FileObject o1, FileObject o2) { - return StringUtils.STR_CMP.compare(o1.getNameExt(), o2.getNameExt()); - } - }); + Arrays.sort(children, Comparator.comparing(FileObject::getNameExt, StringUtils.STR_CMP::compare)); for (FileObject child: children) { if (scriptProvider.isScriptFileName(child.getNameExt())) { diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/GradleHomeNode.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/GradleHomeNode.java index 5e604479..c3eaf2e0 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/GradleHomeNode.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/GradleHomeNode.java @@ -14,12 +14,8 @@ import javax.swing.AbstractAction; import javax.swing.Action; import org.jtrim.cancel.Cancellation; -import org.jtrim.cancel.CancellationToken; -import org.jtrim.concurrent.CancelableTask; import org.jtrim.event.EventListeners; -import org.jtrim.event.ListenerRef; import org.jtrim.event.ProxyListenerRegistry; -import org.jtrim.event.SimpleListenerRegistry; import org.jtrim.utils.ExceptionHelper; import org.netbeans.gradle.project.NbIcons; import org.netbeans.gradle.project.NbStrings; @@ -241,11 +237,8 @@ private void updateUserHome() { userHomeChangeListeners.replaceRegistry(NbListenerManagers.neverNotifingRegistry()); } else { - userHomeChangeListeners.replaceRegistry(new SimpleListenerRegistry() { - @Override - public ListenerRef registerListener(Runnable listener) { - return NbFileUtils.addDirectoryContentListener(userHome, true, listener); - } + userHomeChangeListeners.replaceRegistry((Runnable listener) -> { + return NbFileUtils.addDirectoryContentListener(userHome, true, listener); }); } userHomeChangeListeners.onEvent(EventListeners.runnableDispatcher(), null); @@ -253,19 +246,9 @@ public ListenerRef registerListener(Runnable listener) { @Override protected void addNotify() { - listenerRefs.add(GradleFileUtils.GRADLE_USER_HOME.addChangeListener(new Runnable() { - @Override - public void run() { - updateUserHome(); - } - })); + listenerRefs.add(GradleFileUtils.GRADLE_USER_HOME.addChangeListener(this::updateUserHome)); updateUserHome(); - listenerRefs.add(userHomeChangeListeners.registerListener(new Runnable() { - @Override - public void run() { - refresh(false); - } - })); + listenerRefs.add(userHomeChangeListeners.registerListener(() -> refresh(false))); } @Override @@ -347,12 +330,7 @@ private void addOtherGradleFiles( } } - Collections.sort(gradleFiles, new Comparator() { - @Override - public int compare(FileObject o1, FileObject o2) { - return StringUtils.STR_CMP.compare(o1.getNameExt(), o2.getNameExt()); - } - }); + Collections.sort(gradleFiles, Comparator.comparing(FileObject::getNameExt, StringUtils.STR_CMP::compare)); for (FileObject file: gradleFiles) { SingleNodeFactory node = NodeUtils.tryGetFileNode( @@ -415,14 +393,11 @@ public CreateInitDAction() { @Override public void actionPerformed(ActionEvent e) { - NbTaskExecutors.DEFAULT_EXECUTOR.execute(Cancellation.UNCANCELABLE_TOKEN, new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) throws Exception { - Path userHome = getGradleUserHome(); - if (userHome != null) { - Path initDPath = userHome.resolve(INIT_D_NAME); - Files.createDirectories(initDPath); - } + NbTaskExecutors.DEFAULT_EXECUTOR.execute(Cancellation.UNCANCELABLE_TOKEN, (cancelToken) -> { + Path userHome = getGradleUserHome(); + if (userHome != null) { + Path initDPath = userHome.resolve(INIT_D_NAME); + Files.createDirectories(initDPath); } }, null); } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/GradleProjectChildFactory.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/GradleProjectChildFactory.java index 4d9ba3b2..6f9c2e8b 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/GradleProjectChildFactory.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/GradleProjectChildFactory.java @@ -68,12 +68,9 @@ public GradleProjectChildFactory(NbGradleProject project, GradleProjectLogicalVi this.createdOnce = false; this.refreshNotifier = new GenericChangeListenerManager(SwingTaskExecutor.getStrictExecutor(false)); - this.refreshNotifier.registerListener(new Runnable() { - @Override - public void run() { - if (createdOnce) { - refresh(false); - } + this.refreshNotifier.registerListener(() -> { + if (createdOnce) { + refresh(false); } }); } @@ -157,31 +154,20 @@ private void updateNodesIfNeeded(NodeExtensions newNodeExtensions) { @Override protected void addNotify() { - final Runnable simpleChangeListener = new Runnable() { - @Override - public void run() { - refreshChildren(); - } - }; + Runnable simpleChangeListener = this::refreshChildren; annotationChildNodes.addNotify(); listenerRefs.add(annotationChildNodes.nodeFactories().addChangeListener(simpleChangeListener)); - listenerRefs.add(project.currentModel().addChangeListener(new Runnable() { - @Override - public void run() { - NodeExtensions newNodeExtensions - = NodeExtensions.create(getExtensionNodes(), simpleChangeListener); + listenerRefs.add(project.currentModel().addChangeListener(() -> { + NodeExtensions newNodeExtensions + = NodeExtensions.create(getExtensionNodes(), simpleChangeListener); - updateNodesIfNeeded(newNodeExtensions); - } + updateNodesIfNeeded(newNodeExtensions); })); - listenerRefs.add(NbListenerRefs.fromRunnable(new Runnable() { - @Override - public void run() { - tryReplaceNodeExtensionAndClose(null); - } + listenerRefs.add(NbListenerRefs.fromRunnable(() -> { + tryReplaceNodeExtensionAndClose(null); })); listenerRefs.add(registerModelRefreshListener()); @@ -254,13 +240,10 @@ private void addChildren(List toPopulate) { } final List children = getAllChildren(shownModule); - toPopulate.add(new SingleNodeFactory() { - @Override - public Node createNode() { - return new FilterNode( - createSimpleNode(), - createSubprojectsChild(), - Lookups.singleton(shownModule.getMainProject())) { + toPopulate.add(() -> new FilterNode( + createSimpleNode(), + createSubprojectsChild(), + Lookups.singleton(shownModule.getMainProject())) { @Override public String getName() { return "SubProjectsNode_" + getShownModule().getMainProject().getProjectFullName().replace(':', '_'); @@ -293,9 +276,7 @@ public Image getOpenedIcon(int type) { public boolean canRename() { return false; } - }; - } - }); + }); } private void readKeys(List toPopulate) throws DataObjectNotFoundException { @@ -357,12 +338,7 @@ public boolean isNeedRefreshOnProjectReload() { } public static NodeExtensions createEmpty() { - return create(Collections.emptyList(), new Runnable() { - @Override - public void run() { - // Do nothing. - } - }); + return create(Collections.emptyList(), () -> { }); } public static NodeExtensions create( diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/GradleProjectLogicalViewProvider.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/GradleProjectLogicalViewProvider.java index b7d6dbfd..27973aff 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/GradleProjectLogicalViewProvider.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/GradleProjectLogicalViewProvider.java @@ -11,7 +11,6 @@ import javax.swing.Action; import org.jtrim.concurrent.UpdateTaskExecutor; import org.jtrim.event.CopyOnTriggerListenerManager; -import org.jtrim.event.EventDispatcher; import org.jtrim.event.ListenerManager; import org.jtrim.event.ListenerRef; import org.jtrim.swing.concurrent.SwingUpdateTaskExecutor; @@ -70,12 +69,9 @@ public ListenerRef addChildModelRefreshListener(final ModelRefreshListener liste @Override public void startRefresh() { final List listeners = new ArrayList<>(); - childRefreshListeners.onEvent(new EventDispatcher() { - @Override - public void onEvent(ModelRefreshListener eventListener, Void arg) { - eventListener.startRefresh(); - listeners.add(eventListener); - } + childRefreshListeners.onEvent((ModelRefreshListener eventListener, Void arg) -> { + eventListener.startRefresh(); + listeners.add(eventListener); }, null); Collection prevListeners = listenersToFinalize.getAndSet(listeners); @@ -100,34 +96,13 @@ public void endRefresh(boolean extensionsChanged) { public Node createLogicalView() { DataFolder projectFolder = DataFolder.findFolder(project.getProjectDirectory()); - final GradleProjectNode result = new GradleProjectNode(projectFolder, actionProvider); - + GradleProjectNode result = new GradleProjectNode(projectFolder, actionProvider); ProjectDisplayInfo displayInfo = project.getDisplayInfo(); - final ListenerRef displayNameRef = displayInfo.displayName().addChangeListener(new Runnable() { - @Override - public void run() { - result.fireDisplayNameChange(); - } - }); - final ListenerRef descriptionRef = displayInfo.description().addChangeListener(new Runnable() { - @Override - public void run() { - result.fireShortDescriptionChange(); - } - }); - final ListenerRef modelListenerRef = project.currentModel().addChangeListener(new Runnable() { - @Override - public void run() { - result.fireModelChange(); - } - }); - final ListenerRef infoListenerRef = project.getProjectIssueManager().addChangeListener(new Runnable() { - @Override - public void run() { - result.fireInfoChangeEvent(); - } - }); + final ListenerRef displayNameRef = displayInfo.displayName().addChangeListener(result::fireDisplayNameChange); + final ListenerRef descriptionRef = displayInfo.description().addChangeListener(result::fireShortDescriptionChange); + final ListenerRef modelListenerRef = project.currentModel().addChangeListener(result::fireModelChange); + final ListenerRef infoListenerRef = project.getProjectIssueManager().addChangeListener(result::fireInfoChangeEvent); result.addNodeListener(new NodeAdapter(){ @Override public void nodeDestroyed(NodeEvent ev) { @@ -190,39 +165,21 @@ private void updateActionsList() { } public void fireDisplayNameChange() { - displayNameChanges.execute(new Runnable() { - @Override - public void run() { - fireDisplayNameChange(null, null); - } - }); + displayNameChanges.execute(() -> fireDisplayNameChange(null, null)); } public void fireShortDescriptionChange() { - descriptionChanges.execute(new Runnable() { - @Override - public void run() { - fireShortDescriptionChange(null, null); - } - }); + descriptionChanges.execute(() -> fireShortDescriptionChange(null, null)); } public void fireModelChange() { - modelChanges.execute(new Runnable() { - @Override - public void run() { - updateActionsList(); - } - }); + modelChanges.execute(this::updateActionsList); } public void fireInfoChangeEvent() { - iconChanges.execute(new Runnable() { - @Override - public void run() { - fireIconChange(); - fireOpenedIconChange(); - } + iconChanges.execute(() -> { + fireIconChange(); + fireOpenedIconChange(); }); } @@ -258,7 +215,7 @@ public Image getIcon(int type) { = new EnumMap<>(ProjectIssue.Kind.class); for (ProjectIssue.Kind kind: ProjectIssue.Kind.values()) { - infoMap.put(kind, new ArrayList()); + infoMap.put(kind, new ArrayList<>()); } Kind mostImportantKind = Kind.INFO; diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/NodeUtils.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/NodeUtils.java index 8bc18b28..426d0c10 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/NodeUtils.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/NodeUtils.java @@ -39,12 +39,9 @@ public static NodeRefresher defaultNodeRefresher( ExceptionHelper.checkNotNullArgument(children, "children"); ExceptionHelper.checkNotNullArgument(childrenRefresher, "childrenRefresher"); - return new NodeRefresher() { - @Override - public void refreshNode() { - childrenRefresher.refreshChildren(); - NodeUtils.refreshChildNodes(children); - } + return () -> { + childrenRefresher.refreshChildren(); + NodeUtils.refreshChildNodes(children); }; } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/OpenAlwaysFileAction.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/OpenAlwaysFileAction.java index 671969b9..85ddb2e7 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/OpenAlwaysFileAction.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/OpenAlwaysFileAction.java @@ -8,8 +8,6 @@ import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import org.jtrim.cancel.Cancellation; -import org.jtrim.cancel.CancellationToken; -import org.jtrim.concurrent.CancelableTask; import org.jtrim.utils.ExceptionHelper; import org.netbeans.gradle.project.NbStrings; import org.netbeans.gradle.project.output.OpenEditorOutputListener; @@ -30,12 +28,7 @@ public OpenAlwaysFileAction(Path file) { } public OpenAlwaysFileAction(String name, final Path file) { - this(name, new NbSupplier() { - @Override - public Path get() { - return file; - } - }); + this(name, () -> file); ExceptionHelper.checkNotNullArgument(file, "file"); } @@ -57,12 +50,7 @@ public static OpenAlwaysFileAction openScriptAction( String caption = NbStrings.getOpenFileCaption(scriptBaseName + CommonScripts.DEFAULT_SCRIPT_EXTENSION); final CommonScripts commonScripts = new CommonScripts(scriptProvider); - return new OpenAlwaysFileAction(caption, new NbSupplier() { - @Override - public Path get() { - return commonScripts.getScriptFilePath(baseDir, scriptBaseName); - } - }); + return new OpenAlwaysFileAction(caption, () -> commonScripts.getScriptFilePath(baseDir, scriptBaseName)); } private FileObject tryGetFileObjectCreateIfNeeded() { @@ -95,26 +83,20 @@ private void showCannotCreateFile() { private void openFileNow() { final FileObject fileObj = tryGetFileObjectCreateIfNeeded(); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (fileObj != null) { - OpenEditorOutputListener.tryOpenFile(fileObj, -1); - } - else { - showCannotCreateFile(); - } + SwingUtilities.invokeLater(() -> { + if (fileObj != null) { + OpenEditorOutputListener.tryOpenFile(fileObj, -1); + } + else { + showCannotCreateFile(); } }); } @Override public void actionPerformed(ActionEvent e) { - NbTaskExecutors.DEFAULT_EXECUTOR.execute(Cancellation.UNCANCELABLE_TOKEN, new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) throws Exception { - openFileNow(); - } + NbTaskExecutors.DEFAULT_EXECUTOR.execute(Cancellation.UNCANCELABLE_TOKEN, (cancelToken) -> { + openFileNow(); }, null); } } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/OpenProjectsAction.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/OpenProjectsAction.java index 98354499..85852a76 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/OpenProjectsAction.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/OpenProjectsAction.java @@ -11,8 +11,6 @@ import java.util.logging.Logger; import javax.swing.AbstractAction; import org.jtrim.cancel.Cancellation; -import org.jtrim.cancel.CancellationToken; -import org.jtrim.concurrent.CancelableTask; import org.jtrim.utils.ExceptionHelper; import org.netbeans.api.project.Project; import org.netbeans.api.project.ProjectManager; @@ -99,12 +97,9 @@ public static void openProject(File projectDir) { @Override public void actionPerformed(ActionEvent e) { - NbTaskExecutors.DEFAULT_EXECUTOR.execute(Cancellation.UNCANCELABLE_TOKEN, new CancelableTask() { - @Override - public void execute(CancellationToken cancelToken) { - for (File projectDir: projectDirs) { - openProject(projectDir); - } + NbTaskExecutors.DEFAULT_EXECUTOR.execute(Cancellation.UNCANCELABLE_TOKEN, (cancelToken) -> { + for (File projectDir: projectDirs) { + openProject(projectDir); } }, null); } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/ProjectContextActionProvider.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/ProjectContextActionProvider.java index 7ee1e91d..f6c5c38d 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/ProjectContextActionProvider.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/ProjectContextActionProvider.java @@ -2,11 +2,9 @@ import java.awt.Dialog; import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.ListIterator; @@ -256,14 +254,7 @@ public void updateMenuContent() { lastUsedModule = mainModule; List commonTasksList = new ArrayList<>(commonTasks.getTasks()); - Collections.sort(commonTasksList, new Comparator() { - @Override - public int compare(PredefinedTask o1, PredefinedTask o2) { - String name1 = o1.getDisplayName(); - String name2 = o2.getDisplayName(); - return StringUtils.STR_CMP.compare(name1, name2); - } - }); + commonTasksList.sort(Comparator.comparing(PredefinedTask::getDisplayName, StringUtils.STR_CMP::compare)); boolean hasCustomTasks = false; menu.removeAll(); @@ -277,11 +268,8 @@ public int compare(PredefinedTask o1, PredefinedTask o2) { } JMenuItem menuItem = new JMenuItem(task.getDisplayName()); - menuItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - executeCommandTemplate(project, task.toCommandTemplate()); - } + menuItem.addActionListener((ActionEvent e) -> { + executeCommandTemplate(project, task.toCommandTemplate()); }); menu.add(menuItem); hasCustomTasks = true; @@ -486,14 +474,11 @@ private void addToMenu(JMenu rootMenu, List rootNodes) { final GradleTaskID taskID = root.getTaskID(); if (taskID != null) { - toAdd.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - GradleCommandTemplate.Builder command - = new GradleCommandTemplate.Builder("", Arrays.asList(taskID.getFullName())); - - executeCommandTemplate(project, command.create()); - } + toAdd.addActionListener((ActionEvent e) -> { + GradleCommandTemplate.Builder command + = new GradleCommandTemplate.Builder("", Arrays.asList(taskID.getFullName())); + + executeCommandTemplate(project, command.create()); }); } diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/ProjectScriptFilesNode.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/ProjectScriptFilesNode.java index 916c3fc1..5e74f94c 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/ProjectScriptFilesNode.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/ProjectScriptFilesNode.java @@ -4,7 +4,6 @@ import java.io.File; import java.nio.file.Path; import java.util.ArrayList; -import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Objects; @@ -169,12 +168,7 @@ public void refreshChildren() { @Override protected void addNotify() { - Runnable refreshChildrenTask = new Runnable() { - @Override - public void run() { - refreshChildren(); - } - }; + Runnable refreshChildrenTask = this::refreshChildren; listenerRefs.add(project.currentModel().addChangeListener(refreshChildrenTask)); listenerRefs.add(NbFileUtils.addDirectoryContentListener(project.getProjectDirectory(), refreshChildrenTask)); @@ -251,12 +245,7 @@ private void readKeys(List toPopulate) { } } - Collections.sort(gradleFiles, new Comparator() { - @Override - public int compare(FileObject o1, FileObject o2) { - return StringUtils.STR_CMP.compare(o1.getNameExt(), o2.getNameExt()); - } - }); + gradleFiles.sort(Comparator.comparing(FileObject::getNameExt, StringUtils.STR_CMP::compare)); for (FileObject file: gradleFiles) { addGradleFile(file, toPopulate); diff --git a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/SubProjectsChildFactory.java b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/SubProjectsChildFactory.java index 3e2aacbc..943bdce2 100644 --- a/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/SubProjectsChildFactory.java +++ b/netbeans-gradle-plugin/src/main/java/org/netbeans/gradle/project/view/SubProjectsChildFactory.java @@ -71,12 +71,7 @@ private SubProjectsChildFactory( } private static void sortModules(List modules) { - Collections.sort(modules, new Comparator(){ - @Override - public int compare(NbGradleProjectTree o1, NbGradleProjectTree o2) { - return StringUtils.STR_CMP.compare(o1.getProjectName(), o2.getProjectName()); - } - }); + modules.sort(Comparator.comparing(NbGradleProjectTree::getProjectName, StringUtils.STR_CMP::compare)); } private static boolean hasRelevantDifferences(NbGradleProjectTree tree1, NbGradleProjectTree tree2) { @@ -136,12 +131,7 @@ private void modelChanged() { @Override protected void addNotify() { if (root) { - listenerRefs.add(project.currentModel().addChangeListener(new Runnable() { - @Override - public void run() { - modelChanged(); - } - })); + listenerRefs.add(project.currentModel().addChangeListener(this::modelChanged)); } } @@ -168,16 +158,13 @@ private List getSubProjects() { @Override protected boolean createKeys(List toPopulate) { - for (final NbGradleProjectTree subProject: getSubProjects()) { - toPopulate.add(new SingleNodeFactory() { - @Override - public Node createNode() { - if (subProject.getChildren().isEmpty()) { - return new SubModuleNode(project, subProject); - } - else { - return new SubModuleWithChildren(project, subProject); - } + for (NbGradleProjectTree subProject: getSubProjects()) { + toPopulate.add(() -> { + if (subProject.getChildren().isEmpty()) { + return new SubModuleNode(project, subProject); + } + else { + return new SubModuleWithChildren(project, subProject); } }); } diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/api/entry/FakeSubProjectTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/api/entry/FakeSubProjectTest.java index 8c989426..1c87ce6b 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/api/entry/FakeSubProjectTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/api/entry/FakeSubProjectTest.java @@ -11,11 +11,8 @@ import static org.junit.Assert.*; public final class FakeSubProjectTest { - private static final NbConsumer EXTRA_SETTINGS = new NbConsumer() { - @Override - public void accept(CommonGlobalSettings settings) { - settings.loadRootProjectFirst().setValue(true); - } + private static final NbConsumer EXTRA_SETTINGS = (CommonGlobalSettings settings) -> { + settings.loadRootProjectFirst().setValue(true); }; @ClassRule diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/api/entry/SampleProjectRule.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/api/entry/SampleProjectRule.java index 9db1396e..f1f91781 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/api/entry/SampleProjectRule.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/api/entry/SampleProjectRule.java @@ -51,15 +51,12 @@ public static SampleProjectRule getStandardRule( final NbConsumer additionalConfig, Class... services) { - NbConsumer settingsConfigurer = new NbConsumer() { - @Override - public void accept(CommonGlobalSettings settings) { - settings.gradleLocation().setValue(SampleGradleProject.DEFAULT_GRADLE_TARGET); - settings.gradleJvmArgs().setValue(Arrays.asList("-Xmx256m")); - settings.defaultJdk().setValue(ScriptPlatform.getDefault()); + NbConsumer settingsConfigurer = (CommonGlobalSettings settings) -> { + settings.gradleLocation().setValue(SampleGradleProject.DEFAULT_GRADLE_TARGET); + settings.gradleJvmArgs().setValue(Arrays.asList("-Xmx256m")); + settings.defaultJdk().setValue(ScriptPlatform.getDefault()); - additionalConfig.accept(settings); - } + additionalConfig.accept(settings); }; return new SampleProjectRule(resourceName, @@ -68,13 +65,7 @@ public void accept(CommonGlobalSettings settings) { } public static SampleProjectRule getStandardRule(String resourceName, Class... services) { - NbConsumer additionalConfig = new NbConsumer() { - @Override - public void accept(CommonGlobalSettings settings) { - } - }; - - return getStandardRule(resourceName, additionalConfig, services); + return getStandardRule(resourceName, settings -> { }, services); } private void introduceProject(Project project) { diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/api/entry/SimpleJavaProjectTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/api/entry/SimpleJavaProjectTest.java index f18de05a..7a720347 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/api/entry/SimpleJavaProjectTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/api/entry/SimpleJavaProjectTest.java @@ -1,6 +1,5 @@ package org.netbeans.gradle.project.api.entry; -import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import java.beans.PropertyChangeListener; import java.io.IOException; @@ -140,12 +139,7 @@ private void verifyClasspath(Project prj, FileObject fo, String cpType, String.. for (final String entry: entries) { assertTrue( "classpath " + classpath + " contains entry " + entry, - Iterables.any(cpRoots, new Predicate() { - @Override - public boolean apply(String t) { - return t.endsWith(entry); - } - })); + Iterables.any(cpRoots, t -> t.endsWith(entry))); } } diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/java/properties/JavaDebuggingPanelTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/java/properties/JavaDebuggingPanelTest.java index afb8e0cb..c9a36fbf 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/java/properties/JavaDebuggingPanelTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/java/properties/JavaDebuggingPanelTest.java @@ -5,17 +5,11 @@ import org.netbeans.gradle.project.api.config.ui.ProfileBasedSettingsPage; import org.netbeans.gradle.project.properties.global.CommonGlobalSettings; import org.netbeans.gradle.project.properties.ui.GlobalSettingsPanelTestUtils; -import org.netbeans.gradle.project.util.NbConsumer; import org.netbeans.gradle.project.util.NbSupplier; public class JavaDebuggingPanelTest { private static NbSupplier settingsPageFactory(final boolean allowInherit) { - return new NbSupplier() { - @Override - public ProfileBasedSettingsPage get() { - return JavaDebuggingPanel.createSettingsPage(allowInherit); - } - }; + return () -> JavaDebuggingPanel.createSettingsPage(allowInherit); } private static PropertyReference javaDebugMode(CommonGlobalSettings input) { @@ -23,11 +17,8 @@ private static PropertyReference javaDebugMode(CommonGlobalSettings i } private void testInitAndReadBack(boolean allowInherit, final DebugMode debugMode) throws Exception { - GlobalSettingsPanelTestUtils.testGenericInitAndReadBack(settingsPageFactory(allowInherit), new NbConsumer() { - @Override - public void accept(CommonGlobalSettings input) { - javaDebugMode(input).setValue(debugMode); - } + GlobalSettingsPanelTestUtils.testGenericInitAndReadBack(settingsPageFactory(allowInherit), (input) -> { + javaDebugMode(input).setValue(debugMode); }); } diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/java/query/GradleBinaryForSourceQueryTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/java/query/GradleBinaryForSourceQueryTest.java index 8992cb60..386e2c83 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/java/query/GradleBinaryForSourceQueryTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/java/query/GradleBinaryForSourceQueryTest.java @@ -29,13 +29,8 @@ public class GradleBinaryForSourceQueryTest { public static final SafeTmpFolder TMP_DIR_ROOT = new SafeTmpFolder(); private NbSupplier testModule(File rootDir) throws IOException { - final NbJavaModule module = JavaModelTestUtils.createModule(rootDir); - return new NbSupplier() { - @Override - public NbJavaModule get() { - return module; - } - }; + NbJavaModule module = JavaModelTestUtils.createModule(rootDir); + return () -> module; } private void verifyAllSourceDirsHaveClassesDir(BinaryForSourceQueryImplementation query, NbJavaModule module) throws IOException { diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/java/query/GradleSourceForBinaryQueryTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/java/query/GradleSourceForBinaryQueryTest.java index 0140c295..6b90c7aa 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/java/query/GradleSourceForBinaryQueryTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/java/query/GradleSourceForBinaryQueryTest.java @@ -28,13 +28,8 @@ public GradleSourceForBinaryQueryTest() { } private NbSupplier testModule(File rootDir) throws IOException { - final NbJavaModule module = JavaModelTestUtils.createModule(rootDir); - return new NbSupplier() { - @Override - public NbJavaModule get() { - return module; - } - }; + NbJavaModule module = JavaModelTestUtils.createModule(rootDir); + return () -> module; } private void verifyAllClassesDirHaveSources(SourceForBinaryQueryImplementation2 query, NbJavaModule module) throws IOException { diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/license/DefaultLicenseStoreTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/license/DefaultLicenseStoreTest.java index 34d7ce8b..9a46e13c 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/license/DefaultLicenseStoreTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/license/DefaultLicenseStoreTest.java @@ -21,11 +21,8 @@ public void testAddAndRemove() throws IOException { final DefaultLicenseDef licenseDef = new DefaultLicenseDef(src, "TestLicense1", "TestDisplayName1"); final DefaultLicenseStore store = new DefaultLicenseStore(); - addAndRemove(store, licenseDef, new Runnable() { - @Override - public void run() { - assertTrue(store.containsLicense(licenseDef.getLicenseId())); - } + addAndRemove(store, licenseDef, () -> { + assertTrue(store.containsLicense(licenseDef.getLicenseId())); }); assertFalse(store.containsLicense(licenseDef.getLicenseId())); @@ -51,17 +48,14 @@ public void testGetLicenses() throws IOException { final DefaultLicenseDef licenseDef = new DefaultLicenseDef(src, "TestLicense1", "TestDisplayName1"); final DefaultLicenseStore store = new DefaultLicenseStore(); - addAndRemove(store, licenseDef, new Runnable() { - @Override - public void run() { - Collection licenses = store.getAllLicense(); - LicenseRef found = findById(licenses, licenseDef.getLicenseId()); - assertNotNull("License", found); + addAndRemove(store, licenseDef, () -> { + Collection licenses = store.getAllLicense(); + LicenseRef found = findById(licenses, licenseDef.getLicenseId()); + assertNotNull("License", found); - assertEquals("Dynamic", true, found.isDynamic()); - assertEquals("DisplayName", licenseDef.getDisplayName(), found.getDisplayName()); - assertEquals("Id", licenseDef.getLicenseId(), found.getId()); - } + assertEquals("Dynamic", true, found.isDynamic()); + assertEquals("DisplayName", licenseDef.getDisplayName(), found.getDisplayName()); + assertEquals("Id", licenseDef.getLicenseId(), found.getId()); }); assertFalse(store.containsLicense(licenseDef.getLicenseId())); diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/license/LicenseManagerTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/license/LicenseManagerTest.java index 5d80dd8d..c04dd4fc 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/license/LicenseManagerTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/license/LicenseManagerTest.java @@ -13,7 +13,6 @@ import org.jtrim.property.PropertySource; import org.junit.Test; import org.netbeans.gradle.project.util.CloseableAction; -import org.netbeans.gradle.project.util.NbFunction; import static org.junit.Assert.*; import static org.mockito.Mockito.*; @@ -31,23 +30,8 @@ private static LicenseHeaderInfo testLicenseInfo(String name, String fileName) { } private static LicenseManager createTestManager(LicenseStore licenseStore) { - NbFunction licenseRootProvider = new NbFunction() { - @Override - public Path apply(String ownerModel) { - return Paths.get(ownerModel); - } - }; - - NbFunction modelNameProvider = new NbFunction() { - @Override - public String apply(String ownerModel) { - return toModelName(ownerModel); - } - }; - TaskExecutor executor = SyncTaskExecutor.getSimpleExecutor(); - - return LicenseManagers.createLicenseManager(executor, licenseStore, licenseRootProvider, modelNameProvider); + return LicenseManagers.createLicenseManager(executor, licenseStore, Paths::get, LicenseManagerTest::toModelName); } @Test diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/model/LazyProjectModelPersisterFactoryTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/model/LazyProjectModelPersisterFactoryTest.java index 41e4b27d..b52c698b 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/model/LazyProjectModelPersisterFactoryTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/model/LazyProjectModelPersisterFactoryTest.java @@ -8,7 +8,6 @@ import org.jtrim.concurrent.TaskExecutors; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.netbeans.gradle.project.util.NbConsumer; import static org.junit.Assert.*; @@ -55,12 +54,9 @@ public void testPersistingOnExecutor() throws Exception { @SuppressWarnings("unchecked") PersistentModelStore modelStore = (PersistentModelStore)mock(PersistentModelStore.class); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - modelStorePersistModel.accept(contextAwareExecutor.isExecutingInThis()); - return null; - } + doAnswer((InvocationOnMock invocation) -> { + modelStorePersistModel.accept(contextAwareExecutor.isExecutingInThis()); + return null; }).when(modelStore).persistModel(any(), any(Path.class)); PersistentModelStore persister = createLazyStore(modelStore, contextAwareExecutor); diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/model/MultiFileModelCacheTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/model/MultiFileModelCacheTest.java index b5a7d3e7..99930624 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/model/MultiFileModelCacheTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/model/MultiFileModelCacheTest.java @@ -5,18 +5,12 @@ import java.util.Arrays; import java.util.Collections; import org.junit.Test; -import org.netbeans.gradle.project.util.NbFunction; import static org.junit.Assert.*; public class MultiFileModelCacheTest { private static MultiFileModelCache getTestCache(PersistentModelStore persister) { - return new MultiFileModelCache<>(persister, new NbFunction() { - @Override - public PersistentModelKey apply(TestModel model) { - return model.getKey(); - } - }); + return new MultiFileModelCache<>(persister, TestModel::getKey); } private static PersistentModelKey getKey(String rootName, String subName) { diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/others/PluginClassImplementationTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/others/PluginClassImplementationTest.java index 18a298f6..e6a84996 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/others/PluginClassImplementationTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/others/PluginClassImplementationTest.java @@ -39,11 +39,8 @@ public void testDelegateToInterfaceWithException() throws Throwable { Runnable2 wrapped = mock(Runnable2.class); final InvocationHandler run2Handler = mock(InvocationHandler.class); - InvocationHandlerFactory exceptionalCase = new InvocationHandlerFactory() { - @Override - public InvocationHandler tryGetInvocationHandler(Object proxy, Method method, Object[] args) { - return "run2".equals(method.getName()) ? run2Handler : null; - } + InvocationHandlerFactory exceptionalCase = (Object proxy, Method method, Object[] args) -> { + return "run2".equals(method.getName()) ? run2Handler : null; }; PluginClassImplementation impl = new PluginClassImplementation( diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/output/IOTabMaintainerTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/output/IOTabMaintainerTest.java index 5941a772..73452c6e 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/output/IOTabMaintainerTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/output/IOTabMaintainerTest.java @@ -7,12 +7,7 @@ public class IOTabMaintainerTest { private static IOTabMaintainer create() { - return new IOTabMaintainer<>(new IOTabFactory() { - @Override - public Tab create(String caption) { - return new Tab(caption); - } - }); + return new IOTabMaintainer<>(Tab::new); } @Test diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/NbPropertiesTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/NbPropertiesTest.java index f7d8a1c9..5cb259ba 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/NbPropertiesTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/NbPropertiesTest.java @@ -24,19 +24,14 @@ private static void runGC() { private static void addWeakListener( PropertySource property, - final AtomicInteger listenerCallCount, + AtomicInteger listenerCallCount, AtomicReference resultRef) { // We do this in a separate method to decrease the chance that // some hidden local variable will keep a hard reference to the listener // or the ListenerRef. PropertySource weakProperty = NbProperties.weakListenerProperty(property); - resultRef.set(weakProperty.addChangeListener(new Runnable() { - @Override - public void run() { - listenerCallCount.incrementAndGet(); - } - })); + resultRef.set(weakProperty.addChangeListener(listenerCallCount::incrementAndGet)); } @Test diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/PredefinedTaskTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/PredefinedTaskTest.java index 39428d08..7c67fb23 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/PredefinedTaskTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/PredefinedTaskTest.java @@ -256,15 +256,12 @@ public void testIsTasksExistsIfRequired_MustExist_WithVar() { } private static TaskVariableMap singletonVarMap(final String name, final String value) { - return new TaskVariableMap() { - @Override - public String tryGetValueForVariable(TaskVariable variable) { - if (variable.getVariableName().equals(name)) { - return value; - } - else { - return null; - } + return (TaskVariable variable) -> { + if (variable.getVariableName().equals(name)) { + return value; + } + else { + return null; } }; } diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/PropertyOfPropertyTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/PropertyOfPropertyTest.java index ff46323b..cbcbe87c 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/PropertyOfPropertyTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/PropertyOfPropertyTest.java @@ -5,7 +5,6 @@ import org.jtrim.property.PropertyFactory; import org.jtrim.property.PropertySource; import org.junit.Test; -import org.netbeans.gradle.project.util.NbFunction; import static org.junit.Assert.*; import static org.mockito.Mockito.*; @@ -112,12 +111,7 @@ private static final class TestProperty { public TestProperty() { this.property = PropertyFactory.memProperty(PropertyFactory.memProperty(0)); - this.wrapper = new PropertyOfProperty<>(property, new NbFunction, PropertySource>() { - @Override - public PropertySource apply(MutableProperty arg) { - return arg; - } - }); + this.wrapper = new PropertyOfProperty<>(property, arg -> arg); } public MutableProperty setSubProperty(int value) { diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/AppearancePanelTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/AppearancePanelTest.java index 755c59f1..1b979790 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/AppearancePanelTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/AppearancePanelTest.java @@ -10,7 +10,6 @@ import org.netbeans.gradle.project.properties.global.CommonGlobalSettings; import org.netbeans.gradle.project.properties.global.GlobalSettingsPage; import org.netbeans.gradle.project.properties.global.JavaSourcesDisplayMode; -import org.netbeans.gradle.project.util.NbConsumer; import org.netbeans.gradle.project.util.NbSupplier; public class AppearancePanelTest { @@ -19,12 +18,7 @@ private static PropertyReference displayNamePattern(CommonGlobalSettings } private static NbSupplier settingsPageFactory() { - return new NbSupplier() { - @Override - public GlobalSettingsPage get() { - return AppearancePanel.createSettingsPage(false); - } - }; + return () -> AppearancePanel.createSettingsPage(false); } private static PropertyReference javaSourcesDisplayMode(CommonGlobalSettings input) { @@ -37,34 +31,25 @@ private static PropertyReference javaSourcesDisplayMode( @Test public void testInitAndReadBack1() throws Exception { - GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), new NbConsumer() { - @Override - public void accept(CommonGlobalSettings input) { - displayNamePattern(input).setValue("${project.name}"); - javaSourcesDisplayMode(input).setValue(JavaSourcesDisplayMode.GROUP_BY_SOURCESET); - } + GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), (input) -> { + displayNamePattern(input).setValue("${project.name}"); + javaSourcesDisplayMode(input).setValue(JavaSourcesDisplayMode.GROUP_BY_SOURCESET); }); } @Test public void testInitAndReadBack2() throws Exception { - GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), new NbConsumer() { - @Override - public void accept(CommonGlobalSettings input) { - displayNamePattern(input).setValue("${project.path}-${project.version}-test"); - javaSourcesDisplayMode(input).setValue(JavaSourcesDisplayMode.GROUP_BY_SOURCESET); - } + GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), (input) -> { + displayNamePattern(input).setValue("${project.path}-${project.version}-test"); + javaSourcesDisplayMode(input).setValue(JavaSourcesDisplayMode.GROUP_BY_SOURCESET); }); } @Test public void testInitAndReadBack3() throws Exception { - GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), new NbConsumer() { - @Override - public void accept(CommonGlobalSettings input) { - displayNamePattern(input).setValue("${project.path}"); - javaSourcesDisplayMode(input).setValue(JavaSourcesDisplayMode.DEFAULT_MODE); - } + GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), (input) -> { + displayNamePattern(input).setValue("${project.path}"); + javaSourcesDisplayMode(input).setValue(JavaSourcesDisplayMode.DEFAULT_MODE); }); } } diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/BuildScriptParsingPanelTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/BuildScriptParsingPanelTest.java index b2062f57..130c96df 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/BuildScriptParsingPanelTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/BuildScriptParsingPanelTest.java @@ -4,40 +4,28 @@ import org.netbeans.gradle.project.properties.ModelLoadingStrategy; import org.netbeans.gradle.project.properties.global.CommonGlobalSettings; import org.netbeans.gradle.project.properties.global.GlobalSettingsPage; -import org.netbeans.gradle.project.util.NbConsumer; import org.netbeans.gradle.project.util.NbSupplier; public class BuildScriptParsingPanelTest { private static NbSupplier settingsPageFactory() { - return new NbSupplier() { - @Override - public GlobalSettingsPage get() { - return BuildScriptParsingPanel.createSettingsPage(); - } - }; + return BuildScriptParsingPanel::createSettingsPage; } @Test public void testInitAndReadBack1() throws Exception { - GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), new NbConsumer() { - @Override - public void accept(CommonGlobalSettings input) { - input.modelLoadingStrategy().setValue(ModelLoadingStrategy.USE_IDEA_MODEL); - input.loadRootProjectFirst().setValue(false); - input.mayRelyOnJavaOfScript().setValue(true); - } + GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), (CommonGlobalSettings input) -> { + input.modelLoadingStrategy().setValue(ModelLoadingStrategy.USE_IDEA_MODEL); + input.loadRootProjectFirst().setValue(false); + input.mayRelyOnJavaOfScript().setValue(true); }); } @Test public void testInitAndReadBack2() throws Exception { - GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), new NbConsumer() { - @Override - public void accept(CommonGlobalSettings input) { - input.modelLoadingStrategy().setValue(ModelLoadingStrategy.NEWEST_POSSIBLE); - input.loadRootProjectFirst().setValue(true); - input.mayRelyOnJavaOfScript().setValue(false); - } + GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), (CommonGlobalSettings input) -> { + input.modelLoadingStrategy().setValue(ModelLoadingStrategy.NEWEST_POSSIBLE); + input.loadRootProjectFirst().setValue(true); + input.mayRelyOnJavaOfScript().setValue(false); }); } } diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/CustomVariablesPanelTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/CustomVariablesPanelTest.java index e59d35ef..dca4bbec 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/CustomVariablesPanelTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/CustomVariablesPanelTest.java @@ -10,40 +10,28 @@ import org.netbeans.gradle.project.properties.standard.CustomVariable; import org.netbeans.gradle.project.properties.standard.CustomVariables; import org.netbeans.gradle.project.properties.standard.MemCustomVariables; -import org.netbeans.gradle.project.util.NbConsumer; import org.netbeans.gradle.project.util.NbSupplier; public class CustomVariablesPanelTest { private static NbSupplier settingsPageFactory() { - return new NbSupplier() { - @Override - public ProfileBasedSettingsPage get() { - return CustomVariablesPanel.createSettingsPage(); - } - }; + return CustomVariablesPanel::createSettingsPage; } @Test public void testInitAndReadBack1() throws Exception { - GlobalSettingsPanelTestUtils.testGenericInitAndReadBack(settingsPageFactory(), new NbConsumer() { - @Override - public void accept(CommonGlobalSettings input) { - PropertyReference customVariables = NbGradleCommonProperties.customVariables(input.getActiveSettingsQuery()); - customVariables.setValue(new MemCustomVariables(Arrays.asList( - new CustomVariable("var1", "value1"), - new CustomVariable("var2", "value2")))); - } + GlobalSettingsPanelTestUtils.testGenericInitAndReadBack(settingsPageFactory(), (CommonGlobalSettings input) -> { + PropertyReference customVariables = NbGradleCommonProperties.customVariables(input.getActiveSettingsQuery()); + customVariables.setValue(new MemCustomVariables(Arrays.asList( + new CustomVariable("var1", "value1"), + new CustomVariable("var2", "value2")))); }); } @Test public void testInitAndReadBack2() throws Exception { - GlobalSettingsPanelTestUtils.testGenericInitAndReadBack(settingsPageFactory(), new NbConsumer() { - @Override - public void accept(CommonGlobalSettings input) { - PropertyReference customVariables = NbGradleCommonProperties.customVariables(input.getActiveSettingsQuery()); - customVariables.setValue(new MemCustomVariables(Collections.emptyList())); - } + GlobalSettingsPanelTestUtils.testGenericInitAndReadBack(settingsPageFactory(), (CommonGlobalSettings input) -> { + PropertyReference customVariables = NbGradleCommonProperties.customVariables(input.getActiveSettingsQuery()); + customVariables.setValue(new MemCustomVariables(Collections.emptyList())); }); } } diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/GlobalSettingsPanelTestUtils.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/GlobalSettingsPanelTestUtils.java index 9e174f37..9af98939 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/GlobalSettingsPanelTestUtils.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/GlobalSettingsPanelTestUtils.java @@ -32,32 +32,29 @@ private static void testInitAndReadBackNow( throw new IllegalStateException("Expected EDT"); } - CommonGlobalSettings.withCleanMemorySettings(new NbConsumer() { - @Override - public void accept(GenericProfileSettings preference) { - GenericProfileSettings input = GenericProfileSettings.createTestMemorySettings(); - CommonGlobalSettings inputSettings = toGlobalSettings(input); + CommonGlobalSettings.withCleanMemorySettings((GenericProfileSettings preference) -> { + GenericProfileSettings input = GenericProfileSettings.createTestMemorySettings(); + CommonGlobalSettings inputSettings = toGlobalSettings(input); - T page = pageFactory.get(); + T page = pageFactory.get(); - initializer.accept(inputSettings); - ConfigTree inputValues = input.getContentSnapshot(); + initializer.accept(inputSettings); + ConfigTree inputValues = input.getContentSnapshot(); - ProfileEditor editor = page.getEditorFactory().startEditingProfile( - new ProfileInfo(ProfileKey.GLOBAL_PROFILE, NbStrings.getGlobalProfileName()), - inputSettings.getActiveSettingsQuery()); + ProfileEditor editor = page.getEditorFactory().startEditingProfile( + new ProfileInfo(ProfileKey.GLOBAL_PROFILE, NbStrings.getGlobalProfileName()), + inputSettings.getActiveSettingsQuery()); - editor.readFromSettings().displaySettings(); + editor.readFromSettings().displaySettings(); - check.accept(page); + check.accept(page); - input.clearSettings(); - editor.readFromGui().saveSettings(); + input.clearSettings(); + editor.readFromGui().saveSettings(); - ConfigTree outputValues = input.getContentSnapshot(); + ConfigTree outputValues = input.getContentSnapshot(); - Assert.assertEquals(inputValues, outputValues); - } + Assert.assertEquals(inputValues, outputValues); }); } @@ -82,32 +79,22 @@ public static void testInitAndReadBack( final NbSupplier panelFactory, final NbConsumer initializer, final NbConsumer check) throws Exception { - invokeAndWait(new Runnable() { - @Override - public void run() { - testInitAndReadBackNow(panelFactory, initializer, check); - } + invokeAndWait(() -> { + testInitAndReadBackNow(panelFactory, initializer, check); }); } public static void testGenericInitAndReadBack( final NbSupplier pageFactory, final NbConsumer initializer) throws Exception { - testInitAndReadBack(pageFactory, initializer, new NbConsumer() { - @Override - public void accept(ProfileBasedSettingsPage page) { - } - }); + testInitAndReadBack(pageFactory, initializer, page -> { }); } public static void testGlobalInitAndReadBack( final NbSupplier pageFactory, final NbConsumer initializer) throws Exception { - testInitAndReadBack(pageFactory, initializer, new NbConsumer() { - @Override - public void accept(GlobalSettingsPage page) { - Assert.assertTrue("Initial form must be valid.", page.valid().getValue()); - } + testInitAndReadBack(pageFactory, initializer, (GlobalSettingsPage page) -> { + Assert.assertTrue("Initial form must be valid.", page.valid().getValue()); }); } diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/GradleDaemonPanelTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/GradleDaemonPanelTest.java index 0c2193ea..e0e28352 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/GradleDaemonPanelTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/GradleDaemonPanelTest.java @@ -2,29 +2,18 @@ import java.util.concurrent.TimeUnit; import org.junit.Test; -import org.netbeans.gradle.project.properties.global.CommonGlobalSettings; import org.netbeans.gradle.project.properties.global.GlobalSettingsPage; -import org.netbeans.gradle.project.util.NbConsumer; import org.netbeans.gradle.project.util.NbSupplier; - public class GradleDaemonPanelTest { private static NbSupplier settingsPageFactory() { - return new NbSupplier() { - @Override - public GlobalSettingsPage get() { - return GradleDaemonPanel.createSettingsPage(); - } - }; + return GradleDaemonPanel::createSettingsPage; } @Test public void testInitAndReadBack() throws Exception { - GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), new NbConsumer() { - @Override - public void accept(CommonGlobalSettings input) { - input.gradleDaemonTimeoutSec().setValue((int)TimeUnit.MINUTES.toSeconds(37)); - } + GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), (input) -> { + input.gradleDaemonTimeoutSec().setValue((int)TimeUnit.MINUTES.toSeconds(37)); }); } } diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/GradleInstallationPanelTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/GradleInstallationPanelTest.java index a5eb72ee..74d64240 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/GradleInstallationPanelTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/GradleInstallationPanelTest.java @@ -4,62 +4,43 @@ import org.junit.Test; import org.netbeans.gradle.project.properties.GradleLocationDef; import org.netbeans.gradle.project.properties.GradleLocationDefault; -import org.netbeans.gradle.project.properties.global.CommonGlobalSettings; import org.netbeans.gradle.project.properties.global.GlobalSettingsPage; -import org.netbeans.gradle.project.util.NbConsumer; import org.netbeans.gradle.project.util.NbSupplier; public class GradleInstallationPanelTest { private static NbSupplier settingsPageFactory() { - return new NbSupplier() { - @Override - public GlobalSettingsPage get() { - return GradleInstallationPanel.createSettingsPage(); - } - }; + return GradleInstallationPanel::createSettingsPage; } @Test public void testInitAndReadBack1() throws Exception { - GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), new NbConsumer() { - @Override - public void accept(CommonGlobalSettings input) { - input.gradleLocation().setValue(GradleLocationDef.fromVersion("1.7", true)); - input.gradleUserHomeDir().setValue(new File("my-user-home1")); - } + GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), (input) -> { + input.gradleLocation().setValue(GradleLocationDef.fromVersion("1.7", true)); + input.gradleUserHomeDir().setValue(new File("my-user-home1")); }); } @Test public void testInitAndReadBack2() throws Exception { - GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), new NbConsumer() { - @Override - public void accept(CommonGlobalSettings input) { - input.gradleLocation().setValue(GradleLocationDef.fromVersion("1.9", false)); - input.gradleUserHomeDir().setValue(new File("my-user-home2")); - } + GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), (input) -> { + input.gradleLocation().setValue(GradleLocationDef.fromVersion("1.9", false)); + input.gradleUserHomeDir().setValue(new File("my-user-home2")); }); } @Test public void testInitAndReadBack3() throws Exception { - GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), new NbConsumer() { - @Override - public void accept(CommonGlobalSettings input) { - input.gradleLocation().setValue(new GradleLocationDef(GradleLocationDefault.DEFAULT_REF, false)); - input.gradleUserHomeDir().setValue(new File("my-user-home3")); - } + GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), (input) -> { + input.gradleLocation().setValue(new GradleLocationDef(GradleLocationDefault.DEFAULT_REF, false)); + input.gradleUserHomeDir().setValue(new File("my-user-home3")); }); } @Test public void testInitAndReadBack4() throws Exception { - GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), new NbConsumer() { - @Override - public void accept(CommonGlobalSettings input) { - input.gradleLocation().setValue(new GradleLocationDef(GradleLocationDefault.DEFAULT_REF, true)); - input.gradleUserHomeDir().setValue(new File("my-user-home4")); - } + GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), (input) -> { + input.gradleLocation().setValue(new GradleLocationDef(GradleLocationDefault.DEFAULT_REF, true)); + input.gradleUserHomeDir().setValue(new File("my-user-home4")); }); } } diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/LicenseHeaderPanelTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/LicenseHeaderPanelTest.java index aa5f6e33..c329bcd6 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/LicenseHeaderPanelTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/LicenseHeaderPanelTest.java @@ -1,6 +1,5 @@ package org.netbeans.gradle.project.properties.ui; -import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; @@ -14,35 +13,19 @@ import org.netbeans.gradle.project.license.LicenseSource; import org.netbeans.gradle.project.properties.NbGradleCommonProperties; import org.netbeans.gradle.project.properties.global.CommonGlobalSettings; -import org.netbeans.gradle.project.util.NbConsumer; import org.netbeans.gradle.project.util.NbSupplier; public class LicenseHeaderPanelTest { - private static final NbSupplier NULL_PATH = new NbSupplier() { - @Override - public Path get() { - return null; - } - }; + private static final NbSupplier NULL_PATH = () -> null; private static final LicenseSource EMPTY_LICENSE_SOURCE = licenseSource(Collections.emptyList()); private static LicenseSource licenseSource(final Collection licenses) { - return new LicenseSource() { - @Override - public Collection getAllLicense() throws IOException { - return licenses; - } - }; + return () -> licenses; } private static NbSupplier settingsPageFactory(final LicenseSource licenseSource) { - return new NbSupplier() { - @Override - public ProfileBasedSettingsPage get() { - return LicenseHeaderPanel.createSettingsPage(NULL_PATH, licenseSource); - } - }; + return () -> LicenseHeaderPanel.createSettingsPage(NULL_PATH, licenseSource); } private static NbSupplier settingsPageFactory() { @@ -54,11 +37,8 @@ private static PropertyReference licenseHeaderInfo(CommonGlob } private void testInitAndReadBack(final LicenseHeaderInfo headerInfo) throws Exception { - GlobalSettingsPanelTestUtils.testGenericInitAndReadBack(settingsPageFactory(), new NbConsumer() { - @Override - public void accept(CommonGlobalSettings input) { - licenseHeaderInfo(input).setValue(headerInfo); - } + GlobalSettingsPanelTestUtils.testGenericInitAndReadBack(settingsPageFactory(), (input) -> { + licenseHeaderInfo(input).setValue(headerInfo); }); } @@ -89,15 +69,12 @@ private void testInitAndReadBackWithKnownLicense(boolean dynamic) throws Excepti new LicenseRef("MyBuiltInLicense", "DisplayNameOfLicense", dynamic), new LicenseRef("ZZZZ", "DisplayNameOfZZZZ", false) )); - GlobalSettingsPanelTestUtils.testGenericInitAndReadBack(settingsPageFactory(), new NbConsumer() { - @Override - public void accept(CommonGlobalSettings input) { - LicenseHeaderInfo headerInfo = new LicenseHeaderInfo( - "MyBuiltInLicense", - Collections.singletonMap("organization", "MyTestOrg"), - null); - licenseHeaderInfo(input).setValue(headerInfo); - } + GlobalSettingsPanelTestUtils.testGenericInitAndReadBack(settingsPageFactory(), (input) -> { + LicenseHeaderInfo headerInfo = new LicenseHeaderInfo( + "MyBuiltInLicense", + Collections.singletonMap("organization", "MyTestOrg"), + null); + licenseHeaderInfo(input).setValue(headerInfo); }); } diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/ManageTasksPanelTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/ManageTasksPanelTest.java index f65ad212..4028467e 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/ManageTasksPanelTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/ManageTasksPanelTest.java @@ -9,17 +9,11 @@ import org.netbeans.gradle.project.properties.PredefinedTask; import org.netbeans.gradle.project.properties.global.CommonGlobalSettings; import org.netbeans.gradle.project.properties.standard.PredefinedTasks; -import org.netbeans.gradle.project.util.NbConsumer; import org.netbeans.gradle.project.util.NbSupplier; public class ManageTasksPanelTest { private static NbSupplier settingsPageFactory() { - return new NbSupplier() { - @Override - public ProfileBasedSettingsPage get() { - return ManageTasksPanel.createSettingsPage(); - } - }; + return ManageTasksPanel::createSettingsPage; } private static PropertyReference customTasks(CommonGlobalSettings input) { @@ -27,11 +21,8 @@ private static PropertyReference customTasks(CommonGlobalSettin } private void testInitAndReadBack(final PredefinedTasks tasks) throws Exception { - GlobalSettingsPanelTestUtils.testGenericInitAndReadBack(settingsPageFactory(), new NbConsumer() { - @Override - public void accept(CommonGlobalSettings input) { - customTasks(input).setValue(tasks); - } + GlobalSettingsPanelTestUtils.testGenericInitAndReadBack(settingsPageFactory(), (input) -> { + customTasks(input).setValue(tasks); }); } diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/OtherOptionsPanelTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/OtherOptionsPanelTest.java index 6488194e..29c5e48c 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/OtherOptionsPanelTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/OtherOptionsPanelTest.java @@ -1,42 +1,29 @@ package org.netbeans.gradle.project.properties.ui; import org.junit.Test; -import org.netbeans.gradle.project.properties.global.CommonGlobalSettings; import org.netbeans.gradle.project.properties.global.GlobalSettingsPage; -import org.netbeans.gradle.project.util.NbConsumer; import org.netbeans.gradle.project.util.NbSupplier; public class OtherOptionsPanelTest { private static NbSupplier settingsPageFactory() { - return new NbSupplier() { - @Override - public GlobalSettingsPage get() { - return OtherOptionsPanel.createSettingsPage(); - } - }; + return OtherOptionsPanel::createSettingsPage; } @Test public void testInitAndReadBack1() throws Exception { - GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), new NbConsumer() { - @Override - public void accept(CommonGlobalSettings input) { - input.detectProjectDependenciesByJarName().setValue(true); - input.compileOnSave().setValue(false); - input.projectCacheSize().setValue(251); - } + GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), (input) -> { + input.detectProjectDependenciesByJarName().setValue(true); + input.compileOnSave().setValue(false); + input.projectCacheSize().setValue(251); }); } @Test public void testInitAndReadBack2() throws Exception { - GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), new NbConsumer() { - @Override - public void accept(CommonGlobalSettings input) { - input.detectProjectDependenciesByJarName().setValue(false); - input.compileOnSave().setValue(true); - input.projectCacheSize().setValue(251); - } + GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), (input) -> { + input.detectProjectDependenciesByJarName().setValue(false); + input.compileOnSave().setValue(true); + input.projectCacheSize().setValue(251); }); } } diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/PlatformPriorityPanelTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/PlatformPriorityPanelTest.java index b4b2888a..1eabe6ec 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/PlatformPriorityPanelTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/PlatformPriorityPanelTest.java @@ -3,41 +3,28 @@ import java.util.Arrays; import org.junit.Test; import org.netbeans.api.java.platform.JavaPlatform; -import org.netbeans.gradle.project.properties.global.CommonGlobalSettings; import org.netbeans.gradle.project.properties.global.GlobalSettingsPage; import org.netbeans.gradle.project.properties.global.PlatformOrder; -import org.netbeans.gradle.project.util.NbConsumer; import org.netbeans.gradle.project.util.NbSupplier; public class PlatformPriorityPanelTest { private static NbSupplier settingsPageFactory(final boolean hasOwnButtons) { - return new NbSupplier() { - @Override - public GlobalSettingsPage get() { - return PlatformPriorityPanel.createSettingsPage(hasOwnButtons); - } - }; + return () -> PlatformPriorityPanel.createSettingsPage(hasOwnButtons); } @Test public void testInitAndReadBack1() throws Exception { - GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(false), new NbConsumer() { - @Override - public void accept(CommonGlobalSettings input) { - input.platformPreferenceOrder().setValue(new PlatformOrder(Arrays.asList( - JavaPlatform.getDefault()))); - } + GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(false), (input) -> { + input.platformPreferenceOrder().setValue(new PlatformOrder(Arrays.asList( + JavaPlatform.getDefault()))); }); } @Test public void testInitAndReadBack2() throws Exception { - GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(true), new NbConsumer() { - @Override - public void accept(CommonGlobalSettings input) { - input.platformPreferenceOrder().setValue(new PlatformOrder(Arrays.asList( - JavaPlatform.getDefault()))); - } + GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(true), (input) -> { + input.platformPreferenceOrder().setValue(new PlatformOrder(Arrays.asList( + JavaPlatform.getDefault()))); }); } } diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/ScriptAndTasksPanelTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/ScriptAndTasksPanelTest.java index 5b464610..3d67e71c 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/ScriptAndTasksPanelTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/ScriptAndTasksPanelTest.java @@ -4,42 +4,29 @@ import java.util.Collections; import org.junit.Test; import org.netbeans.gradle.project.properties.ScriptPlatform; -import org.netbeans.gradle.project.properties.global.CommonGlobalSettings; import org.netbeans.gradle.project.properties.global.GlobalSettingsPage; -import org.netbeans.gradle.project.util.NbConsumer; import org.netbeans.gradle.project.util.NbSupplier; public class ScriptAndTasksPanelTest { private static NbSupplier settingsPageFactory() { - return new NbSupplier() { - @Override - public GlobalSettingsPage get() { - return ScriptAndTasksPanel.createSettingsPage(); - } - }; + return ScriptAndTasksPanel::createSettingsPage; } @Test public void testInitAndReadBack1() throws Exception { - GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), new NbConsumer() { - @Override - public void accept(CommonGlobalSettings input) { - input.defaultJdk().setValue(ScriptPlatform.getDefault()); - input.gradleArgs().setValue(Arrays.asList("arg1", "arg2")); - input.gradleJvmArgs().setValue(Arrays.asList("j-arg1", "j-arg2")); - } + GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), (input) -> { + input.defaultJdk().setValue(ScriptPlatform.getDefault()); + input.gradleArgs().setValue(Arrays.asList("arg1", "arg2")); + input.gradleJvmArgs().setValue(Arrays.asList("j-arg1", "j-arg2")); }); } @Test public void testInitAndReadBack2() throws Exception { - GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), new NbConsumer() { - @Override - public void accept(CommonGlobalSettings input) { - input.defaultJdk().setValue(ScriptPlatform.getDefault()); - input.gradleArgs().setValue(Collections.emptyList()); - input.gradleJvmArgs().setValue(Collections.emptyList()); - } + GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), (input) -> { + input.defaultJdk().setValue(ScriptPlatform.getDefault()); + input.gradleArgs().setValue(Collections.emptyList()); + input.gradleJvmArgs().setValue(Collections.emptyList()); }); } } diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/TaskExecutionPanelTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/TaskExecutionPanelTest.java index 72a7cb99..fe83079c 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/TaskExecutionPanelTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/properties/ui/TaskExecutionPanelTest.java @@ -1,61 +1,45 @@ package org.netbeans.gradle.project.properties.ui; import org.junit.Test; -import org.netbeans.gradle.project.properties.global.CommonGlobalSettings; import org.netbeans.gradle.project.properties.global.GlobalSettingsPage; import org.netbeans.gradle.project.properties.global.SelfMaintainedTasks; -import org.netbeans.gradle.project.util.NbConsumer; import org.netbeans.gradle.project.util.NbSupplier; public class TaskExecutionPanelTest { private static NbSupplier settingsPageFactory() { - return new NbSupplier() { - @Override - public GlobalSettingsPage get() { - return TaskExecutionPanel.createSettingsPage(); - } - }; + return TaskExecutionPanel::createSettingsPage; } @Test public void testInitAndReadBack1() throws Exception { - GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), new NbConsumer() { - @Override - public void accept(CommonGlobalSettings input) { - input.selfMaintainedTasks().setValue(SelfMaintainedTasks.TRUE); - input.alwaysClearOutput().setValue(true); - input.skipTests().setValue(true); - input.skipCheck().setValue(false); - input.replaceLfOnStdIn().setValue(false); - } + GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), (input) -> { + input.selfMaintainedTasks().setValue(SelfMaintainedTasks.TRUE); + input.alwaysClearOutput().setValue(true); + input.skipTests().setValue(true); + input.skipCheck().setValue(false); + input.replaceLfOnStdIn().setValue(false); }); } @Test public void testInitAndReadBack2() throws Exception { - GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), new NbConsumer() { - @Override - public void accept(CommonGlobalSettings input) { - input.selfMaintainedTasks().setValue(SelfMaintainedTasks.FALSE); - input.alwaysClearOutput().setValue(false); - input.skipTests().setValue(false); - input.skipCheck().setValue(true); - input.replaceLfOnStdIn().setValue(true); - } + GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), (input) -> { + input.selfMaintainedTasks().setValue(SelfMaintainedTasks.FALSE); + input.alwaysClearOutput().setValue(false); + input.skipTests().setValue(false); + input.skipCheck().setValue(true); + input.replaceLfOnStdIn().setValue(true); }); } @Test public void testInitAndReadBack3() throws Exception { - GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), new NbConsumer() { - @Override - public void accept(CommonGlobalSettings input) { - input.selfMaintainedTasks().setValue(SelfMaintainedTasks.MANUAL); - input.alwaysClearOutput().setValue(true); - input.skipTests().setValue(false); - input.skipCheck().setValue(true); - input.replaceLfOnStdIn().setValue(false); - } + GlobalSettingsPanelTestUtils.testGlobalInitAndReadBack(settingsPageFactory(), (input) -> { + input.selfMaintainedTasks().setValue(SelfMaintainedTasks.MANUAL); + input.alwaysClearOutput().setValue(true); + input.skipTests().setValue(false); + input.skipCheck().setValue(true); + input.replaceLfOnStdIn().setValue(false); }); } } diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/query/GradleCacheSourceForBinaryQueryTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/query/GradleCacheSourceForBinaryQueryTest.java index a2baa4f9..2921e604 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/query/GradleCacheSourceForBinaryQueryTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/query/GradleCacheSourceForBinaryQueryTest.java @@ -7,7 +7,6 @@ import org.junit.Test; import org.netbeans.api.java.queries.SourceForBinaryQuery; import org.netbeans.gradle.model.util.BasicFileUtils; -import org.netbeans.gradle.project.util.NbSupplier; import org.netbeans.gradle.project.util.SafeTmpFolder; import org.netbeans.gradle.project.util.TestBinaryUtils; import org.netbeans.spi.java.queries.SourceForBinaryQueryImplementation2; @@ -21,12 +20,7 @@ public class GradleCacheSourceForBinaryQueryTest { public static final SafeTmpFolder TMP_DIR_ROOT = new SafeTmpFolder(); private static SourceForBinaryQueryImplementation2 createWithRoot(final File gradleHomeRoot) { - return new GradleCacheSourceForBinaryQuery(new NbSupplier() { - @Override - public File get() { - return gradleHomeRoot; - } - }); + return new GradleCacheSourceForBinaryQuery(() -> gradleHomeRoot); } private void verifySource(File gradleHome, URL binaryUrl, File srcFile) { diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/query/GradleHomeSourceForBinaryQueryTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/query/GradleHomeSourceForBinaryQueryTest.java index 5b850a09..55c5f5db 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/query/GradleHomeSourceForBinaryQueryTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/query/GradleHomeSourceForBinaryQueryTest.java @@ -7,7 +7,6 @@ import org.junit.Test; import org.netbeans.api.java.queries.SourceForBinaryQuery; import org.netbeans.gradle.model.util.BasicFileUtils; -import org.netbeans.gradle.project.util.NbSupplier; import org.netbeans.gradle.project.util.SafeTmpFolder; import org.netbeans.gradle.project.util.TestBinaryUtils; import org.netbeans.spi.java.queries.SourceForBinaryQueryImplementation2; @@ -24,12 +23,7 @@ public class GradleHomeSourceForBinaryQueryTest { private GradleHomeSourceForBinaryQuery createWithRoot(File rootDir) { final FileObject rootObj = rootDir != null ? FileUtil.toFileObject(rootDir) : null; - return new GradleHomeSourceForBinaryQuery(new NbSupplier() { - @Override - public FileObject get() { - return rootObj; - } - }); + return new GradleHomeSourceForBinaryQuery(() -> rootObj); } private void doTestFindSourceOfStandardLibInSubDir(String... jarSubDir) throws IOException { diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/util/CustomGlobalSettingsRule.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/util/CustomGlobalSettingsRule.java index 6813077b..7e52b300 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/util/CustomGlobalSettingsRule.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/util/CustomGlobalSettingsRule.java @@ -27,16 +27,13 @@ public void evaluate() throws Throwable { } private void withCleanMemorySettings(final Statement base) throws Throwable { - withCleanMemorySettings(new NbConsumer() { - @Override - public void accept(GenericProfileSettings settings) { - settingsProvider.accept(CommonGlobalSettings.getDefault()); - - try { - base.evaluate(); - } catch (Throwable ex) { - throw new TestExceptionWrapper(ex); - } + withCleanMemorySettings((GenericProfileSettings settings) -> { + settingsProvider.accept(CommonGlobalSettings.getDefault()); + + try { + base.evaluate(); + } catch (Throwable ex) { + throw new TestExceptionWrapper(ex); } }); } diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/util/FileSystemWatcherTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/util/FileSystemWatcherTest.java index e5188138..6b3db8e9 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/util/FileSystemWatcherTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/util/FileSystemWatcherTest.java @@ -48,85 +48,45 @@ private void testModifications(WatchSetup setup, Modification... modifications) watcher.waitFor(TIMEOUT_SEC, TimeUnit.SECONDS); } - private static Modification createDirAction() { - return new Modification() { - @Override - public void doModification(Path watchedDir) throws IOException { - Files.createDirectory(watchedDir); - } - }; - } - - private static Modification createMultipleDirsAction() { - return new Modification() { - @Override - public void doModification(Path watchedDir) throws IOException { - Files.createDirectories(watchedDir); - } - }; - } - - private static Modification deleteDirAction() { - return new Modification() { - @Override - public void doModification(Path watchedDir) throws IOException { - Files.delete(watchedDir); - } - }; - } - @Test public void testMultiActionLevel1() throws IOException { - testModifications(new WatchSetup() { - @Override - public Path setupWatch(Path root) throws IOException { - return root.resolve("subdir"); - } - }, createDirAction(), deleteDirAction(), createDirAction()); + testModifications( + root -> root.resolve("subdir"), + Files::createDirectory, + Files::delete, + Files::createDirectory); } @Test public void testCreateLevel1() throws IOException { - testModifications(new WatchSetup() { - @Override - public Path setupWatch(Path root) throws IOException { - return root.resolve("subdir"); - } - }, createDirAction()); + testModifications( + root -> root.resolve("subdir"), + Files::createDirectory); } @Test public void testDeleteLevel1() throws IOException { - testModifications(new WatchSetup() { - @Override - public Path setupWatch(Path root) throws IOException { - Path watchedDir = root.resolve("subdir"); - Files.createDirectory(watchedDir); - return watchedDir; - } - }, deleteDirAction()); + testModifications((Path root) -> { + Path watchedDir = root.resolve("subdir"); + Files.createDirectory(watchedDir); + return watchedDir; + }, Files::delete); } @Test public void testCreateLevel2() throws IOException { - testModifications(new WatchSetup() { - @Override - public Path setupWatch(Path root) throws IOException { - return root.resolve("subdir").resolve("subdir2"); - } - }, createMultipleDirsAction()); + testModifications( + root -> root.resolve("subdir").resolve("subdir2"), + Files::createDirectories); } @Test public void testDeleteLevel2() throws IOException { - testModifications(new WatchSetup() { - @Override - public Path setupWatch(Path root) throws IOException { - Path watchedDir = root.resolve("subdir").resolve("subdir2"); - Files.createDirectories(watchedDir); - return watchedDir; - } - }, deleteDirAction()); + testModifications((Path root) -> { + Path watchedDir = root.resolve("subdir").resolve("subdir2"); + Files.createDirectories(watchedDir); + return watchedDir; + }, Files::delete); } private static final class TestListener implements Runnable { diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/util/SwingTestsRule.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/util/SwingTestsRule.java index b6168dac..9b92a827 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/util/SwingTestsRule.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/util/SwingTestsRule.java @@ -32,14 +32,11 @@ public void evaluate() throws Throwable { try { Thread.interrupted(); - SwingUtilities.invokeAndWait(new Runnable() { - @Override - public void run() { - try { - base.evaluate(); - } catch (Throwable ex) { - throw new TestExceptionWrapper(ex); - } + SwingUtilities.invokeAndWait(() -> { + try { + base.evaluate(); + } catch (Throwable ex) { + throw new TestExceptionWrapper(ex); } }); } catch (InvocationTargetException ex) { diff --git a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/view/AnnotationChildNodesTest.java b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/view/AnnotationChildNodesTest.java index 96247bba..304083c5 100644 --- a/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/view/AnnotationChildNodesTest.java +++ b/netbeans-gradle-plugin/src/test/java/org/netbeans/gradle/project/view/AnnotationChildNodesTest.java @@ -14,7 +14,6 @@ import org.netbeans.api.project.Project; import org.netbeans.gradle.project.api.nodes.SingleNodeFactory; import org.netbeans.gradle.project.properties.NbProperties; -import org.netbeans.gradle.project.util.NbSupplier; import org.netbeans.gradle.project.util.SwingTest; import org.netbeans.gradle.project.util.SwingTestAware; import org.netbeans.spi.project.ui.support.NodeFactory; @@ -45,12 +44,7 @@ public Lookup getLookup() { private AnnotationChildNodes testNodes(Object... factories) { final Lookup lookup = Lookups.fixed(factories); Project project = mockProject(); - return new AnnotationChildNodes(project, new NbSupplier() { - @Override - public Lookup get() { - return lookup; - } - }); + return new AnnotationChildNodes(project, () -> lookup); } private static NodeList testNodeList(PropertySource nodeList) { @@ -58,12 +52,9 @@ private static NodeList testNodeList(PropertySource nodeList) { - return new NodeFactory() { - @Override - public NodeList createNodes(Project project) { - ExceptionHelper.checkNotNullArgument(project, "project"); - return testNodeList(nodeList); - } + return (Project project) -> { + ExceptionHelper.checkNotNullArgument(project, "project"); + return testNodeList(nodeList); }; }