@Nullable private static String findEnclosingName(final SourcePosition position) { PsiElement element = findElementAt(position); while (true) { element = PsiTreeUtil.getParentOfType(element, GrTypeDefinition.class, PsiClassImpl.class); if (element == null || (element instanceof GrTypeDefinition && !((GrTypeDefinition)element).isAnonymous()) || (element instanceof PsiClassImpl && ((PsiClassImpl)element).getName() != null) ) { break; } } if (element != null) { return getClassNameForJvm((PsiClass)element); } return null; }
@Nullable private static String getOuterClassName(final SourcePosition position) { AccessToken accessToken = ApplicationManager.getApplication().acquireReadActionLock(); try { PsiElement element = findElementAt(position); if (element == null) return null; PsiElement sourceImage = PsiTreeUtil.getParentOfType(element, GrClosableBlock.class, GrTypeDefinition.class, PsiClassImpl.class); if (sourceImage instanceof PsiClass) { return getClassNameForJvm((PsiClass)sourceImage); } return null; } finally { accessToken.finish(); } }
@Override public void visitClass(PsiClass aClass) { if (InspectionPsiUtil.isAbstactClass(aClass)) { return; } if (!(aClass instanceof PsiClassImpl)) { return; } Project project = aClass.getProject(); PsiClass activityClass = InspectionPsiUtil.createPsiClass(QUALIFIED_NAME_OF_SUPER_CLASS, project); if (activityClass == null || !aClass.isInheritor(activityClass, true)) { return; } PsiMethod[] methods = aClass.getMethods(); for (PsiMethod method : methods) { if (isTargetMethod(method)) { return; } } registerProblem(aClass); }
@Override public void visitClass(PsiClass aClass) { if (InspectionPsiUtil.isAbstactClass(aClass)) { return; } if (!(aClass instanceof PsiClassImpl)) { return; } if (!isFragment(aClass)) { return; } PsiMethod[] methods = aClass.getMethods(); for (PsiMethod method : methods) { if (isNewInstanceMethod(aClass, method)) { return; } } registerProblem(aClass); }
@Test public void TestIsImplicitUsageForClass() throws Exception { ModuleHelper helper = mock(ModuleHelper.class); PsiClass c = mock(PsiClassImpl.class); PsiMethod method = mock(PsiMethod.class); PsiModifierList list = mock(PsiModifierList.class); PsiAnnotation annotation = mock(PsiAnnotation.class); when(annotation.getQualifiedName()).thenReturn(BeforeStep.class.getCanonicalName()); when(list.getAnnotations()).thenReturn(new PsiAnnotation[]{annotation}); when(method.getModifierList()).thenReturn(list); when(c.getMethods()).thenReturn(new PsiMethod[]{method}); when(helper.isGaugeModule(c)).thenReturn(true); boolean isUsed = new ImplUsageProvider(null, helper).isImplicitUsage(c); assertTrue(isUsed); }
@Nullable private static PsiClassImpl getRootClassUnderOperation(PsiFile psiFile) { Optional<PsiClassImpl> javaClass = Stream.of(psiFile.getChildren()) .filter(psiElement -> psiElement instanceof PsiClassImpl) .map(psiElement -> (PsiClassImpl) psiElement).findFirst(); if (!javaClass.isPresent()) { return null; } PsiClassImpl psiJavaClass = javaClass.get(); return psiJavaClass; }
@Override public PsiClass createPsi(@NotNull final ASTNode node) { if (node instanceof EnumConstantInitializerElement) { return new PsiEnumConstantInitializerImpl(node); } else if (node instanceof AnonymousClassElement) { return new PsiAnonymousClassImpl(node); } return new PsiClassImpl(node); }
private static boolean isEnumValuesMethodUsed(@NotNull Project project, @NotNull PsiFile containingFile, @NotNull PsiMember member, @NotNull ProgressIndicator progress, @NotNull GlobalUsageHelper helper) { final PsiClass containingClass = member.getContainingClass(); if (!(containingClass instanceof PsiClassImpl)) return true; final PsiMethod valuesMethod = ((PsiClassImpl)containingClass).getValuesMethod(); return valuesMethod == null || isMethodReferenced(project, containingFile, valuesMethod, progress, helper); }
@Test public void TestIsImplicitUsageForClassWithNoMethods() throws Exception { ModuleHelper helper = mock(ModuleHelper.class); PsiClass c = mock(PsiClassImpl.class); when(helper.isGaugeModule(c)).thenReturn(true); when(c.getMethods()).thenReturn(new PsiMethod[]{}); boolean isUsed = new ImplUsageProvider(null, helper).isImplicitUsage(c); assertFalse(isUsed); }
@Nullable private static String findEnclosingName(final SourcePosition position) { PsiElement element = findElementAt(position); while (true) { element = PsiTreeUtil.getParentOfType(element, GrTypeDefinition.class, PsiClassImpl.class); if (element == null || (element instanceof GrTypeDefinition && !((GrTypeDefinition)element).isAnonymous()) || (element instanceof PsiClassImpl && ((PsiClassImpl)element).getName() != null) ) { break; } } return null; }
@Override public PsiClass createPsi(@NotNull final ASTNode node) { if(node instanceof EnumConstantInitializerElement) { return new PsiEnumConstantInitializerImpl(node); } else if(node instanceof AnonymousClassElement) { return new PsiAnonymousClassImpl(node); } return new PsiClassImpl(node); }
private static boolean isEnumValuesMethodUsed(@NotNull Project project, @NotNull PsiFile containingFile, @NotNull PsiMember member, @NotNull ProgressIndicator progress, @NotNull GlobalUsageHelper helper) { final PsiClass containingClass = member.getContainingClass(); if(!(containingClass instanceof PsiClassImpl)) { return true; } if(containingClass.isEnum()) { PsiMethod[] methodsByName = containingClass.findMethodsByName(JavaEnumAugmentProvider.VALUES_METHOD_NAME, false); PsiMethod valuesMethod = null; for(PsiMethod psiMethod : methodsByName) { if(psiMethod.getParameterList().getParametersCount() == 0 && psiMethod.hasModifierProperty (PsiModifier.STATIC)) { valuesMethod = psiMethod; break; } } return valuesMethod == null || isMethodReferenced(project, containingFile, valuesMethod, progress, helper); } else { return true; } }
@Override protected void doExecute(Editor editor, @Nullable Caret caret, DataContext dataContext) { System.out.println("doExecute called: editor = [" + editor + "], caret = [" + caret + "], " + "dataContext = [" + dataContext + "]"); super.doExecute(editor, caret, dataContext); Project project = (Project) dataContext.getData(DataKeys.PROJECT.getName()); if (project == null) return; PsiFile rootPsiFile = PsiUtilBase.getPsiFileInEditor(editor, project); if (rootPsiFile == null) return; PsiClass sourceClassName = Stream.of(rootPsiFile.getChildren()) .peek(psiElement -> System.out.println(psiElement.getClass())) .filter(psiElement -> psiElement instanceof PsiClass) .peek(System.out::println) .map(psiElement -> (PsiClass) psiElement) .collect(Collectors.toList()).get(0); SourceClass sourceClass = new SourceClass(sourceClassName.getName()); List<Variable> extractedVariables = Stream.of(rootPsiFile.getChildren()) .filter(psiElement -> psiElement instanceof PsiClassImpl) .map(PsiElement::getChildren) .flatMap(Arrays::stream) .filter(psiElement -> psiElement instanceof PsiVariable) .map(psiElement -> (PsiVariable) psiElement) .map(psiVariable -> new Variable( new Type(psiVariable.getType().getCanonicalText()), new Variable.Name(psiVariable.getName()))) .peek(System.out::println) .collect(Collectors.toList()); if (extractedVariables.isEmpty()) return; PsiClassImpl sourceJavaPsiClass = getRootClassUnderOperation(rootPsiFile); if (sourceJavaPsiClass == null) return; GeneratedValueWriter writeActionRunner = new GeneratedValueWriter( sourceJavaPsiClass, project, extractedVariables, sourceClass, rootPsiFile ); WriteCommandAction.runWriteCommandAction(project, writeActionRunner); }
public PsiClassImpl getPsiClass() { return psiClass; }
public void setPsiClass(PsiClassImpl psiClass) { this.psiClass = psiClass; }
public void actionPerformed(AnActionEvent event) { String projectPath = StringUtils.EMPTY; try { //todo need check if need module. UserConfigService.loadUserConfig(ProjectHelper.getProjectPath(event)); projectPath = ProjectHelper.getProjectPath(event); Project project = event.getProject(); Editor editor = event.getData(LangDataKeys.EDITOR); PsiFile currentFile = event.getData(LangDataKeys.PSI_FILE); CaretModel caretModel = editor.getCaretModel(); LogicalPosition oldLogicPos = caretModel.getLogicalPosition(); String text = currentFile.getText(); List<String> lines = Splitter.on("\n").splitToList(text); PojoLine pojo = getCursorLine(lines, oldLogicPos); PsiDirectory containingDirectory = currentFile.getContainingDirectory(); // HintManager.getInstance().showInformationHint(editor,"success"); String dir = containingDirectory.getVirtualFile().getCanonicalPath() + GenCodeResponseHelper.getPathSplitter() + currentFile.getName(); AutoCodingRequest request = new AutoCodingRequest(); request.setRequestType("AutoCoding"); request.setCodingType("Setter"); ServerRequestHelper.fillCommonField(request); if (pojo != null) { request.setPojoName(pojo.getClassName()); LogicalPosition newStatementPos = new LogicalPosition(pojo.getLineNumber() , pojo.getLineStartPos() + 1); LogicalPosition insertPos = new LogicalPosition(pojo.getLineNumber() + 1 , 0 ); caretModel.moveToLogicalPosition(newStatementPos); PsiElement currentFileElement = event.getData(LangDataKeys.PSI_ELEMENT); if (currentFileElement instanceof PsiClassImpl || currentFileElement instanceof ClsClassImpl) { // Integer trueOffSet = getOffset(pojo, dir); // if(trueOffSet != 0){ // offset = trueOffSet; // } Document document = PsiDocumentManager.getInstance(event.getProject()).getDocument(currentFile); caretModel.moveToLogicalPosition(insertPos); Integer offset = caretModel.getOffset(); String insert = insertSetter(project, pojo, document, currentFileElement, offset); request.setInsert(insert); // SettingService.getSetting().setLastInsertPos(offset); // SettingService.getSetting().setLastInsertLength(setter.length()); } } // VirtualFileManager.getInstance().syncRefresh(); // ApplicationManager.getApplication().saveAll(); caretModel.moveToLogicalPosition(oldLogicPos); SendToServerService.post(project,request); } catch (Throwable ignored) { LOGGER.error("actionPerformed :{}", ignored); }finally { LoggerWrapper.saveAllLogs(projectPath); SettingService.updateLastRunTime(); } }
public static void parseIdeaFieldInfo(@NotNull OnePojoInfo onePojoInfo, GenCodeResponse response){ String pojoName = onePojoInfo.getPojoName(); String pojoFileShortName = pojoName + ".java"; Project project = response.getRequest().getProject(); PsiFile[] psiFile = FilenameIndex .getFilesByName(project, pojoFileShortName, GlobalSearchScope.projectScope(project)); PsiElement firstChild = psiFile[0].getFirstChild(); LOGGER.info("parseIdeaFieldInfo psiFile[0] path :{}", psiFile[0].getVirtualFile().getPath()); PsiElement child = null; for (PsiFile each: psiFile){ VirtualFile vf = each.getVirtualFile(); LOGGER.info("parseIdeaFieldInfo :{}, :{}", vf.getPath(), onePojoInfo.getFullPojoPath()); if (removeSplit(vf.getPath()).equals(removeSplit(onePojoInfo.getFullPojoPath()))){ child = firstChild; } } List<PsiElement> elements = Lists.newArrayList(); // i// Find Psi of class and package do { if (child instanceof PsiClassImpl) { elements.add(child); } if (child instanceof PsiPackageStatementImpl){ onePojoInfo.setPojoPackage(((PsiPackageStatementImpl) child).getPackageName()); } child = child.getNextSibling(); } while (child != null); PsiClassImpl psiClass = (PsiClassImpl) elements.get(0); PsiElement context = psiClass.getContext(); if(context == null){ throw new RuntimeException("parse class error"); } String text = context.getText(); onePojoInfo.setPojoPackage(parsePackage(text)); PsiField[] allFields = psiClass.getAllFields(); List<PojoFieldInfo> fieldList = Lists.newArrayList(); for (PsiField field : allFields) { if(isStaticField(field)){ continue; } SupportFieldClass fieldClass = SupportFieldClass.fromDesc(field.getType().getCanonicalText()); LOGGER.info("parseIdeaFieldInfo canonicalText :{}", field.getType().getCanonicalText()); if(fieldClass == SupportFieldClass.NONE){ continue; } PojoFieldInfo fieldInfo = new PojoFieldInfo(); fieldInfo.setFieldComment(parseComment(field)); fieldInfo.setFieldName(field.getName()); fieldInfo.setFieldClass(fieldClass); fieldInfo.setAnnotations(Lists.newArrayList()); fieldList.add(fieldInfo); } onePojoInfo.setPojoFieldInfos(fieldList); }
@Override public PsiClassType[] getReferencedTypes() { if (myTypes != null) return myTypes; if (myNames.length == 0) { myTypes = PsiClassType.EMPTY_ARRAY; return myTypes; } PsiClassType[] types = new PsiClassType[myNames.length]; final boolean compiled = ((JavaClassReferenceListElementType)getStubType()).isCompiled(this); if (compiled) { for (int i = 0; i < types.length; i++) { types[i] = new PsiClassReferenceType(new ClsJavaCodeReferenceElementImpl(getPsi(), StringRef.toString(myNames[i])), null); } } else { final PsiElementFactory factory = JavaPsiFacade.getInstance(getProject()).getElementFactory(); int nullCount = 0; final PsiReferenceList psi = getPsi(); for (int i = 0; i < types.length; i++) { PsiElement context = psi; if (getParentStub() instanceof PsiClassStub) { context = ((PsiClassImpl)getParentStub().getPsi()).calcBasesResolveContext(PsiNameHelper.getShortClassName(StringRef.toString(myNames[i])), psi); } try { final PsiJavaCodeReferenceElement ref = factory.createReferenceFromText(StringRef.toString(myNames[i]), context); ((PsiJavaCodeReferenceElementImpl)ref).setKindWhenDummy(PsiJavaCodeReferenceElementImpl.CLASS_NAME_KIND); types[i] = factory.createType(ref); } catch (IncorrectOperationException e) { types[i] = null; nullCount++; } } if (nullCount > 0) { PsiClassType[] newTypes = new PsiClassType[types.length - nullCount]; int cnt = 0; for (PsiClassType type : types) { if (type != null) newTypes[cnt++] = type; } types = newTypes; } } myTypes = types; return types; }
public boolean isImplicitUsage(PsiElement element) { if (element == null || !moduleHelper.isGaugeModule(element)) return false; if (element instanceof PsiClassImpl) return isClassUsed((PsiClassImpl) element); if (element instanceof PsiParameterImpl) return isParameterUsed((PsiParameterImpl) element); return isElementUsed(element); }
private boolean isClassUsed(PsiClassImpl element) { for (PsiMethod psiMethod : element.getMethods()) if (StepUtil.getGaugeStepAnnotationValues(psiMethod).size() > 0 || HookUtil.isHook(psiMethod)) return true; return false; }
private static boolean isEnumValuesMethodUsed(PsiMember member, ProgressIndicator progress, GlobalUsageHelper helper) { final PsiClass containingClass = member.getContainingClass(); if (containingClass == null || !(containingClass instanceof PsiClassImpl)) return true; final PsiMethod valuesMethod = ((PsiClassImpl)containingClass).getValuesMethod(); return valuesMethod == null || isMethodReferenced(valuesMethod, progress, helper); }
@Override public void putInfo(@NotNull Map<String, String> info) { PsiClassImpl.putInfo(this, info); }