@Override public void visitField(@NotNull PsiField field) { super.visitField(field); if (field instanceof PsiEnumConstant) { return; } if (!field.hasModifierProperty(PsiModifier.STATIC) || !field.hasModifierProperty(PsiModifier.FINAL)) { return; } final String name = field.getName(); if (name == null) { return; } final PsiType type = field.getType(); if (onlyCheckImmutables && !ClassUtils.isImmutable(type)) { return; } if (isValid(name)) { return; } registerFieldError(field, name); }
@Nullable public static PsiType getWritablePropertyType(@Nullable PsiClass containingClass, @Nullable PsiElement declaration) { if (declaration instanceof PsiField) { return getWrappedPropertyType((PsiField) declaration, JavaFxCommonNames.ourWritableMap); } if (declaration instanceof PsiMethod) { final PsiMethod method = (PsiMethod) declaration; if (method.getParameterList().getParametersCount() != 0) { return getSetterArgumentType(method); } final String propertyName = PropertyUtil.getPropertyName(method); final PsiClass psiClass = containingClass != null ? containingClass : method.getContainingClass(); if (propertyName != null && containingClass != null) { final PsiMethod setter = findInstancePropertySetter(psiClass, propertyName); if (setter != null) { final PsiType setterArgumentType = getSetterArgumentType(setter); if (setterArgumentType != null) return setterArgumentType; } } return getGetterReturnType(method); } return null; }
private static boolean hasGetAndSet(@NonNull String getPrefix, @NonNull String setPrefix, @NonNull PsiClass cls, @NonNull PsiField field) { boolean isPublic = field.hasModifierProperty(PsiModifier.PUBLIC); if (isPublic) return true; String fieldName = captureName(field.getName()); String getMethodName = getPrefix + fieldName; String setMethodName = setPrefix + fieldName; PsiMethod[] gets = cls.findMethodsByName(getMethodName, true); PsiMethod[] sets = cls.findMethodsByName(setMethodName, true); boolean hasGet = gets.length > 0; boolean hasSet = sets.length > 0; return hasGet && hasSet; }
@Nullable Resolution getResolutionFrom(PsiField field) { PsiAnnotation annotation = scenarioStateProvider.getJGivenAnnotationOn(field); if (annotation == null) { return null; } PsiExpression annotationValue = annotationValueProvider.getAnnotationValue(annotation, FIELD_RESOLUTION); return Optional.ofNullable(annotationValue) .map(PsiElement::getText) .map(t -> { for (Resolution resolution : Resolution.values()) { if (resolution != Resolution.AUTO && t.contains(resolution.name())) { return resolution; } } return getResolutionForFieldType(field); }).orElse(getResolutionForFieldType(field)); }
@Test public void should_process_reference() throws Exception { // given PsiReference reference1 = mock(PsiReference.class); PsiReference reference2 = mock(PsiReference.class); PsiField field = mock(PsiField.class); ReferencesSearch.SearchParameters searchParameters = mock(ReferencesSearch.SearchParameters.class); when(searchParameters.getElementToSearch()).thenReturn(field); when(searchParameters.getEffectiveSearchScope()).thenReturn(mock(GlobalSearchScope.class)); when(scenarioStateReferenceProvider.findReferences(field)).thenReturn(Arrays.asList(reference1, reference2)); when(scenarioStateProvider.isJGivenScenarioState(field)).thenReturn(true); // when referenceProvider.processQuery(searchParameters, processor); // then verify(processor).process(reference1); verify(processor).process(reference2); }
@NotNull @Override public ResolveResult[] multiResolve(final boolean incompleteCode) { Project project = myElement.getProject(); final String enumLiteralJavaModelName = myElement.getText().replaceAll("\"", "").toUpperCase(); final PsiShortNamesCache psiShortNamesCache = PsiShortNamesCache.getInstance(project); final PsiField[] javaEnumLiteralFields = psiShortNamesCache.getFieldsByName( enumLiteralJavaModelName, GlobalSearchScope.allScope(project) ); final Set<PsiField> enumFields = stream(javaEnumLiteralFields) .filter(literal -> literal.getParent() != null) .filter(literal -> literal.getParent() instanceof ClsClassImpl) .filter(literal -> ((ClsClassImpl) literal.getParent()).isEnum()) .collect(Collectors.toSet()); return PsiElementResolveResult.createResults(enumFields); }
private Optional<ConfigInfo> extractConfigInfo(PropertiesFile propertiesFile, CoffigResolver.Match match) { Optional<String> description = Optional.ofNullable(propertiesFile.findPropertyByKey(match.getUnmatchedPath())).map(IProperty::getValue); if (description.isPresent()) { // Base info ConfigInfo configInfo = new ConfigInfo(match.getFullPath(), description.get()); // Extended info Optional.ofNullable(propertiesFile.findPropertyByKey(match.getUnmatchedPath() + ".long")).map(IProperty::getValue).ifPresent(configInfo::setLongDescription); // Field info CoffigResolver.Match resolvedMatch = match.fullyResolve(); if (resolvedMatch.isFullyResolved()) { Optional<PsiField> psiField = resolvedMatch.resolveField(resolvedMatch.getUnmatchedPath()); psiField.map(PsiVariable::getType).map(PsiType::getPresentableText).ifPresent(configInfo::setType); } return Optional.of(configInfo); } return Optional.empty(); }
Optional<PsiClass> resolveFieldConfigType(PsiField psiField) { PsiType fieldType = psiField.getType(); if (fieldType instanceof PsiClassType) { PsiClassType fieldClassType = ((PsiClassType) fieldType); if (collectionType != null && collectionType.isAssignableFrom(fieldType) && fieldClassType.getParameterCount() == 1) { return toPsiClass(fieldClassType.getParameters()[0]); } else if (mapType != null && mapType.isAssignableFrom(fieldType) && fieldClassType.getParameterCount() == 2) { return toPsiClass(fieldClassType.getParameters()[1]); } else { return toPsiClass(fieldType); } } else if (fieldType instanceof PsiArrayType) { return toPsiClass(((PsiArrayType) fieldType).getComponentType()); } else { return Optional.empty(); } }
@Override public boolean canProcessElement( @NotNull PsiElement elem ) { PsiElement[] element = new PsiElement[]{elem}; List<PsiElement> javaElems = findJavaElements( element ); if( javaElems.isEmpty() ) { return false; } for( PsiElement javaElem : javaElems ) { if( !(javaElem instanceof PsiMethod) && !(javaElem instanceof PsiField) && !(javaElem instanceof PsiClass) ) { return false; } } return true; }
public SrcClass makeSrcClass( String fqn, PsiClass psiClass, ManModule module ) { SrcClass srcClass = new SrcClass( fqn, getKind( psiClass ) ) .modifiers( getModifiers( psiClass.getModifierList() ) ); for( PsiTypeParameter typeVar : psiClass.getTypeParameters() ) { srcClass.addTypeVar( new SrcType( makeTypeVar( typeVar ) ) ); } setSuperTypes( srcClass, psiClass ); for( PsiMethod psiMethod : psiClass.getMethods() ) { addMethod( srcClass, psiMethod ); } for( PsiField psiField : psiClass.getFields() ) { addField( srcClass, psiField ); } for( PsiClass psiInnerClass : psiClass.getInnerClasses() ) { addInnerClass( srcClass, psiInnerClass, module ); } return srcClass; }
private void init(@NonNull PsiClass clazz) { mClass = clazz; mClassFields = new HashMap<>(); mWriteFieldGroupMethods = new ArrayList<>(); mShardWriteFieldGroupMatrix = new ArrayList<>(); mFunctions = new ArrayList<>(); mMethodsToSeparateByGroup = new HashMap<>(); mMethodsToSeparateBySingle = new ArrayList<>(); mMethodsTrySeparateByRole = new HashMap<>(); mUnusedMethods = new HashSet<>(); mUnusedMethods.addAll(Arrays.asList(mClass.getMethods())); // PsiClass#getMethods() では、コンストラクタもメソッドに含まれます。 for (PsiField field : mClass.getFields()) { mClassFields.put(field.getName(), field); } }
/** * 左右のメソッドが共有する変更フィールド変数(状態)を解析 * @return 左右のメソッドが共有する変更フィールド変数 */ private Map<String, PsiField> parse() { Map<String, PsiField> leftWriteFields = mLeftMethod.provideWriteFields(); Map<String, PsiField> rightWriteFields = mRightMethod.provideWriteFields(); Map<String, PsiField> sharedWriteFields = new HashMap<>(); Collection<PsiField> leftValues = leftWriteFields.values(); Collection<PsiField> rightValues = rightWriteFields.values(); for (PsiField field : leftValues) { if (rightValues.contains(field)) { sharedWriteFields.put(field.getName(), field); } } return sharedWriteFields; }
public Settings(boolean replaceUsages, @Nullable String classParameterName, @Nullable VariableData[] variableDatum, boolean delegate) { myReplaceUsages = replaceUsages; myDelegate = delegate; myMakeClassParameter = classParameterName != null; myClassParameterName = classParameterName; myMakeFieldParameters = variableDatum != null; myFieldToNameList = new ArrayList<FieldParameter>(); if(myMakeFieldParameters) { myFieldToNameMapping = new HashMap<PsiField, String>(); for (VariableData data : variableDatum) { if (data.passAsParameter) { myFieldToNameMapping.put((PsiField)data.variable, data.name); myFieldToNameList.add(new FieldParameter((PsiField)data.variable, data.name, data.type)); } } } else { myFieldToNameMapping = null; } }
@Override public BaseInspectionVisitor buildVisitor() { return new BaseInspectionVisitor() { @Override public void visitField(PsiField field) { final boolean ruleAnnotated = REPORT_RULE_PROBLEMS && AnnotationUtil.isAnnotated(field, RULE_FQN, false); final boolean classRuleAnnotated = REPORT_CLASS_RULE_PROBLEMS && AnnotationUtil.isAnnotated(field, CLASS_RULE_FQN, false); if (ruleAnnotated || classRuleAnnotated) { String annotation = ruleAnnotated ? RULE_FQN : CLASS_RULE_FQN; String errorMessage = getPublicStaticErrorMessage(field, ruleAnnotated, classRuleAnnotated); if (errorMessage != null) { registerError(field.getNameIdentifier(), InspectionGadgetsBundle.message("junit.rule.problem.descriptor", annotation, errorMessage), "Make field " + errorMessage, annotation); } if (!InheritanceUtil.isInheritor(PsiUtil.resolveClassInClassTypeOnly(field.getType()), false, "org.junit.rules.TestRule")) { registerError(field.getNameIdentifier(), InspectionGadgetsBundle.message("junit.rule.type.problem.descriptor")); } } } }; }
@Override public void visitSynchronizedStatement(GrSynchronizedStatement synchronizedStatement) { super.visitSynchronizedStatement(synchronizedStatement); final GrExpression lock = synchronizedStatement.getMonitor(); if (lock == null || !(lock instanceof GrReferenceExpression)) { return; } final PsiElement referent = ((PsiReference) lock).resolve(); if (!(referent instanceof PsiField)) { return; } final PsiField field = (PsiField) referent; if (field.hasModifierProperty(PsiModifier.FINAL)) { return; } registerError(lock); }
@Override public void visitField(@NotNull PsiField field) { if (!field.hasModifierProperty(PsiModifier.STATIC)) { return; } if (field.hasModifierProperty(PsiModifier.FINAL)) { if (!checkMutableFinals) { return; } else { final PsiType type = field.getType(); if (ClassUtils.isImmutable(type)) { return; } } } final String name = field.getName(); if (name == null) { return; } if (isValid(name)) { return; } registerFieldError(field, name); }
@Override public void visitReferenceExpression(@NotNull PsiReferenceExpression expression) { super.visitReferenceExpression(expression); final String name = expression.getReferenceName(); if (!HardcodedMethodConstants.OUT.equals(name) && !HardcodedMethodConstants.ERR.equals(name)) { return; } final PsiElement referent = expression.resolve(); if (!(referent instanceof PsiField)) { return; } final PsiField field = (PsiField)referent; final PsiClass containingClass = field.getContainingClass(); if (containingClass == null) { return; } final String className = containingClass.getQualifiedName(); if (!"java.lang.System".equals(className)) { return; } registerError(expression, expression); }
@Override protected void doOKAction() { if (myCbFinal.isEnabled()) { PropertiesComponent.getInstance().setValue(PROPERTY_NAME, myCbFinal.isSelected()); } final PsiField[] fields = myTargetClass.getFields(); for (PsiField field : fields) { if (field.getName().equals(getEnteredName())) { int result = Messages.showOkCancelDialog( getContentPane(), CodeInsightBundle.message("dialog.create.field.from.parameter.already.exists.text", getEnteredName()), CodeInsightBundle.message("dialog.create.field.from.parameter.already.exists.title"), Messages.getQuestionIcon()); if (result == Messages.OK) { close(OK_EXIT_CODE); } else { return; } } } close(OK_EXIT_CODE); }
@NotNull public List<ArrangementEntryDependencyInfo> getRoots() { List<ArrangementEntryDependencyInfo> list = ContainerUtil.newArrayList(); for (Map.Entry<PsiField, Set<PsiField>> entry : myFieldDependencies.entrySet()) { ArrangementEntryDependencyInfo currentInfo = myFieldInfosMap.get(entry.getKey()); for (PsiField usedInInitialization : entry.getValue()) { ArrangementEntryDependencyInfo fieldInfo = myFieldInfosMap.get(usedInInitialization); if (fieldInfo != null) currentInfo.addDependentEntryInfo(fieldInfo); } list.add(currentInfo); } return list; }
@Override public void visitClass(@NotNull PsiClass aClass) { if (!containsSynchronization(aClass)) { return; } final VariableAccessVisitor visitor = new VariableAccessVisitor(aClass, countGettersAndSetters); aClass.accept(visitor); final Set<PsiField> fields = visitor.getInappropriatelyAccessedFields(); for (final PsiField field : fields) { if (field.hasModifierProperty(PsiModifier.FINAL) || field.hasModifierProperty(PsiModifier.VOLATILE)) { continue; } final PsiClass containingClass = field.getContainingClass(); if (aClass.equals(containingClass)) { registerFieldError(field, field); } } }
/** * Gets the list of members to be put in the VelocityContext. * * @param members a list of {@link PsiMember} objects. * @param selectedNotNullMembers * @param useAccessors * @return a filtered list of only the fields as {@link FieldElement} objects. */ public static List<FieldElement> getOnlyAsFieldElements(Collection<? extends PsiMember> members, Collection<? extends PsiMember> selectedNotNullMembers, boolean useAccessors) { List<FieldElement> fieldElementList = new ArrayList<FieldElement>(); for (PsiMember member : members) { if (member instanceof PsiField) { PsiField field = (PsiField) member; FieldElement fe = ElementFactory.newFieldElement(field, useAccessors); if (selectedNotNullMembers.contains(member)) { fe.setNotNull(true); } fieldElementList.add(fe); } } return fieldElementList; }
private boolean ifStatementAssignsVolatileVariable( GrIfStatement statement) { GrStatement innerThen = statement.getThenBranch(); innerThen = ControlFlowUtils.stripBraces(innerThen); if (!(innerThen instanceof GrAssignmentExpression)) { return false; } final GrAssignmentExpression assignmentExpression = (GrAssignmentExpression) innerThen; final GrExpression lhs = assignmentExpression.getLValue(); if (!(lhs instanceof GrReferenceExpression)) { return false; } final GrReferenceExpression referenceExpression = (GrReferenceExpression) lhs; final PsiElement element = referenceExpression.resolve(); if (!(element instanceof PsiField)) { return false; } final PsiField field = (PsiField) element; return field.hasModifierProperty(PsiModifier.VOLATILE); }
@Override protected void check(@NotNull GrControlFlowOwner owner, @NotNull ProblemsHolder problemsHolder) { Instruction[] flow = owner.getControlFlow(); ReadWriteVariableInstruction[] reads = ControlFlowBuilderUtil.getReadsWithoutPriorWrites(flow, true); for (ReadWriteVariableInstruction read : reads) { PsiElement element = read.getElement(); if (element instanceof GroovyPsiElement && !(element instanceof GrClosableBlock)) { String name = read.getVariableName(); GroovyPsiElement property = ResolveUtil.resolveProperty((GroovyPsiElement)element, name); if (property != null && !(property instanceof PsiParameter) && !(property instanceof PsiField) && PsiTreeUtil.isAncestor(owner, property, false) && !(myIgnoreBooleanExpressions && isBooleanCheck(element)) ) { problemsHolder.registerProblem(element, GroovyInspectionBundle.message("unassigned.access.tooltip", name)); } } } }
@Override public void visitField(@NotNull PsiField field) { super.visitField(field); if (!field.hasModifierProperty(PsiModifier.PUBLIC)) { return; } if (!field.hasModifierProperty(PsiModifier.STATIC)) { return; } final PsiType type = field.getType(); if (!(type instanceof PsiArrayType)) { return; } if (CollectionUtils.isConstantEmptyArray(field)) { return; } registerFieldError(field); }
private void appendConflicts(StringBuffer buf, final Set<PsiParameter> paramsNeeding) { if (!paramsNeeding.isEmpty()) { buf.append(paramsNeeding == paramsNeedingGetters ? "Getters" : "Setters"); buf.append(" for the following fields are required:\n"); buf.append(StringUtil.join(paramsNeeding, new Function<PsiParameter, String>() { public String fun(PsiParameter psiParameter) { final IntroduceParameterObjectProcessor.ParameterChunk chunk = IntroduceParameterObjectProcessor.ParameterChunk.getChunkByParameter(psiParameter, parameters); if (chunk != null) { final PsiField field = chunk.getField(); if (field != null) { return field.getName(); } } return psiParameter.getName(); } }, ", ")); buf.append(".\n"); } }
@Override protected String buildMethod(PsiClass psiClass, boolean isOverride, boolean needAll) { StringBuilder sb = new StringBuilder(); sb.append("public ").append(getMethodType()).append(mMethodName).append("(){"); PsiField[] fields; if (isOverride && !needAll) { sb.append(getMethodType()).append(mFieldName).append("=super.").append(mMethodName).append("();"); fields = psiClass.getFields(); } else { sb.append(getMethodType()).append(mFieldName).append("=new ").append(getParamsType()).append("();"); fields = psiClass.getAllFields(); } for (PsiField field : fields) { PsiModifierList modifiers = field.getModifierList(); if (!findIgnore(modifiers)) { if (findPostFiles(modifiers)) { sb.append("if (").append(field.getName()).append("!=null&&").append(field.getName()).append(".size()>0){"); sb.append("for (FileInput file : ").append(field.getName()).append(") {"); sb.append(mFieldName).append(".put(file.key + \"\\\"; filename=\\\"\" + file.filename,") .append(getValueType()).append(".create(").append(getMediaType()).append(".parse(guessMimeType(file.filename)), file.file));}}"); } else if (findPostFile(modifiers)) { sb.append("if (").append(field.getName()).append("!=null){"); sb.append(mFieldName).append(".put(").append(field.getName()).append(".key + \"\\\"; filename=\\\"\" + ").append(field.getName()) .append(".filename, ").append(getValueType()).append(".create(").append(getMediaType()).append(".parse(guessMimeType(") .append(field.getName()).append(".filename)),").append(field.getName()).append(".file));}"); } else { sb.append(mFieldName).append(".put(").append("\"").append(field.getName()).append("\", ").append(getValueType()) .append(".create(").append(getMediaType()).append(".parse(\"text/plain\"), String.valueOf(").append(field.getName()).append(")));"); } } } sb.append("return ").append(mFieldName).append(";}"); return sb.toString(); }
@Override protected String buildMethod(PsiClass psiClass, boolean isOverride, boolean needAll) { StringBuilder sb = new StringBuilder(); sb.append("public ").append(getMethodType()).append(mMethodName).append("(){"); PsiField[] fields; if (isOverride && !needAll) { sb.append(getMethodType()).append(mFieldName).append("=super.").append(mMethodName).append("();"); fields = psiClass.getFields(); } else { sb.append(getMethodType()).append(mFieldName).append("=new ").append(getMethodType()).append("().setType(MultipartBody.FORM);"); fields = psiClass.getAllFields(); } for (PsiField field : fields) { PsiModifierList modifiers = field.getModifierList(); if (!findIgnore(modifiers)) { if (findPostFiles(modifiers)) { sb.append("if (").append(field.getName()).append("!=null&&").append(field.getName()).append(".size()>0){"); sb.append("for (FileInput file : ").append(field.getName()).append(") {"); sb.append(mFieldName).append(".addFormDataPart(file.key, file.filename, ") .append(getValueType()).append(".create(").append(getMediaType()).append(".parse(guessMimeType(file.filename)), file.file));}}"); } else if (findPostFile(modifiers)) { sb.append("if (").append(field.getName()).append("!=null){"); sb.append(mFieldName).append(".addFormDataPart(").append(field.getName()).append(".key,") .append(field.getName()).append(".filename,").append(getValueType()).append(".create(").append(getMediaType()).append(".parse(guessMimeType(") .append(field.getName()).append(".filename)),").append(field.getName()).append(".file));}"); } else { sb.append(mFieldName).append(".addFormDataPart(\"").append(field.getName()).append("\", String.valueOf(").append(field.getName()).append("));"); } } } sb.append("return ").append(mFieldName).append(";}"); return sb.toString(); }
@Override protected String buildMethod(PsiClass psiClass, boolean isOverride, boolean needAll) { StringBuilder sb = new StringBuilder(); sb.append("public ").append(getMethodType()).append(mMethodName).append("(){"); PsiField[] fields; if (isOverride && !needAll) { sb.append(getMethodType()).append(mFieldName).append("=super.").append(mMethodName).append("();"); fields = psiClass.getFields(); } else { sb.append(getMethodType()).append(mFieldName).append("=new ").append(getParamsType()).append("();"); fields = psiClass.getAllFields(); } for (PsiField field : fields) { PsiModifierList modifiers = field.getModifierList(); if (!findIgnore(modifiers)) { if (findPostFiles(modifiers)) { sb.append("if (").append(field.getName()).append("!=null&&").append(field.getName()).append(".size()>0){"); sb.append("for (FileInput file : ").append(field.getName()).append(") {"); sb.append(mFieldName).append(".add(").append(getValueType()).append(".createFormData(file.key, file.filename, ") .append(getRequestBody()).append(".create(").append(getMediaType()).append(".parse(guessMimeType(file.filename)), file.file)));}}"); } else if (findPostFile(modifiers)) { sb.append("if (").append(field.getName()).append("!=null){"); sb.append(mFieldName).append(".add(").append(getValueType()).append(".createFormData(").append(field.getName()).append(".key,") .append(field.getName()).append(".filename,").append(getRequestBody()).append(".create(").append(getMediaType()).append(".parse(guessMimeType(") .append(field.getName()).append(".filename)),").append(field.getName()).append(".file)));}"); } else { sb.append(mFieldName).append(".add(").append(getValueType()).append(".createFormData(\"").append(field.getName()).append("\", String.valueOf(").append(field.getName()).append(")));"); } } } sb.append("return ").append(mFieldName).append(";}"); return sb.toString(); }
@NotNull public static Optional<PsiField> findSettablePsiField(@NotNull PsiClass clazz, @Nullable String propertyName) { PsiMethod propertySetter = PropertyUtil.findPropertySetter(clazz, propertyName, false, true); return null == propertySetter ? Optional.empty() : Optional.ofNullable(PropertyUtil.findPropertyFieldByMember(propertySetter)); }
@Nullable public static PsiType getWrappedPropertyType(final PsiField field) { return CachedValuesManager.getCachedValue(field, () -> { final PsiType fieldType = field.getType(); final PsiClassType.ClassResolveResult resolveResult = com.intellij.psi.util.PsiUtil.resolveGenericsClassInType(fieldType); final PsiClass fieldClass = resolveResult.getElement(); if (fieldClass == null) { final PsiType propertyType = eraseFreeTypeParameters(fieldType, field); return CachedValueProvider.Result.create(propertyType, JAVA_STRUCTURE_MODIFICATION_COUNT); } return CachedValueProvider.Result.create(null, JAVA_STRUCTURE_MODIFICATION_COUNT); }); }
public boolean resolutionMatches(PsiField field, PsiField fieldToSearch) { Resolution fieldResolution = resolutionProvider.getResolutionFrom(field); Resolution resolution = resolutionProvider.getResolutionFrom(fieldToSearch); if (resolution != fieldResolution) { return false; } if (resolution != Resolution.NAME) { return field.getType().getPresentableText().equalsIgnoreCase(fieldToSearch.getType().getPresentableText()); } return Objects.equals( field.getName(), fieldToSearch.getName() ); }
@Nullable private MyLineMarkerInfo collectMarkerFor(@NotNull PsiElement element) { Optional<PsiField> field = PsiElementUtil.findParentOfTypeOn(element, PsiField.class); if (!(element instanceof PsiIdentifier) || !(element.getParent() instanceof PsiField)) { return null; } List<PsiField> references = allReferencingFields(field.orElseThrow(IllegalArgumentException::new)); if (references.isEmpty()) { return null; } return new MyLineMarkerInfo(element, Icons.JGIVEN, new MarkerType("jgiven", (e) -> "JGiven States", navigatorToElements()), "JGiven States"); }
@NotNull private LineMarkerNavigator navigatorToElements() { return new LineMarkerNavigator() { @Override public void browse(MouseEvent e, PsiElement element) { Optional<PsiField> field = PsiElementUtil.findParentOfTypeOn(element, PsiField.class); List<PsiField> references = allReferencingFields(field.orElseThrow(IllegalArgumentException::new)); PsiElementListNavigator.openTargets(e, Iterables.toArray(references, PsiField.class), "JGiven States", "", new DefaultPsiElementCellRenderer()); } }; }
public List<PsiReference> findReferences(PsiField field, int maxNumberOfResults) { PsiClass fieldClass = PsiTypesUtil.getPsiClass(field.getType()); if (fieldClass == null) { return Collections.emptyList(); } Project project = field.getProject(); PsiManager manager = PsiManager.getInstance(project); JGivenUsageProvider usageProvider = new JGivenUsageProvider(scenarioStateProvider, resolutionHandler, new ReferenceFactory(manager)); StateReferenceProcessor processor = new StateReferenceProcessor(field, maxNumberOfResults, usageProvider); SearchScope scope = GlobalSearchScope.everythingScope(project).intersectWith(javaFilesScope(project)); findPsiFields(project, (GlobalSearchScope) scope, processor); return processor.getResults(); }
@Override public boolean process(PsiField field) { PsiReference reference = usageProvider.createReferenceIfJGivenUsage(fieldToSearch, field); if (reference != null) { results.add(reference); } return results.size() < maxNumberOfResults || maxNumberOfResults == ScenarioStateReferenceProvider.ANY_NUMBER_OF_RESULTS; }
@Nullable PsiReference createReferenceIfJGivenUsage(PsiField fieldToSearch, PsiField field) { if (scenarioStateProvider.isJGivenScenarioState(field) && !fieldToSearch.equals(field) && resolutionHandler.resolutionMatches(field, fieldToSearch)) { return referenceFactory.referenceFor(field); } return null; }
@Override public void processQuery(@NotNull ReferencesSearch.SearchParameters queryParameters, @NotNull Processor<PsiReference> consumer) { final PsiElement element = queryParameters.getElementToSearch(); ApplicationManager.getApplication().runReadAction(() -> { SearchScope scope = queryParameters.getEffectiveSearchScope(); if (!scenarioStateProvider.isJGivenScenarioState(element) || !(scope instanceof GlobalSearchScope)) { return; } PsiField field = (PsiField) element; scenarioStateReferenceProvider.findReferences(field).forEach(consumer::process); }); }
@Test public void should_add_reference() throws Exception { PsiField field = mock(PsiField.class); StateReferenceProcessor processor = referenceProcessorFor(2); PsiReference reference = mock(PsiReference.class); when(usageProvider.createReferenceIfJGivenUsage(fieldToSearch, field)).thenReturn(reference); boolean result = processor.process(field); assertThat(processor.getResults()).containsOnly(reference); assertThat(result).isTrue(); }
@Test public void should_not_add_reference() throws Exception { PsiField field = mock(PsiField.class); StateReferenceProcessor processor = referenceProcessorFor(1); when(usageProvider.createReferenceIfJGivenUsage(fieldToSearch, field)).thenReturn(null); processor.process(field); assertThat(processor.getResults()).isEmpty(); }
@Test public void should_return_false_if_enough_results_have_been_read() throws Exception { PsiField field1 = mock(PsiField.class); PsiReference reference1 = mock(PsiReference.class); when(usageProvider.createReferenceIfJGivenUsage(fieldToSearch, field1)).thenReturn(reference1); StateReferenceProcessor processor = referenceProcessorFor(1); boolean result = processor.process(field1); assertThat(result).isFalse(); }