Java Code Examples for javax.lang.model.element.ElementKind#FIELD

The following examples show how to use javax.lang.model.element.ElementKind#FIELD . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PrivateStaticFinalLoggers.java    From besu with Apache License 2.0 6 votes vote down vote up
@Override
public Description matchVariable(final VariableTree tree, final VisitorState state) {
  final Symbol.VarSymbol sym = ASTHelpers.getSymbol(tree);
  if (sym == null || sym.getKind() != ElementKind.FIELD) {
    return NO_MATCH;
  }
  if (sym.getModifiers()
      .containsAll(List.of(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL))) {
    return NO_MATCH;
  }
  if (!isSubtype(
      getType(tree), state.getTypeFromString("org.apache.logging.log4j.Logger"), state)) {
    return NO_MATCH;
  }
  return buildDescription(tree)
      .addFix(addModifiers(tree, state, Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL))
      .build();
}
 
Example 2
Source File: CompromiseSATest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testFieldSignatureFromElement () throws Exception {
InputStream in = this.prepareData(TEST_CLASS);
try {
    JavacTask jt = prepareJavac ();
    Elements elements = jt.getElements();
    TypeElement be = elements.getTypeElement(TEST_CLASS);
    ClassFile cf = new ClassFile (in, true);
    String className = cf.getName().getInternalName().replace('/','.');	    //NOI18N
    List<? extends Element> members = be.getEnclosedElements();
    for (Element e : members) {
	if (e.getKind() == ElementKind.FIELD) {
	    String[] msig = ClassFileUtil.createFieldDescriptor((VariableElement) e);
	    assertEquals (className,msig[0]);
	    assertEquals (e.getSimpleName().toString(),msig[1]);
	    Variable v = cf.getVariable (e.getSimpleName().toString());		    
	    assertNotNull (v);		    
	    assertEquals (v.getDescriptor(), msig[2]);
	}
    }
} finally {
    in.close ();
}
   }
 
Example 3
Source File: ABTestProcessor.java    From abtestgen with Apache License 2.0 6 votes vote down vote up
private void getResTests(RoundEnvironment roundEnv, Multimap<String, ViewTestData> viewTestMap) {
  for (Element element : roundEnv.getElementsAnnotatedWith(ResourceTest.class)) {
    ResourceTest testAnnotation = element.getAnnotation(ResourceTest.class);
    if (element.getKind() != ElementKind.FIELD) {
      messager.printMessage(Diagnostic.Kind.ERROR, "Can only run ABView tests on a field!");
    } else {
      TypeMirror typeMirror = element.asType();
      String type = typeMirror.toString();
      TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
      Integer[] ints = new Integer[testAnnotation.values().length];
      for (int i = 0; i < ints.length; i++) {
        ints[i] = testAnnotation.values()[i];
      }
      ViewTestData data =
          createABViewData(testAnnotation.testName(), testAnnotation.method(), element,
              enclosingElement, ints);
      viewTestMap.put(data.getTestClassPath(), data);
    }
  }
}
 
Example 4
Source File: TypeProductionFilter.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private boolean hasBeanType( TypeMirror arrayComponentType,
        Element productionElement )
{
    Collection<TypeMirror> restrictedTypes = RestrictedTypedFilter.
        getRestrictedTypes(productionElement, getImplementation());
    if ( restrictedTypes == null  ){
        TypeMirror productionType= null;
        if ( productionElement.getKind() == ElementKind.FIELD){
            productionType = productionElement.asType();
        }
        else if ( productionElement.getKind() == ElementKind.METHOD){
            productionType = ((ExecutableElement)productionElement).
                getReturnType();
        }
        return checkArrayBeanType(productionType, arrayComponentType);
    }
    Types types = getImplementation().getHelper().
        getCompilationController().getTypes();
    for( TypeMirror restrictedType : restrictedTypes ){
        if ( types.isSameType( restrictedType, getElementType())){
            return true;
        }
    }
    return false;
}
 
Example 5
Source File: BaseAbstractProcessor.java    From RapidORM with Apache License 2.0 5 votes vote down vote up
protected Element getElementOwnerElement(Element element) {
    Element resultEle;

    // todo: Get the Class which element's owner.
    ElementKind elementKind = element.getKind();
    if (ElementKind.FIELD == elementKind) {
        resultEle = MoreElements.asVariable(element).getEnclosingElement();
    } else if (ElementKind.METHOD == elementKind) {
        resultEle = MoreElements.asExecutable(element).getEnclosingElement();
    } else {
        resultEle = element;
    }
    return resultEle;
}
 
Example 6
Source File: Tiny.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean tryResolveIdentifier(CompilationInfo info, TreePath place, 
        TypeMirror expectedType, Set<Element> resolved, String ident) {
    SourcePositions[] positions = new SourcePositions[1];
    ExpressionTree et = info.getTreeUtilities().parseExpression(ident, positions);
    TypeMirror unqType = info.getTreeUtilities().attributeTree(et, info.getTrees().getScope(place));
    Element e = info.getTrees().getElement(new TreePath(place, et));
    if (!Utilities.isValidType(unqType) || e == null || 
            (e.getKind() != ElementKind.FIELD && e.getKind() != ElementKind.ENUM_CONSTANT)) {
        return false;
    }
    if (!resolved.add(e)) {
        return false;
    }
    return info.getTypes().isAssignable(unqType, expectedType);
}
 
Example 7
Source File: SourceTreeModel.java    From Akatsuki with Apache License 2.0 5 votes vote down vote up
private static void collectElements(ArrayList<Element> elements, Element root,
		Set<Class<? extends Annotation>> classes) {
	if (root.getKind() == ElementKind.CLASS) {
		for (Element element : root.getEnclosedElements()) {
			collectElements(elements, element, classes);
		}
	} else if (root.getKind() == ElementKind.FIELD
			&& classes.stream().anyMatch(c -> root.getAnnotation(c) != null)) {
		elements.add(root);
	}
}
 
Example 8
Source File: InjectPresenterProcessor.java    From Moxy with MIT License 5 votes vote down vote up
private static List<TargetPresenterField> collectFields(TypeElement presentersContainer) {
	List<TargetPresenterField> fields = new ArrayList<>();

	for (Element element : presentersContainer.getEnclosedElements()) {
		if (element.getKind() != ElementKind.FIELD) {
			continue;
		}

		AnnotationMirror annotation = Util.getAnnotation(element, PRESENTER_FIELD_ANNOTATION);

		if (annotation == null) {
			continue;
		}

		// TODO: simplify?
		TypeMirror clazz = ((DeclaredType) element.asType()).asElement().asType();

		String name = element.toString();

		String type = Util.getAnnotationValueAsString(annotation, "type");
		String tag = Util.getAnnotationValueAsString(annotation, "tag");
		String presenterId = Util.getAnnotationValueAsString(annotation, "presenterId");

		TargetPresenterField field = new TargetPresenterField(clazz, name, type, tag, presenterId);
		fields.add(field);
	}
	return fields;
}
 
Example 9
Source File: AbstractCommandSpecProcessor.java    From picocli with Apache License 2.0 5 votes vote down vote up
private TypedMember extractTypedMember(Element element, String annotation) {
    debugElement(element, annotation);
    if (element.getKind() == ElementKind.FIELD) { // || element.getKind() == ElementKind.PARAMETER) {
        return new TypedMember((VariableElement) element, -1);
    } else if (element.getKind() == ElementKind.METHOD) {
        return new TypedMember((ExecutableElement) element, AbstractCommandSpecProcessor.this);
    }
    error(element, "Cannot only process %s annotations on fields, " +
            "methods and method parameters, not on %s", annotation, element.getKind());
    return null;
}
 
Example 10
Source File: IntroduceFieldPanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean updateUI(MemberSearchResult result) {
    if (notifier == null) {
        return false;
    } 
    boolean ok = false;
    boolean refactor = false;
    if (result == null) {
        ok = true;
    } else if (result.getConflictingKind() != null) {
        if (result.getConflictingKind() != ElementKind.FIELD) {
            notifier.setErrorMessage(Bundle.ERR_LocalVarOrParameterHidden());
        } else {
            notifier.setErrorMessage(Bundle.ERR_ConflictingField());
        }
        ok = false;
    } else if (result.getOverriden() != null) {
        // fields are not really overriden, but introducing a field which shadows
        // a superclass may affect outside code.
        notifier.setWarningMessage(Bundle.WARN_InheritedFieldHidden());
    } else if (result.getShadowed() != null) {
        notifier.setInformationMessage(Bundle.INFO_FieldHidden());
        refactor = true;
    } else {
        ok = true;
    }
    if (ok) {
        notifier.clearMessages();
    }
    if (refactor) {
        checkRefactorExisting.setEnabled(true);
        checkRefactorExisting.setSelected(refactor);
    } else {
        checkRefactorExisting.setEnabled(false);
        checkRefactorExisting.setSelected(false);
    }
    return result == null || !result.isConflicting();
}
 
Example 11
Source File: ResourceStringFoldProvider.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public Void visitMethodInvocation(MethodInvocationTree node, Void p) {
    messageMethod = null;
    exprBundleName = null;

    Void d = scan(node.getMethodSelect(), p);
    
    try {
        if (messageMethod == null) {
            return d;
        }
        String bundleFile = null;
        if (messageMethod.getKeyParam() == MessagePattern.GET_BUNDLE_CALL) {
            processGetBundleCall(node);
        } else {
            int bp = messageMethod.getBundleParam();
            if (bp == MessagePattern.BUNDLE_FROM_CLASS) {
                TypeMirror tm = info.getTrees().getTypeMirror(methodOwnerPath);
                if (tm != null && tm.getKind() == TypeKind.DECLARED) {
                    bundleFile = bundleFileFromClass(methodOwnerPath, messageMethod.getBundleFile());
                }
            } else if (bp == MessagePattern.BUNDLE_FROM_INSTANCE) {
                // simplification: assume the selector expression is a variable
                Element el = info.getTrees().getElement(methodOwnerPath);
                if (el != null && (el.getKind() == ElementKind.LOCAL_VARIABLE || el.getKind() == ElementKind.FIELD)) {
                    bundleFile = variableBundles.get(el);
                } else {
                    bundleFile = exprBundleName;
                }
            } else if (bp >= 0 && bp < node.getArguments().size()) {
                bundleFile = getBundleName(node, bp, messageMethod.getBundleFile());
            }
        }

        if (bundleFile == null) {
            return d;
        }

        int keyIndex = messageMethod.getKeyParam();
        if (node.getArguments().size() <= keyIndex) {
            return d;
        }

        String keyVal;
        if (keyIndex == MessagePattern.KEY_FROM_METHODNAME) {
            keyVal = this.methodName;
        } else {
            ExpressionTree keyArg = node.getArguments().get(keyIndex);
            if (keyArg.getKind() != Tree.Kind.STRING_LITERAL) {
                return d;
            }
            Object o = ((LiteralTree)keyArg).getValue();
            if (o == null) {
                return d;
            }
            keyVal = o.toString();
        }

        defineFold(bundleFile, keyVal, node);
    } finally {
    
        String expr = exprBundleName;

        scan(node.getArguments(), p);

        this.exprBundleName = expr;
    }
    
    // simplification, accept only String literals
    return d;
}
 
Example 12
Source File: RenamePropertyRefactoringPlugin.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
protected Problem fastCheckParameters(CompilationController info) throws IOException {
    if (!isRenameProperty()) {
        return null;
    }
    initDelegates();
    
    info.toPhase(JavaSource.Phase.RESOLVED);
    Element el = property.resolveElement(info);
    if (el == null || el.getKind() != ElementKind.FIELD) {
        return null;
    }
    String oldName = el.getSimpleName().toString();
    String bareName = RefactoringUtils.removeFieldPrefixSuffix(el, codeStyle);

    boolean isStatic = el.getModifiers().contains(Modifier.STATIC);
    String bareNewName = CodeStyleUtils.removePrefixSuffix(refactoring.getNewName(),
            isStatic ? codeStyle.getStaticFieldNamePrefix() : codeStyle.getFieldNamePrefix(),
            isStatic ? codeStyle.getStaticFieldNameSuffix() : codeStyle.getFieldNameSuffix());
    
    if (bareName.equals(bareNewName)) {
        return null;
    }
    
    Problem p = null;
    JavaRenameProperties renameProps = refactoring.getContext().lookup(JavaRenameProperties.class);
    boolean saveNoChange = false;
    if (renameProps != null) {
        saveNoChange = renameProps.isNoChangeOK();
        renameProps.setNoChangeOK(true);
    }
    try {
        if (getterDelegate != null) {
            String gettername = CodeStyleUtils.computeGetterName(
                                    refactoring.getNewName(), isBoolean, isStatic, codeStyle);
            getterDelegate.setNewName(gettername);
            p = JavaPluginUtils.chainProblems(p, getterDelegate.fastCheckParameters());
            if (p != null && p.isFatal()) {
                return p;
            }
        }
        if (setterDelegate != null) {
            String settername = CodeStyleUtils.computeSetterName(
                                    refactoring.getNewName(), isStatic, codeStyle);
            setterDelegate.setNewName(settername);
            p = JavaPluginUtils.chainProblems(p, setterDelegate.fastCheckParameters());
            if (p != null && p.isFatal()) {
                return p;
            }
        }
        if (parameterDelegate != null) {
            String newParam = RefactoringUtils.addParamPrefixSuffix(
                            CodeStyleUtils.removePrefixSuffix(
                            refactoring.getNewName(),
                            isStatic ? codeStyle.getStaticFieldNamePrefix() : codeStyle.getFieldNamePrefix(),
                            isStatic ? codeStyle.getStaticFieldNameSuffix() : codeStyle.getFieldNameSuffix()), codeStyle);
            parameterDelegate.setNewName(newParam);
            p = JavaPluginUtils.chainProblems(p, parameterDelegate.fastCheckParameters());
            if (p != null && p.isFatal()) {
                return p;
            }
        }
    } finally {
        if (renameProps != null) {
            renameProps.setNoChangeOK(saveNoChange);
        }
    }
    return p = JavaPluginUtils.chainProblems(p, super.fastCheckParameters(info));
}
 
Example 13
Source File: ParcelablePleaseProcessor.java    From ParcelablePlease with Apache License 2.0 4 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {

  Element lastElement = null;
  CodeGenerator codeGenerator = new CodeGenerator(elementUtils, filer);

  for (Element element : env.getElementsAnnotatedWith(ParcelablePlease.class)) {

    if (!isClass(element)) {
      continue;
    }

    List<ParcelableField> fields = new ArrayList<ParcelableField>();

    lastElement = element;

    ParcelablePlease annotation = element.getAnnotation(ParcelablePlease.class);
    boolean allFields = annotation.allFields();
    boolean ignorePrivateFields = annotation.ignorePrivateFields();

    List<? extends Element> memberFields = elementUtils.getAllMembers((TypeElement) element);

    if (memberFields != null) {
      for (Element member : memberFields) {
        // Search for fields

        if (member.getKind() != ElementKind.FIELD || !(member instanceof VariableElement)) {
          continue; // Not a field, so go on
        }

        // it's a field, so go on

        ParcelableNoThanks skipFieldAnnotation = member.getAnnotation(ParcelableNoThanks.class);
        if (skipFieldAnnotation != null) {
          // Field is marked as not parcelabel, so continue with the next
          continue;
        }

        if (!allFields) {
          ParcelableThisPlease fieldAnnotated = member.getAnnotation(ParcelableThisPlease.class);
          if (fieldAnnotated == null) {
            // Not all fields should parcelable,
            // and this field is not annotated as parcelable, so skip this field
            continue;
          }
        }

        // Check the visibility of the field and modifiers
        Set<Modifier> modifiers = member.getModifiers();

        if (modifiers.contains(Modifier.STATIC)) {
          // Static fields are skipped
          continue;
        }

        if (modifiers.contains(Modifier.PRIVATE)) {

          if (ignorePrivateFields) {
            continue;
          }

          ProcessorMessage.error(member,
              "The field %s  in %s is private. At least default package visibility is required "
                  + "or annotate this field as not been parcelable with @%s "
                  + "or configure this class to ignore private fields "
                  + "with @%s( ignorePrivateFields = true )", member.getSimpleName(),
              element.getSimpleName(), ParcelableNoThanks.class.getSimpleName(),
              ParcelablePlease.class.getSimpleName());
        }

        if (modifiers.contains(Modifier.FINAL)) {
          ProcessorMessage.error(member,
              "The field %s in %s is final. Final can not be Parcelable", element.getSimpleName(),
              member.getSimpleName());
        }

        // If we are here the field is be parcelable
        fields.add(new ParcelableField((VariableElement) member, elementUtils, typeUtils));
      }
    }

    //
    // Generate the code
    //

    try {
      codeGenerator.generate((TypeElement) element, fields);
    } catch (Exception e) {
      e.printStackTrace();
      ProcessorMessage.error(lastElement, "An error has occurred while processing %s : %s",
          element.getSimpleName(), e.getMessage());
    }

  } // End for loop

  return true;
}
 
Example 14
Source File: Flow.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public Boolean visitCompoundAssignment(CompoundAssignmentTree node, ConstructorData p) {
    TypeElement oldQName = this.referenceTarget;
    this.referenceTarget = null;

    lValueDereference = true;
    scan(node.getVariable(), null);
    lValueDereference = false;

    Boolean constVal = scan(node.getExpression(), p);

    Element e = info.getTrees().getElement(new TreePath(getCurrentPath(), node.getVariable()));

    if (e != null) {
        if (SUPPORTED_VARIABLES.contains(e.getKind())) {
            VariableElement ve = (VariableElement) e;
            State prevState = variable2State.get(ve);
            if (LOCAL_VARIABLES.contains(e.getKind())) {
                addUse2Values(node.getVariable(), prevState);
            } else if (e.getKind() == ElementKind.FIELD && prevState != null && prevState.hasUnassigned() && !finalCandidates.contains(ve)) {
                usedWhileUndefined.add(ve);
            }
            recordVariableState(ve, getCurrentPath());
        } else if (shouldProcessUndefined(e)) {
            Element cv = canonicalUndefined(e);
            recordVariableState(cv, getCurrentPath());
        }
    }

    this.referenceTarget = oldQName;
    boolean retain = false;
    switch (node.getKind()) {
        case OR_ASSIGNMENT:
            retain = constVal == Boolean.TRUE;
            break;
        case AND_ASSIGNMENT:
            retain = constVal == Boolean.FALSE;
            break;
    }
    return retain ? constVal : null;
}
 
Example 15
Source File: ExpectedTypeResolver.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * For member select, find the most generic type which declares that member.
 * When traversing up the inheritance tree, the return type must be checked, as it may
 * become too general to fit the parent expression's requirements.
 */
@Override
public List<? extends TypeMirror> visitMemberSelect(MemberSelectTree tree, Object v) {
    if (casted != null) {
        // if the casted type is a primitive, the cast is NOT redundant as member select is applied to
        // the originally primitive value.
        TypeMirror castedType = info.getTrees().getTypeMirror(casted);
        if (castedType != null && castedType.getKind().isPrimitive()) {
            notRedundant = true;
        }
    }
    // must compute expected type of the method:
    TreePath[] p = new TreePath[1];
    ExpressionTree[] e = new ExpressionTree[1];
    Tree[] l = new Tree[1];
    List<TypeMirror> tt = new ArrayList<TypeMirror>();
    Element el = info.getTrees().getElement(getCurrentPath());
    
    if (el == null) {
        return null;
    }
    
    if (el.getKind() == ElementKind.METHOD) {
        // special hack: if the casted value is a lambda, we NEED to assign it a type prior to method invocation:
        TreePath exp = getExpressionWithoutCasts();
        if (exp != null && exp.getLeaf().getKind() == Tree.Kind.LAMBDA_EXPRESSION) {
            return null;
        }
        TreePath methodInvocation = getCurrentPath().getParentPath();
        TreePath invocationParent = methodInvocation.getParentPath();
        ExpectedTypeResolver subResolver = new ExpectedTypeResolver(methodInvocation, info);
        subResolver.theExpression = methodInvocation;
        subResolver.typeCastDepth++;
        List<? extends TypeMirror> parentTypes = subResolver.scan(invocationParent, v);
        TypeMirror castable = null;
        if (parentTypes == null) {
            castable = subResolver.getCastableTo();
        }
        if (parentTypes != null || castable != null) {
            TypeMirror exprType = info.getTrees().getTypeMirror(new TreePath(getCurrentPath(), tree.getExpression()));
            if (!(exprType instanceof DeclaredType)) {
                return null;
            }
            ExecutableElement elem = (ExecutableElement)el;
            TreePath method = getCurrentPath();
            while (method != null && method.getLeaf().getKind() != Tree.Kind.METHOD) {
                method = method.getParentPath();
            }
            if (method == null) {
                method = getCurrentPath();
            }
            List<TypeMirror> cans = findBaseTypes(info, elem, (DeclaredType)exprType,
                    parentTypes, 
                    castable, 
                    info.getTrees().getScope(method));
            if (!cans.isEmpty()) {
                return cans;
            }
        } else {
            TypeMirror exprm = info.getTrees().getTypeMirror(new TreePath(getCurrentPath(), tree.getExpression()));
            return Collections.singletonList(exprm);
        }
    } else if (el.getKind() == ElementKind.FIELD) {
        // access to a field
        Element parent = el.getEnclosingElement();
        if (parent.getKind() == ElementKind.CLASS || parent.getKind() == ElementKind.INTERFACE || parent.getKind() == ElementKind.ENUM) {
            return Collections.singletonList(parent.asType());
        }
    }
    return null;
}
 
Example 16
Source File: PropertyProcessor.java    From jasperreports with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv)
{
	CompiledPropertiesMetadata props = new CompiledPropertiesMetadata();
	String messagesName = processingEnv.getOptions().get(OPTION_MESSAGES_NAME);
	props.setMessagesName(messagesName);
	
	for (TypeElement annotation : annotations)
	{
		Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(annotation);
		for (Element element : elements)
		{
			if (element.getKind() != ElementKind.FIELD)
			{
				processingEnv.getMessager().printMessage(Kind.WARNING, 
						"Annotation " + annotation + " can only be applied to static fields", 
						element);
				continue;
			}
			
			VariableElement varElement = (VariableElement) element;
			Set<Modifier> modifiers = varElement.getModifiers();
			if (!modifiers.contains(Modifier.STATIC) || !modifiers.contains(Modifier.PUBLIC)
					|| !modifiers.contains(Modifier.FINAL))
			{
				processingEnv.getMessager().printMessage(Kind.WARNING, 
						"Annotation " + annotation + " can only be applied to public static final fields", 
						element);
				continue;
			}
			
			TypeMirror varType = varElement.asType();
			if (!varType.toString().equals(String.class.getCanonicalName()))
			{
				processingEnv.getMessager().printMessage(Kind.WARNING, 
						"Annotation " + annotation + " can only be applied to String fields", 
						element);
				continue;
			}
			
			AnnotationMirror propertyAnnotation = findPropertyAnnotation(varElement);
			if (propertyAnnotation == null)
			{
				//should not happen
				continue;
			}
			
			CompiledPropertyMetadata property = toPropertyMetadata(varElement, propertyAnnotation);
			if (property != null)
			{
				props.addProperty(property);
			}
		}
	}
	
	if (!props.getProperties().isEmpty())
	{
		writePropertiesMetadata(props);
		
		String propertiesDoc = processingEnv.getOptions().get(OPTION_PROPERTIES_DOC);
		if (propertiesDoc != null)
		{
			PropertiesDocReader docReader = new PropertiesDocReader(processingEnv, props);
			docReader.readPropertiesDoc(propertiesDoc);
			docReader.writeDefaultMessages();
			
			String referenceOut = processingEnv.getOptions().get(OPTION_CONFIG_REFERENCE_OUT);
			if (referenceOut != null)
			{
				docReader.writeConfigReference(referenceOut);
			}
		}
	}
	
	return true;
}
 
Example 17
Source File: NoLoggers.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@TriggerTreeKind({Tree.Kind.ANNOTATION_TYPE, Tree.Kind.CLASS, Tree.Kind.ENUM, Tree.Kind.INTERFACE})
public static Iterable<ErrorDescription> checkNoLoggers(HintContext ctx) {
    Element cls = ctx.getInfo().getTrees().getElement(ctx.getPath());
    if (cls == null || cls.getKind() != ElementKind.CLASS || cls.getModifiers().contains(Modifier.ABSTRACT) ||
        (cls.getEnclosingElement() != null && cls.getEnclosingElement().getKind() != ElementKind.PACKAGE)
    ) {
        return null;
    }

    TypeElement loggerTypeElement = ctx.getInfo().getElements().getTypeElement("java.util.logging.Logger"); // NOI18N
    if (loggerTypeElement == null) {
        return null;
    }
    TypeMirror loggerTypeElementAsType = loggerTypeElement.asType();
    if (loggerTypeElementAsType == null || loggerTypeElementAsType.getKind() != TypeKind.DECLARED) {
        return null;
    }

    List<TypeMirror> customLoggersList = new ArrayList<>();
    if (isCustomEnabled(ctx.getPreferences())) {
        List<String> customLoggerClasses = getCustomLoggers(ctx.getPreferences());
        if (customLoggerClasses != null) {
            for (String className : customLoggerClasses) {
                TypeElement customTypeElement = ctx.getInfo().getElements().getTypeElement(className);
                if (customTypeElement == null) {
                    continue;
                }
                TypeMirror customTypeMirror = customTypeElement.asType();
                if (customTypeMirror == null || customTypeMirror.getKind() != TypeKind.DECLARED) {
                    continue;
                }
                customLoggersList.add(customTypeMirror);
            }
        }
    }

    List<VariableElement> loggerFields = new LinkedList<VariableElement>();
    List<VariableElement> fields = ElementFilter.fieldsIn(cls.getEnclosedElements());
    for(VariableElement f : fields) {
        if (f.getKind() != ElementKind.FIELD) {
            continue;
        }

        if (f.asType().equals(loggerTypeElementAsType)) {
            loggerFields.add(f);
        } else if (customLoggersList.contains(f.asType())) {
            loggerFields.add(f);
        }
    }

    if (loggerFields.size() == 0) {
        return Collections.singleton(ErrorDescriptionFactory.forName(
                ctx,
                ctx.getPath(),
                NbBundle.getMessage(NoLoggers.class, "MSG_NoLoggers_checkNoLoggers", cls), //NOI18N
                new NoLoggersFix(NbBundle.getMessage(NoLoggers.class, "MSG_NoLoggers_checkNoLoggers_Fix", cls), TreePathHandle.create(cls, ctx.getInfo())).toEditorFix() //NOI18N
        ));
    } else {
        return null;
    }
}
 
Example 18
Source File: ElementUtil.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Returns whether this variable will be an ObjC instance variable.
 */
public static boolean isInstanceVar(VariableElement element) {
  return element.getKind() == ElementKind.FIELD && !isGlobalVar(element);
}
 
Example 19
Source File: TurbineElement.java    From turbine with Apache License 2.0 4 votes vote down vote up
@Override
public ElementKind getKind() {
  return ((info().access() & TurbineFlag.ACC_ENUM) == TurbineFlag.ACC_ENUM)
      ? ElementKind.ENUM_CONSTANT
      : ElementKind.FIELD;
}
 
Example 20
Source File: RenamePanel.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
  public void initialize() {
      if (initialized) {
          return;
      }

      if (handle!=null && handle.getKind() != Tree.Kind.LABELED_STATEMENT &&
              handle.getElementHandle() != null 
              && (handle.getElementHandle().getKind() == ElementKind.FIELD
              || handle.getElementHandle().getKind() == ElementKind.CLASS
|| handle.getElementHandle().getKind() == ElementKind.METHOD)) {
          JavaSource source = JavaSource.forFileObject(handle.getFileObject());
          CancellableTask<CompilationController> task = new CancellableTask<CompilationController>() {

              @Override
              public void cancel() {
                  throw new UnsupportedOperationException("Not supported yet."); // NOI18N
              }

              @Override
              public void run(CompilationController info) throws Exception {
                  info.toPhase(Phase.RESOLVED);
                  if(handle.getElementHandle().getKind() == ElementKind.FIELD) {
                      VariableElement element = (VariableElement) handle.resolveElement(info);
                      if(element == null) {
                          LOG.log(Level.WARNING, "Cannot resolve ElementHandle {0} {1}", new Object[] {handle, info.getClasspathInfo()});
                          return;
                      }
                      TypeElement parent = (TypeElement) element.getEnclosingElement();
                      boolean hasGetters = false;
                      for (ExecutableElement method : ElementFilter.methodsIn(parent.getEnclosedElements())) {
                          if (RefactoringUtils.isGetter(info, method, element) || RefactoringUtils.isSetter(info, method, element)) {
                              hasGetters = true;
                              break;
                          }
                      }

                      if (hasGetters) {
                          SwingUtilities.invokeLater(new Runnable() {

                              @Override
                              public void run() {
                                  renameGettersAndCheckersCheckBox.setVisible(true);
                              }
                          });
                      }
                  }
                  
                  if(handle.getElementHandle().getKind() == ElementKind.CLASS || handle.getElementHandle().getKind() == ElementKind.METHOD) {
	final Element methodElement = handle.resolveElement(info);
                      if(methodElement == null) {
                          LOG.log(Level.WARNING, "Cannot resolve ElementHandle {0} {1}", new Object[] {handle, info.getClasspathInfo()});
                          return;
                      }
                      final FileObject fileObject = handle.getFileObject();
                      Collection<? extends TestLocator> testLocators = Lookup.getDefault().lookupAll(TestLocator.class);
                      for (final TestLocator testLocator : testLocators) {
                          if(testLocator.appliesTo(fileObject)) {
                              if(testLocator.asynchronous()) {
                                  testLocator.findOpposite(fileObject, -1, new TestLocator.LocationListener() {

                                      @Override
                                      public void foundLocation(FileObject fo, LocationResult location) {
			    if(handle.getElementHandle().getKind() == ElementKind.CLASS) {
				addTestFile(location, testLocator);
			    } else if(handle.getElementHandle().getKind() == ElementKind.METHOD) {
				addTestMethod(location, testLocator, methodElement);
			    }
                                      }
                                  });
                              } else {
		    if(handle.getElementHandle().getKind() == ElementKind.CLASS) {
			addTestFile(testLocator.findOpposite(fileObject, -1), testLocator);
		    } else if (handle.getElementHandle().getKind() == ElementKind.METHOD) {
			addTestMethod(testLocator.findOpposite(fileObject, -1), testLocator, methodElement);
		    }
                              }
                          }
                      }
                  }
              }
          };
          try {
              source.runUserActionTask(task, true);
          } catch (IOException ioe) {
              throw new RuntimeException(ioe);
          }
      }
      
      initialized = true;
  }