Search in sources :

Example 1 with IncorrectOperationException

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

the class GroovyGenerateEqualsHelper method createEquals.

private PsiMethod createEquals() throws IncorrectOperationException {
    final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(myProject);
    String[] nameSuggestions = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, PsiType.getJavaLangObject(myClass.getManager(), myClass.getResolveScope())).names;
    final String objectBaseName = nameSuggestions.length > 0 ? nameSuggestions[0] : BASE_OBJECT_PARAMETER_NAME;
    myParameterName = getUniqueLocalVarName(objectBaseName, myEqualsFields);
    //todo isApplicable it
    final PsiType classType = TypesUtil.createType(myClass.getQualifiedName(), myClass.getContext());
    nameSuggestions = codeStyleManager.suggestVariableName(VariableKind.LOCAL_VARIABLE, null, null, classType).names;
    String instanceBaseName = nameSuggestions.length > 0 && nameSuggestions[0].length() < 10 ? nameSuggestions[0] : BASE_OBJECT_LOCAL_NAME;
    myClassInstanceName = getUniqueLocalVarName(instanceBaseName, myEqualsFields);
    @NonNls StringBuffer buffer = new StringBuffer();
    buffer.append("boolean equals(").append(myParameterName).append(") {\n");
    addEqualsPrologue(buffer);
    if (myEqualsFields.length > 0) {
        addClassInstance(buffer);
        ArrayList<PsiField> equalsFields = new ArrayList<>();
        ContainerUtil.addAll(equalsFields, myEqualsFields);
        Collections.sort(equalsFields, EqualsFieldsComparator.INSTANCE);
        for (PsiField field : equalsFields) {
            if (!field.hasModifierProperty(PsiModifier.STATIC)) {
                final PsiType type = field.getType();
                if (type instanceof PsiArrayType) {
                    addArrayEquals(buffer, field);
                } else if (type instanceof PsiPrimitiveType) {
                    if (PsiType.DOUBLE.equals(type) || PsiType.FLOAT.equals(type)) {
                        addDoubleFieldComparison(buffer, field);
                    } else {
                        addFieldComparison(buffer, field);
                    }
                } else {
                    if (type instanceof PsiClassType) {
                        final PsiClass aClass = ((PsiClassType) type).resolve();
                        if (aClass != null && aClass.isEnum()) {
                            addFieldComparison(buffer, field);
                            continue;
                        }
                    }
                    addFieldComparison(buffer, field);
                }
            }
        }
    }
    buffer.append("\nreturn true\n}");
    GrMethod result = myFactory.createMethodFromText(buffer.toString());
    final PsiParameter parameter = result.getParameterList().getParameters()[0];
    PsiUtil.setModifierProperty(parameter, PsiModifier.FINAL, CodeStyleSettingsManager.getSettings(myProject).GENERATE_FINAL_PARAMETERS);
    try {
        result = ((GrMethod) CodeStyleManager.getInstance(myProject).reformat(result));
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
    return result;
}
Also used : NonNls(org.jetbrains.annotations.NonNls) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Example 2 with IncorrectOperationException

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

the class GroovyGeneratePropertyMissingHandler method chooseOriginalMembers.

@Nullable
@Override
protected ClassMember[] chooseOriginalMembers(PsiClass aClass, Project project) {
    final PsiMethod[] missings = aClass.findMethodsByName("propertyMissing", true);
    PsiMethod getter = null;
    PsiMethod setter = null;
    for (PsiMethod missing : missings) {
        final PsiParameter[] parameters = missing.getParameterList().getParameters();
        if (parameters.length == 1) {
            if (isNameParam(parameters[0])) {
                getter = missing;
            }
        } else if (parameters.length == 2) {
            if (isNameParam(parameters[0])) {
                setter = missing;
            }
        }
    }
    if (setter != null && getter != null) {
        String text = GroovyCodeInsightBundle.message("generate.property.missing.already.defined.warning");
        if (Messages.showYesNoDialog(project, text, GroovyCodeInsightBundle.message("generate.property.missing.already.defined.title"), Messages.getQuestionIcon()) == Messages.YES) {
            final PsiMethod finalGetter = getter;
            final PsiMethod finalSetter = setter;
            if (!ApplicationManager.getApplication().runWriteAction(new Computable<Boolean>() {

                @Override
                public Boolean compute() {
                    try {
                        finalSetter.delete();
                        finalGetter.delete();
                        return Boolean.TRUE;
                    } catch (IncorrectOperationException e) {
                        LOG.error(e);
                        return Boolean.FALSE;
                    }
                }
            }).booleanValue()) {
                return null;
            }
        } else {
            return null;
        }
    }
    return new ClassMember[1];
}
Also used : PsiParameter(com.intellij.psi.PsiParameter) PsiMethod(com.intellij.psi.PsiMethod) IncorrectOperationException(com.intellij.util.IncorrectOperationException) ClassMember(com.intellij.codeInsight.generation.ClassMember) Nullable(org.jetbrains.annotations.Nullable)

Example 3 with IncorrectOperationException

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

the class CreateClassActionBase method createClassByType.

@Nullable
public static GrTypeDefinition createClassByType(@NotNull final PsiDirectory directory, @NotNull final String name, @NotNull final PsiManager manager, @Nullable final PsiElement contextElement, @NotNull final String templateName, boolean allowReformatting) {
    return WriteAction.compute(() -> {
        try {
            GrTypeDefinition targetClass = null;
            try {
                PsiFile file = GroovyTemplatesFactory.createFromTemplate(directory, name, name + ".groovy", templateName, allowReformatting);
                for (PsiElement element : file.getChildren()) {
                    if (element instanceof GrTypeDefinition) {
                        targetClass = ((GrTypeDefinition) element);
                        break;
                    }
                }
                if (targetClass == null) {
                    throw new IncorrectOperationException(GroovyBundle.message("no.class.in.file.template"));
                }
            } catch (final IncorrectOperationException e) {
                ApplicationManager.getApplication().invokeLater(() -> Messages.showErrorDialog(GroovyBundle.message("cannot.create.class.error.text", name, e.getLocalizedMessage()), GroovyBundle.message("cannot.create.class.error.title")));
                return null;
            }
            PsiModifierList modifiers = targetClass.getModifierList();
            if (contextElement != null && !JavaPsiFacade.getInstance(manager.getProject()).getResolveHelper().isAccessible(targetClass, contextElement, null) && modifiers != null) {
                modifiers.setModifierProperty(PsiModifier.PUBLIC, true);
            }
            return targetClass;
        } catch (IncorrectOperationException e) {
            LOG.error(e);
            return null;
        }
    });
}
Also used : GrTypeDefinition(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Nullable(org.jetbrains.annotations.Nullable)

Example 4 with IncorrectOperationException

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

the class YAMLUtil method rename.

//public static void removeI18nRecord(final YAMLFile file, final String[] key){
//  PsiElement element = getQualifiedKeyInFile(file, key);
//  while (element != null){
//    final PsiElement parent = element.getParent();
//    if (parent instanceof YAMLDocument) {
//      ((YAMLKeyValue)element).getValue().delete();
//      return;
//    }
//    if (parent instanceof YAMLCompoundValue) {
//      if (((YAMLCompoundValue)parent).getYAMLElements().size() > 1) {
//        element.delete();
//        return;
//      }
//    }
//    element = parent;
//  }
//}
public static PsiElement rename(final YAMLKeyValue element, final String newName) {
    if (newName.contains(".")) {
        throw new IncorrectOperationException(YAMLBundle.message("rename.wrong.name"));
    }
    if (newName.equals(element.getName())) {
        throw new IncorrectOperationException(YAMLBundle.message("rename.same.name"));
    }
    final YAMLKeyValue topKeyValue = YAMLElementGenerator.getInstance(element.getProject()).createYamlKeyValue(newName, "Foo");
    final PsiElement key = element.getKey();
    if (key == null || topKeyValue.getKey() == null) {
        throw new IllegalStateException();
    }
    key.replace(topKeyValue.getKey());
    return element;
}
Also used : IncorrectOperationException(com.intellij.util.IncorrectOperationException) PsiElement(com.intellij.psi.PsiElement)

Example 5 with IncorrectOperationException

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

the class PyMakeFunctionTopLevelTest method runRefactoring.

private void runRefactoring(@Nullable String destination, @Nullable String errorMessage) {
    final PyFunction function = assertInstanceOf(myFixture.getElementAtCaret(), PyFunction.class);
    if (destination == null) {
        destination = PyPsiUtils.getContainingFilePath(function);
    } else {
        final VirtualFile srcRoot = ModuleRootManager.getInstance(myFixture.getModule()).getSourceRoots()[0];
        destination = FileUtil.join(srcRoot.getPath(), destination);
    }
    assertNotNull(destination);
    final String finalDestination = destination;
    try {
        WriteCommandAction.runWriteCommandAction(myFixture.getProject(), () -> {
            if (function.getContainingClass() != null) {
                new PyMakeMethodTopLevelProcessor(function, finalDestination).run();
            } else {
                new PyMakeLocalFunctionTopLevelProcessor(function, finalDestination).run();
            }
        });
    } catch (IncorrectOperationException e) {
        if (errorMessage == null) {
            fail("Refactoring failed unexpectedly with message: " + e.getMessage());
        }
        assertEquals(errorMessage, e.getMessage());
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) PyMakeLocalFunctionTopLevelProcessor(com.jetbrains.python.refactoring.move.makeFunctionTopLevel.PyMakeLocalFunctionTopLevelProcessor) PyFunction(com.jetbrains.python.psi.PyFunction) PyMakeMethodTopLevelProcessor(com.jetbrains.python.refactoring.move.makeFunctionTopLevel.PyMakeMethodTopLevelProcessor) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Aggregations

IncorrectOperationException (com.intellij.util.IncorrectOperationException)494 Project (com.intellij.openapi.project.Project)91 NotNull (org.jetbrains.annotations.NotNull)91 PsiElement (com.intellij.psi.PsiElement)55 Nullable (org.jetbrains.annotations.Nullable)55 TextRange (com.intellij.openapi.util.TextRange)43 VirtualFile (com.intellij.openapi.vfs.VirtualFile)39 Document (com.intellij.openapi.editor.Document)38 PsiFile (com.intellij.psi.PsiFile)38 ASTNode (com.intellij.lang.ASTNode)35 Editor (com.intellij.openapi.editor.Editor)33 ArrayList (java.util.ArrayList)32 NonNls (org.jetbrains.annotations.NonNls)32 UsageInfo (com.intellij.usageView.UsageInfo)31 IOException (java.io.IOException)27 JavaCodeStyleManager (com.intellij.psi.codeStyle.JavaCodeStyleManager)24 GroovyPsiElementFactory (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory)21 XmlTag (com.intellij.psi.xml.XmlTag)20 CodeStyleManager (com.intellij.psi.codeStyle.CodeStyleManager)19 Module (com.intellij.openapi.module.Module)18