2 * Copyright 2000-2009 JetBrains s.r.o.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
21 package com.intellij.refactoring.replaceConstructorWithBuilder;
23 import com.intellij.openapi.actionSystem.DataContext;
24 import com.intellij.openapi.editor.Editor;
25 import com.intellij.openapi.project.Project;
26 import com.intellij.psi.*;
27 import com.intellij.psi.util.PsiTreeUtil;
28 import com.intellij.refactoring.HelpID;
29 import com.intellij.refactoring.RefactoringActionHandler;
30 import com.intellij.refactoring.util.CommonRefactoringUtil;
31 import org.jetbrains.annotations.NotNull;
32 import org.jetbrains.annotations.Nullable;
34 public class ReplaceConstructorWithBuilderHandler implements RefactoringActionHandler {
35 public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file, final DataContext dataContext) {
36 final int offset = editor.getCaretModel().getOffset();
37 final PsiElement element = file.findElementAt(offset);
38 final PsiClass psiClass = getParentNamedClass(element);
39 if (psiClass == null) {
40 showErrorMessage("The caret should be positioned inside a class which constructors are to be replaced with builder.", project, editor);
44 final PsiMethod[] constructors = psiClass.getConstructors();
45 if (constructors.length == 0) {
46 showErrorMessage("Current class doesn't have constructors to replace with builder.", project, editor);
50 new ReplaceConstructorWithBuilderDialog(project, constructors).show();
54 public static PsiClass getParentNamedClass(PsiElement element) {
55 final PsiClass psiClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
56 if (psiClass instanceof PsiAnonymousClass) {
57 return getParentNamedClass(psiClass);
62 public void invoke(@NotNull final Project project, @NotNull final PsiElement[] elements, final DataContext dataContext) {
63 throw new UnsupportedOperationException();
66 private static void showErrorMessage(String message, Project project, Editor editor) {
67 CommonRefactoringUtil.showErrorHint(project, editor, message, ReplaceConstructorWithBuilderProcessor.REFACTORING_NAME, HelpID.REPLACE_CONSTRUCTOR_WITH_BUILDER);