protected void invokeImpl(final PsiClass targetClass) {
    final Project project = myConstructorCall.getProject();
    PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory();

    try {
      PsiMethod constructor = (PsiMethod) targetClass.add(elementFactory.createConstructor());

      final PsiFile file = targetClass.getContainingFile();
      TemplateBuilderImpl templateBuilder = new TemplateBuilderImpl(constructor);
      CreateFromUsageUtils.setupMethodParameters(
          constructor,
          templateBuilder,
          myConstructorCall.getArgumentList(),
          getTargetSubstitutor(myConstructorCall));
      final PsiMethod superConstructor =
          CreateClassFromNewFix.setupSuperCall(targetClass, constructor, templateBuilder);

      constructor = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(constructor);
      Template template = templateBuilder.buildTemplate();
      if (targetClass == null) return;
      final Editor editor = positionCursor(project, targetClass.getContainingFile(), targetClass);
      final TextRange textRange = constructor.getTextRange();
      editor.getDocument().deleteString(textRange.getStartOffset(), textRange.getEndOffset());
      editor.getCaretModel().moveToOffset(textRange.getStartOffset());

      startTemplate(
          editor,
          template,
          project,
          new TemplateEditingAdapter() {
            public void templateFinished(Template template, boolean brokenOff) {
              ApplicationManager.getApplication()
                  .runWriteAction(
                      new Runnable() {
                        public void run() {
                          try {
                            PsiDocumentManager.getInstance(project)
                                .commitDocument(editor.getDocument());
                            final int offset = editor.getCaretModel().getOffset();
                            PsiMethod constructor =
                                PsiTreeUtil.findElementOfClassAtOffset(
                                    file, offset, PsiMethod.class, false);
                            if (superConstructor == null) {
                              CreateFromUsageUtils.setupMethodBody(constructor);
                            } else {
                              OverrideImplementUtil.setupMethodBody(
                                  constructor, superConstructor, targetClass);
                            }
                            CreateFromUsageUtils.setupEditor(constructor, editor);
                          } catch (IncorrectOperationException e) {
                            LOG.error(e);
                          }
                        }
                      });
            }
          });
    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }
  @Override
  protected boolean preprocessUsages(@NotNull final Ref<UsageInfo[]> refUsages) {
    final MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>();
    myExtractEnumProcessor.findEnumConstantConflicts(refUsages);
    if (!DestinationFolderComboBox.isAccessible(
        myProject,
        sourceClass.getContainingFile().getVirtualFile(),
        myClass.getContainingFile().getContainingDirectory().getVirtualFile())) {
      conflicts.putValue(
          sourceClass,
          "Extracted class won't be accessible in "
              + RefactoringUIUtil.getDescription(sourceClass, true));
    }
    ApplicationManager.getApplication()
        .runWriteAction(
            new Runnable() {
              public void run() {
                myClass.delete();
              }
            });
    final Project project = sourceClass.getProject();
    final GlobalSearchScope scope = GlobalSearchScope.allScope(project);
    final PsiClass existingClass =
        JavaPsiFacade.getInstance(project).findClass(getQualifiedName(), scope);
    if (existingClass != null) {
      conflicts.putValue(
          existingClass,
          RefactorJBundle.message("cannot.perform.the.refactoring")
              + RefactorJBundle.message("there.already.exists.a.class.with.the.chosen.name"));
    }

    if (!myGenerateAccessors) {
      calculateInitializersConflicts(conflicts);
      final NecessaryAccessorsVisitor visitor = checkNecessaryGettersSetters4ExtractedClass();
      final NecessaryAccessorsVisitor srcVisitor = checkNecessaryGettersSetters4SourceClass();
      final Set<PsiField> fieldsNeedingGetter = new LinkedHashSet<PsiField>();
      fieldsNeedingGetter.addAll(visitor.getFieldsNeedingGetter());
      fieldsNeedingGetter.addAll(srcVisitor.getFieldsNeedingGetter());
      for (PsiField field : fieldsNeedingGetter) {
        conflicts.putValue(field, "Field \'" + field.getName() + "\' needs getter");
      }
      final Set<PsiField> fieldsNeedingSetter = new LinkedHashSet<PsiField>();
      fieldsNeedingSetter.addAll(visitor.getFieldsNeedingSetter());
      fieldsNeedingSetter.addAll(srcVisitor.getFieldsNeedingSetter());
      for (PsiField field : fieldsNeedingSetter) {
        conflicts.putValue(field, "Field \'" + field.getName() + "\' needs setter");
      }
    }
    checkConflicts(refUsages, conflicts);
    return showConflicts(conflicts, refUsages.get());
  }
  @Override
  public PsiFile getContainingFile() {
    final PsiClass psiClass = getContainingClassElement();
    if (psiClass == null) return null;

    return psiClass.getContainingFile();
  }
  public void execute(final String line, final int textEndOffset) {
    myResult = null;
    myInfo = parseExceptionLine(line);
    if (myInfo == null) {
      return;
    }

    myMethod = myInfo.getSecond().substring(line);

    final int lparenthIndex = myInfo.third.getStartOffset();
    final int rparenthIndex = myInfo.third.getEndOffset();
    final String fileAndLine = line.substring(lparenthIndex + 1, rparenthIndex).trim();

    final int colonIndex = fileAndLine.lastIndexOf(':');
    if (colonIndex < 0) return;

    final String lineString = fileAndLine.substring(colonIndex + 1);
    try {
      final int lineNumber = Integer.parseInt(lineString);
      myClass = findPositionClass(line);
      myFile =
          myClass == null ? null : (PsiFile) myClass.getContainingFile().getNavigationElement();
      if (myFile == null) {
        // try find the file with the required name
        PsiFile[] files =
            PsiShortNamesCache.getInstance(myProject)
                .getFilesByName(fileAndLine.substring(0, colonIndex).trim());
        if (files.length > 0) {
          myFile = files[0];
        }
      }
      if (myFile == null) return;

      /*
       IDEADEV-4976: Some scramblers put something like SourceFile mock instead of real class name.
      final String filePath = fileAndLine.substring(0, colonIndex).replace('/', File.separatorChar);
      final int slashIndex = filePath.lastIndexOf(File.separatorChar);
      final String shortFileName = slashIndex < 0 ? filePath : filePath.substring(slashIndex + 1);
      if (!file.getName().equalsIgnoreCase(shortFileName)) return null;
      */

      final int textStartOffset = textEndOffset - line.length();

      final int highlightStartOffset = textStartOffset + lparenthIndex + 1;
      final int highlightEndOffset = textStartOffset + rparenthIndex;
      final VirtualFile virtualFile = myFile.getVirtualFile();

      HyperlinkInfo linkInfo = new MyHyperlinkInfo(myProject, virtualFile, lineNumber);

      TextAttributes attributes = HYPERLINK_ATTRIBUTES.clone();
      if (!ProjectRootManager.getInstance(myProject).getFileIndex().isInContent(virtualFile)) {
        Color color = UIUtil.getInactiveTextColor();
        attributes.setForegroundColor(color);
        attributes.setEffectColor(color);
      }
      myResult = new Filter.Result(highlightStartOffset, highlightEndOffset, linkInfo, attributes);
    } catch (NumberFormatException e) {
      //
    }
  }
  public AddModuleDependencyFix(
      Module currentModule, VirtualFile classVFile, PsiClass[] classes, PsiReference reference) {
    final PsiElement psiElement = reference.getElement();
    final Project project = psiElement.getProject();
    final JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
    final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();

    for (PsiClass aClass : classes) {
      if (!facade.getResolveHelper().isAccessible(aClass, psiElement, aClass)) continue;
      PsiFile psiFile = aClass.getContainingFile();
      if (psiFile == null) continue;
      VirtualFile virtualFile = psiFile.getVirtualFile();
      if (virtualFile == null) continue;
      final Module classModule = fileIndex.getModuleForFile(virtualFile);
      if (classModule != null
          && classModule != currentModule
          && !ModuleRootManager.getInstance(currentModule).isDependsOn(classModule)) {
        myModules.add(classModule);
      }
    }
    myCurrentModule = currentModule;
    myClassVFile = classVFile;
    myClasses = classes;
    myReference = reference;
  }
  @Nullable
  private PsiClass mapClass(@NotNull PsiClass psiClass) {
    String qualifiedName = psiClass.getQualifiedName();
    if (qualifiedName == null) {
      return psiClass;
    }

    PsiFile file = psiClass.getContainingFile();
    if (file == null || !file.getViewProvider().isPhysical()) {
      return psiClass;
    }

    final VirtualFile vFile = file.getVirtualFile();
    if (vFile == null) {
      return psiClass;
    }

    final FileIndexFacade index = FileIndexFacade.getInstance(file.getProject());
    if (!index.isInSource(vFile)
        && !index.isInLibrarySource(vFile)
        && !index.isInLibraryClasses(vFile)) {
      return psiClass;
    }

    return JavaPsiFacade.getInstance(psiClass.getProject())
        .findClass(qualifiedName, myResolveScope);
  }
  private boolean checkAccessibility(final PsiClass aClass) {
    // We don't care about accessibility in javadoc
    if (JavaResolveUtil.isInJavaDoc(myPlace)) {
      return true;
    }

    if (PsiImplUtil.isInServerPage(aClass.getContainingFile())) {
      PsiFile file = FileContextUtil.getContextFile(myPlace);
      if (PsiImplUtil.isInServerPage(file)) {
        return true;
      }
    }

    boolean accessible = true;
    if (aClass instanceof PsiTypeParameter) {
      accessible = !myStaticContext;
    }

    PsiManager manager = aClass.getManager();
    if (aClass.hasModifierProperty(PsiModifier.PRIVATE)) {
      PsiElement parent = aClass.getParent();
      while (true) {
        PsiElement parentScope = parent.getParent();
        if (parentScope instanceof PsiJavaFile) break;
        parent = parentScope;
        if (!(parentScope instanceof PsiClass)) break;
      }
      if (parent instanceof PsiDeclarationStatement) {
        parent = parent.getParent();
      }
      accessible = false;
      for (PsiElement placeParent = myPlace;
          placeParent != null;
          placeParent = placeParent.getContext()) {
        if (manager.areElementsEquivalent(placeParent, parent)) accessible = true;
      }
    }
    final JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject());
    if (aClass.hasModifierProperty(PsiModifier.PROTECTED)) {
      accessible = false;
      if (myPlace != null && facade.arePackagesTheSame(aClass, myPlace)) {
        accessible = true;
      } else {
        if (aClass.getContainingClass() != null) {
          accessible =
              myAccessClass == null
                  || myPlace != null
                      && facade.getResolveHelper().isAccessible(aClass, myPlace, myAccessClass);
        }
      }
    }
    if (aClass.hasModifierProperty(PsiModifier.PACKAGE_LOCAL)) {
      if (myPlace == null || !facade.arePackagesTheSame(aClass, myPlace)) {
        accessible = false;
      }
    }
    return accessible;
  }
 private PsiClass createArrayClass(String text, LanguageLevel level) {
   PsiClass psiClass =
       ((PsiExtensibleClass) createClassFromText(text, null)).getOwnInnerClasses().get(0);
   ensureNonWritable(psiClass);
   PsiFile file = psiClass.getContainingFile();
   ((PsiJavaFileBaseImpl) file).clearCaches();
   PsiUtil.FILE_LANGUAGE_LEVEL_KEY.set(file, level);
   return psiClass;
 }
  public static boolean isClassEquivalentTo(@NotNull PsiClass aClass, PsiElement another) {
    if (aClass == another) return true;
    if (!(another instanceof PsiClass)) return false;
    String name1 = aClass.getName();
    if (name1 == null) return false;
    if (!another.isValid()) return false;
    String name2 = ((PsiClass) another).getName();
    if (name2 == null) return false;
    if (name1.hashCode() != name2.hashCode()) return false;
    if (!name1.equals(name2)) return false;
    String qName1 = aClass.getQualifiedName();
    String qName2 = ((PsiClass) another).getQualifiedName();
    if (qName1 == null || qName2 == null) {
      //noinspection StringEquality
      if (qName1 != qName2) return false;

      if (aClass instanceof PsiTypeParameter && another instanceof PsiTypeParameter) {
        PsiTypeParameter p1 = (PsiTypeParameter) aClass;
        PsiTypeParameter p2 = (PsiTypeParameter) another;

        return p1.getIndex() == p2.getIndex()
            && aClass.getManager().areElementsEquivalent(p1.getOwner(), p2.getOwner());
      } else {
        return false;
      }
    }
    if (qName1.hashCode() != qName2.hashCode() || !qName1.equals(qName2)) {
      return false;
    }

    if (originalElement(aClass).equals(originalElement((PsiClass) another))) {
      return true;
    }

    final PsiFile file1 = aClass.getContainingFile().getOriginalFile();
    final PsiFile file2 = another.getContainingFile().getOriginalFile();

    // see com.intellij.openapi.vcs.changes.PsiChangeTracker
    // see com.intellij.psi.impl.PsiFileFactoryImpl#createFileFromText(CharSequence,PsiFile)
    final PsiFile original1 = file1.getUserData(PsiFileFactory.ORIGINAL_FILE);
    final PsiFile original2 = file2.getUserData(PsiFileFactory.ORIGINAL_FILE);
    if (original1 == original2 && original1 != null
        || original1 == file2
        || original2 == file1
        || file1 == file2) {
      return compareClassSeqNumber(aClass, (PsiClass) another);
    }

    final FileIndexFacade fileIndex =
        ServiceManager.getService(file1.getProject(), FileIndexFacade.class);
    final VirtualFile vfile1 = file1.getViewProvider().getVirtualFile();
    final VirtualFile vfile2 = file2.getViewProvider().getVirtualFile();
    boolean lib1 = fileIndex.isInLibraryClasses(vfile1);
    boolean lib2 = fileIndex.isInLibraryClasses(vfile2);

    return (fileIndex.isInSource(vfile1) || lib1) && (fileIndex.isInSource(vfile2) || lib2);
  }
  private static void findClassUsages(
      final PsiClass psiClass,
      final PsiElement[] allElementsToDelete,
      final List<UsageInfo> usages) {
    final boolean justPrivates = containsOnlyPrivates(psiClass);
    final String qualifiedName = psiClass.getQualifiedName();
    final boolean annotationType = psiClass.isAnnotationType() && qualifiedName != null;

    ReferencesSearch.search(psiClass)
        .forEach(
            reference -> {
              final PsiElement element = reference.getElement();

              if (!isInside(element, allElementsToDelete)) {
                PsiElement parent = element.getParent();
                if (parent instanceof PsiReferenceList) {
                  final PsiElement pparent = parent.getParent();
                  if (pparent instanceof PsiClass
                      && element instanceof PsiJavaCodeReferenceElement) {
                    final PsiClass inheritor = (PsiClass) pparent;
                    // If psiClass contains only private members, then it is safe to remove it and
                    // change inheritor's extends/implements accordingly
                    if (justPrivates) {
                      if (parent.equals(inheritor.getExtendsList())
                          || parent.equals(inheritor.getImplementsList())) {
                        usages.add(
                            new SafeDeleteExtendsClassUsageInfo(
                                (PsiJavaCodeReferenceElement) element, psiClass, inheritor));
                        return true;
                      }
                    }
                  }
                }
                LOG.assertTrue(element.getTextRange() != null);
                final PsiFile containingFile = psiClass.getContainingFile();
                boolean sameFileWithSingleClass = false;
                if (containingFile instanceof PsiClassOwner) {
                  final PsiClass[] classes = ((PsiClassOwner) containingFile).getClasses();
                  sameFileWithSingleClass =
                      classes.length == 1
                          && classes[0] == psiClass
                          && element.getContainingFile() == containingFile;
                }

                final boolean safeDelete = sameFileWithSingleClass || isInNonStaticImport(element);
                if (annotationType && parent instanceof PsiAnnotation) {
                  usages.add(
                      new SafeDeleteAnnotation((PsiAnnotation) parent, psiClass, safeDelete));
                } else {
                  usages.add(
                      new SafeDeleteReferenceJavaDeleteUsageInfo(element, psiClass, safeDelete));
                }
              }
              return true;
            });
  }
 public JavaPsiClassReferenceElement(PsiClass psiClass) {
   super(psiClass.getName(), psiClass.getName());
   myClass =
       psiClass.getContainingFile().getVirtualFile() == null
           ? psiClass
           : PsiAnchor.create(psiClass);
   myQualifiedName = psiClass.getQualifiedName();
   JavaCompletionUtil.setShowFQN(this);
   setInsertHandler(AllClassesGetter.TRY_SHORTENING);
   setTailType(TailType.NONE);
 }
  public void testStaticImports() throws IOException {
    setupLoadingFilter();

    final PsiClass aClass =
        myJavaFacade.findClass(
            "staticImports.StaticImports", GlobalSearchScope.moduleScope(myModule));
    assertNotNull(aClass);
    final PsiJavaFile javaFile = (PsiJavaFile) aClass.getContainingFile();
    doTestStaticImports(javaFile, false);
    teardownLoadingFilter();
    doTestStaticImports(javaFile, true);
  }
  @NotNull
  public static SearchScope getClassUseScope(@NotNull PsiClass aClass) {
    if (aClass instanceof PsiAnonymousClass) {
      return new LocalSearchScope(aClass);
    }
    final GlobalSearchScope maximalUseScope = ResolveScopeManager.getElementUseScope(aClass);
    PsiFile file = aClass.getContainingFile();
    if (PsiImplUtil.isInServerPage(file)) return maximalUseScope;
    final PsiClass containingClass = aClass.getContainingClass();
    if (aClass.hasModifierProperty(PsiModifier.PUBLIC)
        || aClass.hasModifierProperty(PsiModifier.PROTECTED)) {
      return containingClass == null ? maximalUseScope : containingClass.getUseScope();
    } else if (aClass.hasModifierProperty(PsiModifier.PRIVATE)
        || aClass instanceof PsiTypeParameter) {
      PsiClass topClass = PsiUtil.getTopLevelClass(aClass);
      return new LocalSearchScope(topClass == null ? aClass.getContainingFile() : topClass);
    } else {
      PsiPackage aPackage = null;
      if (file instanceof PsiJavaFile) {
        aPackage =
            JavaPsiFacade.getInstance(aClass.getProject())
                .findPackage(((PsiJavaFile) file).getPackageName());
      }

      if (aPackage == null) {
        PsiDirectory dir = file.getContainingDirectory();
        if (dir != null) {
          aPackage = JavaDirectoryService.getInstance().getPackage(dir);
        }
      }

      if (aPackage != null) {
        SearchScope scope = PackageScope.packageScope(aPackage, false);
        scope = scope.intersectWith(maximalUseScope);
        return scope;
      }

      return new LocalSearchScope(file);
    }
  }
 public void applyFix(final Project project, final PsiFile file, final Editor editor) {
   if (!CodeInsightUtilBase.prepareFileForWrite(myClass.getContainingFile())) return;
   PsiCodeBlock body;
   if (myClass.isInterface() && (body = myMethod.getBody()) != null) body.delete();
   for (String exception : myExceptions) {
     PsiUtil.addException(myMethod, exception);
   }
   PsiMethod method = (PsiMethod) myClass.add(myMethod);
   method = (PsiMethod) method.replace(reformat(project, method));
   if (editor != null) {
     GenerateMembersUtil.positionCaret(editor, method, true);
   }
 }
 private static List<PsiClass> filterAllowedDependencies(PsiElement element, PsiClass[] classes) {
   DependencyValidationManager dependencyValidationManager =
       DependencyValidationManager.getInstance(element.getProject());
   PsiFile fromFile = element.getContainingFile();
   List<PsiClass> result = new ArrayList<PsiClass>();
   for (PsiClass psiClass : classes) {
     if (dependencyValidationManager.getViolatorDependencyRule(
             fromFile, psiClass.getContainingFile())
         == null) {
       result.add(psiClass);
     }
   }
   return result;
 }
  @Override
  public void run() throws Throwable {
    if (mCreateHolder) {
      generateAdapter();
    } else {
      generateFields();
      generateFindViewById();
    }

    // reformat class
    JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(mProject);
    styleManager.optimizeImports(mFile);
    styleManager.shortenClassReferences(mClass);
    new ReformatCodeProcessor(mProject, mClass.getContainingFile(), null, false)
        .runWithoutProgress();
  }
 private static void addIdAndSuperClasses(PsiFile file, @NotNull TIntHashSet forward) {
   if (file instanceof PsiJavaFile
       && file.getName().equals("Object.class")
       && ((PsiJavaFile) file).getPackageName().equals("java.lang")) {
     return;
   }
   VirtualFile virtualFile = PsiUtilCore.getVirtualFile(file);
   if (virtualFile instanceof VirtualFileWithId
       && forward.add(getAbsId(virtualFile))
       && file instanceof PsiClassOwner) {
     for (PsiClass aClass : ((PsiClassOwner) file).getClasses()) {
       for (PsiClass superClass : aClass.getSupers()) {
         addIdAndSuperClasses(superClass.getContainingFile(), forward);
       }
     }
   }
 }
  private void deleteStepDefinition(@NotNull final String stepDefName) {
    final PsiClass psiClass = getStepDefClass();
    final PsiFile psiFile = psiClass.getContainingFile();

    new WriteCommandAction(getProject(), psiFile) {
      @Override
      protected void run(Result result) throws Throwable {

        for (PsiMethod method : psiClass.getAllMethods()) {
          if (method.getName().equals(stepDefName)) {
            method.delete();
            break;
          }
        }
      }
    }.execute();
  }
  private String createStepDefinition(@NotNull final String stepDef) {
    final PsiClass psiClass = getStepDefClass();
    final PsiFile psiFile = psiClass.getContainingFile();

    final Ref<String> createdMethodName = new Ref<String>();

    new WriteCommandAction(getProject(), psiFile) {
      @Override
      protected void run(final Result result) throws Throwable {
        final PsiElementFactory factory =
            JavaPsiFacade.getInstance(getProject()).getElementFactory();
        final PsiMethod method = factory.createMethodFromText(stepDef, psiClass);
        psiClass.add(method);
        createdMethodName.set(method.getName());
      }
    }.execute();

    return createdMethodName.get();
  }
Exemple #20
0
  private static PsiFile getTargetFile(PsiElement element) {
    final PsiConstructorCall constructorCall = (PsiConstructorCall) element;

    // Enum constants constructors are file local
    if (constructorCall instanceof PsiEnumConstant) return constructorCall.getContainingFile();

    PsiJavaCodeReferenceElement referenceElement = getReferenceElement(constructorCall);
    if (referenceElement.getQualifier() instanceof PsiJavaCodeReferenceElement) {
      PsiJavaCodeReferenceElement qualifier =
          (PsiJavaCodeReferenceElement) referenceElement.getQualifier();
      PsiElement psiElement = qualifier.resolve();
      if (psiElement instanceof PsiClass) {
        PsiClass psiClass = (PsiClass) psiElement;
        return psiClass.getContainingFile();
      }
    }

    return null;
  }
 protected final void registerClassError(@NotNull PsiClass aClass, Object... infos) {
   final PsiElement nameIdentifier;
   if (aClass instanceof PsiEnumConstantInitializer) {
     final PsiEnumConstantInitializer enumConstantInitializer =
         (PsiEnumConstantInitializer) aClass;
     final PsiEnumConstant enumConstant = enumConstantInitializer.getEnumConstant();
     nameIdentifier = enumConstant.getNameIdentifier();
   } else if (aClass instanceof PsiAnonymousClass) {
     final PsiAnonymousClass anonymousClass = (PsiAnonymousClass) aClass;
     nameIdentifier = anonymousClass.getBaseClassReference();
   } else {
     nameIdentifier = aClass.getNameIdentifier();
   }
   if (nameIdentifier == null) {
     registerError(aClass.getContainingFile(), infos);
   } else {
     registerError(nameIdentifier, infos);
   }
 }
 @Override
 public void invoke(
     @NotNull Project project,
     @NotNull PsiFile file,
     @Nullable("is null when called from inspection") Editor editor,
     @NotNull PsiElement startElement,
     @NotNull PsiElement endElement) {
   final PsiClass myClass = (PsiClass) startElement;
   if (!CodeInsightUtilBase.prepareFileForWrite(myClass.getContainingFile())) return;
   PsiCodeBlock body;
   if (myClass.isInterface() && (body = myMethodPrototype.getBody()) != null) body.delete();
   for (String exception : myExceptions) {
     PsiUtil.addException(myMethodPrototype, exception);
   }
   PsiMethod method = (PsiMethod) myClass.add(myMethodPrototype);
   method = (PsiMethod) method.replace(reformat(project, method));
   if (editor != null) {
     GenerateMembersUtil.positionCaret(editor, method, true);
   }
 }
  @Nullable
  protected VirtualFile findCoreJar(@Nullable Module module) {
    if (module == null) return null;

    JavaPsiFacade javaFacade = JavaPsiFacade.getInstance(module.getProject());

    for (PsiClass aClass :
        javaFacade.findClasses(
            getSomeFrameworkClass(), GlobalSearchScope.moduleWithLibrariesScope(module))) {
      VirtualFile virtualFile = aClass.getContainingFile().getVirtualFile();
      if (virtualFile != null && virtualFile.getFileSystem() instanceof JarFileSystem) {
        VirtualFile localFile = PathUtil.getLocalFile(virtualFile);
        if (isCoreJar(localFile)) {
          return localFile;
        }
      }
    }

    return null;
  }
  @Nullable
  private RunnerAndConfigurationSettings createConfiguration(final PsiClass aClass) {
    final Project project = aClass.getProject();
    RunnerAndConfigurationSettings settings =
        RunManagerEx.getInstanceEx(project).createConfiguration("", getConfigurationFactory());
    final GroovyScriptRunConfiguration configuration =
        (GroovyScriptRunConfiguration) settings.getConfiguration();
    final PsiFile file = aClass.getContainingFile().getOriginalFile();
    final PsiDirectory dir = file.getContainingDirectory();
    if (dir == null) return null;
    configuration.setWorkDir(dir.getVirtualFile().getPath());
    final VirtualFile vFile = file.getVirtualFile();
    if (vFile == null) return null;
    configuration.setScriptPath(vFile.getPath());
    RunConfigurationModule module = configuration.getConfigurationModule();

    String name = getConfigurationName(aClass, module);
    configuration.setName(name);
    configuration.setModule(JavaExecutionUtil.findModule(aClass));
    return settings;
  }
  protected <Psi extends PsiElement> void processIntern(
      @NotNull PsiClass psiClass, @NotNull PsiAnnotation psiAnnotation, @NotNull List<Psi> target) {
    PsiElementFactory psiElementFactory = psiElementFactory(psiClass);
    PsiManager manager = psiClass.getContainingFile().getManager();

    PsiType psiProviderType = psiElementFactory.createTypeFromText(RMI_PROVIDER_TYPE, psiClass);
    LombokLightFieldBuilder providerField =
        LombokPsiElementFactory.getInstance()
            .createLightField(manager, RMI_PROVIDER_FIELD_NAME, psiProviderType)
            .withContainingClass(psiClass)
            .withModifier(PsiModifier.PRIVATE)
            .withNavigationElement(psiAnnotation);
    PsiExpression initializer =
        psiElementFactory.createExpressionFromText(
            String.format(RMI_PROVIDER_FIELD_INITIALIZER), psiClass);
    providerField.setInitializer(initializer);

    LombokLightMethodBuilder method =
        LombokPsiElementFactory.getInstance()
            .createLightMethod(psiClass.getManager(), METHOD_GET_RMI_PROVIDER)
            .withMethodReturnType(psiProviderType)
            .withContainingClass(psiClass)
            .withModifier(PsiModifier.PUBLIC)
            .withNavigationElement(psiAnnotation);
    target.add((Psi) method);

    method =
        LombokPsiElementFactory.getInstance()
            .createLightMethod(psiClass.getManager(), METHOD_SET_RMI_PROVIDER)
            .withMethodReturnType(PsiPrimitiveTypeFactory.getInstance().getVoidType())
            .withContainingClass(psiClass)
            .withParameter(PROVIDER, psiProviderType)
            .withModifier(PsiModifier.PUBLIC)
            .withNavigationElement(psiAnnotation);
    target.add((Psi) method);

    for (MethodDescriptor methodDesc : METHODS) {
      target.add((Psi) PsiMethodUtil.createMethod(psiClass, methodDesc.signature, psiAnnotation));
    }
  }
  @NotNull
  private Object[] getSubclassVariants(
      @NotNull PsiPackage context, @NotNull String[] extendClasses) {
    HashSet<Object> lookups = new HashSet<Object>();
    GlobalSearchScope packageScope = PackageScope.packageScope(context, true);
    GlobalSearchScope scope = myJavaClassReferenceSet.getProvider().getScope();
    if (scope != null) {
      packageScope = packageScope.intersectWith(scope);
    }
    final GlobalSearchScope allScope = ProjectScope.getAllScope(context.getProject());
    final boolean instantiatable =
        JavaClassReferenceProvider.INSTANTIATABLE.getBooleanValue(getOptions());
    final boolean notInterface =
        JavaClassReferenceProvider.NOT_INTERFACE.getBooleanValue(getOptions());
    final boolean notEnum = JavaClassReferenceProvider.NOT_ENUM.getBooleanValue(getOptions());
    final boolean concrete = JavaClassReferenceProvider.CONCRETE.getBooleanValue(getOptions());

    final ClassKind classKind = getClassKind();

    for (String extendClassName : extendClasses) {
      final PsiClass extendClass =
          JavaPsiFacade.getInstance(context.getProject()).findClass(extendClassName, allScope);
      if (extendClass != null) {
        // add itself
        if (packageScope.contains(extendClass.getContainingFile().getVirtualFile())) {
          if (isClassAccepted(
              extendClass, classKind, instantiatable, concrete, notInterface, notEnum)) {
            ContainerUtil.addIfNotNull(createSubclassLookupValue(context, extendClass), lookups);
          }
        }
        for (final PsiClass clazz : ClassInheritorsSearch.search(extendClass, packageScope, true)) {
          if (isClassAccepted(clazz, classKind, instantiatable, concrete, notInterface, notEnum)) {
            ContainerUtil.addIfNotNull(createSubclassLookupValue(context, clazz), lookups);
          }
        }
      }
    }
    return lookups.toArray();
  }
  private void processMethodsDuplicates() {
    ProgressManager.getInstance()
        .runProcessWithProgressSynchronously(
            () ->
                ApplicationManager.getApplication()
                    .runReadAction(
                        () -> {
                          if (!myTargetSuperClass.isValid()) return;
                          final Query<PsiClass> search =
                              ClassInheritorsSearch.search(myTargetSuperClass);
                          final Set<VirtualFile> hierarchyFiles = new HashSet<>();
                          for (PsiClass aClass : search) {
                            final PsiFile containingFile = aClass.getContainingFile();
                            if (containingFile != null) {
                              final VirtualFile virtualFile = containingFile.getVirtualFile();
                              if (virtualFile != null) {
                                hierarchyFiles.add(virtualFile);
                              }
                            }
                          }
                          final Set<PsiMember> methodsToSearchDuplicates = new HashSet<>();
                          for (PsiMember psiMember : myMembersAfterMove) {
                            if (psiMember instanceof PsiMethod
                                && psiMember.isValid()
                                && ((PsiMethod) psiMember).getBody() != null) {
                              methodsToSearchDuplicates.add(psiMember);
                            }
                          }

                          MethodDuplicatesHandler.invokeOnScope(
                              myProject,
                              methodsToSearchDuplicates,
                              new AnalysisScope(myProject, hierarchyFiles),
                              true);
                        }),
            MethodDuplicatesHandler.REFACTORING_NAME,
            true,
            myProject);
  }
 @Nullable
 public static String getTestDataBasePath(PsiClass psiClass) {
   final PsiAnnotation annotation =
       AnnotationUtil.findAnnotationInHierarchy(
           psiClass, Collections.singleton(TEST_DATA_PATH_ANNOTATION_QUALIFIED_NAME));
   if (annotation != null) {
     final PsiAnnotationMemberValue value =
         annotation.findAttributeValue(PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME);
     if (value instanceof PsiExpression) {
       final Project project = value.getProject();
       final PsiConstantEvaluationHelper evaluationHelper =
           JavaPsiFacade.getInstance(project).getConstantEvaluationHelper();
       final Object constantValue = evaluationHelper.computeConstantExpression(value, false);
       if (constantValue instanceof String) {
         String path = (String) constantValue;
         if (path.contains(CONTENT_ROOT_VARIABLE)) {
           final ProjectFileIndex fileIndex =
               ProjectRootManager.getInstance(project).getFileIndex();
           final VirtualFile file = psiClass.getContainingFile().getVirtualFile();
           if (file == null) {
             return null;
           }
           final VirtualFile contentRoot = fileIndex.getContentRootForFile(file);
           if (contentRoot == null) return null;
           path = path.replace(CONTENT_ROOT_VARIABLE, contentRoot.getPath());
         }
         if (path.contains(PROJECT_ROOT_VARIABLE)) {
           final VirtualFile baseDir = project.getBaseDir();
           if (baseDir == null) {
             return null;
           }
           path = path.replace(PROJECT_ROOT_VARIABLE, baseDir.getPath());
         }
         return path;
       }
     }
   }
   return null;
 }
Exemple #29
0
  @Override
  protected void run() throws Throwable {
    int fieldCount = 0;
    PsiMethod initViewMethod = getInitView();
    StringBuilder methodBuild = new StringBuilder("private void initView() {");
    for (ViewPart viewPart : viewPartList) {
      if (!viewPart.isSelected() || fieldExist(viewPart)) {
        continue;
      }
      mClass.add(mFactory.createFieldFromText(viewPart.getDeclareString(false, false), mClass));
      if (initViewMethod != null) {
        initViewMethod
            .getBody()
            .add(mFactory.createStatementFromText(viewPart.getFindViewString(), mClass));
      } else {
        if (isViewHolder) {
          methodBuild.append(viewPart.getFindViewStringForViewHolder("convertView"));
        } else if (isAddRootView && !TextUtils.isEmpty(rootViewStr)) {
          methodBuild.append(viewPart.getFindViewStringWithRootView(rootViewStr));
        } else {
          methodBuild.append(viewPart.getFindViewString());
        }
        fieldCount++;
      }
    }
    methodBuild.append("}");
    if (fieldCount > 0) {
      mClass.add(mFactory.createMethodFromText(methodBuild.toString(), mClass));
    }
    addInitViewAfterOnCreate();

    // reformat class
    JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(mProject);
    styleManager.optimizeImports(psiFile);
    styleManager.shortenClassReferences(mClass);
    new ReformatCodeProcessor(mProject, mClass.getContainingFile(), null, false)
        .runWithoutProgress();
  }
 @Override
 public String toString() {
   if (myText == null) {
     Module module = ModuleUtilCore.findModuleForPsiElement(myClass);
     if (module != null) {
       myText = module.getName();
     } else {
       VirtualFile virtualFile = myClass.getContainingFile().getVirtualFile();
       final ProjectFileIndex index =
           ProjectRootManager.getInstance(myClass.getProject()).getFileIndex();
       VirtualFile root = index.getSourceRootForFile(virtualFile);
       if (root == null) {
         root = index.getClassRootForFile(virtualFile);
       }
       if (root != null) {
         myText = root.getName();
       } else {
         myText = virtualFile.getPath();
       }
     }
   }
   return myText;
 }