summaryrefslogtreecommitdiff
path: root/plugins/generate-tostring
diff options
context:
space:
mode:
authorJean-Baptiste Queru <jbq@google.com>2013-02-08 15:14:04 -0800
committerJean-Baptiste Queru <jbq@google.com>2013-02-08 15:14:04 -0800
commit9edc8f6b58f71ec510ba36b838f115718d9a174d (patch)
tree06f6df92024fa534ff27e1c0b5fc8b2002848093 /plugins/generate-tostring
parentb56ea2a18f232d79481e778085fd64e8ae486fc3 (diff)
downloadidea-9edc8f6b58f71ec510ba36b838f115718d9a174d.tar.gz
Snapshot of commit 84dc01e773388c2c72a1fc437f313dd5747e7809
from branch master of git://git.jetbrains.org/idea/community.git
Diffstat (limited to 'plugins/generate-tostring')
-rw-r--r--plugins/generate-tostring/generate-tostring.iml3
-rw-r--r--plugins/generate-tostring/resources/inspectionDescriptions/FieldNotUsedInToString.html20
-rw-r--r--plugins/generate-tostring/src/META-INF/plugin.xml4
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/GenerateToStringActionHandler.java17
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/GenerateToStringActionHandlerImpl.java44
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/GenerateToStringConfigurable.java13
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/GenerateToStringUtils.java75
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/GenerateToStringWorker.java152
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/CancelPolicy.java9
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/Config.java42
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/ConflictResolutionPolicy.java6
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/DuplicatePolicy.java11
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/DuplicationPolicy.java (renamed from plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/DuplicatonPolicy.java)7
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/FilterPattern.java141
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/Filterable.java31
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/InsertAfterEqualsHashCodeStrategy.java25
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/InsertAtCaretStrategy.java11
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/InsertLastStrategy.java14
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/InsertNewMethodStrategy.java9
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/PolicyOptions.java16
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/element/ClassElement.java20
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/element/ElementFactory.java86
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/element/ElementUtils.java37
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/element/FieldElement.java50
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/element/MethodElement.java45
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/inspection/AbstractGenerateToStringQuickFix.java44
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/inspection/ClassHasNoToStringMethodInspection.java89
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/inspection/FieldNotUsedInToStringInspection.java304
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/inspection/GenerateToStringQuickFix.java39
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/package.html22
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/psi/PsiAdapter.java315
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/psi/PsiAdapterFactory.java43
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultBuffer.vm27
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultBuilder.vm21
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultConcatMember.vm10
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultConcatMemberSuper.vm10
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultGuava.vm7
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultObjectsToString.vm3
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultToStringBuilder.vm9
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/TemplateResource.java80
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/TemplateResourceLocator.java80
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/util/FileUtil.java62
-rw-r--r--plugins/generate-tostring/src/org/jetbrains/generate/tostring/view/ConfigUI.java105
-rw-r--r--plugins/generate-tostring/testSrc/org/jetbrains/generate/tostring/inspection/FieldNotUsedInToStringInspectionTest.java77
44 files changed, 890 insertions, 1345 deletions
diff --git a/plugins/generate-tostring/generate-tostring.iml b/plugins/generate-tostring/generate-tostring.iml
index 1a5701c2a8c2..501580be8464 100644
--- a/plugins/generate-tostring/generate-tostring.iml
+++ b/plugins/generate-tostring/generate-tostring.iml
@@ -5,6 +5,7 @@
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/resources" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/testSrc" isTestSource="true" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
@@ -14,6 +15,8 @@
<orderEntry type="library" name="Velocity" level="project" />
<orderEntry type="module" module-name="platform-impl" />
<orderEntry type="module" module-name="java-impl" />
+ <orderEntry type="module" module-name="RegExpSupport" />
+ <orderEntry type="module" module-name="testFramework-java" scope="TEST" />
</component>
</module>
diff --git a/plugins/generate-tostring/resources/inspectionDescriptions/FieldNotUsedInToString.html b/plugins/generate-tostring/resources/inspectionDescriptions/FieldNotUsedInToString.html
index 2eb798c9fe4b..cd973915ddab 100644
--- a/plugins/generate-tostring/resources/inspectionDescriptions/FieldNotUsedInToString.html
+++ b/plugins/generate-tostring/resources/inspectionDescriptions/FieldNotUsedInToString.html
@@ -1,14 +1,10 @@
<html>
- <body>
- <table height="170"> <tr height="150"> <td valign="top">
- <font face="verdana" size="-1">
- This inspection reports any fields which are not used in the toString() method of the class. This can be useful to discover
- fields that were added after the toString() method was created and for which the toString() method was not correctly adjusted.
- It is possible to exclude fields from this check in the settings accessible via the Generate > toString() dialog.
- <p>
- This inspection will also check for problems with getter methods if 'enable getters in code generation' is enabled
- in settings.
- </font>
- </td> </tr> </table>
- </body>
+<body>
+Reports any fields which are not used in the <b>toString()</b> method of a class. This can be useful to discover
+fields that were added after the <b>toString()</b> method was created and for which the <b>toString()</b> method was not
+correctly adjusted. It is possible to exclude fields from this check in the settings accessible via the Generate > toString() dialog.
+<p>
+ This inspection will also check for problems with getter methods if 'enable getters in code generation' is enabled
+ in settings.
+</body>
</html> \ No newline at end of file
diff --git a/plugins/generate-tostring/src/META-INF/plugin.xml b/plugins/generate-tostring/src/META-INF/plugin.xml
index d8f159691044..7889a0ff3b36 100644
--- a/plugins/generate-tostring/src/META-INF/plugin.xml
+++ b/plugins/generate-tostring/src/META-INF/plugin.xml
@@ -22,10 +22,10 @@
<applicationService serviceInterface="org.jetbrains.generate.tostring.GenerateToStringContext"
serviceImplementation="org.jetbrains.generate.tostring.GenerateToStringContext"/>
- <localInspection language="JAVA" shortName="ClassHasNoToStringMethod" displayName="Class does not overwrite toString() method"
+ <localInspection language="JAVA" shortName="ClassHasNoToStringMethod" displayName="Class does not override 'toString()' method"
groupName="toString() issues" enabledByDefault="false" level="WARNING"
implementationClass="org.jetbrains.generate.tostring.inspection.ClassHasNoToStringMethodInspection"/>
- <localInspection language="JAVA" shortName="FieldNotUsedInToString" displayName="Field not used in toString() method" groupName="toString() issues"
+ <localInspection language="JAVA" shortName="FieldNotUsedInToString" displayName="Field not used in 'toString()' method" groupName="toString() issues"
enabledByDefault="false" level="WARNING" runForWholeFile="true"
implementationClass="org.jetbrains.generate.tostring.inspection.FieldNotUsedInToStringInspection"/>
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/GenerateToStringActionHandler.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/GenerateToStringActionHandler.java
index c349724e6a16..2e15736ccdee 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/GenerateToStringActionHandler.java
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/GenerateToStringActionHandler.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2001-2007 the original author or authors.
+ * Copyright 2001-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,8 +15,6 @@
*/
package org.jetbrains.generate.tostring;
-import com.intellij.openapi.actionSystem.DataContext;
-import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
@@ -28,22 +26,11 @@ import com.intellij.psi.PsiClass;
public interface GenerateToStringActionHandler {
/**
- * The action that does the actual generation of the code.
- * <p/>
- * This is called automatically by IDEA when user invokes the plugin from the generate menu.
- *
- * @param editor the current editor.
- * @param dataContext the current data context.
- */
- void executeWriteAction(Editor editor, DataContext dataContext);
-
-
- /**
* Action to be executed from quick fix.
*
* @param project the current project.
* @param clazz the class.
*/
- void executeActionQickFix(Project project, PsiClass clazz);
+ void executeActionQuickFix(Project project, PsiClass clazz);
}
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/GenerateToStringActionHandlerImpl.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/GenerateToStringActionHandlerImpl.java
index 58819249bdc8..1fc2b7c4940b 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/GenerateToStringActionHandlerImpl.java
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/GenerateToStringActionHandlerImpl.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2001-2007 the original author or authors.
+ * Copyright 2001-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,7 +32,6 @@ import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.options.TabbedConfigurable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
-import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Disposer;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
@@ -40,8 +39,6 @@ import com.intellij.psi.util.PsiUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.generate.tostring.config.Config;
-import org.jetbrains.generate.tostring.psi.PsiAdapter;
-import org.jetbrains.generate.tostring.psi.PsiAdapterFactory;
import org.jetbrains.generate.tostring.template.TemplateResource;
import org.jetbrains.generate.tostring.template.TemplatesManager;
import org.jetbrains.generate.tostring.view.TemplatesPanel;
@@ -72,7 +69,7 @@ public class GenerateToStringActionHandlerImpl extends EditorWriteActionHandler
}
- public void executeActionQickFix(final Project project, final PsiClass clazz) {
+ public void executeActionQuickFix(final Project project, final PsiClass clazz) {
doExecuteAction(project, clazz, null);
}
@@ -98,9 +95,8 @@ public class GenerateToStringActionHandlerImpl extends EditorWriteActionHandler
final MemberChooserBuilder<PsiElementClassMember> builder = new MemberChooserBuilder<PsiElementClassMember>(project);
final MemberChooserHeaderPanel header = new MemberChooserHeaderPanel(clazz);
builder.setHeaderPanel(header);
- boolean isJdk15Enabled = PsiUtil.isLanguageLevel5OrHigher(clazz);
- builder.overrideAnnotationVisible(isJdk15Enabled);
- builder.setTitle(calcCurrentTitle());
+ builder.overrideAnnotationVisible(PsiUtil.isLanguageLevel5OrHigher(clazz));
+ builder.setTitle("Generate toString()");
logger.debug("Displaying member chooser dialog");
SwingUtilities.invokeLater(new Runnable() {
@@ -122,7 +118,7 @@ public class GenerateToStringActionHandlerImpl extends EditorWriteActionHandler
GenerateToStringWorker.executeGenerateActionLater(clazz, editor, selectedMembers, template, dialog.isInsertOverrideAnnotation());
}
else {
- Messages.showWarningDialog("The template chosen is invalid.", "Broken Template");
+ HintManager.getInstance().showErrorHint(editor, "toString() template '" + template.getFileName() + "' is invalid");
}
}
}
@@ -131,39 +127,23 @@ public class GenerateToStringActionHandlerImpl extends EditorWriteActionHandler
logger.debug("+++ doExecuteAction - END +++");
}
- private static String calcCurrentTitle() {
- final TemplateResource template = TemplatesManager.getInstance().getDefaultTemplate();
-
- if (template.isValidTemplate()) {
- return "Generate " + template.getTargetMethodName();
- }
- else {
- return "Generate";
- }
- }
-
public static void updateDialog(PsiClass clazz, MemberChooser<PsiElementClassMember> dialog) {
- dialog.setTitle(calcCurrentTitle());
-
final PsiElementClassMember[] members = buildMembersToShow(clazz);
dialog.resetElements(members);
dialog.selectElements(members);
}
private static PsiElementClassMember[] buildMembersToShow(PsiClass clazz) {
- Project project = clazz.getProject();
-
- PsiAdapter psi = PsiAdapterFactory.getPsiAdapter();
Config config = GenerateToStringContext.getConfig();
-
- PsiField[] filteredFields = GenerateToStringUtils.filterAvailableFields(project, psi, clazz, config.getFilterPattern());
- if (logger.isDebugEnabled()) logger.debug("Number of fields after filtering: " + filteredFields.length);
+ PsiField[] filteredFields = GenerateToStringUtils.filterAvailableFields(clazz, config.getFilterPattern());
if (logger.isDebugEnabled()) logger.debug("Number of fields after filtering: " + filteredFields.length);
- PsiMethod[] filteredMethods = new PsiMethod[0];
+ PsiMethod[] filteredMethods;
if (config.enableMethods) {
// filter methods as it is enabled from config
- filteredMethods = GenerateToStringUtils.filterAvailableMethods(psi, clazz, config.getFilterPattern());
+ filteredMethods = GenerateToStringUtils.filterAvailableMethods(clazz, config.getFilterPattern());
if (logger.isDebugEnabled()) logger.debug("Number of methods after filtering: " + filteredMethods.length);
+ } else {
+ filteredMethods = PsiMethod.EMPTY_ARRAY;
}
return GenerateToStringUtils.combineToClassMemberList(filteredFields, filteredMethods);
@@ -218,7 +198,7 @@ public class GenerateToStringActionHandlerImpl extends EditorWriteActionHandler
Configurable composite = new TabbedConfigurable(disposable) {
protected List<Configurable> createConfigurables() {
List<Configurable> res = new ArrayList<Configurable>();
- res.add(new GenerateToStringConfigurable());
+ res.add(new GenerateToStringConfigurable(clazz.getProject()));
res.add(ui);
return res;
}
@@ -227,7 +207,7 @@ public class GenerateToStringActionHandlerImpl extends EditorWriteActionHandler
return "toString() Generation Settings";
}
- public String getHelpTopic() {
+ public String getHelpTopic() {
return null; // TODO:
}
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/GenerateToStringConfigurable.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/GenerateToStringConfigurable.java
index 797dda99a641..bee539235d1f 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/GenerateToStringConfigurable.java
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/GenerateToStringConfigurable.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,6 +18,7 @@ package org.jetbrains.generate.tostring;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
+import com.intellij.openapi.project.Project;
import org.jetbrains.generate.tostring.config.Config;
import org.jetbrains.generate.tostring.view.ConfigUI;
@@ -30,6 +31,11 @@ public class GenerateToStringConfigurable implements Configurable {
private static final Logger log = Logger.getInstance("#org.jetbrains.generate.tostring.GenerateToStringConfigurable");
private ConfigUI configUI;
+ private final Project myProject;
+
+ public GenerateToStringConfigurable(Project project) {
+ myProject = project;
+ }
public String getDisplayName() {
return "Settings";
@@ -40,7 +46,7 @@ public class GenerateToStringConfigurable implements Configurable {
}
public JComponent createComponent() {
- return configUI = new ConfigUI(GenerateToStringContext.getConfig());
+ return configUI = new ConfigUI(GenerateToStringContext.getConfig(), myProject);
}
public boolean isModified() {
@@ -49,7 +55,6 @@ public class GenerateToStringConfigurable implements Configurable {
public void apply() throws ConfigurationException {
Config config = configUI.getConfig();
-
GenerateToStringContext.setConfig(config); // update context
if (log.isDebugEnabled()) log.debug("Config updated:\n" + config);
@@ -62,6 +67,4 @@ public class GenerateToStringConfigurable implements Configurable {
public void disposeUIResources() {
configUI = null;
}
-
-
}
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/GenerateToStringUtils.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/GenerateToStringUtils.java
index c74798537cb2..678699373b51 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/GenerateToStringUtils.java
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/GenerateToStringUtils.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2001-2007 the original author or authors.
+ * Copyright 2001-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,10 +22,8 @@ import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.psi.*;
+import org.jetbrains.annotations.NotNull;
import org.jetbrains.generate.tostring.config.FilterPattern;
-import org.jetbrains.generate.tostring.element.ElementFactory;
-import org.jetbrains.generate.tostring.element.FieldElement;
-import org.jetbrains.generate.tostring.element.MethodElement;
import org.jetbrains.generate.tostring.exception.GenerateCodeException;
import org.jetbrains.generate.tostring.exception.PluginException;
import org.jetbrains.generate.tostring.psi.PsiAdapter;
@@ -37,35 +35,28 @@ import java.util.List;
* Utility methods for GenerationToStringAction and the inspections.
*/
public class GenerateToStringUtils {
+
private static final Logger log = Logger.getInstance("#org.jetbrains.generate.tostring.GenerateToStringUtils");
- /**
- * Private constructor.
- */
- private GenerateToStringUtils() {
- }
+ private GenerateToStringUtils() {}
/**
* Filters the list of fields from the class with the given parameters from the {@link org.jetbrains.generate.tostring.config.Config config} settings.
*
- * @param project Project
- * @param psi PSI adapter
* @param clazz the class to filter it's fields
* @param pattern the filter pattern to filter out unwanted fields
- * @return fields avaiable for this action after the filter process.
+ * @return fields available for this action after the filter process.
*/
- public static PsiField[] filterAvailableFields(Project project, PsiAdapter psi, PsiClass clazz, FilterPattern pattern) {
+ @NotNull
+ public static PsiField[] filterAvailableFields(PsiClass clazz, FilterPattern pattern) {
if (log.isDebugEnabled()) log.debug("Filtering fields using the pattern: " + pattern);
List<PsiField> availableFields = new ArrayList<PsiField>();
// performs til filtering process
- PsiField[] fields = clazz.getFields();
+ PsiField[] fields = clazz.getFields();
for (PsiField field : fields) {
- FieldElement fe = ElementFactory.newFieldElement(project, field, psi);
- if (log.isDebugEnabled()) log.debug("Field being filtered: " + fe);
-
- // if the field matches the pattern then it shouldn't be in the list of avaialble fields
- if (!fe.applyFilter(pattern)) {
+ // if the field matches the pattern then it shouldn't be in the list of available fields
+ if (!pattern.fieldMatches(field)) {
availableFields.add(field);
}
}
@@ -81,59 +72,59 @@ public class GenerateToStringUtils {
* <li/>public, non static, non abstract
* <ul/>
*
- * @param psi PSI adapter
+ *
* @param clazz the class to filter it's fields
* @param pattern the filter pattern to filter out unwanted fields
- * @return methods avaiable for this action after the filter process.
+ * @return methods available for this action after the filter process.
*/
- public static PsiMethod[] filterAvailableMethods(PsiAdapter psi, PsiClass clazz, FilterPattern pattern) {
+ @NotNull
+ public static PsiMethod[] filterAvailableMethods(PsiClass clazz, @NotNull FilterPattern pattern) {
if (log.isDebugEnabled()) log.debug("Filtering methods using the pattern: " + pattern);
List<PsiMethod> availableMethods = new ArrayList<PsiMethod>();
- PsiElementFactory elementFactory = JavaPsiFacade.getInstance(clazz.getProject()).getElementFactory();
-
- PsiMethod[] methods = clazz.getMethods();
+ PsiMethod[] methods = clazz.getMethods();
for (PsiMethod method : methods) {
-
- MethodElement me = ElementFactory.newMethodElement(method, elementFactory, psi);
- if (log.isDebugEnabled()) log.debug("Method being filtered: " + me);
-
// the method should be a getter
- if (!me.isGetter()) {
+ if (!PsiAdapter.isGetterMethod(method)) {
continue;
}
// must not return void
- if (me.isReturnTypeVoid()) {
+ final PsiType returnType = method.getReturnType();
+ if (returnType == null || PsiType.VOID.equals(returnType)) {
continue;
}
// method should be public, non static, non abstract
- if (!me.isModifierPublic() || me.isModifierStatic() || me.isModifierAbstract()) {
+ if (!method.hasModifierProperty(PsiModifier.PUBLIC) || method.hasModifierProperty(PsiModifier.STATIC) ||
+ method.hasModifierProperty(PsiModifier.ABSTRACT)) {
continue;
}
// method should not be a getter for an existing field
- if (clazz.findFieldByName(me.getFieldName(), false) != null) {
+ String fieldName = PsiAdapter.getGetterFieldName(method);
+ if (clazz.findFieldByName(fieldName, false) != null) {
continue;
}
// must not be named toString or getClass
- if ("toString".equals(me.getMethodName()) || "getClass".equals(me.getMethodName())) {
+ final String methodName = method.getName();
+ if ("toString".equals(methodName) || "getClass".equals(methodName) || "hashCode".equals(methodName)) {
continue;
}
- // if the method matches the pattern then it shouldn't be in the list of avaialble methods
- if (!me.applyFilter(pattern)) {
- if (log.isDebugEnabled())
- log.debug("Adding the method " + method.getName() + " as there is not a field for this getter");
- availableMethods.add(method);
+ // if the method matches the pattern then it shouldn't be in the list of available methods
+ if (pattern.methodMatches(method)) {
+ continue;
}
- }
+ if (log.isDebugEnabled())
+ log.debug("Adding the method " + methodName + " as there is not a field for this getter");
+ availableMethods.add(method);
+ }
return availableMethods.toArray(new PsiMethod[availableMethods.size()]);
}
- /**
+ /**
* Handles any exception during the executing on this plugin.
*
* @param project PSI project
@@ -144,7 +135,7 @@ public class GenerateToStringUtils {
log.info(e);
if (e instanceof GenerateCodeException) {
- // code generation error - display velocity errror in error dialog so user can identify problem quicker
+ // code generation error - display velocity error in error dialog so user can identify problem quicker
Messages.showMessageDialog(project, "Velocity error generating code - see IDEA log for more details (stacktrace should be in idea.log):\n" + e.getMessage(), "Warning", Messages.getWarningIcon());
} else if (e instanceof PluginException) {
// plugin related error - could be recoverable.
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/GenerateToStringWorker.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/GenerateToStringWorker.java
index d2dd14f394ef..9572a8611855 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/GenerateToStringWorker.java
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/GenerateToStringWorker.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,27 +19,25 @@
*/
package org.jetbrains.generate.tostring;
-import com.intellij.codeInsight.intention.AddAnnotationFix;
import com.intellij.openapi.application.ApplicationManager;
+import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.editor.VisualPosition;
-import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
+import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.util.IncorrectOperationException;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
-import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.generate.tostring.config.*;
import org.jetbrains.generate.tostring.element.*;
import org.jetbrains.generate.tostring.exception.GenerateCodeException;
import org.jetbrains.generate.tostring.psi.PsiAdapter;
-import org.jetbrains.generate.tostring.psi.PsiAdapterFactory;
import org.jetbrains.generate.tostring.template.TemplateResource;
import org.jetbrains.generate.tostring.velocity.VelocityFactory;
import org.jetbrains.generate.tostring.view.MethodExistsDialog;
@@ -50,26 +48,14 @@ import java.util.*;
public class GenerateToStringWorker {
private static final Logger logger = Logger.getInstance("#org.jetbrains.generate.tostring.GenerateToStringWorker");
- private final PsiElementFactory elementFactory;
- private final JVMElementFactory topLevelFactory;
- private final CodeStyleManager codeStyleManager;
private final Editor editor;
- private final PsiFile containingFile;
private final PsiClass clazz;
- private final PsiAdapter psi;
private final Config config;
- private final Project project;
private final boolean hasOverrideAnnotation;
public GenerateToStringWorker(PsiClass clazz, Editor editor, boolean insertAtOverride) {
this.clazz = clazz;
- this.project = clazz.getProject();
- this.psi = PsiAdapterFactory.getPsiAdapter();
this.editor = editor;
- this.elementFactory = JavaPsiFacade.getInstance(project).getElementFactory();
- this.topLevelFactory = JVMElementFactories.getFactory(clazz.getLanguage(), project);
- this.codeStyleManager = CodeStyleManager.getInstance(project);
- this.containingFile = clazz.getContainingFile();
this.config = GenerateToStringContext.getConfig();
this.hasOverrideAnnotation = insertAtOverride;
}
@@ -109,22 +95,22 @@ public class GenerateToStringWorker {
}
/**
- * This method get's the choice if there is an existing <code>toString</code> method.
+ * This method gets the choice if there is an existing <code>toString</code> method.
* <br/> 1) If there is a settings to always override use this.
* <br/> 2) Prompt a dialog and let the user decide.
*
- * @param template the choosen template to use
+ * @param template the chosen template to use
* @return the policy the user selected (never null)
*/
private ConflictResolutionPolicy exitsMethodDialog(TemplateResource template) {
- final DuplicatonPolicy dupPolicy = config.getReplaceDialogInitialOption();
- if (dupPolicy == DuplicatonPolicy.ASK) {
- PsiMethod existingMethod = psi.findMethodByName(clazz, template.getTargetMethodName());
+ final DuplicationPolicy dupPolicy = config.getReplaceDialogInitialOption();
+ if (dupPolicy == DuplicationPolicy.ASK) {
+ PsiMethod existingMethod = PsiAdapter.findMethodByName(clazz, template.getTargetMethodName());
if (existingMethod != null) {
return MethodExistsDialog.showDialog(template.getTargetMethodName());
}
}
- else if (dupPolicy == DuplicatonPolicy.REPLACE) {
+ else if (dupPolicy == DuplicationPolicy.REPLACE) {
return ReplacePolicy.getInstance();
}
@@ -139,7 +125,7 @@ public class GenerateToStringWorker {
* @param template the template to use
*/
private void beforeCreateToStringMethod(Map<String, String> params, TemplateResource template) {
- PsiMethod existingMethod = psi.findMethodByName(clazz, template.getTargetMethodName()); // find the existing method
+ PsiMethod existingMethod = PsiAdapter.findMethodByName(clazz, template.getTargetMethodName()); // find the existing method
if (existingMethod != null && existingMethod.getDocComment() != null) {
PsiDocComment doc = existingMethod.getDocComment();
if (doc != null) {
@@ -172,8 +158,9 @@ public class GenerateToStringWorker {
body = StringUtil.convertLineSeparators(body);
// create psi newMethod named toString()
- PsiMethod newMethod = topLevelFactory.createMethodFromText(template.getMethodSignature() + " { " + body + " }", null);
- codeStyleManager.reformat(newMethod);
+ final JVMElementFactory topLevelFactory = JVMElementFactories.getFactory(clazz.getLanguage(), clazz.getProject());
+ PsiMethod newMethod = topLevelFactory.createMethodFromText(template.getMethodSignature() + " { " + body + " }", clazz);
+ CodeStyleManager.getInstance(clazz.getProject()).reformat(newMethod);
// insertNewMethod conflict resolution policy (add/replace, duplicate, cancel)
PsiMethod existingMethod = clazz.findMethodBySignature(newMethod, false);
@@ -183,17 +170,7 @@ public class GenerateToStringWorker {
}
if (hasOverrideAnnotation) {
- annotate(toStringMethod, "java.lang.Override");
- }
-
- // add annotations
- if (template.hasAnnotations()) {
- String[] annotations = template.getAnnotations();
- // must reverse loop to add annotations in the same order as in the template (when inserting it would insert in top)
- for (int i = annotations.length - 1; i > -1; i--) {
- String text = annotations[i];
- psi.addAnnotationToMethod(topLevelFactory, toStringMethod, text);
- }
+ toStringMethod.getModifierList().addAnnotation("java.lang.Override");
}
// applyJavaDoc conflict resolution policy (add or keep existing)
@@ -204,20 +181,16 @@ public class GenerateToStringWorker {
newJavaDoc = velocityGenerateCode(selectedMembers, params, newJavaDoc);
if (logger.isDebugEnabled()) logger.debug("JavaDoc body generated from Velocity:\n" + newJavaDoc);
- applyJavaDoc(toStringMethod, elementFactory, codeStyleManager, existingJavaDoc, newJavaDoc);
+ applyJavaDoc(toStringMethod, existingJavaDoc, newJavaDoc);
}
// return the created method
return toStringMethod;
}
- private void applyJavaDoc(PsiMethod newMethod,
- PsiElementFactory elementFactory,
- CodeStyleManager codeStyleManager,
- String existingJavaDoc,
- String newJavaDoc) throws IncorrectOperationException {
+ private static void applyJavaDoc(PsiMethod newMethod, String existingJavaDoc, String newJavaDoc) {
String text = newJavaDoc != null ? newJavaDoc : existingJavaDoc; // prefer to use new javadoc
- psi.addOrReplaceJavadoc(elementFactory, codeStyleManager, newMethod, text, true);
+ PsiAdapter.addOrReplaceJavadoc(newMethod, text, true);
}
@@ -229,62 +202,43 @@ public class GenerateToStringWorker {
* @param template the template to use
* @throws IncorrectOperationException is thrown by IDEA
*/
- private void afterCreateToStringMethod(PsiMethod method, Map<String, String> params, TemplateResource template)
- throws IncorrectOperationException {
-
+ private void afterCreateToStringMethod(PsiMethod method, Map<String, String> params, TemplateResource template) {
+ PsiFile containingFile = clazz.getContainingFile();
if (containingFile instanceof PsiJavaFile) {
final PsiJavaFile javaFile = (PsiJavaFile)containingFile;
- // if the code uses Arrays, then make sure java.util.Arrays is imported.
- String javaCode = method.getText();
- if (javaCode.indexOf("Arrays.") > 0 &&
- !(psi.hasImportStatement(javaFile, "java.util.*") || psi.hasImportStatement(javaFile, "java.util.Arrays"))) {
- // java.util.Arrays must be imported as java.util.* since the addImportStatement method doens't support onDemand-import statement yet.
- psi.addImportStatement(javaFile, "java.util.*", elementFactory);
- }
-
- // if the code uses Reflection (Field[]), then make sure java.lang.reflect.Field is imported.
- if (javaCode.indexOf("Field[]") > 0 &&
- !(psi.hasImportStatement(javaFile, "java.lang.reflect.*") || psi.hasImportStatement(javaFile, "java.lang.reflect.Field"))) {
- // java.lang.reflect.Field must be imported as java.lang.reflect.* since the addImportStatement method doens't support onDemand-import statement yet.
- psi.addImportStatement(javaFile, "java.lang.reflect.*", elementFactory);
- }
-
- // any additional packages to import from the params
if (params.get("autoImportPackages") != null) {
+ // keep this for old user templates
autoImportPackages(javaFile, params.get("autoImportPackages"));
}
+ method = (PsiMethod)JavaCodeStyleManager.getInstance(clazz.getProject()).shortenClassReferences(method);
}
- // reformat code
- codeStyleManager.reformat(method);
-
// jump to method
- if (config.isJumpToMethod() && editor != null) {
- PsiMethod newMethod = psi.findMethodByName(clazz, template.getTargetMethodName());
- if (newMethod != null) {
- int offset = newMethod.getTextOffset();
- if (offset > 2) {
- VisualPosition vp = editor.offsetToVisualPosition(offset);
- if (logger.isDebugEnabled()) logger.debug("Moving/Scrolling caret to " + vp + " (offset=" + offset + ")");
- editor.getCaretModel().moveToVisualPosition(vp);
- editor.getScrollingModel().scrollToCaret(ScrollType.CENTER_DOWN);
- }
- }
+ if (!config.isJumpToMethod() || editor == null) {
+ return;
+ }
+ int offset = method.getTextOffset();
+ if (offset <= 2) {
+ return;
}
+ VisualPosition vp = editor.offsetToVisualPosition(offset);
+ if (logger.isDebugEnabled()) logger.debug("Moving/Scrolling caret to " + vp + " (offset=" + offset + ")");
+ editor.getCaretModel().moveToVisualPosition(vp);
+ editor.getScrollingModel().scrollToCaret(ScrollType.CENTER_DOWN);
}
/**
* Automatic import the packages.
*
- * @param packageNames names of packages (must end with .* and be seperated by ; or ,)
+ * @param packageNames names of packages (must end with .* and be separated by ; or ,)
* @throws IncorrectOperationException error adding imported package
*/
- private void autoImportPackages(PsiJavaFile psiJavaFile, String packageNames) throws IncorrectOperationException {
+ private static void autoImportPackages(PsiJavaFile psiJavaFile, String packageNames) throws IncorrectOperationException {
StringTokenizer tok = new StringTokenizer(packageNames, ",");
while (tok.hasMoreTokens()) {
String packageName = tok.nextToken().trim(); // trim in case of space
if (logger.isDebugEnabled()) logger.debug("Auto importing package: " + packageName);
- psi.addImportStatement(psiJavaFile, packageName, elementFactory);
+ PsiAdapter.addImportStatement(psiJavaFile, packageName);
}
}
@@ -295,7 +249,7 @@ public class GenerateToStringWorker {
*
* @param selectedMembers the selected members as both {@link com.intellij.psi.PsiField} and {@link com.intellij.psi.PsiMethod}.
* @param params additional parameters stored with key/value in the map.
- * @param templateMacro the veloicty macro template
+ * @param templateMacro the velocity macro template
* @return code (usually javacode). Returns null if templateMacro is null.
* @throws GenerateCodeException is thrown when there is an error generating the javacode.
*/
@@ -309,17 +263,19 @@ public class GenerateToStringWorker {
try {
VelocityContext vc = new VelocityContext();
+ vc.put("java_version", PsiAdapter.getJavaVersion(clazz));
+
// field information
logger.debug("Velocity Context - adding fields");
- vc.put("fields", ElementUtils.getOnlyAsFieldElements(project, psi, selectedMembers));
+ vc.put("fields", ElementUtils.getOnlyAsFieldElements(selectedMembers));
// method information
logger.debug("Velocity Context - adding methods");
- vc.put("methods", ElementUtils.getOnlyAsMethodElements(elementFactory, psi, selectedMembers));
+ vc.put("methods", ElementUtils.getOnlyAsMethodElements(selectedMembers));
// element information (both fields and methods)
logger.debug("Velocity Context - adding members (fields and methods)");
- List<Element> elements = ElementUtils.getOnlyAsFieldAndMethodElements(project, elementFactory, psi, selectedMembers);
+ List<Element> elements = ElementUtils.getOnlyAsFieldAndMethodElements(selectedMembers);
// sort elements if enabled and not using chooser dialog
if (config.getSortElements() != 0) {
Collections.sort(elements, new ElementComparator(config.getSortElements()));
@@ -327,11 +283,11 @@ public class GenerateToStringWorker {
vc.put("members", elements);
// class information
- ClassElement ce = ElementFactory.newClassElement(project, clazz, psi);
+ ClassElement ce = ElementFactory.newClassElement(clazz);
vc.put("class", ce);
if (logger.isDebugEnabled()) logger.debug("Velocity Context - adding class: " + ce);
- // information to keep as it is to avoid breaking compability with prior releases
+ // information to keep as it is to avoid breaking compatibility with prior releases
vc.put("classname", config.isUseFullyQualifiedName() ? ce.getQualifiedName() : ce.getName());
vc.put("FQClassname", ce.getQualifiedName());
@@ -347,12 +303,6 @@ public class GenerateToStringWorker {
if (vc.get("autoImportPackages") != null) {
params.put("autoImportPackages", (String)vc.get("autoImportPackages"));
}
-
- // add java.io.Serializable if choosen in [settings] and does not already implements it
- if (config.isAddImplementSerializable() && !ce.isImplements("java.io.Serializable")) {
- psi.addImplements(project, clazz, "java.io.Serializable");
- }
-
}
catch (Exception e) {
throw new GenerateCodeException("Error in Velocity code generator", e);
@@ -365,13 +315,13 @@ public class GenerateToStringWorker {
* Generates the toString() code for the specified class and selected
* fields, doing the work through a WriteAction ran by a CommandProcessor.
*
- * @param selectedMemebers list of members selected
- * @param template the choosen template to use
+ * @param selectedMembers list of members selected
+ * @param template the chosen template to use
* @param insertAtOverride
*/
public static void executeGenerateActionLater(final PsiClass clazz,
final Editor editor,
- final Collection<PsiMember> selectedMemebers,
+ final Collection<PsiMember> selectedMembers,
final TemplateResource template,
final boolean insertAtOverride) {
Runnable writeCommand = new Runnable() {
@@ -379,7 +329,7 @@ public class GenerateToStringWorker {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
try {
- new GenerateToStringWorker(clazz, editor, insertAtOverride).execute(selectedMemebers, template);
+ new GenerateToStringWorker(clazz, editor, insertAtOverride).execute(selectedMembers, template);
}
catch (Exception e) {
GenerateToStringUtils.handleException(clazz.getProject(), e);
@@ -389,14 +339,6 @@ public class GenerateToStringWorker {
}
};
- PsiAdapterFactory.getPsiAdapter().executeCommand(clazz.getProject(), writeCommand);
- }
-
- private static void annotate(@NotNull PsiMethod result, String fqn) throws IncorrectOperationException {
- Project project = result.getProject();
- AddAnnotationFix fix = new AddAnnotationFix(fqn, result);
- if (fix.isAvailable(project, null, result.getContainingFile())) {
- fix.invoke(project, null, result.getContainingFile());
- }
+ CommandProcessor.getInstance().executeCommand(clazz.getProject(), writeCommand, "GenerateToString", null);
}
}
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/CancelPolicy.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/CancelPolicy.java
index a20ec7c084d2..a45f7b7bcbb9 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/CancelPolicy.java
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/CancelPolicy.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2001-2007 the original author or authors.
+ * Copyright 2001-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,8 +28,7 @@ public class CancelPolicy implements ConflictResolutionPolicy {
private static final CancelPolicy instance = new CancelPolicy();
- private CancelPolicy() {
- }
+ private CancelPolicy() {}
public static CancelPolicy getInstance() {
return instance;
@@ -39,13 +38,11 @@ public class CancelPolicy implements ConflictResolutionPolicy {
// not used as this is cancel
}
- public PsiMethod applyMethod(PsiClass clazz, PsiMethod existingMethod, @NotNull PsiMethod newMethod, Editor editor) throws IncorrectOperationException {
+ public PsiMethod applyMethod(PsiClass clazz, PsiMethod existingMethod, @NotNull PsiMethod newMethod, Editor editor) {
return null;
}
public String toString() {
return "Cancel";
}
-
-
}
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/Config.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/Config.java
index 8d11c87f357b..facdfa526150 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/Config.java
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/Config.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2001-2007 the original author or authors.
+ * Copyright 2001-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,8 +16,6 @@
package org.jetbrains.generate.tostring.config;
/**
- * Configuration.
- * <p/>
* The configuration is stored standard xmlb.XmlSerializer that automatically stores the
* state of this classes public fields.
*/
@@ -25,7 +23,7 @@ public class Config {
public boolean useFullyQualifiedName = false;
public InsertWhere insertNewMethodOption = InsertWhere.AT_CARET;
- public DuplicatonPolicy whenDuplicatesOption = DuplicatonPolicy.ASK;
+ public DuplicationPolicy whenDuplicatesOption = DuplicationPolicy.ASK;
public boolean filterConstantField = true;
public boolean filterEnumField = false;
public boolean filterTransientModifier = false;
@@ -40,6 +38,8 @@ public class Config {
public boolean jumpToMethod = true; // jump cursor to toString method
public int sortElements = 0; // 0 = none, 1 = asc, 2 = desc
+ private FilterPattern myPattern = null;
+
public boolean isUseFullyQualifiedName() {
return useFullyQualifiedName;
}
@@ -48,11 +48,11 @@ public class Config {
this.useFullyQualifiedName = useFullyQualifiedName;
}
- public DuplicatonPolicy getReplaceDialogInitialOption() {
+ public DuplicationPolicy getReplaceDialogInitialOption() {
return whenDuplicatesOption;
}
- public void setReplaceDialogInitialOption(DuplicatonPolicy option) {
+ public void setReplaceDialogInitialOption(DuplicationPolicy option) {
this.whenDuplicatesOption = option;
}
@@ -89,6 +89,9 @@ public class Config {
}
public String getFilterFieldName() {
+ if (filterFieldName == null) {
+ return "";
+ }
return filterFieldName;
}
@@ -96,14 +99,6 @@ public class Config {
this.filterFieldName = filterFieldName;
}
- public boolean isAddImplementSerializable() {
- return addImplementSerializable;
- }
-
- public void setAddImplementSerializable(boolean addImplementSerializable) {
- this.addImplementSerializable = addImplementSerializable;
- }
-
public boolean isEnableMethods() {
return enableMethods;
}
@@ -113,6 +108,9 @@ public class Config {
}
public String getFilterMethodName() {
+ if (filterMethodName == null) {
+ return "";
+ }
return filterMethodName;
}
@@ -145,6 +143,9 @@ public class Config {
}
public String getFilterFieldType() {
+ if (filterFieldType == null) {
+ return "";
+ }
return filterFieldType;
}
@@ -161,6 +162,9 @@ public class Config {
}
public String getFilterMethodType() {
+ if (filterMethodType == null) {
+ return "";
+ }
return filterMethodType;
}
@@ -169,12 +173,16 @@ public class Config {
}
/**
- * Get's the filter pattern that this configuration represent.
+ * Gets the filter pattern that this configuration represents.
*
* @return the filter pattern.
*/
public FilterPattern getFilterPattern() {
- FilterPattern pattern = new FilterPattern();
+ FilterPattern pattern = myPattern;
+ if (pattern != null) {
+ return pattern;
+ }
+ pattern = new FilterPattern();
pattern.setConstantField(filterConstantField);
pattern.setTransientModifier(filterTransientModifier);
pattern.setStaticModifier(filterStaticModifier);
@@ -184,7 +192,7 @@ public class Config {
pattern.setMethodType(filterMethodType);
pattern.setEnumField(filterEnumField);
pattern.setLoggers(filterLoggers);
- return pattern;
+ return myPattern = pattern;
}
public boolean equals(Object o) {
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/ConflictResolutionPolicy.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/ConflictResolutionPolicy.java
index 29afdd54f710..c726b88e8e2f 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/ConflictResolutionPolicy.java
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/ConflictResolutionPolicy.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2001-2007 the original author or authors.
+ * Copyright 2001-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -38,7 +38,7 @@ public interface ConflictResolutionPolicy {
void setNewMethodStrategy(InsertNewMethodStrategy strategy);
/**
- * Applies the choosen policy.
+ * Applies the chosen policy.
*
* @param clazz PSIClass.
* @param existingMethod existing method if one exists.
@@ -48,5 +48,5 @@ public interface ConflictResolutionPolicy {
* @throws IncorrectOperationException is thrown if there is an IDEA error.
*/
@Nullable
- PsiMethod applyMethod(PsiClass clazz, PsiMethod existingMethod, @NotNull PsiMethod newMethod, Editor editor) throws IncorrectOperationException;
+ PsiMethod applyMethod(PsiClass clazz, PsiMethod existingMethod, @NotNull PsiMethod newMethod, Editor editor);
}
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/DuplicatePolicy.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/DuplicatePolicy.java
index 65d65b00279c..5de932ede689 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/DuplicatePolicy.java
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/DuplicatePolicy.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2001-2007 the original author or authors.
+ * Copyright 2001-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,10 +27,9 @@ import org.jetbrains.annotations.NotNull;
public class DuplicatePolicy implements ConflictResolutionPolicy {
private static final DuplicatePolicy instance = new DuplicatePolicy();
- private static InsertNewMethodStrategy newMethodStrategy = InsertAtCaretStrategy.getInstance();
+ private InsertNewMethodStrategy newMethodStrategy = InsertAtCaretStrategy.getInstance();
- private DuplicatePolicy() {
- }
+ private DuplicatePolicy() {}
public static DuplicatePolicy getInstance() {
return instance;
@@ -40,13 +39,11 @@ public class DuplicatePolicy implements ConflictResolutionPolicy {
newMethodStrategy = strategy;
}
- public PsiMethod applyMethod(PsiClass clazz, PsiMethod existingMethod, @NotNull PsiMethod newMethod, Editor editor)
- throws IncorrectOperationException {
+ public PsiMethod applyMethod(PsiClass clazz, PsiMethod existingMethod, @NotNull PsiMethod newMethod, Editor editor) {
return newMethodStrategy.insertNewMethod(clazz, newMethod, editor);
}
public String toString() {
return "Duplicate";
}
-
}
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/DuplicatonPolicy.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/DuplicationPolicy.java
index 4e771629c9a8..3d0171344cc4 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/DuplicatonPolicy.java
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/DuplicationPolicy.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,18 +19,17 @@
*/
package org.jetbrains.generate.tostring.config;
-public enum DuplicatonPolicy {
+public enum DuplicationPolicy {
ASK("Ask"),
REPLACE("Replace existing"),
DUPLICATE("Generate duplicating method");
private final String displayName;
- DuplicatonPolicy(String displayName) {
+ DuplicationPolicy(String displayName) {
this.displayName = displayName;
}
-
@Override
public String toString() {
return displayName;
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/FilterPattern.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/FilterPattern.java
index 7fe374c85b2e..a1cbe9761861 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/FilterPattern.java
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/FilterPattern.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2001-2007 the original author or authors.
+ * Copyright 2001-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,11 +15,33 @@
*/
package org.jetbrains.generate.tostring.config;
+import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.psi.PsiField;
+import com.intellij.psi.PsiMethod;
+import com.intellij.psi.PsiModifier;
+import com.intellij.psi.PsiType;
+import gnu.trove.THashSet;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.generate.tostring.psi.PsiAdapter;
+
+import java.util.Collections;
+import java.util.Set;
+import java.util.regex.Pattern;
+import java.util.regex.PatternSyntaxException;
+
/**
* This is a filtering pattern, used to filter unwanted fields for this action.
*/
public class FilterPattern {
+ private static final Logger LOG = Logger.getInstance("#org.jetbrains.generate.tostring.config.FilterPattern");
+ private static final Set<String> loggerNames = new THashSet<String>();
+ static {
+ Collections.addAll(loggerNames,
+ "org.apache.log4j.Logger", "java.util.logging.Logger", "org.apache.commons.logging.Log", "org.slf4j.Logger");
+ }
+
private String fieldName;
private String fieldType;
private String methodName;
@@ -29,13 +51,71 @@ public class FilterPattern {
private boolean transientModifier;
private boolean enumField;
private boolean loggers;
+ private Pattern methodNamePattern = null;
+ private Pattern methodTypePattern = null;
+ private Pattern fieldNamePattern = null;
+ private Pattern fieldTypePattern = null;
- public String getFieldName() {
- return fieldName;
+ public boolean fieldMatches(PsiField field) {
+ if (isConstantField() && PsiAdapter.isConstantField(field)) {
+ return true;
+ }
+ if (isEnumField() && PsiAdapter.isEnumField(field)) {
+ return true;
+ }
+ if (isStaticModifier() && field.hasModifierProperty(PsiModifier.STATIC)) {
+ return true;
+ }
+ if (isTransientModifier() && field.hasModifierProperty(PsiModifier.TRANSIENT)) {
+ return true;
+ }
+ final Pattern fieldNamePattern = getFieldNamePattern();
+ if ((fieldNamePattern != null) && fieldNamePattern.matcher(field.getName()).matches()) {
+ return true;
+ }
+ final String typeText = field.getType().getCanonicalText();
+ final Pattern fieldTypePattern = getFieldTypePattern();
+ if ((fieldTypePattern != null) && fieldTypePattern.matcher(typeText).matches()) {
+ return true;
+ }
+ if (isLoggers() && loggerNames.contains(typeText)) {
+ return true;
+ }
+ return false;
+ }
+
+ public boolean methodMatches(@NotNull PsiMethod method) {
+ final String methodName = method.getName();
+ final Pattern methodNamePattern = getMethodNamePattern();
+ if ((methodNamePattern != null) && methodNamePattern.matcher(methodName).matches()) {
+ return true;
+ }
+ final PsiType returnType = method.getReturnType();
+ if (returnType == null) {
+ return false;
+ }
+ final Pattern patternTypePattern = getMethodTypePattern();
+ final String methodType = returnType.getCanonicalText();
+ return (patternTypePattern != null) && methodTypePattern.matcher(methodType).matches();
+ }
+
+ public Pattern getFieldNamePattern() {
+ if (StringUtil.isEmpty(fieldName)) {
+ return null;
+ }
+ if (fieldNamePattern == null) {
+ try {
+ fieldNamePattern = Pattern.compile(fieldName);
+ } catch (PatternSyntaxException e) {
+ fieldName = null;
+ LOG.warn(e.getMessage());
+ }
+ }
+ return fieldNamePattern;
}
/**
- * Set's a filtering using regular expression on the field name.
+ * Sets a filtering using regular expression on the field name.
*
* @param regexp the regular expression.
*/
@@ -82,12 +162,23 @@ public class FilterPattern {
this.staticModifier = staticModifier;
}
- public String getMethodName() {
- return methodName;
+ public Pattern getMethodNamePattern() {
+ if (StringUtil.isEmpty(methodName)) {
+ return null;
+ }
+ if (methodNamePattern == null) {
+ try {
+ methodNamePattern = Pattern.compile(methodName);
+ } catch (PatternSyntaxException e) {
+ methodName = null;
+ LOG.warn(e.getMessage());
+ }
+ }
+ return methodNamePattern;
}
/**
- * Set's a filtering using regular expression on the method name.
+ * Sets a filtering using regular expression on the method name.
*
* @param regexp the regular expression.
*/
@@ -123,12 +214,23 @@ public class FilterPattern {
this.loggers = loggers;
}
- public String getFieldType() {
- return fieldType;
+ public Pattern getFieldTypePattern() {
+ if (StringUtil.isEmpty(fieldType)) {
+ return null;
+ }
+ if (fieldTypePattern == null) {
+ try {
+ fieldTypePattern = Pattern.compile(fieldType);
+ } catch (PatternSyntaxException e) {
+ fieldType = null;
+ LOG.warn(e.getMessage());
+ }
+ }
+ return fieldTypePattern;
}
/**
- * Set's a filtering using the field type FQN.
+ * Sets a filtering using the field type FQN.
*
* @param fieldType the field type
* @since 3.20
@@ -137,12 +239,23 @@ public class FilterPattern {
this.fieldType = fieldType;
}
- public String getMethodType() {
- return methodType;
+ public Pattern getMethodTypePattern() {
+ if (StringUtil.isEmpty(methodType)) {
+ return null;
+ }
+ if (methodTypePattern == null) {
+ try {
+ methodTypePattern = Pattern.compile(methodType);
+ } catch (PatternSyntaxException e) {
+ methodType = null;
+ LOG.warn(e.getMessage());
+ }
+ }
+ return methodTypePattern;
}
/**
- * Set's a filtering using the method return type FQN.
+ * Sets a filtering using the method return type FQN.
*
* @param methodType the method return type
* @since 3.20
@@ -164,6 +277,4 @@ public class FilterPattern {
", loggers=" + loggers +
"}";
}
-
-
}
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/Filterable.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/Filterable.java
deleted file mode 100644
index ef540f837326..000000000000
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/Filterable.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright 2001-2007 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.jetbrains.generate.tostring.config;
-
-/**
- * Gives the ability to perform a matching agaist a class field to be used in a filtering process for unwanted fields.
- */
-public interface Filterable {
-
- /**
- * Performs the filter process and returns true if the field matches the filtering patterns.
- *
- * @param pattern filter patterns.
- * @return true if the field matches the patterns.
- */
- boolean applyFilter(FilterPattern pattern);
-
-} \ No newline at end of file
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/InsertAfterEqualsHashCodeStrategy.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/InsertAfterEqualsHashCodeStrategy.java
index c5841b41934a..d9757947531a 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/InsertAfterEqualsHashCodeStrategy.java
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/InsertAfterEqualsHashCodeStrategy.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2001-2007 the original author or authors.
+ * Copyright 2001-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,10 +18,8 @@ package org.jetbrains.generate.tostring.config;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiMethod;
-import com.intellij.util.IncorrectOperationException;
-import org.jetbrains.generate.tostring.psi.PsiAdapter;
-import org.jetbrains.generate.tostring.psi.PsiAdapterFactory;
import org.jetbrains.annotations.NotNull;
+import org.jetbrains.generate.tostring.psi.PsiAdapter;
/**
* Inserts the method after the hashCode/equals methods in the javafile.
@@ -29,26 +27,18 @@ import org.jetbrains.annotations.NotNull;
public class InsertAfterEqualsHashCodeStrategy implements InsertNewMethodStrategy {
private static final InsertAfterEqualsHashCodeStrategy instance = new InsertAfterEqualsHashCodeStrategy();
- private static PsiAdapter psi;
- private InsertAfterEqualsHashCodeStrategy() {
- }
+ private InsertAfterEqualsHashCodeStrategy() {}
public static InsertAfterEqualsHashCodeStrategy getInstance() {
return instance;
}
- public PsiMethod insertNewMethod(PsiClass clazz, @NotNull PsiMethod newMethod, Editor editor) throws IncorrectOperationException {
- // lazy initialize otherwise IDEA throws error: Component requests are not allowed before they are created
- if (psi == null) {
- psi = PsiAdapterFactory.getPsiAdapter();
- }
-
- // if main method exists and is the last then add toString just before main method
- PsiMethod methodHashCode = psi.findHashCodeMethod(clazz);
- PsiMethod methodEquals = psi.findEqualsMethod(clazz);
+ public PsiMethod insertNewMethod(PsiClass clazz, @NotNull PsiMethod newMethod, Editor editor) {
+ PsiMethod methodHashCode = PsiAdapter.findHashCodeMethod(clazz);
+ PsiMethod methodEquals = PsiAdapter.findEqualsMethod(clazz);
- // if both methos exist determine the last method in the javafile
+ // if both methods exist determine the last method in the javafile
PsiMethod method;
if (methodEquals != null && methodHashCode != null) {
if (methodEquals.getTextOffset() > methodHashCode.getTextOffset()) {
@@ -74,5 +64,4 @@ public class InsertAfterEqualsHashCodeStrategy implements InsertNewMethodStrateg
public String toString() {
return "After equals/hashCode";
}
-
}
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/InsertAtCaretStrategy.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/InsertAtCaretStrategy.java
index 6d9770865a90..f41c60196921 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/InsertAtCaretStrategy.java
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/InsertAtCaretStrategy.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2001-2007 the original author or authors.
+ * Copyright 2001-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,16 +33,15 @@ public class InsertAtCaretStrategy implements InsertNewMethodStrategy {
private static final InsertAtCaretStrategy instance = new InsertAtCaretStrategy();
- private InsertAtCaretStrategy() {
- }
+ private InsertAtCaretStrategy() {}
public static InsertAtCaretStrategy getInstance() {
return instance;
}
- public PsiMethod insertNewMethod(PsiClass clazz, @NotNull PsiMethod newMethod, Editor editor) throws IncorrectOperationException {
- int offset = editor != null ? editor.getCaretModel().getOffset() : clazz.getTextRange().getEndOffset() - 1;
- final PsiGenerationInfo<PsiMethod> generationInfo = OverrideImplementUtil.createGenerationInfo(newMethod, false);
+ public PsiMethod insertNewMethod(PsiClass clazz, @NotNull PsiMethod newMethod, Editor editor) {
+ int offset = (editor != null) ? editor.getCaretModel().getOffset() : (clazz.getTextRange().getEndOffset() - 1);
+ final PsiGenerationInfo<PsiMethod> generationInfo = new PsiGenerationInfo<PsiMethod>(newMethod, false);
GenerateMembersUtil.insertMembersAtOffset(clazz.getContainingFile(), offset, Arrays.asList(generationInfo));
return generationInfo.getPsiMember();
}
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/InsertLastStrategy.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/InsertLastStrategy.java
index cc6b969b914c..24c8461273a3 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/InsertLastStrategy.java
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/InsertLastStrategy.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2001-2007 the original author or authors.
+ * Copyright 2001-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,9 +20,8 @@ import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMethod;
import com.intellij.util.IncorrectOperationException;
-import org.jetbrains.generate.tostring.psi.PsiAdapter;
-import org.jetbrains.generate.tostring.psi.PsiAdapterFactory;
import org.jetbrains.annotations.NotNull;
+import org.jetbrains.generate.tostring.psi.PsiAdapter;
/**
* Inserts the method last in the javafile.
@@ -31,18 +30,16 @@ public class InsertLastStrategy implements InsertNewMethodStrategy {
private static final InsertLastStrategy instance = new InsertLastStrategy();
- private InsertLastStrategy() {
- }
+ private InsertLastStrategy() {}
public static InsertLastStrategy getInstance() {
return instance;
}
- public PsiMethod insertNewMethod(PsiClass clazz, @NotNull PsiMethod newMethod, Editor editor) throws IncorrectOperationException {
- PsiAdapter psi = PsiAdapterFactory.getPsiAdapter();
+ public PsiMethod insertNewMethod(PsiClass clazz, @NotNull PsiMethod newMethod, Editor editor) {
// if main method exists and is the last then add toString just before main method
- PsiMethod mainMethod = psi.findPublicStaticVoidMainMethod(clazz);
+ PsiMethod mainMethod = PsiAdapter.findPublicStaticVoidMainMethod(clazz);
if (mainMethod != null) {
// add before main method if it is the last method
PsiMethod[] methods = clazz.getMethods();
@@ -59,5 +56,4 @@ public class InsertLastStrategy implements InsertNewMethodStrategy {
public String toString() {
return "Last";
}
-
}
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/InsertNewMethodStrategy.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/InsertNewMethodStrategy.java
index 9e25039631c6..7b30a1b6e488 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/InsertNewMethodStrategy.java
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/InsertNewMethodStrategy.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2001-2007 the original author or authors.
+ * Copyright 2001-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,16 +29,13 @@ import org.jetbrains.annotations.Nullable;
public interface InsertNewMethodStrategy {
/**
- * Applies the choosen policy.
+ * Applies the chosen policy.
*
* @param clazz PSIClass.
* @param newMethod new method.
* @param editor
* @return if the policy was executed normally (not cancelled)
- * @throws com.intellij.util.IncorrectOperationException
- * is thrown if there is an IDEA error.
*/
@Nullable
- PsiMethod insertNewMethod(PsiClass clazz, @NotNull PsiMethod newMethod, Editor editor) throws IncorrectOperationException;
-
+ PsiMethod insertNewMethod(PsiClass clazz, @NotNull PsiMethod newMethod, Editor editor);
}
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/PolicyOptions.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/PolicyOptions.java
index c0b9b5bfc9cf..40e830bb9a4c 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/PolicyOptions.java
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/config/PolicyOptions.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2001-2007 the original author or authors.
+ * Copyright 2001-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,13 +22,12 @@ public class PolicyOptions {
private static final transient InsertWhere[] newMethodOptions = {InsertWhere.AT_CARET, InsertWhere.AFTER_EQUALS_AND_HASHCODE, InsertWhere.AT_THE_END_OF_A_CLASS};
- private static final transient DuplicatonPolicy[] conflictOptions = {DuplicatonPolicy.ASK, DuplicatonPolicy.REPLACE, DuplicatonPolicy.DUPLICATE};
+ private static final transient DuplicationPolicy[] conflictOptions = {DuplicationPolicy.ASK, DuplicationPolicy.REPLACE, DuplicationPolicy.DUPLICATE};
- private PolicyOptions() {
- }
+ private PolicyOptions() {}
- /**
- * Get's the options for the the insert new method policy.
+ /**
+ * Gets the options for the the insert new method policy.
* @return the options for the the insert new method policy.
*/
public static InsertWhere[] getNewMethodOptions() {
@@ -36,11 +35,10 @@ public class PolicyOptions {
}
/**
- * Get's the options for the the conflict resolution policy.
+ * Gets the options for the the conflict resolution policy.
* @return the options for the the conflict resolution policy.
*/
- public static DuplicatonPolicy[] getConflictOptions() {
+ public static DuplicationPolicy[] getConflictOptions() {
return conflictOptions;
}
-
}
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/element/ClassElement.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/element/ClassElement.java
index 3432b6c81e6b..6b9d8057419d 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/element/ClassElement.java
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/element/ClassElement.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2001-2007 the original author or authors.
+ * Copyright 2001-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,7 +17,6 @@ package org.jetbrains.generate.tostring.element;
import com.intellij.openapi.util.text.StringUtil;
-import java.io.Serializable;
import java.util.Arrays;
/**
@@ -26,11 +25,10 @@ import java.util.Arrays;
* Note: getters are accessed from Velocity templates, they aren't dead code
*/
@SuppressWarnings({"UnusedDeclaration"})
-public class ClassElement implements Serializable {
+public class ClassElement {
private String name;
private String qualifiedName;
- private boolean hasSuper;
private String superName;
private String superQualifiedName;
private String[] implementNames;
@@ -50,7 +48,7 @@ public class ClassElement implements Serializable {
*/
public boolean isImplements(String interfaceName) {
for (String className : implementNames) {
- if (interfaceName.indexOf(className) != -1) {
+ if (interfaceName.contains(className)) {
return true;
}
}
@@ -65,7 +63,7 @@ public class ClassElement implements Serializable {
* @return true if this class extends one of the given classnames.
*/
public boolean isExtends(String classNames) {
- return (classNames.indexOf(superName) != -1);
+ return classNames.contains(superName);
}
/**
@@ -79,7 +77,6 @@ public class ClassElement implements Serializable {
if (StringUtil.isEmpty(regexp)) {
throw new IllegalArgumentException("Can't perform regular expression since the given input is empty. Check your Velocity template: regexp='" + regexp + "'");
}
-
return name.matches(regexp);
}
@@ -124,11 +121,7 @@ public class ClassElement implements Serializable {
}
public boolean isHasSuper() {
- return hasSuper;
- }
-
- public void setHasSuper(boolean hasSuper) {
- this.hasSuper = hasSuper;
+ return this.superName != null;
}
public boolean isDeprecated() {
@@ -167,7 +160,6 @@ public class ClassElement implements Serializable {
return "ClassElement{" +
"name='" + name + "'" +
", qualifiedName='" + qualifiedName + "'" +
- ", hasSuper=" + hasSuper +
", superName='" + superName + "'" +
", superQualifiedName='" + superQualifiedName + "'" +
", implementNames=" + (implementNames == null ? null : Arrays.asList(implementNames)) +
@@ -177,6 +169,4 @@ public class ClassElement implements Serializable {
", abstract=" + _abstract +
"}";
}
-
-
}
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/element/ElementFactory.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/element/ElementFactory.java
index d5ca95abf134..68c60c899a9a 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/element/ElementFactory.java
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/element/ElementFactory.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2001-2007 the original author or authors.
+ * Copyright 2001-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,7 +16,6 @@
package org.jetbrains.generate.tostring.element;
import com.intellij.openapi.diagnostic.Logger;
-import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import org.jetbrains.generate.tostring.psi.PsiAdapter;
@@ -33,12 +32,10 @@ public class ElementFactory {
/**
* Creates a new {@link ClassElement} object.
*
- * @param project the IDEA project.
* @param clazz class information.
- * @param psi the psi adapter
* @return a new {@link ClassElement} object.
*/
- public static ClassElement newClassElement(Project project, PsiClass clazz, PsiAdapter psi) {
+ public static ClassElement newClassElement(PsiClass clazz) {
ClassElement ce = new ClassElement();
// name
@@ -46,12 +43,11 @@ public class ElementFactory {
ce.setQualifiedName(clazz.getQualifiedName());
// super
- ce.setHasSuper(psi.hasSuperClass(project, clazz));
- PsiClass superClass = psi.getSuperClass(project, clazz);
- ce.setSuperName(superClass == null ? null : superClass.getName());
+ PsiClass superClass = clazz.getSuperClass();
+ ce.setSuperName((superClass == null) ? null : superClass.getName());
// interfaces
- ce.setImplementNames(psi.getImplementsClassnames(clazz));
+ ce.setImplementNames(PsiAdapter.getImplementsClassnames(clazz));
// other
ce.setEnum(clazz.isEnum());
@@ -65,28 +61,24 @@ public class ElementFactory {
/**
* Create a new {@link FieldElement} object.
*
- * @param project the IDEA project.
* @param field the {@link com.intellij.psi.PsiField} to get the information from.
- * @param psi the psi adapter
* @return a new {@link FieldElement} object.
*/
- public static FieldElement newFieldElement(Project project, PsiField field, PsiAdapter psi) {
- PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
-
+ public static FieldElement newFieldElement(PsiField field) {
FieldElement fe = new FieldElement();
- PsiType type = field.getType();
-
fe.setName(field.getName());
- if (psi.isConstantField(field)) fe.setConstant(true);
- if (psi.isEnumField(field)) fe.setEnum(true);
+ if (PsiAdapter.isConstantField(field)) fe.setConstant(true);
+ if (PsiAdapter.isEnumField(field)) fe.setEnum(true);
PsiModifierList modifiers = field.getModifierList();
if (modifiers != null) {
if (modifiers.hasModifierProperty(PsiModifier.TRANSIENT)) fe.setModifierTransient(true);
if (modifiers.hasModifierProperty(PsiModifier.VOLATILE)) fe.setModifierVolatile(true);
}
- setElementInfo(fe, factory, type, modifiers, psi);
+ PsiElementFactory factory = JavaPsiFacade.getInstance(field.getProject()).getElementFactory();
+ PsiType type = field.getType();
+ setElementInfo(fe, factory, type, modifiers);
return fe;
}
@@ -95,12 +87,10 @@ public class ElementFactory {
* Creates a new {@link MethodElement} object.
*
* @param method the PSI method object.
- * @param factory the PsiAdapterFactory.
- * @param psi the psi adapter
* @return a new {@link MethodElement} object.
* @since 2.15
*/
- public static MethodElement newMethodElement(PsiMethod method, PsiElementFactory factory, PsiAdapter psi) {
+ public static MethodElement newMethodElement(PsiMethod method) {
MethodElement me = new MethodElement();
PsiType type = method.getReturnType();
PsiModifierList modifiers = method.getModifierList();
@@ -111,25 +101,25 @@ public class ElementFactory {
log.warn("This method does not have a valid return type: " + method.getName() + ", returnType=" + type);
return me;
}
-
- setElementInfo(me, factory, type, modifiers, psi);
+ PsiElementFactory factory = JavaPsiFacade.getInstance(method.getProject()).getElementFactory();
+ setElementInfo(me, factory, type, modifiers);
// names
- String fieldName = psi.getGetterFieldName(factory, method);
+ String fieldName = PsiAdapter.getGetterFieldName(method);
me.setName(fieldName == null ? method.getName() : fieldName);
me.setFieldName(fieldName);
me.setMethodName(method.getName());
// getter
- me.setGetter(psi.isGetterMethod(factory, method));
+ me.setGetter(PsiAdapter.isGetterMethod(method));
// misc
me.setDeprecated(method.isDeprecated());
- me.setReturnTypeVoid(psi.isTypeOfVoid(method.getReturnType()));
+ me.setReturnTypeVoid(PsiAdapter.isTypeOfVoid(method.getReturnType()));
// modifiers
if (modifiers.hasModifierProperty(PsiModifier.ABSTRACT)) me.setModifierAbstract(true);
- if (modifiers.hasModifierProperty(PsiModifier.SYNCHRONIZED)) me.setModifierSynchronzied(true);
+ if (modifiers.hasModifierProperty(PsiModifier.SYNCHRONIZED)) me.setModifierSynchronized(true);
return me;
}
@@ -138,48 +128,46 @@ public class ElementFactory {
* Sets the basic element information from the given type.
*
* @param element the element to set information from the type
- * @param factory the PsiAdapterFactory.
+ * @param factory
* @param type the type
- * @param psi the psi adapter.
* @param modifiers modifier list
* @since 2.15
*/
private static void setElementInfo(AbstractElement element,
PsiElementFactory factory,
PsiType type,
- PsiModifierList modifiers,
- PsiAdapter psi) {
+ PsiModifierList modifiers) {
// type names
- element.setTypeName(psi.getTypeClassName(type));
- element.setTypeQualifiedName(psi.getTypeQualifiedClassName(type));
+ element.setTypeName(PsiAdapter.getTypeClassName(type));
+ element.setTypeQualifiedName(PsiAdapter.getTypeQualifiedClassName(type));
// arrays, collections and maps types
- if (psi.isObjectArrayType(type)) {
+ if (PsiAdapter.isObjectArrayType(type)) {
element.setObjectArray(true);
element.setArray(true);
// additional specify if the element is a string array
- if (psi.isStringArrayType(type)) element.setStringArray(true);
+ if (PsiAdapter.isStringArrayType(type)) element.setStringArray(true);
}
- else if (psi.isPrimitiveArrayType(type)) {
+ else if (PsiAdapter.isPrimitiveArrayType(type)) {
element.setPrimitiveArray(true);
element.setArray(true);
}
- if (psi.isCollectionType(factory, type)) element.setCollection(true);
- if (psi.isListType(factory, type)) element.setList(true);
- if (psi.isSetType(factory, type)) element.setSet(true);
- if (psi.isMapType(factory, type)) element.setMap(true);
+ if (PsiAdapter.isCollectionType(factory, type)) element.setCollection(true);
+ if (PsiAdapter.isListType(factory, type)) element.setList(true);
+ if (PsiAdapter.isSetType(factory, type)) element.setSet(true);
+ if (PsiAdapter.isMapType(factory, type)) element.setMap(true);
// other types
- if (psi.isPrimitiveType(type)) element.setPrimitive(true);
- if (psi.isObjectType(factory, type)) element.setObject(true);
- if (psi.isStringType(factory, type)) element.setString(true);
- if (psi.isNumericType(factory, type)) element.setNumeric(true);
- if (psi.isDateType(factory, type)) element.setDate(true);
- if (psi.isCalendarType(factory, type)) element.setCalendar(true);
- if (psi.isBooleanType(factory, type)) element.setBoolean(true);
+ if (PsiAdapter.isPrimitiveType(type)) element.setPrimitive(true);
+ if (PsiAdapter.isObjectType(factory, type)) element.setObject(true);
+ if (PsiAdapter.isStringType(factory, type)) element.setString(true);
+ if (PsiAdapter.isNumericType(factory, type)) element.setNumeric(true);
+ if (PsiAdapter.isDateType(factory, type)) element.setDate(true);
+ if (PsiAdapter.isCalendarType(factory, type)) element.setCalendar(true);
+ if (PsiAdapter.isBooleanType(factory, type)) element.setBoolean(true);
// modifiers
if (modifiers != null) {
@@ -196,7 +184,5 @@ public class ElementFactory {
}
else if (modifiers.hasModifierProperty(PsiModifier.PRIVATE)) element.setModifierPrivate(true);
}
-
}
-
}
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/element/ElementUtils.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/element/ElementUtils.java
index a6939103001b..3c2ddae6e73c 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/element/ElementUtils.java
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/element/ElementUtils.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2001-2007 the original author or authors.
+ * Copyright 2001-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,12 +15,9 @@
*/
package org.jetbrains.generate.tostring.element;
-import com.intellij.openapi.project.Project;
-import com.intellij.psi.PsiElementFactory;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiMember;
import com.intellij.psi.PsiMethod;
-import org.jetbrains.generate.tostring.psi.PsiAdapter;
import java.util.ArrayList;
import java.util.Collection;
@@ -31,24 +28,21 @@ import java.util.List;
*/
public class ElementUtils {
- private ElementUtils() {
- }
+ private ElementUtils() {}
/**
- * Get's the list of members to be put in the VelocityContext.
+ * Gets the list of members to be put in the VelocityContext.
*
- * @param project Project
- * @param psi PSI adapter
* @param members a list of {@link com.intellij.psi.PsiMember} objects.
* @return a filtered list of only the fields as {@link FieldElement} objects.
*/
- public static List<FieldElement> getOnlyAsFieldElements(Project project, PsiAdapter psi, Collection<PsiMember> members) {
+ public static List<FieldElement> getOnlyAsFieldElements(Collection<PsiMember> members) {
List<FieldElement> fieldElementList = new ArrayList<FieldElement>();
for (PsiMember member : members) {
if (member instanceof PsiField) {
PsiField field = (PsiField) member;
- FieldElement fe = ElementFactory.newFieldElement(project, field, psi);
+ FieldElement fe = ElementFactory.newFieldElement(field);
fieldElementList.add(fe);
}
}
@@ -57,20 +51,18 @@ public class ElementUtils {
}
/**
- * Get's the list of members to be put in the VelocityContext.
+ * Gets the list of members to be put in the VelocityContext.
*
- * @param psi PSI adapter
- * @param elementFactory Element Factory
* @param members a list of {@link com.intellij.psi.PsiMember} objects.
* @return a filtered list of only the methods as a {@link MethodElement} objects.
*/
- public static List<MethodElement> getOnlyAsMethodElements(PsiElementFactory elementFactory, PsiAdapter psi, Collection<PsiMember> members) {
+ public static List<MethodElement> getOnlyAsMethodElements(Collection<PsiMember> members) {
List<MethodElement> methodElementList = new ArrayList<MethodElement>();
for (PsiMember member : members) {
if (member instanceof PsiMethod) {
PsiMethod method = (PsiMethod) member;
- MethodElement me = ElementFactory.newMethodElement(method, elementFactory, psi);
+ MethodElement me = ElementFactory.newMethodElement(method);
methodElementList.add(me);
}
}
@@ -79,30 +71,25 @@ public class ElementUtils {
}
/**
- * Get's the list of members to be put in the VelocityContext.
+ * Gets the list of members to be put in the VelocityContext.
*
- * @param project Project
- * @param elementFactory Element Factory
- * @param psi PSI adapter
* @param members a list of {@link com.intellij.psi.PsiMember} objects.
* @return a filtered list of only the methods as a {@link FieldElement} or {@link MethodElement} objects.
*/
- public static List<Element> getOnlyAsFieldAndMethodElements(Project project, PsiElementFactory elementFactory, PsiAdapter psi, Collection<PsiMember> members) {
+ public static List<Element> getOnlyAsFieldAndMethodElements(Collection<PsiMember> members) {
List<Element> elementList = new ArrayList<Element>();
for (PsiMember member : members) {
if (member instanceof PsiField) {
PsiField field = (PsiField) member;
- FieldElement fe = ElementFactory.newFieldElement(project, field, psi);
+ FieldElement fe = ElementFactory.newFieldElement(field);
elementList.add(fe);
} else if (member instanceof PsiMethod) {
PsiMethod method = (PsiMethod) member;
- MethodElement me = ElementFactory.newMethodElement(method, elementFactory, psi);
+ MethodElement me = ElementFactory.newMethodElement(method);
elementList.add(me);
}
}
-
return elementList;
}
-
}
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/element/FieldElement.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/element/FieldElement.java
index 965b2aa1e8d4..8be76e1edbd4 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/element/FieldElement.java
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/element/FieldElement.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2001-2007 the original author or authors.
+ * Copyright 2001-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,10 +16,6 @@
package org.jetbrains.generate.tostring.element;
import com.intellij.openapi.util.text.StringUtil;
-import org.jetbrains.generate.tostring.config.FilterPattern;
-import org.jetbrains.generate.tostring.config.Filterable;
-
-import java.io.Serializable;
/**
* This is a field element containing information about the field.
@@ -27,7 +23,7 @@ import java.io.Serializable;
* @see ElementFactory
*/
@SuppressWarnings({"JavaDoc"})
-public class FieldElement extends AbstractElement implements Serializable, Element, Filterable {
+public class FieldElement extends AbstractElement implements Element {
private boolean isConstant;
private boolean isEnum;
@@ -78,7 +74,7 @@ public class FieldElement extends AbstractElement implements Serializable, Eleme
void setModifierVolatile(boolean modifierVolatile) {
this.isModifierVolatile = modifierVolatile;
- }
+ }
public void setEnum(boolean anEnum) {
isEnum = anEnum;
@@ -99,44 +95,6 @@ public class FieldElement extends AbstractElement implements Serializable, Eleme
return name.matches(regexp);
}
- public boolean applyFilter(FilterPattern pattern) {
- if (pattern == null)
- return false;
-
- if (pattern.isConstantField() && isConstant) {
- return true;
- }
-
- if (pattern.isEnumField() && isEnum) {
- return true;
- }
-
- if (pattern.isStaticModifier() && isModifierStatic) {
- return true;
- }
-
- if (pattern.isTransientModifier() && isModifierTransient) {
- return true;
- }
-
- if (StringUtil.isNotEmpty(pattern.getFieldName()) && name.matches(pattern.getFieldName())) {
- return true;
- }
-
- if (StringUtil.isNotEmpty(pattern.getFieldType()) && !isPrimitive && getTypeQualifiedName() != null) {
- String type = getTypeQualifiedName();
- if (type.matches(pattern.getFieldType()))
- return true;
- }
-
- if (pattern.isLoggers() && !isPrimitive && ("org.apache.log4j.Logger".equals(getTypeQualifiedName())
- || "java.util.logging.Logger".equals(getTypeQualifiedName()) || "org.apache.commons.logging.Log".equals(getTypeQualifiedName())) ) {
- return true;
- }
-
- return false;
- }
-
public String toString() {
return super.toString() + " ::: FieldElement{" +
"isConstant=" + isConstant +
@@ -145,6 +103,4 @@ public class FieldElement extends AbstractElement implements Serializable, Eleme
", isModifierVolatile=" + isModifierVolatile +
"}";
}
-
-
} \ No newline at end of file
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/element/MethodElement.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/element/MethodElement.java
index fe9c65e1d4e7..4005a8bb3f9d 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/element/MethodElement.java
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/element/MethodElement.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2001-2007 the original author or authors.
+ * Copyright 2001-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,10 +16,6 @@
package org.jetbrains.generate.tostring.element;
import com.intellij.openapi.util.text.StringUtil;
-import org.jetbrains.generate.tostring.config.FilterPattern;
-import org.jetbrains.generate.tostring.config.Filterable;
-
-import java.io.Serializable;
/**
* This is a method element containing information about the method.
@@ -27,12 +23,12 @@ import java.io.Serializable;
* @see ElementFactory
*/
@SuppressWarnings({"UnusedDeclaration"})
-public class MethodElement extends AbstractElement implements Serializable, Element, Filterable {
+public class MethodElement extends AbstractElement implements Element {
private String methodName;
private String fieldName;
private boolean modifierAbstract;
- private boolean modifierSynchronzied;
+ private boolean modifierSynchronized;
private boolean returnTypeVoid;
private boolean getter;
private boolean deprecated;
@@ -65,12 +61,19 @@ public class MethodElement extends AbstractElement implements Serializable, Elem
this.modifierAbstract = modifierAbstract;
}
+ /**
+ * Exists for compatibility with old templates
+ */
public boolean isModifierSynchronzied() {
- return modifierSynchronzied;
+ return isModifierSynchronized();
+ }
+
+ public boolean isModifierSynchronized() {
+ return modifierSynchronized;
}
- public void setModifierSynchronzied(boolean modifierSynchronzied) {
- this.modifierSynchronzied = modifierSynchronzied;
+ public void setModifierSynchronized(boolean modifierSynchronized) {
+ this.modifierSynchronized = modifierSynchronized;
}
public boolean isReturnTypeVoid() {
@@ -112,35 +115,15 @@ public class MethodElement extends AbstractElement implements Serializable, Elem
return methodName.matches(regexp);
}
- public boolean applyFilter(FilterPattern pattern) {
- if (pattern == null)
- return false;
-
- if (StringUtil.isNotEmpty(pattern.getMethodName()) && methodName.matches(pattern.getMethodName())) {
- return true;
- }
-
- if (StringUtil.isNotEmpty(pattern.getMethodType()) && !returnTypeVoid && !isPrimitive && getTypeQualifiedName() != null) {
- String type = getTypeQualifiedName();
- if (type.matches(pattern.getMethodType())) {
- return true;
- }
- }
-
- return false;
- }
-
public String toString() {
return super.toString() + " ::: MethodElement{" +
"fieldName='" + fieldName + "'" +
", methodName='" + methodName + "'" +
", modifierAbstract=" + modifierAbstract +
- ", modifierSynchronzied=" + modifierSynchronzied +
+ ", modifierSynchronized=" + modifierSynchronized +
", returnTypeVoid=" + returnTypeVoid +
", getter=" + getter +
", deprecated=" + deprecated +
"}";
}
-
-
}
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/inspection/AbstractGenerateToStringQuickFix.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/inspection/AbstractGenerateToStringQuickFix.java
deleted file mode 100644
index c0cba4040c9e..000000000000
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/inspection/AbstractGenerateToStringQuickFix.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright 2001-2007 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.jetbrains.generate.tostring.inspection;
-
-import com.intellij.codeInspection.LocalQuickFix;
-import org.jetbrains.generate.tostring.psi.PsiAdapter;
-import org.jetbrains.generate.tostring.psi.PsiAdapterFactory;
-import org.jetbrains.annotations.NotNull;
-
-/**
- * Base class to extend for different types of quick fixes.
- */
-public abstract class AbstractGenerateToStringQuickFix implements LocalQuickFix {
-
- protected PsiAdapter psi;
-
- public AbstractGenerateToStringQuickFix() {
- psi = PsiAdapterFactory.getPsiAdapter();
- }
-
- @NotNull
- public String getName() {
- return "Generate toString()";
- }
-
- @NotNull
- public String getFamilyName() {
- return "Generate";
- }
-
-}
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/inspection/ClassHasNoToStringMethodInspection.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/inspection/ClassHasNoToStringMethodInspection.java
index a6a734af5c7f..95a165676c0f 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/inspection/ClassHasNoToStringMethodInspection.java
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/inspection/ClassHasNoToStringMethodInspection.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2001-2012 the original author or authors.
+ * Copyright 2001-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,20 +15,18 @@
*/
package org.jetbrains.generate.tostring.inspection;
+import com.intellij.codeInsight.TestFrameworks;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ProblemsHolder;
-import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
+import com.intellij.psi.util.InheritanceUtil;
+import com.intellij.util.ui.CheckBox;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.generate.tostring.GenerateToStringContext;
import org.jetbrains.generate.tostring.GenerateToStringUtils;
-import org.jetbrains.generate.tostring.psi.PsiAdapter;
-import org.jetbrains.generate.tostring.psi.PsiAdapterFactory;
import org.jetbrains.generate.tostring.util.StringUtil;
import javax.swing.*;
-import javax.swing.event.ChangeEvent;
-import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
@@ -44,8 +42,6 @@ import java.awt.*;
*/
public class ClassHasNoToStringMethodInspection extends AbstractToStringInspection {
- private final AbstractGenerateToStringQuickFix fix = new GenerateToStringQuickFix();
-
/** User options for classes to exclude. Must be a regexp pattern */
public String excludeClassNames = ""; // must be public for JDOMSerialization
/** User options for excluded exception classes */
@@ -57,9 +53,11 @@ public class ClassHasNoToStringMethodInspection extends AbstractToStringInspecti
/** User options for excluded abstract classes */
public boolean excludeAbstract = false; // must be public for JDOMSerialization
+ public boolean excludeTestCode = false;
+
@NotNull
public String getDisplayName() {
- return "Class does not override toString() method";
+ return "Class does not override 'toString()' method";
}
@NotNull
@@ -80,10 +78,8 @@ public class ClassHasNoToStringMethodInspection extends AbstractToStringInspecti
if (nameIdentifier == null || clazz.getName() == null)
return;
- PsiAdapter psi = PsiAdapterFactory.getPsiAdapter();
-
// must not be an exception
- if (excludeException && PsiAdapter.isExceptionClass(clazz)) {
+ if (excludeException && InheritanceUtil.isInheritor(clazz, CommonClassNames.JAVA_LANG_THROWABLE)) {
log.debug("This class is an exception");
return;
}
@@ -105,6 +101,11 @@ public class ClassHasNoToStringMethodInspection extends AbstractToStringInspecti
return;
}
+ if (excludeTestCode && TestFrameworks.getInstance().isTestClass(clazz)) {
+ log.debug("Class is test class");
+ return;
+ }
+
// if it is an excluded class - then skip
if (StringUtil.isNotEmpty(excludeClassNames)) {
String name = clazz.getName();
@@ -122,19 +123,17 @@ public class ClassHasNoToStringMethodInspection extends AbstractToStringInspecti
}
// get list of fields and getter methods supposed to be dumped in the toString method
- Project project = clazz.getProject();
- fields = GenerateToStringUtils.filterAvailableFields(project, psi, clazz, GenerateToStringContext.getConfig().getFilterPattern());
+ fields = GenerateToStringUtils.filterAvailableFields(clazz, GenerateToStringContext.getConfig().getFilterPattern());
PsiMethod[] methods = null;
if (GenerateToStringContext.getConfig().isEnableMethods()) {
// okay 'getters in code generation' is enabled so check
- methods = GenerateToStringUtils.filterAvailableMethods(psi, clazz, GenerateToStringContext.getConfig().getFilterPattern());
+ methods = GenerateToStringUtils.filterAvailableMethods(clazz, GenerateToStringContext.getConfig().getFilterPattern());
}
// there should be any fields
- if (fields == null && methods == null)
- return;
- else if (Math.max( fields == null ? 0 : fields.length, methods == null ? 0 : methods.length) == 0)
- return;
+ if (Math.max(fields.length, methods == null ? 0 : methods.length) == 0) {
+ return;
+ }
// okay some fields/getter methods are supposed to dumped, does a toString method exist
final PsiMethod[] toStringMethods = clazz.findMethodsByName("toString", false);
@@ -158,7 +157,8 @@ public class ClassHasNoToStringMethodInspection extends AbstractToStringInspecti
}
if (log.isDebugEnabled()) log.debug("Class does not override toString() method: " + clazz.getQualifiedName());
- holder.registerProblem(nameIdentifier, "Class '" + clazz.getName() + "' does not override toString() method", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, fix);
+ holder.registerProblem(nameIdentifier, "Class '" + clazz.getName() + "' does not override 'toString()' method",
+ ProblemHighlightType.GENERIC_ERROR_OR_WARNING, GenerateToStringQuickFix.getInstance());
}
};
}
@@ -206,59 +206,30 @@ public class ClassHasNoToStringMethodInspection extends AbstractToStringInspecti
constraints.fill = GridBagConstraints.NONE;
panel.add(excludeClassNamesField, constraints);
- final JCheckBox excludeExceptionCheckBox = new JCheckBox("Exclude exception classes", excludeException);
- final ButtonModel bmException = excludeExceptionCheckBox.getModel();
- bmException.addChangeListener(new ChangeListener() {
- public void stateChanged(ChangeEvent changeEvent) {
- excludeException = bmException.isSelected();
- }
- });
+ final CheckBox excludeExceptionCheckBox = new CheckBox("Ignore exception classes", this, "excludeException");
constraints.gridx = 0;
constraints.gridy = 1;
constraints.gridwidth = 2;
constraints.fill = GridBagConstraints.HORIZONTAL;
panel.add(excludeExceptionCheckBox, constraints);
- final JCheckBox excludeDeprectedCheckBox = new JCheckBox("Exclude deprecated classes", excludeDeprecated);
- final ButtonModel bmDeprecated = excludeDeprectedCheckBox.getModel();
- bmDeprecated.addChangeListener(new ChangeListener() {
- public void stateChanged(ChangeEvent changeEvent) {
- excludeDeprecated = bmDeprecated.isSelected();
- }
- });
- constraints.gridx = 0;
+ final CheckBox excludeDeprecatedCheckBox = new CheckBox("Ignore deprecated classes", this, "excludeDeprecated");
constraints.gridy = 2;
- constraints.gridwidth = 2;
- constraints.fill = GridBagConstraints.HORIZONTAL;
- panel.add(excludeDeprectedCheckBox, constraints);
+ panel.add(excludeDeprecatedCheckBox, constraints);
- final JCheckBox excludeEnumCheckBox = new JCheckBox("Exclude enum classes", excludeEnum);
- final ButtonModel bmEnum = excludeEnumCheckBox.getModel();
- bmEnum.addChangeListener(new ChangeListener() {
- public void stateChanged(ChangeEvent changeEvent) {
- excludeEnum = bmEnum.isSelected();
- }
- });
- constraints.gridx = 0;
+ final CheckBox excludeEnumCheckBox = new CheckBox("Ignore enum classes", this, "excludeEnum");
constraints.gridy = 3;
- constraints.gridwidth = 2;
- constraints.fill = GridBagConstraints.HORIZONTAL;
panel.add(excludeEnumCheckBox, constraints);
- final JCheckBox excludeAbstractCheckBox = new JCheckBox("Exclude abstract classes", excludeAbstract);
- final ButtonModel bmAbstract = excludeAbstractCheckBox.getModel();
- bmAbstract.addChangeListener(new ChangeListener() {
- public void stateChanged(ChangeEvent changeEvent) {
- excludeAbstract = bmAbstract.isSelected();
- }
- });
- constraints.gridx = 0;
+ final CheckBox excludeAbstractCheckBox = new CheckBox("Ignore abstract classes", this, "excludeAbstract");
constraints.gridy = 4;
- constraints.gridwidth = 2;
- constraints.weighty = 1.0;
- constraints.fill = GridBagConstraints.HORIZONTAL;
panel.add(excludeAbstractCheckBox, constraints);
+ final CheckBox excludeInTestCodeCheckBox = new CheckBox("Ignore test classes", this, "excludeTestCode");
+ constraints.gridy = 5;
+ constraints.weighty = 1.0;
+ panel.add(excludeInTestCodeCheckBox, constraints);
+
return panel;
}
}
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/inspection/FieldNotUsedInToStringInspection.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/inspection/FieldNotUsedInToStringInspection.java
index 60da814170a5..2f38c189979f 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/inspection/FieldNotUsedInToStringInspection.java
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/inspection/FieldNotUsedInToStringInspection.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2001-2007 the original author or authors.
+ * Copyright 2001-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,209 +17,161 @@ package org.jetbrains.generate.tostring.inspection;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ProblemsHolder;
-import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
+import com.intellij.psi.util.PropertyUtil;
+import gnu.trove.THashSet;
+import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.generate.tostring.GenerateToStringContext;
import org.jetbrains.generate.tostring.GenerateToStringUtils;
-import org.jetbrains.generate.tostring.psi.PsiAdapter;
-import org.jetbrains.generate.tostring.psi.PsiAdapterFactory;
+
+import java.util.Collections;
/**
- * Intention to check if the current class toString() method is out of
- * sync with the fields defined.
- * <p/>
- * This inspection will use filter information from the settings to exclude certain fields (eg. constants etc.).
- * <p/>
- * This inspection will only perform inspection if the class has a toString() method.
+ * Inspection to check if the current class toString() method is out of
+ * sync with the fields defined. It uses filter information from the settings
+ * to exclude certain fields (eg. constants etc.). Will only warn if the
+ * class has a toString() method.
*/
public class FieldNotUsedInToStringInspection extends AbstractToStringInspection {
- private final AbstractGenerateToStringQuickFix fix = new GenerateToStringQuickFix();
+ @NotNull
+ public String getDisplayName() {
+ return "Field not used in 'toString()' method";
+ }
- @NotNull
- public String getDisplayName() {
- return "Field not used in toString() method";
- }
+ @NotNull
+ public String getShortName() {
+ return "FieldNotUsedInToString";
+ }
+
+ @Override
+ public boolean runForWholeFile() {
+ return true;
+ }
+
+ @NotNull
+ @Override
+ public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
+ return new FieldNotUsedInToStringVisitor(holder);
+ }
+
+ private static class FieldNotUsedInToStringVisitor extends JavaElementVisitor{
- @NotNull
- public String getShortName() {
- return "FieldNotUsedInToString";
+ private final ProblemsHolder myHolder;
+
+ public FieldNotUsedInToStringVisitor(ProblemsHolder holder) {
+ myHolder = holder;
}
@Override
- public boolean runForWholeFile() {
- return true;
+ public void visitField(PsiField field) {
+ super.visitField(field);
}
- @NotNull
@Override
- public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
- return new JavaElementVisitor() {
- @Override
- public void visitClass(PsiClass clazz) {
- checkFields(holder, clazz);
- checkMethods(holder, clazz);
- }
- };
+ public void visitMethod(PsiMethod method) {
+ super.visitMethod(method);
+ @NonNls final String methodName = method.getName();
+ if (!"toString".equals(methodName)) {
+ return;
+ }
+ final PsiParameterList parameterList = method.getParameterList();
+ if (parameterList.getParametersCount() != 0) {
+ return;
+ }
+ final PsiType returnType = method.getReturnType();
+ final PsiClassType javaLangString = PsiType.getJavaLangString(method.getManager(), method.getResolveScope());
+ if (!javaLangString.equals(returnType)) {
+ return;
+ }
+ final PsiClass aClass = method.getContainingClass();
+ if (aClass == null) {
+ return;
+ }
+ final PsiField[] fields =
+ GenerateToStringUtils.filterAvailableFields(aClass, GenerateToStringContext.getConfig().getFilterPattern());
+ final PsiMethod[] methods;
+ if (GenerateToStringContext.getConfig().isEnableMethods()) {
+ methods = GenerateToStringUtils.filterAvailableMethods(aClass, GenerateToStringContext.getConfig().getFilterPattern());
+ }
+ else {
+ methods = PsiMethod.EMPTY_ARRAY;
+ }
+ final FieldUsedVisitor visitor = new FieldUsedVisitor(fields, methods);
+ method.accept(visitor);
+ for (PsiField field : visitor.getUnusedFields()) {
+ final String fieldName = field.getName();
+ myHolder.registerProblem(field.getNameIdentifier(), "Field '" + fieldName + "' is not used in 'toString()' method",
+ ProblemHighlightType.GENERIC_ERROR_OR_WARNING, GenerateToStringQuickFix.getInstance());
+ }
+ for (PsiMethod unusedMethod : visitor.getUnusedMethods()) {
+ final PsiIdentifier identifier = unusedMethod.getNameIdentifier();
+ final PsiElement target = identifier == null ? unusedMethod : identifier;
+ myHolder.registerProblem(target, "Method '" + unusedMethod.getName() + "' is not used in 'toString()' method",
+ ProblemHighlightType.GENERIC_ERROR_OR_WARNING, GenerateToStringQuickFix.getInstance());
+ }
}
+ }
- /**
- * Checking for problems with fields.
- *
- * @param clazz the class to check
- * @param holder a sink to feed the problem to
- */
- private void checkFields(ProblemsHolder holder, PsiClass clazz) {
- if (log.isDebugEnabled()) log.debug("checkFields: clazz=" + clazz);
-
- // must be a class
- if (clazz == null || clazz.getName() == null) {
- return;
- }
-
- // must have fields
- PsiAdapter psi = PsiAdapterFactory.getPsiAdapter();
- PsiField[] fields = clazz.getFields();
- if (fields.length == 0) {
- log.debug("Class does not have any fields");
- return;
- }
-
- // a toString method must exist
- PsiMethod toStringMethod = psi.findMethodByName(clazz, "toString");
- if (toStringMethod == null) {
- log.debug("No toString() method");
- return;
- }
-
- // a toString code block must exist
- PsiCodeBlock code = toStringMethod.getBody();
- if (code == null) {
- log.debug("No toString() code");
- return;
- }
-
- // check if toString uses reflection if so exit
- String body = code.getText();
- if (body.indexOf("getDeclaredFields()") != -1) {
- log.debug("Using reflection");
- return;
- } else if (body.indexOf("ReflectionToStringBuilder(this).toString()") != -1) {
- log.debug("Using reflection (ReflectionToStringBuilder)");
- return;
- }
-
- // get list of fields supposed to be dumped in the toString method
- Project project = clazz.getProject();
- fields = GenerateToStringUtils.filterAvailableFields(project, psi, clazz, GenerateToStringContext.getConfig().getFilterPattern());
- if (fields == null || fields.length == 0) {
- log.debug("No fields to be dumped as all fields was excluded (exclude field by XXX from Settings)");
- return;
- }
-
- // toString exists and fields are supposed to be dumped
- // check if any fields are missing (out of sync)
- for (PsiField field : fields) {
- if (log.isDebugEnabled()) log.debug("Evaluating if field " + field.getName() + " is in toString() method");
-
- // field must be enclosed with non words before and after the field to ensure the fieldname are dumped
- String pattern = "(?s).*\\W" + field.getName() + "[\\W&&[^=]].*";
- if (log.isDebugEnabled()) log.debug("Match pattern = " + pattern);
+ private static class FieldUsedVisitor extends JavaRecursiveElementVisitor {
- // use regexp to match if field is used in code
- if (!body.matches(pattern)) {
- if (log.isDebugEnabled()) log.debug("Field is not used in toString() method (out-of-sync): " + field);
- holder.registerProblem(field, "Field '" + field.getName() + "' is not used in toString() method", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, fix);
- }
- }
+ private final THashSet<PsiField> myUnusedFields = new THashSet<PsiField>();
+ private final THashSet<PsiMethod> myUnusedMethods = new THashSet<PsiMethod>();
+ public FieldUsedVisitor(PsiField[] fields, PsiMethod[] methods) {
+ Collections.addAll(myUnusedFields, fields);
+ Collections.addAll(myUnusedMethods, methods);
}
- /**
- * Checking for problems with fields.
- *
- * @param clazz the class to check
- * @param holder a sink to feed the problem to
- */
- private void checkMethods(ProblemsHolder holder, PsiClass clazz) {
- if (log.isDebugEnabled()) log.debug("checkMethods: clazz=" + clazz);
-
- // must be a class
- if (clazz == null || clazz.getName() == null) {
- return;
- }
-
- // must have 'Enable getters in code generation' set to true
- if (! GenerateToStringContext.getConfig().isEnableMethods()) {
- return;
- }
-
- // a toString method must exist
- PsiAdapter psi = PsiAdapterFactory.getPsiAdapter();
- PsiMethod toStringMethod = psi.findMethodByName(clazz, "toString");
- if (toStringMethod == null) {
- log.debug("No toString() method");
- return;
- }
-
- // a toString code block must exist
- PsiCodeBlock code = toStringMethod.getBody();
- if (code == null) {
- log.debug("No toString() code");
- return;
- }
-
- // check if toString uses reflection if so exit
- String body = code.getText();
- if (body.indexOf("getDeclaredFields()") != -1) {
- log.debug("Using reflection");
- return;
- }
-
- // must have methods
- PsiMethod[] methods = clazz.getMethods();
- if (methods.length == 0) {
- log.debug("Class does not have any methods");
- return;
- }
-
- // get list of methods supposed to be dumped in the toString method
- methods = GenerateToStringUtils.filterAvailableMethods(psi, clazz, GenerateToStringContext.getConfig().getFilterPattern());
- if (methods == null || methods.length == 0) {
- log.debug("No getter methods to be dumped as all methods was excluded or a field existed for the getter method (exclude method by XXX from Settings)");
- return;
+ @Override
+ public void visitReferenceExpression(PsiReferenceExpression expression) {
+ if (myUnusedFields.isEmpty() && myUnusedMethods.isEmpty()) {
+ return;
+ }
+ super.visitReferenceExpression(expression);
+ final PsiElement target = expression.resolve();
+ if (target instanceof PsiField) {
+ final PsiField field = (PsiField)target;
+ myUnusedFields.remove(field);
+ }
+ else if (target instanceof PsiMethod) {
+ final PsiMethod method = (PsiMethod)target;
+ if (usesReflection(method)) {
+ myUnusedFields.clear();
+ myUnusedMethods.clear();
}
-
- // toString exists and methods are supposed to be dumped
- // check if any methods are missing (out of sync)
- for (PsiMethod method : methods) {
- if (log.isDebugEnabled()) log.debug("Evaluating if method " + method.getName() + " is in toString() method");
-
- // method must be enclosed with non words before and after the method to ensure the fieldname are dumped
- String pattern = "(?s).*\\W" + method.getName() + "[\\W&&[^=]].*";
- if (log.isDebugEnabled()) log.debug("Match pattern = " + pattern);
-
- // use regexp to match if method is used in code
- if (!body.matches(pattern)) {
- // method is not in toString
- if (log.isDebugEnabled()) log.debug("Getter method is not used in toString() method (out-of-sync): " + method);
- holder.registerProblem(method, "Method '" + method.getName() + "' is not used in toString() method", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, fix);
- }
+ else {
+ myUnusedMethods.remove(method);
+ final PsiField field = PropertyUtil.findPropertyFieldByMember(method);
+ myUnusedFields.remove(field);
}
-
+ }
}
+ private boolean usesReflection(PsiMethod method) {
+ @NonNls final String name = method.getName();
+ final PsiClass containingClass = method.getContainingClass();
+ if (containingClass == null) {
+ return false;
+ }
+ @NonNls final String qualifiedName = containingClass.getQualifiedName();
+ if ("getDeclaredFields".equals(name)) {
+ return "java.lang.Class".equals(qualifiedName);
+ }
+ else if ("toString".equals(name)) {
+ return "org.apache.commons.lang.builder.ReflectionToStringBuilder".equals(qualifiedName) ||
+ "java.util.Objects".equals(qualifiedName);
+ }
+ return false;
+ }
-/*
- public static void main(String[] args) {
- // for testing regexp pattern
- String me = "return \"DummyTestBean{\" +\n" +
- " \", myNewString ='\" + myNewString + \"'\" +\n" +
- " \"}\";";
- System.out.println("me = " + me);
- System.out.println( me.matches("(?s).*\\WmyNewString[\\W*&&[^\\s*=]].*") );
+ public THashSet<PsiField> getUnusedFields() {
+ return myUnusedFields;
}
-*/
+ public THashSet<PsiMethod> getUnusedMethods() {
+ return myUnusedMethods;
+ }
+ }
}
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/inspection/GenerateToStringQuickFix.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/inspection/GenerateToStringQuickFix.java
index b711808e06cf..47e5f63d599a 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/inspection/GenerateToStringQuickFix.java
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/inspection/GenerateToStringQuickFix.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2001-2007 the original author or authors.
+ * Copyright 2001-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,6 +15,7 @@
*/
package org.jetbrains.generate.tostring.inspection;
+import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
@@ -26,19 +27,33 @@ import org.jetbrains.generate.tostring.GenerateToStringActionHandlerImpl;
/**
* Quick fix to run Generate toString() to fix any code inspection problems.
*/
-public class GenerateToStringQuickFix extends AbstractGenerateToStringQuickFix {
+public class GenerateToStringQuickFix implements LocalQuickFix {
- public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor desc) {
+ public static final GenerateToStringQuickFix INSTANCE = new GenerateToStringQuickFix();
- // find the class
- PsiClass clazz = PsiTreeUtil.getParentOfType(desc.getPsiElement(), PsiClass.class);
- if (clazz == null) {
- return; // no class to fix, so return
- }
+ private final GenerateToStringActionHandler myHandler = new GenerateToStringActionHandlerImpl();
- // execute the action
- GenerateToStringActionHandler handler = new GenerateToStringActionHandlerImpl();
- handler.executeActionQickFix(project, clazz);
- }
+ private GenerateToStringQuickFix() {}
+
+ public static GenerateToStringQuickFix getInstance() {
+ return INSTANCE;
+ }
+
+ @NotNull
+ public String getName() {
+ return "Generate toString()";
+ }
+ @NotNull
+ public String getFamilyName() {
+ return "Generate";
+ }
+
+ public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor desc) {
+ final PsiClass clazz = PsiTreeUtil.getParentOfType(desc.getPsiElement(), PsiClass.class);
+ if (clazz == null) {
+ return; // no class to fix
+ }
+ myHandler.executeActionQuickFix(project, clazz);
+ }
}
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/package.html b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/package.html
index c8e91dec4314..53296bfaf325 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/package.html
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/package.html
@@ -3,7 +3,7 @@
<h2>Generate toString() plugin</h2>
<h3>Plugin home page</h3>
- The plugin is hosted at Google code where there is an offical issue tracker and wiki pages with more information.
+ The plugin is hosted at Google code where there is an official issue tracker and wiki pages with more information.
<br/>
Plugin home page: <a href="http://code.google.com/p/generate-tostring/">generate-tostring</a>
@@ -49,7 +49,7 @@
<h3>Enable getters in code generation</h3>
Using this feature getter methods that does not directly use an existing field are avail in the Velocity Template Macro
- langauge as the variable $methods.
+ language as the variable $methods.
<br/>The example again with getters enabled:
<pre>
@@ -113,8 +113,8 @@
<tr/><td>Exclude fields by typename</td><td>Performs a regular expression matching on the field type name (fully qualified name). If the result is <b>true</b> the field will <b>not</b> be part of available fields for the code generator.</td>
<tr/><td>Exclude methods by name</td><td>Performs a regular expression matching on the method name. If the result is <b>true</b> the method will <b>not</b> be part of available methods for the code generator.</td>
<tr/><td>Exclude methods by return typename</td><td>Performs a regular expression matching on the method return typename (fully qualified name). If the result is <b>true</b> the method will <b>not</b> be part of available methods for the code generator.</td>
- <tr/><td>Automatic add implements java.io.Serializable</td><td>Will automatic add <code>implements Serializable</code> to the java bean class if not already implemented. This is usefull for value objects that usually have to implement this interface for working in J2EE environments.</td>
- <tr/><td>Automatic import packages</td><td>Will automatic import the packages. Additional packages can be separated using comma. IDEA will optmize the imports so java.util.* will be optimized to java.util.List;java.util.Arrays etc. <br/>Can be used to import your own classes that might be added to the generated code in the toString method.</td>
+ <tr/><td>Automatic add implements java.io.Serializable</td><td>Will automatic add <code>implements Serializable</code> to the java bean class if not already implemented. This is useful for value objects that usually have to implement this interface for working in J2EE environments.</td>
+ <tr/><td>Automatic import packages</td><td>Will automatic import the packages. Additional packages can be separated using comma. IDEA will optimize the imports so java.util.* will be optimized to java.util.List;java.util.Arrays etc. <br/>Can be used to import your own classes that might be added to the generated code in the toString method.</td>
<tr/><td>Templates</td><td>A list of predefined templates to choose. To use a new template first select it and click the <b>Use this template</b> button.</td>
<tr/><td>Active template</td><td>Activates the current selected template. A confirm dialog will be prompted.</td>
<tr/><td>Save template</td><td>Saving the current template to a file. A file chooser dialog will be prompted.</td>
@@ -160,7 +160,7 @@
<h3>JavaDoc</h3>
It is possible to add javadoc comments to the generated toString() method. This is done by inserting the javadoc
- comments in the veloicty template. See the supplied javadoc templte example. A requirement is to use /** and */
+ comments in the velocity template. See the supplied javadoc template example. A requirement is to use /** and */
enclosing the javadoc comments. The javadoc comments should be in the top of the template.
<p/>
Here is an example:
@@ -246,7 +246,7 @@
<h3>Inspection</h3>
This plugin provides two code inspections:
<ul>
- <li/>Class does not overwrite toString() method
+ <li/>Class does not override toString() method
<li/>Field not used in toString() method
</ul>
The <b>Field not used in toString() method</b> inspection can be used to identify out of synchronization situations
@@ -259,7 +259,7 @@
Enabling the on-the-fly feature can be done from setting <b>settings -> Errors -> ToString() Issues</b>.
Also on-the-fly should be enabled from the settings to the plugin.
<p/>
- The inspection <b>Class does not overwrite toString() method</b> can be used to identify any classes where you
+ The inspection <b>Class does not override toString() method</b> can be used to identify any classes where you
might have forgotten to add a toString() method. This inspection will use the exclude settings from the plugin
configuration to ignore classes having fields not supposed to be dumped. An additional settings is to exclude certain
classes by using a regular expression matching their classname. As default this is used to exclude any Exception classes.
@@ -298,8 +298,8 @@
<tr><td>$member.accessor</td><td>String</td><td>The accessor of the field or method. For field it is the <code>$field.name</code> and for method it is <code>$method.methodName</code></td></tr>
<tr><td>$member.typeName</td><td>String</td><td>The classname of the type (Object, String, List etc.)</td></tr>
<tr><td>$member.typeQualifiedName</td><td>String</td><td>The qualified classname of the type (java.lang.Object, java.lang.String, java.uti.List etc.)</td></tr>
- <tr><td>$member.array</td><td>boolean</td><td>Tests if the type is an array type (either a primitve array or object array)?</td></tr>
- <tr><td>$member.primitiveArray</td><td>boolean</td><td>Is the type a primitve array type? (int[], short[], float[] etc.)</td></tr>
+ <tr><td>$member.array</td><td>boolean</td><td>Tests if the type is an array type (either a primitive array or object array)?</td></tr>
+ <tr><td>$member.primitiveArray</td><td>boolean</td><td>Is the type a primitive array type? (int[], short[], float[] etc.)</td></tr>
<tr><td>$member.objectArray</td><td>boolean</td><td>Is the type an Object array type? (Object[], String[] etc.)</td></tr>
<tr><td>$member.stringArray</td><td>boolean</td><td>Is the type an String array type? (String[])</td></tr>
<tr><td>$member.collection</td><td>boolean</td><td>Is the type assignable from java.util.Collection?</td></tr>
@@ -333,9 +333,9 @@
<tr><td>$method.methodName</td><td>String</td><td>The name of the method (getFoo).</td></tr>
<tr><td>$method.fieldName</td><td>String</td><td>The name of the field this getter method covers - null if the method is not a getter for a field</td></tr>
<tr><td>$method.modifierAbstract</td><td>boolean</td><td>Is this method an abstract method?</td></tr>
- <tr><td>$method.modifierSynchronzied</td><td>boolean</td><td>Is this method a synchronzied method?</td></tr>
+ <tr><td>$method.modifierSynchronized</td><td>boolean</td><td>Is this method a synchronized method?</td></tr>
<tr><td>$method.returnTypeVoid</td><td>boolean</td><td>Is this method a void method (does not return anything) ?</td></tr>
- <tr><td>$methor.getter</td><td>boolean</td><td>Is this a getter method?</td></tr>
+ <tr><td>$method.getter</td><td>boolean</td><td>Is this a getter method?</td></tr>
<tr><td>$method.matchName(regexp)</td><td>boolean</td><td>Performs a regular expression matching on the methodname.</td></tr>
<tr><td>$method.deprecated</td><td>boolean</td><td>Is this method deprecated?</td></tr>
<tr><td></td><td></td></tr>
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/psi/PsiAdapter.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/psi/PsiAdapter.java
index d262cb5960cc..2a6d2752677f 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/psi/PsiAdapter.java
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/psi/PsiAdapter.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2001-2007 the original author or authors.
+ * Copyright 2001-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@ package org.jetbrains.generate.tostring.psi;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.project.Project;
+import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
@@ -24,6 +25,7 @@ import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PropertyUtil;
+import com.intellij.psi.util.PsiUtil;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.Nullable;
@@ -34,22 +36,18 @@ import org.jetbrains.generate.tostring.util.StringUtil;
*/
public class PsiAdapter {
- /**
- * Constructor - use {@link PsiAdapterFactory}.
- */
- protected PsiAdapter() {
- }
+ private PsiAdapter() {}
- /**
+ /**
* Returns true if a field is constant.
* <p/>
- * This is identifed as the name of the field is only in uppercase and it has
+ * This is identified as the name of the field is only in uppercase and it has
* a <code>static</code> modifier.
*
* @param field field to check if it's a constant
* @return true if constant.
*/
- public boolean isConstantField(PsiField field) {
+ public static boolean isConstantField(PsiField field) {
PsiModifierList list = field.getModifierList();
if (list == null) {
return false;
@@ -65,7 +63,7 @@ public class PsiAdapter {
}
/**
- * Find's an existing method with the given name.
+ * Finds an existing method with the given name.
* If there isn't a method with the name, null is returned.
*
* @param clazz the class
@@ -73,25 +71,26 @@ public class PsiAdapter {
* @return the found method, null if none exist
*/
@Nullable
- public PsiMethod findMethodByName(PsiClass clazz, String name) {
+ public static PsiMethod findMethodByName(PsiClass clazz, String name) {
PsiMethod[] methods = clazz.getMethods();
- // use reverse to find from botton as the duplicate conflict resolution policy requires this
+ // use reverse to find from bottom as the duplicate conflict resolution policy requires this
for (int i = methods.length - 1; i >= 0; i--) {
PsiMethod method = methods[i];
- if (name.equals(method.getName()))
+ if (name.equals(method.getName())) {
return method;
+ }
}
return null;
}
/**
- * Returns true if the given field a primtive array type (e.g., int[], long[], float[]).
+ * Returns true if the given field a primitive array type (e.g., int[], long[], float[]).
*
* @param type type.
- * @return true if field is a primitve array type.
+ * @return true if field is a primitive array type.
*/
- public boolean isPrimitiveArrayType(PsiType type) {
+ public static boolean isPrimitiveArrayType(PsiType type) {
return type instanceof PsiArrayType && isPrimitiveType(((PsiArrayType) type).getComponentType());
}
@@ -101,7 +100,7 @@ public class PsiAdapter {
* @param type type.
* @return true if it's an Object array type.
*/
- public boolean isObjectArrayType(PsiType type) {
+ public static boolean isObjectArrayType(PsiType type) {
return type instanceof PsiArrayType && !isPrimitiveType(((PsiArrayType) type).getComponentType());
}
@@ -111,7 +110,7 @@ public class PsiAdapter {
* @param type type.
* @return true if it's a String array type.
*/
- public boolean isStringArrayType(PsiType type) {
+ public static boolean isStringArrayType(PsiType type) {
if (isPrimitiveType(type))
return false;
@@ -125,7 +124,7 @@ public class PsiAdapter {
* @param type type.
* @return true if it's a Collection type.
*/
- public boolean isCollectionType(PsiElementFactory factory, PsiType type) {
+ public static boolean isCollectionType(PsiElementFactory factory, PsiType type) {
return isTypeOf(factory, type, "java.util.Collection");
}
@@ -136,7 +135,7 @@ public class PsiAdapter {
* @param type type.
* @return true if it's a Map type.
*/
- public boolean isMapType(PsiElementFactory factory, PsiType type) {
+ public static boolean isMapType(PsiElementFactory factory, PsiType type) {
return isTypeOf(factory, type, CommonClassNames.JAVA_UTIL_MAP);
}
@@ -147,7 +146,7 @@ public class PsiAdapter {
* @param type type.
* @return true if it's a Map type.
*/
- public boolean isSetType(PsiElementFactory factory, PsiType type) {
+ public static boolean isSetType(PsiElementFactory factory, PsiType type) {
return isTypeOf(factory, type, CommonClassNames.JAVA_UTIL_SET);
}
@@ -158,7 +157,7 @@ public class PsiAdapter {
* @param type type.
* @return true if it's a Map type.
*/
- public boolean isListType(PsiElementFactory factory, PsiType type) {
+ public static boolean isListType(PsiElementFactory factory, PsiType type) {
return isTypeOf(factory, type, CommonClassNames.JAVA_UTIL_LIST);
}
@@ -169,7 +168,7 @@ public class PsiAdapter {
* @param type type.
* @return true if it's a String type.
*/
- public boolean isStringType(PsiElementFactory factory, PsiType type) {
+ public static boolean isStringType(PsiElementFactory factory, PsiType type) {
return isTypeOf(factory, type, "java.lang.String");
}
@@ -180,7 +179,7 @@ public class PsiAdapter {
* @param type type.
* @return true if it's an Object type.
*/
- public boolean isObjectType(PsiElementFactory factory, PsiType type) {
+ public static boolean isObjectType(PsiElementFactory factory, PsiType type) {
return isTypeOf(factory, type, CommonClassNames.JAVA_LANG_OBJECT);
}
@@ -191,7 +190,7 @@ public class PsiAdapter {
* @param type type.
* @return true if it's a Date type.
*/
- public boolean isDateType(PsiElementFactory factory, PsiType type) {
+ public static boolean isDateType(PsiElementFactory factory, PsiType type) {
return isTypeOf(factory, type, "java.util.Date");
}
@@ -202,7 +201,7 @@ public class PsiAdapter {
* @param type type.
* @return true if it's a Calendar type.
*/
- public boolean isCalendarType(PsiElementFactory factory, PsiType type) {
+ public static boolean isCalendarType(PsiElementFactory factory, PsiType type) {
return isTypeOf(factory, type, "java.util.Calendar");
}
@@ -213,7 +212,7 @@ public class PsiAdapter {
* @param type type.
* @return true if it's a Boolean or boolean type.
*/
- public boolean isBooleanType(PsiElementFactory factory, PsiType type) {
+ public static boolean isBooleanType(PsiElementFactory factory, PsiType type) {
if (isPrimitiveType(type)) {
// test for simple type of boolean
String s = type.getCanonicalText();
@@ -231,7 +230,7 @@ public class PsiAdapter {
* @param type type.
* @return true if it's a numeric type.
*/
- public boolean isNumericType(PsiElementFactory factory, PsiType type) {
+ public static boolean isNumericType(PsiElementFactory factory, PsiType type) {
if (isPrimitiveType(type)) {
// test for simple type of numeric
String s = type.getCanonicalText();
@@ -242,36 +241,37 @@ public class PsiAdapter {
}
}
- /**
+ /**
* Does the javafile have the import statement?
*
* @param javaFile javafile.
* @param importStatement import statement to test existing for.
* @return true if the javafile has the import statement.
*/
- public boolean hasImportStatement(PsiJavaFile javaFile, String importStatement) {
+ public static boolean hasImportStatement(PsiJavaFile javaFile, String importStatement) {
PsiImportList importList = javaFile.getImportList();
if (importList == null) {
return false;
}
if (importStatement.endsWith(".*")) {
- return (importList.findOnDemandImportStatement(fixImportStatement(importStatement)) != null);
+ return importList.findOnDemandImportStatement(fixImportStatement(importStatement)) != null;
} else {
- return (importList.findSingleClassImportStatement(importStatement) != null);
+ return importList.findSingleClassImportStatement(importStatement) != null;
}
}
/**
- * Add's an importstatement to the javafile and optimizes the imports afterwards.
+ * Adds an import statement to the javafile and optimizes the imports afterwards.
+ *
*
* @param javaFile javafile.
- * @param importStatementOnDemand name of importstatement, must be with a wildcard (etc. java.util.*).
- * @param factory PSI element factory.
+ * @param importStatementOnDemand name of import statement, must be with a wildcard (etc. java.util.*).
* @throws com.intellij.util.IncorrectOperationException
- * is thrown if there is an error creating the importstatement.
+ * is thrown if there is an error creating the import statement.
*/
- public void addImportStatement(PsiJavaFile javaFile, String importStatementOnDemand, PsiElementFactory factory) throws IncorrectOperationException {
+ public static void addImportStatement(PsiJavaFile javaFile, String importStatementOnDemand) {
+ PsiElementFactory factory = JavaPsiFacade.getInstance(javaFile.getProject()).getElementFactory();
PsiImportStatement is = factory.createImportStatementOnDemand(fixImportStatement(importStatementOnDemand));
// add the import to the file, and optimize the imports
@@ -293,7 +293,7 @@ public class PsiAdapter {
* @param importStatementOnDemand import statement
* @return import statement only with packagename
*/
- private String fixImportStatement(String importStatementOnDemand) {
+ private static String fixImportStatement(String importStatementOnDemand) {
if (importStatementOnDemand.endsWith(".*")) {
return importStatementOnDemand.substring(0, importStatementOnDemand.length() - 2);
} else {
@@ -311,33 +311,14 @@ public class PsiAdapter {
}
/**
- * Does this class have a super class?
- * <p/>
- * If the class just extends java.lang.Object then false is returned.
- * Extending java.lang.Object is <b>not</b> concidered the class to have a super class.
- *
- * @param project the IDEA project
- * @param clazz the class to test
- * @return true if this class extends another class.
- */
- public boolean hasSuperClass(Project project, PsiClass clazz) {
- PsiClass superClass = getSuperClass(project, clazz);
- if (superClass == null) {
- return false;
- }
-
- return (!"Object".equals(superClass.getName()));
- }
-
- /**
- * Get's the fields fully qualified classname (etc java.lang.String, java.util.ArrayList)
+ * Gets the fields fully qualified classname (etc java.lang.String, java.util.ArrayList)
*
* @param type the type.
* @return the fully qualified classname, null if the field is a primitive.
* @see #getTypeClassName(com.intellij.psi.PsiType) for the non qualified version.
*/
@Nullable
- public String getTypeQualifiedClassName(PsiType type) {
+ public static String getTypeQualifiedClassName(PsiType type) {
if (isPrimitiveType(type)) {
return null;
}
@@ -352,14 +333,14 @@ public class PsiAdapter {
}
/**
- * Get's the fields classname (etc. String, ArrayList)
+ * Gets the fields classname (etc. String, ArrayList)
*
* @param type the type.
* @return the classname, null if the field is a primitive.
* @see #getTypeQualifiedClassName(com.intellij.psi.PsiType) for the qualified version.
*/
@Nullable
- public String getTypeClassName(PsiType type) {
+ public static String getTypeClassName(PsiType type) {
String name = getTypeQualifiedClassName(type);
// return null if it was a primitive type
@@ -371,14 +352,14 @@ public class PsiAdapter {
return name.substring(i + 1, name.length());
}
- /**
+ /**
* Finds the public static void main(String[] args) method.
*
* @param clazz the class.
* @return the method if it exists, null if not.
*/
@Nullable
- public PsiMethod findPublicStaticVoidMainMethod(PsiClass clazz) {
+ public static PsiMethod findPublicStaticVoidMainMethod(PsiClass clazz) {
PsiMethod[] methods = clazz.findMethodsByName("main", false);
// is it public static void main(String[] args)
@@ -395,7 +376,7 @@ public class PsiAdapter {
// must have void as return type
PsiType returnType = method.getReturnType();
- if (returnType == null || returnType.equalsToText("void")) {
+ if (!PsiType.VOID.equals(returnType)) {
continue;
}
@@ -421,8 +402,6 @@ public class PsiAdapter {
/**
* Add or replaces the javadoc comment to the given method.
*
- * @param factory element factory.
- * @param codeStyleManager CodeStyleManager.
* @param method the method the javadoc should be added/set to.
* @param javadoc the javadoc comment.
* @param replace true if any existing javadoc should be replaced. false will not replace any existing javadoc and thus leave the javadoc untouched.
@@ -430,7 +409,9 @@ public class PsiAdapter {
* @throws IncorrectOperationException is thrown if error adding/replacing the javadoc comment.
*/
@Nullable
- public PsiComment addOrReplaceJavadoc(PsiElementFactory factory, CodeStyleManager codeStyleManager, PsiMethod method, String javadoc, boolean replace) throws IncorrectOperationException {
+ public static PsiComment addOrReplaceJavadoc(PsiMethod method, String javadoc, boolean replace) {
+ final Project project = method.getProject();
+ PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
PsiComment comment = factory.createCommentFromText(javadoc, null);
// does a method already exists?
@@ -439,6 +420,7 @@ public class PsiAdapter {
if (replace) {
// javadoc already exists, so replace
doc.replace(comment);
+ final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
codeStyleManager.reformat(method); // to reformat javadoc
return comment;
} else {
@@ -448,6 +430,7 @@ public class PsiAdapter {
} else {
// add new javadoc
method.addBefore(comment, method.getFirstChild());
+ final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
codeStyleManager.reformat(method); // to reformat javadoc
return comment;
}
@@ -459,8 +442,8 @@ public class PsiAdapter {
* @param type the type.
* @return true if a void type, false if not.
*/
- public boolean isTypeOfVoid(PsiType type) {
- return (type != null && type.equalsToText("void"));
+ public static boolean isTypeOfVoid(PsiType type) {
+ return type != null && type.equalsToText("void");
}
/**
@@ -469,27 +452,24 @@ public class PsiAdapter {
* The name of the method must start with <code>get</code> or <code>is</code>.
* And if the method is a <code>isXXX</code> then the method must return a java.lang.Boolean or boolean.
*
- * @param factory element factory.
+ *
* @param method the method
* @return true if a getter method, false if not.
*/
- public boolean isGetterMethod(PsiElementFactory factory, PsiMethod method) {
+ public static boolean isGetterMethod(PsiMethod method) {
// must not be a void method
if (isTypeOfVoid(method.getReturnType())) {
return false;
}
-
- if (method.getName().matches("^(is|has)\\p{Upper}.*")) {
- return isBooleanType(factory, method.getReturnType());
- } else if (method.getName().matches("^(get)\\p{Upper}.*")) {
- return true;
+ final PsiParameterList parameterList = method.getParameterList();
+ if (parameterList.getParametersCount() != 0) {
+ return false;
}
-
- return false;
+ return true;
}
/**
- * Get's the field name of the getter method.
+ * Gets the field name of the getter method.
* <p/>
* The method must be a getter method for a field.
* Returns null if this method is not a getter.
@@ -499,49 +479,35 @@ public class PsiAdapter {
* <p/>
* Example: methodName=getName will return fieldname=name
*
- * @param factory element factory.
+ *
* @param method the method
* @return the fieldname if this is a getter method.
- * @see #isGetterMethod(com.intellij.psi.PsiElementFactory,com.intellij.psi.PsiMethod) for the getter check
+ * @see #isGetterMethod(com.intellij.psi.PsiMethod) for the getter check
*/
@Nullable
- public String getGetterFieldName(PsiElementFactory factory, PsiMethod method) {
+ public static String getGetterFieldName(PsiMethod method) {
// must be a getter
- if (!isGetterMethod(factory, method)) {
+ if (!isGetterMethod(method)) {
return null;
}
-
return PropertyUtil.getPropertyNameByGetter(method);
}
- /**
+ /**
* Returns true if the field is enum (JDK1.5).
*
* @param field field to check if it's a enum
* @return true if enum.
*/
- public boolean isEnumField(PsiField field) {
+ public static boolean isEnumField(PsiField field) {
PsiType type = field.getType();
-
- // must not be an primitive type
- if (isPrimitiveType(type)) {
- return false;
- }
-
- GlobalSearchScope scope = type.getResolveScope();
- if (scope == null) {
- return false;
- }
-
- // find the class
- String name = type.getCanonicalText();
- PsiClass clazz = JavaPsiFacade.getInstance(field.getProject()).findClass(name, scope);
- if (clazz == null) {
+ if (!(type instanceof PsiClassType)) {
return false;
}
-
- return clazz.isEnum();
- }
+ final PsiClassType classType = (PsiClassType)type;
+ final PsiClass aClass = classType.resolve();
+ return (aClass != null) && aClass.isEnum();
+ }
/**
* Is the class an exception - extends Throwable (will check super).
@@ -553,14 +519,14 @@ public class PsiAdapter {
return InheritanceUtil.isInheritor(clazz, CommonClassNames.JAVA_LANG_THROWABLE);
}
- /**
+ /**
* Finds the public boolean equals(Object o) method.
*
* @param clazz the class.
* @return the method if it exists, null if not.
*/
@Nullable
- public PsiMethod findEqualsMethod(PsiClass clazz) {
+ public static PsiMethod findEqualsMethod(PsiClass clazz) {
PsiMethod[] methods = clazz.findMethodsByName("equals", false);
// is it public boolean equals(Object o)
@@ -571,13 +537,13 @@ public class PsiAdapter {
}
// must not be static
- if (method.hasModifierProperty(PsiModifier.STATIC)) {
- continue;
- }
+ if (method.hasModifierProperty(PsiModifier.STATIC)) {
+ continue;
+ }
// must have boolean as return type
PsiType returnType = method.getReturnType();
- if (returnType == null || !returnType.equalsToText("boolean")) {
+ if (!PsiType.BOOLEAN.equals(returnType)) {
continue;
}
@@ -607,7 +573,7 @@ public class PsiAdapter {
* @return the method if it exists, null if not.
*/
@Nullable
- public PsiMethod findHashCodeMethod(PsiClass clazz) {
+ public static PsiMethod findHashCodeMethod(PsiClass clazz) {
PsiMethod[] methods = clazz.findMethodsByName("hashCode", false);
// is it public int hashCode()
@@ -618,19 +584,19 @@ public class PsiAdapter {
}
// must not be static
- if (method.hasModifierProperty(PsiModifier.STATIC)) {
- continue;
- }
+ if (method.hasModifierProperty(PsiModifier.STATIC)) {
+ continue;
+ }
// must have int as return type
PsiType returnType = method.getReturnType();
- if (returnType == null || !returnType.equalsToText("int")) {
+ if (!PsiType.INT.equals(returnType)) {
continue;
}
// must not have a parameter
- PsiParameter[] parameters = method.getParameterList().getParameters();
- if (parameters.length != 0) {
+ PsiParameterList parameters = method.getParameterList();
+ if (parameters.getParametersCount() != 0) {
continue;
}
@@ -643,38 +609,14 @@ public class PsiAdapter {
}
/**
- * Adds/replaces the given annotation text to the method.
- *
- * @param factory element factory.
- * @param method the method the javadoc should be added/set to.
- * @param annotation the annotation as text.
- * @return the added annotation object
- * @throws IncorrectOperationException is thrown if error adding/replacing the javadoc comment.
- */
- public PsiAnnotation addAnnotationToMethod(JVMElementFactory factory, PsiMethod method, String annotation) throws IncorrectOperationException {
- PsiAnnotation ann = method.getModifierList().findAnnotation(annotation);
- if (ann == null) {
- // add new annotation
- ann = factory.createAnnotationFromText(annotation, method.getModifierList());
- PsiModifierList modifierList = method.getModifierList();
- modifierList.addBefore(ann, modifierList.getFirstChild());
- } else {
- PsiModifierList modifierList = method.getModifierList();
- modifierList.replace(ann); // already exist so replace
- }
-
- return ann;
- }
-
- /**
* Check if the given type against a FQ classname (assignable).
*
* @param factory IDEA factory
* @param type the type
* @param typeFQClassName the FQ classname to test against.
- * @return true if the given type is assigneable of FQ classname.
+ * @return true if the given type is assignable of FQ classname.
*/
- protected boolean isTypeOf(PsiElementFactory factory, PsiType type, String typeFQClassName) {
+ protected static boolean isTypeOf(PsiElementFactory factory, PsiType type, String typeFQClassName) {
// fix for IDEA where fields can have 'void' type and generate NPE.
if (isTypeOfVoid(type)) {
return false;
@@ -693,35 +635,12 @@ public class PsiAdapter {
}
/**
- * Get's the superclass.
- *
- * @param project IDEA project
- * @param clazz the class
- * @return the super, null if not found.
- */
- @Nullable
- public PsiClass getSuperClass(Project project, PsiClass clazz) {
- PsiReferenceList list = clazz.getExtendsList();
-
- // check if no superclass at all
- if (list == null || list.getReferencedTypes().length != 1) {
- return null;
- }
-
- // have superclass get it [0] is the index of the superclass (a class can not extend more than one class)
- GlobalSearchScope scope = list.getReferencedTypes()[0].getResolveScope();
- String classname = list.getReferencedTypes()[0].getCanonicalText();
-
- return JavaPsiFacade.getInstance(project).findClass(classname, scope);
- }
-
- /**
- * Get's the names the given class implements (not FQ names).
+ * Gets the names the given class implements (not FQ names).
*
* @param clazz the class
* @return the names.
*/
- public String[] getImplementsClassnames(PsiClass clazz) {
+ public static String[] getImplementsClassnames(PsiClass clazz) {
PsiClass[] interfaces = clazz.getInterfaces();
if (interfaces == null || interfaces.length == 0) {
@@ -743,41 +662,33 @@ public class PsiAdapter {
* @param type the type.
* @return true if primitive, false if not.
*/
- public boolean isPrimitiveType(PsiType type) {
+ public static boolean isPrimitiveType(PsiType type) {
return type instanceof PsiPrimitiveType;
}
- /**
- * Executes the given runable in IDEA command.
- *
- * @param project IDEA project
- * @param runable the runable task to exexute.
- */
- public void executeCommand(Project project, Runnable runable) {
- CommandProcessor.getInstance().executeCommand(project, runable, "GenerateToString", null);
- }
-
- /**
- * Add's the interface name to the class implementation list.
- *
- * @param project IDEA project
- * @param clazz the class
- * @param interfaceName the interface name the class should implement
- * @throws IncorrectOperationException is thrown by IDEA.
- */
- public void addImplements(Project project, PsiClass clazz, String interfaceName) throws IncorrectOperationException {
- JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
-
- // get the interface class
- PsiClass interfaceClass = facade.findClass(interfaceName, GlobalSearchScope.allScope(project));
-
- // if the interface exists add it as a reference in the implements list
- if (interfaceClass != null) {
- PsiJavaCodeReferenceElement ref = facade.getElementFactory().createClassReferenceElement(interfaceClass);
- PsiReferenceList list = clazz.getImplementsList();
- if (list != null) {
- list.add(ref);
- }
- }
- }
+ public static int getJavaVersion(PsiElement element) {
+ final LanguageLevel languageLevel = PsiUtil.getLanguageLevel(element);
+ int version = 0;
+ switch (languageLevel) {
+ case JDK_1_3:
+ version = 3;
+ break;
+ case JDK_1_4:
+ version = 4;
+ break;
+ case JDK_1_5:
+ version = 5;
+ break;
+ case JDK_1_6:
+ version = 6;
+ break;
+ case JDK_1_7:
+ version = 7;
+ break;
+ case JDK_1_8:
+ version = 8;
+ break;
+ }
+ return version;
+ }
}
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/psi/PsiAdapterFactory.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/psi/PsiAdapterFactory.java
deleted file mode 100644
index 3e797fa5bb44..000000000000
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/psi/PsiAdapterFactory.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright 2001-2007 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.jetbrains.generate.tostring.psi;
-
-/**
- * Factory to get a PsiAdapter class compatible with the correct version of IDEA.
- *
- * @see PsiAdapter
- */
-public class PsiAdapterFactory {
-
- private static PsiAdapter instance; // singleton instance
-
- private PsiAdapterFactory() {
- }
-
- /**
- * Gets the PsiAdapter
- *
- * @return the PsiAdapter used for the current version of IDEA.
- */
- public static PsiAdapter getPsiAdapter() {
- if (instance == null) {
- instance = new PsiAdapter();
- }
-
- return instance;
- }
-
-}
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultBuffer.vm b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultBuffer.vm
index 7c4f30828d8b..56ded32c0d74 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultBuffer.vm
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultBuffer.vm
@@ -1,11 +1,9 @@
-public String toString() {
-final StringBuffer sb = new StringBuffer();
-sb.append("$classname");
+public java.lang.String toString() {
+final java.lang.StringBuffer sb = new java.lang.StringBuffer("$classname{");
#set ($i = 0)
#foreach ($member in $members)
-#if (!$member.modifierStatic)
#if ($i == 0)
-sb.append("{##
+sb.append("##
#else
sb.append(", ##
#end
@@ -15,11 +13,17 @@ $member.name='")##
$member.name=")##
#end
#if ($member.primitiveArray)
-.append($member.name == null ? "null" : "");
-for (int i = 0; $member.name != null && i < $member.name .length; ++i)
- sb.append(i == 0 ? "" : ", ").append($member.name[$i]);
+;
+if ($member.name == null) ##
+sb.append("null");
+else {
+sb.append('[');
+for (int i = 0; i < $member.name .length; ++i)
+sb.append(i == 0 ? "" : ", ").append($member.name [i]);
+sb.append(']');
+}
#elseif ($member.objectArray)
-.append($member.name == null ? "null" : Arrays.asList($member.name).toString());
+.append($member.name == null ? "null" : java.util.Arrays.asList($member.name).toString());
#elseif ($member.string)
.append($member.accessor).append('\'');
#else
@@ -27,11 +31,6 @@ for (int i = 0; $member.name != null && i < $member.name .length; ++i)
#end
#set ($i = $i + 1)
#end
-#end
-#if ($members.size() == 0)
-sb.append("{}");
-#else
sb.append('}');
-#end
return sb.toString();
} \ No newline at end of file
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultBuilder.vm b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultBuilder.vm
index e424555dbf64..50c17175c568 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultBuilder.vm
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultBuilder.vm
@@ -1,11 +1,9 @@
-public String toString() {
-final StringBuilder sb = new StringBuilder();
-sb.append("$classname");
+public java.lang.String toString() {
+final java.lang.StringBuilder sb = new java.lang.StringBuilder("$classname{");
#set ($i = 0)
#foreach ($member in $members)
-#if (!$member.modifierStatic)
#if ($i == 0)
-sb.append("{##
+sb.append("##
#else
sb.append(", ##
#end
@@ -14,12 +12,8 @@ $member.name='")##
#else
$member.name=")##
#end
-#if ($member.primitiveArray)
-.append($member.name == null ? "null" : "");
-for (int i = 0; $member.name != null && i < $member.name .length; ++i)
- sb.append(i == 0 ? "" : ", ").append($member.name[$i]);
-#elseif ($member.objectArray)
-.append($member.name == null ? "null" : Arrays.asList($member.name).toString());
+#if ($member.primitiveArray || $member.objectArray)
+.append(java.util.Arrays.toString($member.name));
#elseif ($member.string)
.append($member.accessor).append('\'');
#else
@@ -27,11 +21,6 @@ for (int i = 0; $member.name != null && i < $member.name .length; ++i)
#end
#set ($i = $i + 1)
#end
-#end
-#if ($members.size() == 0)
-sb.append("{}");
-#else
sb.append('}');
-#end
return sb.toString();
} \ No newline at end of file
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultConcatMember.vm b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultConcatMember.vm
index 1073e84b1911..1449358785f7 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultConcatMember.vm
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultConcatMember.vm
@@ -1,4 +1,4 @@
-public String toString() {
+public java.lang.String toString() {
#if ( $members.size() > 0 )
#set ( $i = 0 )
return "$classname{" +
@@ -9,7 +9,13 @@ public String toString() {
", ##
#end
#if ( $member.objectArray )
-$member.name=" + ($member.accessor == null ? null : Arrays.asList($member.accessor)) +
+#if ($java_version < 5)
+$member.name=" + ($member.accessor == null ? null : java.util.Arrays.asList($member.accessor)) +
+#else
+$member.name=" + java.util.Arrays.toString($member.accessor) +
+#end
+#elseif ( $member.primitiveArray && $java_version >= 5)
+$member.name=" + java.util.Arrays.toString($member.accessor) +
#elseif ( $member.string )
$member.name='" + $member.accessor + '\'' +
#else
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultConcatMemberSuper.vm b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultConcatMemberSuper.vm
index e71975557a22..19ac22755954 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultConcatMemberSuper.vm
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultConcatMemberSuper.vm
@@ -1,4 +1,4 @@
-public String toString() {
+public java.lang.String toString() {
#if ( $members.size() > 0 )
#set ( $i = 0 )
return "$classname{" +
@@ -9,7 +9,13 @@ public String toString() {
", ##
#end
#if ( $member.objectArray )
-$member.name=" + ($member.accessor == null ? null : Arrays.asList($member.accessor)) +
+#if ($java_version < 5)
+$member.name=" + ($member.accessor == null ? null : java.util.Arrays.asList($member.accessor)) +
+#else
+$member.name=" + java.util.Arrays.toString($member.accessor) +
+#end
+#elseif ( $member.primitiveArray && $java_version >= 5)
+$member.name=" + java.util.Arrays.toString($member.accessor) +
#elseif ( $member.string )
$member.name='" + $member.accessor + '\'' +
#else
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultGuava.vm b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultGuava.vm
new file mode 100644
index 000000000000..18b6c1085f83
--- /dev/null
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultGuava.vm
@@ -0,0 +1,7 @@
+public java.lang.String toString() {
+return com.google.common.base.Objects.toStringHelper(this)
+#foreach ($member in $members)
+.add("$member.name", $member.accessor)
+#end
+.toString();
+}
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultObjectsToString.vm b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultObjectsToString.vm
new file mode 100644
index 000000000000..e8fdfdbb297f
--- /dev/null
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultObjectsToString.vm
@@ -0,0 +1,3 @@
+public java.lang.String toString() {
+return java.util.Objects.toString(this);
+}
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultToStringBuilder.vm b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultToStringBuilder.vm
index 6bb48b3b805d..ac952a4a694b 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultToStringBuilder.vm
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/DefaultToStringBuilder.vm
@@ -1,8 +1,7 @@
-public String toString() {
-#set ($autoImportPackages = "org.apache.commons.lang.builder.ToStringBuilder")
- return new ToStringBuilder(this).
+public java.lang.String toString() {
+ return new org.apache.commons.lang.builder.ToStringBuilder(this)
#foreach ($member in $members)
- append("$member.name", $member.accessor).
+ .append("$member.name", $member.accessor)
#end
- toString();
+ .toString();
} \ No newline at end of file
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/TemplateResource.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/TemplateResource.java
index 4b828c37c091..e2a847049381 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/TemplateResource.java
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/TemplateResource.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2001-2007 the original author or authors.
+ * Copyright 2001-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,9 +21,7 @@ import org.jetbrains.generate.tostring.util.StringUtil;
import java.io.Serializable;
/**
- * A template.
- * <p/>
- * A template contains the methody body and the filename of the resource where
+ * A template contains the method body and the filename of the resource where
* the text is stored.
*/
public class TemplateResource implements Serializable {
@@ -31,16 +29,6 @@ public class TemplateResource implements Serializable {
private String fileName = "";
private String template = "";
- /**
- * Constructor.
- *
- * @param fileName a template filename
- * @param template the template velocity body content
- */
- public TemplateResource(String fileName, String template) {
- this(fileName, template, false);
- }
-
public TemplateResource(String fileName, String template, boolean aDefault) {
isDefault = aDefault;
this.fileName = fileName;
@@ -133,7 +121,7 @@ public class TemplateResource implements Serializable {
continue;
}
signature.append(line);
- if (line.indexOf("{") > -1) {
+ if (line.indexOf('{') > -1) {
break;
}
}
@@ -144,7 +132,7 @@ public class TemplateResource implements Serializable {
}
/**
- * Get's the method that this template is for (toString)
+ * Gets the method that this template is for (toString)
*/
public String getTargetMethodName() {
String s = getMethodSignature();
@@ -171,13 +159,13 @@ public class TemplateResource implements Serializable {
public static boolean isValidTemplate(String template) {
template = template.trim();
- if (template.indexOf("{") == -1) {
+ if (template.indexOf('{') == -1) {
return false;
}
// ending } must be the last character
String s = template.trim();
- if (s.lastIndexOf("}") != s.length() - 1) {
+ if (s.lastIndexOf('}') != s.length() - 1) {
return false;
}
@@ -193,52 +181,7 @@ public class TemplateResource implements Serializable {
}
/**
- * Does the template use annotations?
- *
- * @return true if so, false if not.
- */
- public boolean hasAnnotations() {
- return getAnnotations() != null;
- }
-
- /**
- * Get's the annotations
- *
- * @return the annotation, null if does not have.
- */
- public String[] getAnnotations() {
- String signature = getMethodSignature();
- String javadoc = getJavaDoc();
- String annotations;
- if (javadoc != null) {
- annotations = StringUtil.middle(template, javadoc, signature);
- }
- else {
- annotations = StringUtil.before(template, signature);
- }
-
- if (StringUtil.isEmpty(annotations)) {
- return null;
- }
-
- if (annotations.indexOf("@") == -1) {
- return null;
- }
-
- // remove first and last \n
- annotations = annotations.trim();
- if (annotations.startsWith("\n")) {
- annotations = annotations.substring(1);
- }
- if (annotations.endsWith("\n")) {
- annotations = annotations.substring(0, annotations.length() - 1);
- }
-
- return annotations.split("\n");
- }
-
- /**
- * Important to return filename only as it is the displayname in the UI.
+ * Important to return filename only as it is the display name in the UI.
*
* @return filename for UI.
*/
@@ -250,15 +193,6 @@ public class TemplateResource implements Serializable {
return fileName;
}
- public void copyFrom(TemplateResource templateResource) {
- fileName = templateResource.getFileName();
- template = templateResource.getTemplate();
- }
-
- public void setName(String name) {
- fileName = name;
- }
-
@Override
public boolean equals(Object o) {
if (this == o) return true;
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/TemplateResourceLocator.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/TemplateResourceLocator.java
index ed475f23f84e..ef01c93a4221 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/TemplateResourceLocator.java
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/TemplateResourceLocator.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2001-2007 the original author or authors.
+ * Copyright 2001-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,53 +15,59 @@
*/
package org.jetbrains.generate.tostring.template;
+import com.intellij.openapi.util.io.FileUtil;
+import com.intellij.openapi.util.text.StringUtil;
import org.jetbrains.generate.tostring.exception.TemplateResourceException;
-import org.jetbrains.generate.tostring.util.FileUtil;
+import java.io.BufferedInputStream;
import java.io.IOException;
+import java.io.InputStreamReader;
/**
- * Resource locator for default method body templates and user specific.
- * <p/>
- * Will scan the 'tostring-plugin' folder of the IDEA plugins folder for additional templates.
+ * Resource locator for default method body templates.
*/
public class TemplateResourceLocator {
- /** Foldername for additional velocity body templates. The folder should be a subfolder in the IDEA/<i>plugins</i> folder. */
- public static final String FOLDER_NAME = "tostring-plugin";
- /** Filename for autosaving active template. */
- public static final String AUTOSAVE_ACTIVE_TEMPLATE_FILE_NAME = "__autosave_active";
+ private static final String DEFAULT_CONCAT = "/org/jetbrains/generate/tostring/template/DefaultConcatMember.vm";
+ private static final String DEFAULT_CONCAT_SUPER = "/org/jetbrains/generate/tostring/template/DefaultConcatMemberSuper.vm";
+ private static final String DEFAULT_BUFFER = "/org/jetbrains/generate/tostring/template/DefaultBuffer.vm";
+ private static final String DEFAULT_BUILDER = "/org/jetbrains/generate/tostring/template/DefaultBuilder.vm";
+ private static final String DEFAULT_OBJECTS = "/org/jetbrains/generate/tostring/template/DefaultObjectsToString.vm";
+ private static final String DEFAULT_TOSTRINGBUILDER = "/org/jetbrains/generate/tostring/template/DefaultToStringBuilder.vm";
+ private static final String DEFAULT_GUAVA = "/org/jetbrains/generate/tostring/template/DefaultGuava.vm";
- private static final String DEFAULT_CONCAT = "/org/jetbrains/generate/tostring/template/DefaultConcatMember.vm";
- private static final String DEFAULT_CONCAT_SUPER = "/org/jetbrains/generate/tostring/template/DefaultConcatMemberSuper.vm";
- private static final String DEFAULT_BUFFER = "/org/jetbrains/generate/tostring/template/DefaultBuffer.vm";
- private static final String DEFAULT_BUILDER = "/org/jetbrains/generate/tostring/template/DefaultBuilder.vm";
- private static final String DEFAULT_TOSTRINGBUILDER = "/org/jetbrains/generate/tostring/template/DefaultToStringBuilder.vm";
+ private TemplateResourceLocator() {}
- /**
- * Only static methods.
- */
- private TemplateResourceLocator() {
+ /**
+ * Get the default templates.
+ */
+ public static TemplateResource[] getDefaultTemplates() {
+ try {
+ return new TemplateResource[]{
+ new TemplateResource("String concat (+)", readFile(DEFAULT_CONCAT), true),
+ new TemplateResource("String concat (+) and super.toString()", readFile(DEFAULT_CONCAT_SUPER), true),
+ new TemplateResource("StringBuffer", readFile(DEFAULT_BUFFER), true),
+ new TemplateResource("StringBuilder (JDK 1.5)", readFile(DEFAULT_BUILDER), true),
+ new TemplateResource("Objects.toString() (JDK 1.7)", readFile(DEFAULT_OBJECTS), true),
+ new TemplateResource("ToStringBuilder (Apache Commons)", readFile(DEFAULT_TOSTRINGBUILDER), true),
+ new TemplateResource("Objects.toStringHelper (Guava)", readFile(DEFAULT_GUAVA), true)
+ };
}
-
-
- /**
- * Get the default templates.
- */
- public static TemplateResource[] getDefaultTemplates() {
- try {
- TemplateResource tr1 = new TemplateResource("String concat (+)", FileUtil.readFile(DEFAULT_CONCAT), true);
- TemplateResource tr2 = new TemplateResource("String concat (+) and super.toString()", FileUtil.readFile(DEFAULT_CONCAT_SUPER), true);
- TemplateResource tr3 = new TemplateResource("StringBuffer", FileUtil.readFile(DEFAULT_BUFFER), true);
- TemplateResource tr4 = new TemplateResource("StringBuilder (JDK 1.5)", FileUtil.readFile(DEFAULT_BUILDER), true);
- TemplateResource tr5 = new TemplateResource("ToStringBuilder (Apache Commons)", FileUtil.readFile(DEFAULT_TOSTRINGBUILDER), true);
-
- return new TemplateResource[]{tr1, tr2, tr3, tr4, tr5};
-
- } catch (IOException e) {
- throw new TemplateResourceException("Error loading default templates", e);
- }
+ catch (IOException e) {
+ throw new TemplateResourceException("Error loading default templates", e);
}
+ }
-
+ /**
+ * Reads the content of the resource and return it as a String.
+ * <p/>Uses the class loader that loaded this class to find the resource in its classpath.
+ *
+ * @param resource the resource name. Will lookup using the classpath.
+ * @return the content if the resource
+ * @throws IOException error reading the file.
+ */
+ private static String readFile(String resource) throws IOException {
+ BufferedInputStream in = new BufferedInputStream(TemplateResourceLocator.class.getResourceAsStream(resource));
+ return StringUtil.convertLineSeparators(FileUtil.loadTextAndClose(new InputStreamReader(in, "UTF-8")));
+ }
}
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/util/FileUtil.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/util/FileUtil.java
deleted file mode 100644
index fc4a179ef279..000000000000
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/util/FileUtil.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright 2001-2007 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.jetbrains.generate.tostring.util;
-
-import com.intellij.openapi.util.text.StringUtil;
-
-import java.io.BufferedInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * Utility methods for file IO.
- */
-public class FileUtil {
-
- /**
- * Private constructor, as only static methods allowed.
- */
- private FileUtil() {
- }
-
- /**
- * Reads the content of the resource and return it as a String.
- * <p/>Uses the classloader that loaded this class to find the resource in its classpath.
- *
- * @param resource the resouce name. Will lookup using the classpath.
- * @return the content if the resource
- * @throws IOException error reading the file.
- */
- public static String readFile(String resource) throws IOException {
- BufferedInputStream in = new BufferedInputStream(FileUtil.class.getResourceAsStream(resource));
- return readFileContent(in);
- }
-
- /**
- * Reads the files content and return it as a String.
- *
- * @param in the file input stream.
- * @return the file content.
- * @throws IOException error reading the file.
- */
- public static String readFileContent(InputStream in) throws IOException {
- StringBuffer buf = new StringBuffer();
- for (int i = in.read(); i != -1; i = in.read()) {
- buf.append((char) i);
- }
- return StringUtil.convertLineSeparators(buf.toString());
- }
-}
diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/view/ConfigUI.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/view/ConfigUI.java
index e66f402d60d7..fc5979d34a46 100644
--- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/view/ConfigUI.java
+++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/view/ConfigUI.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2001-2007 the original author or authors.
+ * Copyright 2001-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,27 +15,20 @@
*/
package org.jetbrains.generate.tostring.view;
-import com.intellij.openapi.ui.Messages;
+import com.intellij.openapi.project.Project;
import com.intellij.ui.IdeBorderFactory;
-import org.apache.velocity.VelocityContext;
-import org.apache.velocity.app.VelocityEngine;
-import org.apache.velocity.exception.ParseErrorException;
+import com.intellij.ui.LanguageTextField;
+import org.intellij.lang.regexp.RegExpLanguage;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.generate.tostring.config.Config;
-import org.jetbrains.generate.tostring.config.DuplicatonPolicy;
+import org.jetbrains.generate.tostring.config.DuplicationPolicy;
import org.jetbrains.generate.tostring.config.InsertWhere;
import org.jetbrains.generate.tostring.config.PolicyOptions;
-import org.jetbrains.generate.tostring.exception.PluginException;
-import org.jetbrains.generate.tostring.template.TemplateResource;
-import org.jetbrains.generate.tostring.velocity.VelocityFactory;
import javax.swing.*;
-import javax.swing.border.Border;
-import javax.swing.border.EtchedBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
-import java.io.StringWriter;
/**
* Configuration User Interface.
@@ -43,36 +36,38 @@ import java.io.StringWriter;
* The configuration is in the menu <b>File - Settings - GenerateToString</b>
*/
public class ConfigUI extends JPanel {
- private final Border etched = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
- private final JCheckBox fullyQualifiedName = new JCheckBox("Use fully qualified classname in code generation ($classname)");
+ private final JCheckBox fullyQualifiedName = new JCheckBox("Use fully qualified class name in code generation ($classname)");
private final JCheckBox enableMethods = new JCheckBox("Enable getters in code generation ($methods)");
private final JCheckBox moveCaretToMethod = new JCheckBox("Move caret to generated method");
private JRadioButton[] initialValueForReplaceDialog;
private JRadioButton[] initialValueForNewMethodDialog;
- private final JCheckBox filterConstant = new JCheckBox("Exclude all constant fields");
- private final JCheckBox filterEnum = new JCheckBox("Exclude all enum fields");
- private final JCheckBox filterStatic = new JCheckBox("Exclude all static fields");
- private final JCheckBox filterTransient = new JCheckBox("Exclude all transient fields");
- private final JCheckBox filterLoggers = new JCheckBox("Exclude all logger fields (Log4j, JDK Logging, Jakarta Commons Logging)");
- private final JTextField filterFieldName = new JTextField();
- private final JTextField filterFieldType = new JTextField();
- private final JTextField filterMethodName = new JTextField();
- private final JTextField filterMethodType = new JTextField();
+ private final JCheckBox filterConstant = new JCheckBox("Exclude constant fields");
+ private final JCheckBox filterEnum = new JCheckBox("Exclude enum fields");
+ private final JCheckBox filterStatic = new JCheckBox("Exclude static fields");
+ private final JCheckBox filterTransient = new JCheckBox("Exclude transient fields");
+ private final JCheckBox filterLoggers = new JCheckBox("Exclude logger fields (Log4j, JDK Logging, Jakarta Commons Logging)");
+ private final LanguageTextField filterFieldName;
+ private final LanguageTextField filterFieldType;
+ private final LanguageTextField filterMethodName;
+ private final LanguageTextField filterMethodType;
private final JComboBox sortElementsComboBox = new JComboBox();
private final JCheckBox sortElements = new JCheckBox("Sort elements");
- private final JCheckBox autoAddImplementsSerializable = new JCheckBox("Automatic add implements java.io.Serializable");
-
/**
* Constructor.
*
* @param config Configuration for this UI to display.
+ * @param project
*/
- public ConfigUI(Config config) {
+ public ConfigUI(Config config, Project project) {
super(new BorderLayout());
+ filterFieldName = new LanguageTextField(RegExpLanguage.INSTANCE, project, config.getFilterFieldName());
+ filterFieldType = new LanguageTextField(RegExpLanguage.INSTANCE, project, config.getFilterFieldType());
+ filterMethodName = new LanguageTextField(RegExpLanguage.INSTANCE, project, config.getFilterMethodName());
+ filterMethodType = new LanguageTextField(RegExpLanguage.INSTANCE, project, config.getFilterMethodType());
init();
setConfig(config);
}
@@ -95,8 +90,7 @@ public class ConfigUI extends JPanel {
*/
private JPanel initSettingPanel() {
GridBagConstraints constraint = new GridBagConstraints();
- JPanel outer = new JPanel();
- outer.setLayout(new GridBagLayout());
+ JPanel outer = new JPanel(new GridBagLayout());
// UI Layout - Settings
JPanel panel = new JPanel();
@@ -126,10 +120,12 @@ public class ConfigUI extends JPanel {
constraint.fill = GridBagConstraints.BOTH;
constraint.gridx = 0;
constraint.gridy = 0;
+ constraint.insets.left = 5;
+ constraint.insets.right = 5;
outer.add(panel, constraint);
// UI Layout - Conflict Resolution
- DuplicatonPolicy[] options = PolicyOptions.getConflictOptions();
+ DuplicationPolicy[] options = PolicyOptions.getConflictOptions();
initialValueForReplaceDialog = new JRadioButton[options.length];
ButtonGroup selection = new ButtonGroup();
for (int i = 0; i < options.length; i++) {
@@ -195,7 +191,7 @@ public class ConfigUI extends JPanel {
filterFieldName.setMinimumSize(new Dimension(100, 20)); // avoid input field to small
panel.add(innerPanel);
innerPanel = Box.createHorizontalBox();
- innerPanel.add(new JLabel("Exclude fields by typename (reg exp)"));
+ innerPanel.add(new JLabel("Exclude fields by type name (reg exp)"));
innerPanel.add(Box.createHorizontalStrut(3));
innerPanel.add(filterFieldType);
filterFieldType.setMinimumSize(new Dimension(100, 20)); // avoid input field to small
@@ -207,7 +203,7 @@ public class ConfigUI extends JPanel {
filterMethodName.setMinimumSize(new Dimension(100, 20)); // avoid input field to small
panel.add(innerPanel);
innerPanel = Box.createHorizontalBox();
- innerPanel.add(new JLabel("Exclude methods by return typename (reg exp)"));
+ innerPanel.add(new JLabel("Exclude methods by return type name (reg exp)"));
innerPanel.add(Box.createHorizontalStrut(3));
innerPanel.add(filterMethodType);
filterMethodType.setMinimumSize(new Dimension(100, 20)); // avoid input field to small
@@ -226,7 +222,7 @@ public class ConfigUI extends JPanel {
*/
public final void setConfig(Config config) {
fullyQualifiedName.setSelected(config.isUseFullyQualifiedName());
- DuplicatonPolicy option = config.getReplaceDialogInitialOption();
+ DuplicationPolicy option = config.getReplaceDialogInitialOption();
for (JRadioButton anInitialValueForReplaceDialog : initialValueForReplaceDialog) {
if (anInitialValueForReplaceDialog.getText().equals(option.toString())) {
anInitialValueForReplaceDialog.setSelected(true);
@@ -245,12 +241,7 @@ public class ConfigUI extends JPanel {
filterStatic.setSelected(config.isFilterStaticModifier());
filterTransient.setSelected(config.isFilterTransientModifier());
filterLoggers.setSelected(config.isFilterLoggers());
- filterFieldName.setText(config.getFilterFieldName());
- filterFieldType.setText(config.getFilterFieldType());
- filterMethodName.setText(config.getFilterMethodName());
- filterMethodType.setText(config.getFilterMethodType());
- autoAddImplementsSerializable.setSelected(config.isAddImplementSerializable());
enableMethods.setSelected(config.isEnableMethods());
moveCaretToMethod.setSelected(config.isJumpToMethod());
@@ -301,7 +292,6 @@ public class ConfigUI extends JPanel {
config.setFilterMethodName(emptyToNull(filterMethodName.getText()));
config.setFilterMethodType(emptyToNull(filterMethodType.getText()));
- config.setAddImplementSerializable(autoAddImplementsSerializable.isSelected());
config.setEnableMethods(enableMethods.isSelected());
config.setJumpToMethod(moveCaretToMethod.isSelected());
@@ -320,9 +310,9 @@ public class ConfigUI extends JPanel {
* Action for the options for the conflict resolution policy
*/
private static class ConflictResolutionOptionAction extends AbstractAction {
- public final DuplicatonPolicy option;
+ public final DuplicationPolicy option;
- ConflictResolutionOptionAction(DuplicatonPolicy option) {
+ ConflictResolutionOptionAction(DuplicationPolicy option) {
super(option.toString());
this.option = option;
}
@@ -355,39 +345,4 @@ public class ConfigUI extends JPanel {
sortElementsComboBox.setEnabled(sortElements.isSelected());
}
}
-
- /**
- * Action listener for user clicking syntax check
- */
- private class OnSyntaxCheck implements ActionListener {
- private final JTextArea methodBody = new JTextArea();
- public void actionPerformed(ActionEvent event) {
-
- // validate template first
- if (!TemplateResource.isValidTemplate(methodBody.getText())) {
- Messages.showWarningDialog("The template is incompatible with this version of the plugin.", "Incompatible Template");
- return;
- }
-
- // okay let veloicty do it's syntax check
- try {
- StringWriter sw = new StringWriter();
- VelocityContext vc = new VelocityContext();
-
- // velocity
- VelocityEngine velocity = VelocityFactory.getVelocityEngine();
- velocity.evaluate(vc, sw, "org.intellij.idea.plugin.tostring.view.ConfigUI$OnSyntaxCheck", methodBody.getText());
-
- // no errors
- Messages.showMessageDialog("Syntax check complete - no errors found", "Syntax Check", Messages.getInformationIcon());
-
- } catch (ParseErrorException e) {
- // Syntax Error - display to user
- Messages.showMessageDialog("Syntax Error:\n" + e.getMessage(), "Syntax Error", Messages.getErrorIcon());
- } catch (Exception e) {
- throw new PluginException("Error syntax checking template", e);
- }
- }
- }
-
}
diff --git a/plugins/generate-tostring/testSrc/org/jetbrains/generate/tostring/inspection/FieldNotUsedInToStringInspectionTest.java b/plugins/generate-tostring/testSrc/org/jetbrains/generate/tostring/inspection/FieldNotUsedInToStringInspectionTest.java
new file mode 100644
index 000000000000..0fbc07976950
--- /dev/null
+++ b/plugins/generate-tostring/testSrc/org/jetbrains/generate/tostring/inspection/FieldNotUsedInToStringInspectionTest.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright 2000-2013 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.jetbrains.generate.tostring.inspection;
+
+import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase;
+import org.jetbrains.annotations.NonNls;
+
+/**
+ * @author Bas Leijdekkers
+ */
+public class FieldNotUsedInToStringInspectionTest extends LightCodeInsightFixtureTestCase {
+
+ public void testBasic() {
+ doTest("class X {" +
+ " private int <warning descr=\"Field 'i' is not used in 'toString()' method\">i</warning> = 0;" +
+ " public String toString() {" +
+ " return null;" +
+ " }" +
+ "}");
+ }
+
+ public void testGetterUsed() {
+ doTest("public class ToStringTest3 {" +
+ "" +
+ " int number;" +
+ "" +
+ " public int getNumber() {" +
+ " return number;" +
+ " }" +
+ "" +
+ " @Override" +
+ " public String toString() {" +
+ " final StringBuilder sb = new StringBuilder();" +
+ " sb.append(\"ToStringTest3\");" +
+ " sb.append(\"{number=\").append(getNumber());" +
+ " sb.append('}');" +
+ " return sb.toString();" +
+ " }" +
+ "}");
+ }
+
+ public void testReflectionUsed() {
+ myFixture.addClass("package java.util;" +
+ "public class Objects {" +
+ " public static String toString(Object object) {" +
+ " return null;" +
+ " }" +
+ "}");
+ doTest("import java.util.Objects;" +
+ "class X {" +
+ " private int i = 0;" +
+ " " +
+ " public String toString() {" +
+ " return Objects.toString(this);" +
+ " }" +
+ "}");
+ }
+
+ private void doTest(@NonNls String text) {
+ myFixture.configureByText("X.java", text);
+ myFixture.enableInspections(new FieldNotUsedInToStringInspection());
+ myFixture.testHighlighting(true, false, false);
+ }
+}