diff --git a/README.md b/README.md index 10b26a2..2360b37 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ -# Builder Generator Idea plugin ![build](https://github.com/mjedynak/builder-generator-idea-plugin/actions/workflows/build-gradle-project.yml/badge.svg?branch=master) - -Plugin for IntelliJ IDEA that adds ability to generate builder for a class and switch between them. - -Switching between builder and source class is similar to 'Go To Test' action. - -Generated builder class does not use reflection, only setter methods or constructor. +# Builder Generator Idea plugin ![build](https://github.com/mjedynak/builder-generator-idea-plugin/actions/workflows/build-gradle-project.yml/badge.svg?branch=master) + +Plugin for IntelliJ IDEA that adds ability to generate builder for a class and switch between them. + +Switching between builder and source class is similar to 'Go To Test' action. + +Generated builder class does not use reflection, only setter methods or constructor. diff --git a/build.gradle.kts b/build.gradle.kts index c2e4a70..6aa463f 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -50,4 +50,3 @@ spotless { palantirJavaFormat() } } - diff --git a/gradlew.bat b/gradlew.bat index 7101f8e..25da30d 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,92 +1,92 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%"=="" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%"=="" set DIRNAME=. -@rem This is normally unused -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if %ERRORLEVEL% equ 0 goto execute - -echo. 1>&2 -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. 1>&2 -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if %ERRORLEVEL% equ 0 goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -set EXIT_CODE=%ERRORLEVEL% -if %EXIT_CODE% equ 0 set EXIT_CODE=1 -if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% -exit /b %EXIT_CODE% - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/action/AbstractBuilderAction.java b/src/main/java/pl/mjedynak/idea/plugins/builder/action/AbstractBuilderAction.java index 67d4563..ba56b07 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/action/AbstractBuilderAction.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/action/AbstractBuilderAction.java @@ -1,56 +1,56 @@ -package pl.mjedynak.idea.plugins.builder.action; - -import com.intellij.openapi.editor.actionSystem.EditorAction; -import com.intellij.util.pico.DefaultPicoContainer; -import org.picocontainer.MutablePicoContainer; -import pl.mjedynak.idea.plugins.builder.action.handler.AbstractBuilderActionHandler; -import pl.mjedynak.idea.plugins.builder.action.handler.DisplayChoosers; -import pl.mjedynak.idea.plugins.builder.factory.CreateBuilderDialogFactory; -import pl.mjedynak.idea.plugins.builder.factory.MemberChooserDialogFactory; -import pl.mjedynak.idea.plugins.builder.factory.PopupChooserBuilderFactory; -import pl.mjedynak.idea.plugins.builder.factory.PsiElementClassMemberFactory; -import pl.mjedynak.idea.plugins.builder.factory.PsiFieldsForBuilderFactory; -import pl.mjedynak.idea.plugins.builder.factory.PsiManagerFactory; -import pl.mjedynak.idea.plugins.builder.factory.ReferenceEditorComboWithBrowseButtonFactory; -import pl.mjedynak.idea.plugins.builder.finder.BuilderFinder; -import pl.mjedynak.idea.plugins.builder.finder.ClassFinder; -import pl.mjedynak.idea.plugins.builder.gui.helper.GuiHelper; -import pl.mjedynak.idea.plugins.builder.psi.BestConstructorSelector; -import pl.mjedynak.idea.plugins.builder.psi.BuilderPsiClassBuilder; -import pl.mjedynak.idea.plugins.builder.psi.PsiFieldSelector; -import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; -import pl.mjedynak.idea.plugins.builder.verifier.BuilderVerifier; -import pl.mjedynak.idea.plugins.builder.verifier.PsiFieldVerifier; -import pl.mjedynak.idea.plugins.builder.writer.BuilderWriter; - -public abstract class AbstractBuilderAction extends EditorAction { - - protected static AbstractBuilderActionHandler builderActionHandler; - - protected static MutablePicoContainer picoContainer = new DefaultPicoContainer(); - - static { - picoContainer.registerComponentImplementation(PsiHelper.class); - picoContainer.registerComponentImplementation(BuilderVerifier.class); - picoContainer.registerComponentImplementation(ClassFinder.class); - picoContainer.registerComponentImplementation(BuilderPsiClassBuilder.class); - picoContainer.registerComponentImplementation(BuilderFinder.class); - picoContainer.registerComponentImplementation(PopupChooserBuilderFactory.class); - picoContainer.registerComponentImplementation(PsiManagerFactory.class); - picoContainer.registerComponentImplementation(CreateBuilderDialogFactory.class); - picoContainer.registerComponentImplementation(GuiHelper.class); - picoContainer.registerComponentImplementation(PsiFieldVerifier.class); - picoContainer.registerComponentImplementation(PsiElementClassMemberFactory.class); - picoContainer.registerComponentImplementation(ReferenceEditorComboWithBrowseButtonFactory.class); - picoContainer.registerComponentImplementation(MemberChooserDialogFactory.class); - picoContainer.registerComponentImplementation(BuilderWriter.class); - picoContainer.registerComponentImplementation(PsiFieldSelector.class); - picoContainer.registerComponentImplementation(PsiFieldsForBuilderFactory.class); - picoContainer.registerComponentImplementation(DisplayChoosers.class); - picoContainer.registerComponentImplementation(BestConstructorSelector.class); - } - - protected AbstractBuilderAction() { - super(builderActionHandler); - } -} +package pl.mjedynak.idea.plugins.builder.action; + +import com.intellij.openapi.editor.actionSystem.EditorAction; +import com.intellij.util.pico.DefaultPicoContainer; +import org.picocontainer.MutablePicoContainer; +import pl.mjedynak.idea.plugins.builder.action.handler.AbstractBuilderActionHandler; +import pl.mjedynak.idea.plugins.builder.action.handler.DisplayChoosers; +import pl.mjedynak.idea.plugins.builder.factory.CreateBuilderDialogFactory; +import pl.mjedynak.idea.plugins.builder.factory.MemberChooserDialogFactory; +import pl.mjedynak.idea.plugins.builder.factory.PopupChooserBuilderFactory; +import pl.mjedynak.idea.plugins.builder.factory.PsiElementClassMemberFactory; +import pl.mjedynak.idea.plugins.builder.factory.PsiFieldsForBuilderFactory; +import pl.mjedynak.idea.plugins.builder.factory.PsiManagerFactory; +import pl.mjedynak.idea.plugins.builder.factory.ReferenceEditorComboWithBrowseButtonFactory; +import pl.mjedynak.idea.plugins.builder.finder.BuilderFinder; +import pl.mjedynak.idea.plugins.builder.finder.ClassFinder; +import pl.mjedynak.idea.plugins.builder.gui.helper.GuiHelper; +import pl.mjedynak.idea.plugins.builder.psi.BestConstructorSelector; +import pl.mjedynak.idea.plugins.builder.psi.BuilderPsiClassBuilder; +import pl.mjedynak.idea.plugins.builder.psi.PsiFieldSelector; +import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; +import pl.mjedynak.idea.plugins.builder.verifier.BuilderVerifier; +import pl.mjedynak.idea.plugins.builder.verifier.PsiFieldVerifier; +import pl.mjedynak.idea.plugins.builder.writer.BuilderWriter; + +public abstract class AbstractBuilderAction extends EditorAction { + + protected static AbstractBuilderActionHandler builderActionHandler; + + protected static MutablePicoContainer picoContainer = new DefaultPicoContainer(); + + static { + picoContainer.registerComponentImplementation(PsiHelper.class); + picoContainer.registerComponentImplementation(BuilderVerifier.class); + picoContainer.registerComponentImplementation(ClassFinder.class); + picoContainer.registerComponentImplementation(BuilderPsiClassBuilder.class); + picoContainer.registerComponentImplementation(BuilderFinder.class); + picoContainer.registerComponentImplementation(PopupChooserBuilderFactory.class); + picoContainer.registerComponentImplementation(PsiManagerFactory.class); + picoContainer.registerComponentImplementation(CreateBuilderDialogFactory.class); + picoContainer.registerComponentImplementation(GuiHelper.class); + picoContainer.registerComponentImplementation(PsiFieldVerifier.class); + picoContainer.registerComponentImplementation(PsiElementClassMemberFactory.class); + picoContainer.registerComponentImplementation(ReferenceEditorComboWithBrowseButtonFactory.class); + picoContainer.registerComponentImplementation(MemberChooserDialogFactory.class); + picoContainer.registerComponentImplementation(BuilderWriter.class); + picoContainer.registerComponentImplementation(PsiFieldSelector.class); + picoContainer.registerComponentImplementation(PsiFieldsForBuilderFactory.class); + picoContainer.registerComponentImplementation(DisplayChoosers.class); + picoContainer.registerComponentImplementation(BestConstructorSelector.class); + } + + protected AbstractBuilderAction() { + super(builderActionHandler); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/action/AbstractBuilderAdditionalAction.java b/src/main/java/pl/mjedynak/idea/plugins/builder/action/AbstractBuilderAdditionalAction.java index a3ea9ba..99e7ded 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/action/AbstractBuilderAdditionalAction.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/action/AbstractBuilderAdditionalAction.java @@ -1,5 +1,5 @@ -package pl.mjedynak.idea.plugins.builder.action; - -import com.intellij.codeInsight.navigation.GotoTargetHandler; - -public abstract class AbstractBuilderAdditionalAction implements GotoTargetHandler.AdditionalAction {} +package pl.mjedynak.idea.plugins.builder.action; + +import com.intellij.codeInsight.navigation.GotoTargetHandler; + +public abstract class AbstractBuilderAdditionalAction implements GotoTargetHandler.AdditionalAction {} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/action/GenerateBuilderAction.java b/src/main/java/pl/mjedynak/idea/plugins/builder/action/GenerateBuilderAction.java index fcd55fa..b2fcbb9 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/action/GenerateBuilderAction.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/action/GenerateBuilderAction.java @@ -1,17 +1,17 @@ -package pl.mjedynak.idea.plugins.builder.action; - -import pl.mjedynak.idea.plugins.builder.action.handler.AbstractBuilderActionHandler; -import pl.mjedynak.idea.plugins.builder.action.handler.GenerateBuilderActionHandler; -import pl.mjedynak.idea.plugins.builder.factory.GenerateBuilderPopupListFactory; -import pl.mjedynak.idea.plugins.builder.gui.displayer.GenerateBuilderPopupDisplayer; - -public class GenerateBuilderAction extends AbstractBuilderAction { - - static { - picoContainer.registerComponentImplementation(GenerateBuilderActionHandler.class); - picoContainer.registerComponentImplementation(GenerateBuilderPopupDisplayer.class); - picoContainer.registerComponentImplementation(GenerateBuilderPopupListFactory.class); - builderActionHandler = (AbstractBuilderActionHandler) - picoContainer.getComponentInstanceOfType(GenerateBuilderActionHandler.class); - } -} +package pl.mjedynak.idea.plugins.builder.action; + +import pl.mjedynak.idea.plugins.builder.action.handler.AbstractBuilderActionHandler; +import pl.mjedynak.idea.plugins.builder.action.handler.GenerateBuilderActionHandler; +import pl.mjedynak.idea.plugins.builder.factory.GenerateBuilderPopupListFactory; +import pl.mjedynak.idea.plugins.builder.gui.displayer.GenerateBuilderPopupDisplayer; + +public class GenerateBuilderAction extends AbstractBuilderAction { + + static { + picoContainer.registerComponentImplementation(GenerateBuilderActionHandler.class); + picoContainer.registerComponentImplementation(GenerateBuilderPopupDisplayer.class); + picoContainer.registerComponentImplementation(GenerateBuilderPopupListFactory.class); + builderActionHandler = (AbstractBuilderActionHandler) + picoContainer.getComponentInstanceOfType(GenerateBuilderActionHandler.class); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/action/GenerateBuilderAdditionalAction.java b/src/main/java/pl/mjedynak/idea/plugins/builder/action/GenerateBuilderAdditionalAction.java index c4c1ee5..2b64bbc 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/action/GenerateBuilderAdditionalAction.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/action/GenerateBuilderAdditionalAction.java @@ -1,26 +1,26 @@ -package pl.mjedynak.idea.plugins.builder.action; - -import com.intellij.openapi.util.IconLoader; -import javax.swing.Icon; -import org.jetbrains.annotations.NotNull; - -public class GenerateBuilderAdditionalAction extends AbstractBuilderAdditionalAction { - - private static final String TEXT = "Create New Builder..."; - private static final Icon ICON = - IconLoader.getIcon("/actions/intentionBulb.png", GenerateBuilderAdditionalAction.class); - - @NotNull - @Override - public String getText() { - return TEXT; - } - - @Override - public Icon getIcon() { - return ICON; - } - - @Override - public void execute() {} -} +package pl.mjedynak.idea.plugins.builder.action; + +import com.intellij.openapi.util.IconLoader; +import javax.swing.Icon; +import org.jetbrains.annotations.NotNull; + +public class GenerateBuilderAdditionalAction extends AbstractBuilderAdditionalAction { + + private static final String TEXT = "Create New Builder..."; + private static final Icon ICON = + IconLoader.getIcon("/actions/intentionBulb.png", GenerateBuilderAdditionalAction.class); + + @NotNull + @Override + public String getText() { + return TEXT; + } + + @Override + public Icon getIcon() { + return ICON; + } + + @Override + public void execute() {} +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/action/GoToBuilderAction.java b/src/main/java/pl/mjedynak/idea/plugins/builder/action/GoToBuilderAction.java index c137088..132542a 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/action/GoToBuilderAction.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/action/GoToBuilderAction.java @@ -1,17 +1,17 @@ -package pl.mjedynak.idea.plugins.builder.action; - -import pl.mjedynak.idea.plugins.builder.action.handler.AbstractBuilderActionHandler; -import pl.mjedynak.idea.plugins.builder.action.handler.GoToBuilderActionHandler; -import pl.mjedynak.idea.plugins.builder.factory.GoToBuilderPopupListFactory; -import pl.mjedynak.idea.plugins.builder.gui.displayer.GoToBuilderPopupDisplayer; - -public class GoToBuilderAction extends AbstractBuilderAction { - - static { - picoContainer.registerComponentImplementation(GoToBuilderActionHandler.class); - picoContainer.registerComponentImplementation(GoToBuilderPopupDisplayer.class); - picoContainer.registerComponentImplementation(GoToBuilderPopupListFactory.class); - builderActionHandler = - (AbstractBuilderActionHandler) picoContainer.getComponentInstanceOfType(GoToBuilderActionHandler.class); - } -} +package pl.mjedynak.idea.plugins.builder.action; + +import pl.mjedynak.idea.plugins.builder.action.handler.AbstractBuilderActionHandler; +import pl.mjedynak.idea.plugins.builder.action.handler.GoToBuilderActionHandler; +import pl.mjedynak.idea.plugins.builder.factory.GoToBuilderPopupListFactory; +import pl.mjedynak.idea.plugins.builder.gui.displayer.GoToBuilderPopupDisplayer; + +public class GoToBuilderAction extends AbstractBuilderAction { + + static { + picoContainer.registerComponentImplementation(GoToBuilderActionHandler.class); + picoContainer.registerComponentImplementation(GoToBuilderPopupDisplayer.class); + picoContainer.registerComponentImplementation(GoToBuilderPopupListFactory.class); + builderActionHandler = + (AbstractBuilderActionHandler) picoContainer.getComponentInstanceOfType(GoToBuilderActionHandler.class); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/action/GoToBuilderAdditionalAction.java b/src/main/java/pl/mjedynak/idea/plugins/builder/action/GoToBuilderAdditionalAction.java index b161bd5..96b467e 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/action/GoToBuilderAdditionalAction.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/action/GoToBuilderAdditionalAction.java @@ -1,25 +1,25 @@ -package pl.mjedynak.idea.plugins.builder.action; - -import com.intellij.openapi.util.IconLoader; -import javax.swing.Icon; -import org.jetbrains.annotations.NotNull; - -public class GoToBuilderAdditionalAction extends AbstractBuilderAdditionalAction { - - private static final String TEXT = "Go to builder..."; - private static final Icon ICON = IconLoader.getIcon("/actions/intentionBulb.png"); - - @NotNull - @Override - public String getText() { - return TEXT; - } - - @Override - public Icon getIcon() { - return ICON; - } - - @Override - public void execute() {} -} +package pl.mjedynak.idea.plugins.builder.action; + +import com.intellij.openapi.util.IconLoader; +import javax.swing.Icon; +import org.jetbrains.annotations.NotNull; + +public class GoToBuilderAdditionalAction extends AbstractBuilderAdditionalAction { + + private static final String TEXT = "Go to builder..."; + private static final Icon ICON = IconLoader.getIcon("/actions/intentionBulb.png"); + + @NotNull + @Override + public String getText() { + return TEXT; + } + + @Override + public Icon getIcon() { + return ICON; + } + + @Override + public void execute() {} +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/action/RegenerateBuilderAdditionalAction.java b/src/main/java/pl/mjedynak/idea/plugins/builder/action/RegenerateBuilderAdditionalAction.java index d11a93e..1dd9c05 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/action/RegenerateBuilderAdditionalAction.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/action/RegenerateBuilderAdditionalAction.java @@ -1,25 +1,25 @@ -package pl.mjedynak.idea.plugins.builder.action; - -import com.intellij.openapi.util.IconLoader; -import javax.swing.Icon; -import org.jetbrains.annotations.NotNull; - -public class RegenerateBuilderAdditionalAction extends AbstractBuilderAdditionalAction { - - private static final String TEXT = "Regenerate builder..."; - private static final Icon ICON = IconLoader.getIcon("/actions/intentionBulb.png"); - - @NotNull - @Override - public String getText() { - return TEXT; - } - - @Override - public Icon getIcon() { - return ICON; - } - - @Override - public void execute() {} -} +package pl.mjedynak.idea.plugins.builder.action; + +import com.intellij.openapi.util.IconLoader; +import javax.swing.Icon; +import org.jetbrains.annotations.NotNull; + +public class RegenerateBuilderAdditionalAction extends AbstractBuilderAdditionalAction { + + private static final String TEXT = "Regenerate builder..."; + private static final Icon ICON = IconLoader.getIcon("/actions/intentionBulb.png"); + + @NotNull + @Override + public String getText() { + return TEXT; + } + + @Override + public Icon getIcon() { + return ICON; + } + + @Override + public void execute() {} +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/action/handler/AbstractBuilderActionHandler.java b/src/main/java/pl/mjedynak/idea/plugins/builder/action/handler/AbstractBuilderActionHandler.java index 362b308..9bdbe73 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/action/handler/AbstractBuilderActionHandler.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/action/handler/AbstractBuilderActionHandler.java @@ -1,78 +1,78 @@ -package pl.mjedynak.idea.plugins.builder.action.handler; - -import com.intellij.openapi.actionSystem.CommonDataKeys; -import com.intellij.openapi.actionSystem.DataContext; -import com.intellij.openapi.editor.Editor; -import com.intellij.openapi.editor.actionSystem.EditorActionHandler; -import com.intellij.openapi.project.Project; -import com.intellij.psi.PsiClass; -import pl.mjedynak.idea.plugins.builder.factory.AbstractPopupListFactory; -import pl.mjedynak.idea.plugins.builder.finder.BuilderFinder; -import pl.mjedynak.idea.plugins.builder.gui.displayer.AbstractPopupDisplayer; -import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; -import pl.mjedynak.idea.plugins.builder.verifier.BuilderVerifier; - -public abstract class AbstractBuilderActionHandler extends EditorActionHandler { - - private final BuilderVerifier builderVerifier; - private final BuilderFinder builderFinder; - protected PsiHelper psiHelper; - protected AbstractPopupDisplayer popupDisplayer; - protected AbstractPopupListFactory popupListFactory; - protected DisplayChoosers displayChoosers; - - public AbstractBuilderActionHandler( - PsiHelper psiHelper, - BuilderVerifier builderVerifier, - BuilderFinder builderFinder, - AbstractPopupDisplayer popupDisplayer, - AbstractPopupListFactory popupListFactory, - DisplayChoosers displayChoosers) { - this.psiHelper = psiHelper; - this.builderVerifier = builderVerifier; - this.builderFinder = builderFinder; - this.popupDisplayer = popupDisplayer; - this.popupListFactory = popupListFactory; - this.displayChoosers = displayChoosers; - } - - @Override - public void execute(Editor editor, DataContext dataContext) { - Project project = (Project) dataContext.getData(CommonDataKeys.PROJECT.getName()); - PsiClass psiClassFromEditor = psiHelper.getPsiClassFromEditor(editor, project); - prepareDisplayChoosers(editor, psiClassFromEditor, dataContext); - if (psiClassFromEditor != null) { - forwardToSpecificAction(editor, psiClassFromEditor, dataContext); - } - } - - private void prepareDisplayChoosers(Editor editor, PsiClass psiClassFromEditor, DataContext dataContext) { - Project project = (Project) dataContext.getData(CommonDataKeys.PROJECT.getName()); - displayChoosers.setEditor(editor); - displayChoosers.setProject(project); - displayChoosers.setPsiClassFromEditor(psiClassFromEditor); - } - - private void forwardToSpecificAction(Editor editor, PsiClass psiClassFromEditor, DataContext dataContext) { - boolean isBuilder = builderVerifier.isBuilder(psiClassFromEditor); - PsiClass classToGo = findClassToGo(psiClassFromEditor, isBuilder); - if (classToGo != null) { - doActionWhenClassToGoIsFound(editor, psiClassFromEditor, dataContext, isBuilder, classToGo); - } else { - doActionWhenClassToGoIsNotFound(editor, psiClassFromEditor, dataContext, isBuilder); - } - } - - private PsiClass findClassToGo(PsiClass psiClassFromEditor, boolean isBuilder) { - if (isBuilder) { - return builderFinder.findClassForBuilder(psiClassFromEditor); - } - return builderFinder.findBuilderForClass(psiClassFromEditor); - } - - protected abstract void doActionWhenClassToGoIsFound( - Editor editor, PsiClass psiClassFromEditor, DataContext dataContext, boolean isBuilder, PsiClass classToGo); - - protected abstract void doActionWhenClassToGoIsNotFound( - Editor editor, PsiClass psiClassFromEditor, DataContext dataContext, boolean isBuilder); -} +package pl.mjedynak.idea.plugins.builder.action.handler; + +import com.intellij.openapi.actionSystem.CommonDataKeys; +import com.intellij.openapi.actionSystem.DataContext; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.editor.actionSystem.EditorActionHandler; +import com.intellij.openapi.project.Project; +import com.intellij.psi.PsiClass; +import pl.mjedynak.idea.plugins.builder.factory.AbstractPopupListFactory; +import pl.mjedynak.idea.plugins.builder.finder.BuilderFinder; +import pl.mjedynak.idea.plugins.builder.gui.displayer.AbstractPopupDisplayer; +import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; +import pl.mjedynak.idea.plugins.builder.verifier.BuilderVerifier; + +public abstract class AbstractBuilderActionHandler extends EditorActionHandler { + + private final BuilderVerifier builderVerifier; + private final BuilderFinder builderFinder; + protected PsiHelper psiHelper; + protected AbstractPopupDisplayer popupDisplayer; + protected AbstractPopupListFactory popupListFactory; + protected DisplayChoosers displayChoosers; + + public AbstractBuilderActionHandler( + PsiHelper psiHelper, + BuilderVerifier builderVerifier, + BuilderFinder builderFinder, + AbstractPopupDisplayer popupDisplayer, + AbstractPopupListFactory popupListFactory, + DisplayChoosers displayChoosers) { + this.psiHelper = psiHelper; + this.builderVerifier = builderVerifier; + this.builderFinder = builderFinder; + this.popupDisplayer = popupDisplayer; + this.popupListFactory = popupListFactory; + this.displayChoosers = displayChoosers; + } + + @Override + public void execute(Editor editor, DataContext dataContext) { + Project project = (Project) dataContext.getData(CommonDataKeys.PROJECT.getName()); + PsiClass psiClassFromEditor = psiHelper.getPsiClassFromEditor(editor, project); + prepareDisplayChoosers(editor, psiClassFromEditor, dataContext); + if (psiClassFromEditor != null) { + forwardToSpecificAction(editor, psiClassFromEditor, dataContext); + } + } + + private void prepareDisplayChoosers(Editor editor, PsiClass psiClassFromEditor, DataContext dataContext) { + Project project = (Project) dataContext.getData(CommonDataKeys.PROJECT.getName()); + displayChoosers.setEditor(editor); + displayChoosers.setProject(project); + displayChoosers.setPsiClassFromEditor(psiClassFromEditor); + } + + private void forwardToSpecificAction(Editor editor, PsiClass psiClassFromEditor, DataContext dataContext) { + boolean isBuilder = builderVerifier.isBuilder(psiClassFromEditor); + PsiClass classToGo = findClassToGo(psiClassFromEditor, isBuilder); + if (classToGo != null) { + doActionWhenClassToGoIsFound(editor, psiClassFromEditor, dataContext, isBuilder, classToGo); + } else { + doActionWhenClassToGoIsNotFound(editor, psiClassFromEditor, dataContext, isBuilder); + } + } + + private PsiClass findClassToGo(PsiClass psiClassFromEditor, boolean isBuilder) { + if (isBuilder) { + return builderFinder.findClassForBuilder(psiClassFromEditor); + } + return builderFinder.findBuilderForClass(psiClassFromEditor); + } + + protected abstract void doActionWhenClassToGoIsFound( + Editor editor, PsiClass psiClassFromEditor, DataContext dataContext, boolean isBuilder, PsiClass classToGo); + + protected abstract void doActionWhenClassToGoIsNotFound( + Editor editor, PsiClass psiClassFromEditor, DataContext dataContext, boolean isBuilder); +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/action/handler/DisplayChoosers.java b/src/main/java/pl/mjedynak/idea/plugins/builder/action/handler/DisplayChoosers.java index 87f7fe6..3cbeb10 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/action/handler/DisplayChoosers.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/action/handler/DisplayChoosers.java @@ -1,122 +1,122 @@ -package pl.mjedynak.idea.plugins.builder.action.handler; - -import com.intellij.codeInsight.generation.PsiElementClassMember; -import com.intellij.openapi.editor.Editor; -import com.intellij.openapi.project.Project; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiDirectory; -import com.intellij.psi.PsiPackage; -import java.util.List; -import pl.mjedynak.idea.plugins.builder.factory.CreateBuilderDialogFactory; -import pl.mjedynak.idea.plugins.builder.factory.MemberChooserDialogFactory; -import pl.mjedynak.idea.plugins.builder.factory.PsiFieldsForBuilderFactory; -import pl.mjedynak.idea.plugins.builder.gui.CreateBuilderDialog; -import pl.mjedynak.idea.plugins.builder.psi.PsiFieldSelector; -import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; -import pl.mjedynak.idea.plugins.builder.psi.model.PsiFieldsForBuilder; -import pl.mjedynak.idea.plugins.builder.writer.BuilderContext; -import pl.mjedynak.idea.plugins.builder.writer.BuilderWriter; - -public class DisplayChoosers { - - private PsiClass psiClassFromEditor; - private Project project; - private Editor editor; - private final PsiHelper psiHelper; - private final CreateBuilderDialogFactory createBuilderDialogFactory; - private final PsiFieldSelector psiFieldSelector; - private final MemberChooserDialogFactory memberChooserDialogFactory; - private final BuilderWriter builderWriter; - private final PsiFieldsForBuilderFactory psiFieldsForBuilderFactory; - - public DisplayChoosers( - PsiHelper psiHelper, - CreateBuilderDialogFactory createBuilderDialogFactory, - PsiFieldSelector psiFieldSelector, - MemberChooserDialogFactory memberChooserDialogFactory, - BuilderWriter builderWriter, - PsiFieldsForBuilderFactory psiFieldsForBuilderFactory) { - this.psiHelper = psiHelper; - this.createBuilderDialogFactory = createBuilderDialogFactory; - this.psiFieldSelector = psiFieldSelector; - this.memberChooserDialogFactory = memberChooserDialogFactory; - this.builderWriter = builderWriter; - this.psiFieldsForBuilderFactory = psiFieldsForBuilderFactory; - } - - public void run(PsiClass existingBuilder) { - CreateBuilderDialog createBuilderDialog = showDialog(existingBuilder); - if (createBuilderDialog.isOK()) { - PsiDirectory targetDirectory = createBuilderDialog.getTargetDirectory(); - String className = createBuilderDialog.getClassName(); - String methodPrefix = createBuilderDialog.getMethodPrefix(); - boolean innerBuilder = createBuilderDialog.isInnerBuilder(); - boolean useSingleField = createBuilderDialog.useSingleField(); - boolean hasButMethod = createBuilderDialog.hasButMethod(); - List> fieldsToDisplay = - getFieldsToIncludeInBuilder(psiClassFromEditor, innerBuilder, useSingleField, hasButMethod); - com.intellij.ide.util.MemberChooser> memberChooserDialog = - memberChooserDialogFactory.getMemberChooserDialog(fieldsToDisplay, project); - memberChooserDialog.show(); - writeBuilderIfNecessary( - targetDirectory, - className, - methodPrefix, - memberChooserDialog, - createBuilderDialog, - existingBuilder); - } - } - - private void writeBuilderIfNecessary( - PsiDirectory targetDirectory, - String className, - String methodPrefix, - com.intellij.ide.util.MemberChooser> memberChooserDialog, - CreateBuilderDialog createBuilderDialog, - PsiClass existingBuilder) { - if (memberChooserDialog.isOK()) { - List> selectedElements = memberChooserDialog.getSelectedElements(); - PsiFieldsForBuilder psiFieldsForBuilder = - psiFieldsForBuilderFactory.createPsiFieldsForBuilder(selectedElements, psiClassFromEditor); - BuilderContext context = new BuilderContext( - project, - psiFieldsForBuilder, - targetDirectory, - className, - psiClassFromEditor, - methodPrefix, - createBuilderDialog.isInnerBuilder(), - createBuilderDialog.hasButMethod(), - createBuilderDialog.useSingleField(), - createBuilderDialog.hasAddCopyConstructor()); - builderWriter.writeBuilder(context, existingBuilder); - } - } - - private CreateBuilderDialog showDialog(PsiClass existingBuilder) { - PsiDirectory srcDir = psiHelper.getPsiFileFromEditor(editor, project).getContainingDirectory(); - PsiPackage srcPackage = psiHelper.getPackage(srcDir); - CreateBuilderDialog dialog = createBuilderDialogFactory.createBuilderDialog( - psiClassFromEditor, project, srcPackage, existingBuilder); - dialog.show(); - return dialog; - } - - private List> getFieldsToIncludeInBuilder( - PsiClass clazz, boolean innerBuilder, boolean useSingleField, boolean hasButMethod) { - return psiFieldSelector.selectFieldsToIncludeInBuilder(clazz, innerBuilder, useSingleField, hasButMethod); - } - - public void setPsiClassFromEditor(PsiClass psiClassFromEditor) { - this.psiClassFromEditor = psiClassFromEditor; - } - - public void setProject(Project project) { - this.project = project; - } - - public void setEditor(Editor editor) { - this.editor = editor; - } -} +package pl.mjedynak.idea.plugins.builder.action.handler; + +import com.intellij.codeInsight.generation.PsiElementClassMember; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.project.Project; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiDirectory; +import com.intellij.psi.PsiPackage; +import java.util.List; +import pl.mjedynak.idea.plugins.builder.factory.CreateBuilderDialogFactory; +import pl.mjedynak.idea.plugins.builder.factory.MemberChooserDialogFactory; +import pl.mjedynak.idea.plugins.builder.factory.PsiFieldsForBuilderFactory; +import pl.mjedynak.idea.plugins.builder.gui.CreateBuilderDialog; +import pl.mjedynak.idea.plugins.builder.psi.PsiFieldSelector; +import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; +import pl.mjedynak.idea.plugins.builder.psi.model.PsiFieldsForBuilder; +import pl.mjedynak.idea.plugins.builder.writer.BuilderContext; +import pl.mjedynak.idea.plugins.builder.writer.BuilderWriter; + +public class DisplayChoosers { + + private PsiClass psiClassFromEditor; + private Project project; + private Editor editor; + private final PsiHelper psiHelper; + private final CreateBuilderDialogFactory createBuilderDialogFactory; + private final PsiFieldSelector psiFieldSelector; + private final MemberChooserDialogFactory memberChooserDialogFactory; + private final BuilderWriter builderWriter; + private final PsiFieldsForBuilderFactory psiFieldsForBuilderFactory; + + public DisplayChoosers( + PsiHelper psiHelper, + CreateBuilderDialogFactory createBuilderDialogFactory, + PsiFieldSelector psiFieldSelector, + MemberChooserDialogFactory memberChooserDialogFactory, + BuilderWriter builderWriter, + PsiFieldsForBuilderFactory psiFieldsForBuilderFactory) { + this.psiHelper = psiHelper; + this.createBuilderDialogFactory = createBuilderDialogFactory; + this.psiFieldSelector = psiFieldSelector; + this.memberChooserDialogFactory = memberChooserDialogFactory; + this.builderWriter = builderWriter; + this.psiFieldsForBuilderFactory = psiFieldsForBuilderFactory; + } + + public void run(PsiClass existingBuilder) { + CreateBuilderDialog createBuilderDialog = showDialog(existingBuilder); + if (createBuilderDialog.isOK()) { + PsiDirectory targetDirectory = createBuilderDialog.getTargetDirectory(); + String className = createBuilderDialog.getClassName(); + String methodPrefix = createBuilderDialog.getMethodPrefix(); + boolean innerBuilder = createBuilderDialog.isInnerBuilder(); + boolean useSingleField = createBuilderDialog.useSingleField(); + boolean hasButMethod = createBuilderDialog.hasButMethod(); + List> fieldsToDisplay = + getFieldsToIncludeInBuilder(psiClassFromEditor, innerBuilder, useSingleField, hasButMethod); + com.intellij.ide.util.MemberChooser> memberChooserDialog = + memberChooserDialogFactory.getMemberChooserDialog(fieldsToDisplay, project); + memberChooserDialog.show(); + writeBuilderIfNecessary( + targetDirectory, + className, + methodPrefix, + memberChooserDialog, + createBuilderDialog, + existingBuilder); + } + } + + private void writeBuilderIfNecessary( + PsiDirectory targetDirectory, + String className, + String methodPrefix, + com.intellij.ide.util.MemberChooser> memberChooserDialog, + CreateBuilderDialog createBuilderDialog, + PsiClass existingBuilder) { + if (memberChooserDialog.isOK()) { + List> selectedElements = memberChooserDialog.getSelectedElements(); + PsiFieldsForBuilder psiFieldsForBuilder = + psiFieldsForBuilderFactory.createPsiFieldsForBuilder(selectedElements, psiClassFromEditor); + BuilderContext context = new BuilderContext( + project, + psiFieldsForBuilder, + targetDirectory, + className, + psiClassFromEditor, + methodPrefix, + createBuilderDialog.isInnerBuilder(), + createBuilderDialog.hasButMethod(), + createBuilderDialog.useSingleField(), + createBuilderDialog.hasAddCopyConstructor()); + builderWriter.writeBuilder(context, existingBuilder); + } + } + + private CreateBuilderDialog showDialog(PsiClass existingBuilder) { + PsiDirectory srcDir = psiHelper.getPsiFileFromEditor(editor, project).getContainingDirectory(); + PsiPackage srcPackage = psiHelper.getPackage(srcDir); + CreateBuilderDialog dialog = createBuilderDialogFactory.createBuilderDialog( + psiClassFromEditor, project, srcPackage, existingBuilder); + dialog.show(); + return dialog; + } + + private List> getFieldsToIncludeInBuilder( + PsiClass clazz, boolean innerBuilder, boolean useSingleField, boolean hasButMethod) { + return psiFieldSelector.selectFieldsToIncludeInBuilder(clazz, innerBuilder, useSingleField, hasButMethod); + } + + public void setPsiClassFromEditor(PsiClass psiClassFromEditor) { + this.psiClassFromEditor = psiClassFromEditor; + } + + public void setProject(Project project) { + this.project = project; + } + + public void setEditor(Editor editor) { + this.editor = editor; + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/action/handler/GenerateBuilderActionHandler.java b/src/main/java/pl/mjedynak/idea/plugins/builder/action/handler/GenerateBuilderActionHandler.java index 69840e5..7e9cdd1 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/action/handler/GenerateBuilderActionHandler.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/action/handler/GenerateBuilderActionHandler.java @@ -1,58 +1,58 @@ -package pl.mjedynak.idea.plugins.builder.action.handler; - -import com.intellij.openapi.actionSystem.DataContext; -import com.intellij.openapi.editor.Editor; -import com.intellij.psi.PsiClass; -import javax.swing.JList; -import pl.mjedynak.idea.plugins.builder.action.GoToBuilderAdditionalAction; -import pl.mjedynak.idea.plugins.builder.action.RegenerateBuilderAdditionalAction; -import pl.mjedynak.idea.plugins.builder.factory.GenerateBuilderPopupListFactory; -import pl.mjedynak.idea.plugins.builder.finder.BuilderFinder; -import pl.mjedynak.idea.plugins.builder.gui.displayer.GenerateBuilderPopupDisplayer; -import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; -import pl.mjedynak.idea.plugins.builder.verifier.BuilderVerifier; - -public class GenerateBuilderActionHandler extends AbstractBuilderActionHandler { - - public GenerateBuilderActionHandler( - PsiHelper psiHelper, - BuilderVerifier builderVerifier, - BuilderFinder builderFinder, - GenerateBuilderPopupDisplayer popupDisplayer, - GenerateBuilderPopupListFactory popupListFactory, - DisplayChoosers displayChoosersRunnable) { - super(psiHelper, builderVerifier, builderFinder, popupDisplayer, popupListFactory, displayChoosersRunnable); - } - - @Override - protected void doActionWhenClassToGoIsFound( - Editor editor, - PsiClass psiClassFromEditor, - DataContext dataContext, - boolean isBuilder, - PsiClass classToGo) { - if (!isBuilder) { - displayPopup(editor, classToGo); - } - } - - @Override - protected void doActionWhenClassToGoIsNotFound( - Editor editor, PsiClass psiClassFromEditor, DataContext dataContext, boolean isBuilder) { - if (!isBuilder) { - displayChoosers.run(null); - } - } - - @SuppressWarnings("rawtypes") - private void displayPopup(Editor editor, PsiClass classToGo) { - JList popupList = popupListFactory.getPopupList(); - popupDisplayer.displayPopupChooser(editor, popupList, () -> { - if (popupList.getSelectedValue() instanceof GoToBuilderAdditionalAction) { - psiHelper.navigateToClass(classToGo); - } else if (popupList.getSelectedValue() instanceof RegenerateBuilderAdditionalAction) { - displayChoosers.run(classToGo); - } - }); - } -} +package pl.mjedynak.idea.plugins.builder.action.handler; + +import com.intellij.openapi.actionSystem.DataContext; +import com.intellij.openapi.editor.Editor; +import com.intellij.psi.PsiClass; +import javax.swing.JList; +import pl.mjedynak.idea.plugins.builder.action.GoToBuilderAdditionalAction; +import pl.mjedynak.idea.plugins.builder.action.RegenerateBuilderAdditionalAction; +import pl.mjedynak.idea.plugins.builder.factory.GenerateBuilderPopupListFactory; +import pl.mjedynak.idea.plugins.builder.finder.BuilderFinder; +import pl.mjedynak.idea.plugins.builder.gui.displayer.GenerateBuilderPopupDisplayer; +import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; +import pl.mjedynak.idea.plugins.builder.verifier.BuilderVerifier; + +public class GenerateBuilderActionHandler extends AbstractBuilderActionHandler { + + public GenerateBuilderActionHandler( + PsiHelper psiHelper, + BuilderVerifier builderVerifier, + BuilderFinder builderFinder, + GenerateBuilderPopupDisplayer popupDisplayer, + GenerateBuilderPopupListFactory popupListFactory, + DisplayChoosers displayChoosersRunnable) { + super(psiHelper, builderVerifier, builderFinder, popupDisplayer, popupListFactory, displayChoosersRunnable); + } + + @Override + protected void doActionWhenClassToGoIsFound( + Editor editor, + PsiClass psiClassFromEditor, + DataContext dataContext, + boolean isBuilder, + PsiClass classToGo) { + if (!isBuilder) { + displayPopup(editor, classToGo); + } + } + + @Override + protected void doActionWhenClassToGoIsNotFound( + Editor editor, PsiClass psiClassFromEditor, DataContext dataContext, boolean isBuilder) { + if (!isBuilder) { + displayChoosers.run(null); + } + } + + @SuppressWarnings("rawtypes") + private void displayPopup(Editor editor, PsiClass classToGo) { + JList popupList = popupListFactory.getPopupList(); + popupDisplayer.displayPopupChooser(editor, popupList, () -> { + if (popupList.getSelectedValue() instanceof GoToBuilderAdditionalAction) { + psiHelper.navigateToClass(classToGo); + } else if (popupList.getSelectedValue() instanceof RegenerateBuilderAdditionalAction) { + displayChoosers.run(classToGo); + } + }); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/action/handler/GoToBuilderActionHandler.java b/src/main/java/pl/mjedynak/idea/plugins/builder/action/handler/GoToBuilderActionHandler.java index 3366521..bdf6bb0 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/action/handler/GoToBuilderActionHandler.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/action/handler/GoToBuilderActionHandler.java @@ -1,48 +1,48 @@ -package pl.mjedynak.idea.plugins.builder.action.handler; - -import com.intellij.openapi.actionSystem.DataContext; -import com.intellij.openapi.editor.Editor; -import com.intellij.psi.PsiClass; -import javax.swing.JList; -import pl.mjedynak.idea.plugins.builder.factory.GoToBuilderPopupListFactory; -import pl.mjedynak.idea.plugins.builder.finder.BuilderFinder; -import pl.mjedynak.idea.plugins.builder.gui.displayer.GoToBuilderPopupDisplayer; -import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; -import pl.mjedynak.idea.plugins.builder.verifier.BuilderVerifier; - -public class GoToBuilderActionHandler extends AbstractBuilderActionHandler { - - public GoToBuilderActionHandler( - PsiHelper psiHelper, - BuilderVerifier builderVerifier, - BuilderFinder builderFinder, - GoToBuilderPopupDisplayer popupDisplayer, - GoToBuilderPopupListFactory popupListFactory, - DisplayChoosers displayChoosersRunnable) { - super(psiHelper, builderVerifier, builderFinder, popupDisplayer, popupListFactory, displayChoosersRunnable); - } - - @Override - protected void doActionWhenClassToGoIsFound( - Editor editor, - PsiClass psiClassFromEditor, - DataContext dataContext, - boolean isBuilder, - PsiClass classToGo) { - psiHelper.navigateToClass(classToGo); - } - - @Override - protected void doActionWhenClassToGoIsNotFound( - Editor editor, PsiClass psiClassFromEditor, DataContext dataContext, boolean isBuilder) { - if (!isBuilder) { - displayPopup(editor); - } - } - - @SuppressWarnings("rawtypes") - private void displayPopup(Editor editor) { - JList popupList = popupListFactory.getPopupList(); - popupDisplayer.displayPopupChooser(editor, popupList, () -> displayChoosers.run(null)); - } -} +package pl.mjedynak.idea.plugins.builder.action.handler; + +import com.intellij.openapi.actionSystem.DataContext; +import com.intellij.openapi.editor.Editor; +import com.intellij.psi.PsiClass; +import javax.swing.JList; +import pl.mjedynak.idea.plugins.builder.factory.GoToBuilderPopupListFactory; +import pl.mjedynak.idea.plugins.builder.finder.BuilderFinder; +import pl.mjedynak.idea.plugins.builder.gui.displayer.GoToBuilderPopupDisplayer; +import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; +import pl.mjedynak.idea.plugins.builder.verifier.BuilderVerifier; + +public class GoToBuilderActionHandler extends AbstractBuilderActionHandler { + + public GoToBuilderActionHandler( + PsiHelper psiHelper, + BuilderVerifier builderVerifier, + BuilderFinder builderFinder, + GoToBuilderPopupDisplayer popupDisplayer, + GoToBuilderPopupListFactory popupListFactory, + DisplayChoosers displayChoosersRunnable) { + super(psiHelper, builderVerifier, builderFinder, popupDisplayer, popupListFactory, displayChoosersRunnable); + } + + @Override + protected void doActionWhenClassToGoIsFound( + Editor editor, + PsiClass psiClassFromEditor, + DataContext dataContext, + boolean isBuilder, + PsiClass classToGo) { + psiHelper.navigateToClass(classToGo); + } + + @Override + protected void doActionWhenClassToGoIsNotFound( + Editor editor, PsiClass psiClassFromEditor, DataContext dataContext, boolean isBuilder) { + if (!isBuilder) { + displayPopup(editor); + } + } + + @SuppressWarnings("rawtypes") + private void displayPopup(Editor editor) { + JList popupList = popupListFactory.getPopupList(); + popupDisplayer.displayPopupChooser(editor, popupList, () -> displayChoosers.run(null)); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/factory/AbstractPopupListFactory.java b/src/main/java/pl/mjedynak/idea/plugins/builder/factory/AbstractPopupListFactory.java index b2d0452..9fb5914 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/factory/AbstractPopupListFactory.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/factory/AbstractPopupListFactory.java @@ -1,25 +1,25 @@ -package pl.mjedynak.idea.plugins.builder.factory; - -import javax.swing.JList; -import pl.mjedynak.idea.plugins.builder.renderer.ActionCellRenderer; - -public abstract class AbstractPopupListFactory { - - private ActionCellRenderer actionCellRenderer; - - @SuppressWarnings({"unchecked", "rawtypes"}) - public JList getPopupList() { - JList list = createList(); - list.setCellRenderer(cellRenderer()); - return list; - } - - protected abstract JList createList(); - - private ActionCellRenderer cellRenderer() { - if (actionCellRenderer == null) { - actionCellRenderer = new ActionCellRenderer(); - } - return actionCellRenderer; - } -} +package pl.mjedynak.idea.plugins.builder.factory; + +import javax.swing.JList; +import pl.mjedynak.idea.plugins.builder.renderer.ActionCellRenderer; + +public abstract class AbstractPopupListFactory { + + private ActionCellRenderer actionCellRenderer; + + @SuppressWarnings({"unchecked", "rawtypes"}) + public JList getPopupList() { + JList list = createList(); + list.setCellRenderer(cellRenderer()); + return list; + } + + protected abstract JList createList(); + + private ActionCellRenderer cellRenderer() { + if (actionCellRenderer == null) { + actionCellRenderer = new ActionCellRenderer(); + } + return actionCellRenderer; + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/factory/CreateBuilderDialogFactory.java b/src/main/java/pl/mjedynak/idea/plugins/builder/factory/CreateBuilderDialogFactory.java index 11345d3..29c8dd5 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/factory/CreateBuilderDialogFactory.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/factory/CreateBuilderDialogFactory.java @@ -1,41 +1,41 @@ -package pl.mjedynak.idea.plugins.builder.factory; - -import com.intellij.openapi.project.Project; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiPackage; -import pl.mjedynak.idea.plugins.builder.gui.CreateBuilderDialog; -import pl.mjedynak.idea.plugins.builder.gui.helper.GuiHelper; -import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; - -public class CreateBuilderDialogFactory { - - private static final String BUILDER_SUFFIX = "Builder"; - private static final String DIALOG_NAME = "CreateBuilder"; - - private final PsiHelper psiHelper; - private final ReferenceEditorComboWithBrowseButtonFactory referenceEditorComboWithBrowseButtonFactory; - private final GuiHelper guiHelper; - - public CreateBuilderDialogFactory( - PsiHelper psiHelper, - ReferenceEditorComboWithBrowseButtonFactory referenceEditorComboWithBrowseButtonFactory, - GuiHelper guiHelper) { - this.psiHelper = psiHelper; - this.referenceEditorComboWithBrowseButtonFactory = referenceEditorComboWithBrowseButtonFactory; - this.guiHelper = guiHelper; - } - - public CreateBuilderDialog createBuilderDialog( - PsiClass sourceClass, Project project, PsiPackage srcPackage, PsiClass existingBuilder) { - return new CreateBuilderDialog( - project, - DIALOG_NAME, - sourceClass, - sourceClass.getName() + BUILDER_SUFFIX, - srcPackage, - psiHelper, - guiHelper, - referenceEditorComboWithBrowseButtonFactory, - existingBuilder); - } -} +package pl.mjedynak.idea.plugins.builder.factory; + +import com.intellij.openapi.project.Project; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiPackage; +import pl.mjedynak.idea.plugins.builder.gui.CreateBuilderDialog; +import pl.mjedynak.idea.plugins.builder.gui.helper.GuiHelper; +import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; + +public class CreateBuilderDialogFactory { + + private static final String BUILDER_SUFFIX = "Builder"; + private static final String DIALOG_NAME = "CreateBuilder"; + + private final PsiHelper psiHelper; + private final ReferenceEditorComboWithBrowseButtonFactory referenceEditorComboWithBrowseButtonFactory; + private final GuiHelper guiHelper; + + public CreateBuilderDialogFactory( + PsiHelper psiHelper, + ReferenceEditorComboWithBrowseButtonFactory referenceEditorComboWithBrowseButtonFactory, + GuiHelper guiHelper) { + this.psiHelper = psiHelper; + this.referenceEditorComboWithBrowseButtonFactory = referenceEditorComboWithBrowseButtonFactory; + this.guiHelper = guiHelper; + } + + public CreateBuilderDialog createBuilderDialog( + PsiClass sourceClass, Project project, PsiPackage srcPackage, PsiClass existingBuilder) { + return new CreateBuilderDialog( + project, + DIALOG_NAME, + sourceClass, + sourceClass.getName() + BUILDER_SUFFIX, + srcPackage, + psiHelper, + guiHelper, + referenceEditorComboWithBrowseButtonFactory, + existingBuilder); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/factory/GenerateBuilderPopupListFactory.java b/src/main/java/pl/mjedynak/idea/plugins/builder/factory/GenerateBuilderPopupListFactory.java index 652c6aa..47e5105 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/factory/GenerateBuilderPopupListFactory.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/factory/GenerateBuilderPopupListFactory.java @@ -1,17 +1,17 @@ -package pl.mjedynak.idea.plugins.builder.factory; - -import static java.util.Arrays.asList; - -import com.intellij.ui.components.JBList; -import javax.swing.JList; -import pl.mjedynak.idea.plugins.builder.action.GoToBuilderAdditionalAction; -import pl.mjedynak.idea.plugins.builder.action.RegenerateBuilderAdditionalAction; - -public class GenerateBuilderPopupListFactory extends AbstractPopupListFactory { - - @Override - @SuppressWarnings({"unchecked", "rawtypes"}) - protected JList createList() { - return new JBList(asList(new GoToBuilderAdditionalAction(), new RegenerateBuilderAdditionalAction())); - } -} +package pl.mjedynak.idea.plugins.builder.factory; + +import static java.util.Arrays.asList; + +import com.intellij.ui.components.JBList; +import javax.swing.JList; +import pl.mjedynak.idea.plugins.builder.action.GoToBuilderAdditionalAction; +import pl.mjedynak.idea.plugins.builder.action.RegenerateBuilderAdditionalAction; + +public class GenerateBuilderPopupListFactory extends AbstractPopupListFactory { + + @Override + @SuppressWarnings({"unchecked", "rawtypes"}) + protected JList createList() { + return new JBList(asList(new GoToBuilderAdditionalAction(), new RegenerateBuilderAdditionalAction())); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/factory/GoToBuilderPopupListFactory.java b/src/main/java/pl/mjedynak/idea/plugins/builder/factory/GoToBuilderPopupListFactory.java index cb95a61..d5ed04d 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/factory/GoToBuilderPopupListFactory.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/factory/GoToBuilderPopupListFactory.java @@ -1,16 +1,16 @@ -package pl.mjedynak.idea.plugins.builder.factory; - -import static java.util.Collections.singletonList; - -import com.intellij.ui.components.JBList; -import javax.swing.JList; -import pl.mjedynak.idea.plugins.builder.action.GenerateBuilderAdditionalAction; - -public class GoToBuilderPopupListFactory extends AbstractPopupListFactory { - - @Override - @SuppressWarnings({"unchecked", "rawtypes"}) - protected JList createList() { - return new JBList(singletonList(new GenerateBuilderAdditionalAction())); - } -} +package pl.mjedynak.idea.plugins.builder.factory; + +import static java.util.Collections.singletonList; + +import com.intellij.ui.components.JBList; +import javax.swing.JList; +import pl.mjedynak.idea.plugins.builder.action.GenerateBuilderAdditionalAction; + +public class GoToBuilderPopupListFactory extends AbstractPopupListFactory { + + @Override + @SuppressWarnings({"unchecked", "rawtypes"}) + protected JList createList() { + return new JBList(singletonList(new GenerateBuilderAdditionalAction())); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/factory/MemberChooserDialogFactory.java b/src/main/java/pl/mjedynak/idea/plugins/builder/factory/MemberChooserDialogFactory.java index 283308e..a1c339d 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/factory/MemberChooserDialogFactory.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/factory/MemberChooserDialogFactory.java @@ -1,28 +1,28 @@ -package pl.mjedynak.idea.plugins.builder.factory; - -import com.intellij.codeInsight.generation.PsiElementClassMember; -import com.intellij.ide.util.MemberChooser; -import com.intellij.openapi.project.Project; -import java.util.List; - -public class MemberChooserDialogFactory { - - static final String TITLE = "Select Fields to Be Available in Builder"; - - public com.intellij.ide.util.MemberChooser> getMemberChooserDialog( - List> elements, Project project) { - PsiElementClassMember[] psiElementClassMembers = elements.toArray(new PsiElementClassMember[0]); - MemberChooser> memberChooserDialog = - createNewInstance(project, psiElementClassMembers); - memberChooserDialog.setCopyJavadocVisible(false); - memberChooserDialog.selectElements(psiElementClassMembers); - memberChooserDialog.setTitle(TITLE); - return memberChooserDialog; - } - - MemberChooser> createNewInstance( - Project project, PsiElementClassMember[] psiElementClassMembers) { - return new com.intellij.ide.util.MemberChooser>( - psiElementClassMembers, false, true, project, false); - } -} +package pl.mjedynak.idea.plugins.builder.factory; + +import com.intellij.codeInsight.generation.PsiElementClassMember; +import com.intellij.ide.util.MemberChooser; +import com.intellij.openapi.project.Project; +import java.util.List; + +public class MemberChooserDialogFactory { + + static final String TITLE = "Select Fields to Be Available in Builder"; + + public com.intellij.ide.util.MemberChooser> getMemberChooserDialog( + List> elements, Project project) { + PsiElementClassMember[] psiElementClassMembers = elements.toArray(new PsiElementClassMember[0]); + MemberChooser> memberChooserDialog = + createNewInstance(project, psiElementClassMembers); + memberChooserDialog.setCopyJavadocVisible(false); + memberChooserDialog.selectElements(psiElementClassMembers); + memberChooserDialog.setTitle(TITLE); + return memberChooserDialog; + } + + MemberChooser> createNewInstance( + Project project, PsiElementClassMember[] psiElementClassMembers) { + return new com.intellij.ide.util.MemberChooser>( + psiElementClassMembers, false, true, project, false); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/factory/PackageChooserDialogFactory.java b/src/main/java/pl/mjedynak/idea/plugins/builder/factory/PackageChooserDialogFactory.java index 0a6e0ea..2c9f55c 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/factory/PackageChooserDialogFactory.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/factory/PackageChooserDialogFactory.java @@ -1,15 +1,15 @@ -package pl.mjedynak.idea.plugins.builder.factory; - -import com.intellij.ide.util.PackageChooserDialog; -import com.intellij.openapi.project.Project; - -public class PackageChooserDialogFactory { - - public PackageChooserDialog getPackageChooserDialog(String message, Project project) { - return createNewInstance(message, project); - } - - PackageChooserDialog createNewInstance(String message, Project project) { - return new PackageChooserDialog(message, project); - } -} +package pl.mjedynak.idea.plugins.builder.factory; + +import com.intellij.ide.util.PackageChooserDialog; +import com.intellij.openapi.project.Project; + +public class PackageChooserDialogFactory { + + public PackageChooserDialog getPackageChooserDialog(String message, Project project) { + return createNewInstance(message, project); + } + + PackageChooserDialog createNewInstance(String message, Project project) { + return new PackageChooserDialog(message, project); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/factory/PopupChooserBuilderFactory.java b/src/main/java/pl/mjedynak/idea/plugins/builder/factory/PopupChooserBuilderFactory.java index 33c1cdb..c520493 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/factory/PopupChooserBuilderFactory.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/factory/PopupChooserBuilderFactory.java @@ -1,11 +1,11 @@ -package pl.mjedynak.idea.plugins.builder.factory; - -import com.intellij.openapi.ui.popup.PopupChooserBuilder; -import javax.swing.JList; - -public class PopupChooserBuilderFactory { - - public PopupChooserBuilder getPopupChooserBuilder(JList list) { - return new PopupChooserBuilder<>(list); - } -} +package pl.mjedynak.idea.plugins.builder.factory; + +import com.intellij.openapi.ui.popup.PopupChooserBuilder; +import javax.swing.JList; + +public class PopupChooserBuilderFactory { + + public PopupChooserBuilder getPopupChooserBuilder(JList list) { + return new PopupChooserBuilder<>(list); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/factory/PsiElementClassMemberFactory.java b/src/main/java/pl/mjedynak/idea/plugins/builder/factory/PsiElementClassMemberFactory.java index e4e3716..9dec7d4 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/factory/PsiElementClassMemberFactory.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/factory/PsiElementClassMemberFactory.java @@ -1,12 +1,12 @@ -package pl.mjedynak.idea.plugins.builder.factory; - -import com.intellij.codeInsight.generation.PsiElementClassMember; -import com.intellij.codeInsight.generation.PsiFieldMember; -import com.intellij.psi.PsiField; - -public class PsiElementClassMemberFactory { - - public PsiElementClassMember createPsiElementClassMember(PsiField psiField) { - return new PsiFieldMember(psiField); - } -} +package pl.mjedynak.idea.plugins.builder.factory; + +import com.intellij.codeInsight.generation.PsiElementClassMember; +import com.intellij.codeInsight.generation.PsiFieldMember; +import com.intellij.psi.PsiField; + +public class PsiElementClassMemberFactory { + + public PsiElementClassMember createPsiElementClassMember(PsiField psiField) { + return new PsiFieldMember(psiField); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/factory/PsiFieldsForBuilderFactory.java b/src/main/java/pl/mjedynak/idea/plugins/builder/factory/PsiFieldsForBuilderFactory.java index 23892d0..08bb503 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/factory/PsiFieldsForBuilderFactory.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/factory/PsiFieldsForBuilderFactory.java @@ -1,75 +1,75 @@ -package pl.mjedynak.idea.plugins.builder.factory; - -import com.google.common.collect.Lists; -import com.intellij.codeInsight.generation.PsiElementClassMember; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiField; -import com.intellij.psi.PsiMethod; -import java.util.List; -import pl.mjedynak.idea.plugins.builder.psi.BestConstructorSelector; -import pl.mjedynak.idea.plugins.builder.psi.model.PsiFieldsForBuilder; -import pl.mjedynak.idea.plugins.builder.verifier.PsiFieldVerifier; - -public class PsiFieldsForBuilderFactory { - - private final PsiFieldVerifier psiFieldVerifier; - private final BestConstructorSelector bestConstructorSelector; - - public PsiFieldsForBuilderFactory( - PsiFieldVerifier psiFieldVerifier, BestConstructorSelector bestConstructorSelector) { - this.psiFieldVerifier = psiFieldVerifier; - this.bestConstructorSelector = bestConstructorSelector; - } - - @SuppressWarnings("rawtypes") - public PsiFieldsForBuilder createPsiFieldsForBuilder( - List> psiElementClassMembers, PsiClass psiClass) { - List allSelectedPsiFields = Lists.newArrayList(); - List psiFieldsFoundInSetters = Lists.newArrayList(); - for (PsiElementClassMember psiElementClassMember : psiElementClassMembers) { - PsiElement psiElement = psiElementClassMember.getPsiElement(); - if (psiElement instanceof PsiField) { - allSelectedPsiFields.add((PsiField) psiElement); - if (psiFieldVerifier.isSetInSetterMethod((PsiField) psiElement, psiClass)) { - psiFieldsFoundInSetters.add((PsiField) psiElement); - } - } - } - List psiFieldsToFindInConstructor = getSubList(allSelectedPsiFields, psiFieldsFoundInSetters); - List psiFieldsForConstructor = Lists.newArrayList(); - PsiMethod bestConstructor = bestConstructorSelector.getBestConstructor(psiFieldsToFindInConstructor, psiClass); - if (bestConstructor != null) { - buildPsiFieldsForConstructor(psiFieldsForConstructor, allSelectedPsiFields, bestConstructor); - } - List psiFieldsForSetters = getSubList(psiFieldsFoundInSetters, psiFieldsForConstructor); - - return new PsiFieldsForBuilder( - psiFieldsForSetters, psiFieldsForConstructor, allSelectedPsiFields, bestConstructor); - } - - private void buildPsiFieldsForConstructor( - List psiFieldsForConstructor, List allSelectedPsiFields, PsiMethod bestConstructor) { - for (PsiField selectedPsiField : allSelectedPsiFields) { - if (psiFieldVerifier.checkConstructor(selectedPsiField, bestConstructor)) { - psiFieldsForConstructor.add(selectedPsiField); - } - } - } - - private List getSubList(List inputList, List listToRemove) { - List newList = Lists.newArrayList(); - for (PsiField inputPsiField : inputList) { - boolean setterMustBeAdded = true; - for (PsiField psiFieldToRemove : listToRemove) { - if (psiFieldToRemove.getName().equals(inputPsiField.getName())) { - setterMustBeAdded = false; - } - } - if (setterMustBeAdded) { - newList.add(inputPsiField); - } - } - return newList; - } -} +package pl.mjedynak.idea.plugins.builder.factory; + +import com.google.common.collect.Lists; +import com.intellij.codeInsight.generation.PsiElementClassMember; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiField; +import com.intellij.psi.PsiMethod; +import java.util.List; +import pl.mjedynak.idea.plugins.builder.psi.BestConstructorSelector; +import pl.mjedynak.idea.plugins.builder.psi.model.PsiFieldsForBuilder; +import pl.mjedynak.idea.plugins.builder.verifier.PsiFieldVerifier; + +public class PsiFieldsForBuilderFactory { + + private final PsiFieldVerifier psiFieldVerifier; + private final BestConstructorSelector bestConstructorSelector; + + public PsiFieldsForBuilderFactory( + PsiFieldVerifier psiFieldVerifier, BestConstructorSelector bestConstructorSelector) { + this.psiFieldVerifier = psiFieldVerifier; + this.bestConstructorSelector = bestConstructorSelector; + } + + @SuppressWarnings("rawtypes") + public PsiFieldsForBuilder createPsiFieldsForBuilder( + List> psiElementClassMembers, PsiClass psiClass) { + List allSelectedPsiFields = Lists.newArrayList(); + List psiFieldsFoundInSetters = Lists.newArrayList(); + for (PsiElementClassMember psiElementClassMember : psiElementClassMembers) { + PsiElement psiElement = psiElementClassMember.getPsiElement(); + if (psiElement instanceof PsiField) { + allSelectedPsiFields.add((PsiField) psiElement); + if (psiFieldVerifier.isSetInSetterMethod((PsiField) psiElement, psiClass)) { + psiFieldsFoundInSetters.add((PsiField) psiElement); + } + } + } + List psiFieldsToFindInConstructor = getSubList(allSelectedPsiFields, psiFieldsFoundInSetters); + List psiFieldsForConstructor = Lists.newArrayList(); + PsiMethod bestConstructor = bestConstructorSelector.getBestConstructor(psiFieldsToFindInConstructor, psiClass); + if (bestConstructor != null) { + buildPsiFieldsForConstructor(psiFieldsForConstructor, allSelectedPsiFields, bestConstructor); + } + List psiFieldsForSetters = getSubList(psiFieldsFoundInSetters, psiFieldsForConstructor); + + return new PsiFieldsForBuilder( + psiFieldsForSetters, psiFieldsForConstructor, allSelectedPsiFields, bestConstructor); + } + + private void buildPsiFieldsForConstructor( + List psiFieldsForConstructor, List allSelectedPsiFields, PsiMethod bestConstructor) { + for (PsiField selectedPsiField : allSelectedPsiFields) { + if (psiFieldVerifier.checkConstructor(selectedPsiField, bestConstructor)) { + psiFieldsForConstructor.add(selectedPsiField); + } + } + } + + private List getSubList(List inputList, List listToRemove) { + List newList = Lists.newArrayList(); + for (PsiField inputPsiField : inputList) { + boolean setterMustBeAdded = true; + for (PsiField psiFieldToRemove : listToRemove) { + if (psiFieldToRemove.getName().equals(inputPsiField.getName())) { + setterMustBeAdded = false; + } + } + if (setterMustBeAdded) { + newList.add(inputPsiField); + } + } + return newList; + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/factory/PsiManagerFactory.java b/src/main/java/pl/mjedynak/idea/plugins/builder/factory/PsiManagerFactory.java index 3f8fca4..9e36e83 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/factory/PsiManagerFactory.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/factory/PsiManagerFactory.java @@ -1,11 +1,11 @@ -package pl.mjedynak.idea.plugins.builder.factory; - -import com.intellij.openapi.project.Project; -import com.intellij.psi.PsiManager; - -public class PsiManagerFactory { - - public PsiManager getPsiManager(Project project) { - return PsiManager.getInstance(project); - } -} +package pl.mjedynak.idea.plugins.builder.factory; + +import com.intellij.openapi.project.Project; +import com.intellij.psi.PsiManager; + +public class PsiManagerFactory { + + public PsiManager getPsiManager(Project project) { + return PsiManager.getInstance(project); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/factory/ReferenceEditorComboWithBrowseButtonFactory.java b/src/main/java/pl/mjedynak/idea/plugins/builder/factory/ReferenceEditorComboWithBrowseButtonFactory.java index 64f6618..5d36178 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/factory/ReferenceEditorComboWithBrowseButtonFactory.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/factory/ReferenceEditorComboWithBrowseButtonFactory.java @@ -1,12 +1,12 @@ -package pl.mjedynak.idea.plugins.builder.factory; - -import com.intellij.openapi.project.Project; -import com.intellij.ui.ReferenceEditorComboWithBrowseButton; - -public class ReferenceEditorComboWithBrowseButtonFactory { - - public ReferenceEditorComboWithBrowseButton getReferenceEditorComboWithBrowseButton( - Project project, String packageName, String recentsKey) { - return new ReferenceEditorComboWithBrowseButton(null, packageName, project, true, recentsKey); - } -} +package pl.mjedynak.idea.plugins.builder.factory; + +import com.intellij.openapi.project.Project; +import com.intellij.ui.ReferenceEditorComboWithBrowseButton; + +public class ReferenceEditorComboWithBrowseButtonFactory { + + public ReferenceEditorComboWithBrowseButton getReferenceEditorComboWithBrowseButton( + Project project, String packageName, String recentsKey) { + return new ReferenceEditorComboWithBrowseButton(null, packageName, project, true, recentsKey); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/finder/BuilderFinder.java b/src/main/java/pl/mjedynak/idea/plugins/builder/finder/BuilderFinder.java index 3eaf9bd..756e37f 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/finder/BuilderFinder.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/finder/BuilderFinder.java @@ -1,55 +1,55 @@ -package pl.mjedynak.idea.plugins.builder.finder; - -import com.intellij.psi.PsiClass; -import java.util.Objects; - -public class BuilderFinder { - - static final String SEARCH_PATTERN = "Builder"; - public static final String EMPTY_STRING = ""; - - private final ClassFinder classFinder; - - public BuilderFinder(ClassFinder classFinder) { - this.classFinder = classFinder; - } - - public PsiClass findBuilderForClass(PsiClass psiClass) { - PsiClass innerBuilderClass = tryFindInnerBuilder(psiClass); - if (innerBuilderClass != null) { - return innerBuilderClass; - } else { - String searchName = psiClass.getName() + SEARCH_PATTERN; - return findClass(psiClass, searchName); - } - } - - private PsiClass tryFindInnerBuilder(PsiClass psiClass) { - PsiClass innerBuilderClass = null; - PsiClass[] allInnerClasses = psiClass.getAllInnerClasses(); - for (PsiClass innerClass : allInnerClasses) { - if (Objects.requireNonNull(innerClass.getName()).contains(SEARCH_PATTERN)) { - innerBuilderClass = innerClass; - break; - } - } - return innerBuilderClass; - } - - public PsiClass findClassForBuilder(PsiClass psiClass) { - String searchName = Objects.requireNonNull(psiClass.getName()).replaceFirst(SEARCH_PATTERN, EMPTY_STRING); - return findClass(psiClass, searchName); - } - - private PsiClass findClass(PsiClass psiClass, String searchName) { - PsiClass result = null; - if (typeIsCorrect(psiClass)) { - result = classFinder.findClass(searchName, psiClass.getProject()); - } - return result; - } - - private boolean typeIsCorrect(PsiClass psiClass) { - return !psiClass.isAnnotationType() && !psiClass.isEnum() && !psiClass.isInterface(); - } -} +package pl.mjedynak.idea.plugins.builder.finder; + +import com.intellij.psi.PsiClass; +import java.util.Objects; + +public class BuilderFinder { + + static final String SEARCH_PATTERN = "Builder"; + public static final String EMPTY_STRING = ""; + + private final ClassFinder classFinder; + + public BuilderFinder(ClassFinder classFinder) { + this.classFinder = classFinder; + } + + public PsiClass findBuilderForClass(PsiClass psiClass) { + PsiClass innerBuilderClass = tryFindInnerBuilder(psiClass); + if (innerBuilderClass != null) { + return innerBuilderClass; + } else { + String searchName = psiClass.getName() + SEARCH_PATTERN; + return findClass(psiClass, searchName); + } + } + + private PsiClass tryFindInnerBuilder(PsiClass psiClass) { + PsiClass innerBuilderClass = null; + PsiClass[] allInnerClasses = psiClass.getAllInnerClasses(); + for (PsiClass innerClass : allInnerClasses) { + if (Objects.requireNonNull(innerClass.getName()).contains(SEARCH_PATTERN)) { + innerBuilderClass = innerClass; + break; + } + } + return innerBuilderClass; + } + + public PsiClass findClassForBuilder(PsiClass psiClass) { + String searchName = Objects.requireNonNull(psiClass.getName()).replaceFirst(SEARCH_PATTERN, EMPTY_STRING); + return findClass(psiClass, searchName); + } + + private PsiClass findClass(PsiClass psiClass, String searchName) { + PsiClass result = null; + if (typeIsCorrect(psiClass)) { + result = classFinder.findClass(searchName, psiClass.getProject()); + } + return result; + } + + private boolean typeIsCorrect(PsiClass psiClass) { + return !psiClass.isAnnotationType() && !psiClass.isEnum() && !psiClass.isInterface(); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/finder/ClassFinder.java b/src/main/java/pl/mjedynak/idea/plugins/builder/finder/ClassFinder.java index 5b246c5..0c714b3 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/finder/ClassFinder.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/finder/ClassFinder.java @@ -1,29 +1,29 @@ -package pl.mjedynak.idea.plugins.builder.finder; - -import com.intellij.openapi.project.Project; -import com.intellij.psi.PsiClass; -import com.intellij.psi.search.GlobalSearchScope; -import com.intellij.psi.search.PsiShortNamesCache; -import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; - -public class ClassFinder { - - private final PsiHelper psiHelper; - - public ClassFinder(PsiHelper psiHelper) { - this.psiHelper = psiHelper; - } - - public PsiClass findClass(String pattern, Project project) { - PsiClass result; - GlobalSearchScope projectScope = GlobalSearchScope.projectScope(project); - PsiShortNamesCache psiShortNamesCache = psiHelper.getPsiShortNamesCache(project); - PsiClass[] classesArray = psiShortNamesCache.getClassesByName(pattern, projectScope); - result = getPsiClass(classesArray); - return result; - } - - private PsiClass getPsiClass(PsiClass[] classesArray) { - return (classesArray != null && classesArray.length != 0) ? classesArray[0] : null; - } -} +package pl.mjedynak.idea.plugins.builder.finder; + +import com.intellij.openapi.project.Project; +import com.intellij.psi.PsiClass; +import com.intellij.psi.search.GlobalSearchScope; +import com.intellij.psi.search.PsiShortNamesCache; +import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; + +public class ClassFinder { + + private final PsiHelper psiHelper; + + public ClassFinder(PsiHelper psiHelper) { + this.psiHelper = psiHelper; + } + + public PsiClass findClass(String pattern, Project project) { + PsiClass result; + GlobalSearchScope projectScope = GlobalSearchScope.projectScope(project); + PsiShortNamesCache psiShortNamesCache = psiHelper.getPsiShortNamesCache(project); + PsiClass[] classesArray = psiShortNamesCache.getClassesByName(pattern, projectScope); + result = getPsiClass(classesArray); + return result; + } + + private PsiClass getPsiClass(PsiClass[] classesArray) { + return (classesArray != null && classesArray.length != 0) ? classesArray[0] : null; + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/gui/ChooserDisplayerActionListener.java b/src/main/java/pl/mjedynak/idea/plugins/builder/gui/ChooserDisplayerActionListener.java index 58a9b83..ef17431 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/gui/ChooserDisplayerActionListener.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/gui/ChooserDisplayerActionListener.java @@ -1,38 +1,38 @@ -package pl.mjedynak.idea.plugins.builder.gui; - -import com.intellij.codeInsight.CodeInsightBundle; -import com.intellij.ide.util.PackageChooserDialog; -import com.intellij.openapi.project.Project; -import com.intellij.psi.PsiPackage; -import com.intellij.ui.ReferenceEditorComboWithBrowseButton; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import pl.mjedynak.idea.plugins.builder.factory.PackageChooserDialogFactory; - -public class ChooserDisplayerActionListener implements ActionListener { - - private final ReferenceEditorComboWithBrowseButton comboWithBrowseButton; - private final PackageChooserDialogFactory packageChooserDialogFactory; - private final Project project; - - public ChooserDisplayerActionListener( - ReferenceEditorComboWithBrowseButton comboWithBrowseButton, - PackageChooserDialogFactory packageChooserDialogFactory, - Project project) { - this.comboWithBrowseButton = comboWithBrowseButton; - this.packageChooserDialogFactory = packageChooserDialogFactory; - this.project = project; - } - - @Override - public void actionPerformed(ActionEvent e) { - PackageChooserDialog chooser = packageChooserDialogFactory.getPackageChooserDialog( - CodeInsightBundle.message("dialog.create.class.package.chooser.title"), project); - chooser.selectPackage(comboWithBrowseButton.getText()); - chooser.show(); - PsiPackage aPackage = chooser.getSelectedPackage(); - if (aPackage != null) { - comboWithBrowseButton.setText(aPackage.getQualifiedName()); - } - } -} +package pl.mjedynak.idea.plugins.builder.gui; + +import com.intellij.codeInsight.CodeInsightBundle; +import com.intellij.ide.util.PackageChooserDialog; +import com.intellij.openapi.project.Project; +import com.intellij.psi.PsiPackage; +import com.intellij.ui.ReferenceEditorComboWithBrowseButton; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import pl.mjedynak.idea.plugins.builder.factory.PackageChooserDialogFactory; + +public class ChooserDisplayerActionListener implements ActionListener { + + private final ReferenceEditorComboWithBrowseButton comboWithBrowseButton; + private final PackageChooserDialogFactory packageChooserDialogFactory; + private final Project project; + + public ChooserDisplayerActionListener( + ReferenceEditorComboWithBrowseButton comboWithBrowseButton, + PackageChooserDialogFactory packageChooserDialogFactory, + Project project) { + this.comboWithBrowseButton = comboWithBrowseButton; + this.packageChooserDialogFactory = packageChooserDialogFactory; + this.project = project; + } + + @Override + public void actionPerformed(ActionEvent e) { + PackageChooserDialog chooser = packageChooserDialogFactory.getPackageChooserDialog( + CodeInsightBundle.message("dialog.create.class.package.chooser.title"), project); + chooser.selectPackage(comboWithBrowseButton.getText()); + chooser.show(); + PsiPackage aPackage = chooser.getSelectedPackage(); + if (aPackage != null) { + comboWithBrowseButton.setText(aPackage.getQualifiedName()); + } + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/gui/CreateBuilderDialog.java b/src/main/java/pl/mjedynak/idea/plugins/builder/gui/CreateBuilderDialog.java index 42326f1..d1d39ce 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/gui/CreateBuilderDialog.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/gui/CreateBuilderDialog.java @@ -1,389 +1,389 @@ -package pl.mjedynak.idea.plugins.builder.gui; - -import com.intellij.CommonBundle; -import com.intellij.codeInsight.CodeInsightBundle; -import com.intellij.openapi.actionSystem.AnAction; -import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.actionSystem.CustomShortcutSet; -import com.intellij.openapi.command.CommandProcessor; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.ui.DialogWrapper; -import com.intellij.openapi.ui.Messages; -import com.intellij.psi.JavaPsiFacade; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiDirectory; -import com.intellij.psi.PsiMethod; -import com.intellij.psi.PsiPackage; -import com.intellij.ui.DocumentAdapter; -import com.intellij.ui.IdeBorderFactory; -import com.intellij.ui.RecentsManager; -import com.intellij.ui.ReferenceEditorComboWithBrowseButton; -import com.intellij.util.IncorrectOperationException; -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.FontMetrics; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.InputEvent; -import java.awt.event.KeyEvent; -import javax.swing.Action; -import javax.swing.JCheckBox; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.KeyStroke; -import javax.swing.event.DocumentEvent; -import org.jetbrains.annotations.NotNull; -import pl.mjedynak.idea.plugins.builder.factory.PackageChooserDialogFactory; -import pl.mjedynak.idea.plugins.builder.factory.ReferenceEditorComboWithBrowseButtonFactory; -import pl.mjedynak.idea.plugins.builder.gui.helper.GuiHelper; -import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; -import pl.mjedynak.idea.plugins.builder.settings.BuilderGeneratorSettingsState; - -public class CreateBuilderDialog extends DialogWrapper { - - static final String RECENTS_KEY = "CreateBuilderDialog.RecentsKey"; - private static final int WIDTH = 40; - - private static BuilderGeneratorSettingsState defaultStates = BuilderGeneratorSettingsState.getInstance(); - - private final PsiHelper psiHelper; - private final GuiHelper guiHelper; - private final Project project; - private final PsiClass sourceClass; - private final JTextField targetClassNameField; - private final JTextField targetMethodPrefix; - private final ReferenceEditorComboWithBrowseButton targetPackageField; - private final PsiClass existingBuilder; - private PsiDirectory targetDirectory; - private JCheckBox innerBuilder; - private JCheckBox butMethod; - private JCheckBox useSingleField; - private JCheckBox copyConstructor; - - public CreateBuilderDialog( - Project project, - String title, - PsiClass sourceClass, - String targetClassName, - PsiPackage targetPackage, - PsiHelper psiHelper, - GuiHelper guiHelper, - ReferenceEditorComboWithBrowseButtonFactory referenceEditorComboWithBrowseButtonFactory, - PsiClass existingBuilder) { - super(project, true); - this.psiHelper = psiHelper; - this.guiHelper = guiHelper; - this.project = project; - this.sourceClass = sourceClass; - this.existingBuilder = existingBuilder; - targetClassNameField = new JTextField(targetClassName); - targetMethodPrefix = new JTextField(defaultStates.defaultMethodPrefix); - setPreferredSize(targetClassNameField); - setPreferredSize(targetMethodPrefix); - - String targetPackageName = (targetPackage != null) ? targetPackage.getQualifiedName() : ""; - targetPackageField = referenceEditorComboWithBrowseButtonFactory.getReferenceEditorComboWithBrowseButton( - project, targetPackageName, RECENTS_KEY); - targetPackageField.addActionListener( - new ChooserDisplayerActionListener(targetPackageField, new PackageChooserDialogFactory(), project)); - setTitle(title); - } - - @Override - public void show() { - super.init(); - super.show(); - } - - private void setPreferredSize(JTextField field) { - Dimension size = field.getPreferredSize(); - FontMetrics fontMetrics = field.getFontMetrics(field.getFont()); - size.width = fontMetrics.charWidth('a') * WIDTH; - field.setPreferredSize(size); - } - - @NotNull - @Override - protected Action[] createActions() { - return new Action[] {getOKAction(), getCancelAction(), getHelpAction()}; - } - - @Override - protected JComponent createCenterPanel() { - JPanel panel = new JPanel(new GridBagLayout()); - GridBagConstraints gbConstraints = new GridBagConstraints(); - - panel.setBorder(IdeBorderFactory.createBorder()); - - // Class name - gbConstraints.insets = new Insets(4, 8, 4, 8); - gbConstraints.gridx = 0; - gbConstraints.weightx = 0; - gbConstraints.gridwidth = 1; - gbConstraints.fill = GridBagConstraints.HORIZONTAL; - gbConstraints.anchor = GridBagConstraints.WEST; - panel.add(new JLabel("Class name"), gbConstraints); - - gbConstraints.insets = new Insets(4, 8, 4, 8); - gbConstraints.gridx = 1; - gbConstraints.weightx = 1; - gbConstraints.gridwidth = 1; - gbConstraints.fill = GridBagConstraints.HORIZONTAL; - gbConstraints.anchor = GridBagConstraints.WEST; - panel.add(targetClassNameField, gbConstraints); - targetClassNameField.getDocument().addDocumentListener(new DocumentAdapter() { - @Override - protected void textChanged(DocumentEvent e) { - getOKAction() - .setEnabled(JavaPsiFacade.getInstance(project) - .getNameHelper() - .isIdentifier(getClassName())); - } - }); - // Class name - - // Method prefix - gbConstraints.insets = new Insets(4, 8, 4, 8); - gbConstraints.gridx = 0; - gbConstraints.gridy = 2; - gbConstraints.weightx = 0; - gbConstraints.gridwidth = 1; - gbConstraints.fill = GridBagConstraints.HORIZONTAL; - gbConstraints.anchor = GridBagConstraints.WEST; - panel.add(new JLabel("Method prefix"), gbConstraints); - - gbConstraints.insets = new Insets(4, 8, 4, 8); - gbConstraints.gridx = 1; - gbConstraints.weightx = 1; - gbConstraints.gridwidth = 1; - gbConstraints.fill = GridBagConstraints.HORIZONTAL; - gbConstraints.anchor = GridBagConstraints.WEST; - panel.add(targetMethodPrefix, gbConstraints); - // Method prefix - - // Destination package - gbConstraints.gridx = 0; - gbConstraints.gridy = 3; - gbConstraints.weightx = 0; - gbConstraints.gridwidth = 1; - panel.add( - new JLabel(CodeInsightBundle.message("dialog.create.class.destination.package.label")), gbConstraints); - - gbConstraints.gridx = 1; - gbConstraints.weightx = 1; - - AnAction clickAction = new AnAction() { - @Override - public void actionPerformed(AnActionEvent e) { - targetPackageField.getButton().doClick(); - } - }; - clickAction.registerCustomShortcutSet( - new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.SHIFT_DOWN_MASK)), - targetPackageField.getChildComponent()); - - addInnerPanelForDestinationPackageField(panel, gbConstraints); - // Destination package - - // Inner builder - gbConstraints.insets = new Insets(4, 8, 4, 8); - gbConstraints.gridx = 0; - gbConstraints.weightx = 0; - gbConstraints.gridy = 4; - gbConstraints.fill = GridBagConstraints.HORIZONTAL; - gbConstraints.anchor = GridBagConstraints.WEST; - panel.add(new JLabel("Inner builder"), gbConstraints); - - gbConstraints.insets = new Insets(4, 8, 4, 8); - gbConstraints.gridx = 1; - gbConstraints.weightx = 1; - gbConstraints.gridwidth = 1; - gbConstraints.fill = GridBagConstraints.HORIZONTAL; - gbConstraints.anchor = GridBagConstraints.WEST; - - innerBuilder = new JCheckBox(); - innerBuilder.setSelected(defaultStates.isInnerBuilder); - innerBuilder.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - targetPackageField.setEnabled(!innerBuilder.isSelected()); - } - }); - panel.add(innerBuilder, gbConstraints); - // Inner builder - - // but method - gbConstraints.insets = new Insets(4, 8, 4, 8); - gbConstraints.gridx = 0; - gbConstraints.weightx = 0; - gbConstraints.gridy = 5; - gbConstraints.fill = GridBagConstraints.HORIZONTAL; - gbConstraints.anchor = GridBagConstraints.WEST; - panel.add(new JLabel("'but' method"), gbConstraints); - - gbConstraints.insets = new Insets(4, 8, 4, 8); - gbConstraints.gridx = 1; - gbConstraints.weightx = 1; - gbConstraints.gridwidth = 1; - gbConstraints.fill = GridBagConstraints.HORIZONTAL; - gbConstraints.anchor = GridBagConstraints.WEST; - butMethod = new JCheckBox(); - butMethod.setSelected(defaultStates.isButMethod); - panel.add(butMethod, gbConstraints); - // but method - - // useSingleField - gbConstraints.insets = new Insets(4, 8, 4, 8); - gbConstraints.gridx = 0; - gbConstraints.weightx = 0; - gbConstraints.gridy = 6; - gbConstraints.fill = GridBagConstraints.HORIZONTAL; - gbConstraints.anchor = GridBagConstraints.WEST; - panel.add(new JLabel("Use single field"), gbConstraints); - - gbConstraints.insets = new Insets(4, 8, 4, 8); - gbConstraints.gridx = 1; - gbConstraints.weightx = 1; - gbConstraints.gridwidth = 1; - gbConstraints.fill = GridBagConstraints.HORIZONTAL; - gbConstraints.anchor = GridBagConstraints.WEST; - useSingleField = new JCheckBox(); - useSingleField.setSelected(defaultStates.isUseSinglePrefix); - panel.add(useSingleField, gbConstraints); - // useSingleField - - // copy constructor - gbConstraints.insets = new Insets(4, 8, 4, 8); - gbConstraints.gridx = 0; - gbConstraints.weightx = 0; - gbConstraints.gridy = 7; - gbConstraints.fill = GridBagConstraints.HORIZONTAL; - gbConstraints.anchor = GridBagConstraints.WEST; - panel.add(new JLabel("Add copy constructor"), gbConstraints); - - gbConstraints.insets = new Insets(4, 8, 4, 8); - gbConstraints.gridx = 1; - gbConstraints.weightx = 1; - gbConstraints.gridwidth = 1; - gbConstraints.fill = GridBagConstraints.HORIZONTAL; - gbConstraints.anchor = GridBagConstraints.WEST; - copyConstructor = new JCheckBox(); - copyConstructor.setSelected(defaultStates.isAddCopyConstructor); - panel.add(copyConstructor, gbConstraints); - // copy constructor - - return panel; - } - - private void addInnerPanelForDestinationPackageField(JPanel panel, GridBagConstraints gbConstraints) { - JPanel innerPanel = createInnerPanelForDestinationPackageField(); - panel.add(innerPanel, gbConstraints); - } - - private JPanel createInnerPanelForDestinationPackageField() { - JPanel innerPanel = new JPanel(new BorderLayout()); - innerPanel.add(targetPackageField, BorderLayout.CENTER); - return innerPanel; - } - - @Override - protected void doOKAction() { - registerEntry(RECENTS_KEY, targetPackageField.getText()); - Module module = psiHelper.findModuleForPsiClass(sourceClass, project); - if (module == null) { - throw new IllegalStateException("Cannot find module for class " + sourceClass.getName()); - } - try { - checkIfSourceClassHasZeroArgsConstructorWhenUsingSingleField(); - checkIfClassCanBeCreated(module); - callSuper(); - } catch (IncorrectOperationException e) { - guiHelper.showMessageDialog(project, e.getMessage(), CommonBundle.getErrorTitle(), Messages.getErrorIcon()); - } - } - - void checkIfSourceClassHasZeroArgsConstructorWhenUsingSingleField() { - if (useSingleField()) { - PsiMethod[] constructors = sourceClass.getConstructors(); - if (constructors.length == 0) { - return; - } - for (PsiMethod constructor : constructors) { - if (constructor.getParameterList().getParametersCount() == 0) { - return; - } - } - throw new IncorrectOperationException( - String.format("%s must define a default constructor", sourceClass.getName())); - } - } - - void checkIfClassCanBeCreated(Module module) { - if (!isInnerBuilder()) { - SelectDirectory selectDirectory = - new SelectDirectory(this, psiHelper, module, getPackageName(), getClassName(), existingBuilder); - executeCommand(selectDirectory); - } - } - - void registerEntry(String key, String entry) { - RecentsManager.getInstance(project).registerRecentEntry(key, entry); - } - - void callSuper() { - super.doOKAction(); - } - - void executeCommand(SelectDirectory selectDirectory) { - CommandProcessor.getInstance() - .executeCommand(project, selectDirectory, CodeInsightBundle.message("create.directory.command"), null); - } - - private String getPackageName() { - String name = targetPackageField.getText(); - return (name != null) ? name.trim() : ""; - } - - @Override - public JComponent getPreferredFocusedComponent() { - return targetClassNameField; - } - - public String getClassName() { - return targetClassNameField.getText(); - } - - public String getMethodPrefix() { - return targetMethodPrefix.getText(); - } - - public boolean isInnerBuilder() { - return innerBuilder.isSelected(); - } - - public boolean hasButMethod() { - return butMethod.isSelected(); - } - - public boolean useSingleField() { - return useSingleField.isSelected(); - } - - public boolean hasAddCopyConstructor() { - return copyConstructor.isSelected(); - } - - public PsiDirectory getTargetDirectory() { - return targetDirectory; - } - - public void setTargetDirectory(PsiDirectory targetDirectory) { - this.targetDirectory = targetDirectory; - } -} +package pl.mjedynak.idea.plugins.builder.gui; + +import com.intellij.CommonBundle; +import com.intellij.codeInsight.CodeInsightBundle; +import com.intellij.openapi.actionSystem.AnAction; +import com.intellij.openapi.actionSystem.AnActionEvent; +import com.intellij.openapi.actionSystem.CustomShortcutSet; +import com.intellij.openapi.command.CommandProcessor; +import com.intellij.openapi.module.Module; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.ui.DialogWrapper; +import com.intellij.openapi.ui.Messages; +import com.intellij.psi.JavaPsiFacade; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiDirectory; +import com.intellij.psi.PsiMethod; +import com.intellij.psi.PsiPackage; +import com.intellij.ui.DocumentAdapter; +import com.intellij.ui.IdeBorderFactory; +import com.intellij.ui.RecentsManager; +import com.intellij.ui.ReferenceEditorComboWithBrowseButton; +import com.intellij.util.IncorrectOperationException; +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FontMetrics; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.InputEvent; +import java.awt.event.KeyEvent; +import javax.swing.Action; +import javax.swing.JCheckBox; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.KeyStroke; +import javax.swing.event.DocumentEvent; +import org.jetbrains.annotations.NotNull; +import pl.mjedynak.idea.plugins.builder.factory.PackageChooserDialogFactory; +import pl.mjedynak.idea.plugins.builder.factory.ReferenceEditorComboWithBrowseButtonFactory; +import pl.mjedynak.idea.plugins.builder.gui.helper.GuiHelper; +import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; +import pl.mjedynak.idea.plugins.builder.settings.BuilderGeneratorSettingsState; + +public class CreateBuilderDialog extends DialogWrapper { + + static final String RECENTS_KEY = "CreateBuilderDialog.RecentsKey"; + private static final int WIDTH = 40; + + private static BuilderGeneratorSettingsState defaultStates = BuilderGeneratorSettingsState.getInstance(); + + private final PsiHelper psiHelper; + private final GuiHelper guiHelper; + private final Project project; + private final PsiClass sourceClass; + private final JTextField targetClassNameField; + private final JTextField targetMethodPrefix; + private final ReferenceEditorComboWithBrowseButton targetPackageField; + private final PsiClass existingBuilder; + private PsiDirectory targetDirectory; + private JCheckBox innerBuilder; + private JCheckBox butMethod; + private JCheckBox useSingleField; + private JCheckBox copyConstructor; + + public CreateBuilderDialog( + Project project, + String title, + PsiClass sourceClass, + String targetClassName, + PsiPackage targetPackage, + PsiHelper psiHelper, + GuiHelper guiHelper, + ReferenceEditorComboWithBrowseButtonFactory referenceEditorComboWithBrowseButtonFactory, + PsiClass existingBuilder) { + super(project, true); + this.psiHelper = psiHelper; + this.guiHelper = guiHelper; + this.project = project; + this.sourceClass = sourceClass; + this.existingBuilder = existingBuilder; + targetClassNameField = new JTextField(targetClassName); + targetMethodPrefix = new JTextField(defaultStates.defaultMethodPrefix); + setPreferredSize(targetClassNameField); + setPreferredSize(targetMethodPrefix); + + String targetPackageName = (targetPackage != null) ? targetPackage.getQualifiedName() : ""; + targetPackageField = referenceEditorComboWithBrowseButtonFactory.getReferenceEditorComboWithBrowseButton( + project, targetPackageName, RECENTS_KEY); + targetPackageField.addActionListener( + new ChooserDisplayerActionListener(targetPackageField, new PackageChooserDialogFactory(), project)); + setTitle(title); + } + + @Override + public void show() { + super.init(); + super.show(); + } + + private void setPreferredSize(JTextField field) { + Dimension size = field.getPreferredSize(); + FontMetrics fontMetrics = field.getFontMetrics(field.getFont()); + size.width = fontMetrics.charWidth('a') * WIDTH; + field.setPreferredSize(size); + } + + @NotNull + @Override + protected Action[] createActions() { + return new Action[] {getOKAction(), getCancelAction(), getHelpAction()}; + } + + @Override + protected JComponent createCenterPanel() { + JPanel panel = new JPanel(new GridBagLayout()); + GridBagConstraints gbConstraints = new GridBagConstraints(); + + panel.setBorder(IdeBorderFactory.createBorder()); + + // Class name + gbConstraints.insets = new Insets(4, 8, 4, 8); + gbConstraints.gridx = 0; + gbConstraints.weightx = 0; + gbConstraints.gridwidth = 1; + gbConstraints.fill = GridBagConstraints.HORIZONTAL; + gbConstraints.anchor = GridBagConstraints.WEST; + panel.add(new JLabel("Class name"), gbConstraints); + + gbConstraints.insets = new Insets(4, 8, 4, 8); + gbConstraints.gridx = 1; + gbConstraints.weightx = 1; + gbConstraints.gridwidth = 1; + gbConstraints.fill = GridBagConstraints.HORIZONTAL; + gbConstraints.anchor = GridBagConstraints.WEST; + panel.add(targetClassNameField, gbConstraints); + targetClassNameField.getDocument().addDocumentListener(new DocumentAdapter() { + @Override + protected void textChanged(DocumentEvent e) { + getOKAction() + .setEnabled(JavaPsiFacade.getInstance(project) + .getNameHelper() + .isIdentifier(getClassName())); + } + }); + // Class name + + // Method prefix + gbConstraints.insets = new Insets(4, 8, 4, 8); + gbConstraints.gridx = 0; + gbConstraints.gridy = 2; + gbConstraints.weightx = 0; + gbConstraints.gridwidth = 1; + gbConstraints.fill = GridBagConstraints.HORIZONTAL; + gbConstraints.anchor = GridBagConstraints.WEST; + panel.add(new JLabel("Method prefix"), gbConstraints); + + gbConstraints.insets = new Insets(4, 8, 4, 8); + gbConstraints.gridx = 1; + gbConstraints.weightx = 1; + gbConstraints.gridwidth = 1; + gbConstraints.fill = GridBagConstraints.HORIZONTAL; + gbConstraints.anchor = GridBagConstraints.WEST; + panel.add(targetMethodPrefix, gbConstraints); + // Method prefix + + // Destination package + gbConstraints.gridx = 0; + gbConstraints.gridy = 3; + gbConstraints.weightx = 0; + gbConstraints.gridwidth = 1; + panel.add( + new JLabel(CodeInsightBundle.message("dialog.create.class.destination.package.label")), gbConstraints); + + gbConstraints.gridx = 1; + gbConstraints.weightx = 1; + + AnAction clickAction = new AnAction() { + @Override + public void actionPerformed(AnActionEvent e) { + targetPackageField.getButton().doClick(); + } + }; + clickAction.registerCustomShortcutSet( + new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.SHIFT_DOWN_MASK)), + targetPackageField.getChildComponent()); + + addInnerPanelForDestinationPackageField(panel, gbConstraints); + // Destination package + + // Inner builder + gbConstraints.insets = new Insets(4, 8, 4, 8); + gbConstraints.gridx = 0; + gbConstraints.weightx = 0; + gbConstraints.gridy = 4; + gbConstraints.fill = GridBagConstraints.HORIZONTAL; + gbConstraints.anchor = GridBagConstraints.WEST; + panel.add(new JLabel("Inner builder"), gbConstraints); + + gbConstraints.insets = new Insets(4, 8, 4, 8); + gbConstraints.gridx = 1; + gbConstraints.weightx = 1; + gbConstraints.gridwidth = 1; + gbConstraints.fill = GridBagConstraints.HORIZONTAL; + gbConstraints.anchor = GridBagConstraints.WEST; + + innerBuilder = new JCheckBox(); + innerBuilder.setSelected(defaultStates.isInnerBuilder); + innerBuilder.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + targetPackageField.setEnabled(!innerBuilder.isSelected()); + } + }); + panel.add(innerBuilder, gbConstraints); + // Inner builder + + // but method + gbConstraints.insets = new Insets(4, 8, 4, 8); + gbConstraints.gridx = 0; + gbConstraints.weightx = 0; + gbConstraints.gridy = 5; + gbConstraints.fill = GridBagConstraints.HORIZONTAL; + gbConstraints.anchor = GridBagConstraints.WEST; + panel.add(new JLabel("'but' method"), gbConstraints); + + gbConstraints.insets = new Insets(4, 8, 4, 8); + gbConstraints.gridx = 1; + gbConstraints.weightx = 1; + gbConstraints.gridwidth = 1; + gbConstraints.fill = GridBagConstraints.HORIZONTAL; + gbConstraints.anchor = GridBagConstraints.WEST; + butMethod = new JCheckBox(); + butMethod.setSelected(defaultStates.isButMethod); + panel.add(butMethod, gbConstraints); + // but method + + // useSingleField + gbConstraints.insets = new Insets(4, 8, 4, 8); + gbConstraints.gridx = 0; + gbConstraints.weightx = 0; + gbConstraints.gridy = 6; + gbConstraints.fill = GridBagConstraints.HORIZONTAL; + gbConstraints.anchor = GridBagConstraints.WEST; + panel.add(new JLabel("Use single field"), gbConstraints); + + gbConstraints.insets = new Insets(4, 8, 4, 8); + gbConstraints.gridx = 1; + gbConstraints.weightx = 1; + gbConstraints.gridwidth = 1; + gbConstraints.fill = GridBagConstraints.HORIZONTAL; + gbConstraints.anchor = GridBagConstraints.WEST; + useSingleField = new JCheckBox(); + useSingleField.setSelected(defaultStates.isUseSinglePrefix); + panel.add(useSingleField, gbConstraints); + // useSingleField + + // copy constructor + gbConstraints.insets = new Insets(4, 8, 4, 8); + gbConstraints.gridx = 0; + gbConstraints.weightx = 0; + gbConstraints.gridy = 7; + gbConstraints.fill = GridBagConstraints.HORIZONTAL; + gbConstraints.anchor = GridBagConstraints.WEST; + panel.add(new JLabel("Add copy constructor"), gbConstraints); + + gbConstraints.insets = new Insets(4, 8, 4, 8); + gbConstraints.gridx = 1; + gbConstraints.weightx = 1; + gbConstraints.gridwidth = 1; + gbConstraints.fill = GridBagConstraints.HORIZONTAL; + gbConstraints.anchor = GridBagConstraints.WEST; + copyConstructor = new JCheckBox(); + copyConstructor.setSelected(defaultStates.isAddCopyConstructor); + panel.add(copyConstructor, gbConstraints); + // copy constructor + + return panel; + } + + private void addInnerPanelForDestinationPackageField(JPanel panel, GridBagConstraints gbConstraints) { + JPanel innerPanel = createInnerPanelForDestinationPackageField(); + panel.add(innerPanel, gbConstraints); + } + + private JPanel createInnerPanelForDestinationPackageField() { + JPanel innerPanel = new JPanel(new BorderLayout()); + innerPanel.add(targetPackageField, BorderLayout.CENTER); + return innerPanel; + } + + @Override + protected void doOKAction() { + registerEntry(RECENTS_KEY, targetPackageField.getText()); + Module module = psiHelper.findModuleForPsiClass(sourceClass, project); + if (module == null) { + throw new IllegalStateException("Cannot find module for class " + sourceClass.getName()); + } + try { + checkIfSourceClassHasZeroArgsConstructorWhenUsingSingleField(); + checkIfClassCanBeCreated(module); + callSuper(); + } catch (IncorrectOperationException e) { + guiHelper.showMessageDialog(project, e.getMessage(), CommonBundle.getErrorTitle(), Messages.getErrorIcon()); + } + } + + void checkIfSourceClassHasZeroArgsConstructorWhenUsingSingleField() { + if (useSingleField()) { + PsiMethod[] constructors = sourceClass.getConstructors(); + if (constructors.length == 0) { + return; + } + for (PsiMethod constructor : constructors) { + if (constructor.getParameterList().getParametersCount() == 0) { + return; + } + } + throw new IncorrectOperationException( + String.format("%s must define a default constructor", sourceClass.getName())); + } + } + + void checkIfClassCanBeCreated(Module module) { + if (!isInnerBuilder()) { + SelectDirectory selectDirectory = + new SelectDirectory(this, psiHelper, module, getPackageName(), getClassName(), existingBuilder); + executeCommand(selectDirectory); + } + } + + void registerEntry(String key, String entry) { + RecentsManager.getInstance(project).registerRecentEntry(key, entry); + } + + void callSuper() { + super.doOKAction(); + } + + void executeCommand(SelectDirectory selectDirectory) { + CommandProcessor.getInstance() + .executeCommand(project, selectDirectory, CodeInsightBundle.message("create.directory.command"), null); + } + + private String getPackageName() { + String name = targetPackageField.getText(); + return (name != null) ? name.trim() : ""; + } + + @Override + public JComponent getPreferredFocusedComponent() { + return targetClassNameField; + } + + public String getClassName() { + return targetClassNameField.getText(); + } + + public String getMethodPrefix() { + return targetMethodPrefix.getText(); + } + + public boolean isInnerBuilder() { + return innerBuilder.isSelected(); + } + + public boolean hasButMethod() { + return butMethod.isSelected(); + } + + public boolean useSingleField() { + return useSingleField.isSelected(); + } + + public boolean hasAddCopyConstructor() { + return copyConstructor.isSelected(); + } + + public PsiDirectory getTargetDirectory() { + return targetDirectory; + } + + public void setTargetDirectory(PsiDirectory targetDirectory) { + this.targetDirectory = targetDirectory; + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/gui/SelectDirectory.java b/src/main/java/pl/mjedynak/idea/plugins/builder/gui/SelectDirectory.java index 7727e82..4a1bbfa 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/gui/SelectDirectory.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/gui/SelectDirectory.java @@ -1,63 +1,63 @@ -package pl.mjedynak.idea.plugins.builder.gui; - -import com.intellij.openapi.module.Module; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiDirectory; -import com.intellij.util.IncorrectOperationException; -import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; - -public class SelectDirectory implements Runnable { - - private final CreateBuilderDialog createBuilderDialog; - private final PsiHelper psiHelper; - private final Module module; - private final String packageName; - private final String className; - private final PsiClass existingBuilder; - - public SelectDirectory( - CreateBuilderDialog createBuilderDialog, - PsiHelper psiHelper, - Module module, - String packageName, - String className, - PsiClass existingBuilder) { - this.createBuilderDialog = createBuilderDialog; - this.psiHelper = psiHelper; - this.module = module; - this.packageName = packageName; - this.className = className; - this.existingBuilder = existingBuilder; - } - - @Override - public void run() { - PsiDirectory targetDirectory = psiHelper.getDirectoryFromModuleAndPackageName(module, packageName); - if (targetDirectory != null) { - throwExceptionIfClassCannotBeCreated(targetDirectory); - createBuilderDialog.setTargetDirectory(targetDirectory); - } - } - - private void throwExceptionIfClassCannotBeCreated(PsiDirectory targetDirectory) { - if (!isClassToCreateSameAsBuilderToDelete(targetDirectory)) { - String errorString = psiHelper.checkIfClassCanBeCreated(targetDirectory, className); - if (errorString != null) { - throw new IncorrectOperationException(errorString); - } - } - } - - private boolean isClassToCreateSameAsBuilderToDelete(PsiDirectory targetDirectory) { - return existingBuilder != null - && existingBuilder.getContainingFile() != null - && existingBuilder.getContainingFile().getContainingDirectory() != null - && existingBuilder - .getContainingFile() - .getContainingDirectory() - .getName() - .equals(targetDirectory.getName()) - && existingBuilder.getName() != null - && existingBuilder.getName().equals(className); - } -} +package pl.mjedynak.idea.plugins.builder.gui; + +import com.intellij.openapi.module.Module; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiDirectory; +import com.intellij.util.IncorrectOperationException; +import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; + +public class SelectDirectory implements Runnable { + + private final CreateBuilderDialog createBuilderDialog; + private final PsiHelper psiHelper; + private final Module module; + private final String packageName; + private final String className; + private final PsiClass existingBuilder; + + public SelectDirectory( + CreateBuilderDialog createBuilderDialog, + PsiHelper psiHelper, + Module module, + String packageName, + String className, + PsiClass existingBuilder) { + this.createBuilderDialog = createBuilderDialog; + this.psiHelper = psiHelper; + this.module = module; + this.packageName = packageName; + this.className = className; + this.existingBuilder = existingBuilder; + } + + @Override + public void run() { + PsiDirectory targetDirectory = psiHelper.getDirectoryFromModuleAndPackageName(module, packageName); + if (targetDirectory != null) { + throwExceptionIfClassCannotBeCreated(targetDirectory); + createBuilderDialog.setTargetDirectory(targetDirectory); + } + } + + private void throwExceptionIfClassCannotBeCreated(PsiDirectory targetDirectory) { + if (!isClassToCreateSameAsBuilderToDelete(targetDirectory)) { + String errorString = psiHelper.checkIfClassCanBeCreated(targetDirectory, className); + if (errorString != null) { + throw new IncorrectOperationException(errorString); + } + } + } + + private boolean isClassToCreateSameAsBuilderToDelete(PsiDirectory targetDirectory) { + return existingBuilder != null + && existingBuilder.getContainingFile() != null + && existingBuilder.getContainingFile().getContainingDirectory() != null + && existingBuilder + .getContainingFile() + .getContainingDirectory() + .getName() + .equals(targetDirectory.getName()) + && existingBuilder.getName() != null + && existingBuilder.getName().equals(className); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/gui/displayer/AbstractPopupDisplayer.java b/src/main/java/pl/mjedynak/idea/plugins/builder/gui/displayer/AbstractPopupDisplayer.java index 0467ade..c0156ca 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/gui/displayer/AbstractPopupDisplayer.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/gui/displayer/AbstractPopupDisplayer.java @@ -1,27 +1,27 @@ -package pl.mjedynak.idea.plugins.builder.gui.displayer; - -import com.intellij.openapi.editor.Editor; -import com.intellij.openapi.ui.popup.PopupChooserBuilder; -import javax.swing.JList; -import pl.mjedynak.idea.plugins.builder.factory.PopupChooserBuilderFactory; - -public abstract class AbstractPopupDisplayer { - - private final PopupChooserBuilderFactory popupChooserBuilderFactory; - - public AbstractPopupDisplayer(PopupChooserBuilderFactory popupChooserBuilderFactory) { - this.popupChooserBuilderFactory = popupChooserBuilderFactory; - } - - @SuppressWarnings("rawtypes") - public void displayPopupChooser(Editor editor, JList list, Runnable runnable) { - PopupChooserBuilder builder = popupChooserBuilderFactory.getPopupChooserBuilder(list); - builder.setTitle(getTitle()) - .setItemChoosenCallback(runnable) - .setMovable(true) - .createPopup() - .showInBestPositionFor(editor); - } - - protected abstract String getTitle(); -} +package pl.mjedynak.idea.plugins.builder.gui.displayer; + +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.ui.popup.PopupChooserBuilder; +import javax.swing.JList; +import pl.mjedynak.idea.plugins.builder.factory.PopupChooserBuilderFactory; + +public abstract class AbstractPopupDisplayer { + + private final PopupChooserBuilderFactory popupChooserBuilderFactory; + + public AbstractPopupDisplayer(PopupChooserBuilderFactory popupChooserBuilderFactory) { + this.popupChooserBuilderFactory = popupChooserBuilderFactory; + } + + @SuppressWarnings("rawtypes") + public void displayPopupChooser(Editor editor, JList list, Runnable runnable) { + PopupChooserBuilder builder = popupChooserBuilderFactory.getPopupChooserBuilder(list); + builder.setTitle(getTitle()) + .setItemChoosenCallback(runnable) + .setMovable(true) + .createPopup() + .showInBestPositionFor(editor); + } + + protected abstract String getTitle(); +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/gui/displayer/GenerateBuilderPopupDisplayer.java b/src/main/java/pl/mjedynak/idea/plugins/builder/gui/displayer/GenerateBuilderPopupDisplayer.java index 1db960f..be35803 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/gui/displayer/GenerateBuilderPopupDisplayer.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/gui/displayer/GenerateBuilderPopupDisplayer.java @@ -1,17 +1,17 @@ -package pl.mjedynak.idea.plugins.builder.gui.displayer; - -import pl.mjedynak.idea.plugins.builder.factory.PopupChooserBuilderFactory; - -public class GenerateBuilderPopupDisplayer extends AbstractPopupDisplayer { - - private static final String TITLE = "Builder already exists"; - - public GenerateBuilderPopupDisplayer(PopupChooserBuilderFactory popupChooserBuilderFactory) { - super(popupChooserBuilderFactory); - } - - @Override - protected String getTitle() { - return TITLE; - } -} +package pl.mjedynak.idea.plugins.builder.gui.displayer; + +import pl.mjedynak.idea.plugins.builder.factory.PopupChooserBuilderFactory; + +public class GenerateBuilderPopupDisplayer extends AbstractPopupDisplayer { + + private static final String TITLE = "Builder already exists"; + + public GenerateBuilderPopupDisplayer(PopupChooserBuilderFactory popupChooserBuilderFactory) { + super(popupChooserBuilderFactory); + } + + @Override + protected String getTitle() { + return TITLE; + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/gui/displayer/GoToBuilderPopupDisplayer.java b/src/main/java/pl/mjedynak/idea/plugins/builder/gui/displayer/GoToBuilderPopupDisplayer.java index ac59916..09483e5 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/gui/displayer/GoToBuilderPopupDisplayer.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/gui/displayer/GoToBuilderPopupDisplayer.java @@ -1,17 +1,17 @@ -package pl.mjedynak.idea.plugins.builder.gui.displayer; - -import pl.mjedynak.idea.plugins.builder.factory.PopupChooserBuilderFactory; - -public class GoToBuilderPopupDisplayer extends AbstractPopupDisplayer { - - private static final String TITLE = "Builder not found"; - - public GoToBuilderPopupDisplayer(PopupChooserBuilderFactory popupChooserBuilderFactory) { - super(popupChooserBuilderFactory); - } - - @Override - protected String getTitle() { - return TITLE; - } -} +package pl.mjedynak.idea.plugins.builder.gui.displayer; + +import pl.mjedynak.idea.plugins.builder.factory.PopupChooserBuilderFactory; + +public class GoToBuilderPopupDisplayer extends AbstractPopupDisplayer { + + private static final String TITLE = "Builder not found"; + + public GoToBuilderPopupDisplayer(PopupChooserBuilderFactory popupChooserBuilderFactory) { + super(popupChooserBuilderFactory); + } + + @Override + protected String getTitle() { + return TITLE; + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/gui/helper/GuiHelper.java b/src/main/java/pl/mjedynak/idea/plugins/builder/gui/helper/GuiHelper.java index 4593559..63773d0 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/gui/helper/GuiHelper.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/gui/helper/GuiHelper.java @@ -1,24 +1,24 @@ -package pl.mjedynak.idea.plugins.builder.gui.helper; - -import com.intellij.codeInsight.CodeInsightUtil; -import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.ui.Messages; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiFile; -import javax.swing.Icon; - -public class GuiHelper { - - public void showMessageDialog(Project project, String message, String title, Icon icon) { - Messages.showMessageDialog(project, message, title, icon); - } - - public void includeCurrentPlaceAsChangePlace(Project project) { - IdeDocumentHistory.getInstance(project).includeCurrentPlaceAsChangePlace(); - } - - public void positionCursor(Project project, PsiFile psiFile, PsiElement psiElement) { - CodeInsightUtil.positionCursor(project, psiFile, psiElement); - } -} +package pl.mjedynak.idea.plugins.builder.gui.helper; + +import com.intellij.codeInsight.CodeInsightUtil; +import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.ui.Messages; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiFile; +import javax.swing.Icon; + +public class GuiHelper { + + public void showMessageDialog(Project project, String message, String title, Icon icon) { + Messages.showMessageDialog(project, message, title, icon); + } + + public void includeCurrentPlaceAsChangePlace(Project project) { + IdeDocumentHistory.getInstance(project).includeCurrentPlaceAsChangePlace(); + } + + public void positionCursor(Project project, PsiFile psiFile, PsiElement psiElement) { + CodeInsightUtil.positionCursor(project, psiFile, psiElement); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/psi/BestConstructorSelector.java b/src/main/java/pl/mjedynak/idea/plugins/builder/psi/BestConstructorSelector.java index fad062a..3f8c71b 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/psi/BestConstructorSelector.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/psi/BestConstructorSelector.java @@ -1,138 +1,138 @@ -package pl.mjedynak.idea.plugins.builder.psi; - -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiField; -import com.intellij.psi.PsiMethod; -import java.util.Collection; -import java.util.List; -import java.util.TreeSet; -import org.jetbrains.annotations.NotNull; -import pl.mjedynak.idea.plugins.builder.verifier.PsiFieldVerifier; - -public class BestConstructorSelector { - - private final PsiFieldVerifier psiFieldVerifier; - - private List constructorsWithEqualParameterCount; - private TreeSet constructorsWithHigherParameterCount; - private List constructorsWithLowerParameterCount; - - public BestConstructorSelector(PsiFieldVerifier psiFieldVerifier) { - this.psiFieldVerifier = psiFieldVerifier; - } - - public PsiMethod getBestConstructor(Collection psiFieldsToFindInConstructor, PsiClass psiClass) { - int fieldsToFindCount = psiFieldsToFindInConstructor.size(); - createConstructorLists(psiFieldsToFindInConstructor, psiClass); - - computeNumberOfMatchingFields(constructorsWithEqualParameterCount, psiFieldsToFindInConstructor); - PsiMethod bestConstructor = - findConstructorWithAllFieldsToFind(constructorsWithEqualParameterCount, fieldsToFindCount); - if (bestConstructor != null) { - return bestConstructor; - } - - computeNumberOfMatchingFields(constructorsWithHigherParameterCount, psiFieldsToFindInConstructor); - bestConstructor = findConstructorWithAllFieldsToFind(constructorsWithHigherParameterCount, fieldsToFindCount); - if (bestConstructor != null) { - return bestConstructor; - } - - computeNumberOfMatchingFields(constructorsWithLowerParameterCount, psiFieldsToFindInConstructor); - return findConstructorWithMaximumOfFieldsToFind(); - } - - private void createConstructorLists(Collection psiFieldsToFindInConstructor, PsiClass psiClass) { - constructorsWithEqualParameterCount = Lists.newArrayList(); - constructorsWithHigherParameterCount = Sets.newTreeSet(); - constructorsWithLowerParameterCount = Lists.newArrayList(); - PsiMethod[] constructors = psiClass.getConstructors(); - for (PsiMethod constructor : constructors) { - int parameterCount = constructor.getParameterList().getParametersCount(); - if (parameterCount > psiFieldsToFindInConstructor.size()) { - constructorsWithHigherParameterCount.add(new ConstructorWithExtraData(constructor)); - } else if (parameterCount == psiFieldsToFindInConstructor.size()) { - constructorsWithEqualParameterCount.add(new ConstructorWithExtraData(constructor)); - } else if (parameterCount >= 0) { - constructorsWithLowerParameterCount.add(new ConstructorWithExtraData(constructor)); - } - } - } - - private void computeNumberOfMatchingFields( - Iterable constuctorsWithExtraData, - Iterable psiFieldsToFindInConstructor) { - for (ConstructorWithExtraData constructorWithExtraData : constuctorsWithExtraData) { - int matchingFieldsCount = 0; - for (PsiField psiField : psiFieldsToFindInConstructor) { - if (psiFieldVerifier.checkConstructor(psiField, constructorWithExtraData.getConstructor())) { - matchingFieldsCount++; - } - } - constructorWithExtraData.setMatchingFieldsCount(matchingFieldsCount); - } - } - - private PsiMethod findConstructorWithAllFieldsToFind( - Iterable constructorsWithExtraData, int fieldsToFindCount) { - for (ConstructorWithExtraData constructorWithExtraData : constructorsWithExtraData) { - if (constructorWithExtraData.getMatchingFieldsCount() == fieldsToFindCount) { - return constructorWithExtraData.getConstructor(); - } - } - return null; - } - - private PsiMethod findConstructorWithMaximumOfFieldsToFind() { - Iterable allConstructors = Iterables.concat( - constructorsWithEqualParameterCount, - constructorsWithHigherParameterCount, - constructorsWithLowerParameterCount); - int matchingFieldCount = -1; - int parameterCount = 0; - PsiMethod bestConstructor = null; - for (ConstructorWithExtraData constructor : allConstructors) { - if (constructor.getMatchingFieldsCount() > matchingFieldCount - || constructor.getMatchingFieldsCount() == matchingFieldCount - && constructor.getParametersCount() < parameterCount) { - bestConstructor = constructor.getConstructor(); - matchingFieldCount = constructor.getMatchingFieldsCount(); - parameterCount = constructor.getParametersCount(); - } - } - return bestConstructor; - } - - private static class ConstructorWithExtraData implements Comparable { - private final PsiMethod constructor; - private Integer matchingFieldsCount; - - ConstructorWithExtraData(PsiMethod constructor) { - this.constructor = constructor; - } - - @Override - public int compareTo(@NotNull ConstructorWithExtraData constructorToCompare) { - return this.getParametersCount().compareTo(constructorToCompare.getParametersCount()); - } - - PsiMethod getConstructor() { - return constructor; - } - - Integer getMatchingFieldsCount() { - return matchingFieldsCount; - } - - void setMatchingFieldsCount(Integer matchingFieldsCount) { - this.matchingFieldsCount = matchingFieldsCount; - } - - Integer getParametersCount() { - return constructor == null ? null : constructor.getParameterList().getParametersCount(); - } - } -} +package pl.mjedynak.idea.plugins.builder.psi; + +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiField; +import com.intellij.psi.PsiMethod; +import java.util.Collection; +import java.util.List; +import java.util.TreeSet; +import org.jetbrains.annotations.NotNull; +import pl.mjedynak.idea.plugins.builder.verifier.PsiFieldVerifier; + +public class BestConstructorSelector { + + private final PsiFieldVerifier psiFieldVerifier; + + private List constructorsWithEqualParameterCount; + private TreeSet constructorsWithHigherParameterCount; + private List constructorsWithLowerParameterCount; + + public BestConstructorSelector(PsiFieldVerifier psiFieldVerifier) { + this.psiFieldVerifier = psiFieldVerifier; + } + + public PsiMethod getBestConstructor(Collection psiFieldsToFindInConstructor, PsiClass psiClass) { + int fieldsToFindCount = psiFieldsToFindInConstructor.size(); + createConstructorLists(psiFieldsToFindInConstructor, psiClass); + + computeNumberOfMatchingFields(constructorsWithEqualParameterCount, psiFieldsToFindInConstructor); + PsiMethod bestConstructor = + findConstructorWithAllFieldsToFind(constructorsWithEqualParameterCount, fieldsToFindCount); + if (bestConstructor != null) { + return bestConstructor; + } + + computeNumberOfMatchingFields(constructorsWithHigherParameterCount, psiFieldsToFindInConstructor); + bestConstructor = findConstructorWithAllFieldsToFind(constructorsWithHigherParameterCount, fieldsToFindCount); + if (bestConstructor != null) { + return bestConstructor; + } + + computeNumberOfMatchingFields(constructorsWithLowerParameterCount, psiFieldsToFindInConstructor); + return findConstructorWithMaximumOfFieldsToFind(); + } + + private void createConstructorLists(Collection psiFieldsToFindInConstructor, PsiClass psiClass) { + constructorsWithEqualParameterCount = Lists.newArrayList(); + constructorsWithHigherParameterCount = Sets.newTreeSet(); + constructorsWithLowerParameterCount = Lists.newArrayList(); + PsiMethod[] constructors = psiClass.getConstructors(); + for (PsiMethod constructor : constructors) { + int parameterCount = constructor.getParameterList().getParametersCount(); + if (parameterCount > psiFieldsToFindInConstructor.size()) { + constructorsWithHigherParameterCount.add(new ConstructorWithExtraData(constructor)); + } else if (parameterCount == psiFieldsToFindInConstructor.size()) { + constructorsWithEqualParameterCount.add(new ConstructorWithExtraData(constructor)); + } else if (parameterCount >= 0) { + constructorsWithLowerParameterCount.add(new ConstructorWithExtraData(constructor)); + } + } + } + + private void computeNumberOfMatchingFields( + Iterable constuctorsWithExtraData, + Iterable psiFieldsToFindInConstructor) { + for (ConstructorWithExtraData constructorWithExtraData : constuctorsWithExtraData) { + int matchingFieldsCount = 0; + for (PsiField psiField : psiFieldsToFindInConstructor) { + if (psiFieldVerifier.checkConstructor(psiField, constructorWithExtraData.getConstructor())) { + matchingFieldsCount++; + } + } + constructorWithExtraData.setMatchingFieldsCount(matchingFieldsCount); + } + } + + private PsiMethod findConstructorWithAllFieldsToFind( + Iterable constructorsWithExtraData, int fieldsToFindCount) { + for (ConstructorWithExtraData constructorWithExtraData : constructorsWithExtraData) { + if (constructorWithExtraData.getMatchingFieldsCount() == fieldsToFindCount) { + return constructorWithExtraData.getConstructor(); + } + } + return null; + } + + private PsiMethod findConstructorWithMaximumOfFieldsToFind() { + Iterable allConstructors = Iterables.concat( + constructorsWithEqualParameterCount, + constructorsWithHigherParameterCount, + constructorsWithLowerParameterCount); + int matchingFieldCount = -1; + int parameterCount = 0; + PsiMethod bestConstructor = null; + for (ConstructorWithExtraData constructor : allConstructors) { + if (constructor.getMatchingFieldsCount() > matchingFieldCount + || constructor.getMatchingFieldsCount() == matchingFieldCount + && constructor.getParametersCount() < parameterCount) { + bestConstructor = constructor.getConstructor(); + matchingFieldCount = constructor.getMatchingFieldsCount(); + parameterCount = constructor.getParametersCount(); + } + } + return bestConstructor; + } + + private static class ConstructorWithExtraData implements Comparable { + private final PsiMethod constructor; + private Integer matchingFieldsCount; + + ConstructorWithExtraData(PsiMethod constructor) { + this.constructor = constructor; + } + + @Override + public int compareTo(@NotNull ConstructorWithExtraData constructorToCompare) { + return this.getParametersCount().compareTo(constructorToCompare.getParametersCount()); + } + + PsiMethod getConstructor() { + return constructor; + } + + Integer getMatchingFieldsCount() { + return matchingFieldsCount; + } + + void setMatchingFieldsCount(Integer matchingFieldsCount) { + this.matchingFieldsCount = matchingFieldsCount; + } + + Integer getParametersCount() { + return constructor == null ? null : constructor.getParameterList().getParametersCount(); + } + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/psi/BuilderPsiClassBuilder.java b/src/main/java/pl/mjedynak/idea/plugins/builder/psi/BuilderPsiClassBuilder.java index 23afea6..acd0034 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/psi/BuilderPsiClassBuilder.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/psi/BuilderPsiClassBuilder.java @@ -1,310 +1,310 @@ -package pl.mjedynak.idea.plugins.builder.psi; - -import static com.intellij.openapi.util.text.StringUtil.isVowel; - -import com.intellij.psi.JavaDirectoryService; -import com.intellij.psi.JavaPsiFacade; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiElementFactory; -import com.intellij.psi.PsiField; -import com.intellij.psi.PsiMethod; -import com.intellij.psi.PsiModifier; -import com.intellij.psi.PsiModifierList; -import com.intellij.psi.PsiParameter; -import com.intellij.psi.PsiType; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Set; -import org.apache.commons.lang3.StringUtils; -import pl.mjedynak.idea.plugins.builder.settings.CodeStyleSettings; -import pl.mjedynak.idea.plugins.builder.verifier.PsiFieldVerifier; -import pl.mjedynak.idea.plugins.builder.writer.BuilderContext; - -public class BuilderPsiClassBuilder { - - private static final String SPACE = " "; - private static final String A_PREFIX = " a"; - private static final String AN_PREFIX = " an"; - private static final String SEMICOLON = ","; - - private final PsiHelper psiHelper = new PsiHelper(); - private final PsiFieldsModifier psiFieldsModifier = new PsiFieldsModifier(); - private final PsiFieldVerifier psiFieldVerifier = new PsiFieldVerifier(); - private final CodeStyleSettings codeStyleSettings = new CodeStyleSettings(); - private ButMethodCreator butMethodCreator; - private CopyConstructorCreator copyConstructorCreator; - private MethodCreator methodCreator; - - private PsiClass srcClass = null; - private String builderClassName = null; - - private List psiFieldsForSetters = null; - private List psiFieldsForConstructor = null; - private List allSelectedPsiFields = null; - private PsiMethod bestConstructor = null; - - private PsiClass builderClass = null; - private PsiElementFactory elementFactory = null; - private String srcClassName = null; - private String srcClassFieldName = null; - - private boolean useSingleField = false; - private boolean isInline = false; - private boolean copyConstructor = false; - - public BuilderPsiClassBuilder aBuilder(BuilderContext context) { - initializeFields(context); - JavaDirectoryService javaDirectoryService = psiHelper.getJavaDirectoryService(); - builderClass = javaDirectoryService.createClass(context.getTargetDirectory(), builderClassName); - PsiModifierList modifierList = builderClass.getModifierList(); - modifierList.setModifierProperty(PsiModifier.FINAL, true); - return this; - } - - public BuilderPsiClassBuilder anInnerBuilder(BuilderContext context) { - initializeFields(context); - builderClass = elementFactory.createClass(builderClassName); - PsiModifierList modifierList = builderClass.getModifierList(); - modifierList.setModifierProperty(PsiModifier.FINAL, true); - modifierList.setModifierProperty(PsiModifier.STATIC, true); - return this; - } - - private void initializeFields(BuilderContext context) { - JavaPsiFacade javaPsiFacade = psiHelper.getJavaPsiFacade(context.getProject()); - elementFactory = javaPsiFacade.getElementFactory(); - srcClass = context.getPsiClassFromEditor(); - builderClassName = context.getClassName(); - srcClassName = context.getPsiClassFromEditor().getName(); - srcClassFieldName = StringUtils.uncapitalize(srcClassName); - psiFieldsForSetters = context.getPsiFieldsForBuilder().getFieldsForSetters(); - psiFieldsForConstructor = context.getPsiFieldsForBuilder().getFieldsForConstructor(); - allSelectedPsiFields = context.getPsiFieldsForBuilder().getAllSelectedFields(); - useSingleField = context.useSingleField(); - bestConstructor = context.getPsiFieldsForBuilder().getBestConstructor(); - methodCreator = new MethodCreator(elementFactory, builderClassName); - butMethodCreator = new ButMethodCreator(elementFactory); - copyConstructorCreator = new CopyConstructorCreator(elementFactory); - isInline = allSelectedPsiFields.size() == psiFieldsForConstructor.size(); - copyConstructor = context.hasAddCopyConstructor(); - } - - public BuilderPsiClassBuilder withFields() { - if (useSingleField) { - String fieldText = "private " + srcClassName + " " + srcClassFieldName + ";"; - PsiField singleField = elementFactory.createFieldFromText(fieldText, srcClass); - builderClass.add(singleField); - } else if (isInnerBuilder(builderClass)) { - psiFieldsModifier.modifyFieldsForInnerClass(allSelectedPsiFields, builderClass); - } else { - psiFieldsModifier.modifyFields(psiFieldsForSetters, psiFieldsForConstructor, builderClass); - } - return this; - } - - public BuilderPsiClassBuilder withConstructor() { - PsiMethod constructor; - if (useSingleField) { - constructor = elementFactory.createMethodFromText( - builderClassName + "(){ " + srcClassFieldName + " = new " + srcClassName + "(); }", srcClass); - } else { - constructor = elementFactory.createConstructor(); - } - - constructor - .getModifierList() - .setModifierProperty(copyConstructor ? PsiModifier.PUBLIC : PsiModifier.PRIVATE, true); - - builderClass.add(constructor); - return this; - } - - public BuilderPsiClassBuilder withInitializingMethod() { - String prefix = isVowel(srcClassName.toLowerCase(Locale.ENGLISH).charAt(0)) ? AN_PREFIX : A_PREFIX; - PsiMethod staticMethod = elementFactory.createMethodFromText( - "public static " + builderClassName + prefix + srcClassName + "() { return new " + builderClassName - + "(); }", - srcClass); - builderClass.add(staticMethod); - return this; - } - - public BuilderPsiClassBuilder withSetMethods(String methodPrefix) { - if (useSingleField || isInnerBuilder(builderClass)) { - for (PsiField psiFieldForAssignment : allSelectedPsiFields) { - createAndAddMethod(psiFieldForAssignment, methodPrefix); - } - } else { - for (PsiField psiFieldForSetter : psiFieldsForSetters) { - createAndAddMethod(psiFieldForSetter, methodPrefix); - } - for (PsiField psiFieldForConstructor : psiFieldsForConstructor) { - createAndAddMethod(psiFieldForConstructor, methodPrefix); - } - } - return this; - } - - private boolean isInnerBuilder(PsiClass aClass) { - return aClass.hasModifierProperty(PsiModifier.STATIC); - } - - public BuilderPsiClassBuilder withButMethod() { - PsiMethod method = - butMethodCreator.butMethod(builderClassName, builderClass, srcClass, srcClassFieldName, useSingleField); - builderClass.add(method); - return this; - } - - public BuilderPsiClassBuilder withCopyConstructor() { - final PsiMethod method = copyConstructorCreator.copyConstructor( - builderClass, srcClass, isInnerBuilder(builderClass), useSingleField); - builderClass.add(method); - return this; - } - - private void createAndAddMethod(PsiField psiField, String methodPrefix) { - builderClass.add(methodCreator.createMethod(psiField, methodPrefix, srcClassFieldName, useSingleField)); - } - - public PsiClass build() { - if (useSingleField) { - return buildUseSingleField(); - } else if (isInline) { - return buildIsInline(); - } else { - return buildDefault(); - } - } - - private PsiClass buildUseSingleField() { - String buildMethodText = "public " + srcClassName + " build() { " + "return " + srcClassFieldName + ";" + " }"; - PsiMethod buildMethod = elementFactory.createMethodFromText(buildMethodText, srcClass); - builderClass.add(buildMethod); - return builderClass; - } - - private PsiClass buildIsInline() { - StringBuilder buildMethodText = new StringBuilder(); - buildMethodText.append("public ").append(srcClassName).append(" build() { "); - buildMethodText.append("return "); - appendConstructor(buildMethodText); - buildMethodText.append(" }"); - PsiMethod buildMethod = elementFactory.createMethodFromText(buildMethodText.toString(), srcClass); - builderClass.add(buildMethod); - return builderClass; - } - - private PsiClass buildDefault() { - StringBuilder buildMethodText = new StringBuilder(); - buildMethodText.append("public ").append(srcClassName).append(" build() { "); - buildMethodText - .append(srcClassName) - .append(SPACE) - .append(srcClassFieldName) - .append(" = "); - appendConstructor(buildMethodText); - appendSetMethodsOrAssignments(buildMethodText); - buildMethodText.append("return ").append(srcClassFieldName).append(";"); - buildMethodText.append(" }"); - PsiMethod buildMethod = elementFactory.createMethodFromText(buildMethodText.toString(), srcClass); - builderClass.add(buildMethod); - return builderClass; - } - - private void appendConstructor(StringBuilder buildMethodText) { - String constructorParameters = createConstructorParameters(); - buildMethodText - .append("new ") - .append(srcClassName) - .append("(") - .append(constructorParameters) - .append(");"); - } - - private void appendSetMethodsOrAssignments(StringBuilder buildMethodText) { - appendSetMethods(buildMethodText, psiFieldsForSetters); - if (isInnerBuilder(builderClass)) { - Set fieldsSetViaAssignment = new HashSet(allSelectedPsiFields); - fieldsSetViaAssignment.removeAll(psiFieldsForSetters); - fieldsSetViaAssignment.removeAll(psiFieldsForConstructor); - appendAssignments(buildMethodText, fieldsSetViaAssignment); - } - } - - private void appendSetMethods(StringBuilder buildMethodText, Collection fieldsToBeSetViaSetter) { - for (PsiField psiFieldsForSetter : fieldsToBeSetViaSetter) { - String fieldNamePrefix = codeStyleSettings.getFieldNamePrefix(); - String fieldName = psiFieldsForSetter.getName(); - String fieldNameWithoutPrefix = fieldName.replaceFirst(fieldNamePrefix, ""); - String fieldNameUppercase = StringUtils.capitalize(fieldNameWithoutPrefix); - buildMethodText - .append(srcClassFieldName) - .append(".set") - .append(fieldNameUppercase) - .append("(") - .append(fieldName) - .append(");"); - } - } - - private void appendAssignments(StringBuilder buildMethodText, Collection fieldsSetViaAssignment) { - for (PsiField field : fieldsSetViaAssignment) { - buildMethodText - .append(srcClassFieldName) - .append(".") - .append(field.getName()) - .append("=") - .append("this.") - .append(field.getName()) - .append(";"); - } - } - - private String createConstructorParameters() { - if (bestConstructor == null) { - return ""; - } - StringBuilder sb = new StringBuilder(); - for (PsiParameter psiParameter : bestConstructor.getParameterList().getParameters()) { - boolean parameterHasMatchingField = false; - for (PsiField psiField : psiFieldsForConstructor) { - if (psiFieldVerifier.areNameAndTypeEqual(psiField, psiParameter)) { - sb.append(psiField.getName()).append(SEMICOLON); - parameterHasMatchingField = true; - break; - } - } - if (!parameterHasMatchingField) { - sb.append(getDefaultValue(psiParameter.getType())).append(SEMICOLON); - } - } - removeLastSemicolon(sb); - return sb.toString(); - } - - private String getDefaultValue(PsiType type) { - if (type.equals(PsiType.BOOLEAN)) { - return "false"; - } else if (type.equals(PsiType.BYTE) || type.equals(PsiType.SHORT) || type.equals(PsiType.INT)) { - return "0"; - } else if (type.equals(PsiType.LONG)) { - return "0L"; - } else if (type.equals(PsiType.FLOAT)) { - return "0.0f"; - } else if (type.equals(PsiType.DOUBLE)) { - return "0.0d"; - } else if (type.equals(PsiType.CHAR)) { - return "'\\u0000'"; - } - return "null"; - } - - private void removeLastSemicolon(StringBuilder sb) { - if (sb.toString().endsWith(SEMICOLON)) { - sb.deleteCharAt(sb.length() - 1); - } - } -} +package pl.mjedynak.idea.plugins.builder.psi; + +import static com.intellij.openapi.util.text.StringUtil.isVowel; + +import com.intellij.psi.JavaDirectoryService; +import com.intellij.psi.JavaPsiFacade; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiElementFactory; +import com.intellij.psi.PsiField; +import com.intellij.psi.PsiMethod; +import com.intellij.psi.PsiModifier; +import com.intellij.psi.PsiModifierList; +import com.intellij.psi.PsiParameter; +import com.intellij.psi.PsiType; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import org.apache.commons.lang3.StringUtils; +import pl.mjedynak.idea.plugins.builder.settings.CodeStyleSettings; +import pl.mjedynak.idea.plugins.builder.verifier.PsiFieldVerifier; +import pl.mjedynak.idea.plugins.builder.writer.BuilderContext; + +public class BuilderPsiClassBuilder { + + private static final String SPACE = " "; + private static final String A_PREFIX = " a"; + private static final String AN_PREFIX = " an"; + private static final String SEMICOLON = ","; + + private final PsiHelper psiHelper = new PsiHelper(); + private final PsiFieldsModifier psiFieldsModifier = new PsiFieldsModifier(); + private final PsiFieldVerifier psiFieldVerifier = new PsiFieldVerifier(); + private final CodeStyleSettings codeStyleSettings = new CodeStyleSettings(); + private ButMethodCreator butMethodCreator; + private CopyConstructorCreator copyConstructorCreator; + private MethodCreator methodCreator; + + private PsiClass srcClass = null; + private String builderClassName = null; + + private List psiFieldsForSetters = null; + private List psiFieldsForConstructor = null; + private List allSelectedPsiFields = null; + private PsiMethod bestConstructor = null; + + private PsiClass builderClass = null; + private PsiElementFactory elementFactory = null; + private String srcClassName = null; + private String srcClassFieldName = null; + + private boolean useSingleField = false; + private boolean isInline = false; + private boolean copyConstructor = false; + + public BuilderPsiClassBuilder aBuilder(BuilderContext context) { + initializeFields(context); + JavaDirectoryService javaDirectoryService = psiHelper.getJavaDirectoryService(); + builderClass = javaDirectoryService.createClass(context.getTargetDirectory(), builderClassName); + PsiModifierList modifierList = builderClass.getModifierList(); + modifierList.setModifierProperty(PsiModifier.FINAL, true); + return this; + } + + public BuilderPsiClassBuilder anInnerBuilder(BuilderContext context) { + initializeFields(context); + builderClass = elementFactory.createClass(builderClassName); + PsiModifierList modifierList = builderClass.getModifierList(); + modifierList.setModifierProperty(PsiModifier.FINAL, true); + modifierList.setModifierProperty(PsiModifier.STATIC, true); + return this; + } + + private void initializeFields(BuilderContext context) { + JavaPsiFacade javaPsiFacade = psiHelper.getJavaPsiFacade(context.getProject()); + elementFactory = javaPsiFacade.getElementFactory(); + srcClass = context.getPsiClassFromEditor(); + builderClassName = context.getClassName(); + srcClassName = context.getPsiClassFromEditor().getName(); + srcClassFieldName = StringUtils.uncapitalize(srcClassName); + psiFieldsForSetters = context.getPsiFieldsForBuilder().getFieldsForSetters(); + psiFieldsForConstructor = context.getPsiFieldsForBuilder().getFieldsForConstructor(); + allSelectedPsiFields = context.getPsiFieldsForBuilder().getAllSelectedFields(); + useSingleField = context.useSingleField(); + bestConstructor = context.getPsiFieldsForBuilder().getBestConstructor(); + methodCreator = new MethodCreator(elementFactory, builderClassName); + butMethodCreator = new ButMethodCreator(elementFactory); + copyConstructorCreator = new CopyConstructorCreator(elementFactory); + isInline = allSelectedPsiFields.size() == psiFieldsForConstructor.size(); + copyConstructor = context.hasAddCopyConstructor(); + } + + public BuilderPsiClassBuilder withFields() { + if (useSingleField) { + String fieldText = "private " + srcClassName + " " + srcClassFieldName + ";"; + PsiField singleField = elementFactory.createFieldFromText(fieldText, srcClass); + builderClass.add(singleField); + } else if (isInnerBuilder(builderClass)) { + psiFieldsModifier.modifyFieldsForInnerClass(allSelectedPsiFields, builderClass); + } else { + psiFieldsModifier.modifyFields(psiFieldsForSetters, psiFieldsForConstructor, builderClass); + } + return this; + } + + public BuilderPsiClassBuilder withConstructor() { + PsiMethod constructor; + if (useSingleField) { + constructor = elementFactory.createMethodFromText( + builderClassName + "(){ " + srcClassFieldName + " = new " + srcClassName + "(); }", srcClass); + } else { + constructor = elementFactory.createConstructor(); + } + + constructor + .getModifierList() + .setModifierProperty(copyConstructor ? PsiModifier.PUBLIC : PsiModifier.PRIVATE, true); + + builderClass.add(constructor); + return this; + } + + public BuilderPsiClassBuilder withInitializingMethod() { + String prefix = isVowel(srcClassName.toLowerCase(Locale.ENGLISH).charAt(0)) ? AN_PREFIX : A_PREFIX; + PsiMethod staticMethod = elementFactory.createMethodFromText( + "public static " + builderClassName + prefix + srcClassName + "() { return new " + builderClassName + + "(); }", + srcClass); + builderClass.add(staticMethod); + return this; + } + + public BuilderPsiClassBuilder withSetMethods(String methodPrefix) { + if (useSingleField || isInnerBuilder(builderClass)) { + for (PsiField psiFieldForAssignment : allSelectedPsiFields) { + createAndAddMethod(psiFieldForAssignment, methodPrefix); + } + } else { + for (PsiField psiFieldForSetter : psiFieldsForSetters) { + createAndAddMethod(psiFieldForSetter, methodPrefix); + } + for (PsiField psiFieldForConstructor : psiFieldsForConstructor) { + createAndAddMethod(psiFieldForConstructor, methodPrefix); + } + } + return this; + } + + private boolean isInnerBuilder(PsiClass aClass) { + return aClass.hasModifierProperty(PsiModifier.STATIC); + } + + public BuilderPsiClassBuilder withButMethod() { + PsiMethod method = + butMethodCreator.butMethod(builderClassName, builderClass, srcClass, srcClassFieldName, useSingleField); + builderClass.add(method); + return this; + } + + public BuilderPsiClassBuilder withCopyConstructor() { + final PsiMethod method = copyConstructorCreator.copyConstructor( + builderClass, srcClass, isInnerBuilder(builderClass), useSingleField); + builderClass.add(method); + return this; + } + + private void createAndAddMethod(PsiField psiField, String methodPrefix) { + builderClass.add(methodCreator.createMethod(psiField, methodPrefix, srcClassFieldName, useSingleField)); + } + + public PsiClass build() { + if (useSingleField) { + return buildUseSingleField(); + } else if (isInline) { + return buildIsInline(); + } else { + return buildDefault(); + } + } + + private PsiClass buildUseSingleField() { + String buildMethodText = "public " + srcClassName + " build() { " + "return " + srcClassFieldName + ";" + " }"; + PsiMethod buildMethod = elementFactory.createMethodFromText(buildMethodText, srcClass); + builderClass.add(buildMethod); + return builderClass; + } + + private PsiClass buildIsInline() { + StringBuilder buildMethodText = new StringBuilder(); + buildMethodText.append("public ").append(srcClassName).append(" build() { "); + buildMethodText.append("return "); + appendConstructor(buildMethodText); + buildMethodText.append(" }"); + PsiMethod buildMethod = elementFactory.createMethodFromText(buildMethodText.toString(), srcClass); + builderClass.add(buildMethod); + return builderClass; + } + + private PsiClass buildDefault() { + StringBuilder buildMethodText = new StringBuilder(); + buildMethodText.append("public ").append(srcClassName).append(" build() { "); + buildMethodText + .append(srcClassName) + .append(SPACE) + .append(srcClassFieldName) + .append(" = "); + appendConstructor(buildMethodText); + appendSetMethodsOrAssignments(buildMethodText); + buildMethodText.append("return ").append(srcClassFieldName).append(";"); + buildMethodText.append(" }"); + PsiMethod buildMethod = elementFactory.createMethodFromText(buildMethodText.toString(), srcClass); + builderClass.add(buildMethod); + return builderClass; + } + + private void appendConstructor(StringBuilder buildMethodText) { + String constructorParameters = createConstructorParameters(); + buildMethodText + .append("new ") + .append(srcClassName) + .append("(") + .append(constructorParameters) + .append(");"); + } + + private void appendSetMethodsOrAssignments(StringBuilder buildMethodText) { + appendSetMethods(buildMethodText, psiFieldsForSetters); + if (isInnerBuilder(builderClass)) { + Set fieldsSetViaAssignment = new HashSet(allSelectedPsiFields); + fieldsSetViaAssignment.removeAll(psiFieldsForSetters); + fieldsSetViaAssignment.removeAll(psiFieldsForConstructor); + appendAssignments(buildMethodText, fieldsSetViaAssignment); + } + } + + private void appendSetMethods(StringBuilder buildMethodText, Collection fieldsToBeSetViaSetter) { + for (PsiField psiFieldsForSetter : fieldsToBeSetViaSetter) { + String fieldNamePrefix = codeStyleSettings.getFieldNamePrefix(); + String fieldName = psiFieldsForSetter.getName(); + String fieldNameWithoutPrefix = fieldName.replaceFirst(fieldNamePrefix, ""); + String fieldNameUppercase = StringUtils.capitalize(fieldNameWithoutPrefix); + buildMethodText + .append(srcClassFieldName) + .append(".set") + .append(fieldNameUppercase) + .append("(") + .append(fieldName) + .append(");"); + } + } + + private void appendAssignments(StringBuilder buildMethodText, Collection fieldsSetViaAssignment) { + for (PsiField field : fieldsSetViaAssignment) { + buildMethodText + .append(srcClassFieldName) + .append(".") + .append(field.getName()) + .append("=") + .append("this.") + .append(field.getName()) + .append(";"); + } + } + + private String createConstructorParameters() { + if (bestConstructor == null) { + return ""; + } + StringBuilder sb = new StringBuilder(); + for (PsiParameter psiParameter : bestConstructor.getParameterList().getParameters()) { + boolean parameterHasMatchingField = false; + for (PsiField psiField : psiFieldsForConstructor) { + if (psiFieldVerifier.areNameAndTypeEqual(psiField, psiParameter)) { + sb.append(psiField.getName()).append(SEMICOLON); + parameterHasMatchingField = true; + break; + } + } + if (!parameterHasMatchingField) { + sb.append(getDefaultValue(psiParameter.getType())).append(SEMICOLON); + } + } + removeLastSemicolon(sb); + return sb.toString(); + } + + private String getDefaultValue(PsiType type) { + if (type.equals(PsiType.BOOLEAN)) { + return "false"; + } else if (type.equals(PsiType.BYTE) || type.equals(PsiType.SHORT) || type.equals(PsiType.INT)) { + return "0"; + } else if (type.equals(PsiType.LONG)) { + return "0L"; + } else if (type.equals(PsiType.FLOAT)) { + return "0.0f"; + } else if (type.equals(PsiType.DOUBLE)) { + return "0.0d"; + } else if (type.equals(PsiType.CHAR)) { + return "'\\u0000'"; + } + return "null"; + } + + private void removeLastSemicolon(StringBuilder sb) { + if (sb.toString().endsWith(SEMICOLON)) { + sb.deleteCharAt(sb.length() - 1); + } + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/psi/ButMethodCreator.java b/src/main/java/pl/mjedynak/idea/plugins/builder/psi/ButMethodCreator.java index d95c5c9..85ada72 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/psi/ButMethodCreator.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/psi/ButMethodCreator.java @@ -1,75 +1,75 @@ -package pl.mjedynak.idea.plugins.builder.psi; - -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiElementFactory; -import com.intellij.psi.PsiMethod; -import com.intellij.psi.PsiParameterList; -import org.apache.commons.lang3.StringUtils; -import pl.mjedynak.idea.plugins.builder.settings.CodeStyleSettings; - -public class ButMethodCreator { - - private final CodeStyleSettings codeStyleSettings = new CodeStyleSettings(); - private final PsiElementFactory elementFactory; - - public ButMethodCreator(PsiElementFactory elementFactory) { - this.elementFactory = elementFactory; - } - - public PsiMethod butMethod( - String builderClassName, - PsiClass builderClass, - PsiClass srcClass, - String srcClassFieldName, - boolean useSingleField) { - PsiMethod[] methods = builderClass.getMethods(); - StringBuilder text = new StringBuilder("public " + builderClassName + " but() { return "); - for (PsiMethod method : methods) { - PsiParameterList parameterList = method.getParameterList(); - if (methodIsNotConstructor(builderClassName, method)) { - appendMethod(text, method, parameterList, srcClassFieldName, useSingleField); - } - } - deleteLastDot(text); - text.append("; }"); - return elementFactory.createMethodFromText(text.toString(), srcClass); - } - - private void appendMethod( - StringBuilder text, - PsiMethod method, - PsiParameterList parameterList, - String srcClassFieldName, - boolean useSingleField) { - if (isInitializingMethod(parameterList)) { - text.append(method.getName()).append("()."); - } else { - String parameterName = parameterList.getParameters()[0].getName(); - String parameterNamePrefix = codeStyleSettings.getParameterNamePrefix(); - String parameterNameWithoutPrefix = parameterName.replaceFirst(parameterNamePrefix, ""); - String fieldNamePrefix = codeStyleSettings.getFieldNamePrefix(); - text.append(method.getName()).append("("); - if (useSingleField) { - text.append(srcClassFieldName) - .append(".get") - .append(StringUtils.capitalize(parameterNameWithoutPrefix)) - .append("()"); - } else { - text.append(fieldNamePrefix).append(parameterNameWithoutPrefix); - } - text.append(")."); - } - } - - private boolean isInitializingMethod(PsiParameterList parameterList) { - return parameterList.getParametersCount() <= 0; - } - - private void deleteLastDot(StringBuilder text) { - text.deleteCharAt(text.length() - 1); - } - - private boolean methodIsNotConstructor(String builderClassName, PsiMethod method) { - return !method.getName().equals(builderClassName); - } -} +package pl.mjedynak.idea.plugins.builder.psi; + +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiElementFactory; +import com.intellij.psi.PsiMethod; +import com.intellij.psi.PsiParameterList; +import org.apache.commons.lang3.StringUtils; +import pl.mjedynak.idea.plugins.builder.settings.CodeStyleSettings; + +public class ButMethodCreator { + + private final CodeStyleSettings codeStyleSettings = new CodeStyleSettings(); + private final PsiElementFactory elementFactory; + + public ButMethodCreator(PsiElementFactory elementFactory) { + this.elementFactory = elementFactory; + } + + public PsiMethod butMethod( + String builderClassName, + PsiClass builderClass, + PsiClass srcClass, + String srcClassFieldName, + boolean useSingleField) { + PsiMethod[] methods = builderClass.getMethods(); + StringBuilder text = new StringBuilder("public " + builderClassName + " but() { return "); + for (PsiMethod method : methods) { + PsiParameterList parameterList = method.getParameterList(); + if (methodIsNotConstructor(builderClassName, method)) { + appendMethod(text, method, parameterList, srcClassFieldName, useSingleField); + } + } + deleteLastDot(text); + text.append("; }"); + return elementFactory.createMethodFromText(text.toString(), srcClass); + } + + private void appendMethod( + StringBuilder text, + PsiMethod method, + PsiParameterList parameterList, + String srcClassFieldName, + boolean useSingleField) { + if (isInitializingMethod(parameterList)) { + text.append(method.getName()).append("()."); + } else { + String parameterName = parameterList.getParameters()[0].getName(); + String parameterNamePrefix = codeStyleSettings.getParameterNamePrefix(); + String parameterNameWithoutPrefix = parameterName.replaceFirst(parameterNamePrefix, ""); + String fieldNamePrefix = codeStyleSettings.getFieldNamePrefix(); + text.append(method.getName()).append("("); + if (useSingleField) { + text.append(srcClassFieldName) + .append(".get") + .append(StringUtils.capitalize(parameterNameWithoutPrefix)) + .append("()"); + } else { + text.append(fieldNamePrefix).append(parameterNameWithoutPrefix); + } + text.append(")."); + } + } + + private boolean isInitializingMethod(PsiParameterList parameterList) { + return parameterList.getParametersCount() <= 0; + } + + private void deleteLastDot(StringBuilder text) { + text.deleteCharAt(text.length() - 1); + } + + private boolean methodIsNotConstructor(String builderClassName, PsiMethod method) { + return !method.getName().equals(builderClassName); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/psi/CopyConstructorCreator.java b/src/main/java/pl/mjedynak/idea/plugins/builder/psi/CopyConstructorCreator.java index e88d41f..be5c192 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/psi/CopyConstructorCreator.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/psi/CopyConstructorCreator.java @@ -1,61 +1,61 @@ -package pl.mjedynak.idea.plugins.builder.psi; - -import static java.util.Objects.nonNull; - -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiElementFactory; -import com.intellij.psi.PsiField; -import com.intellij.psi.PsiMethod; -import com.intellij.psi.util.PropertyUtilBase; -import com.intellij.util.IncorrectOperationException; - -public class CopyConstructorCreator { - - private final PsiElementFactory elementFactory; - - public CopyConstructorCreator(PsiElementFactory elementFactory) { - this.elementFactory = elementFactory; - } - - public PsiMethod copyConstructor( - PsiClass builderClass, PsiClass srcClass, boolean isInnerBuilder, boolean useSingleField) { - PsiField[] fields = builderClass.getAllFields(); - StringBuilder text = new StringBuilder("public " - + builderClass.getNameIdentifier().getText() + "(" + srcClass.getQualifiedName() + " other) { "); - - for (PsiField field : fields) { - text.append("this.").append(field.getName()).append(" = other"); - - if (srcClass.isRecord()) { - text.append(".").append(field.getName()).append("();"); - } else if (isInnerBuilder) { - if (useSingleField) { - text.append(";"); - } else { - text.append(".").append(field.getName()).append(";"); - } - } else { - if (useSingleField) { - text.append(";"); - } else { - text.append(".") - .append(findFieldGetter(srcClass, field).getName()) - .append("();"); - } - } - } - text.append(" }"); - - return elementFactory.createMethodFromText(text.toString(), srcClass); - } - - private PsiMethod findFieldGetter(final PsiClass srcClass, final PsiField field) { - PsiMethod method = srcClass.findMethodBySignature(PropertyUtilBase.generateGetterPrototype(field), true); - - if (nonNull(method)) { - return method; - } - - throw new IncorrectOperationException("Could not create copy constructor as cannot get field getters"); - } -} +package pl.mjedynak.idea.plugins.builder.psi; + +import static java.util.Objects.nonNull; + +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiElementFactory; +import com.intellij.psi.PsiField; +import com.intellij.psi.PsiMethod; +import com.intellij.psi.util.PropertyUtilBase; +import com.intellij.util.IncorrectOperationException; + +public class CopyConstructorCreator { + + private final PsiElementFactory elementFactory; + + public CopyConstructorCreator(PsiElementFactory elementFactory) { + this.elementFactory = elementFactory; + } + + public PsiMethod copyConstructor( + PsiClass builderClass, PsiClass srcClass, boolean isInnerBuilder, boolean useSingleField) { + PsiField[] fields = builderClass.getAllFields(); + StringBuilder text = new StringBuilder("public " + + builderClass.getNameIdentifier().getText() + "(" + srcClass.getQualifiedName() + " other) { "); + + for (PsiField field : fields) { + text.append("this.").append(field.getName()).append(" = other"); + + if (srcClass.isRecord()) { + text.append(".").append(field.getName()).append("();"); + } else if (isInnerBuilder) { + if (useSingleField) { + text.append(";"); + } else { + text.append(".").append(field.getName()).append(";"); + } + } else { + if (useSingleField) { + text.append(";"); + } else { + text.append(".") + .append(findFieldGetter(srcClass, field).getName()) + .append("();"); + } + } + } + text.append(" }"); + + return elementFactory.createMethodFromText(text.toString(), srcClass); + } + + private PsiMethod findFieldGetter(final PsiClass srcClass, final PsiField field) { + PsiMethod method = srcClass.findMethodBySignature(PropertyUtilBase.generateGetterPrototype(field), true); + + if (nonNull(method)) { + return method; + } + + throw new IncorrectOperationException("Could not create copy constructor as cannot get field getters"); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/psi/MethodCreator.java b/src/main/java/pl/mjedynak/idea/plugins/builder/psi/MethodCreator.java index bb87323..b150807 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/psi/MethodCreator.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/psi/MethodCreator.java @@ -1,40 +1,40 @@ -package pl.mjedynak.idea.plugins.builder.psi; - -import com.intellij.psi.PsiElementFactory; -import com.intellij.psi.PsiField; -import com.intellij.psi.PsiMethod; -import pl.mjedynak.idea.plugins.builder.settings.CodeStyleSettings; - -public class MethodCreator { - - private final CodeStyleSettings codeStyleSettings = new CodeStyleSettings(); - private final MethodNameCreator methodNameCreator = new MethodNameCreator(); - private final PsiElementFactory elementFactory; - private final String builderClassName; - - public MethodCreator(PsiElementFactory elementFactory, String builderClassName) { - this.elementFactory = elementFactory; - this.builderClassName = builderClassName; - } - - public PsiMethod createMethod( - PsiField psiField, String methodPrefix, String srcClassFieldName, boolean useSingleField) { - String fieldName = psiField.getName(); - String fieldType = psiField.getType().getPresentableText(); - String fieldNamePrefix = codeStyleSettings.getFieldNamePrefix(); - String fieldNameWithoutPrefix = fieldName.replaceFirst(fieldNamePrefix, ""); - String parameterNamePrefix = codeStyleSettings.getParameterNamePrefix(); - String parameterName = parameterNamePrefix + fieldNameWithoutPrefix; - String methodName = methodNameCreator.createMethodName(methodPrefix, fieldNameWithoutPrefix); - String methodText; - if (useSingleField) { - String setterName = methodNameCreator.createMethodName("set", fieldNameWithoutPrefix); - methodText = "public " + builderClassName + " " + methodName + "(" + fieldType + " " + parameterName - + ") { " + srcClassFieldName + "." + setterName + "(" + fieldName + "); return this; }"; - } else { - methodText = "public " + builderClassName + " " + methodName + "(" + fieldType + " " + parameterName - + ") { this." + fieldName + " = " + parameterName + "; return this; }"; - } - return elementFactory.createMethodFromText(methodText, psiField); - } -} +package pl.mjedynak.idea.plugins.builder.psi; + +import com.intellij.psi.PsiElementFactory; +import com.intellij.psi.PsiField; +import com.intellij.psi.PsiMethod; +import pl.mjedynak.idea.plugins.builder.settings.CodeStyleSettings; + +public class MethodCreator { + + private final CodeStyleSettings codeStyleSettings = new CodeStyleSettings(); + private final MethodNameCreator methodNameCreator = new MethodNameCreator(); + private final PsiElementFactory elementFactory; + private final String builderClassName; + + public MethodCreator(PsiElementFactory elementFactory, String builderClassName) { + this.elementFactory = elementFactory; + this.builderClassName = builderClassName; + } + + public PsiMethod createMethod( + PsiField psiField, String methodPrefix, String srcClassFieldName, boolean useSingleField) { + String fieldName = psiField.getName(); + String fieldType = psiField.getType().getPresentableText(); + String fieldNamePrefix = codeStyleSettings.getFieldNamePrefix(); + String fieldNameWithoutPrefix = fieldName.replaceFirst(fieldNamePrefix, ""); + String parameterNamePrefix = codeStyleSettings.getParameterNamePrefix(); + String parameterName = parameterNamePrefix + fieldNameWithoutPrefix; + String methodName = methodNameCreator.createMethodName(methodPrefix, fieldNameWithoutPrefix); + String methodText; + if (useSingleField) { + String setterName = methodNameCreator.createMethodName("set", fieldNameWithoutPrefix); + methodText = "public " + builderClassName + " " + methodName + "(" + fieldType + " " + parameterName + + ") { " + srcClassFieldName + "." + setterName + "(" + fieldName + "); return this; }"; + } else { + methodText = "public " + builderClassName + " " + methodName + "(" + fieldType + " " + parameterName + + ") { this." + fieldName + " = " + parameterName + "; return this; }"; + } + return elementFactory.createMethodFromText(methodText, psiField); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/psi/MethodNameCreator.java b/src/main/java/pl/mjedynak/idea/plugins/builder/psi/MethodNameCreator.java index 604176b..9ff9ff4 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/psi/MethodNameCreator.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/psi/MethodNameCreator.java @@ -1,16 +1,16 @@ -package pl.mjedynak.idea.plugins.builder.psi; - -import static org.apache.commons.lang3.StringUtils.capitalize; -import static org.apache.commons.lang3.StringUtils.isEmpty; - -public class MethodNameCreator { - - public String createMethodName(String methodPrefix, String fieldName) { - if (isEmpty(methodPrefix)) { - return fieldName; - } else { - String fieldNameUppercase = capitalize(fieldName); - return methodPrefix + fieldNameUppercase; - } - } -} +package pl.mjedynak.idea.plugins.builder.psi; + +import static org.apache.commons.lang3.StringUtils.capitalize; +import static org.apache.commons.lang3.StringUtils.isEmpty; + +public class MethodNameCreator { + + public String createMethodName(String methodPrefix, String fieldName) { + if (isEmpty(methodPrefix)) { + return fieldName; + } else { + String fieldNameUppercase = capitalize(fieldName); + return methodPrefix + fieldNameUppercase; + } + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/psi/PsiFieldSelector.java b/src/main/java/pl/mjedynak/idea/plugins/builder/psi/PsiFieldSelector.java index c5bba2c..3b28fce 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/psi/PsiFieldSelector.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/psi/PsiFieldSelector.java @@ -1,55 +1,55 @@ -package pl.mjedynak.idea.plugins.builder.psi; - -import static java.util.Arrays.stream; -import static java.util.stream.Collectors.toList; - -import com.intellij.codeInsight.generation.PsiElementClassMember; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiField; -import java.util.ArrayList; -import java.util.List; -import pl.mjedynak.idea.plugins.builder.factory.PsiElementClassMemberFactory; -import pl.mjedynak.idea.plugins.builder.verifier.PsiFieldVerifier; - -public class PsiFieldSelector { - - private final PsiElementClassMemberFactory psiElementClassMemberFactory; - private final PsiFieldVerifier psiFieldVerifier; - - public PsiFieldSelector( - PsiElementClassMemberFactory psiElementClassMemberFactory, PsiFieldVerifier psiFieldVerifier) { - this.psiElementClassMemberFactory = psiElementClassMemberFactory; - this.psiFieldVerifier = psiFieldVerifier; - } - - public List> selectFieldsToIncludeInBuilder( - PsiClass psiClass, boolean innerBuilder, boolean useSingleField, boolean hasButMethod) { - List> result = new ArrayList<>(); - - List psiFields = stream(psiClass.getAllFields()) - .filter(psiField -> !"serialVersionUID".equals(psiField.getName())) - .toList(); - Iterable filtered = psiFields.stream() - .filter(psiField -> isAppropriate(psiClass, psiField, innerBuilder, useSingleField, hasButMethod)) - .collect(toList()); - - for (PsiField psiField : filtered) { - result.add(psiElementClassMemberFactory.createPsiElementClassMember(psiField)); - } - return result; - } - - private boolean isAppropriate( - PsiClass psiClass, PsiField psiField, boolean innerBuilder, boolean useSingleField, boolean hasButMethod) { - if (useSingleField && hasButMethod) { - return psiFieldVerifier.isSetInSetterMethod(psiField, psiClass) - && psiFieldVerifier.hasGetterMethod(psiField, psiClass); - } else if (useSingleField) { - return psiFieldVerifier.isSetInSetterMethod(psiField, psiClass); - } else if (!innerBuilder) { - return psiFieldVerifier.isSetInSetterMethod(psiField, psiClass) - || psiFieldVerifier.isSetInConstructor(psiField, psiClass); - } - return true; - } -} +package pl.mjedynak.idea.plugins.builder.psi; + +import static java.util.Arrays.stream; +import static java.util.stream.Collectors.toList; + +import com.intellij.codeInsight.generation.PsiElementClassMember; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiField; +import java.util.ArrayList; +import java.util.List; +import pl.mjedynak.idea.plugins.builder.factory.PsiElementClassMemberFactory; +import pl.mjedynak.idea.plugins.builder.verifier.PsiFieldVerifier; + +public class PsiFieldSelector { + + private final PsiElementClassMemberFactory psiElementClassMemberFactory; + private final PsiFieldVerifier psiFieldVerifier; + + public PsiFieldSelector( + PsiElementClassMemberFactory psiElementClassMemberFactory, PsiFieldVerifier psiFieldVerifier) { + this.psiElementClassMemberFactory = psiElementClassMemberFactory; + this.psiFieldVerifier = psiFieldVerifier; + } + + public List> selectFieldsToIncludeInBuilder( + PsiClass psiClass, boolean innerBuilder, boolean useSingleField, boolean hasButMethod) { + List> result = new ArrayList<>(); + + List psiFields = stream(psiClass.getAllFields()) + .filter(psiField -> !"serialVersionUID".equals(psiField.getName())) + .toList(); + Iterable filtered = psiFields.stream() + .filter(psiField -> isAppropriate(psiClass, psiField, innerBuilder, useSingleField, hasButMethod)) + .collect(toList()); + + for (PsiField psiField : filtered) { + result.add(psiElementClassMemberFactory.createPsiElementClassMember(psiField)); + } + return result; + } + + private boolean isAppropriate( + PsiClass psiClass, PsiField psiField, boolean innerBuilder, boolean useSingleField, boolean hasButMethod) { + if (useSingleField && hasButMethod) { + return psiFieldVerifier.isSetInSetterMethod(psiField, psiClass) + && psiFieldVerifier.hasGetterMethod(psiField, psiClass); + } else if (useSingleField) { + return psiFieldVerifier.isSetInSetterMethod(psiField, psiClass); + } else if (!innerBuilder) { + return psiFieldVerifier.isSetInSetterMethod(psiField, psiClass) + || psiFieldVerifier.isSetInConstructor(psiField, psiClass); + } + return true; + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/psi/PsiFieldsModifier.java b/src/main/java/pl/mjedynak/idea/plugins/builder/psi/PsiFieldsModifier.java index 151b186..d81f160 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/psi/PsiFieldsModifier.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/psi/PsiFieldsModifier.java @@ -1,42 +1,42 @@ -package pl.mjedynak.idea.plugins.builder.psi; - -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiElementFactory; -import com.intellij.psi.PsiField; -import com.intellij.psi.PsiModifier; -import java.util.List; - -public class PsiFieldsModifier { - - public void modifyFields( - List psiFieldsForSetters, List psiFieldsForConstructor, PsiClass builderClass) { - for (PsiField psiFieldsForSetter : psiFieldsForSetters) { - removeModifiers(psiFieldsForSetter, builderClass); - } - for (PsiField psiFieldForConstructor : psiFieldsForConstructor) { - removeModifiers(psiFieldForConstructor, builderClass); - } - } - - public void modifyFieldsForInnerClass(List allFields, PsiClass innerBuilderClass) { - for (PsiField field : allFields) { - removeModifiers(field, innerBuilderClass); - } - } - - private void removeModifiers(PsiField psiField, PsiClass builderClass) { - PsiElement copy = copyField(psiField, builderClass); - builderClass.add(copy); - } - - private PsiElement copyField(final PsiField psiField, final PsiClass builderClass) { - PsiField builderField = PsiElementFactory.getInstance(builderClass.getProject()) - .createField(psiField.getName(), psiField.getType()); - if (builderField.getModifierList() != null) { - builderField.getModifierList().setModifierProperty(PsiModifier.PRIVATE, true); - } - - return builderField; - } -} +package pl.mjedynak.idea.plugins.builder.psi; + +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiElementFactory; +import com.intellij.psi.PsiField; +import com.intellij.psi.PsiModifier; +import java.util.List; + +public class PsiFieldsModifier { + + public void modifyFields( + List psiFieldsForSetters, List psiFieldsForConstructor, PsiClass builderClass) { + for (PsiField psiFieldsForSetter : psiFieldsForSetters) { + removeModifiers(psiFieldsForSetter, builderClass); + } + for (PsiField psiFieldForConstructor : psiFieldsForConstructor) { + removeModifiers(psiFieldForConstructor, builderClass); + } + } + + public void modifyFieldsForInnerClass(List allFields, PsiClass innerBuilderClass) { + for (PsiField field : allFields) { + removeModifiers(field, innerBuilderClass); + } + } + + private void removeModifiers(PsiField psiField, PsiClass builderClass) { + PsiElement copy = copyField(psiField, builderClass); + builderClass.add(copy); + } + + private PsiElement copyField(final PsiField psiField, final PsiClass builderClass) { + PsiField builderField = PsiElementFactory.getInstance(builderClass.getProject()) + .createField(psiField.getName(), psiField.getType()); + if (builderField.getModifierList() != null) { + builderField.getModifierList().setModifierProperty(PsiModifier.PRIVATE, true); + } + + return builderField; + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/psi/PsiHelper.java b/src/main/java/pl/mjedynak/idea/plugins/builder/psi/PsiHelper.java index c64b8ef..4a1abd3 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/psi/PsiHelper.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/psi/PsiHelper.java @@ -1,92 +1,92 @@ -package pl.mjedynak.idea.plugins.builder.psi; - -import static com.intellij.ide.util.EditSourceUtil.getDescriptor; - -import com.intellij.ide.util.PackageUtil; -import com.intellij.openapi.application.Application; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.command.CommandProcessor; -import com.intellij.openapi.editor.Editor; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.module.ModuleUtil; -import com.intellij.openapi.project.Project; -import com.intellij.pom.Navigatable; -import com.intellij.psi.JavaDirectoryService; -import com.intellij.psi.JavaPsiFacade; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiClassOwner; -import com.intellij.psi.PsiDirectory; -import com.intellij.psi.PsiFile; -import com.intellij.psi.PsiPackage; -import com.intellij.psi.search.PsiShortNamesCache; -import com.intellij.psi.util.PsiUtilBase; -import com.intellij.refactoring.util.RefactoringMessageUtil; - -public class PsiHelper { - - public PsiFile getPsiFileFromEditor(Editor editor, Project project) { - return getPsiFile(editor, project); - } - - public PsiClass getPsiClassFromEditor(Editor editor, Project project) { - PsiClass psiClass = null; - PsiFile psiFile = getPsiFile(editor, project); - if (psiFile instanceof PsiClassOwner) { - PsiClass[] classes = ((PsiClassOwner) psiFile).getClasses(); - if (classes.length == 1) { - psiClass = classes[0]; - } - } - return psiClass; - } - - private PsiFile getPsiFile(Editor editor, Project project) { - return PsiUtilBase.getPsiFileInEditor(editor, project); - } - - public PsiShortNamesCache getPsiShortNamesCache(Project project) { - return PsiShortNamesCache.getInstance(project); - } - - public PsiDirectory getDirectoryFromModuleAndPackageName(Module module, String packageName) { - PsiDirectory baseDir = PackageUtil.findPossiblePackageDirectoryInModule(module, packageName); - return PackageUtil.findOrCreateDirectoryForPackage(module, packageName, baseDir, true); - } - - public void navigateToClass(PsiClass psiClass) { - if (psiClass != null) { - Navigatable navigatable = getDescriptor(psiClass); - if (navigatable != null) { - navigatable.navigate(true); - } - } - } - - public String checkIfClassCanBeCreated(PsiDirectory targetDirectory, String className) { - return RefactoringMessageUtil.checkCanCreateClass(targetDirectory, className); - } - - public JavaDirectoryService getJavaDirectoryService() { - return JavaDirectoryService.getInstance(); - } - - public PsiPackage getPackage(PsiDirectory psiDirectory) { - return getJavaDirectoryService().getPackage(psiDirectory); - } - - public JavaPsiFacade getJavaPsiFacade(Project project) { - return JavaPsiFacade.getInstance(project); - } - - public CommandProcessor getCommandProcessor() { - return CommandProcessor.getInstance(); - } - - public Application getApplication() { - return ApplicationManager.getApplication(); - } - - public Module findModuleForPsiClass(PsiClass psiClass, Project project) { - return ModuleUtil.findModuleForFile(psiClass.getContainingFile().getVirtualFile(), project); - } -} +package pl.mjedynak.idea.plugins.builder.psi; + +import static com.intellij.ide.util.EditSourceUtil.getDescriptor; + +import com.intellij.ide.util.PackageUtil; +import com.intellij.openapi.application.Application; +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.command.CommandProcessor; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.module.Module; +import com.intellij.openapi.module.ModuleUtil; +import com.intellij.openapi.project.Project; +import com.intellij.pom.Navigatable; +import com.intellij.psi.JavaDirectoryService; +import com.intellij.psi.JavaPsiFacade; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiClassOwner; +import com.intellij.psi.PsiDirectory; +import com.intellij.psi.PsiFile; +import com.intellij.psi.PsiPackage; +import com.intellij.psi.search.PsiShortNamesCache; +import com.intellij.psi.util.PsiUtilBase; +import com.intellij.refactoring.util.RefactoringMessageUtil; + +public class PsiHelper { + + public PsiFile getPsiFileFromEditor(Editor editor, Project project) { + return getPsiFile(editor, project); + } + + public PsiClass getPsiClassFromEditor(Editor editor, Project project) { + PsiClass psiClass = null; + PsiFile psiFile = getPsiFile(editor, project); + if (psiFile instanceof PsiClassOwner) { + PsiClass[] classes = ((PsiClassOwner) psiFile).getClasses(); + if (classes.length == 1) { + psiClass = classes[0]; + } + } + return psiClass; + } + + private PsiFile getPsiFile(Editor editor, Project project) { + return PsiUtilBase.getPsiFileInEditor(editor, project); + } + + public PsiShortNamesCache getPsiShortNamesCache(Project project) { + return PsiShortNamesCache.getInstance(project); + } + + public PsiDirectory getDirectoryFromModuleAndPackageName(Module module, String packageName) { + PsiDirectory baseDir = PackageUtil.findPossiblePackageDirectoryInModule(module, packageName); + return PackageUtil.findOrCreateDirectoryForPackage(module, packageName, baseDir, true); + } + + public void navigateToClass(PsiClass psiClass) { + if (psiClass != null) { + Navigatable navigatable = getDescriptor(psiClass); + if (navigatable != null) { + navigatable.navigate(true); + } + } + } + + public String checkIfClassCanBeCreated(PsiDirectory targetDirectory, String className) { + return RefactoringMessageUtil.checkCanCreateClass(targetDirectory, className); + } + + public JavaDirectoryService getJavaDirectoryService() { + return JavaDirectoryService.getInstance(); + } + + public PsiPackage getPackage(PsiDirectory psiDirectory) { + return getJavaDirectoryService().getPackage(psiDirectory); + } + + public JavaPsiFacade getJavaPsiFacade(Project project) { + return JavaPsiFacade.getInstance(project); + } + + public CommandProcessor getCommandProcessor() { + return CommandProcessor.getInstance(); + } + + public Application getApplication() { + return ApplicationManager.getApplication(); + } + + public Module findModuleForPsiClass(PsiClass psiClass, Project project) { + return ModuleUtil.findModuleForFile(psiClass.getContainingFile().getVirtualFile(), project); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/psi/model/PsiFieldsForBuilder.java b/src/main/java/pl/mjedynak/idea/plugins/builder/psi/model/PsiFieldsForBuilder.java index 9275258..4357411 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/psi/model/PsiFieldsForBuilder.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/psi/model/PsiFieldsForBuilder.java @@ -1,41 +1,41 @@ -package pl.mjedynak.idea.plugins.builder.psi.model; - -import com.google.common.collect.ImmutableList; -import com.intellij.psi.PsiField; -import com.intellij.psi.PsiMethod; -import java.util.List; - -public class PsiFieldsForBuilder { - - private final List psiFieldsForSetters; - private final List psiFieldsForConstructor; - private final List allSelectedPsiFields; - private final PsiMethod bestConstructor; - - public PsiFieldsForBuilder( - List psiFieldsForSetters, - List psiFieldsForConstructor, - List allSelectedPsiFields, - PsiMethod bestConstructor) { - this.psiFieldsForSetters = ImmutableList.copyOf(psiFieldsForSetters); - this.psiFieldsForConstructor = ImmutableList.copyOf(psiFieldsForConstructor); - this.allSelectedPsiFields = ImmutableList.copyOf(allSelectedPsiFields); - this.bestConstructor = bestConstructor; - } - - public List getFieldsForSetters() { - return psiFieldsForSetters; - } - - public List getFieldsForConstructor() { - return psiFieldsForConstructor; - } - - public List getAllSelectedFields() { - return allSelectedPsiFields; - } - - public PsiMethod getBestConstructor() { - return bestConstructor; - } -} +package pl.mjedynak.idea.plugins.builder.psi.model; + +import com.google.common.collect.ImmutableList; +import com.intellij.psi.PsiField; +import com.intellij.psi.PsiMethod; +import java.util.List; + +public class PsiFieldsForBuilder { + + private final List psiFieldsForSetters; + private final List psiFieldsForConstructor; + private final List allSelectedPsiFields; + private final PsiMethod bestConstructor; + + public PsiFieldsForBuilder( + List psiFieldsForSetters, + List psiFieldsForConstructor, + List allSelectedPsiFields, + PsiMethod bestConstructor) { + this.psiFieldsForSetters = ImmutableList.copyOf(psiFieldsForSetters); + this.psiFieldsForConstructor = ImmutableList.copyOf(psiFieldsForConstructor); + this.allSelectedPsiFields = ImmutableList.copyOf(allSelectedPsiFields); + this.bestConstructor = bestConstructor; + } + + public List getFieldsForSetters() { + return psiFieldsForSetters; + } + + public List getFieldsForConstructor() { + return psiFieldsForConstructor; + } + + public List getAllSelectedFields() { + return allSelectedPsiFields; + } + + public PsiMethod getBestConstructor() { + return bestConstructor; + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/renderer/ActionCellRenderer.java b/src/main/java/pl/mjedynak/idea/plugins/builder/renderer/ActionCellRenderer.java index f25ea32..b8480e2 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/renderer/ActionCellRenderer.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/renderer/ActionCellRenderer.java @@ -1,21 +1,21 @@ -package pl.mjedynak.idea.plugins.builder.renderer; - -import com.intellij.codeInsight.navigation.GotoTargetHandler; -import java.awt.Component; -import javax.swing.DefaultListCellRenderer; -import javax.swing.JList; - -public class ActionCellRenderer extends DefaultListCellRenderer { - - @Override - public Component getListCellRendererComponent( - JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - Component result = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (value != null) { - GotoTargetHandler.AdditionalAction action = (GotoTargetHandler.AdditionalAction) value; - setText(action.getText()); - setIcon(action.getIcon()); - } - return result; - } -} +package pl.mjedynak.idea.plugins.builder.renderer; + +import com.intellij.codeInsight.navigation.GotoTargetHandler; +import java.awt.Component; +import javax.swing.DefaultListCellRenderer; +import javax.swing.JList; + +public class ActionCellRenderer extends DefaultListCellRenderer { + + @Override + public Component getListCellRendererComponent( + JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + Component result = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (value != null) { + GotoTargetHandler.AdditionalAction action = (GotoTargetHandler.AdditionalAction) value; + setText(action.getText()); + setIcon(action.getIcon()); + } + return result; + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/settings/BuilderGeneratorSettingsComponent.java b/src/main/java/pl/mjedynak/idea/plugins/builder/settings/BuilderGeneratorSettingsComponent.java index f30812e..3886b73 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/settings/BuilderGeneratorSettingsComponent.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/settings/BuilderGeneratorSettingsComponent.java @@ -1,78 +1,78 @@ -package pl.mjedynak.idea.plugins.builder.settings; - -import com.intellij.ui.components.JBCheckBox; -import com.intellij.ui.components.JBLabel; -import com.intellij.ui.components.JBTextField; -import com.intellij.util.ui.FormBuilder; -import javax.swing.*; -import org.jetbrains.annotations.NotNull; - -public class BuilderGeneratorSettingsComponent { - - private final JPanel myMainPanel; - private final JBTextField defaultMethodPrefixText = new JBTextField(); - private final JBCheckBox innerBuilderCheckBox = new JBCheckBox("Inner builder"); - private final JBCheckBox butMethodCheckBox = new JBCheckBox("'but' method'"); - private final JBCheckBox useSinglePrefixCheckBox = new JBCheckBox("Use single prefix"); - private final JBCheckBox addCopyConstructorCheckBox = new JBCheckBox("Add copy constructor"); - - public BuilderGeneratorSettingsComponent() { - myMainPanel = FormBuilder.createFormBuilder() - .addLabeledComponent(new JBLabel("Default prefix: "), defaultMethodPrefixText, 1, false) - .addComponent(innerBuilderCheckBox, 1) - .addComponent(butMethodCheckBox, 1) - .addComponent(useSinglePrefixCheckBox, 1) - .addComponent(addCopyConstructorCheckBox, 1) - .addComponentFillVertically(new JPanel(), 0) - .getPanel(); - } - - public JPanel getPanel() { - return myMainPanel; - } - - public JComponent getPreferredFocusedComponent() { - return defaultMethodPrefixText; - } - - @NotNull - public String getDefaultMethodPrefixText() { - return defaultMethodPrefixText.getText(); - } - - public void setDefaultMethodPrefixText(@NotNull String newText) { - defaultMethodPrefixText.setText(newText); - } - - public boolean isInnerBuilder() { - return innerBuilderCheckBox.isSelected(); - } - - public void setInnerBuilder(boolean isInnerBuilder) { - innerBuilderCheckBox.setSelected(isInnerBuilder); - } - - public boolean isButMethod() { - return butMethodCheckBox.isSelected(); - } - - public void setButMethod(boolean isButMethod) { - butMethodCheckBox.setSelected(isButMethod); - } - - public boolean isUseSinglePrefix() { - return useSinglePrefixCheckBox.isSelected(); - } - - public void setUseSinglePrefix(boolean isUseSinglePrefix) { - useSinglePrefixCheckBox.setSelected(isUseSinglePrefix); - } - - public boolean isAddCopyConstructor() { - return addCopyConstructorCheckBox.isSelected(); - } - - public void setAddCopyConstructor(boolean addCopyConstructor) { - addCopyConstructorCheckBox.setSelected(addCopyConstructor); - } -} +package pl.mjedynak.idea.plugins.builder.settings; + +import com.intellij.ui.components.JBCheckBox; +import com.intellij.ui.components.JBLabel; +import com.intellij.ui.components.JBTextField; +import com.intellij.util.ui.FormBuilder; +import javax.swing.*; +import org.jetbrains.annotations.NotNull; + +public class BuilderGeneratorSettingsComponent { + + private final JPanel myMainPanel; + private final JBTextField defaultMethodPrefixText = new JBTextField(); + private final JBCheckBox innerBuilderCheckBox = new JBCheckBox("Inner builder"); + private final JBCheckBox butMethodCheckBox = new JBCheckBox("'but' method'"); + private final JBCheckBox useSinglePrefixCheckBox = new JBCheckBox("Use single prefix"); + private final JBCheckBox addCopyConstructorCheckBox = new JBCheckBox("Add copy constructor"); + + public BuilderGeneratorSettingsComponent() { + myMainPanel = FormBuilder.createFormBuilder() + .addLabeledComponent(new JBLabel("Default prefix: "), defaultMethodPrefixText, 1, false) + .addComponent(innerBuilderCheckBox, 1) + .addComponent(butMethodCheckBox, 1) + .addComponent(useSinglePrefixCheckBox, 1) + .addComponent(addCopyConstructorCheckBox, 1) + .addComponentFillVertically(new JPanel(), 0) + .getPanel(); + } + + public JPanel getPanel() { + return myMainPanel; + } + + public JComponent getPreferredFocusedComponent() { + return defaultMethodPrefixText; + } + + @NotNull + public String getDefaultMethodPrefixText() { + return defaultMethodPrefixText.getText(); + } + + public void setDefaultMethodPrefixText(@NotNull String newText) { + defaultMethodPrefixText.setText(newText); + } + + public boolean isInnerBuilder() { + return innerBuilderCheckBox.isSelected(); + } + + public void setInnerBuilder(boolean isInnerBuilder) { + innerBuilderCheckBox.setSelected(isInnerBuilder); + } + + public boolean isButMethod() { + return butMethodCheckBox.isSelected(); + } + + public void setButMethod(boolean isButMethod) { + butMethodCheckBox.setSelected(isButMethod); + } + + public boolean isUseSinglePrefix() { + return useSinglePrefixCheckBox.isSelected(); + } + + public void setUseSinglePrefix(boolean isUseSinglePrefix) { + useSinglePrefixCheckBox.setSelected(isUseSinglePrefix); + } + + public boolean isAddCopyConstructor() { + return addCopyConstructorCheckBox.isSelected(); + } + + public void setAddCopyConstructor(boolean addCopyConstructor) { + addCopyConstructorCheckBox.setSelected(addCopyConstructor); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/settings/BuilderGeneratorSettingsConfigurable.java b/src/main/java/pl/mjedynak/idea/plugins/builder/settings/BuilderGeneratorSettingsConfigurable.java index a5f7a76..c3323c4 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/settings/BuilderGeneratorSettingsConfigurable.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/settings/BuilderGeneratorSettingsConfigurable.java @@ -1,68 +1,68 @@ -package pl.mjedynak.idea.plugins.builder.settings; - -import com.intellij.openapi.options.Configurable; -import javax.swing.*; -import org.jetbrains.annotations.Nls; -import org.jetbrains.annotations.Nullable; - -public class BuilderGeneratorSettingsConfigurable implements Configurable { - - private BuilderGeneratorSettingsComponent mySettingsComponent; - - // A default constructor with no arguments is required because this implementation - // is registered as an applicationConfigurable EP - - @Nls(capitalization = Nls.Capitalization.Title) - @Override - public String getDisplayName() { - return "Builder Generator Default Settings"; - } - - @Override - public JComponent getPreferredFocusedComponent() { - return mySettingsComponent.getPreferredFocusedComponent(); - } - - @Nullable - @Override - public JComponent createComponent() { - mySettingsComponent = new BuilderGeneratorSettingsComponent(); - return mySettingsComponent.getPanel(); - } - - @Override - public boolean isModified() { - BuilderGeneratorSettingsState settings = BuilderGeneratorSettingsState.getInstance(); - boolean modified = !mySettingsComponent.getDefaultMethodPrefixText().equals(settings.defaultMethodPrefix); - modified |= mySettingsComponent.isInnerBuilder() != settings.isInnerBuilder; - modified |= mySettingsComponent.isButMethod() != settings.isButMethod; - modified |= mySettingsComponent.isUseSinglePrefix() != settings.isUseSinglePrefix; - modified |= mySettingsComponent.isAddCopyConstructor() != settings.isAddCopyConstructor; - return modified; - } - - @Override - public void apply() { - BuilderGeneratorSettingsState settings = BuilderGeneratorSettingsState.getInstance(); - settings.defaultMethodPrefix = mySettingsComponent.getDefaultMethodPrefixText(); - settings.isInnerBuilder = mySettingsComponent.isInnerBuilder(); - settings.isButMethod = mySettingsComponent.isButMethod(); - settings.isUseSinglePrefix = mySettingsComponent.isUseSinglePrefix(); - settings.isAddCopyConstructor = mySettingsComponent.isAddCopyConstructor(); - } - - @Override - public void reset() { - BuilderGeneratorSettingsState settings = BuilderGeneratorSettingsState.getInstance(); - mySettingsComponent.setDefaultMethodPrefixText(settings.defaultMethodPrefix); - mySettingsComponent.setInnerBuilder(settings.isInnerBuilder); - mySettingsComponent.setButMethod(settings.isButMethod); - mySettingsComponent.setUseSinglePrefix(settings.isUseSinglePrefix); - mySettingsComponent.setAddCopyConstructor(settings.isAddCopyConstructor); - } - - @Override - public void disposeUIResources() { - mySettingsComponent = null; - } -} +package pl.mjedynak.idea.plugins.builder.settings; + +import com.intellij.openapi.options.Configurable; +import javax.swing.*; +import org.jetbrains.annotations.Nls; +import org.jetbrains.annotations.Nullable; + +public class BuilderGeneratorSettingsConfigurable implements Configurable { + + private BuilderGeneratorSettingsComponent mySettingsComponent; + + // A default constructor with no arguments is required because this implementation + // is registered as an applicationConfigurable EP + + @Nls(capitalization = Nls.Capitalization.Title) + @Override + public String getDisplayName() { + return "Builder Generator Default Settings"; + } + + @Override + public JComponent getPreferredFocusedComponent() { + return mySettingsComponent.getPreferredFocusedComponent(); + } + + @Nullable + @Override + public JComponent createComponent() { + mySettingsComponent = new BuilderGeneratorSettingsComponent(); + return mySettingsComponent.getPanel(); + } + + @Override + public boolean isModified() { + BuilderGeneratorSettingsState settings = BuilderGeneratorSettingsState.getInstance(); + boolean modified = !mySettingsComponent.getDefaultMethodPrefixText().equals(settings.defaultMethodPrefix); + modified |= mySettingsComponent.isInnerBuilder() != settings.isInnerBuilder; + modified |= mySettingsComponent.isButMethod() != settings.isButMethod; + modified |= mySettingsComponent.isUseSinglePrefix() != settings.isUseSinglePrefix; + modified |= mySettingsComponent.isAddCopyConstructor() != settings.isAddCopyConstructor; + return modified; + } + + @Override + public void apply() { + BuilderGeneratorSettingsState settings = BuilderGeneratorSettingsState.getInstance(); + settings.defaultMethodPrefix = mySettingsComponent.getDefaultMethodPrefixText(); + settings.isInnerBuilder = mySettingsComponent.isInnerBuilder(); + settings.isButMethod = mySettingsComponent.isButMethod(); + settings.isUseSinglePrefix = mySettingsComponent.isUseSinglePrefix(); + settings.isAddCopyConstructor = mySettingsComponent.isAddCopyConstructor(); + } + + @Override + public void reset() { + BuilderGeneratorSettingsState settings = BuilderGeneratorSettingsState.getInstance(); + mySettingsComponent.setDefaultMethodPrefixText(settings.defaultMethodPrefix); + mySettingsComponent.setInnerBuilder(settings.isInnerBuilder); + mySettingsComponent.setButMethod(settings.isButMethod); + mySettingsComponent.setUseSinglePrefix(settings.isUseSinglePrefix); + mySettingsComponent.setAddCopyConstructor(settings.isAddCopyConstructor); + } + + @Override + public void disposeUIResources() { + mySettingsComponent = null; + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/settings/BuilderGeneratorSettingsState.java b/src/main/java/pl/mjedynak/idea/plugins/builder/settings/BuilderGeneratorSettingsState.java index fc02124..23f0281 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/settings/BuilderGeneratorSettingsState.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/settings/BuilderGeneratorSettingsState.java @@ -1,45 +1,45 @@ -package pl.mjedynak.idea.plugins.builder.settings; - -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.components.PersistentStateComponent; -import com.intellij.openapi.components.State; -import com.intellij.openapi.components.Storage; -import com.intellij.util.xmlb.XmlSerializerUtil; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Supports storing the application settings in a persistent way. - * The {@link State} and {@link Storage} annotations define the name of the data and the file name where - * these persistent application settings are stored. - */ -@State(name = "org.intellij.sdk.settings.AppSettingsState", storages = @Storage("SdkSettingsPlugin.xml")) -public class BuilderGeneratorSettingsState implements PersistentStateComponent { - - public String defaultMethodPrefix = "with"; - public boolean isInnerBuilder = false; - public boolean isButMethod = false; - public boolean isUseSinglePrefix = false; - public boolean isAddCopyConstructor = false; - - public BuilderGeneratorSettingsState() {} - - public static BuilderGeneratorSettingsState getInstance() { - try { - return ApplicationManager.getApplication().getService(BuilderGeneratorSettingsState.class); - } catch (NullPointerException e) { - return new BuilderGeneratorSettingsState(); - } - } - - @Nullable - @Override - public BuilderGeneratorSettingsState getState() { - return this; - } - - @Override - public void loadState(@NotNull BuilderGeneratorSettingsState state) { - XmlSerializerUtil.copyBean(state, this); - } -} +package pl.mjedynak.idea.plugins.builder.settings; + +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.components.PersistentStateComponent; +import com.intellij.openapi.components.State; +import com.intellij.openapi.components.Storage; +import com.intellij.util.xmlb.XmlSerializerUtil; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * Supports storing the application settings in a persistent way. + * The {@link State} and {@link Storage} annotations define the name of the data and the file name where + * these persistent application settings are stored. + */ +@State(name = "org.intellij.sdk.settings.AppSettingsState", storages = @Storage("SdkSettingsPlugin.xml")) +public class BuilderGeneratorSettingsState implements PersistentStateComponent { + + public String defaultMethodPrefix = "with"; + public boolean isInnerBuilder = false; + public boolean isButMethod = false; + public boolean isUseSinglePrefix = false; + public boolean isAddCopyConstructor = false; + + public BuilderGeneratorSettingsState() {} + + public static BuilderGeneratorSettingsState getInstance() { + try { + return ApplicationManager.getApplication().getService(BuilderGeneratorSettingsState.class); + } catch (NullPointerException e) { + return new BuilderGeneratorSettingsState(); + } + } + + @Nullable + @Override + public BuilderGeneratorSettingsState getState() { + return this; + } + + @Override + public void loadState(@NotNull BuilderGeneratorSettingsState state) { + XmlSerializerUtil.copyBean(state, this); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/settings/CodeStyleSettings.java b/src/main/java/pl/mjedynak/idea/plugins/builder/settings/CodeStyleSettings.java index fd14eac..3897fda 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/settings/CodeStyleSettings.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/settings/CodeStyleSettings.java @@ -1,11 +1,11 @@ -package pl.mjedynak.idea.plugins.builder.settings; - -public class CodeStyleSettings { - public String getFieldNamePrefix() { - return ""; - } - - public String getParameterNamePrefix() { - return ""; - } -} +package pl.mjedynak.idea.plugins.builder.settings; + +public class CodeStyleSettings { + public String getFieldNamePrefix() { + return ""; + } + + public String getParameterNamePrefix() { + return ""; + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/verifier/BuilderVerifier.java b/src/main/java/pl/mjedynak/idea/plugins/builder/verifier/BuilderVerifier.java index 33bc275..7671fa7 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/verifier/BuilderVerifier.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/verifier/BuilderVerifier.java @@ -1,12 +1,12 @@ -package pl.mjedynak.idea.plugins.builder.verifier; - -import com.intellij.psi.PsiClass; - -public class BuilderVerifier { - - private static final String SUFFIX = "Builder"; - - public boolean isBuilder(PsiClass psiClass) { - return psiClass.getName().endsWith(SUFFIX); - } -} +package pl.mjedynak.idea.plugins.builder.verifier; + +import com.intellij.psi.PsiClass; + +public class BuilderVerifier { + + private static final String SUFFIX = "Builder"; + + public boolean isBuilder(PsiClass psiClass) { + return psiClass.getName().endsWith(SUFFIX); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/verifier/PsiFieldVerifier.java b/src/main/java/pl/mjedynak/idea/plugins/builder/verifier/PsiFieldVerifier.java index a663f2a..22503be 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/verifier/PsiFieldVerifier.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/verifier/PsiFieldVerifier.java @@ -1,94 +1,94 @@ -package pl.mjedynak.idea.plugins.builder.verifier; - -import static org.apache.commons.lang3.StringUtils.EMPTY; - -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiField; -import com.intellij.psi.PsiMethod; -import com.intellij.psi.PsiModifier; -import com.intellij.psi.PsiModifierList; -import com.intellij.psi.PsiParameter; -import com.intellij.psi.PsiParameterList; -import org.apache.commons.text.WordUtils; -import pl.mjedynak.idea.plugins.builder.settings.CodeStyleSettings; - -public class PsiFieldVerifier { - - static final String SET_PREFIX = "set"; - static final String GET_PREFIX = "get"; - - private final CodeStyleSettings codeStyleSettings = new CodeStyleSettings(); - - public boolean isSetInConstructor(PsiField psiField, PsiClass psiClass) { - boolean result = false; - PsiMethod[] constructors = psiClass.getConstructors(); - for (int i = 0; i < constructors.length && !result; i++) { - result = checkConstructor(psiField, constructors[i]); - } - return result; - } - - public boolean checkConstructor(PsiField psiField, PsiMethod constructor) { - PsiParameterList parameterList = constructor.getParameterList(); - PsiParameter[] parameters = parameterList.getParameters(); - return iterateOverParameters(psiField, parameters); - } - - private boolean iterateOverParameters(PsiField psiField, PsiParameter[] parameters) { - boolean result = false; - for (int i = 0; i < parameters.length && !result; i++) { - result = checkParameter(psiField, parameters[i]); - } - return result; - } - - private boolean checkParameter(PsiField psiField, PsiParameter parameter) { - return areNameAndTypeEqual(psiField, parameter); - } - - public boolean areNameAndTypeEqual(PsiField psiField, PsiParameter parameter) { - String parameterNamePrefix = codeStyleSettings.getParameterNamePrefix(); - String parameterName = parameter.getName(); - String parameterNameWithoutPrefix = parameterName.replace(parameterNamePrefix, ""); - String fieldNamePrefix = codeStyleSettings.getFieldNamePrefix(); - String fieldName = psiField.getName(); - String fieldNameWithoutPrefix = fieldName.replaceFirst(fieldNamePrefix, ""); - return parameterNameWithoutPrefix.equals(fieldNameWithoutPrefix) - && parameter.getType().equals(psiField.getType()); - } - - public boolean isSetInSetterMethod(PsiField psiField, PsiClass psiClass) { - return methodIsNotPrivateAndHasProperPrefixAndProperName(psiField, psiClass, SET_PREFIX); - } - - public boolean hasGetterMethod(PsiField psiField, PsiClass psiClass) { - return methodIsNotPrivateAndHasProperPrefixAndProperName(psiField, psiClass, GET_PREFIX); - } - - private boolean methodIsNotPrivateAndHasProperPrefixAndProperName( - PsiField psiField, PsiClass psiClass, String prefix) { - boolean result = false; - for (PsiMethod method : psiClass.getAllMethods()) { - if (methodIsNotPrivate(method) && methodHaProperPrefixAndProperName(psiField, method, prefix)) { - result = true; - break; - } - } - return result; - } - - private boolean methodIsNotPrivate(PsiMethod method) { - PsiModifierList modifierList = method.getModifierList(); - return modifierListHasNoPrivateModifier(modifierList); - } - - private boolean methodHaProperPrefixAndProperName(PsiField psiField, PsiMethod method, String prefix) { - String fieldNamePrefix = codeStyleSettings.getFieldNamePrefix(); - String fieldNameWithoutPrefix = psiField.getName().replace(fieldNamePrefix, EMPTY); - return method.getName().equals(prefix + WordUtils.capitalize(fieldNameWithoutPrefix)); - } - - private boolean modifierListHasNoPrivateModifier(PsiModifierList modifierList) { - return !modifierList.hasExplicitModifier(PsiModifier.PRIVATE); - } -} +package pl.mjedynak.idea.plugins.builder.verifier; + +import static org.apache.commons.lang3.StringUtils.EMPTY; + +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiField; +import com.intellij.psi.PsiMethod; +import com.intellij.psi.PsiModifier; +import com.intellij.psi.PsiModifierList; +import com.intellij.psi.PsiParameter; +import com.intellij.psi.PsiParameterList; +import org.apache.commons.text.WordUtils; +import pl.mjedynak.idea.plugins.builder.settings.CodeStyleSettings; + +public class PsiFieldVerifier { + + static final String SET_PREFIX = "set"; + static final String GET_PREFIX = "get"; + + private final CodeStyleSettings codeStyleSettings = new CodeStyleSettings(); + + public boolean isSetInConstructor(PsiField psiField, PsiClass psiClass) { + boolean result = false; + PsiMethod[] constructors = psiClass.getConstructors(); + for (int i = 0; i < constructors.length && !result; i++) { + result = checkConstructor(psiField, constructors[i]); + } + return result; + } + + public boolean checkConstructor(PsiField psiField, PsiMethod constructor) { + PsiParameterList parameterList = constructor.getParameterList(); + PsiParameter[] parameters = parameterList.getParameters(); + return iterateOverParameters(psiField, parameters); + } + + private boolean iterateOverParameters(PsiField psiField, PsiParameter[] parameters) { + boolean result = false; + for (int i = 0; i < parameters.length && !result; i++) { + result = checkParameter(psiField, parameters[i]); + } + return result; + } + + private boolean checkParameter(PsiField psiField, PsiParameter parameter) { + return areNameAndTypeEqual(psiField, parameter); + } + + public boolean areNameAndTypeEqual(PsiField psiField, PsiParameter parameter) { + String parameterNamePrefix = codeStyleSettings.getParameterNamePrefix(); + String parameterName = parameter.getName(); + String parameterNameWithoutPrefix = parameterName.replace(parameterNamePrefix, ""); + String fieldNamePrefix = codeStyleSettings.getFieldNamePrefix(); + String fieldName = psiField.getName(); + String fieldNameWithoutPrefix = fieldName.replaceFirst(fieldNamePrefix, ""); + return parameterNameWithoutPrefix.equals(fieldNameWithoutPrefix) + && parameter.getType().equals(psiField.getType()); + } + + public boolean isSetInSetterMethod(PsiField psiField, PsiClass psiClass) { + return methodIsNotPrivateAndHasProperPrefixAndProperName(psiField, psiClass, SET_PREFIX); + } + + public boolean hasGetterMethod(PsiField psiField, PsiClass psiClass) { + return methodIsNotPrivateAndHasProperPrefixAndProperName(psiField, psiClass, GET_PREFIX); + } + + private boolean methodIsNotPrivateAndHasProperPrefixAndProperName( + PsiField psiField, PsiClass psiClass, String prefix) { + boolean result = false; + for (PsiMethod method : psiClass.getAllMethods()) { + if (methodIsNotPrivate(method) && methodHaProperPrefixAndProperName(psiField, method, prefix)) { + result = true; + break; + } + } + return result; + } + + private boolean methodIsNotPrivate(PsiMethod method) { + PsiModifierList modifierList = method.getModifierList(); + return modifierListHasNoPrivateModifier(modifierList); + } + + private boolean methodHaProperPrefixAndProperName(PsiField psiField, PsiMethod method, String prefix) { + String fieldNamePrefix = codeStyleSettings.getFieldNamePrefix(); + String fieldNameWithoutPrefix = psiField.getName().replace(fieldNamePrefix, EMPTY); + return method.getName().equals(prefix + WordUtils.capitalize(fieldNameWithoutPrefix)); + } + + private boolean modifierListHasNoPrivateModifier(PsiModifierList modifierList) { + return !modifierList.hasExplicitModifier(PsiModifier.PRIVATE); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/writer/BuilderContext.java b/src/main/java/pl/mjedynak/idea/plugins/builder/writer/BuilderContext.java index 71816b8..f33b7c3 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/writer/BuilderContext.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/writer/BuilderContext.java @@ -1,107 +1,107 @@ -package pl.mjedynak.idea.plugins.builder.writer; - -import com.google.common.base.Objects; -import com.intellij.openapi.project.Project; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiDirectory; -import pl.mjedynak.idea.plugins.builder.psi.model.PsiFieldsForBuilder; - -public class BuilderContext { - - private final Project project; - private final PsiFieldsForBuilder psiFieldsForBuilder; - private final PsiDirectory targetDirectory; - private final String className; - private final PsiClass psiClassFromEditor; - private final String methodPrefix; - private final boolean isInner; - private final boolean hasButMethod; - private final boolean useSingleField; - private final boolean addCopyConstructor; - - public BuilderContext( - Project project, - PsiFieldsForBuilder psiFieldsForBuilder, - PsiDirectory targetDirectory, - String className, - PsiClass psiClassFromEditor, - String methodPrefix, - boolean isInner, - boolean hasButMethod, - boolean useSingleField, - boolean addCopyConstructor) { - this.project = project; - this.psiFieldsForBuilder = psiFieldsForBuilder; - this.targetDirectory = targetDirectory; - this.className = className; - this.psiClassFromEditor = psiClassFromEditor; - this.methodPrefix = methodPrefix; - this.isInner = isInner; - this.hasButMethod = hasButMethod; - this.useSingleField = useSingleField; - this.addCopyConstructor = addCopyConstructor; - } - - public Project getProject() { - return project; - } - - public PsiFieldsForBuilder getPsiFieldsForBuilder() { - return psiFieldsForBuilder; - } - - public PsiDirectory getTargetDirectory() { - return targetDirectory; - } - - public String getClassName() { - return className; - } - - public PsiClass getPsiClassFromEditor() { - return psiClassFromEditor; - } - - public String getMethodPrefix() { - return methodPrefix; - } - - boolean isInner() { - return isInner; - } - - boolean hasButMethod() { - return hasButMethod; - } - - public boolean useSingleField() { - return useSingleField; - } - - public boolean hasAddCopyConstructor() { - return addCopyConstructor; - } - - @Override - public int hashCode() { - return Objects.hashCode( - project, psiFieldsForBuilder, targetDirectory, className, psiClassFromEditor, methodPrefix); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || getClass() != obj.getClass()) { - return false; - } - BuilderContext other = (BuilderContext) obj; - return Objects.equal(this.project, other.project) - && Objects.equal(this.psiFieldsForBuilder, other.psiFieldsForBuilder) - && Objects.equal(this.targetDirectory, other.targetDirectory) - && Objects.equal(this.className, other.className) - && Objects.equal(this.psiClassFromEditor, other.psiClassFromEditor) - && Objects.equal(this.methodPrefix, other.methodPrefix); - } -} +package pl.mjedynak.idea.plugins.builder.writer; + +import com.google.common.base.Objects; +import com.intellij.openapi.project.Project; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiDirectory; +import pl.mjedynak.idea.plugins.builder.psi.model.PsiFieldsForBuilder; + +public class BuilderContext { + + private final Project project; + private final PsiFieldsForBuilder psiFieldsForBuilder; + private final PsiDirectory targetDirectory; + private final String className; + private final PsiClass psiClassFromEditor; + private final String methodPrefix; + private final boolean isInner; + private final boolean hasButMethod; + private final boolean useSingleField; + private final boolean addCopyConstructor; + + public BuilderContext( + Project project, + PsiFieldsForBuilder psiFieldsForBuilder, + PsiDirectory targetDirectory, + String className, + PsiClass psiClassFromEditor, + String methodPrefix, + boolean isInner, + boolean hasButMethod, + boolean useSingleField, + boolean addCopyConstructor) { + this.project = project; + this.psiFieldsForBuilder = psiFieldsForBuilder; + this.targetDirectory = targetDirectory; + this.className = className; + this.psiClassFromEditor = psiClassFromEditor; + this.methodPrefix = methodPrefix; + this.isInner = isInner; + this.hasButMethod = hasButMethod; + this.useSingleField = useSingleField; + this.addCopyConstructor = addCopyConstructor; + } + + public Project getProject() { + return project; + } + + public PsiFieldsForBuilder getPsiFieldsForBuilder() { + return psiFieldsForBuilder; + } + + public PsiDirectory getTargetDirectory() { + return targetDirectory; + } + + public String getClassName() { + return className; + } + + public PsiClass getPsiClassFromEditor() { + return psiClassFromEditor; + } + + public String getMethodPrefix() { + return methodPrefix; + } + + boolean isInner() { + return isInner; + } + + boolean hasButMethod() { + return hasButMethod; + } + + public boolean useSingleField() { + return useSingleField; + } + + public boolean hasAddCopyConstructor() { + return addCopyConstructor; + } + + @Override + public int hashCode() { + return Objects.hashCode( + project, psiFieldsForBuilder, targetDirectory, className, psiClassFromEditor, methodPrefix); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + BuilderContext other = (BuilderContext) obj; + return Objects.equal(this.project, other.project) + && Objects.equal(this.psiFieldsForBuilder, other.psiFieldsForBuilder) + && Objects.equal(this.targetDirectory, other.targetDirectory) + && Objects.equal(this.className, other.className) + && Objects.equal(this.psiClassFromEditor, other.psiClassFromEditor) + && Objects.equal(this.methodPrefix, other.methodPrefix); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/writer/BuilderWriter.java b/src/main/java/pl/mjedynak/idea/plugins/builder/writer/BuilderWriter.java index e1e78b7..fc32632 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/writer/BuilderWriter.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/writer/BuilderWriter.java @@ -1,27 +1,27 @@ -package pl.mjedynak.idea.plugins.builder.writer; - -import com.intellij.openapi.command.CommandProcessor; -import com.intellij.psi.PsiClass; -import pl.mjedynak.idea.plugins.builder.psi.BuilderPsiClassBuilder; -import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; - -public class BuilderWriter { - - static final String CREATE_BUILDER_STRING = "Create Builder"; - private final BuilderPsiClassBuilder builderPsiClassBuilder; - private final PsiHelper psiHelper; - - public BuilderWriter(BuilderPsiClassBuilder builderPsiClassBuilder, PsiHelper psiHelper) { - this.builderPsiClassBuilder = builderPsiClassBuilder; - this.psiHelper = psiHelper; - } - - public void writeBuilder(BuilderContext context, PsiClass existingBuilder) { - CommandProcessor commandProcessor = psiHelper.getCommandProcessor(); - commandProcessor.executeCommand( - context.getProject(), - new BuilderWriterRunnable(builderPsiClassBuilder, context, existingBuilder), - CREATE_BUILDER_STRING, - this); - } -} +package pl.mjedynak.idea.plugins.builder.writer; + +import com.intellij.openapi.command.CommandProcessor; +import com.intellij.psi.PsiClass; +import pl.mjedynak.idea.plugins.builder.psi.BuilderPsiClassBuilder; +import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; + +public class BuilderWriter { + + static final String CREATE_BUILDER_STRING = "Create Builder"; + private final BuilderPsiClassBuilder builderPsiClassBuilder; + private final PsiHelper psiHelper; + + public BuilderWriter(BuilderPsiClassBuilder builderPsiClassBuilder, PsiHelper psiHelper) { + this.builderPsiClassBuilder = builderPsiClassBuilder; + this.psiHelper = psiHelper; + } + + public void writeBuilder(BuilderContext context, PsiClass existingBuilder) { + CommandProcessor commandProcessor = psiHelper.getCommandProcessor(); + commandProcessor.executeCommand( + context.getProject(), + new BuilderWriterRunnable(builderPsiClassBuilder, context, existingBuilder), + CREATE_BUILDER_STRING, + this); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/writer/BuilderWriterComputable.java b/src/main/java/pl/mjedynak/idea/plugins/builder/writer/BuilderWriterComputable.java index 28c9ad8..cb7b7d3 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/writer/BuilderWriterComputable.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/writer/BuilderWriterComputable.java @@ -1,103 +1,103 @@ -package pl.mjedynak.idea.plugins.builder.writer; - -import com.intellij.openapi.application.Application; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Computable; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiElement; -import com.intellij.util.IncorrectOperationException; -import pl.mjedynak.idea.plugins.builder.gui.helper.GuiHelper; -import pl.mjedynak.idea.plugins.builder.psi.BuilderPsiClassBuilder; -import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; - -class BuilderWriterComputable implements Computable { - - private final GuiHelper guiHelper = new GuiHelper(); - private final PsiHelper psiHelper = new PsiHelper(); - private final BuilderPsiClassBuilder builderPsiClassBuilder; - private final BuilderContext context; - private final PsiClass existingBuilder; - - BuilderWriterComputable( - BuilderPsiClassBuilder builderPsiClassBuilder, BuilderContext context, PsiClass existingBuilder) { - this.builderPsiClassBuilder = builderPsiClassBuilder; - this.context = context; - this.existingBuilder = existingBuilder; - } - - @Override - public PsiElement compute() { - return createBuilder(); - } - - private PsiElement createBuilder() { - try { - guiHelper.includeCurrentPlaceAsChangePlace(context.getProject()); - PsiClass targetClass; - if (existingBuilder != null) { - existingBuilder.delete(); - } - if (context.isInner()) { - targetClass = getInnerBuilderPsiClass(); - context.getPsiClassFromEditor().add(targetClass); - } else { - targetClass = getBuilderPsiClass(); - navigateToClassAndPositionCursor(context.getProject(), targetClass); - } - return targetClass; - } catch (IncorrectOperationException e) { - showErrorMessage(context.getProject(), context.getClassName(), e.getMessage()); - e.printStackTrace(); - return null; - } - } - - private PsiClass getInnerBuilderPsiClass() { - BuilderPsiClassBuilder builder = builderPsiClassBuilder - .anInnerBuilder(context) - .withFields() - .withConstructor() - .withInitializingMethod() - .withSetMethods(context.getMethodPrefix()); - addButMethodIfNecessary(builder); - addCopyConstructorIfNecessary(builder); - return builder.build(); - } - - private PsiClass getBuilderPsiClass() { - BuilderPsiClassBuilder builder = builderPsiClassBuilder - .aBuilder(context) - .withFields() - .withConstructor() - .withInitializingMethod() - .withSetMethods(context.getMethodPrefix()); - addButMethodIfNecessary(builder); - addCopyConstructorIfNecessary(builder); - return builder.build(); - } - - private void addButMethodIfNecessary(BuilderPsiClassBuilder builder) { - if (context.hasButMethod()) { - builder.withButMethod(); - } - } - - private void addCopyConstructorIfNecessary(BuilderPsiClassBuilder builder) { - if (context.hasAddCopyConstructor()) { - builder.withCopyConstructor(); - } - } - - private void navigateToClassAndPositionCursor(Project project, PsiClass targetClass) { - guiHelper.positionCursor(project, targetClass.getContainingFile(), targetClass.getLBrace()); - } - - private void showErrorMessage(Project project, String className, String message) { - BuilderWriterErrorRunnable builderWriterErrorRunnable = message == null - ? new BuilderWriterErrorRunnable(project, className) - : new BuilderWriterErrorRunnable(project, className, message); - - Application application = psiHelper.getApplication(); - application.invokeLater(builderWriterErrorRunnable); - } -} +package pl.mjedynak.idea.plugins.builder.writer; + +import com.intellij.openapi.application.Application; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.Computable; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiElement; +import com.intellij.util.IncorrectOperationException; +import pl.mjedynak.idea.plugins.builder.gui.helper.GuiHelper; +import pl.mjedynak.idea.plugins.builder.psi.BuilderPsiClassBuilder; +import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; + +class BuilderWriterComputable implements Computable { + + private final GuiHelper guiHelper = new GuiHelper(); + private final PsiHelper psiHelper = new PsiHelper(); + private final BuilderPsiClassBuilder builderPsiClassBuilder; + private final BuilderContext context; + private final PsiClass existingBuilder; + + BuilderWriterComputable( + BuilderPsiClassBuilder builderPsiClassBuilder, BuilderContext context, PsiClass existingBuilder) { + this.builderPsiClassBuilder = builderPsiClassBuilder; + this.context = context; + this.existingBuilder = existingBuilder; + } + + @Override + public PsiElement compute() { + return createBuilder(); + } + + private PsiElement createBuilder() { + try { + guiHelper.includeCurrentPlaceAsChangePlace(context.getProject()); + PsiClass targetClass; + if (existingBuilder != null) { + existingBuilder.delete(); + } + if (context.isInner()) { + targetClass = getInnerBuilderPsiClass(); + context.getPsiClassFromEditor().add(targetClass); + } else { + targetClass = getBuilderPsiClass(); + navigateToClassAndPositionCursor(context.getProject(), targetClass); + } + return targetClass; + } catch (IncorrectOperationException e) { + showErrorMessage(context.getProject(), context.getClassName(), e.getMessage()); + e.printStackTrace(); + return null; + } + } + + private PsiClass getInnerBuilderPsiClass() { + BuilderPsiClassBuilder builder = builderPsiClassBuilder + .anInnerBuilder(context) + .withFields() + .withConstructor() + .withInitializingMethod() + .withSetMethods(context.getMethodPrefix()); + addButMethodIfNecessary(builder); + addCopyConstructorIfNecessary(builder); + return builder.build(); + } + + private PsiClass getBuilderPsiClass() { + BuilderPsiClassBuilder builder = builderPsiClassBuilder + .aBuilder(context) + .withFields() + .withConstructor() + .withInitializingMethod() + .withSetMethods(context.getMethodPrefix()); + addButMethodIfNecessary(builder); + addCopyConstructorIfNecessary(builder); + return builder.build(); + } + + private void addButMethodIfNecessary(BuilderPsiClassBuilder builder) { + if (context.hasButMethod()) { + builder.withButMethod(); + } + } + + private void addCopyConstructorIfNecessary(BuilderPsiClassBuilder builder) { + if (context.hasAddCopyConstructor()) { + builder.withCopyConstructor(); + } + } + + private void navigateToClassAndPositionCursor(Project project, PsiClass targetClass) { + guiHelper.positionCursor(project, targetClass.getContainingFile(), targetClass.getLBrace()); + } + + private void showErrorMessage(Project project, String className, String message) { + BuilderWriterErrorRunnable builderWriterErrorRunnable = message == null + ? new BuilderWriterErrorRunnable(project, className) + : new BuilderWriterErrorRunnable(project, className, message); + + Application application = psiHelper.getApplication(); + application.invokeLater(builderWriterErrorRunnable); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/writer/BuilderWriterErrorRunnable.java b/src/main/java/pl/mjedynak/idea/plugins/builder/writer/BuilderWriterErrorRunnable.java index 00815ed..9bef817 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/writer/BuilderWriterErrorRunnable.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/writer/BuilderWriterErrorRunnable.java @@ -1,35 +1,35 @@ -package pl.mjedynak.idea.plugins.builder.writer; - -import com.intellij.codeInsight.CodeInsightBundle; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.ui.Messages; - -public class BuilderWriterErrorRunnable implements Runnable { - - static final String INTENTION_ERROR_CANNOT_CREATE_CLASS_MESSAGE = "intention.error.cannot.create.class.message"; - static final String INTENTION_ERROR_CANNOT_CREATE_CLASS_TITLE = "intention.error.cannot.create.class.title"; - - private final Project project; - private final String className; - private final String message; - - public BuilderWriterErrorRunnable(Project project, String className) { - this.project = project; - this.className = className; - this.message = INTENTION_ERROR_CANNOT_CREATE_CLASS_MESSAGE; - } - - public BuilderWriterErrorRunnable(Project project, String className, String message) { - this.project = project; - this.className = className; - this.message = message; - } - - @Override - public void run() { - Messages.showErrorDialog( - project, - CodeInsightBundle.message(message, className), - CodeInsightBundle.message(INTENTION_ERROR_CANNOT_CREATE_CLASS_TITLE)); - } -} +package pl.mjedynak.idea.plugins.builder.writer; + +import com.intellij.codeInsight.CodeInsightBundle; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.ui.Messages; + +public class BuilderWriterErrorRunnable implements Runnable { + + static final String INTENTION_ERROR_CANNOT_CREATE_CLASS_MESSAGE = "intention.error.cannot.create.class.message"; + static final String INTENTION_ERROR_CANNOT_CREATE_CLASS_TITLE = "intention.error.cannot.create.class.title"; + + private final Project project; + private final String className; + private final String message; + + public BuilderWriterErrorRunnable(Project project, String className) { + this.project = project; + this.className = className; + this.message = INTENTION_ERROR_CANNOT_CREATE_CLASS_MESSAGE; + } + + public BuilderWriterErrorRunnable(Project project, String className, String message) { + this.project = project; + this.className = className; + this.message = message; + } + + @Override + public void run() { + Messages.showErrorDialog( + project, + CodeInsightBundle.message(message, className), + CodeInsightBundle.message(INTENTION_ERROR_CANNOT_CREATE_CLASS_TITLE)); + } +} diff --git a/src/main/java/pl/mjedynak/idea/plugins/builder/writer/BuilderWriterRunnable.java b/src/main/java/pl/mjedynak/idea/plugins/builder/writer/BuilderWriterRunnable.java index 2d38fa2..d9f126a 100644 --- a/src/main/java/pl/mjedynak/idea/plugins/builder/writer/BuilderWriterRunnable.java +++ b/src/main/java/pl/mjedynak/idea/plugins/builder/writer/BuilderWriterRunnable.java @@ -1,27 +1,27 @@ -package pl.mjedynak.idea.plugins.builder.writer; - -import com.intellij.openapi.application.Application; -import com.intellij.psi.PsiClass; -import pl.mjedynak.idea.plugins.builder.psi.BuilderPsiClassBuilder; -import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; - -public class BuilderWriterRunnable implements Runnable { - - private final PsiHelper psiHelper = new PsiHelper(); - private final BuilderPsiClassBuilder builderPsiClassBuilder; - private final BuilderContext context; - private final PsiClass existingBuilder; - - public BuilderWriterRunnable( - BuilderPsiClassBuilder builderPsiClassBuilder, BuilderContext context, PsiClass existingBuilder) { - this.builderPsiClassBuilder = builderPsiClassBuilder; - this.context = context; - this.existingBuilder = existingBuilder; - } - - @Override - public void run() { - Application application = psiHelper.getApplication(); - application.runWriteAction(new BuilderWriterComputable(builderPsiClassBuilder, context, existingBuilder)); - } -} +package pl.mjedynak.idea.plugins.builder.writer; + +import com.intellij.openapi.application.Application; +import com.intellij.psi.PsiClass; +import pl.mjedynak.idea.plugins.builder.psi.BuilderPsiClassBuilder; +import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; + +public class BuilderWriterRunnable implements Runnable { + + private final PsiHelper psiHelper = new PsiHelper(); + private final BuilderPsiClassBuilder builderPsiClassBuilder; + private final BuilderContext context; + private final PsiClass existingBuilder; + + public BuilderWriterRunnable( + BuilderPsiClassBuilder builderPsiClassBuilder, BuilderContext context, PsiClass existingBuilder) { + this.builderPsiClassBuilder = builderPsiClassBuilder; + this.context = context; + this.existingBuilder = existingBuilder; + } + + @Override + public void run() { + Application application = psiHelper.getApplication(); + application.runWriteAction(new BuilderWriterComputable(builderPsiClassBuilder, context, existingBuilder)); + } +} diff --git a/src/test/java/pl/mjedynak/idea/plugins/builder/action/GenerateBuilderAdditionalActionTest.java b/src/test/java/pl/mjedynak/idea/plugins/builder/action/GenerateBuilderAdditionalActionTest.java index b745a64..52b23b2 100644 --- a/src/test/java/pl/mjedynak/idea/plugins/builder/action/GenerateBuilderAdditionalActionTest.java +++ b/src/test/java/pl/mjedynak/idea/plugins/builder/action/GenerateBuilderAdditionalActionTest.java @@ -1,46 +1,46 @@ -package pl.mjedynak.idea.plugins.builder.action; - -import static org.assertj.core.api.Assertions.assertThat; - -import com.intellij.openapi.util.IconLoader; -import javax.swing.Icon; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -public class GenerateBuilderAdditionalActionTest { - - private static final String TEXT = "Create New Builder..."; - private static final Icon ICON = IconLoader.getIcon("/actions/intentionBulb.png"); - - private GenerateBuilderAdditionalAction action; - - @BeforeEach - public void setUp() { - action = new GenerateBuilderAdditionalAction(); - } - - @Test - void shouldGetItsOwnText() { - // when - String result = action.getText(); - - // then - assertThat(result).isEqualTo(TEXT); - } - - @Test - void shouldGetItsOwnIcon() { - // when - Icon result = action.getIcon(); - - // then - assertThat(result).isEqualTo(ICON); - } - - @Test - void shouldDoNothingWhenInvokingExecute() { - // this test has no assertion. Is it really useful, if so it needs rework. - // when - action.execute(); - } -} +package pl.mjedynak.idea.plugins.builder.action; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.intellij.openapi.util.IconLoader; +import javax.swing.Icon; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class GenerateBuilderAdditionalActionTest { + + private static final String TEXT = "Create New Builder..."; + private static final Icon ICON = IconLoader.getIcon("/actions/intentionBulb.png"); + + private GenerateBuilderAdditionalAction action; + + @BeforeEach + public void setUp() { + action = new GenerateBuilderAdditionalAction(); + } + + @Test + void shouldGetItsOwnText() { + // when + String result = action.getText(); + + // then + assertThat(result).isEqualTo(TEXT); + } + + @Test + void shouldGetItsOwnIcon() { + // when + Icon result = action.getIcon(); + + // then + assertThat(result).isEqualTo(ICON); + } + + @Test + void shouldDoNothingWhenInvokingExecute() { + // this test has no assertion. Is it really useful, if so it needs rework. + // when + action.execute(); + } +} diff --git a/src/test/java/pl/mjedynak/idea/plugins/builder/action/GoToBuilderAdditionalActionTest.java b/src/test/java/pl/mjedynak/idea/plugins/builder/action/GoToBuilderAdditionalActionTest.java index ae9b00c..f330bce 100644 --- a/src/test/java/pl/mjedynak/idea/plugins/builder/action/GoToBuilderAdditionalActionTest.java +++ b/src/test/java/pl/mjedynak/idea/plugins/builder/action/GoToBuilderAdditionalActionTest.java @@ -1,46 +1,46 @@ -package pl.mjedynak.idea.plugins.builder.action; - -import static org.assertj.core.api.Assertions.assertThat; - -import com.intellij.openapi.util.IconLoader; -import javax.swing.Icon; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -public class GoToBuilderAdditionalActionTest { - - private static final String TEXT = "Go to builder..."; - private static final Icon ICON = IconLoader.getIcon("/actions/intentionBulb.png"); - - private GoToBuilderAdditionalAction action; - - @BeforeEach - public void setUp() { - action = new GoToBuilderAdditionalAction(); - } - - @Test - void shouldGetItsOwnText() { - // when - String result = action.getText(); - - // then - assertThat(result).isEqualTo(TEXT); - } - - @Test - void shouldGetItsOwnIcon() { - // when - Icon result = action.getIcon(); - - // then - assertThat(result).isEqualTo(ICON); - } - - @Test - void shouldDoNothingWhenInvokingExecute() { - // this test has no assertion. Is it really useful, if so it needs rework. - // when - action.execute(); - } -} +package pl.mjedynak.idea.plugins.builder.action; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.intellij.openapi.util.IconLoader; +import javax.swing.Icon; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class GoToBuilderAdditionalActionTest { + + private static final String TEXT = "Go to builder..."; + private static final Icon ICON = IconLoader.getIcon("/actions/intentionBulb.png"); + + private GoToBuilderAdditionalAction action; + + @BeforeEach + public void setUp() { + action = new GoToBuilderAdditionalAction(); + } + + @Test + void shouldGetItsOwnText() { + // when + String result = action.getText(); + + // then + assertThat(result).isEqualTo(TEXT); + } + + @Test + void shouldGetItsOwnIcon() { + // when + Icon result = action.getIcon(); + + // then + assertThat(result).isEqualTo(ICON); + } + + @Test + void shouldDoNothingWhenInvokingExecute() { + // this test has no assertion. Is it really useful, if so it needs rework. + // when + action.execute(); + } +} diff --git a/src/test/java/pl/mjedynak/idea/plugins/builder/action/RegenerateBuilderAdditionalActionTest.java b/src/test/java/pl/mjedynak/idea/plugins/builder/action/RegenerateBuilderAdditionalActionTest.java index 7652590..bfb5fda 100644 --- a/src/test/java/pl/mjedynak/idea/plugins/builder/action/RegenerateBuilderAdditionalActionTest.java +++ b/src/test/java/pl/mjedynak/idea/plugins/builder/action/RegenerateBuilderAdditionalActionTest.java @@ -1,46 +1,46 @@ -package pl.mjedynak.idea.plugins.builder.action; - -import static org.assertj.core.api.Assertions.assertThat; - -import com.intellij.openapi.util.IconLoader; -import javax.swing.Icon; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -public class RegenerateBuilderAdditionalActionTest { - - private static final String TEXT = "Regenerate builder..."; - private static final Icon ICON = IconLoader.getIcon("/actions/intentionBulb.png"); - - private RegenerateBuilderAdditionalAction action; - - @BeforeEach - public void setUp() { - action = new RegenerateBuilderAdditionalAction(); - } - - @Test - void shouldGetItsOwnText() { - // when - String result = action.getText(); - - // then - assertThat(result).isEqualTo(TEXT); - } - - @Test - void shouldGetItsOwnIcon() { - // when - Icon result = action.getIcon(); - - // then - assertThat(result).isEqualTo(ICON); - } - - @Test - void shouldDoNothingWhenInvokingExecute() { - // this test has no assertion. Is it really useful, if so it needs rework. - // when - action.execute(); - } -} +package pl.mjedynak.idea.plugins.builder.action; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.intellij.openapi.util.IconLoader; +import javax.swing.Icon; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class RegenerateBuilderAdditionalActionTest { + + private static final String TEXT = "Regenerate builder..."; + private static final Icon ICON = IconLoader.getIcon("/actions/intentionBulb.png"); + + private RegenerateBuilderAdditionalAction action; + + @BeforeEach + public void setUp() { + action = new RegenerateBuilderAdditionalAction(); + } + + @Test + void shouldGetItsOwnText() { + // when + String result = action.getText(); + + // then + assertThat(result).isEqualTo(TEXT); + } + + @Test + void shouldGetItsOwnIcon() { + // when + Icon result = action.getIcon(); + + // then + assertThat(result).isEqualTo(ICON); + } + + @Test + void shouldDoNothingWhenInvokingExecute() { + // this test has no assertion. Is it really useful, if so it needs rework. + // when + action.execute(); + } +} diff --git a/src/test/java/pl/mjedynak/idea/plugins/builder/action/handler/GenerateBuilderActionHandlerTest.java b/src/test/java/pl/mjedynak/idea/plugins/builder/action/handler/GenerateBuilderActionHandlerTest.java index ea1a286..b3a3dcf 100644 --- a/src/test/java/pl/mjedynak/idea/plugins/builder/action/handler/GenerateBuilderActionHandlerTest.java +++ b/src/test/java/pl/mjedynak/idea/plugins/builder/action/handler/GenerateBuilderActionHandlerTest.java @@ -1,174 +1,174 @@ -package pl.mjedynak.idea.plugins.builder.action.handler; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -import com.intellij.openapi.actionSystem.CommonDataKeys; -import com.intellij.openapi.actionSystem.DataContext; -import com.intellij.openapi.editor.Editor; -import com.intellij.openapi.project.Project; -import com.intellij.psi.PsiClass; -import javax.swing.JList; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.ArgumentCaptor; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import pl.mjedynak.idea.plugins.builder.action.GoToBuilderAdditionalAction; -import pl.mjedynak.idea.plugins.builder.action.RegenerateBuilderAdditionalAction; -import pl.mjedynak.idea.plugins.builder.factory.GenerateBuilderPopupListFactory; -import pl.mjedynak.idea.plugins.builder.finder.BuilderFinder; -import pl.mjedynak.idea.plugins.builder.gui.displayer.GenerateBuilderPopupDisplayer; -import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; -import pl.mjedynak.idea.plugins.builder.verifier.BuilderVerifier; - -@ExtendWith(MockitoExtension.class) -public class GenerateBuilderActionHandlerTest { - - @InjectMocks - private GenerateBuilderActionHandler builderActionHandler; - - @Mock - private BuilderVerifier builderVerifier; - - @Mock - private BuilderFinder builderFinder; - - @Mock - private PsiHelper psiHelper; - - @Mock - private GenerateBuilderPopupListFactory popupListFactory; - - @Mock - private GenerateBuilderPopupDisplayer popupDisplayer; - - @Mock - private DisplayChoosers displayChoosers; - - @Mock - private PsiClass psiClass; - - @Mock - private PsiClass builderClass; - - @Mock - private Editor editor; - - @Mock - private Project project; - - @Mock - private DataContext dataContext; - - @SuppressWarnings("rawtypes") - @Mock - private JList list; - - @BeforeEach - public void setUp() { - given(dataContext.getData(CommonDataKeys.PROJECT.getName())).willReturn(project); - } - - @Test - void shouldDisplayPopupWhenBuilderIsFoundAndInvokedInsideNotBuilderClass() { - // given - given(psiHelper.getPsiClassFromEditor(editor, project)).willReturn(psiClass); - given(builderVerifier.isBuilder(psiClass)).willReturn(false); - given(builderFinder.findBuilderForClass(psiClass)).willReturn(builderClass); - given(popupListFactory.getPopupList()).willReturn(list); - - // when - builderActionHandler.execute(editor, dataContext); - - // then - verifyDisplayChoosersSetMethods(); - ArgumentCaptor runnableArgumentCaptor = ArgumentCaptor.forClass(Runnable.class); - verify(popupDisplayer).displayPopupChooser(eq(editor), eq(list), runnableArgumentCaptor.capture()); - testRunnableWhenGoToBuilderIsSelected(runnableArgumentCaptor); - testRunnableWhenRegenerateBuilderIsSelected(runnableArgumentCaptor); - } - - private void verifyDisplayChoosersSetMethods() { - verify(displayChoosers).setEditor(editor); - verify(displayChoosers).setProject(project); - verify(displayChoosers).setPsiClassFromEditor(psiClass); - } - - private void testRunnableWhenGoToBuilderIsSelected(ArgumentCaptor runnableArgumentCaptor) { - // given - given(list.getSelectedValue()).willReturn(new GoToBuilderAdditionalAction()); - - // when - runnableArgumentCaptor.getValue().run(); - - // then - verify(psiHelper).navigateToClass(builderClass); - } - - private void testRunnableWhenRegenerateBuilderIsSelected(ArgumentCaptor runnableArgumentCaptor) { - // given - given(list.getSelectedValue()).willReturn(new RegenerateBuilderAdditionalAction()); - - // when - runnableArgumentCaptor.getValue().run(); - - // then - verify(displayChoosers).run(builderClass); - } - - @Test - void shouldDirectlyCallDisplayChoosersWhenBuilderNotFoundAndInvokedInsideNotBuilderClass() { - // given - given(psiHelper.getPsiClassFromEditor(editor, project)).willReturn(psiClass); - given(builderVerifier.isBuilder(psiClass)).willReturn(false); - given(builderFinder.findBuilderForClass(psiClass)).willReturn(null); - - // when - builderActionHandler.execute(editor, dataContext); - - // then - verifyDisplayChoosersSetMethods(); - verify(displayChoosers).run(null); - } - - @Test - void shouldNotDoAnythingWhenNotBuilderClassFoundAndInvokedInsideBuilder() { - // given - given(psiHelper.getPsiClassFromEditor(editor, project)).willReturn(builderClass); - given(builderVerifier.isBuilder(builderClass)).willReturn(true); - given(builderFinder.findClassForBuilder(builderClass)).willReturn(psiClass); - - // when - builderActionHandler.execute(editor, dataContext); - - // then - verifyNothingIsDone(); - } - - @Test - void shouldNotDoAnythingWhenNotBuilderClassNotFoundAndInvokedInsideBuilder() { - // given - given(psiHelper.getPsiClassFromEditor(editor, project)).willReturn(builderClass); - given(builderVerifier.isBuilder(builderClass)).willReturn(true); - given(builderFinder.findClassForBuilder(builderClass)).willReturn(null); - - // when - builderActionHandler.execute(editor, dataContext); - - // then - verifyNothingIsDone(); - } - - private void verifyNothingIsDone() { - verify(psiHelper, never()).navigateToClass(any(PsiClass.class)); - verify(displayChoosers, never()).run(any(PsiClass.class)); - verifyNoMoreInteractions(popupDisplayer); - } -} +package pl.mjedynak.idea.plugins.builder.action.handler; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +import com.intellij.openapi.actionSystem.CommonDataKeys; +import com.intellij.openapi.actionSystem.DataContext; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.project.Project; +import com.intellij.psi.PsiClass; +import javax.swing.JList; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import pl.mjedynak.idea.plugins.builder.action.GoToBuilderAdditionalAction; +import pl.mjedynak.idea.plugins.builder.action.RegenerateBuilderAdditionalAction; +import pl.mjedynak.idea.plugins.builder.factory.GenerateBuilderPopupListFactory; +import pl.mjedynak.idea.plugins.builder.finder.BuilderFinder; +import pl.mjedynak.idea.plugins.builder.gui.displayer.GenerateBuilderPopupDisplayer; +import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; +import pl.mjedynak.idea.plugins.builder.verifier.BuilderVerifier; + +@ExtendWith(MockitoExtension.class) +public class GenerateBuilderActionHandlerTest { + + @InjectMocks + private GenerateBuilderActionHandler builderActionHandler; + + @Mock + private BuilderVerifier builderVerifier; + + @Mock + private BuilderFinder builderFinder; + + @Mock + private PsiHelper psiHelper; + + @Mock + private GenerateBuilderPopupListFactory popupListFactory; + + @Mock + private GenerateBuilderPopupDisplayer popupDisplayer; + + @Mock + private DisplayChoosers displayChoosers; + + @Mock + private PsiClass psiClass; + + @Mock + private PsiClass builderClass; + + @Mock + private Editor editor; + + @Mock + private Project project; + + @Mock + private DataContext dataContext; + + @SuppressWarnings("rawtypes") + @Mock + private JList list; + + @BeforeEach + public void setUp() { + given(dataContext.getData(CommonDataKeys.PROJECT.getName())).willReturn(project); + } + + @Test + void shouldDisplayPopupWhenBuilderIsFoundAndInvokedInsideNotBuilderClass() { + // given + given(psiHelper.getPsiClassFromEditor(editor, project)).willReturn(psiClass); + given(builderVerifier.isBuilder(psiClass)).willReturn(false); + given(builderFinder.findBuilderForClass(psiClass)).willReturn(builderClass); + given(popupListFactory.getPopupList()).willReturn(list); + + // when + builderActionHandler.execute(editor, dataContext); + + // then + verifyDisplayChoosersSetMethods(); + ArgumentCaptor runnableArgumentCaptor = ArgumentCaptor.forClass(Runnable.class); + verify(popupDisplayer).displayPopupChooser(eq(editor), eq(list), runnableArgumentCaptor.capture()); + testRunnableWhenGoToBuilderIsSelected(runnableArgumentCaptor); + testRunnableWhenRegenerateBuilderIsSelected(runnableArgumentCaptor); + } + + private void verifyDisplayChoosersSetMethods() { + verify(displayChoosers).setEditor(editor); + verify(displayChoosers).setProject(project); + verify(displayChoosers).setPsiClassFromEditor(psiClass); + } + + private void testRunnableWhenGoToBuilderIsSelected(ArgumentCaptor runnableArgumentCaptor) { + // given + given(list.getSelectedValue()).willReturn(new GoToBuilderAdditionalAction()); + + // when + runnableArgumentCaptor.getValue().run(); + + // then + verify(psiHelper).navigateToClass(builderClass); + } + + private void testRunnableWhenRegenerateBuilderIsSelected(ArgumentCaptor runnableArgumentCaptor) { + // given + given(list.getSelectedValue()).willReturn(new RegenerateBuilderAdditionalAction()); + + // when + runnableArgumentCaptor.getValue().run(); + + // then + verify(displayChoosers).run(builderClass); + } + + @Test + void shouldDirectlyCallDisplayChoosersWhenBuilderNotFoundAndInvokedInsideNotBuilderClass() { + // given + given(psiHelper.getPsiClassFromEditor(editor, project)).willReturn(psiClass); + given(builderVerifier.isBuilder(psiClass)).willReturn(false); + given(builderFinder.findBuilderForClass(psiClass)).willReturn(null); + + // when + builderActionHandler.execute(editor, dataContext); + + // then + verifyDisplayChoosersSetMethods(); + verify(displayChoosers).run(null); + } + + @Test + void shouldNotDoAnythingWhenNotBuilderClassFoundAndInvokedInsideBuilder() { + // given + given(psiHelper.getPsiClassFromEditor(editor, project)).willReturn(builderClass); + given(builderVerifier.isBuilder(builderClass)).willReturn(true); + given(builderFinder.findClassForBuilder(builderClass)).willReturn(psiClass); + + // when + builderActionHandler.execute(editor, dataContext); + + // then + verifyNothingIsDone(); + } + + @Test + void shouldNotDoAnythingWhenNotBuilderClassNotFoundAndInvokedInsideBuilder() { + // given + given(psiHelper.getPsiClassFromEditor(editor, project)).willReturn(builderClass); + given(builderVerifier.isBuilder(builderClass)).willReturn(true); + given(builderFinder.findClassForBuilder(builderClass)).willReturn(null); + + // when + builderActionHandler.execute(editor, dataContext); + + // then + verifyNothingIsDone(); + } + + private void verifyNothingIsDone() { + verify(psiHelper, never()).navigateToClass(any(PsiClass.class)); + verify(displayChoosers, never()).run(any(PsiClass.class)); + verifyNoMoreInteractions(popupDisplayer); + } +} diff --git a/src/test/java/pl/mjedynak/idea/plugins/builder/action/handler/GoToBuilderActionHandlerTest.java b/src/test/java/pl/mjedynak/idea/plugins/builder/action/handler/GoToBuilderActionHandlerTest.java index 76169a0..80b31fe 100644 --- a/src/test/java/pl/mjedynak/idea/plugins/builder/action/handler/GoToBuilderActionHandlerTest.java +++ b/src/test/java/pl/mjedynak/idea/plugins/builder/action/handler/GoToBuilderActionHandlerTest.java @@ -1,149 +1,149 @@ -package pl.mjedynak.idea.plugins.builder.action.handler; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -import com.intellij.openapi.actionSystem.CommonDataKeys; -import com.intellij.openapi.actionSystem.DataContext; -import com.intellij.openapi.editor.Editor; -import com.intellij.openapi.project.Project; -import com.intellij.psi.PsiClass; -import javax.swing.JList; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.ArgumentCaptor; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import pl.mjedynak.idea.plugins.builder.factory.GoToBuilderPopupListFactory; -import pl.mjedynak.idea.plugins.builder.finder.BuilderFinder; -import pl.mjedynak.idea.plugins.builder.gui.displayer.GoToBuilderPopupDisplayer; -import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; -import pl.mjedynak.idea.plugins.builder.verifier.BuilderVerifier; - -@ExtendWith(MockitoExtension.class) -public class GoToBuilderActionHandlerTest { - - @InjectMocks - private GoToBuilderActionHandler builderActionHandler; - - @Mock - private BuilderVerifier builderVerifier; - - @Mock - private BuilderFinder builderFinder; - - @Mock - private PsiHelper psiHelper; - - @Mock - private GoToBuilderPopupListFactory popupListFactory; - - @Mock - private GoToBuilderPopupDisplayer popupDisplayer; - - @Mock - private DisplayChoosers displayChoosers; - - @Mock - private PsiClass psiClass; - - @Mock - private PsiClass builderClass; - - @Mock - private Editor editor; - - @Mock - private Project project; - - @Mock - private DataContext dataContext; - - @SuppressWarnings("rawtypes") - @Mock - private JList list; - - @BeforeEach - public void setUp() { - given(dataContext.getData(CommonDataKeys.PROJECT.getName())).willReturn(project); - } - - @Test - void shouldNavigateToBuilderIfItExistsAndInvokedInsideNotBuilderClass() { - // given - given(psiHelper.getPsiClassFromEditor(editor, project)).willReturn(psiClass); - given(builderVerifier.isBuilder(psiClass)).willReturn(false); - given(builderFinder.findBuilderForClass(psiClass)).willReturn(builderClass); - - // when - builderActionHandler.execute(editor, dataContext); - - // then - verify(psiHelper).navigateToClass(builderClass); - } - - @Test - void shouldNavigateToNotBuilderClassIfItExistsAndInvokedInsideBuilder() { - // given - given(psiHelper.getPsiClassFromEditor(editor, project)).willReturn(builderClass); - given(builderVerifier.isBuilder(builderClass)).willReturn(true); - given(builderFinder.findClassForBuilder(builderClass)).willReturn(psiClass); - - // when - builderActionHandler.execute(editor, dataContext); - - // then - verify(psiHelper).navigateToClass(psiClass); - } - - @Test - void shouldDisplayPopupWhenBuilderNotFoundAndInvokedInsideNotBuilderClass() { - // given - given(psiHelper.getPsiClassFromEditor(editor, project)).willReturn(psiClass); - given(builderVerifier.isBuilder(psiClass)).willReturn(false); - given(builderFinder.findBuilderForClass(psiClass)).willReturn(null); - given(popupListFactory.getPopupList()).willReturn(list); - - // when - builderActionHandler.execute(editor, dataContext); - - // then - verifyDisplayChoosersSetMethods(); - ArgumentCaptor runnableArgumentCaptor = ArgumentCaptor.forClass(Runnable.class); - verify(popupDisplayer).displayPopupChooser(eq(editor), eq(list), runnableArgumentCaptor.capture()); - runnableArgumentCaptor.getValue().run(); - verify(displayChoosers).run(null); - } - - private void verifyDisplayChoosersSetMethods() { - verify(displayChoosers).setEditor(editor); - verify(displayChoosers).setProject(project); - verify(displayChoosers).setPsiClassFromEditor(psiClass); - } - - @Test - void shouldNotDoAnythingWhenNotBuilderClassNotFoundAndInvokedInsideBuilder() { - // given - given(psiHelper.getPsiClassFromEditor(editor, project)).willReturn(builderClass); - given(builderVerifier.isBuilder(builderClass)).willReturn(true); - given(builderFinder.findClassForBuilder(builderClass)).willReturn(null); - - // when - builderActionHandler.execute(editor, dataContext); - - // then - verifyNothingIsDone(); - } - - private void verifyNothingIsDone() { - verify(psiHelper, never()).navigateToClass(any(PsiClass.class)); - verify(displayChoosers, never()).run(any(PsiClass.class)); - verifyNoMoreInteractions(popupDisplayer); - } -} +package pl.mjedynak.idea.plugins.builder.action.handler; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +import com.intellij.openapi.actionSystem.CommonDataKeys; +import com.intellij.openapi.actionSystem.DataContext; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.project.Project; +import com.intellij.psi.PsiClass; +import javax.swing.JList; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import pl.mjedynak.idea.plugins.builder.factory.GoToBuilderPopupListFactory; +import pl.mjedynak.idea.plugins.builder.finder.BuilderFinder; +import pl.mjedynak.idea.plugins.builder.gui.displayer.GoToBuilderPopupDisplayer; +import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; +import pl.mjedynak.idea.plugins.builder.verifier.BuilderVerifier; + +@ExtendWith(MockitoExtension.class) +public class GoToBuilderActionHandlerTest { + + @InjectMocks + private GoToBuilderActionHandler builderActionHandler; + + @Mock + private BuilderVerifier builderVerifier; + + @Mock + private BuilderFinder builderFinder; + + @Mock + private PsiHelper psiHelper; + + @Mock + private GoToBuilderPopupListFactory popupListFactory; + + @Mock + private GoToBuilderPopupDisplayer popupDisplayer; + + @Mock + private DisplayChoosers displayChoosers; + + @Mock + private PsiClass psiClass; + + @Mock + private PsiClass builderClass; + + @Mock + private Editor editor; + + @Mock + private Project project; + + @Mock + private DataContext dataContext; + + @SuppressWarnings("rawtypes") + @Mock + private JList list; + + @BeforeEach + public void setUp() { + given(dataContext.getData(CommonDataKeys.PROJECT.getName())).willReturn(project); + } + + @Test + void shouldNavigateToBuilderIfItExistsAndInvokedInsideNotBuilderClass() { + // given + given(psiHelper.getPsiClassFromEditor(editor, project)).willReturn(psiClass); + given(builderVerifier.isBuilder(psiClass)).willReturn(false); + given(builderFinder.findBuilderForClass(psiClass)).willReturn(builderClass); + + // when + builderActionHandler.execute(editor, dataContext); + + // then + verify(psiHelper).navigateToClass(builderClass); + } + + @Test + void shouldNavigateToNotBuilderClassIfItExistsAndInvokedInsideBuilder() { + // given + given(psiHelper.getPsiClassFromEditor(editor, project)).willReturn(builderClass); + given(builderVerifier.isBuilder(builderClass)).willReturn(true); + given(builderFinder.findClassForBuilder(builderClass)).willReturn(psiClass); + + // when + builderActionHandler.execute(editor, dataContext); + + // then + verify(psiHelper).navigateToClass(psiClass); + } + + @Test + void shouldDisplayPopupWhenBuilderNotFoundAndInvokedInsideNotBuilderClass() { + // given + given(psiHelper.getPsiClassFromEditor(editor, project)).willReturn(psiClass); + given(builderVerifier.isBuilder(psiClass)).willReturn(false); + given(builderFinder.findBuilderForClass(psiClass)).willReturn(null); + given(popupListFactory.getPopupList()).willReturn(list); + + // when + builderActionHandler.execute(editor, dataContext); + + // then + verifyDisplayChoosersSetMethods(); + ArgumentCaptor runnableArgumentCaptor = ArgumentCaptor.forClass(Runnable.class); + verify(popupDisplayer).displayPopupChooser(eq(editor), eq(list), runnableArgumentCaptor.capture()); + runnableArgumentCaptor.getValue().run(); + verify(displayChoosers).run(null); + } + + private void verifyDisplayChoosersSetMethods() { + verify(displayChoosers).setEditor(editor); + verify(displayChoosers).setProject(project); + verify(displayChoosers).setPsiClassFromEditor(psiClass); + } + + @Test + void shouldNotDoAnythingWhenNotBuilderClassNotFoundAndInvokedInsideBuilder() { + // given + given(psiHelper.getPsiClassFromEditor(editor, project)).willReturn(builderClass); + given(builderVerifier.isBuilder(builderClass)).willReturn(true); + given(builderFinder.findClassForBuilder(builderClass)).willReturn(null); + + // when + builderActionHandler.execute(editor, dataContext); + + // then + verifyNothingIsDone(); + } + + private void verifyNothingIsDone() { + verify(psiHelper, never()).navigateToClass(any(PsiClass.class)); + verify(displayChoosers, never()).run(any(PsiClass.class)); + verifyNoMoreInteractions(popupDisplayer); + } +} diff --git a/src/test/java/pl/mjedynak/idea/plugins/builder/factory/GoToBuilderPopupListFactoryTest.java b/src/test/java/pl/mjedynak/idea/plugins/builder/factory/GoToBuilderPopupListFactoryTest.java index ab148c6..ee81619 100644 --- a/src/test/java/pl/mjedynak/idea/plugins/builder/factory/GoToBuilderPopupListFactoryTest.java +++ b/src/test/java/pl/mjedynak/idea/plugins/builder/factory/GoToBuilderPopupListFactoryTest.java @@ -1,49 +1,49 @@ -package pl.mjedynak.idea.plugins.builder.factory; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.test.util.ReflectionTestUtils.getField; - -import com.intellij.ui.ExpandedItemListCellRendererWrapper; -import com.intellij.ui.components.JBList; -import javax.swing.JList; -import org.junit.jupiter.api.Test; -import pl.mjedynak.idea.plugins.builder.renderer.ActionCellRenderer; - -public class GoToBuilderPopupListFactoryTest { - - private final AbstractPopupListFactory popupListFactory = new GoToBuilderPopupListFactory(); - - @Test - void shouldCreateJBListWithActionCellRenderer() { - // when - JList popupList = popupListFactory.getPopupList(); - - // then - assertThat(popupList).isInstanceOf(JBList.class); - assertThat(popupList.getCellRenderer()).isInstanceOf(ExpandedItemListCellRendererWrapper.class); - assertThat(((ExpandedItemListCellRendererWrapper) popupList.getCellRenderer()).getWrappee()) - .isInstanceOf(ActionCellRenderer.class); - assertThat(((JBList) popupList).getItemsCount()).isEqualTo(1); - } - - @Test - void shouldLazilyInitializeCellRenderer() { - // when - Object actionCellRenderer = getField(popupListFactory, "actionCellRenderer"); - - // then - assertThat(actionCellRenderer).isNull(); - } - - @Test - void shouldUseTheSameCellRendererForConsequentInvocations() { - // when - popupListFactory.getPopupList(); - ActionCellRenderer firstRenderer = (ActionCellRenderer) getField(popupListFactory, "actionCellRenderer"); - popupListFactory.getPopupList(); - ActionCellRenderer secondRenderer = (ActionCellRenderer) getField(popupListFactory, "actionCellRenderer"); - - // then - assertThat(firstRenderer).isSameAs(secondRenderer); - } -} +package pl.mjedynak.idea.plugins.builder.factory; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.util.ReflectionTestUtils.getField; + +import com.intellij.ui.ExpandedItemListCellRendererWrapper; +import com.intellij.ui.components.JBList; +import javax.swing.JList; +import org.junit.jupiter.api.Test; +import pl.mjedynak.idea.plugins.builder.renderer.ActionCellRenderer; + +public class GoToBuilderPopupListFactoryTest { + + private final AbstractPopupListFactory popupListFactory = new GoToBuilderPopupListFactory(); + + @Test + void shouldCreateJBListWithActionCellRenderer() { + // when + JList popupList = popupListFactory.getPopupList(); + + // then + assertThat(popupList).isInstanceOf(JBList.class); + assertThat(popupList.getCellRenderer()).isInstanceOf(ExpandedItemListCellRendererWrapper.class); + assertThat(((ExpandedItemListCellRendererWrapper) popupList.getCellRenderer()).getWrappee()) + .isInstanceOf(ActionCellRenderer.class); + assertThat(((JBList) popupList).getItemsCount()).isEqualTo(1); + } + + @Test + void shouldLazilyInitializeCellRenderer() { + // when + Object actionCellRenderer = getField(popupListFactory, "actionCellRenderer"); + + // then + assertThat(actionCellRenderer).isNull(); + } + + @Test + void shouldUseTheSameCellRendererForConsequentInvocations() { + // when + popupListFactory.getPopupList(); + ActionCellRenderer firstRenderer = (ActionCellRenderer) getField(popupListFactory, "actionCellRenderer"); + popupListFactory.getPopupList(); + ActionCellRenderer secondRenderer = (ActionCellRenderer) getField(popupListFactory, "actionCellRenderer"); + + // then + assertThat(firstRenderer).isSameAs(secondRenderer); + } +} diff --git a/src/test/java/pl/mjedynak/idea/plugins/builder/factory/PackageChooserDialogFactoryTest.java b/src/test/java/pl/mjedynak/idea/plugins/builder/factory/PackageChooserDialogFactoryTest.java index 3129903..5d7132d 100644 --- a/src/test/java/pl/mjedynak/idea/plugins/builder/factory/PackageChooserDialogFactoryTest.java +++ b/src/test/java/pl/mjedynak/idea/plugins/builder/factory/PackageChooserDialogFactoryTest.java @@ -1,45 +1,45 @@ -package pl.mjedynak.idea.plugins.builder.factory; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.doReturn; - -import com.intellij.ide.util.PackageChooserDialog; -import com.intellij.openapi.project.Project; -import com.intellij.psi.PsiManager; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.Spy; -import org.mockito.junit.jupiter.MockitoExtension; - -@ExtendWith(MockitoExtension.class) -public class PackageChooserDialogFactoryTest { - - @Spy - private PackageChooserDialogFactory packageChooserDialogFactory; - - @Mock - private Project project; - - @Mock - private PsiManager psiManager; - - @Mock - private PackageChooserDialog packageChooserDialog; - - @Test - void shouldCreatePackageChooserDialogWithPassedTitle() { - // given - String title = "title"; - given(packageChooserDialog.getTitle()).willReturn(title); - doReturn(packageChooserDialog).when(packageChooserDialogFactory).createNewInstance(title, project); - - // when - PackageChooserDialog result = packageChooserDialogFactory.getPackageChooserDialog(title, project); - - // then - assertThat(result).isEqualTo(packageChooserDialog); - assertThat(result.getTitle()).isEqualTo(title); - } -} +package pl.mjedynak.idea.plugins.builder.factory; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.doReturn; + +import com.intellij.ide.util.PackageChooserDialog; +import com.intellij.openapi.project.Project; +import com.intellij.psi.PsiManager; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +public class PackageChooserDialogFactoryTest { + + @Spy + private PackageChooserDialogFactory packageChooserDialogFactory; + + @Mock + private Project project; + + @Mock + private PsiManager psiManager; + + @Mock + private PackageChooserDialog packageChooserDialog; + + @Test + void shouldCreatePackageChooserDialogWithPassedTitle() { + // given + String title = "title"; + given(packageChooserDialog.getTitle()).willReturn(title); + doReturn(packageChooserDialog).when(packageChooserDialogFactory).createNewInstance(title, project); + + // when + PackageChooserDialog result = packageChooserDialogFactory.getPackageChooserDialog(title, project); + + // then + assertThat(result).isEqualTo(packageChooserDialog); + assertThat(result.getTitle()).isEqualTo(title); + } +} diff --git a/src/test/java/pl/mjedynak/idea/plugins/builder/factory/PsiFieldsForBuilderFactoryTest.java b/src/test/java/pl/mjedynak/idea/plugins/builder/factory/PsiFieldsForBuilderFactoryTest.java index 8c19793..0563610 100644 --- a/src/test/java/pl/mjedynak/idea/plugins/builder/factory/PsiFieldsForBuilderFactoryTest.java +++ b/src/test/java/pl/mjedynak/idea/plugins/builder/factory/PsiFieldsForBuilderFactoryTest.java @@ -1,227 +1,227 @@ -package pl.mjedynak.idea.plugins.builder.factory; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.anyList; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.verify; - -import com.google.common.collect.Lists; -import com.intellij.codeInsight.generation.PsiElementClassMember; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiField; -import com.intellij.psi.PsiMethod; -import java.util.List; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Captor; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import pl.mjedynak.idea.plugins.builder.psi.BestConstructorSelector; -import pl.mjedynak.idea.plugins.builder.psi.model.PsiFieldsForBuilder; -import pl.mjedynak.idea.plugins.builder.verifier.PsiFieldVerifier; - -@ExtendWith(MockitoExtension.class) -public class PsiFieldsForBuilderFactoryTest { - - private static final String PSI_FIELD_NAME = "psiFieldName"; - private static final String PSI_FIELD_NAME_IN_SETTER_ONLY = "psiFieldNameInSetterOnly"; - private static final String PSI_FIELD_NAME_IN_CONSTRUCTOR_ONLY = "psiFieldNameInConstructorOnly"; - private static final String PSI_FIELD_NAME_IN_SETTER_AND_CONSTRUCTOR = "psiFieldNameInSetterAndConstructor"; - private static final String PSI_FIELD_NAME_NOWHERE = "psiFieldNameNowhere"; - - @InjectMocks - private PsiFieldsForBuilderFactory factory; - - @Mock - private PsiFieldVerifier psiFieldVerifier; - - @Mock - private PsiClass psiClass; - - @Mock - private PsiElementClassMember psiElementClassMember; - - @Mock - private PsiElementClassMember psiElementClassMemberInSetterOnly; - - @Mock - private PsiElementClassMember psiElementClassMemberInConstructorOnly; - - @Mock - private PsiElementClassMember psiElementClassMemberInSetterAndConstructor; - - @Mock - private PsiElementClassMember psiElementClassMemberNowhere; - - @Mock - private PsiField psiField; - - @Mock - private PsiField psiFieldInSetterOnly; - - @Mock - private PsiField psiFieldInConstructorOnly; - - @Mock - private PsiField psiFieldInSetterAndConstructor; - - @Mock - private PsiField psiFieldNowhere; - - @Mock - private BestConstructorSelector bestConstructorSelector; - - @Mock - private PsiMethod bestConstructor; - - @Captor - private ArgumentCaptor> argumentCaptor; - - private List> psiElementClassMembers; - - private void initCommonMock() { - psiElementClassMembers = List.of(psiElementClassMember); - given(psiElementClassMember.getPsiElement()).willReturn(psiField); - given(psiField.getName()).willReturn(PSI_FIELD_NAME); - } - - @Test - void shouldCreateObjectWithPsiFieldsForSetters() { - // given - initCommonMock(); - given(psiFieldVerifier.isSetInSetterMethod(psiField, psiClass)).willReturn(true); - given(bestConstructorSelector.getBestConstructor(anyList(), eq(psiClass))) - .willReturn(bestConstructor); - given(psiFieldVerifier.checkConstructor(psiField, bestConstructor)).willReturn(false); - - // when - PsiFieldsForBuilder result = factory.createPsiFieldsForBuilder(psiElementClassMembers, psiClass); - - // then - assertThat(result).isNotNull(); - assertThat(result.getFieldsForConstructor()).isNotNull().hasSize(0); - assertThat(result.getFieldsForSetters()).isNotNull().hasSize(1).containsOnly(psiField); - - verify(psiFieldVerifier).isSetInSetterMethod(psiField, psiClass); - verify(bestConstructorSelector).getBestConstructor(argumentCaptor.capture(), eq(psiClass)); - assertThat(argumentCaptor.getValue()).isNotNull().hasSize(0); - verify(psiFieldVerifier).checkConstructor(psiField, bestConstructor); - } - - @Test - void shouldCreateObjectWithPsiFieldsForConstructor() { - // given - initCommonMock(); - given(psiFieldVerifier.isSetInSetterMethod(psiField, psiClass)).willReturn(false); - given(bestConstructorSelector.getBestConstructor(anyList(), eq(psiClass))) - .willReturn(bestConstructor); - given(psiFieldVerifier.checkConstructor(psiField, bestConstructor)).willReturn(true); - - // when - PsiFieldsForBuilder result = factory.createPsiFieldsForBuilder(psiElementClassMembers, psiClass); - - // then - assertThat(result).isNotNull(); - assertThat(result.getFieldsForSetters()).isNotNull().hasSize(0); - assertThat(result.getFieldsForConstructor()).isNotNull().hasSize(1).containsOnly(psiField); - - verify(psiFieldVerifier).isSetInSetterMethod(psiField, psiClass); - verify(bestConstructorSelector).getBestConstructor(argumentCaptor.capture(), eq(psiClass)); - assertThat(argumentCaptor.getValue()) - .isNotNull() - .hasSize(1) - .extracting("name") - .containsOnly(PSI_FIELD_NAME); - verify(psiFieldVerifier).checkConstructor(psiField, bestConstructor); - } - - @Test - void shouldCreateObjectWithEmptyList() { - // given - initCommonMock(); - given(psiFieldVerifier.isSetInSetterMethod(psiField, psiClass)).willReturn(false); - given(bestConstructorSelector.getBestConstructor(anyList(), eq(psiClass))) - .willReturn(bestConstructor); - given(psiFieldVerifier.checkConstructor(psiField, bestConstructor)).willReturn(false); - - // when - PsiFieldsForBuilder result = factory.createPsiFieldsForBuilder(psiElementClassMembers, psiClass); - - // then - assertThat(result).isNotNull(); - assertThat(result.getFieldsForSetters()).isNotNull().hasSize(0); - assertThat(result.getFieldsForConstructor()).isNotNull().hasSize(0); - - verify(psiFieldVerifier).isSetInSetterMethod(psiField, psiClass); - verify(bestConstructorSelector).getBestConstructor(argumentCaptor.capture(), eq(psiClass)); - assertThat(argumentCaptor.getValue()) - .isNotNull() - .hasSize(1) - .extracting("name") - .containsOnly(PSI_FIELD_NAME); - verify(psiFieldVerifier).checkConstructor(psiField, bestConstructor); - } - - @Test - void shouldManageTrickyCaseAccordingToBestConstructorSelection() { - // given - psiElementClassMembers = Lists.newArrayList( - psiElementClassMemberInSetterOnly, - psiElementClassMemberInConstructorOnly, - psiElementClassMemberInSetterAndConstructor, - psiElementClassMemberNowhere); - - given(psiElementClassMemberInSetterOnly.getPsiElement()).willReturn(psiFieldInSetterOnly); - given(psiElementClassMemberInConstructorOnly.getPsiElement()).willReturn(psiFieldInConstructorOnly); - given(psiElementClassMemberInSetterAndConstructor.getPsiElement()).willReturn(psiFieldInSetterAndConstructor); - given(psiElementClassMemberNowhere.getPsiElement()).willReturn(psiFieldNowhere); - - given(psiFieldInSetterOnly.getName()).willReturn(PSI_FIELD_NAME_IN_SETTER_ONLY); - given(psiFieldInConstructorOnly.getName()).willReturn(PSI_FIELD_NAME_IN_CONSTRUCTOR_ONLY); - given(psiFieldInSetterAndConstructor.getName()).willReturn(PSI_FIELD_NAME_IN_SETTER_AND_CONSTRUCTOR); - given(psiFieldNowhere.getName()).willReturn(PSI_FIELD_NAME_NOWHERE); - - given(psiFieldVerifier.isSetInSetterMethod(psiFieldInSetterOnly, psiClass)) - .willReturn(true); - given(psiFieldVerifier.isSetInSetterMethod(psiFieldInConstructorOnly, psiClass)) - .willReturn(false); - given(psiFieldVerifier.isSetInSetterMethod(psiFieldInSetterAndConstructor, psiClass)) - .willReturn(true); - given(psiFieldVerifier.isSetInSetterMethod(psiFieldNowhere, psiClass)).willReturn(false); - - given(bestConstructorSelector.getBestConstructor(anyList(), eq(psiClass))) - .willReturn(bestConstructor); - - given(psiFieldVerifier.checkConstructor(psiFieldInSetterOnly, bestConstructor)) - .willReturn(false); - given(psiFieldVerifier.checkConstructor(psiFieldInConstructorOnly, bestConstructor)) - .willReturn(true); - given(psiFieldVerifier.checkConstructor(psiFieldInSetterAndConstructor, bestConstructor)) - .willReturn(true); - given(psiFieldVerifier.checkConstructor(psiFieldNowhere, bestConstructor)) - .willReturn(false); - - // when - PsiFieldsForBuilder result = factory.createPsiFieldsForBuilder(psiElementClassMembers, psiClass); - - // then - assertThat(result).isNotNull(); - assertThat(result.getAllSelectedFields()) - .isNotNull() - .hasSize(4) - .containsOnly( - psiFieldInSetterOnly, - psiFieldInConstructorOnly, - psiFieldInSetterAndConstructor, - psiFieldNowhere); - assertThat(result.getFieldsForConstructor()) - .isNotNull() - .hasSize(2) - .containsOnly(psiFieldInConstructorOnly, psiFieldInSetterAndConstructor); - assertThat(result.getFieldsForSetters()).isNotNull().hasSize(1).containsOnly(psiFieldInSetterOnly); - assertThat(result.getBestConstructor()).isEqualTo(bestConstructor); - } -} +package pl.mjedynak.idea.plugins.builder.factory; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; + +import com.google.common.collect.Lists; +import com.intellij.codeInsight.generation.PsiElementClassMember; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiField; +import com.intellij.psi.PsiMethod; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import pl.mjedynak.idea.plugins.builder.psi.BestConstructorSelector; +import pl.mjedynak.idea.plugins.builder.psi.model.PsiFieldsForBuilder; +import pl.mjedynak.idea.plugins.builder.verifier.PsiFieldVerifier; + +@ExtendWith(MockitoExtension.class) +public class PsiFieldsForBuilderFactoryTest { + + private static final String PSI_FIELD_NAME = "psiFieldName"; + private static final String PSI_FIELD_NAME_IN_SETTER_ONLY = "psiFieldNameInSetterOnly"; + private static final String PSI_FIELD_NAME_IN_CONSTRUCTOR_ONLY = "psiFieldNameInConstructorOnly"; + private static final String PSI_FIELD_NAME_IN_SETTER_AND_CONSTRUCTOR = "psiFieldNameInSetterAndConstructor"; + private static final String PSI_FIELD_NAME_NOWHERE = "psiFieldNameNowhere"; + + @InjectMocks + private PsiFieldsForBuilderFactory factory; + + @Mock + private PsiFieldVerifier psiFieldVerifier; + + @Mock + private PsiClass psiClass; + + @Mock + private PsiElementClassMember psiElementClassMember; + + @Mock + private PsiElementClassMember psiElementClassMemberInSetterOnly; + + @Mock + private PsiElementClassMember psiElementClassMemberInConstructorOnly; + + @Mock + private PsiElementClassMember psiElementClassMemberInSetterAndConstructor; + + @Mock + private PsiElementClassMember psiElementClassMemberNowhere; + + @Mock + private PsiField psiField; + + @Mock + private PsiField psiFieldInSetterOnly; + + @Mock + private PsiField psiFieldInConstructorOnly; + + @Mock + private PsiField psiFieldInSetterAndConstructor; + + @Mock + private PsiField psiFieldNowhere; + + @Mock + private BestConstructorSelector bestConstructorSelector; + + @Mock + private PsiMethod bestConstructor; + + @Captor + private ArgumentCaptor> argumentCaptor; + + private List> psiElementClassMembers; + + private void initCommonMock() { + psiElementClassMembers = List.of(psiElementClassMember); + given(psiElementClassMember.getPsiElement()).willReturn(psiField); + given(psiField.getName()).willReturn(PSI_FIELD_NAME); + } + + @Test + void shouldCreateObjectWithPsiFieldsForSetters() { + // given + initCommonMock(); + given(psiFieldVerifier.isSetInSetterMethod(psiField, psiClass)).willReturn(true); + given(bestConstructorSelector.getBestConstructor(anyList(), eq(psiClass))) + .willReturn(bestConstructor); + given(psiFieldVerifier.checkConstructor(psiField, bestConstructor)).willReturn(false); + + // when + PsiFieldsForBuilder result = factory.createPsiFieldsForBuilder(psiElementClassMembers, psiClass); + + // then + assertThat(result).isNotNull(); + assertThat(result.getFieldsForConstructor()).isNotNull().hasSize(0); + assertThat(result.getFieldsForSetters()).isNotNull().hasSize(1).containsOnly(psiField); + + verify(psiFieldVerifier).isSetInSetterMethod(psiField, psiClass); + verify(bestConstructorSelector).getBestConstructor(argumentCaptor.capture(), eq(psiClass)); + assertThat(argumentCaptor.getValue()).isNotNull().hasSize(0); + verify(psiFieldVerifier).checkConstructor(psiField, bestConstructor); + } + + @Test + void shouldCreateObjectWithPsiFieldsForConstructor() { + // given + initCommonMock(); + given(psiFieldVerifier.isSetInSetterMethod(psiField, psiClass)).willReturn(false); + given(bestConstructorSelector.getBestConstructor(anyList(), eq(psiClass))) + .willReturn(bestConstructor); + given(psiFieldVerifier.checkConstructor(psiField, bestConstructor)).willReturn(true); + + // when + PsiFieldsForBuilder result = factory.createPsiFieldsForBuilder(psiElementClassMembers, psiClass); + + // then + assertThat(result).isNotNull(); + assertThat(result.getFieldsForSetters()).isNotNull().hasSize(0); + assertThat(result.getFieldsForConstructor()).isNotNull().hasSize(1).containsOnly(psiField); + + verify(psiFieldVerifier).isSetInSetterMethod(psiField, psiClass); + verify(bestConstructorSelector).getBestConstructor(argumentCaptor.capture(), eq(psiClass)); + assertThat(argumentCaptor.getValue()) + .isNotNull() + .hasSize(1) + .extracting("name") + .containsOnly(PSI_FIELD_NAME); + verify(psiFieldVerifier).checkConstructor(psiField, bestConstructor); + } + + @Test + void shouldCreateObjectWithEmptyList() { + // given + initCommonMock(); + given(psiFieldVerifier.isSetInSetterMethod(psiField, psiClass)).willReturn(false); + given(bestConstructorSelector.getBestConstructor(anyList(), eq(psiClass))) + .willReturn(bestConstructor); + given(psiFieldVerifier.checkConstructor(psiField, bestConstructor)).willReturn(false); + + // when + PsiFieldsForBuilder result = factory.createPsiFieldsForBuilder(psiElementClassMembers, psiClass); + + // then + assertThat(result).isNotNull(); + assertThat(result.getFieldsForSetters()).isNotNull().hasSize(0); + assertThat(result.getFieldsForConstructor()).isNotNull().hasSize(0); + + verify(psiFieldVerifier).isSetInSetterMethod(psiField, psiClass); + verify(bestConstructorSelector).getBestConstructor(argumentCaptor.capture(), eq(psiClass)); + assertThat(argumentCaptor.getValue()) + .isNotNull() + .hasSize(1) + .extracting("name") + .containsOnly(PSI_FIELD_NAME); + verify(psiFieldVerifier).checkConstructor(psiField, bestConstructor); + } + + @Test + void shouldManageTrickyCaseAccordingToBestConstructorSelection() { + // given + psiElementClassMembers = Lists.newArrayList( + psiElementClassMemberInSetterOnly, + psiElementClassMemberInConstructorOnly, + psiElementClassMemberInSetterAndConstructor, + psiElementClassMemberNowhere); + + given(psiElementClassMemberInSetterOnly.getPsiElement()).willReturn(psiFieldInSetterOnly); + given(psiElementClassMemberInConstructorOnly.getPsiElement()).willReturn(psiFieldInConstructorOnly); + given(psiElementClassMemberInSetterAndConstructor.getPsiElement()).willReturn(psiFieldInSetterAndConstructor); + given(psiElementClassMemberNowhere.getPsiElement()).willReturn(psiFieldNowhere); + + given(psiFieldInSetterOnly.getName()).willReturn(PSI_FIELD_NAME_IN_SETTER_ONLY); + given(psiFieldInConstructorOnly.getName()).willReturn(PSI_FIELD_NAME_IN_CONSTRUCTOR_ONLY); + given(psiFieldInSetterAndConstructor.getName()).willReturn(PSI_FIELD_NAME_IN_SETTER_AND_CONSTRUCTOR); + given(psiFieldNowhere.getName()).willReturn(PSI_FIELD_NAME_NOWHERE); + + given(psiFieldVerifier.isSetInSetterMethod(psiFieldInSetterOnly, psiClass)) + .willReturn(true); + given(psiFieldVerifier.isSetInSetterMethod(psiFieldInConstructorOnly, psiClass)) + .willReturn(false); + given(psiFieldVerifier.isSetInSetterMethod(psiFieldInSetterAndConstructor, psiClass)) + .willReturn(true); + given(psiFieldVerifier.isSetInSetterMethod(psiFieldNowhere, psiClass)).willReturn(false); + + given(bestConstructorSelector.getBestConstructor(anyList(), eq(psiClass))) + .willReturn(bestConstructor); + + given(psiFieldVerifier.checkConstructor(psiFieldInSetterOnly, bestConstructor)) + .willReturn(false); + given(psiFieldVerifier.checkConstructor(psiFieldInConstructorOnly, bestConstructor)) + .willReturn(true); + given(psiFieldVerifier.checkConstructor(psiFieldInSetterAndConstructor, bestConstructor)) + .willReturn(true); + given(psiFieldVerifier.checkConstructor(psiFieldNowhere, bestConstructor)) + .willReturn(false); + + // when + PsiFieldsForBuilder result = factory.createPsiFieldsForBuilder(psiElementClassMembers, psiClass); + + // then + assertThat(result).isNotNull(); + assertThat(result.getAllSelectedFields()) + .isNotNull() + .hasSize(4) + .containsOnly( + psiFieldInSetterOnly, + psiFieldInConstructorOnly, + psiFieldInSetterAndConstructor, + psiFieldNowhere); + assertThat(result.getFieldsForConstructor()) + .isNotNull() + .hasSize(2) + .containsOnly(psiFieldInConstructorOnly, psiFieldInSetterAndConstructor); + assertThat(result.getFieldsForSetters()).isNotNull().hasSize(1).containsOnly(psiFieldInSetterOnly); + assertThat(result.getBestConstructor()).isEqualTo(bestConstructor); + } +} diff --git a/src/test/java/pl/mjedynak/idea/plugins/builder/finder/BestConstructorSelectorTest.java b/src/test/java/pl/mjedynak/idea/plugins/builder/finder/BestConstructorSelectorTest.java index da99f19..638317d 100644 --- a/src/test/java/pl/mjedynak/idea/plugins/builder/finder/BestConstructorSelectorTest.java +++ b/src/test/java/pl/mjedynak/idea/plugins/builder/finder/BestConstructorSelectorTest.java @@ -1,191 +1,191 @@ -package pl.mjedynak.idea.plugins.builder.finder; - -import static org.apache.commons.lang3.StringUtils.EMPTY; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mock.Strictness.LENIENT; -import static org.springframework.test.util.ReflectionTestUtils.setField; - -import com.google.common.collect.Lists; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiField; -import com.intellij.psi.PsiMethod; -import com.intellij.psi.PsiParameter; -import com.intellij.psi.PsiParameterList; -import com.intellij.psi.PsiParameterListOwner; -import com.intellij.psi.PsiPrimitiveType; -import com.intellij.psi.PsiType; -import com.intellij.psi.PsiVariable; -import java.util.Collection; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import pl.mjedynak.idea.plugins.builder.psi.BestConstructorSelector; -import pl.mjedynak.idea.plugins.builder.settings.CodeStyleSettings; -import pl.mjedynak.idea.plugins.builder.verifier.PsiFieldVerifier; - -@ExtendWith(MockitoExtension.class) -public class BestConstructorSelectorTest { - - private static final String NAME_1 = "name1"; - private static final String NAME_2 = "name2"; - private static final String NAME_3 = "name3"; - private static final String NAME_4 = "name4"; - private static final String NAME_5 = "name5"; - private static final PsiParameter[] EMPTY_PSI_PARAMETERS = new PsiParameter[0]; - - @Mock(strictness = LENIENT) - private CodeStyleSettings settings; - - @Mock - private PsiClass psiClass; - - @Mock - private PsiMethod constructor0; - - @Mock - private PsiMethod constructor1; - - @Mock - private PsiMethod constructor2a; - - @Mock - private PsiMethod constructor2b; - - @Mock - private PsiMethod constructor3; - - @Mock(strictness = LENIENT) - private PsiParameterList parameterList0; - - @Mock(strictness = LENIENT) - private PsiParameterList parameterList1; - - @Mock(strictness = LENIENT) - private PsiParameterList parameterList2a; - - @Mock(strictness = LENIENT) - private PsiParameterList parameterList2b; - - @Mock(strictness = LENIENT) - private PsiParameterList parameterList3; - - @Mock(strictness = LENIENT) - private PsiField psiField1; - - @Mock(strictness = LENIENT) - private PsiField psiField2; - - @Mock(strictness = LENIENT) - private PsiField psiField3; - - @Mock(strictness = LENIENT) - private PsiField psiField4; - - @Mock(strictness = LENIENT) - private PsiField psiField5; - - @Mock(strictness = LENIENT) - private PsiParameter psiParameter1; - - @Mock(strictness = LENIENT) - private PsiParameter psiParameter2; - - @Mock(strictness = LENIENT) - private PsiParameter psiParameter3; - - @Mock(strictness = LENIENT) - private PsiParameter psiParameter4; - - private final PsiFieldVerifier verifier = new PsiFieldVerifier(); - private final BestConstructorSelector finder = new BestConstructorSelector(verifier); - - @BeforeEach - public void initMock() { - setField(verifier, "codeStyleSettings", settings); - given(settings.getParameterNamePrefix()).willReturn(EMPTY); - given(settings.getFieldNamePrefix()).willReturn(EMPTY); - - mockPsiVariable(psiField1, NAME_1, PsiType.INT); - mockPsiVariable(psiField2, NAME_2, PsiType.INT); - mockPsiVariable(psiField3, NAME_3, PsiType.INT); - mockPsiVariable(psiField4, NAME_4, PsiType.INT); - mockPsiVariable(psiField5, NAME_5, PsiType.INT); - - mockPsiVariable(psiParameter1, NAME_1, PsiType.INT); - mockPsiVariable(psiParameter2, NAME_2, PsiType.INT); - mockPsiVariable(psiParameter3, NAME_3, PsiType.INT); - mockPsiVariable(psiParameter4, NAME_4, PsiType.INT); - - mockConstructor(constructor0, parameterList0, EMPTY_PSI_PARAMETERS); - mockConstructor(constructor1, parameterList1, psiParameter4); - mockConstructor(constructor2a, parameterList2a, psiParameter1, psiParameter2); - mockConstructor(constructor2b, parameterList2b, psiParameter1, psiParameter4); - mockConstructor(constructor3, parameterList3, psiParameter1, psiParameter2, psiParameter3); - } - - private void mockPsiVariable(PsiVariable psiVariable, String name, PsiPrimitiveType type) { - given(psiVariable.getName()).willReturn(name); - given(psiVariable.getType()).willReturn(type); - } - - private void mockConstructor( - PsiParameterListOwner constructor, PsiParameterList parameterList, PsiParameter... psiParameters) { - given(constructor.getParameterList()).willReturn(parameterList); - given(parameterList.getParameters()).willReturn(psiParameters); - given(parameterList.getParametersCount()).willReturn(psiParameters.length); - } - - @Test - void shouldFindConstructorWithLeastParametersIfAnyFieldsToFind() { - doTest( - Lists.newArrayList(), - new PsiMethod[] {constructor0, constructor1, constructor2a, constructor2b, constructor3}, - constructor0); - } - - @Test - void shouldFindConstructorWithLeastParametersIfAnyFieldsToFindFoundInConstructors() { - doTest( - Lists.newArrayList(psiField5), - new PsiMethod[] {constructor0, constructor1, constructor2a, constructor2b, constructor3}, - constructor0); - } - - @Test - void shouldFindConstructorWithExactMatching() { - doTest( - Lists.newArrayList(psiField1, psiField2), - new PsiMethod[] {constructor0, constructor1, constructor2a, constructor2b, constructor3}, - constructor2a); - } - - @Test - void shouldFindConstructorWithAllFieldsFoundButExtraParameters() { - doTest( - Lists.newArrayList(psiField2, psiField3), - new PsiMethod[] {constructor0, constructor1, constructor2a, constructor2b, constructor3}, - constructor3); - } - - @Test - void shouldFindConstructorWithMaxFieldsFoundAndLessParameters() { - doTest( - Lists.newArrayList(psiField2, psiField4), - new PsiMethod[] {constructor0, constructor1, constructor2a, constructor2b, constructor3}, - constructor1); - } - - private void doTest(Collection psiFields, PsiMethod[] psiMethods, PsiMethod expectedConstructor) { - // given - given(psiClass.getConstructors()).willReturn(psiMethods); - - // when - PsiMethod bestConstructor = finder.getBestConstructor(psiFields, psiClass); - - // then - assertThat(bestConstructor).isEqualTo(expectedConstructor); - } -} +package pl.mjedynak.idea.plugins.builder.finder; + +import static org.apache.commons.lang3.StringUtils.EMPTY; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mock.Strictness.LENIENT; +import static org.springframework.test.util.ReflectionTestUtils.setField; + +import com.google.common.collect.Lists; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiField; +import com.intellij.psi.PsiMethod; +import com.intellij.psi.PsiParameter; +import com.intellij.psi.PsiParameterList; +import com.intellij.psi.PsiParameterListOwner; +import com.intellij.psi.PsiPrimitiveType; +import com.intellij.psi.PsiType; +import com.intellij.psi.PsiVariable; +import java.util.Collection; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import pl.mjedynak.idea.plugins.builder.psi.BestConstructorSelector; +import pl.mjedynak.idea.plugins.builder.settings.CodeStyleSettings; +import pl.mjedynak.idea.plugins.builder.verifier.PsiFieldVerifier; + +@ExtendWith(MockitoExtension.class) +public class BestConstructorSelectorTest { + + private static final String NAME_1 = "name1"; + private static final String NAME_2 = "name2"; + private static final String NAME_3 = "name3"; + private static final String NAME_4 = "name4"; + private static final String NAME_5 = "name5"; + private static final PsiParameter[] EMPTY_PSI_PARAMETERS = new PsiParameter[0]; + + @Mock(strictness = LENIENT) + private CodeStyleSettings settings; + + @Mock + private PsiClass psiClass; + + @Mock + private PsiMethod constructor0; + + @Mock + private PsiMethod constructor1; + + @Mock + private PsiMethod constructor2a; + + @Mock + private PsiMethod constructor2b; + + @Mock + private PsiMethod constructor3; + + @Mock(strictness = LENIENT) + private PsiParameterList parameterList0; + + @Mock(strictness = LENIENT) + private PsiParameterList parameterList1; + + @Mock(strictness = LENIENT) + private PsiParameterList parameterList2a; + + @Mock(strictness = LENIENT) + private PsiParameterList parameterList2b; + + @Mock(strictness = LENIENT) + private PsiParameterList parameterList3; + + @Mock(strictness = LENIENT) + private PsiField psiField1; + + @Mock(strictness = LENIENT) + private PsiField psiField2; + + @Mock(strictness = LENIENT) + private PsiField psiField3; + + @Mock(strictness = LENIENT) + private PsiField psiField4; + + @Mock(strictness = LENIENT) + private PsiField psiField5; + + @Mock(strictness = LENIENT) + private PsiParameter psiParameter1; + + @Mock(strictness = LENIENT) + private PsiParameter psiParameter2; + + @Mock(strictness = LENIENT) + private PsiParameter psiParameter3; + + @Mock(strictness = LENIENT) + private PsiParameter psiParameter4; + + private final PsiFieldVerifier verifier = new PsiFieldVerifier(); + private final BestConstructorSelector finder = new BestConstructorSelector(verifier); + + @BeforeEach + public void initMock() { + setField(verifier, "codeStyleSettings", settings); + given(settings.getParameterNamePrefix()).willReturn(EMPTY); + given(settings.getFieldNamePrefix()).willReturn(EMPTY); + + mockPsiVariable(psiField1, NAME_1, PsiType.INT); + mockPsiVariable(psiField2, NAME_2, PsiType.INT); + mockPsiVariable(psiField3, NAME_3, PsiType.INT); + mockPsiVariable(psiField4, NAME_4, PsiType.INT); + mockPsiVariable(psiField5, NAME_5, PsiType.INT); + + mockPsiVariable(psiParameter1, NAME_1, PsiType.INT); + mockPsiVariable(psiParameter2, NAME_2, PsiType.INT); + mockPsiVariable(psiParameter3, NAME_3, PsiType.INT); + mockPsiVariable(psiParameter4, NAME_4, PsiType.INT); + + mockConstructor(constructor0, parameterList0, EMPTY_PSI_PARAMETERS); + mockConstructor(constructor1, parameterList1, psiParameter4); + mockConstructor(constructor2a, parameterList2a, psiParameter1, psiParameter2); + mockConstructor(constructor2b, parameterList2b, psiParameter1, psiParameter4); + mockConstructor(constructor3, parameterList3, psiParameter1, psiParameter2, psiParameter3); + } + + private void mockPsiVariable(PsiVariable psiVariable, String name, PsiPrimitiveType type) { + given(psiVariable.getName()).willReturn(name); + given(psiVariable.getType()).willReturn(type); + } + + private void mockConstructor( + PsiParameterListOwner constructor, PsiParameterList parameterList, PsiParameter... psiParameters) { + given(constructor.getParameterList()).willReturn(parameterList); + given(parameterList.getParameters()).willReturn(psiParameters); + given(parameterList.getParametersCount()).willReturn(psiParameters.length); + } + + @Test + void shouldFindConstructorWithLeastParametersIfAnyFieldsToFind() { + doTest( + Lists.newArrayList(), + new PsiMethod[] {constructor0, constructor1, constructor2a, constructor2b, constructor3}, + constructor0); + } + + @Test + void shouldFindConstructorWithLeastParametersIfAnyFieldsToFindFoundInConstructors() { + doTest( + Lists.newArrayList(psiField5), + new PsiMethod[] {constructor0, constructor1, constructor2a, constructor2b, constructor3}, + constructor0); + } + + @Test + void shouldFindConstructorWithExactMatching() { + doTest( + Lists.newArrayList(psiField1, psiField2), + new PsiMethod[] {constructor0, constructor1, constructor2a, constructor2b, constructor3}, + constructor2a); + } + + @Test + void shouldFindConstructorWithAllFieldsFoundButExtraParameters() { + doTest( + Lists.newArrayList(psiField2, psiField3), + new PsiMethod[] {constructor0, constructor1, constructor2a, constructor2b, constructor3}, + constructor3); + } + + @Test + void shouldFindConstructorWithMaxFieldsFoundAndLessParameters() { + doTest( + Lists.newArrayList(psiField2, psiField4), + new PsiMethod[] {constructor0, constructor1, constructor2a, constructor2b, constructor3}, + constructor1); + } + + private void doTest(Collection psiFields, PsiMethod[] psiMethods, PsiMethod expectedConstructor) { + // given + given(psiClass.getConstructors()).willReturn(psiMethods); + + // when + PsiMethod bestConstructor = finder.getBestConstructor(psiFields, psiClass); + + // then + assertThat(bestConstructor).isEqualTo(expectedConstructor); + } +} diff --git a/src/test/java/pl/mjedynak/idea/plugins/builder/finder/BuilderFinderTest.java b/src/test/java/pl/mjedynak/idea/plugins/builder/finder/BuilderFinderTest.java index 511a4f7..2a17b90 100644 --- a/src/test/java/pl/mjedynak/idea/plugins/builder/finder/BuilderFinderTest.java +++ b/src/test/java/pl/mjedynak/idea/plugins/builder/finder/BuilderFinderTest.java @@ -1,208 +1,208 @@ -package pl.mjedynak.idea.plugins.builder.finder; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mock.Strictness.LENIENT; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -import com.intellij.openapi.project.Project; -import com.intellij.psi.PsiClass; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; - -@ExtendWith(MockitoExtension.class) -public class BuilderFinderTest { - - private static final String CLASS_NAME = "SomeClass"; - private static final String BUILDER_NAME = CLASS_NAME + BuilderFinder.SEARCH_PATTERN; - - @InjectMocks - private BuilderFinder builderFinder; - - @Mock(strictness = LENIENT) - private ClassFinder classFinder; - - @Mock(strictness = LENIENT) - private PsiClass psiClass; - - @Mock(strictness = LENIENT) - private PsiClass builderClass; - - @Mock - private Project project; - - @BeforeEach - public void setUp() { - given(psiClass.isEnum()).willReturn(false); - given(psiClass.isInterface()).willReturn(false); - given(psiClass.isAnnotationType()).willReturn(false); - given(psiClass.getProject()).willReturn(project); - given(psiClass.getName()).willReturn(CLASS_NAME); - given(psiClass.getAllInnerClasses()).willReturn(new PsiClass[0]); - - given(builderClass.getName()).willReturn(BUILDER_NAME); - given(builderClass.getProject()).willReturn(project); - } - - @Test - void shouldNotFindBuilderForEnum() { - // given - given(psiClass.isEnum()).willReturn(true); - - // when - PsiClass result = builderFinder.findBuilderForClass(psiClass); - - // then - assertThat(result).isNull(); - } - - @Test - void shouldNotFindBuilderForInterface() { - // given - given(psiClass.isAnnotationType()).willReturn(true); - - // when - PsiClass result = builderFinder.findBuilderForClass(psiClass); - - // then - assertThat(result).isNull(); - } - - @Test - void shouldNotFindBuilderForAnnotationType() { - // given - given(psiClass.isAnnotationType()).willReturn(true); - - // when - PsiClass result = builderFinder.findBuilderForClass(psiClass); - - // then - assertThat(result).isNull(); - } - - @Test - void shouldNotFindBuilderForClassWhenClassFounderReturnsNull() { - // given - given(classFinder.findClass(CLASS_NAME, project)).willReturn(null); - - // when - PsiClass result = builderFinder.findBuilderForClass(psiClass); - - // then - assertThat(result).isNull(); - } - - @Test - void shouldFindBuilderForClassWhenBuilderWithTheExactClassNameIsPresent() { - // given - - PsiClass builderClass = mock(PsiClass.class); - given(builderClass.getName()).willReturn(BUILDER_NAME); - - given(classFinder.findClass(BUILDER_NAME, project)).willReturn(builderClass); - - // when - PsiClass result = builderFinder.findBuilderForClass(psiClass); - - // then - assertThat(result).isNotNull(); - assertThat(result.getName()).isEqualTo(BUILDER_NAME); - } - - @Test - void shouldFindInnerBuilder() { - // given - PsiClass innerClass = mock(PsiClass.class); - PsiClass[] innerClasses = {innerClass}; - given(innerClass.getName()).willReturn(BuilderFinder.SEARCH_PATTERN); - given(psiClass.getAllInnerClasses()).willReturn(innerClasses); - - // when - PsiClass result = builderFinder.findBuilderForClass(psiClass); - - // then - assertThat(result).isEqualTo(innerClass); - } - - @Test - void shouldNotFindInnerBuilderWhenInnerClassNameDoesNotMatchPattern() { - // given - PsiClass innerClass = mock(PsiClass.class); - PsiClass[] innerClasses = {innerClass}; - given(innerClass.getName()).willReturn("SomeInnerClass"); - given(psiClass.getAllInnerClasses()).willReturn(innerClasses); - - // when - PsiClass result = builderFinder.findBuilderForClass(psiClass); - - // then - assertThat(result).isNull(); - } - - @Test - void shouldNotFindClassForEnum() { - // given - given(psiClass.isEnum()).willReturn(true); - - // when - PsiClass result = builderFinder.findClassForBuilder(psiClass); - - // then - assertThat(result).isNull(); - } - - @Test - void shouldNotFindClassForInterface() { - // given - given(psiClass.isAnnotationType()).willReturn(true); - - // when - PsiClass result = builderFinder.findClassForBuilder(psiClass); - - // then - assertThat(result).isNull(); - } - - @Test - void shouldNotFindClassForAnnotationType() { - // given - given(psiClass.isAnnotationType()).willReturn(true); - - // when - PsiClass result = builderFinder.findClassForBuilder(psiClass); - - // then - assertThat(result).isNull(); - } - - @Test - void shouldNotFindClassForBuilderWhenClassFounderReturnsNull() { - // given - given(classFinder.findClass(BUILDER_NAME, project)).willReturn(null); - - // when - PsiClass result = builderFinder.findClassForBuilder(builderClass); - - // then - assertThat(result).isNull(); - verify(classFinder).findClass(CLASS_NAME, project); - } - - @Test - void shouldFindClassForBuilderWhenClassWithTheExactBuildersNameIsPresent() { - // given - given(classFinder.findClass(CLASS_NAME, project)).willReturn(psiClass); - - // when - PsiClass result = builderFinder.findClassForBuilder(psiClass); - - // then - assertThat(result).isNotNull(); - assertThat(result.getName()).isEqualTo(CLASS_NAME); - } -} +package pl.mjedynak.idea.plugins.builder.finder; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mock.Strictness.LENIENT; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import com.intellij.openapi.project.Project; +import com.intellij.psi.PsiClass; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +public class BuilderFinderTest { + + private static final String CLASS_NAME = "SomeClass"; + private static final String BUILDER_NAME = CLASS_NAME + BuilderFinder.SEARCH_PATTERN; + + @InjectMocks + private BuilderFinder builderFinder; + + @Mock(strictness = LENIENT) + private ClassFinder classFinder; + + @Mock(strictness = LENIENT) + private PsiClass psiClass; + + @Mock(strictness = LENIENT) + private PsiClass builderClass; + + @Mock + private Project project; + + @BeforeEach + public void setUp() { + given(psiClass.isEnum()).willReturn(false); + given(psiClass.isInterface()).willReturn(false); + given(psiClass.isAnnotationType()).willReturn(false); + given(psiClass.getProject()).willReturn(project); + given(psiClass.getName()).willReturn(CLASS_NAME); + given(psiClass.getAllInnerClasses()).willReturn(new PsiClass[0]); + + given(builderClass.getName()).willReturn(BUILDER_NAME); + given(builderClass.getProject()).willReturn(project); + } + + @Test + void shouldNotFindBuilderForEnum() { + // given + given(psiClass.isEnum()).willReturn(true); + + // when + PsiClass result = builderFinder.findBuilderForClass(psiClass); + + // then + assertThat(result).isNull(); + } + + @Test + void shouldNotFindBuilderForInterface() { + // given + given(psiClass.isAnnotationType()).willReturn(true); + + // when + PsiClass result = builderFinder.findBuilderForClass(psiClass); + + // then + assertThat(result).isNull(); + } + + @Test + void shouldNotFindBuilderForAnnotationType() { + // given + given(psiClass.isAnnotationType()).willReturn(true); + + // when + PsiClass result = builderFinder.findBuilderForClass(psiClass); + + // then + assertThat(result).isNull(); + } + + @Test + void shouldNotFindBuilderForClassWhenClassFounderReturnsNull() { + // given + given(classFinder.findClass(CLASS_NAME, project)).willReturn(null); + + // when + PsiClass result = builderFinder.findBuilderForClass(psiClass); + + // then + assertThat(result).isNull(); + } + + @Test + void shouldFindBuilderForClassWhenBuilderWithTheExactClassNameIsPresent() { + // given + + PsiClass builderClass = mock(PsiClass.class); + given(builderClass.getName()).willReturn(BUILDER_NAME); + + given(classFinder.findClass(BUILDER_NAME, project)).willReturn(builderClass); + + // when + PsiClass result = builderFinder.findBuilderForClass(psiClass); + + // then + assertThat(result).isNotNull(); + assertThat(result.getName()).isEqualTo(BUILDER_NAME); + } + + @Test + void shouldFindInnerBuilder() { + // given + PsiClass innerClass = mock(PsiClass.class); + PsiClass[] innerClasses = {innerClass}; + given(innerClass.getName()).willReturn(BuilderFinder.SEARCH_PATTERN); + given(psiClass.getAllInnerClasses()).willReturn(innerClasses); + + // when + PsiClass result = builderFinder.findBuilderForClass(psiClass); + + // then + assertThat(result).isEqualTo(innerClass); + } + + @Test + void shouldNotFindInnerBuilderWhenInnerClassNameDoesNotMatchPattern() { + // given + PsiClass innerClass = mock(PsiClass.class); + PsiClass[] innerClasses = {innerClass}; + given(innerClass.getName()).willReturn("SomeInnerClass"); + given(psiClass.getAllInnerClasses()).willReturn(innerClasses); + + // when + PsiClass result = builderFinder.findBuilderForClass(psiClass); + + // then + assertThat(result).isNull(); + } + + @Test + void shouldNotFindClassForEnum() { + // given + given(psiClass.isEnum()).willReturn(true); + + // when + PsiClass result = builderFinder.findClassForBuilder(psiClass); + + // then + assertThat(result).isNull(); + } + + @Test + void shouldNotFindClassForInterface() { + // given + given(psiClass.isAnnotationType()).willReturn(true); + + // when + PsiClass result = builderFinder.findClassForBuilder(psiClass); + + // then + assertThat(result).isNull(); + } + + @Test + void shouldNotFindClassForAnnotationType() { + // given + given(psiClass.isAnnotationType()).willReturn(true); + + // when + PsiClass result = builderFinder.findClassForBuilder(psiClass); + + // then + assertThat(result).isNull(); + } + + @Test + void shouldNotFindClassForBuilderWhenClassFounderReturnsNull() { + // given + given(classFinder.findClass(BUILDER_NAME, project)).willReturn(null); + + // when + PsiClass result = builderFinder.findClassForBuilder(builderClass); + + // then + assertThat(result).isNull(); + verify(classFinder).findClass(CLASS_NAME, project); + } + + @Test + void shouldFindClassForBuilderWhenClassWithTheExactBuildersNameIsPresent() { + // given + given(classFinder.findClass(CLASS_NAME, project)).willReturn(psiClass); + + // when + PsiClass result = builderFinder.findClassForBuilder(psiClass); + + // then + assertThat(result).isNotNull(); + assertThat(result.getName()).isEqualTo(CLASS_NAME); + } +} diff --git a/src/test/java/pl/mjedynak/idea/plugins/builder/finder/ClassFinderTest.java b/src/test/java/pl/mjedynak/idea/plugins/builder/finder/ClassFinderTest.java index d810615..de5770a 100644 --- a/src/test/java/pl/mjedynak/idea/plugins/builder/finder/ClassFinderTest.java +++ b/src/test/java/pl/mjedynak/idea/plugins/builder/finder/ClassFinderTest.java @@ -1,81 +1,81 @@ -package pl.mjedynak.idea.plugins.builder.finder; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - -import com.intellij.openapi.project.Project; -import com.intellij.psi.PsiClass; -import com.intellij.psi.search.GlobalSearchScope; -import com.intellij.psi.search.PsiShortNamesCache; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.ArgumentMatchers; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; - -@ExtendWith(MockitoExtension.class) -public class ClassFinderTest { - - private static final String CLASS_NAME = "SomeClass"; - - @InjectMocks - private ClassFinder classFinder; - - @Mock - private PsiHelper psiHelper; - - @Mock - private PsiShortNamesCache psiShortNamesCache; - - @Mock - private Project project; - - @Mock - private GlobalSearchScope globalSearchScope; - - @BeforeEach - public void setUp() { - given(project.getUserData(ArgumentMatchers.any())).willReturn(globalSearchScope); - given(psiHelper.getPsiShortNamesCache(project)).willReturn(psiShortNamesCache); - } - - @Test - void shouldNotFindClassWhenSearchPatternNotFound() { - // given - PsiClass[] emptyArray = new PsiClass[0]; - given(psiShortNamesCache.getClassesByName(CLASS_NAME, globalSearchScope)) - .willReturn(emptyArray); - - // when - PsiClass result = classFinder.findClass(CLASS_NAME, project); - - // then - assertThat(result).isNull(); - } - - @Test - void shouldFoundClassWhenBuilderSearchPatternFound() { - // given - PsiClass foundClass = mock(PsiClass.class); - given(foundClass.getName()).willReturn(CLASS_NAME); - PsiClass[] foundClassArray = {foundClass}; - - given(psiShortNamesCache.getClassesByName(CLASS_NAME, globalSearchScope)) - .willReturn(foundClassArray); - - // when - PsiClass result = classFinder.findClass(CLASS_NAME, project); - - // then - verifyClassIsFound(CLASS_NAME, result); - } - - private void verifyClassIsFound(String name, PsiClass result) { - assertThat(result).isNotNull(); - assertThat(result.getName()).isEqualTo(name); - } -} +package pl.mjedynak.idea.plugins.builder.finder; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + +import com.intellij.openapi.project.Project; +import com.intellij.psi.PsiClass; +import com.intellij.psi.search.GlobalSearchScope; +import com.intellij.psi.search.PsiShortNamesCache; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentMatchers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; + +@ExtendWith(MockitoExtension.class) +public class ClassFinderTest { + + private static final String CLASS_NAME = "SomeClass"; + + @InjectMocks + private ClassFinder classFinder; + + @Mock + private PsiHelper psiHelper; + + @Mock + private PsiShortNamesCache psiShortNamesCache; + + @Mock + private Project project; + + @Mock + private GlobalSearchScope globalSearchScope; + + @BeforeEach + public void setUp() { + given(project.getUserData(ArgumentMatchers.any())).willReturn(globalSearchScope); + given(psiHelper.getPsiShortNamesCache(project)).willReturn(psiShortNamesCache); + } + + @Test + void shouldNotFindClassWhenSearchPatternNotFound() { + // given + PsiClass[] emptyArray = new PsiClass[0]; + given(psiShortNamesCache.getClassesByName(CLASS_NAME, globalSearchScope)) + .willReturn(emptyArray); + + // when + PsiClass result = classFinder.findClass(CLASS_NAME, project); + + // then + assertThat(result).isNull(); + } + + @Test + void shouldFoundClassWhenBuilderSearchPatternFound() { + // given + PsiClass foundClass = mock(PsiClass.class); + given(foundClass.getName()).willReturn(CLASS_NAME); + PsiClass[] foundClassArray = {foundClass}; + + given(psiShortNamesCache.getClassesByName(CLASS_NAME, globalSearchScope)) + .willReturn(foundClassArray); + + // when + PsiClass result = classFinder.findClass(CLASS_NAME, project); + + // then + verifyClassIsFound(CLASS_NAME, result); + } + + private void verifyClassIsFound(String name, PsiClass result) { + assertThat(result).isNotNull(); + assertThat(result.getName()).isEqualTo(name); + } +} diff --git a/src/test/java/pl/mjedynak/idea/plugins/builder/gui/ChooserDisplayerActionListenerTest.java b/src/test/java/pl/mjedynak/idea/plugins/builder/gui/ChooserDisplayerActionListenerTest.java index c2ed05e..2e8cb47 100644 --- a/src/test/java/pl/mjedynak/idea/plugins/builder/gui/ChooserDisplayerActionListenerTest.java +++ b/src/test/java/pl/mjedynak/idea/plugins/builder/gui/ChooserDisplayerActionListenerTest.java @@ -1,59 +1,59 @@ -package pl.mjedynak.idea.plugins.builder.gui; - -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -import com.intellij.ide.util.PackageChooserDialog; -import com.intellij.openapi.project.Project; -import com.intellij.psi.PsiPackage; -import com.intellij.ui.ReferenceEditorComboWithBrowseButton; -import java.awt.event.ActionEvent; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import pl.mjedynak.idea.plugins.builder.factory.PackageChooserDialogFactory; - -@ExtendWith(MockitoExtension.class) -public class ChooserDisplayerActionListenerTest { - - @InjectMocks - private ChooserDisplayerActionListener chooserDisplayerActionListener; - - @Mock - private ReferenceEditorComboWithBrowseButton comboWithBrowseButton; - - @Mock - private PackageChooserDialogFactory packageChooserDialogFactory; - - @Mock - private Project project; - - @Test - void shouldShowChooserAndSetText() { - // given - ActionEvent anyEvent = mock(ActionEvent.class); - PackageChooserDialog chooser = mock(PackageChooserDialog.class); - PsiPackage psiPackage = mock(PsiPackage.class); - String text = "text"; - String name = "name"; - - given(packageChooserDialogFactory.getPackageChooserDialog(anyString(), eq(project))) - .willReturn(chooser); - given(comboWithBrowseButton.getText()).willReturn(text); - given(chooser.getSelectedPackage()).willReturn(psiPackage); - given(psiPackage.getQualifiedName()).willReturn(name); - - // when - chooserDisplayerActionListener.actionPerformed(anyEvent); - - // then - verify(chooser).selectPackage(text); - verify(chooser).show(); - verify(comboWithBrowseButton).setText(name); - } -} +package pl.mjedynak.idea.plugins.builder.gui; + +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import com.intellij.ide.util.PackageChooserDialog; +import com.intellij.openapi.project.Project; +import com.intellij.psi.PsiPackage; +import com.intellij.ui.ReferenceEditorComboWithBrowseButton; +import java.awt.event.ActionEvent; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import pl.mjedynak.idea.plugins.builder.factory.PackageChooserDialogFactory; + +@ExtendWith(MockitoExtension.class) +public class ChooserDisplayerActionListenerTest { + + @InjectMocks + private ChooserDisplayerActionListener chooserDisplayerActionListener; + + @Mock + private ReferenceEditorComboWithBrowseButton comboWithBrowseButton; + + @Mock + private PackageChooserDialogFactory packageChooserDialogFactory; + + @Mock + private Project project; + + @Test + void shouldShowChooserAndSetText() { + // given + ActionEvent anyEvent = mock(ActionEvent.class); + PackageChooserDialog chooser = mock(PackageChooserDialog.class); + PsiPackage psiPackage = mock(PsiPackage.class); + String text = "text"; + String name = "name"; + + given(packageChooserDialogFactory.getPackageChooserDialog(anyString(), eq(project))) + .willReturn(chooser); + given(comboWithBrowseButton.getText()).willReturn(text); + given(chooser.getSelectedPackage()).willReturn(psiPackage); + given(psiPackage.getQualifiedName()).willReturn(name); + + // when + chooserDisplayerActionListener.actionPerformed(anyEvent); + + // then + verify(chooser).selectPackage(text); + verify(chooser).show(); + verify(comboWithBrowseButton).setText(name); + } +} diff --git a/src/test/java/pl/mjedynak/idea/plugins/builder/gui/SelectDirectoryTest.java b/src/test/java/pl/mjedynak/idea/plugins/builder/gui/SelectDirectoryTest.java index 29bcc38..1cb58de 100644 --- a/src/test/java/pl/mjedynak/idea/plugins/builder/gui/SelectDirectoryTest.java +++ b/src/test/java/pl/mjedynak/idea/plugins/builder/gui/SelectDirectoryTest.java @@ -1,139 +1,139 @@ -package pl.mjedynak.idea.plugins.builder.gui; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; - -import com.intellij.openapi.module.Module; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiDirectory; -import com.intellij.psi.PsiFile; -import com.intellij.util.IncorrectOperationException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; - -@ExtendWith(MockitoExtension.class) -public class SelectDirectoryTest { - - private static final String PACKAGE_NAME = "packageName"; - private static final String CLASS_NAME = "className"; - private static final String ERROR_MESSAGE = "errorMessage"; - private static final String DIRECTORY_NAME = "directoryName"; - - private SelectDirectory selectDirectory; - - @Mock - private CreateBuilderDialog createBuilderDialog; - - @Mock - private PsiHelper psiHelper; - - @Mock - private Module module; - - @Mock - private PsiDirectory targetDirectory; - - @Mock - private PsiClass existingBuilder; - - @BeforeEach - public void setUp() { - given(psiHelper.getDirectoryFromModuleAndPackageName(module, PACKAGE_NAME)) - .willReturn(targetDirectory); - } - - @Test - void shouldDoNothingIfTargetDirectoryReturnedByPsiHelperIsNull() { - // given - selectDirectory = new SelectDirectory(createBuilderDialog, psiHelper, module, PACKAGE_NAME, CLASS_NAME, null); - given(psiHelper.getDirectoryFromModuleAndPackageName(module, PACKAGE_NAME)) - .willReturn(null); - - // when - selectDirectory.run(); - - // then - verifyNoInteractions(createBuilderDialog); - } - - @Test - void shouldSetTargetDirectoryOnCaller() { - // given - selectDirectory = new SelectDirectory(createBuilderDialog, psiHelper, module, PACKAGE_NAME, CLASS_NAME, null); - given(psiHelper.checkIfClassCanBeCreated(targetDirectory, CLASS_NAME)).willReturn(null); - - // when - selectDirectory.run(); - - // then - verify(createBuilderDialog).setTargetDirectory(targetDirectory); - } - - @SuppressWarnings("JUnitTestMethodWithNoAssertions") - @Test - void shouldThrowExceptionWhenPsiHelperCheckReturnsErrorString() { - Throwable exception = assertThrows(IncorrectOperationException.class, () -> { - - // given - selectDirectory = - new SelectDirectory(createBuilderDialog, psiHelper, module, PACKAGE_NAME, CLASS_NAME, null); - given(psiHelper.checkIfClassCanBeCreated(targetDirectory, CLASS_NAME)) - .willReturn(ERROR_MESSAGE); - - // when - selectDirectory.run(); - }); - assertTrue(exception.getMessage().contains(ERROR_MESSAGE)); - } - - @SuppressWarnings("JUnitTestMethodWithNoAssertions") - @Test - void shouldThrowExceptionWhenPsiHelperThrowsIncorrectOperationException() { - // given - selectDirectory = new SelectDirectory(createBuilderDialog, psiHelper, module, PACKAGE_NAME, CLASS_NAME, null); - IncorrectOperationException exception = new IncorrectOperationException(ERROR_MESSAGE); - given(psiHelper.checkIfClassCanBeCreated(targetDirectory, CLASS_NAME)).willThrow(exception); - - // when - Throwable expectedException = assertThrows(IncorrectOperationException.class, () -> selectDirectory.run()); - - // then - assertThat(expectedException).hasMessageContaining(ERROR_MESSAGE); - } - - @Test - void shouldNotCheckIfClassCanBeCreatedIfExistingBuilderMustBeDeletedAndClassToCreateIsTheSame() { - // given - selectDirectory = - new SelectDirectory(createBuilderDialog, psiHelper, module, PACKAGE_NAME, CLASS_NAME, existingBuilder); - mockIsClassToCreateSameAsBuilderToDelete(); - - // when - selectDirectory.run(); - - // then - verify(psiHelper, never()).checkIfClassCanBeCreated(any(PsiDirectory.class), anyString()); - } - - private void mockIsClassToCreateSameAsBuilderToDelete() { - PsiFile containingFile = mock(PsiFile.class); - PsiDirectory containingDirectory = mock(PsiDirectory.class); - given(existingBuilder.getContainingFile()).willReturn(containingFile); - given(containingFile.getContainingDirectory()).willReturn(containingDirectory); - given(containingDirectory.getName()).willReturn(DIRECTORY_NAME); - given(existingBuilder.getName()).willReturn(CLASS_NAME); - given(targetDirectory.getName()).willReturn(DIRECTORY_NAME); - } -} +package pl.mjedynak.idea.plugins.builder.gui; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; + +import com.intellij.openapi.module.Module; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiDirectory; +import com.intellij.psi.PsiFile; +import com.intellij.util.IncorrectOperationException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; + +@ExtendWith(MockitoExtension.class) +public class SelectDirectoryTest { + + private static final String PACKAGE_NAME = "packageName"; + private static final String CLASS_NAME = "className"; + private static final String ERROR_MESSAGE = "errorMessage"; + private static final String DIRECTORY_NAME = "directoryName"; + + private SelectDirectory selectDirectory; + + @Mock + private CreateBuilderDialog createBuilderDialog; + + @Mock + private PsiHelper psiHelper; + + @Mock + private Module module; + + @Mock + private PsiDirectory targetDirectory; + + @Mock + private PsiClass existingBuilder; + + @BeforeEach + public void setUp() { + given(psiHelper.getDirectoryFromModuleAndPackageName(module, PACKAGE_NAME)) + .willReturn(targetDirectory); + } + + @Test + void shouldDoNothingIfTargetDirectoryReturnedByPsiHelperIsNull() { + // given + selectDirectory = new SelectDirectory(createBuilderDialog, psiHelper, module, PACKAGE_NAME, CLASS_NAME, null); + given(psiHelper.getDirectoryFromModuleAndPackageName(module, PACKAGE_NAME)) + .willReturn(null); + + // when + selectDirectory.run(); + + // then + verifyNoInteractions(createBuilderDialog); + } + + @Test + void shouldSetTargetDirectoryOnCaller() { + // given + selectDirectory = new SelectDirectory(createBuilderDialog, psiHelper, module, PACKAGE_NAME, CLASS_NAME, null); + given(psiHelper.checkIfClassCanBeCreated(targetDirectory, CLASS_NAME)).willReturn(null); + + // when + selectDirectory.run(); + + // then + verify(createBuilderDialog).setTargetDirectory(targetDirectory); + } + + @SuppressWarnings("JUnitTestMethodWithNoAssertions") + @Test + void shouldThrowExceptionWhenPsiHelperCheckReturnsErrorString() { + Throwable exception = assertThrows(IncorrectOperationException.class, () -> { + + // given + selectDirectory = + new SelectDirectory(createBuilderDialog, psiHelper, module, PACKAGE_NAME, CLASS_NAME, null); + given(psiHelper.checkIfClassCanBeCreated(targetDirectory, CLASS_NAME)) + .willReturn(ERROR_MESSAGE); + + // when + selectDirectory.run(); + }); + assertTrue(exception.getMessage().contains(ERROR_MESSAGE)); + } + + @SuppressWarnings("JUnitTestMethodWithNoAssertions") + @Test + void shouldThrowExceptionWhenPsiHelperThrowsIncorrectOperationException() { + // given + selectDirectory = new SelectDirectory(createBuilderDialog, psiHelper, module, PACKAGE_NAME, CLASS_NAME, null); + IncorrectOperationException exception = new IncorrectOperationException(ERROR_MESSAGE); + given(psiHelper.checkIfClassCanBeCreated(targetDirectory, CLASS_NAME)).willThrow(exception); + + // when + Throwable expectedException = assertThrows(IncorrectOperationException.class, () -> selectDirectory.run()); + + // then + assertThat(expectedException).hasMessageContaining(ERROR_MESSAGE); + } + + @Test + void shouldNotCheckIfClassCanBeCreatedIfExistingBuilderMustBeDeletedAndClassToCreateIsTheSame() { + // given + selectDirectory = + new SelectDirectory(createBuilderDialog, psiHelper, module, PACKAGE_NAME, CLASS_NAME, existingBuilder); + mockIsClassToCreateSameAsBuilderToDelete(); + + // when + selectDirectory.run(); + + // then + verify(psiHelper, never()).checkIfClassCanBeCreated(any(PsiDirectory.class), anyString()); + } + + private void mockIsClassToCreateSameAsBuilderToDelete() { + PsiFile containingFile = mock(PsiFile.class); + PsiDirectory containingDirectory = mock(PsiDirectory.class); + given(existingBuilder.getContainingFile()).willReturn(containingFile); + given(containingFile.getContainingDirectory()).willReturn(containingDirectory); + given(containingDirectory.getName()).willReturn(DIRECTORY_NAME); + given(existingBuilder.getName()).willReturn(CLASS_NAME); + given(targetDirectory.getName()).willReturn(DIRECTORY_NAME); + } +} diff --git a/src/test/java/pl/mjedynak/idea/plugins/builder/gui/displayer/GenerateBuilderPopupDisplayerTest.java b/src/test/java/pl/mjedynak/idea/plugins/builder/gui/displayer/GenerateBuilderPopupDisplayerTest.java index 7db9bb9..421f388 100644 --- a/src/test/java/pl/mjedynak/idea/plugins/builder/gui/displayer/GenerateBuilderPopupDisplayerTest.java +++ b/src/test/java/pl/mjedynak/idea/plugins/builder/gui/displayer/GenerateBuilderPopupDisplayerTest.java @@ -1,59 +1,59 @@ -package pl.mjedynak.idea.plugins.builder.gui.displayer; - -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.verify; - -import com.intellij.openapi.editor.Editor; -import com.intellij.openapi.ui.popup.JBPopup; -import com.intellij.openapi.ui.popup.PopupChooserBuilder; -import javax.swing.JList; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import pl.mjedynak.idea.plugins.builder.factory.PopupChooserBuilderFactory; - -@ExtendWith(MockitoExtension.class) -public class GenerateBuilderPopupDisplayerTest { - - private static final String TITLE = "Builder already exists"; - - @InjectMocks - private GenerateBuilderPopupDisplayer popupDisplayer; - - @Mock - private PopupChooserBuilderFactory popupChooserBuilderFactory; - - @SuppressWarnings("rawtypes") - @Mock - private JList list; - - @Mock - private PopupChooserBuilder popupChooserBuilder; - - @Mock - private Editor editor; - - @Mock - private Runnable runnable; - - @Mock - private JBPopup popup; - - @Test - void shouldInvokePopupChooserBuilder() { - // given - given(popupChooserBuilderFactory.getPopupChooserBuilder(list)).willReturn(popupChooserBuilder); - given(popupChooserBuilder.setTitle(TITLE)).willReturn(popupChooserBuilder); - given(popupChooserBuilder.setItemChoosenCallback(runnable)).willReturn(popupChooserBuilder); - given(popupChooserBuilder.setMovable(true)).willReturn(popupChooserBuilder); - given(popupChooserBuilder.createPopup()).willReturn(popup); - - // when - popupDisplayer.displayPopupChooser(editor, list, runnable); - - // then - verify(popup).showInBestPositionFor(editor); - } -} +package pl.mjedynak.idea.plugins.builder.gui.displayer; + +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; + +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.ui.popup.JBPopup; +import com.intellij.openapi.ui.popup.PopupChooserBuilder; +import javax.swing.JList; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import pl.mjedynak.idea.plugins.builder.factory.PopupChooserBuilderFactory; + +@ExtendWith(MockitoExtension.class) +public class GenerateBuilderPopupDisplayerTest { + + private static final String TITLE = "Builder already exists"; + + @InjectMocks + private GenerateBuilderPopupDisplayer popupDisplayer; + + @Mock + private PopupChooserBuilderFactory popupChooserBuilderFactory; + + @SuppressWarnings("rawtypes") + @Mock + private JList list; + + @Mock + private PopupChooserBuilder popupChooserBuilder; + + @Mock + private Editor editor; + + @Mock + private Runnable runnable; + + @Mock + private JBPopup popup; + + @Test + void shouldInvokePopupChooserBuilder() { + // given + given(popupChooserBuilderFactory.getPopupChooserBuilder(list)).willReturn(popupChooserBuilder); + given(popupChooserBuilder.setTitle(TITLE)).willReturn(popupChooserBuilder); + given(popupChooserBuilder.setItemChoosenCallback(runnable)).willReturn(popupChooserBuilder); + given(popupChooserBuilder.setMovable(true)).willReturn(popupChooserBuilder); + given(popupChooserBuilder.createPopup()).willReturn(popup); + + // when + popupDisplayer.displayPopupChooser(editor, list, runnable); + + // then + verify(popup).showInBestPositionFor(editor); + } +} diff --git a/src/test/java/pl/mjedynak/idea/plugins/builder/gui/displayer/GoToBuilderPopupDisplayerTest.java b/src/test/java/pl/mjedynak/idea/plugins/builder/gui/displayer/GoToBuilderPopupDisplayerTest.java index 0f63fc2..03925e8 100644 --- a/src/test/java/pl/mjedynak/idea/plugins/builder/gui/displayer/GoToBuilderPopupDisplayerTest.java +++ b/src/test/java/pl/mjedynak/idea/plugins/builder/gui/displayer/GoToBuilderPopupDisplayerTest.java @@ -1,59 +1,59 @@ -package pl.mjedynak.idea.plugins.builder.gui.displayer; - -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.verify; - -import com.intellij.openapi.editor.Editor; -import com.intellij.openapi.ui.popup.JBPopup; -import com.intellij.openapi.ui.popup.PopupChooserBuilder; -import javax.swing.JList; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import pl.mjedynak.idea.plugins.builder.factory.PopupChooserBuilderFactory; - -@ExtendWith(MockitoExtension.class) -public class GoToBuilderPopupDisplayerTest { - - private static final String TITLE = "Builder not found"; - - @InjectMocks - private GoToBuilderPopupDisplayer popupDisplayer; - - @Mock - private PopupChooserBuilderFactory popupChooserBuilderFactory; - - @SuppressWarnings("rawtypes") - @Mock - private JList list; - - @Mock - private PopupChooserBuilder popupChooserBuilder; - - @Mock - private Editor editor; - - @Mock - private Runnable runnable; - - @Mock - private JBPopup popup; - - @Test - void shouldInvokePopupChooserBuilder() { - // given - given(popupChooserBuilderFactory.getPopupChooserBuilder(list)).willReturn(popupChooserBuilder); - given(popupChooserBuilder.setTitle(TITLE)).willReturn(popupChooserBuilder); - given(popupChooserBuilder.setItemChoosenCallback(runnable)).willReturn(popupChooserBuilder); - given(popupChooserBuilder.setMovable(true)).willReturn(popupChooserBuilder); - given(popupChooserBuilder.createPopup()).willReturn(popup); - - // when - popupDisplayer.displayPopupChooser(editor, list, runnable); - - // then - verify(popup).showInBestPositionFor(editor); - } -} +package pl.mjedynak.idea.plugins.builder.gui.displayer; + +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; + +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.ui.popup.JBPopup; +import com.intellij.openapi.ui.popup.PopupChooserBuilder; +import javax.swing.JList; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import pl.mjedynak.idea.plugins.builder.factory.PopupChooserBuilderFactory; + +@ExtendWith(MockitoExtension.class) +public class GoToBuilderPopupDisplayerTest { + + private static final String TITLE = "Builder not found"; + + @InjectMocks + private GoToBuilderPopupDisplayer popupDisplayer; + + @Mock + private PopupChooserBuilderFactory popupChooserBuilderFactory; + + @SuppressWarnings("rawtypes") + @Mock + private JList list; + + @Mock + private PopupChooserBuilder popupChooserBuilder; + + @Mock + private Editor editor; + + @Mock + private Runnable runnable; + + @Mock + private JBPopup popup; + + @Test + void shouldInvokePopupChooserBuilder() { + // given + given(popupChooserBuilderFactory.getPopupChooserBuilder(list)).willReturn(popupChooserBuilder); + given(popupChooserBuilder.setTitle(TITLE)).willReturn(popupChooserBuilder); + given(popupChooserBuilder.setItemChoosenCallback(runnable)).willReturn(popupChooserBuilder); + given(popupChooserBuilder.setMovable(true)).willReturn(popupChooserBuilder); + given(popupChooserBuilder.createPopup()).willReturn(popup); + + // when + popupDisplayer.displayPopupChooser(editor, list, runnable); + + // then + verify(popup).showInBestPositionFor(editor); + } +} diff --git a/src/test/java/pl/mjedynak/idea/plugins/builder/psi/ButMethodCreatorTest.java b/src/test/java/pl/mjedynak/idea/plugins/builder/psi/ButMethodCreatorTest.java index 857cf15..2c745f8 100644 --- a/src/test/java/pl/mjedynak/idea/plugins/builder/psi/ButMethodCreatorTest.java +++ b/src/test/java/pl/mjedynak/idea/plugins/builder/psi/ButMethodCreatorTest.java @@ -1,113 +1,113 @@ -package pl.mjedynak.idea.plugins.builder.psi; - -import static java.util.Arrays.asList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.springframework.test.util.ReflectionTestUtils.setField; - -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiElementFactory; -import com.intellij.psi.PsiMethod; -import com.intellij.psi.PsiParameter; -import com.intellij.psi.PsiParameterList; -import java.util.List; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import pl.mjedynak.idea.plugins.builder.settings.CodeStyleSettings; - -@ExtendWith(MockitoExtension.class) -public class ButMethodCreatorTest { - - @InjectMocks - private ButMethodCreator butMethodCreator; - - @Mock - private PsiElementFactory psiElementFactory; - - @Mock - private CodeStyleSettings settings; - - @Mock - private PsiClass builderClass; - - @Mock - private PsiClass srcClass; - - @Mock - private PsiMethod method1; - - @Mock - private PsiMethod method2; - - @Mock - private PsiMethod method3; - - @Mock - private PsiMethod createdMethod; - - @Mock - private PsiParameterList parameterList1; - - @Mock - private PsiParameterList parameterList2; - - @Mock - private PsiParameter parameter; - - private final String srcClassFieldName = "className"; - - @BeforeEach - public void mockCodeStyleManager() { - given(settings.getFieldNamePrefix()).willReturn("m_"); - given(settings.getParameterNamePrefix()).willReturn("p_"); - setField(butMethodCreator, "codeStyleSettings", settings); - } - - private void initOtherCommonMocks() { - given(builderClass.getMethods()) - .willReturn(asList(method1, method2, method3).toArray(PsiMethod[]::new)); - given(method1.getName()).willReturn("Builder"); - given(method2.getName()).willReturn("aBuilder"); - given(method2.getParameterList()).willReturn(parameterList1); - given(parameterList1.getParametersCount()).willReturn(0); - given(method3.getName()).willReturn("withAge"); - given(method3.getParameterList()).willReturn(parameterList2); - given(parameterList2.getParametersCount()).willReturn(1); - given(parameterList2.getParameters()).willReturn(List.of(parameter).toArray(PsiParameter[]::new)); - given(parameter.getName()).willReturn("age"); - } - - @Test - void shouldCreateButMethod() { - // given - initOtherCommonMocks(); - given(psiElementFactory.createMethodFromText( - "public Builder but() { return aBuilder().withAge(m_age); }", srcClass)) - .willReturn(createdMethod); - - // when - PsiMethod result = butMethodCreator.butMethod("Builder", builderClass, srcClass, srcClassFieldName, false); - - // then - assertThat(result).isEqualTo(createdMethod); - } - - @Test - void shouldCreateButMethodForSingleField() { - // given - initOtherCommonMocks(); - given(psiElementFactory.createMethodFromText( - "public Builder but() { return aBuilder().withAge(className.getAge()); }", srcClass)) - .willReturn(createdMethod); - - // when - PsiMethod result = butMethodCreator.butMethod("Builder", builderClass, srcClass, srcClassFieldName, true); - - // then - assertThat(result).isEqualTo(createdMethod); - } -} +package pl.mjedynak.idea.plugins.builder.psi; + +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.springframework.test.util.ReflectionTestUtils.setField; + +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiElementFactory; +import com.intellij.psi.PsiMethod; +import com.intellij.psi.PsiParameter; +import com.intellij.psi.PsiParameterList; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import pl.mjedynak.idea.plugins.builder.settings.CodeStyleSettings; + +@ExtendWith(MockitoExtension.class) +public class ButMethodCreatorTest { + + @InjectMocks + private ButMethodCreator butMethodCreator; + + @Mock + private PsiElementFactory psiElementFactory; + + @Mock + private CodeStyleSettings settings; + + @Mock + private PsiClass builderClass; + + @Mock + private PsiClass srcClass; + + @Mock + private PsiMethod method1; + + @Mock + private PsiMethod method2; + + @Mock + private PsiMethod method3; + + @Mock + private PsiMethod createdMethod; + + @Mock + private PsiParameterList parameterList1; + + @Mock + private PsiParameterList parameterList2; + + @Mock + private PsiParameter parameter; + + private final String srcClassFieldName = "className"; + + @BeforeEach + public void mockCodeStyleManager() { + given(settings.getFieldNamePrefix()).willReturn("m_"); + given(settings.getParameterNamePrefix()).willReturn("p_"); + setField(butMethodCreator, "codeStyleSettings", settings); + } + + private void initOtherCommonMocks() { + given(builderClass.getMethods()) + .willReturn(asList(method1, method2, method3).toArray(PsiMethod[]::new)); + given(method1.getName()).willReturn("Builder"); + given(method2.getName()).willReturn("aBuilder"); + given(method2.getParameterList()).willReturn(parameterList1); + given(parameterList1.getParametersCount()).willReturn(0); + given(method3.getName()).willReturn("withAge"); + given(method3.getParameterList()).willReturn(parameterList2); + given(parameterList2.getParametersCount()).willReturn(1); + given(parameterList2.getParameters()).willReturn(List.of(parameter).toArray(PsiParameter[]::new)); + given(parameter.getName()).willReturn("age"); + } + + @Test + void shouldCreateButMethod() { + // given + initOtherCommonMocks(); + given(psiElementFactory.createMethodFromText( + "public Builder but() { return aBuilder().withAge(m_age); }", srcClass)) + .willReturn(createdMethod); + + // when + PsiMethod result = butMethodCreator.butMethod("Builder", builderClass, srcClass, srcClassFieldName, false); + + // then + assertThat(result).isEqualTo(createdMethod); + } + + @Test + void shouldCreateButMethodForSingleField() { + // given + initOtherCommonMocks(); + given(psiElementFactory.createMethodFromText( + "public Builder but() { return aBuilder().withAge(className.getAge()); }", srcClass)) + .willReturn(createdMethod); + + // when + PsiMethod result = butMethodCreator.butMethod("Builder", builderClass, srcClass, srcClassFieldName, true); + + // then + assertThat(result).isEqualTo(createdMethod); + } +} diff --git a/src/test/java/pl/mjedynak/idea/plugins/builder/psi/MethodCreatorTest.java b/src/test/java/pl/mjedynak/idea/plugins/builder/psi/MethodCreatorTest.java index d8da501..31c6847 100644 --- a/src/test/java/pl/mjedynak/idea/plugins/builder/psi/MethodCreatorTest.java +++ b/src/test/java/pl/mjedynak/idea/plugins/builder/psi/MethodCreatorTest.java @@ -1,93 +1,93 @@ -package pl.mjedynak.idea.plugins.builder.psi; - -import static org.apache.commons.lang3.StringUtils.EMPTY; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.springframework.test.util.ReflectionTestUtils.setField; - -import com.intellij.psi.PsiElementFactory; -import com.intellij.psi.PsiField; -import com.intellij.psi.PsiMethod; -import com.intellij.psi.PsiType; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import pl.mjedynak.idea.plugins.builder.settings.CodeStyleSettings; - -@ExtendWith(MockitoExtension.class) -public class MethodCreatorTest { - - private MethodCreator methodCreator; - - @Mock - private MethodNameCreator methodNameCreator; - - @Mock - private CodeStyleSettings codeStyleSettings; - - @Mock - private PsiElementFactory elementFactory; - - @Mock - private PsiField psiField; - - @Mock - private PsiType type; - - @Mock - private PsiMethod method; - - private final String srcClassFieldName = "className"; - - @BeforeEach - public void mockCodeStyleManager() { - methodCreator = new MethodCreator(elementFactory, "BuilderClassName"); - setField(methodCreator, "codeStyleSettings", codeStyleSettings); - setField(methodCreator, "methodNameCreator", methodNameCreator); - given(codeStyleSettings.getFieldNamePrefix()).willReturn(EMPTY); - given(codeStyleSettings.getParameterNamePrefix()).willReturn(EMPTY); - } - - private void initOtherCommonMocks() { - given(psiField.getName()).willReturn("name"); - given(type.getPresentableText()).willReturn("String"); - given(psiField.getType()).willReturn(type); - given(methodNameCreator.createMethodName("with", "name")).willReturn("withName"); - } - - @Test - void shouldCreateMethod() { - // given - initOtherCommonMocks(); - given(elementFactory.createMethodFromText( - "public BuilderClassName withName(String name) { this.name = name; return this; }", psiField)) - .willReturn(method); - String methodPrefix = "with"; - - // when - PsiMethod result = methodCreator.createMethod(psiField, methodPrefix, srcClassFieldName, false); - - // then - assertThat(result).isEqualTo(method); - } - - @Test - void shouldCreateMethodForSingleField() { - // given - initOtherCommonMocks(); - given(methodNameCreator.createMethodName("set", "name")).willReturn("setName"); - given(elementFactory.createMethodFromText( - "public BuilderClassName withName(String name) { className.setName(name); return this; }", - psiField)) - .willReturn(method); - String methodPrefix = "with"; - - // when - PsiMethod result = methodCreator.createMethod(psiField, methodPrefix, srcClassFieldName, true); - - // then - assertThat(result).isEqualTo(method); - } -} +package pl.mjedynak.idea.plugins.builder.psi; + +import static org.apache.commons.lang3.StringUtils.EMPTY; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.springframework.test.util.ReflectionTestUtils.setField; + +import com.intellij.psi.PsiElementFactory; +import com.intellij.psi.PsiField; +import com.intellij.psi.PsiMethod; +import com.intellij.psi.PsiType; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import pl.mjedynak.idea.plugins.builder.settings.CodeStyleSettings; + +@ExtendWith(MockitoExtension.class) +public class MethodCreatorTest { + + private MethodCreator methodCreator; + + @Mock + private MethodNameCreator methodNameCreator; + + @Mock + private CodeStyleSettings codeStyleSettings; + + @Mock + private PsiElementFactory elementFactory; + + @Mock + private PsiField psiField; + + @Mock + private PsiType type; + + @Mock + private PsiMethod method; + + private final String srcClassFieldName = "className"; + + @BeforeEach + public void mockCodeStyleManager() { + methodCreator = new MethodCreator(elementFactory, "BuilderClassName"); + setField(methodCreator, "codeStyleSettings", codeStyleSettings); + setField(methodCreator, "methodNameCreator", methodNameCreator); + given(codeStyleSettings.getFieldNamePrefix()).willReturn(EMPTY); + given(codeStyleSettings.getParameterNamePrefix()).willReturn(EMPTY); + } + + private void initOtherCommonMocks() { + given(psiField.getName()).willReturn("name"); + given(type.getPresentableText()).willReturn("String"); + given(psiField.getType()).willReturn(type); + given(methodNameCreator.createMethodName("with", "name")).willReturn("withName"); + } + + @Test + void shouldCreateMethod() { + // given + initOtherCommonMocks(); + given(elementFactory.createMethodFromText( + "public BuilderClassName withName(String name) { this.name = name; return this; }", psiField)) + .willReturn(method); + String methodPrefix = "with"; + + // when + PsiMethod result = methodCreator.createMethod(psiField, methodPrefix, srcClassFieldName, false); + + // then + assertThat(result).isEqualTo(method); + } + + @Test + void shouldCreateMethodForSingleField() { + // given + initOtherCommonMocks(); + given(methodNameCreator.createMethodName("set", "name")).willReturn("setName"); + given(elementFactory.createMethodFromText( + "public BuilderClassName withName(String name) { className.setName(name); return this; }", + psiField)) + .willReturn(method); + String methodPrefix = "with"; + + // when + PsiMethod result = methodCreator.createMethod(psiField, methodPrefix, srcClassFieldName, true); + + // then + assertThat(result).isEqualTo(method); + } +} diff --git a/src/test/java/pl/mjedynak/idea/plugins/builder/psi/MethodNameCreatorTest.java b/src/test/java/pl/mjedynak/idea/plugins/builder/psi/MethodNameCreatorTest.java index e2ae231..3c531d5 100644 --- a/src/test/java/pl/mjedynak/idea/plugins/builder/psi/MethodNameCreatorTest.java +++ b/src/test/java/pl/mjedynak/idea/plugins/builder/psi/MethodNameCreatorTest.java @@ -1,29 +1,29 @@ -package pl.mjedynak.idea.plugins.builder.psi; - -import static org.apache.commons.lang3.StringUtils.EMPTY; -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.jupiter.api.Test; - -public class MethodNameCreatorTest { - - private final MethodNameCreator methodNameCreator = new MethodNameCreator(); - - @Test - void shouldCreateMethodIfPrefixIsEmpty() { - // when - String result = methodNameCreator.createMethodName(EMPTY, "userName"); - - // then - assertThat(result).isEqualTo("userName"); - } - - @Test - void shouldCreateMethodWithCapitalizedFieldNameIfPrefixIsNotEmpty() { - // when - String result = methodNameCreator.createMethodName("with", "field"); - - // then - assertThat(result).isEqualTo("withField"); - } -} +package pl.mjedynak.idea.plugins.builder.psi; + +import static org.apache.commons.lang3.StringUtils.EMPTY; +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; + +public class MethodNameCreatorTest { + + private final MethodNameCreator methodNameCreator = new MethodNameCreator(); + + @Test + void shouldCreateMethodIfPrefixIsEmpty() { + // when + String result = methodNameCreator.createMethodName(EMPTY, "userName"); + + // then + assertThat(result).isEqualTo("userName"); + } + + @Test + void shouldCreateMethodWithCapitalizedFieldNameIfPrefixIsNotEmpty() { + // when + String result = methodNameCreator.createMethodName("with", "field"); + + // then + assertThat(result).isEqualTo("withField"); + } +} diff --git a/src/test/java/pl/mjedynak/idea/plugins/builder/psi/PsiFieldSelectorTest.java b/src/test/java/pl/mjedynak/idea/plugins/builder/psi/PsiFieldSelectorTest.java index 9e25752..75427a5 100644 --- a/src/test/java/pl/mjedynak/idea/plugins/builder/psi/PsiFieldSelectorTest.java +++ b/src/test/java/pl/mjedynak/idea/plugins/builder/psi/PsiFieldSelectorTest.java @@ -1,115 +1,115 @@ -package pl.mjedynak.idea.plugins.builder.psi; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mock.Strictness.LENIENT; -import static org.mockito.Mockito.mock; - -import com.intellij.codeInsight.generation.PsiElementClassMember; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiField; -import java.util.List; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import pl.mjedynak.idea.plugins.builder.factory.PsiElementClassMemberFactory; -import pl.mjedynak.idea.plugins.builder.verifier.PsiFieldVerifier; - -@ExtendWith(MockitoExtension.class) -public class PsiFieldSelectorTest { - - @InjectMocks - private PsiFieldSelector psiFieldSelector; - - @Mock(strictness = LENIENT) - private PsiElementClassMemberFactory psiElementClassMemberFactory; - - @Mock(strictness = LENIENT) - private PsiFieldVerifier psiFieldVerifier; - - @Mock - private PsiClass psiClass; - - @Mock - private PsiField psiField; - - @BeforeEach - public void setUp() { - PsiField[] fieldsArray = new PsiField[1]; - fieldsArray[0] = psiField; - given(psiClass.getAllFields()).willReturn(fieldsArray); - given(psiElementClassMemberFactory.createPsiElementClassMember(any(PsiField.class))) - .willReturn(mock(PsiElementClassMember.class)); - } - - @Test - void shouldSelectFieldIfVerifierAcceptsItAsSetInSetter() { - doTest(false, true, false, false, false, false, 1); - } - - @Test - void shouldSelectFieldIfVerifierAcceptsItAsSetInConstructor() { - doTest(true, false, false, false, false, false, 1); - } - - @Test - void shouldNotSelectFieldIfVerifierDoesNotAcceptsItAsSetInConstructorOrInSetter() { - doTest(false, false, true, false, false, false, 0); - } - - @Test - void shouldSelectAllFieldsIfInnerBuilder() { - doTest(false, false, false, true, false, false, 1); - } - - @Test - void shouldNeverSelectSerialVersionUIDField() { - given(psiField.getName()).willReturn("serialVersionUID"); - doTest(true, true, true, false, false, false, 0); - } - - @Test - void shouldSelectFieldIfUseSingleFieldAndHasSetter() { - doTest(false, true, false, false, true, false, 1); - } - - @Test - void shouldNotSelectFieldIfUseSingleFieldAndHasNoSetter() { - doTest(true, false, true, false, true, false, 0); - } - - @Test - void shouldSelectFieldIfUseSingleFieldAndButMethodAndHasSetterAndGetter() { - doTest(false, true, true, false, true, true, 1); - } - - @Test - void shouldNotSelectFieldIfUseSingleFieldAndButMethodAndHasSetterAndNoGetter() { - doTest(true, true, false, false, true, true, 0); - } - - private void doTest( - boolean isSetInConstructor, - boolean isSetInSetter, - boolean hasGetter, - boolean isInnerBuilder, - boolean useSingleField, - boolean hasButMethod, - int size) { - // given - given(psiFieldVerifier.isSetInConstructor(psiField, psiClass)).willReturn(isSetInConstructor); - given(psiFieldVerifier.isSetInSetterMethod(psiField, psiClass)).willReturn(isSetInSetter); - given(psiFieldVerifier.hasGetterMethod(psiField, psiClass)).willReturn(hasGetter); - - // when - List> result = - psiFieldSelector.selectFieldsToIncludeInBuilder(psiClass, isInnerBuilder, useSingleField, hasButMethod); - - // then - assertThat(result).hasSize(size); - } -} +package pl.mjedynak.idea.plugins.builder.psi; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mock.Strictness.LENIENT; +import static org.mockito.Mockito.mock; + +import com.intellij.codeInsight.generation.PsiElementClassMember; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiField; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import pl.mjedynak.idea.plugins.builder.factory.PsiElementClassMemberFactory; +import pl.mjedynak.idea.plugins.builder.verifier.PsiFieldVerifier; + +@ExtendWith(MockitoExtension.class) +public class PsiFieldSelectorTest { + + @InjectMocks + private PsiFieldSelector psiFieldSelector; + + @Mock(strictness = LENIENT) + private PsiElementClassMemberFactory psiElementClassMemberFactory; + + @Mock(strictness = LENIENT) + private PsiFieldVerifier psiFieldVerifier; + + @Mock + private PsiClass psiClass; + + @Mock + private PsiField psiField; + + @BeforeEach + public void setUp() { + PsiField[] fieldsArray = new PsiField[1]; + fieldsArray[0] = psiField; + given(psiClass.getAllFields()).willReturn(fieldsArray); + given(psiElementClassMemberFactory.createPsiElementClassMember(any(PsiField.class))) + .willReturn(mock(PsiElementClassMember.class)); + } + + @Test + void shouldSelectFieldIfVerifierAcceptsItAsSetInSetter() { + doTest(false, true, false, false, false, false, 1); + } + + @Test + void shouldSelectFieldIfVerifierAcceptsItAsSetInConstructor() { + doTest(true, false, false, false, false, false, 1); + } + + @Test + void shouldNotSelectFieldIfVerifierDoesNotAcceptsItAsSetInConstructorOrInSetter() { + doTest(false, false, true, false, false, false, 0); + } + + @Test + void shouldSelectAllFieldsIfInnerBuilder() { + doTest(false, false, false, true, false, false, 1); + } + + @Test + void shouldNeverSelectSerialVersionUIDField() { + given(psiField.getName()).willReturn("serialVersionUID"); + doTest(true, true, true, false, false, false, 0); + } + + @Test + void shouldSelectFieldIfUseSingleFieldAndHasSetter() { + doTest(false, true, false, false, true, false, 1); + } + + @Test + void shouldNotSelectFieldIfUseSingleFieldAndHasNoSetter() { + doTest(true, false, true, false, true, false, 0); + } + + @Test + void shouldSelectFieldIfUseSingleFieldAndButMethodAndHasSetterAndGetter() { + doTest(false, true, true, false, true, true, 1); + } + + @Test + void shouldNotSelectFieldIfUseSingleFieldAndButMethodAndHasSetterAndNoGetter() { + doTest(true, true, false, false, true, true, 0); + } + + private void doTest( + boolean isSetInConstructor, + boolean isSetInSetter, + boolean hasGetter, + boolean isInnerBuilder, + boolean useSingleField, + boolean hasButMethod, + int size) { + // given + given(psiFieldVerifier.isSetInConstructor(psiField, psiClass)).willReturn(isSetInConstructor); + given(psiFieldVerifier.isSetInSetterMethod(psiField, psiClass)).willReturn(isSetInSetter); + given(psiFieldVerifier.hasGetterMethod(psiField, psiClass)).willReturn(hasGetter); + + // when + List> result = + psiFieldSelector.selectFieldsToIncludeInBuilder(psiClass, isInnerBuilder, useSingleField, hasButMethod); + + // then + assertThat(result).hasSize(size); + } +} diff --git a/src/test/java/pl/mjedynak/idea/plugins/builder/psi/PsiFieldsModifierTest.java b/src/test/java/pl/mjedynak/idea/plugins/builder/psi/PsiFieldsModifierTest.java index 79c8c7d..48f0fc1 100644 --- a/src/test/java/pl/mjedynak/idea/plugins/builder/psi/PsiFieldsModifierTest.java +++ b/src/test/java/pl/mjedynak/idea/plugins/builder/psi/PsiFieldsModifierTest.java @@ -1,88 +1,88 @@ -package pl.mjedynak.idea.plugins.builder.psi; - -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -import com.intellij.openapi.project.Project; -import com.intellij.psi.PsiAnnotation; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiElementFactory; -import com.intellij.psi.PsiField; -import com.intellij.psi.PsiModifier; -import com.intellij.psi.PsiModifierList; -import com.intellij.psi.PsiType; -import java.util.ArrayList; -import java.util.List; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; - -@ExtendWith(MockitoExtension.class) -public class PsiFieldsModifierTest { - - private final PsiFieldsModifier psiFieldsModifier = new PsiFieldsModifier(); - - @Mock - private PsiClass builderClass; - - @Mock - private Project project; - - @Mock - private PsiElementFactory psiElementFactory; - - private List psiFieldsForSetters; - private List psiFieldsForConstructor; - - @BeforeEach - public void setUp() { - psiFieldsForConstructor = new ArrayList<>(); - psiFieldsForSetters = new ArrayList<>(); - } - - @Test - void shouldAddPrivateFieldsToBuilderClass() { - // given - PsiField psiFieldForSetters = mock(PsiField.class); - given(psiFieldForSetters.getName()).willReturn("setterField"); - given(psiFieldForSetters.getType()).willReturn(PsiType.INT); - psiFieldsForSetters.add(psiFieldForSetters); - PsiField copyPsiFieldForSetter = mock(PsiField.class); - PsiModifierList copyPsiFieldForSetterModifierList = mock(PsiModifierList.class); - given(copyPsiFieldForSetter.getModifierList()).willReturn(copyPsiFieldForSetterModifierList); - given(psiElementFactory.createField("setterField", PsiType.INT)).willReturn(copyPsiFieldForSetter); - - PsiField psiFieldForConstructor = mock(PsiField.class); - given(psiFieldForConstructor.getName()).willReturn("constructorField"); - given(psiFieldForConstructor.getType()).willReturn(PsiType.BOOLEAN); - psiFieldsForConstructor.add(psiFieldForConstructor); - PsiField copyPsiFieldForConstructor = mock(PsiField.class); - PsiModifierList copyPsiFieldForConstructorModifierList = mock(PsiModifierList.class); - given(copyPsiFieldForConstructor.getModifierList()).willReturn(copyPsiFieldForConstructorModifierList); - given(psiElementFactory.createField("constructorField", PsiType.BOOLEAN)) - .willReturn(copyPsiFieldForConstructor); - - given(builderClass.getProject()).willReturn(project); - given(project.getService(PsiElementFactory.class)).willReturn(psiElementFactory); - - // when - psiFieldsModifier.modifyFields(psiFieldsForSetters, psiFieldsForConstructor, builderClass); - - // then - verify(builderClass).add(copyPsiFieldForSetter); - verify(copyPsiFieldForSetterModifierList).setModifierProperty(PsiModifier.PRIVATE, true); - verify(builderClass).add(copyPsiFieldForConstructor); - verify(copyPsiFieldForConstructorModifierList).setModifierProperty(PsiModifier.PRIVATE, true); - verifyNoMoreInteractions(builderClass); - } - - private PsiAnnotation[] createAnnotationArray(PsiAnnotation annotation) { - PsiAnnotation[] annotationArray = new PsiAnnotation[1]; - annotationArray[0] = annotation; - return annotationArray; - } -} +package pl.mjedynak.idea.plugins.builder.psi; + +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +import com.intellij.openapi.project.Project; +import com.intellij.psi.PsiAnnotation; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiElementFactory; +import com.intellij.psi.PsiField; +import com.intellij.psi.PsiModifier; +import com.intellij.psi.PsiModifierList; +import com.intellij.psi.PsiType; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +public class PsiFieldsModifierTest { + + private final PsiFieldsModifier psiFieldsModifier = new PsiFieldsModifier(); + + @Mock + private PsiClass builderClass; + + @Mock + private Project project; + + @Mock + private PsiElementFactory psiElementFactory; + + private List psiFieldsForSetters; + private List psiFieldsForConstructor; + + @BeforeEach + public void setUp() { + psiFieldsForConstructor = new ArrayList<>(); + psiFieldsForSetters = new ArrayList<>(); + } + + @Test + void shouldAddPrivateFieldsToBuilderClass() { + // given + PsiField psiFieldForSetters = mock(PsiField.class); + given(psiFieldForSetters.getName()).willReturn("setterField"); + given(psiFieldForSetters.getType()).willReturn(PsiType.INT); + psiFieldsForSetters.add(psiFieldForSetters); + PsiField copyPsiFieldForSetter = mock(PsiField.class); + PsiModifierList copyPsiFieldForSetterModifierList = mock(PsiModifierList.class); + given(copyPsiFieldForSetter.getModifierList()).willReturn(copyPsiFieldForSetterModifierList); + given(psiElementFactory.createField("setterField", PsiType.INT)).willReturn(copyPsiFieldForSetter); + + PsiField psiFieldForConstructor = mock(PsiField.class); + given(psiFieldForConstructor.getName()).willReturn("constructorField"); + given(psiFieldForConstructor.getType()).willReturn(PsiType.BOOLEAN); + psiFieldsForConstructor.add(psiFieldForConstructor); + PsiField copyPsiFieldForConstructor = mock(PsiField.class); + PsiModifierList copyPsiFieldForConstructorModifierList = mock(PsiModifierList.class); + given(copyPsiFieldForConstructor.getModifierList()).willReturn(copyPsiFieldForConstructorModifierList); + given(psiElementFactory.createField("constructorField", PsiType.BOOLEAN)) + .willReturn(copyPsiFieldForConstructor); + + given(builderClass.getProject()).willReturn(project); + given(project.getService(PsiElementFactory.class)).willReturn(psiElementFactory); + + // when + psiFieldsModifier.modifyFields(psiFieldsForSetters, psiFieldsForConstructor, builderClass); + + // then + verify(builderClass).add(copyPsiFieldForSetter); + verify(copyPsiFieldForSetterModifierList).setModifierProperty(PsiModifier.PRIVATE, true); + verify(builderClass).add(copyPsiFieldForConstructor); + verify(copyPsiFieldForConstructorModifierList).setModifierProperty(PsiModifier.PRIVATE, true); + verifyNoMoreInteractions(builderClass); + } + + private PsiAnnotation[] createAnnotationArray(PsiAnnotation annotation) { + PsiAnnotation[] annotationArray = new PsiAnnotation[1]; + annotationArray[0] = annotation; + return annotationArray; + } +} diff --git a/src/test/java/pl/mjedynak/idea/plugins/builder/psi/model/PsiFieldsForBuilderTest.java b/src/test/java/pl/mjedynak/idea/plugins/builder/psi/model/PsiFieldsForBuilderTest.java index 04a102c..e8de298 100644 --- a/src/test/java/pl/mjedynak/idea/plugins/builder/psi/model/PsiFieldsForBuilderTest.java +++ b/src/test/java/pl/mjedynak/idea/plugins/builder/psi/model/PsiFieldsForBuilderTest.java @@ -1,83 +1,83 @@ -package pl.mjedynak.idea.plugins.builder.psi.model; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.catchThrowableOfType; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.mock; - -import com.google.common.collect.Lists; -import com.intellij.psi.PsiField; -import com.intellij.psi.PsiMethod; -import java.util.List; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.junit.jupiter.MockitoExtension; - -@ExtendWith(MockitoExtension.class) -public class PsiFieldsForBuilderTest { - - private PsiFieldsForBuilder psiFieldsForBuilder; - - private List psiFieldsForSetters; - private List psiFieldsForConstructor; - private List allSelectedPsiFields; - private PsiMethod bestConstructor; - - @BeforeEach - public void setUp() { - psiFieldsForSetters = Lists.newArrayList(); - psiFieldsForSetters.add(mock(PsiField.class)); - psiFieldsForConstructor = Lists.newArrayList(); - psiFieldsForConstructor.add(mock(PsiField.class)); - allSelectedPsiFields = Lists.newArrayList(); - allSelectedPsiFields.add(mock(PsiField.class)); - allSelectedPsiFields.add(mock(PsiField.class)); - bestConstructor = mock(PsiMethod.class); - psiFieldsForBuilder = new PsiFieldsForBuilder( - psiFieldsForSetters, psiFieldsForConstructor, allSelectedPsiFields, bestConstructor); - } - - @Test - void shouldGetThreeListsOfFieldsAndBestConstructor() { - assertThat(psiFieldsForBuilder.getFieldsForSetters()).isEqualTo(psiFieldsForSetters); - assertThat(psiFieldsForBuilder.getFieldsForConstructor()).isEqualTo(psiFieldsForConstructor); - assertThat(psiFieldsForBuilder.getAllSelectedFields()).isEqualTo(allSelectedPsiFields); - assertThat(psiFieldsForBuilder.getBestConstructor()).isEqualTo(bestConstructor); - } - - @Test - void shouldThrowExceptionWhenTryingToModifySettersList() { - assertThrows(UnsupportedOperationException.class, () -> { - // given - List fieldsForSetters = psiFieldsForBuilder.getFieldsForSetters(); - - // when - fieldsForSetters.remove(0); - }); - } - - @Test - void shouldThrowExceptionWhenTryingToModifyConstructorList() { - assertThrows(UnsupportedOperationException.class, () -> { - // given - List fieldsForConstructor = psiFieldsForBuilder.getFieldsForConstructor(); - - // when - fieldsForConstructor.remove(0); - }); - } - - @Test - void shouldThrowExceptionWhenTryingToModifyAllSelectedFieldsList() { - // given - List allSelectedFields = psiFieldsForBuilder.getAllSelectedFields(); - - // when - UnsupportedOperationException exception = - catchThrowableOfType(() -> allSelectedFields.remove(0), UnsupportedOperationException.class); - - // then - assertThat(exception).isNotNull(); - } -} +package pl.mjedynak.idea.plugins.builder.psi.model; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowableOfType; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; + +import com.google.common.collect.Lists; +import com.intellij.psi.PsiField; +import com.intellij.psi.PsiMethod; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +public class PsiFieldsForBuilderTest { + + private PsiFieldsForBuilder psiFieldsForBuilder; + + private List psiFieldsForSetters; + private List psiFieldsForConstructor; + private List allSelectedPsiFields; + private PsiMethod bestConstructor; + + @BeforeEach + public void setUp() { + psiFieldsForSetters = Lists.newArrayList(); + psiFieldsForSetters.add(mock(PsiField.class)); + psiFieldsForConstructor = Lists.newArrayList(); + psiFieldsForConstructor.add(mock(PsiField.class)); + allSelectedPsiFields = Lists.newArrayList(); + allSelectedPsiFields.add(mock(PsiField.class)); + allSelectedPsiFields.add(mock(PsiField.class)); + bestConstructor = mock(PsiMethod.class); + psiFieldsForBuilder = new PsiFieldsForBuilder( + psiFieldsForSetters, psiFieldsForConstructor, allSelectedPsiFields, bestConstructor); + } + + @Test + void shouldGetThreeListsOfFieldsAndBestConstructor() { + assertThat(psiFieldsForBuilder.getFieldsForSetters()).isEqualTo(psiFieldsForSetters); + assertThat(psiFieldsForBuilder.getFieldsForConstructor()).isEqualTo(psiFieldsForConstructor); + assertThat(psiFieldsForBuilder.getAllSelectedFields()).isEqualTo(allSelectedPsiFields); + assertThat(psiFieldsForBuilder.getBestConstructor()).isEqualTo(bestConstructor); + } + + @Test + void shouldThrowExceptionWhenTryingToModifySettersList() { + assertThrows(UnsupportedOperationException.class, () -> { + // given + List fieldsForSetters = psiFieldsForBuilder.getFieldsForSetters(); + + // when + fieldsForSetters.remove(0); + }); + } + + @Test + void shouldThrowExceptionWhenTryingToModifyConstructorList() { + assertThrows(UnsupportedOperationException.class, () -> { + // given + List fieldsForConstructor = psiFieldsForBuilder.getFieldsForConstructor(); + + // when + fieldsForConstructor.remove(0); + }); + } + + @Test + void shouldThrowExceptionWhenTryingToModifyAllSelectedFieldsList() { + // given + List allSelectedFields = psiFieldsForBuilder.getAllSelectedFields(); + + // when + UnsupportedOperationException exception = + catchThrowableOfType(() -> allSelectedFields.remove(0), UnsupportedOperationException.class); + + // then + assertThat(exception).isNotNull(); + } +} diff --git a/src/test/java/pl/mjedynak/idea/plugins/builder/renderer/ActionCellRendererTest.java b/src/test/java/pl/mjedynak/idea/plugins/builder/renderer/ActionCellRendererTest.java index ebbf5a5..d33a5ee 100644 --- a/src/test/java/pl/mjedynak/idea/plugins/builder/renderer/ActionCellRendererTest.java +++ b/src/test/java/pl/mjedynak/idea/plugins/builder/renderer/ActionCellRendererTest.java @@ -1,56 +1,56 @@ -package pl.mjedynak.idea.plugins.builder.renderer; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - -import com.intellij.codeInsight.navigation.GotoTargetHandler; -import java.awt.Component; -import javax.swing.Icon; -import javax.swing.JList; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; - -@ExtendWith(MockitoExtension.class) -public class ActionCellRendererTest { - - private ActionCellRenderer actionCellRenderer; - - @Mock - private JList list; - - @Mock - private GotoTargetHandler.AdditionalAction action; - - private boolean anyBooleanValue; - private int anyIndex; - - @BeforeEach - public void setUp() { - actionCellRenderer = new ActionCellRenderer(); - anyBooleanValue = false; - anyIndex = 0; - } - - @Test - void shouldGetTextAndIconFromActionWhenRendering() { - // given - Icon icon = mock(Icon.class); - String actionText = "actionText"; - given(action.getText()).willReturn(actionText); - given(action.getIcon()).willReturn(icon); - - // when - Component result = actionCellRenderer.getListCellRendererComponent( - list, action, anyIndex, anyBooleanValue, anyBooleanValue); - - // then - assertThat(actionCellRenderer.getText()).isEqualTo(actionText); - assertThat(actionCellRenderer.getIcon()).isEqualTo(icon); - assertThat(result).isNotNull(); - assertThat(result).isInstanceOf(ActionCellRenderer.class); - } -} +package pl.mjedynak.idea.plugins.builder.renderer; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + +import com.intellij.codeInsight.navigation.GotoTargetHandler; +import java.awt.Component; +import javax.swing.Icon; +import javax.swing.JList; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +public class ActionCellRendererTest { + + private ActionCellRenderer actionCellRenderer; + + @Mock + private JList list; + + @Mock + private GotoTargetHandler.AdditionalAction action; + + private boolean anyBooleanValue; + private int anyIndex; + + @BeforeEach + public void setUp() { + actionCellRenderer = new ActionCellRenderer(); + anyBooleanValue = false; + anyIndex = 0; + } + + @Test + void shouldGetTextAndIconFromActionWhenRendering() { + // given + Icon icon = mock(Icon.class); + String actionText = "actionText"; + given(action.getText()).willReturn(actionText); + given(action.getIcon()).willReturn(icon); + + // when + Component result = actionCellRenderer.getListCellRendererComponent( + list, action, anyIndex, anyBooleanValue, anyBooleanValue); + + // then + assertThat(actionCellRenderer.getText()).isEqualTo(actionText); + assertThat(actionCellRenderer.getIcon()).isEqualTo(icon); + assertThat(result).isNotNull(); + assertThat(result).isInstanceOf(ActionCellRenderer.class); + } +} diff --git a/src/test/java/pl/mjedynak/idea/plugins/builder/verifier/BuilderVerifierTest.java b/src/test/java/pl/mjedynak/idea/plugins/builder/verifier/BuilderVerifierTest.java index 626d067..a80bc4e 100644 --- a/src/test/java/pl/mjedynak/idea/plugins/builder/verifier/BuilderVerifierTest.java +++ b/src/test/java/pl/mjedynak/idea/plugins/builder/verifier/BuilderVerifierTest.java @@ -1,49 +1,49 @@ -package pl.mjedynak.idea.plugins.builder.verifier; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; - -import com.intellij.psi.PsiClass; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; - -@ExtendWith(MockitoExtension.class) -public class BuilderVerifierTest { - - private BuilderVerifier builderVerifier; - - @Mock - private PsiClass psiClass; - - @BeforeEach - public void setUp() { - builderVerifier = new BuilderVerifier(); - } - - @Test - void shouldVerifyThatClassIsNotABuilderWhenItsDoesNotHaveBuilderSuffix() { - // given - given(psiClass.getName()).willReturn("AnyNameThatDoesn'tHaveBuilderAtTheEnd"); - - // when - boolean result = builderVerifier.isBuilder(psiClass); - - // then - assertThat(result).isFalse(); - } - - @Test - void shouldVerifyThatClassIsABuilderWhenItHasBuilderSuffix() { - // given - given(psiClass.getName()).willReturn("AnyNameThatEndsWithBuilder"); - - // when - boolean result = builderVerifier.isBuilder(psiClass); - - // then - assertThat(result).isTrue(); - } -} +package pl.mjedynak.idea.plugins.builder.verifier; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; + +import com.intellij.psi.PsiClass; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +public class BuilderVerifierTest { + + private BuilderVerifier builderVerifier; + + @Mock + private PsiClass psiClass; + + @BeforeEach + public void setUp() { + builderVerifier = new BuilderVerifier(); + } + + @Test + void shouldVerifyThatClassIsNotABuilderWhenItsDoesNotHaveBuilderSuffix() { + // given + given(psiClass.getName()).willReturn("AnyNameThatDoesn'tHaveBuilderAtTheEnd"); + + // when + boolean result = builderVerifier.isBuilder(psiClass); + + // then + assertThat(result).isFalse(); + } + + @Test + void shouldVerifyThatClassIsABuilderWhenItHasBuilderSuffix() { + // given + given(psiClass.getName()).willReturn("AnyNameThatEndsWithBuilder"); + + // when + boolean result = builderVerifier.isBuilder(psiClass); + + // then + assertThat(result).isTrue(); + } +} diff --git a/src/test/java/pl/mjedynak/idea/plugins/builder/verifier/PsiFieldVerifierTest.java b/src/test/java/pl/mjedynak/idea/plugins/builder/verifier/PsiFieldVerifierTest.java index ddde88c..deed0c2 100644 --- a/src/test/java/pl/mjedynak/idea/plugins/builder/verifier/PsiFieldVerifierTest.java +++ b/src/test/java/pl/mjedynak/idea/plugins/builder/verifier/PsiFieldVerifierTest.java @@ -1,231 +1,231 @@ -package pl.mjedynak.idea.plugins.builder.verifier; - -import static org.apache.commons.lang3.StringUtils.EMPTY; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mock.Strictness.LENIENT; -import static org.mockito.Mockito.mock; -import static org.springframework.test.util.ReflectionTestUtils.setField; - -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiField; -import com.intellij.psi.PsiMethod; -import com.intellij.psi.PsiModifier; -import com.intellij.psi.PsiModifierList; -import com.intellij.psi.PsiParameter; -import com.intellij.psi.PsiParameterList; -import com.intellij.psi.PsiType; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import pl.mjedynak.idea.plugins.builder.settings.CodeStyleSettings; - -@ExtendWith(MockitoExtension.class) -public class PsiFieldVerifierTest { - - private PsiFieldVerifier psiFieldVerifier; - private PsiMethod[] constructors; - private PsiMethod[] methods; - private PsiParameter[] parameters; - - @Mock(strictness = LENIENT) - private PsiField psiField; - - @Mock - private PsiClass psiClass; - - @Mock - private PsiMethod constructor; - - @Mock - private PsiParameterList parameterList; - - @Mock(strictness = LENIENT) - private PsiParameter parameter; - - @Mock - private PsiType psiType; - - @Mock(strictness = LENIENT) - private PsiMethod method; - - @Mock - private PsiModifierList modifierList; - - @Mock(strictness = LENIENT) - private CodeStyleSettings settings; - - private String name; - - @BeforeEach - public void setUp() { - psiFieldVerifier = new PsiFieldVerifier(); - setField(psiFieldVerifier, "codeStyleSettings", settings); - given(settings.getParameterNamePrefix()).willReturn(EMPTY); - given(settings.getFieldNamePrefix()).willReturn(EMPTY); - constructors = new PsiMethod[1]; - constructors[0] = constructor; - methods = new PsiMethod[1]; - methods[0] = method; - parameters = new PsiParameter[1]; - parameters[0] = parameter; - name = "name"; - } - - @Test - void shouldNotVerifyThatFieldIsSetInConstructorIfConstructorDoesNotExist() { - // given - given(psiClass.getConstructors()).willReturn(new PsiMethod[0]); - - // when - boolean result = psiFieldVerifier.isSetInConstructor(psiField, psiClass); - - // then - assertThat(result).isFalse(); - } - - @Test - void shouldNotVerifyThatFieldIsSetInConstructorIfConstructorHasDifferentParameterName() { - // given - prepareBehaviourForReturningParameter(); - given(parameter.getType()).willReturn(psiType); - given(psiField.getType()).willReturn(psiType); - given(parameter.getName()).willReturn(name); - given(psiField.getName()).willReturn("differentName"); - - // when - boolean result = psiFieldVerifier.isSetInConstructor(psiField, psiClass); - - // then - assertThat(result).isFalse(); - } - - @Test - void shouldNotVerifyThatFieldIsSetInConstructorIfConstructorHasDifferentParameterType() { - // given - PsiType differentPsiType = mock(PsiType.class); - prepareBehaviourForReturningParameter(); - given(parameter.getType()).willReturn(psiType); - given(psiField.getType()).willReturn(differentPsiType); - given(parameter.getName()).willReturn(name); - given(psiField.getName()).willReturn(name); - - // when - boolean result = psiFieldVerifier.isSetInConstructor(psiField, psiClass); - - // then - assertThat(result).isFalse(); - } - - @Test - void shouldVerifyThatFieldIsSetInConstructorIfConstructorHasTheSameParameterTypeAndName() { - // given - prepareBehaviourForReturningParameter(); - given(parameter.getType()).willReturn(psiType); - given(psiField.getType()).willReturn(psiType); - given(parameter.getName()).willReturn(name); - given(psiField.getName()).willReturn(name); - - // when - boolean result = psiFieldVerifier.isSetInConstructor(psiField, psiClass); - - // then - assertThat(result).isTrue(); - } - - @Test - void shouldVerifyThatFieldIsSetInSetterMethodIfItIsNotPrivateAndHasCorrectParameter() { - // given - given(psiClass.getAllMethods()).willReturn(methods); - given(method.getModifierList()).willReturn(modifierList); - given(psiField.getName()).willReturn("field"); - given(method.getName()).willReturn("setField"); - - // when - boolean result = psiFieldVerifier.isSetInSetterMethod(psiField, psiClass); - - // then - assertThat(result).isTrue(); - } - - @Test - void shouldVerifyThatFieldIsNotSetInSetterMethodIfItIsPrivate() { - // given - given(psiClass.getAllMethods()).willReturn(methods); - given(method.getModifierList()).willReturn(modifierList); - given(psiField.getName()).willReturn("field"); - given(modifierList.hasExplicitModifier(PsiModifier.PRIVATE)).willReturn(true); - given(method.getName()).willReturn("setField"); - // when - boolean result = psiFieldVerifier.isSetInSetterMethod(psiField, psiClass); - - // then - assertThat(result).isFalse(); - } - - @Test - void shouldVerifyThatFieldIsNotSetInSetterMethodIfItIsNotPrivateButHasIncorrectParameter() { - // given - given(psiClass.getAllMethods()).willReturn(methods); - given(method.getModifierList()).willReturn(modifierList); - given(psiField.getName()).willReturn("field"); - given(method.getName()).willReturn("setAnotherField"); - // when - boolean result = psiFieldVerifier.isSetInSetterMethod(psiField, psiClass); - - // then - assertThat(result).isFalse(); - } - - @Test - void shouldVerifyThatFieldHasGetterMethodAvailableIfTheMethodIsNotPrivateAndHasCorrectName() { - // given - given(psiClass.getAllMethods()).willReturn(methods); - given(method.getModifierList()).willReturn(modifierList); - given(psiField.getName()).willReturn("field"); - given(method.getName()).willReturn("getField"); - - // when - boolean result = psiFieldVerifier.hasGetterMethod(psiField, psiClass); - - // then - assertThat(result).isTrue(); - } - - @Test - void shouldVerifyThatFieldHasNoGetterMethodAvailableIfTheMethodIsPrivate() { - // given - given(psiClass.getAllMethods()).willReturn(methods); - given(method.getModifierList()).willReturn(modifierList); - given(psiField.getName()).willReturn("field"); - given(modifierList.hasExplicitModifier(PsiModifier.PRIVATE)).willReturn(true); - given(method.getName()).willReturn("setField"); - // when - boolean result = psiFieldVerifier.hasGetterMethod(psiField, psiClass); - - // then - assertThat(result).isFalse(); - } - - @Test - void shouldVerifyThatFieldHasNoGetterMethodAvailableIfTheMethodIsNotPrivateButHasIncorrectName() { - // given - given(psiClass.getAllMethods()).willReturn(methods); - given(method.getModifierList()).willReturn(modifierList); - given(psiField.getName()).willReturn("field"); - given(method.getName()).willReturn("getAnotherField"); - // when - boolean result = psiFieldVerifier.hasGetterMethod(psiField, psiClass); - - // then - assertThat(result).isFalse(); - } - - private void prepareBehaviourForReturningParameter() { - given(psiClass.getConstructors()).willReturn(constructors); - given(constructor.getParameterList()).willReturn(parameterList); - given(parameterList.getParameters()).willReturn(parameters); - } -} +package pl.mjedynak.idea.plugins.builder.verifier; + +import static org.apache.commons.lang3.StringUtils.EMPTY; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mock.Strictness.LENIENT; +import static org.mockito.Mockito.mock; +import static org.springframework.test.util.ReflectionTestUtils.setField; + +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiField; +import com.intellij.psi.PsiMethod; +import com.intellij.psi.PsiModifier; +import com.intellij.psi.PsiModifierList; +import com.intellij.psi.PsiParameter; +import com.intellij.psi.PsiParameterList; +import com.intellij.psi.PsiType; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import pl.mjedynak.idea.plugins.builder.settings.CodeStyleSettings; + +@ExtendWith(MockitoExtension.class) +public class PsiFieldVerifierTest { + + private PsiFieldVerifier psiFieldVerifier; + private PsiMethod[] constructors; + private PsiMethod[] methods; + private PsiParameter[] parameters; + + @Mock(strictness = LENIENT) + private PsiField psiField; + + @Mock + private PsiClass psiClass; + + @Mock + private PsiMethod constructor; + + @Mock + private PsiParameterList parameterList; + + @Mock(strictness = LENIENT) + private PsiParameter parameter; + + @Mock + private PsiType psiType; + + @Mock(strictness = LENIENT) + private PsiMethod method; + + @Mock + private PsiModifierList modifierList; + + @Mock(strictness = LENIENT) + private CodeStyleSettings settings; + + private String name; + + @BeforeEach + public void setUp() { + psiFieldVerifier = new PsiFieldVerifier(); + setField(psiFieldVerifier, "codeStyleSettings", settings); + given(settings.getParameterNamePrefix()).willReturn(EMPTY); + given(settings.getFieldNamePrefix()).willReturn(EMPTY); + constructors = new PsiMethod[1]; + constructors[0] = constructor; + methods = new PsiMethod[1]; + methods[0] = method; + parameters = new PsiParameter[1]; + parameters[0] = parameter; + name = "name"; + } + + @Test + void shouldNotVerifyThatFieldIsSetInConstructorIfConstructorDoesNotExist() { + // given + given(psiClass.getConstructors()).willReturn(new PsiMethod[0]); + + // when + boolean result = psiFieldVerifier.isSetInConstructor(psiField, psiClass); + + // then + assertThat(result).isFalse(); + } + + @Test + void shouldNotVerifyThatFieldIsSetInConstructorIfConstructorHasDifferentParameterName() { + // given + prepareBehaviourForReturningParameter(); + given(parameter.getType()).willReturn(psiType); + given(psiField.getType()).willReturn(psiType); + given(parameter.getName()).willReturn(name); + given(psiField.getName()).willReturn("differentName"); + + // when + boolean result = psiFieldVerifier.isSetInConstructor(psiField, psiClass); + + // then + assertThat(result).isFalse(); + } + + @Test + void shouldNotVerifyThatFieldIsSetInConstructorIfConstructorHasDifferentParameterType() { + // given + PsiType differentPsiType = mock(PsiType.class); + prepareBehaviourForReturningParameter(); + given(parameter.getType()).willReturn(psiType); + given(psiField.getType()).willReturn(differentPsiType); + given(parameter.getName()).willReturn(name); + given(psiField.getName()).willReturn(name); + + // when + boolean result = psiFieldVerifier.isSetInConstructor(psiField, psiClass); + + // then + assertThat(result).isFalse(); + } + + @Test + void shouldVerifyThatFieldIsSetInConstructorIfConstructorHasTheSameParameterTypeAndName() { + // given + prepareBehaviourForReturningParameter(); + given(parameter.getType()).willReturn(psiType); + given(psiField.getType()).willReturn(psiType); + given(parameter.getName()).willReturn(name); + given(psiField.getName()).willReturn(name); + + // when + boolean result = psiFieldVerifier.isSetInConstructor(psiField, psiClass); + + // then + assertThat(result).isTrue(); + } + + @Test + void shouldVerifyThatFieldIsSetInSetterMethodIfItIsNotPrivateAndHasCorrectParameter() { + // given + given(psiClass.getAllMethods()).willReturn(methods); + given(method.getModifierList()).willReturn(modifierList); + given(psiField.getName()).willReturn("field"); + given(method.getName()).willReturn("setField"); + + // when + boolean result = psiFieldVerifier.isSetInSetterMethod(psiField, psiClass); + + // then + assertThat(result).isTrue(); + } + + @Test + void shouldVerifyThatFieldIsNotSetInSetterMethodIfItIsPrivate() { + // given + given(psiClass.getAllMethods()).willReturn(methods); + given(method.getModifierList()).willReturn(modifierList); + given(psiField.getName()).willReturn("field"); + given(modifierList.hasExplicitModifier(PsiModifier.PRIVATE)).willReturn(true); + given(method.getName()).willReturn("setField"); + // when + boolean result = psiFieldVerifier.isSetInSetterMethod(psiField, psiClass); + + // then + assertThat(result).isFalse(); + } + + @Test + void shouldVerifyThatFieldIsNotSetInSetterMethodIfItIsNotPrivateButHasIncorrectParameter() { + // given + given(psiClass.getAllMethods()).willReturn(methods); + given(method.getModifierList()).willReturn(modifierList); + given(psiField.getName()).willReturn("field"); + given(method.getName()).willReturn("setAnotherField"); + // when + boolean result = psiFieldVerifier.isSetInSetterMethod(psiField, psiClass); + + // then + assertThat(result).isFalse(); + } + + @Test + void shouldVerifyThatFieldHasGetterMethodAvailableIfTheMethodIsNotPrivateAndHasCorrectName() { + // given + given(psiClass.getAllMethods()).willReturn(methods); + given(method.getModifierList()).willReturn(modifierList); + given(psiField.getName()).willReturn("field"); + given(method.getName()).willReturn("getField"); + + // when + boolean result = psiFieldVerifier.hasGetterMethod(psiField, psiClass); + + // then + assertThat(result).isTrue(); + } + + @Test + void shouldVerifyThatFieldHasNoGetterMethodAvailableIfTheMethodIsPrivate() { + // given + given(psiClass.getAllMethods()).willReturn(methods); + given(method.getModifierList()).willReturn(modifierList); + given(psiField.getName()).willReturn("field"); + given(modifierList.hasExplicitModifier(PsiModifier.PRIVATE)).willReturn(true); + given(method.getName()).willReturn("setField"); + // when + boolean result = psiFieldVerifier.hasGetterMethod(psiField, psiClass); + + // then + assertThat(result).isFalse(); + } + + @Test + void shouldVerifyThatFieldHasNoGetterMethodAvailableIfTheMethodIsNotPrivateButHasIncorrectName() { + // given + given(psiClass.getAllMethods()).willReturn(methods); + given(method.getModifierList()).willReturn(modifierList); + given(psiField.getName()).willReturn("field"); + given(method.getName()).willReturn("getAnotherField"); + // when + boolean result = psiFieldVerifier.hasGetterMethod(psiField, psiClass); + + // then + assertThat(result).isFalse(); + } + + private void prepareBehaviourForReturningParameter() { + given(psiClass.getConstructors()).willReturn(constructors); + given(constructor.getParameterList()).willReturn(parameterList); + given(parameterList.getParameters()).willReturn(parameters); + } +} diff --git a/src/test/java/pl/mjedynak/idea/plugins/builder/writer/BuilderWriterComputableTest.java b/src/test/java/pl/mjedynak/idea/plugins/builder/writer/BuilderWriterComputableTest.java index 5f4c8cd..16535e8 100644 --- a/src/test/java/pl/mjedynak/idea/plugins/builder/writer/BuilderWriterComputableTest.java +++ b/src/test/java/pl/mjedynak/idea/plugins/builder/writer/BuilderWriterComputableTest.java @@ -1,129 +1,129 @@ -package pl.mjedynak.idea.plugins.builder.writer; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mock.Strictness.LENIENT; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.springframework.test.util.ReflectionTestUtils.setField; - -import com.intellij.openapi.application.Application; -import com.intellij.openapi.project.Project; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiFile; -import com.intellij.util.IncorrectOperationException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import pl.mjedynak.idea.plugins.builder.gui.helper.GuiHelper; -import pl.mjedynak.idea.plugins.builder.psi.BuilderPsiClassBuilder; -import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; - -@ExtendWith(MockitoExtension.class) -public class BuilderWriterComputableTest { - - private static final String METHOD_PREFIX = "with"; - - private BuilderWriterComputable builderWriterComputable; - - @Mock - private PsiHelper psiHelper; - - @Mock - private GuiHelper guiHelper; - - @Mock - private BuilderPsiClassBuilder builderPsiClassBuilder; - - @Mock - private Project project; - - @Mock - private PsiClass srcClass; - - @Mock(strictness = LENIENT) - private PsiClass builderClass; - - @Mock - private PsiFile psiFile; - - @Mock - private PsiElement psiElement; - - @Mock(strictness = LENIENT) - private BuilderContext context; - - @Mock - private PsiClass existingBuilder; - - @BeforeEach - public void setUp() { - builderWriterComputable = new BuilderWriterComputable(builderPsiClassBuilder, context, existingBuilder); - given(context.getProject()).willReturn(project); - given(context.getMethodPrefix()).willReturn(METHOD_PREFIX); - given(context.isInner()).willReturn(false); - setField(builderWriterComputable, "psiHelper", psiHelper); - setField(builderWriterComputable, "guiHelper", guiHelper); - } - - @Test - void shouldIncludeCurrentPlaceAsChangePlaceAndNavigateToCreatedBuilder() { - // given - given(builderPsiClassBuilder.aBuilder(context)).willReturn(builderPsiClassBuilder); - mockBuilder(); - - // when - PsiElement result = builderWriterComputable.compute(); - - // then - verify(guiHelper).includeCurrentPlaceAsChangePlace(project); - verify(guiHelper).positionCursor(project, psiFile, psiElement); - assertThat(result).isInstanceOf(PsiClass.class); - assertThat((PsiClass) result).isEqualTo(builderClass); - } - - @Test - void shouldIncludeCurrentPlaceAsChangePlaceAndCreateInnerBuilder() { - // given - given(context.isInner()).willReturn(true); - given(context.getPsiClassFromEditor()).willReturn(srcClass); - given(builderPsiClassBuilder.anInnerBuilder(context)).willReturn(builderPsiClassBuilder); - mockBuilder(); - - // when - PsiElement result = builderWriterComputable.compute(); - - // then - verify(guiHelper).includeCurrentPlaceAsChangePlace(project); - assertThat(result).isInstanceOf(PsiClass.class); - assertThat((PsiClass) result).isEqualTo(builderClass); - } - - @Test - void shouldInvokeBuilderWriterErrorRunnableWhenExceptionOccurs() { - // given - given(builderPsiClassBuilder.aBuilder(context)).willThrow(IncorrectOperationException.class); - Application application = mock(Application.class); - given(psiHelper.getApplication()).willReturn(application); - - // when - builderWriterComputable.compute(); - - // then - verify(application).invokeLater(isA(BuilderWriterErrorRunnable.class)); - } - - private void mockBuilder() { - given(builderPsiClassBuilder.withFields()).willReturn(builderPsiClassBuilder); - given(builderPsiClassBuilder.withConstructor()).willReturn(builderPsiClassBuilder); - given(builderPsiClassBuilder.withInitializingMethod()).willReturn(builderPsiClassBuilder); - given(builderPsiClassBuilder.withSetMethods(METHOD_PREFIX)).willReturn(builderPsiClassBuilder); - given(builderPsiClassBuilder.build()).willReturn(builderClass); - given(builderClass.getContainingFile()).willReturn(psiFile); - given(builderClass.getLBrace()).willReturn(psiElement); - } -} +package pl.mjedynak.idea.plugins.builder.writer; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mock.Strictness.LENIENT; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.springframework.test.util.ReflectionTestUtils.setField; + +import com.intellij.openapi.application.Application; +import com.intellij.openapi.project.Project; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiFile; +import com.intellij.util.IncorrectOperationException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import pl.mjedynak.idea.plugins.builder.gui.helper.GuiHelper; +import pl.mjedynak.idea.plugins.builder.psi.BuilderPsiClassBuilder; +import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; + +@ExtendWith(MockitoExtension.class) +public class BuilderWriterComputableTest { + + private static final String METHOD_PREFIX = "with"; + + private BuilderWriterComputable builderWriterComputable; + + @Mock + private PsiHelper psiHelper; + + @Mock + private GuiHelper guiHelper; + + @Mock + private BuilderPsiClassBuilder builderPsiClassBuilder; + + @Mock + private Project project; + + @Mock + private PsiClass srcClass; + + @Mock(strictness = LENIENT) + private PsiClass builderClass; + + @Mock + private PsiFile psiFile; + + @Mock + private PsiElement psiElement; + + @Mock(strictness = LENIENT) + private BuilderContext context; + + @Mock + private PsiClass existingBuilder; + + @BeforeEach + public void setUp() { + builderWriterComputable = new BuilderWriterComputable(builderPsiClassBuilder, context, existingBuilder); + given(context.getProject()).willReturn(project); + given(context.getMethodPrefix()).willReturn(METHOD_PREFIX); + given(context.isInner()).willReturn(false); + setField(builderWriterComputable, "psiHelper", psiHelper); + setField(builderWriterComputable, "guiHelper", guiHelper); + } + + @Test + void shouldIncludeCurrentPlaceAsChangePlaceAndNavigateToCreatedBuilder() { + // given + given(builderPsiClassBuilder.aBuilder(context)).willReturn(builderPsiClassBuilder); + mockBuilder(); + + // when + PsiElement result = builderWriterComputable.compute(); + + // then + verify(guiHelper).includeCurrentPlaceAsChangePlace(project); + verify(guiHelper).positionCursor(project, psiFile, psiElement); + assertThat(result).isInstanceOf(PsiClass.class); + assertThat((PsiClass) result).isEqualTo(builderClass); + } + + @Test + void shouldIncludeCurrentPlaceAsChangePlaceAndCreateInnerBuilder() { + // given + given(context.isInner()).willReturn(true); + given(context.getPsiClassFromEditor()).willReturn(srcClass); + given(builderPsiClassBuilder.anInnerBuilder(context)).willReturn(builderPsiClassBuilder); + mockBuilder(); + + // when + PsiElement result = builderWriterComputable.compute(); + + // then + verify(guiHelper).includeCurrentPlaceAsChangePlace(project); + assertThat(result).isInstanceOf(PsiClass.class); + assertThat((PsiClass) result).isEqualTo(builderClass); + } + + @Test + void shouldInvokeBuilderWriterErrorRunnableWhenExceptionOccurs() { + // given + given(builderPsiClassBuilder.aBuilder(context)).willThrow(IncorrectOperationException.class); + Application application = mock(Application.class); + given(psiHelper.getApplication()).willReturn(application); + + // when + builderWriterComputable.compute(); + + // then + verify(application).invokeLater(isA(BuilderWriterErrorRunnable.class)); + } + + private void mockBuilder() { + given(builderPsiClassBuilder.withFields()).willReturn(builderPsiClassBuilder); + given(builderPsiClassBuilder.withConstructor()).willReturn(builderPsiClassBuilder); + given(builderPsiClassBuilder.withInitializingMethod()).willReturn(builderPsiClassBuilder); + given(builderPsiClassBuilder.withSetMethods(METHOD_PREFIX)).willReturn(builderPsiClassBuilder); + given(builderPsiClassBuilder.build()).willReturn(builderClass); + given(builderClass.getContainingFile()).willReturn(psiFile); + given(builderClass.getLBrace()).willReturn(psiElement); + } +} diff --git a/src/test/java/pl/mjedynak/idea/plugins/builder/writer/BuilderWriterRunnableTest.java b/src/test/java/pl/mjedynak/idea/plugins/builder/writer/BuilderWriterRunnableTest.java index 7d2d549..1f52070 100644 --- a/src/test/java/pl/mjedynak/idea/plugins/builder/writer/BuilderWriterRunnableTest.java +++ b/src/test/java/pl/mjedynak/idea/plugins/builder/writer/BuilderWriterRunnableTest.java @@ -1,64 +1,64 @@ -package pl.mjedynak.idea.plugins.builder.writer; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.springframework.test.util.ReflectionTestUtils.getField; -import static org.springframework.test.util.ReflectionTestUtils.setField; - -import com.intellij.openapi.application.Application; -import com.intellij.psi.PsiClass; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import pl.mjedynak.idea.plugins.builder.psi.BuilderPsiClassBuilder; -import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; - -@ExtendWith(MockitoExtension.class) -public class BuilderWriterRunnableTest { - - private BuilderWriterRunnable builderWriterRunnable; - - @Mock - private PsiHelper psiHelper; - - @Mock - private BuilderPsiClassBuilder builderPsiClassBuilder; - - @Mock - private BuilderContext context; - - @Mock - private PsiClass existingBuilder; - - @BeforeEach - public void setUp() { - builderWriterRunnable = new BuilderWriterRunnable(builderPsiClassBuilder, context, existingBuilder); - setField(builderWriterRunnable, "psiHelper", psiHelper); - } - - @Test - void shouldRunWriteActionWithBuilderWriterComputable() { - // given - Application application = mock(Application.class); - given(psiHelper.getApplication()).willReturn(application); - - // when - builderWriterRunnable.run(); - - // then - ArgumentCaptor builderWriterComputableArgumentCaptor = - ArgumentCaptor.forClass(BuilderWriterComputable.class); - verify(application).runWriteAction(builderWriterComputableArgumentCaptor.capture()); - assertThat(getField(builderWriterComputableArgumentCaptor.getValue(), "builderPsiClassBuilder")) - .isEqualTo(builderPsiClassBuilder); - assertThat(getField(builderWriterComputableArgumentCaptor.getValue(), "context")) - .isEqualTo(context); - assertThat(getField(builderWriterComputableArgumentCaptor.getValue(), "existingBuilder")) - .isEqualTo(existingBuilder); - } -} +package pl.mjedynak.idea.plugins.builder.writer; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.springframework.test.util.ReflectionTestUtils.getField; +import static org.springframework.test.util.ReflectionTestUtils.setField; + +import com.intellij.openapi.application.Application; +import com.intellij.psi.PsiClass; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import pl.mjedynak.idea.plugins.builder.psi.BuilderPsiClassBuilder; +import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; + +@ExtendWith(MockitoExtension.class) +public class BuilderWriterRunnableTest { + + private BuilderWriterRunnable builderWriterRunnable; + + @Mock + private PsiHelper psiHelper; + + @Mock + private BuilderPsiClassBuilder builderPsiClassBuilder; + + @Mock + private BuilderContext context; + + @Mock + private PsiClass existingBuilder; + + @BeforeEach + public void setUp() { + builderWriterRunnable = new BuilderWriterRunnable(builderPsiClassBuilder, context, existingBuilder); + setField(builderWriterRunnable, "psiHelper", psiHelper); + } + + @Test + void shouldRunWriteActionWithBuilderWriterComputable() { + // given + Application application = mock(Application.class); + given(psiHelper.getApplication()).willReturn(application); + + // when + builderWriterRunnable.run(); + + // then + ArgumentCaptor builderWriterComputableArgumentCaptor = + ArgumentCaptor.forClass(BuilderWriterComputable.class); + verify(application).runWriteAction(builderWriterComputableArgumentCaptor.capture()); + assertThat(getField(builderWriterComputableArgumentCaptor.getValue(), "builderPsiClassBuilder")) + .isEqualTo(builderPsiClassBuilder); + assertThat(getField(builderWriterComputableArgumentCaptor.getValue(), "context")) + .isEqualTo(context); + assertThat(getField(builderWriterComputableArgumentCaptor.getValue(), "existingBuilder")) + .isEqualTo(existingBuilder); + } +} diff --git a/src/test/java/pl/mjedynak/idea/plugins/builder/writer/BuilderWriterTest.java b/src/test/java/pl/mjedynak/idea/plugins/builder/writer/BuilderWriterTest.java index 57637a7..5e9323d 100644 --- a/src/test/java/pl/mjedynak/idea/plugins/builder/writer/BuilderWriterTest.java +++ b/src/test/java/pl/mjedynak/idea/plugins/builder/writer/BuilderWriterTest.java @@ -1,69 +1,69 @@ -package pl.mjedynak.idea.plugins.builder.writer; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.springframework.test.util.ReflectionTestUtils.getField; - -import com.intellij.openapi.command.CommandProcessor; -import com.intellij.openapi.project.Project; -import com.intellij.psi.PsiClass; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.ArgumentCaptor; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import pl.mjedynak.idea.plugins.builder.psi.BuilderPsiClassBuilder; -import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; - -@ExtendWith(MockitoExtension.class) -public class BuilderWriterTest { - - @InjectMocks - private BuilderWriter builderWriter; - - @Mock - private PsiHelper psiHelper; - - @Mock - private BuilderPsiClassBuilder builderPsiClassBuilder; - - @Mock - private BuilderContext context; - - @Mock - private Project project; - - @Mock - private PsiClass existingBuilder; - - @Test - void shouldExecuteCommandWithRunnable() { - // given - CommandProcessor commandProcessor = mock(CommandProcessor.class); - given(psiHelper.getCommandProcessor()).willReturn(commandProcessor); - given(context.getProject()).willReturn(project); - - // when - builderWriter.writeBuilder(context, existingBuilder); - - // then - ArgumentCaptor builderWriterRunnableArgumentCaptor = - ArgumentCaptor.forClass(BuilderWriterRunnable.class); - verify(commandProcessor) - .executeCommand( - eq(project), - builderWriterRunnableArgumentCaptor.capture(), - eq(BuilderWriter.CREATE_BUILDER_STRING), - eq(builderWriter)); - assertThat(getField(builderWriterRunnableArgumentCaptor.getValue(), "builderPsiClassBuilder")) - .isEqualTo(builderPsiClassBuilder); - assertThat(getField(builderWriterRunnableArgumentCaptor.getValue(), "context")) - .isEqualTo(context); - assertThat(getField(builderWriterRunnableArgumentCaptor.getValue(), "existingBuilder")) - .isEqualTo(existingBuilder); - } -} +package pl.mjedynak.idea.plugins.builder.writer; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.springframework.test.util.ReflectionTestUtils.getField; + +import com.intellij.openapi.command.CommandProcessor; +import com.intellij.openapi.project.Project; +import com.intellij.psi.PsiClass; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import pl.mjedynak.idea.plugins.builder.psi.BuilderPsiClassBuilder; +import pl.mjedynak.idea.plugins.builder.psi.PsiHelper; + +@ExtendWith(MockitoExtension.class) +public class BuilderWriterTest { + + @InjectMocks + private BuilderWriter builderWriter; + + @Mock + private PsiHelper psiHelper; + + @Mock + private BuilderPsiClassBuilder builderPsiClassBuilder; + + @Mock + private BuilderContext context; + + @Mock + private Project project; + + @Mock + private PsiClass existingBuilder; + + @Test + void shouldExecuteCommandWithRunnable() { + // given + CommandProcessor commandProcessor = mock(CommandProcessor.class); + given(psiHelper.getCommandProcessor()).willReturn(commandProcessor); + given(context.getProject()).willReturn(project); + + // when + builderWriter.writeBuilder(context, existingBuilder); + + // then + ArgumentCaptor builderWriterRunnableArgumentCaptor = + ArgumentCaptor.forClass(BuilderWriterRunnable.class); + verify(commandProcessor) + .executeCommand( + eq(project), + builderWriterRunnableArgumentCaptor.capture(), + eq(BuilderWriter.CREATE_BUILDER_STRING), + eq(builderWriter)); + assertThat(getField(builderWriterRunnableArgumentCaptor.getValue(), "builderPsiClassBuilder")) + .isEqualTo(builderPsiClassBuilder); + assertThat(getField(builderWriterRunnableArgumentCaptor.getValue(), "context")) + .isEqualTo(context); + assertThat(getField(builderWriterRunnableArgumentCaptor.getValue(), "existingBuilder")) + .isEqualTo(existingBuilder); + } +}