Java Code Examples for javax.lang.model.util.Elements

The following are top voted examples for showing how to use javax.lang.model.util.Elements. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: jdoocsoup   File: DataClassBuilderDescriptorTest.java   Source Code and License 6 votes vote down vote up
@Before
public void before() {
    mockedDataClassBuilderAnnotation = mock(DataClassBuilder.class);
    mockedProcessingEnv = mock(ProcessingEnvironment.class);
    mockedTypeElement = mock(TypeElement.class);

    when(mockedDataClassBuilderAnnotation.name()).thenReturn("");
    when(mockedTypeElement.getAnnotation(DataClassBuilder.class)).thenReturn(mockedDataClassBuilderAnnotation);

    mockedElementUtils = mock(Elements.class);
    when(mockedProcessingEnv.getElementUtils()).thenReturn(mockedElementUtils);

    PackageElement mockedPackageElement = mock(PackageElement.class);
    when(mockedElementUtils.getPackageOf(any(Element.class))).thenReturn(mockedPackageElement);

    Name mockedQualifiedName = mock(Name.class);
    when(mockedPackageElement.getQualifiedName()).thenReturn(mockedQualifiedName);
    when(mockedQualifiedName.toString()).thenReturn("eu.rsulkowski.test");

    dataClassBuilderDescriptor = new DataClassBuilderDescriptor(mockedProcessingEnv, mockedTypeElement);
}
 
Example 2
Project: GitHub   File: JsonObjectProcessor.java   Source Code and License 6 votes vote down vote up
private void createOrUpdateFieldHolder(Element element, Elements elements, Types types, JsonObjectHolder objectHolder) {
    JsonIgnore ignoreAnnotation = element.getAnnotation(JsonIgnore.class);
    boolean shouldParse = ignoreAnnotation == null || ignoreAnnotation.ignorePolicy() == IgnorePolicy.SERIALIZE_ONLY;
    boolean shouldSerialize = ignoreAnnotation == null || ignoreAnnotation.ignorePolicy() == IgnorePolicy.PARSE_ONLY;

    if (shouldParse || shouldSerialize) {
        JsonFieldHolder fieldHolder = objectHolder.fieldMap.get(element.getSimpleName().toString());
        if (fieldHolder == null) {
            fieldHolder = new JsonFieldHolder();
            objectHolder.fieldMap.put(element.getSimpleName().toString(), fieldHolder);
        }

        String error = fieldHolder.fill(element, elements, types, null, null, objectHolder, shouldParse, shouldSerialize);
        if (!TextUtils.isEmpty(error)) {
            error(element, error);
        }
    }
}
 
Example 3
Project: react4j   File: ReactProcessor.java   Source Code and License 6 votes vote down vote up
private void determineLifecycleMethods( @Nonnull final TypeElement typeElement,
                                        @Nonnull final ComponentDescriptor descriptor )
{
  /*
   * Get the list of lifecycle methods that have been overridden by typeElement
   * a parent class, or by a default method method implemented by typeElement or
   * a parent class.
   */
  final Collection<ExecutableElement> lifecycleMethods = getComponentLifecycleMethods().values();
  final Elements elementUtils = processingEnv.getElementUtils();
  final Types typeUtils = processingEnv.getTypeUtils();
  final TypeElement componentType = elementUtils.getTypeElement( Constants.COMPONENT_CLASSNAME );
  final List<MethodDescriptor> overriddenLifecycleMethods =
    // Get all methods on type parent classes, and default methods from interfaces
    ProcessorUtil.getMethods( typeElement, processingEnv.getTypeUtils() ).stream()
      // Only keep methods that override the lifecycle methods
      .filter( m -> lifecycleMethods.stream().anyMatch( l -> elementUtils.overrides( m, l, typeElement ) ) )
      //Remove those that come from the base classes
      .filter( m -> m.getEnclosingElement() != componentType )
      .map( m -> new MethodDescriptor( m, (ExecutableType) typeUtils.asMemberOf( descriptor.getDeclaredType(), m ) ) )
      .collect( Collectors.toList() );

  descriptor.setLifecycleMethods( overriddenLifecycleMethods );
}
 
Example 4
Project: LifecycleAware   File: UtilsTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testImplementsInterface() throws Exception {
    Elements mockElementUtils = Mockito.mock(Elements.class);
    Types mockTypeUtils = Mockito.mock(Types.class);

    TypeElement mockElement = Mockito.mock(TypeElement.class);
    doReturn(mockElement)
            .when(mockElementUtils)
            .getTypeElement(TestInterface.class.getName());

    TypeMirror mockMirror = Mockito.mock(TypeMirror.class);
    doReturn(mockMirror)
            .when(mockElement)
            .asType();

    doReturn(true)
            .when(mockTypeUtils)
            .isAssignable(mockMirror, mockMirror);

    boolean actual = Utils.implementsInterface(mockElementUtils, mockTypeUtils, mockElement, TestInterface.class);

    Assert.assertTrue(actual);
}
 
Example 5
Project: GitHub   File: JsonFieldProcessor.java   Source Code and License 6 votes vote down vote up
private boolean isJsonFieldFieldAnnotationValid(Element element, Elements elements) {
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

    Annotation objectAnnotation = enclosingElement.getAnnotation(JsonObject.class);
    if (objectAnnotation == null) {
        error(enclosingElement, "%s: @%s fields can only be in classes annotated with @%s.", enclosingElement.getQualifiedName(), JsonField.class.getSimpleName(), JsonObject.class.getSimpleName());
        return false;
    }

    if (element.getModifiers().contains(PRIVATE) && (TextUtils.isEmpty(JsonFieldHolder.getGetter(element, elements)) || TextUtils.isEmpty(JsonFieldHolder.getSetter(element, elements)))) {
        error(element, "@%s annotation can only be used on private fields if both getter and setter are present.", JsonField.class.getSimpleName());
        return false;
    }

    return true;
}
 
Example 6
Project: GitHub   File: Type.java   Source Code and License 6 votes vote down vote up
public static Type typeFor(TypeMirror typeMirror, TypeMirror typeConverterType, Elements elements, Types types) {
    TypeMirror genericClassTypeMirror = types.erasure(typeMirror);
    boolean hasTypeConverter = typeConverterType != null && !typeConverterType.toString().equals("void");

    Type type;
    if (!hasTypeConverter && typeMirror instanceof ArrayType) {
        TypeMirror arrayTypeMirror = ((ArrayType)typeMirror).getComponentType();
        type = new ArrayCollectionType(Type.typeFor(arrayTypeMirror, null, elements, types));
    } else if (!hasTypeConverter && !genericClassTypeMirror.toString().equals(typeMirror.toString())) {
        type = CollectionType.collectionTypeFor(typeMirror, genericClassTypeMirror, elements, types);

        if (type == null) {
            if (typeMirror.toString().contains("?")) {
                throw new RuntimeException("Generic types with wildcards are currently not supported by LoganSquare.");
            }
            try {
                type = new ParameterizedTypeField(TypeName.get(typeMirror));
            } catch (Exception ignored) { }
        }
    } else {
        type = FieldType.fieldTypeFor(typeMirror, typeConverterType, elements, types);
    }

    return type;
}
 
Example 7
Project: GitHub   File: TypeMirrors.java   Source Code and License 6 votes vote down vote up
TypeMirrors(ProcessingEnvironment env) {
    final Types typeUtils = env.getTypeUtils();
    final Elements elementUtils = env.getElementUtils();

    STRING_MIRROR = elementUtils.getTypeElement("java.lang.String").asType();
    BINARY_MIRROR = typeUtils.getArrayType(typeUtils.getPrimitiveType(TypeKind.BYTE));
    BOOLEAN_MIRROR = elementUtils.getTypeElement(Boolean.class.getName()).asType();
    LONG_MIRROR = elementUtils.getTypeElement(Long.class.getName()).asType();
    INTEGER_MIRROR = elementUtils.getTypeElement(Integer.class.getName()).asType();
    SHORT_MIRROR = elementUtils.getTypeElement(Short.class.getName()).asType();
    BYTE_MIRROR = elementUtils.getTypeElement(Byte.class.getName()).asType();
    DOUBLE_MIRROR = elementUtils.getTypeElement(Double.class.getName()).asType();
    FLOAT_MIRROR = elementUtils.getTypeElement(Float.class.getName()).asType();
    DATE_MIRROR = elementUtils.getTypeElement(Date.class.getName()).asType();

    PRIMITIVE_LONG_MIRROR = typeUtils.getPrimitiveType(TypeKind.LONG);
    PRIMITIVE_INT_MIRROR = typeUtils.getPrimitiveType(TypeKind.INT);
    PRIMITIVE_SHORT_MIRROR = typeUtils.getPrimitiveType(TypeKind.SHORT);
    PRIMITIVE_BYTE_MIRROR = typeUtils.getPrimitiveType(TypeKind.BYTE);
}
 
Example 8
Project: jtsgen   File: TSModuleHandlerTest.java   Source Code and License 6 votes vote down vote up
@Before
public void init() {
    Messager messenger = mock(Messager.class);

    this.annotationValue = mock(AnnotationValue.class);

    this.annotationTypeMirror = mock(TypeMirror.class);
    this.executableElement = mock(ExecutableElement.class);

    this.annotationElement = mock(TypeElement.class);
    when(this.annotationElement.asType()).thenReturn(this.annotationTypeMirror);

    this.elementUtils = mock(Elements.class);
    when(this.elementUtils.getTypeElement(any())).thenReturn(this.annotationElement);

    this.processingEnv = mock(ProcessingEnvironment.class);
    when(processingEnv.getMessager()).thenReturn(messenger);
    when(processingEnv.getElementUtils()).thenReturn(this.elementUtils);

    // finally....
    this.testee = new TSModuleHandler(processingEnv);
}
 
Example 9
Project: Kickback   File: KickbackElementClass.java   Source Code and License 6 votes vote down vote up
public KickbackElementClass(VariableElement variableElement, Elements elementUtils) throws VerifyException {
    KickbackElement kickbackElement = variableElement.getAnnotation(KickbackElement.class);
    Weak weak = variableElement.getAnnotation(Weak.class);
    Soft soft = variableElement.getAnnotation(Soft.class);
    PackageElement packageElement = elementUtils.getPackageOf(variableElement);
    this.variableElement = variableElement;
    this.packageName = packageElement.isUnnamed() ? null : packageElement.getQualifiedName().toString();
    this.typeName = TypeName.get(variableElement.asType());
    this.clazzName = variableElement.getSimpleName().toString();
    this.value = variableElement.getConstantValue();
    if(weak != null) this.isWeak = true;
    else this.isWeak = false;
    if(soft != null) this.isSoft = true;
    else this.isSoft = false;

    if(kickbackElement != null) {
        this.elementName =  StringUtils.toUpperCamel(Strings.isNullOrEmpty(kickbackElement.name()) ? this.clazzName : kickbackElement.name());
    } else {
        this.elementName = StringUtils.toUpperCamel(this.clazzName);
    }

    checkPrimitiveType();
    checkModifierValidate();
    checkAnnotationValidate();
}
 
Example 10
Project: incubator-netbeans   File: ElementJavadoc.java   Source Code and License 6 votes vote down vote up
private StringBuilder getContainingClassOrPackageHeader(Element el, Elements elements, ElementUtilities eu) {
    StringBuilder sb = new StringBuilder();
    if (el.getKind() != ElementKind.PACKAGE && el.getKind() != ElementKind.MODULE) {
        TypeElement cls = eu.enclosingTypeElement(el);
        if (cls != null) {
            switch(cls.getEnclosingElement().getKind()) {
                case ANNOTATION_TYPE:
                case CLASS:
                case ENUM:
                case INTERFACE:
                case PACKAGE:
                    sb.append("<font size='+0'><b>"); //NOI18N
                    createLink(sb, cls, makeNameLineBreakable(cls.getQualifiedName().toString()));
                    sb.append("</b></font>"); //NOI18N)
            }
        } else {
            PackageElement pkg = elements.getPackageOf(el);
            if (pkg != null) {
                sb.append("<font size='+0'><b>"); //NOI18N
                createLink(sb, pkg, makeNameLineBreakable(pkg.getQualifiedName().toString()));
                sb.append("</b></font>"); //NOI18N)
            }
        }
    }
    return sb;
}
 
Example 11
Project: incubator-netbeans   File: JavaCompletionTask.java   Source Code and License 6 votes vote down vote up
private void addPackageContent(final Env env, PackageElement pe, EnumSet<ElementKind> kinds, DeclaredType baseType, boolean insideNew, boolean srcOnly) throws IOException {
    Set<? extends TypeMirror> smartTypes = options.contains(Options.ALL_COMPLETION) ? null : getSmartTypes(env);
    CompilationController controller = env.getController();
    Elements elements = controller.getElements();
    Types types = controller.getTypes();
    Trees trees = controller.getTrees();
    ElementUtilities eu = controller.getElementUtilities();
    Scope scope = env.getScope();
    for (Element e : pe.getEnclosedElements()) {
        if (e.getKind().isClass() || e.getKind().isInterface()) {
            String name = e.getSimpleName().toString();
            if ((env.getExcludes() == null || !env.getExcludes().contains(e))
                    && startsWith(env, name) && (Utilities.isShowDeprecatedMembers() || !elements.isDeprecated(e))
                    && trees.isAccessible(scope, (TypeElement) e)
                    && isOfKindAndType(e.asType(), e, kinds, baseType, scope, trees, types)
                    && !Utilities.isExcluded(eu.getElementName(e, true))) {
                results.add(itemFactory.createTypeItem(env.getController(), (TypeElement) e, (DeclaredType) e.asType(), anchorOffset, null, elements.isDeprecated(e), insideNew, insideNew || env.isInsideClass(), true, isOfSmartType(env, e.asType(), smartTypes), false));
            }
        }
    }
    String pkgName = pe.getQualifiedName() + "."; //NOI18N
    addPackages(env, pkgName, srcOnly);
}
 
Example 12
Project: android-auto-mapper   File: MoreTypes.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the non-object superclass of the type with the proper type parameters.
 * An absent Optional is returned if there is no non-Object superclass.
 */
public static Optional<DeclaredType> nonObjectSuperclass(final Types types, Elements elements,
                                                         DeclaredType type) {
    checkNotNull(types);
    checkNotNull(elements);
    checkNotNull(type);

    final TypeMirror objectType =
            elements.getTypeElement(Object.class.getCanonicalName()).asType();
    // It's guaranteed there's only a single CLASS superclass because java doesn't have multiple
    // class inheritance.
    TypeMirror superclass = getOnlyElement(FluentIterable.from(types.directSupertypes(type))
            .filter(new Predicate<TypeMirror>() {
                @Override
                public boolean apply(TypeMirror input) {
                    return input.getKind().equals(TypeKind.DECLARED)
                            && (MoreElements.asType(
                            MoreTypes.asDeclared(input).asElement())).getKind().equals(ElementKind.CLASS)
                            && !types.isSameType(objectType, input);
                }
            }), null);
    return superclass != null
            ? Optional.of(MoreTypes.asDeclared(superclass))
            : Optional.<DeclaredType>absent();
}
 
Example 13
Project: incubator-netbeans   File: ProfilesAnalyzer.java   Source Code and License 6 votes vote down vote up
FindPosScanner(
        @NonNull final FileObject target,
        @NonNull final Trees trees,
        @NonNull final Elements elements,
        @NonNull final TreeUtilities treeUtilities,
        @NonNull final Collection<? extends ProfileSupport.Violation> violations,
        @NonNull final Result errors) {
    assert target != null;
    assert trees != null;
    assert elements != null;
    assert treeUtilities != null;
    assert violations != null;
    assert errors != null;
    this.target = target;
    this.trees = trees;
    this.elements = elements;
    this.treeUtilities = treeUtilities;
    this.errors = errors;
    for (ProfileSupport.Violation v : violations) {
        final ElementHandle<TypeElement> eh = v.getUsedType();
        if (eh != null) {
            violationsByBinNames.put(eh.getBinaryName(), v);
        }
    }
}
 
Example 14
Project: limitjson   File: LJSONTypeElement.java   Source Code and License 6 votes vote down vote up
public static LJSONTypeElement create(Elements elements, Element element) {
    if (element.getKind() != ElementKind.CLASS) {
        throw new IllegalArgumentException(
                String.format("Only CLASS can be annotated with @%s", LIMITJSON.class.getSimpleName()));
    }
    TypeElement typeElement = (TypeElement) element;
    LJSONTypeElement ljsonElement = new LJSONTypeElement();
    ljsonElement.typeElement = typeElement;
    ljsonElement.elements = elements;
    ArrayList<LIMITJSONVariable> list = new ArrayList<>();
    List<? extends Element> enclosedElements = typeElement.getEnclosedElements();
    if (!Collections.isEmpty(enclosedElements)) {
        for (Element ele : enclosedElements) {
            if (ele instanceof VariableElement) {
                list.add(LJSONVariableElement.create((VariableElement) ele));
            }
        }
    }
    ljsonElement.variableElements = list;
    return ljsonElement;
}
 
Example 15
Project: incubator-netbeans   File: CompromiseSATest.java   Source Code and License 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 16
Project: incubator-netbeans   File: JUnit3TestGenerator.java   Source Code and License 6 votes vote down vote up
/**
 * Finds whether the given {@code TypeElement} or any of its type
 * ancestor contains an accessible static no-arg method
 * of the given name.
 * 
 * @param  typeElement  {@code TypeElement} to search
 * @param  methodName  name of the method to be found
 * @param  elements  support instance to be used for the search
 * @return  {@code true} if the given {@code TypeElement} contains,
 *          whether inherited or declared directly,
 *          a static no-argument method of the given name,
 *          {@code false} otherwise
 */
private boolean containsSuiteMethod(TypeElement typeElement,
                                    Elements elements,
                                    Types types,
                                    TypeMirror testType) {
    List<ExecutableElement> allMethods
            = ElementFilter.methodsIn(elements.getAllMembers(typeElement));
    for (ExecutableElement method : allMethods) {
        if (method.getSimpleName().contentEquals("suite")           //NOI18N
                && method.getParameters().isEmpty()) {
            return method.getModifiers().contains(Modifier.STATIC)
                   && types.isSameType(method.getReturnType(),
                                       testType);
        }
    }
    return false;
}
 
Example 17
Project: incubator-netbeans   File: JavadocCompletionQuery.java   Source Code and License 6 votes vote down vote up
private void addTypes(EnumSet<ElementKind> kinds, DeclaredType baseType,
        Set<? extends Element> toExclude, String prefix,
        int substitutionOffset, JavadocContext jdctx) {
    
    if (queryType == CompletionProvider.COMPLETION_ALL_QUERY_TYPE) {
        if (baseType == null) {
            addAllTypes(jdctx, kinds, toExclude, prefix, substitutionOffset);
        } else {
            Elements elements = jdctx.javac.getElements();
            for(DeclaredType subtype : getSubtypesOf(baseType, prefix, jdctx)) {
                TypeElement elem = (TypeElement)subtype.asElement();
                if ((toExclude == null || !toExclude.contains(elem)) && (Utilities.isShowDeprecatedMembers() || !elements.isDeprecated(elem)))
                    items.add(JavaCompletionItem.createTypeItem(jdctx.javac, elem, subtype, substitutionOffset, jdctx.getReferencesCount(), elements.isDeprecated(elem), false, false, false, false, false, null));
            }
        }
    } else {
        addLocalAndImportedTypes(jdctx, kinds, baseType, toExclude, prefix, substitutionOffset);
        hasAdditionalItems = true;
    }
}
 
Example 18
Project: react4j   File: ProcessorUtil.java   Source Code and License 6 votes vote down vote up
@Nullable
private static AnnotationValue findAnnotationValue( @Nonnull final Elements elements,
                                                    @Nonnull final Element typeElement,
                                                    @Nonnull final String annotationClassName,
                                                    @Nonnull final String parameterName )
{
  final AnnotationMirror mirror = getAnnotationByType( typeElement, annotationClassName );
  final Map<? extends ExecutableElement, ? extends AnnotationValue> values =
    elements.getElementValuesWithDefaults( mirror );
  final ExecutableElement annotationKey = values.keySet().stream().
    filter( k -> parameterName.equals( k.getSimpleName().toString() ) ).findFirst().orElse( null );
  return values.get( annotationKey );
}
 
Example 19
Project: incubator-netbeans   File: UiUtilsTest.java   Source Code and License 6 votes vote down vote up
public void testOpen() throws IOException {
    FileObject workDir = FileUtil.toFileObject(this.getWorkDir());
    assertNotNull(workDir);
    FileObject dataDir = FileUtil.toFileObject(this.getDataDir());
    assertNotNull(dataDir);
    FileObject srcFile = createSource(dataDir, workDir);
    JavaSource js = JavaSource.forFileObject(srcFile);
    ClasspathInfo cpInfo = js.getClasspathInfo();
    CompilationInfo ci = SourceUtilsTestUtil.getCompilationInfo(js, Phase.RESOLVED);
    Elements elements = ci.getElements();
    Element ce = elements.getTypeElement("javax.swing.JTable");
    assertNotNull(ce);
    Object[] result = UiUtils.getOpenInfo(cpInfo, ce);
    assertNotNull(result);
    assertTrue(result[0] instanceof FileObject);
    assertTrue(result[1] instanceof Integer);
    assertEquals(srcFile, result[0]);
    assertEquals(7996, ((Integer) result[1]).intValue());
}
 
Example 20
Project: resourceprovider   File: Utils.java   Source Code and License 5 votes vote down vote up
static String getPackageName(Elements elementUtils, TypeElement type)
    throws UnnamedPackageException {
  PackageElement pkg = elementUtils.getPackageOf(type);
  if (pkg.isUnnamed()) {
    throw new UnnamedPackageException(type);
  }
  return pkg.getQualifiedName().toString();
}
 
Example 21
Project: GitHub   File: RequestManagerFactoryGenerator.java   Source Code and License 5 votes vote down vote up
RequestManagerFactoryGenerator(ProcessingEnvironment processingEnv) {
  Elements elementUtils = processingEnv.getElementUtils();
  glideType = elementUtils.getTypeElement(GLIDE_QUALIFIED_NAME);
  lifecycleType = elementUtils.getTypeElement(LIFECYCLE_QUALIFIED_NAME);
  requestManagerTreeNodeType =
      elementUtils.getTypeElement(REQUEST_MANAGER_TREE_NODE_QUALIFIED_NAME);

  requestManagerFactoryInterface =
      elementUtils.getTypeElement(REQUEST_MANAGER_FACTORY_QUALIFIED_NAME);

  TypeElement requestManagerType = elementUtils.getTypeElement(REQUEST_MANAGER_QUALIFIED_NAME);
  requestManagerClassName = ClassName.get(requestManagerType);

}
 
Example 22
Project: GitHub   File: RequestManagerGenerator.java   Source Code and License 5 votes vote down vote up
/**
 * The {@link com.bumptech.glide.request.RequestOptions} subclass should always be our
 * generated subclass type to avoid inadvertent errors where a different subclass is applied that
 * accidentally wipes out some logic in overidden methods in our generated subclass.
 */
@Nullable
private MethodSpec generateOverrideSetRequestOptions(
    String generatedCodePackageName, @Nullable TypeSpec generatedRequestOptions) {
  if (generatedRequestOptions == null) {
    return null;
  }

  Elements elementUtils = processingEnv.getElementUtils();
  TypeElement requestOptionsType =
          elementUtils.getTypeElement(
              RequestOptionsGenerator.REQUEST_OPTIONS_QUALIFIED_NAME);
  TypeElement androidNonNullType =
          elementUtils.getTypeElement("android.support.annotation.NonNull");

  // This class may have just been generated and therefore may not be found if we try to obtain
  // it via Elements, so use just the String version instead.
  String generatedRequestOptionsQualifiedName =
      generatedCodePackageName + "." + generatedRequestOptions.name;

  String methodName = "setRequestOptions";
  String parameterName = "toSet";

  return MethodSpec.methodBuilder(methodName)
      .addAnnotation(Override.class)
      .addModifiers(Modifier.PROTECTED)
      .addParameter(
          ParameterSpec.builder(ClassName.get(requestOptionsType), parameterName)
              .addAnnotation(ClassName.get(androidNonNullType))
              .build())
      .beginControlFlow("if ($N instanceof $L)",
          parameterName, generatedRequestOptionsQualifiedName)
      .addStatement("super.$N($N)", methodName, parameterName)
      .nextControlFlow("else")
      .addStatement("super.setRequestOptions(new $L().apply($N))",
          generatedRequestOptionsQualifiedName, parameterName)
      .endControlFlow()
      .build();
}
 
Example 23
Project: GitHub   File: Utils.java   Source Code and License 5 votes vote down vote up
public static String getPackageName(Elements elements, TypeElement typeElement) throws NoPackageNameException {
    PackageElement pkg = elements.getPackageOf(typeElement);
    if (pkg.isUnnamed()) {
        throw new NoPackageNameException(typeElement);
    }
    return pkg.getQualifiedName().toString();
}
 
Example 24
Project: syndesis   File: SyndesisExtensionActionProcessor.java   Source Code and License 5 votes vote down vote up
/**
 * Explicitly add properties that elude reflection implicit strategy
 * @param element
 * @param props
 */
protected boolean augmentProperties(TypeElement element, Properties props) throws InvocationTargetException, IllegalAccessException {
    final Elements elements = processingEnv.getElementUtils();
    final TypeElement extensionTypeElement = elements.getTypeElement(stepClass.getName());

    if (extensionTypeElement != null && processingEnv.getTypeUtils().isAssignable(element.asType(), extensionTypeElement.asType())) {
        props.put("kind", "STEP");
        props.put("entrypoint", element.getQualifiedName().toString());
    } else {
        props.put("kind", "BEAN");
        props.put("entrypoint", element.getQualifiedName().toString());

        for (Element method: element.getEnclosedElements()) {
            if (method.getAnnotation(handlerAnnotationClass) != null) {

                // Process method
                augmentProperties((ExecutableElement)method, props);
                addActionProperties(method, props);

                // Found a method annotated with Handler, let's search for
                // fields annotated with SyndesisActionProperty
                for (Element field: element.getEnclosedElements()) {
                    if (field.getKind() == ElementKind.FIELD) {
                        addActionProperties(field, props);
                    }
                }

                return true;
            }
        }
    }

    return false;
}
 
Example 25
Project: incubator-netbeans   File: JavaCompletionTask.java   Source Code and License 5 votes vote down vote up
private void addLocalFieldsAndVars(final Env env) throws IOException {
    final CompilationController controller = env.getController();
    final Elements elements = controller.getElements();
    final Types types = controller.getTypes();
    final Scope scope = env.getScope();
    Set<? extends TypeMirror> smartTypes = options.contains(Options.ALL_COMPLETION) ? null : getSmartTypes(env);
    final TypeElement enclClass = scope.getEnclosingClass();
    for (Element e : getLocalMembersAndVars(env)) {
        switch (e.getKind()) {
            case ENUM_CONSTANT:
            case EXCEPTION_PARAMETER:
            case LOCAL_VARIABLE:
            case RESOURCE_VARIABLE:
            case PARAMETER:
                results.add(itemFactory.createVariableItem(env.getController(), (VariableElement) e, e.asType(), anchorOffset, null, env.getScope().getEnclosingClass() != e.getEnclosingElement(), elements.isDeprecated(e), isOfSmartType(env, e.asType(), smartTypes), env.assignToVarPos()));
                break;
            case FIELD:
                String name = e.getSimpleName().toString();
                if (THIS_KEYWORD.equals(name) || SUPER_KEYWORD.equals(name)) {
                    results.add(itemFactory.createKeywordItem(name, null, anchorOffset, isOfSmartType(env, e.asType(), smartTypes)));
                } else {
                    TypeMirror tm = asMemberOf(e, enclClass != null ? enclClass.asType() : null, types);
                    results.add(itemFactory.createVariableItem(env.getController(), (VariableElement) e, tm, anchorOffset, null, env.getScope().getEnclosingClass() != e.getEnclosingElement(), elements.isDeprecated(e), isOfSmartType(env, tm, smartTypes), env.assignToVarPos()));
                }
                break;
        }
    }
}
 
Example 26
Project: android-auto-mapper   File: MoreElements.java   Source Code and License 5 votes vote down vote up
/**
 * Returns the set of all non-private methods from {@code type}, including methods that it
 * inherits from its ancestors. Inherited methods that are overridden are not included in the
 * result. So if {@code type} defines {@code public String toString()}, the returned set will
 * contain that method, but not the {@code toString()} method defined by {@code Object}.
 * <p/>
 * <p>The returned set may contain more than one method with the same signature, if
 * {@code type} inherits those methods from different ancestors. For example, if it
 * inherits from unrelated interfaces {@code One} and {@code Two} which each define
 * {@code void foo();}, and if it does not itself override the {@code foo()} method,
 * then both {@code One.foo()} and {@code Two.foo()} will be in the returned set.
 *
 * @param type         the type whose own and inherited methods are to be returned
 * @param elementUtils an {@link Elements} object, typically returned by
 *                     {@link javax.annotation.processing.AbstractProcessor#processingEnv processingEnv}<!--
 *                     -->.{@link javax.annotation.processing.ProcessingEnvironment.getElementUtils()
 *                     getElementUtils()}
 */
public static ImmutableSet<ExecutableElement> getLocalAndInheritedMethods(
        TypeElement type, Elements elementUtils) {

    SetMultimap<String, ExecutableElement> methodMap = LinkedHashMultimap.create();
    getLocalAndInheritedMethods(getPackage(type), type, methodMap);
    // Find methods that are overridden. We do this using `Elements.overrides`, which means
    // that it is inherently a quadratic operation, since we have to compare every method against
    // every other method. We reduce the performance impact by (a) grouping methods by name, since
    // a method cannot override another method with a different name, and (b) making sure that
    // methods in ancestor types precede those in descendant types, which means we only have to
    // check a method against the ones that follow it in that order.
    Set<ExecutableElement> overridden = new LinkedHashSet<ExecutableElement>();
    for (String methodName : methodMap.keySet()) {
        List<ExecutableElement> methodList = ImmutableList.copyOf(methodMap.get(methodName));
        for (int i = 0; i < methodList.size(); i++) {
            ExecutableElement methodI = methodList.get(i);
            for (int j = i + 1; j < methodList.size(); j++) {
                ExecutableElement methodJ = methodList.get(j);
                if (elementUtils.overrides(methodJ, methodI, type)) {
                    overridden.add(methodI);
                }
            }
        }
    }
    Set<ExecutableElement> methods = new LinkedHashSet<ExecutableElement>(methodMap.values());
    methods.removeAll(overridden);
    return ImmutableSet.copyOf(methods);
}
 
Example 27
Project: GitHub   File: OnPreSerializeProcessor.java   Source Code and License 5 votes vote down vote up
@Override
public void findAndParseObjects(RoundEnvironment env, Map<String, JsonObjectHolder> jsonObjectMap, Elements elements, Types types) {
    for (Element element : env.getElementsAnnotatedWith(OnPreJsonSerialize.class)) {
        try {
            processOnPreJsonSerializeMethodAnnotation(element, jsonObjectMap, elements);
        } catch (Exception e) {
            StringWriter stackTrace = new StringWriter();
            e.printStackTrace(new PrintWriter(stackTrace));

            error(element, "Unable to generate injector for %s. Stack trace incoming:\n%s", OnPreJsonSerialize.class, stackTrace.toString());
        }
    }
}
 
Example 28
Project: GitHub   File: OnPreSerializeProcessor.java   Source Code and License 5 votes vote down vote up
private void processOnPreJsonSerializeMethodAnnotation(Element element, Map<String, JsonObjectHolder> jsonObjectMap, Elements elements) throws Exception {
    if (!isCallbackMethodAnnotationValid(element, OnPreJsonSerialize.class.getSimpleName())) {
        return;
    }

    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
    ExecutableElement executableElement = (ExecutableElement)element;
    JsonObjectHolder objectHolder = jsonObjectMap.get(TypeUtils.getInjectedFQCN(enclosingElement, elements));
    objectHolder.preSerializeCallback = executableElement.getSimpleName().toString();
}
 
Example 29
Project: dataenum   File: ValueParser.java   Source Code and License 5 votes vote down vote up
private static boolean isValueSpecMarker(
    TypeMirror returnType, ProcessingEnvironment processingEnvironment) {
  Types types = processingEnvironment.getTypeUtils();
  Elements elements = processingEnvironment.getElementUtils();

  return types.isSameType(
      returnType, elements.getTypeElement(dataenum_case.class.getCanonicalName()).asType());
}
 
Example 30
Project: GitHub   File: JsonObjectProcessor.java   Source Code and License 5 votes vote down vote up
private void addAllNonPrivateFields(Element element, Elements elements, Types types, JsonObjectHolder objectHolder) {
    List<? extends Element> enclosedElements = element.getEnclosedElements();
    for (Element enclosedElement : enclosedElements) {
        ElementKind enclosedElementKind = enclosedElement.getKind();
        if (enclosedElementKind == ElementKind.FIELD) {
            Set<Modifier> modifiers = enclosedElement.getModifiers();
            if (!modifiers.contains(Modifier.PRIVATE) && !modifiers.contains(Modifier.PROTECTED) && !modifiers.contains(Modifier.TRANSIENT) && !modifiers.contains(Modifier.STATIC)) {
                createOrUpdateFieldHolder(enclosedElement, elements, types, objectHolder);
            }
        }
    }
}
 
Example 31
Project: GitHub   File: OnJsonParseCompleteProcessor.java   Source Code and License 5 votes vote down vote up
private void processOnCompleteMethodAnnotation(Element element, Map<String, JsonObjectHolder> jsonObjectMap, Elements elements) throws Exception {
    if (!isCallbackMethodAnnotationValid(element, OnJsonParseComplete.class.getSimpleName())) {
        return;
    }

    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
    ExecutableElement executableElement = (ExecutableElement)element;
    JsonObjectHolder objectHolder = jsonObjectMap.get(TypeUtils.getInjectedFQCN(enclosingElement, elements));
    objectHolder.onCompleteCallback = executableElement.getSimpleName().toString();
}
 
Example 32
Project: RxPay   File: FieldEntity.java   Source Code and License 5 votes vote down vote up
public FieldEntity(Elements elementUtil, VariableElement element) {
    this.element = element;
    this.classSimpleName = element.getEnclosingElement().getSimpleName().toString();
    this.classQualifiedName = ((TypeElement) element.getEnclosingElement()).getQualifiedName().toString();
    this.feildName = element.getSimpleName().toString();
    this.typeMirror = element.asType();
    this.typeName = typeMirror.toString();
}
 
Example 33
Project: vulture   File: TypeUtils.java   Source Code and License 5 votes vote down vote up
public static boolean isParcelableArray(Types typeUtils, Elements elementUtils, Element element) {
    if (element.asType().getKind() != TypeKind.ARRAY) {
        return false;
    }

    ArrayType arrayType = (ArrayType) element.asType();
    TypeMirror componentType = arrayType.getComponentType();

    TypeElement typeParcelable = elementUtils.getTypeElement(Parcelable.class.getName());
    return typeUtils.isSubtype(componentType, typeParcelable.asType());
}
 
Example 34
Project: incubator-netbeans   File: MethodModelSupportTest.java   Source Code and License 5 votes vote down vote up
public void testGetTypeName() throws Exception {
    TestUtilities.copyStringToFileObject(testFO,
            "package foo;" +
            "public class TestClass {" +
            "}");
    runUserActionTask(testFO, new Task<CompilationController>() {
        public void run(CompilationController controller) throws IOException {
            controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
            Elements elements = controller.getElements();
            Types types = controller.getTypes();
            
            String typeName = String.class.getName();
            String resolvedTypeName = MethodModelSupport.getTypeName(elements.getTypeElement(typeName).asType());
            assertEquals(typeName, resolvedTypeName);
            
            typeName = InputStream.class.getName();
            resolvedTypeName = MethodModelSupport.getTypeName(elements.getTypeElement(typeName).asType());
            assertEquals(typeName, resolvedTypeName);
            
            resolvedTypeName = MethodModelSupport.getTypeName(types.getPrimitiveType(TypeKind.INT));
            assertEquals("int", resolvedTypeName);

            typeName = String.class.getName();
            resolvedTypeName = MethodModelSupport.getTypeName(types.getArrayType(elements.getTypeElement(typeName).asType()));
            assertEquals("java.lang.String[]", resolvedTypeName);
            
            PrimitiveType primitiveType = types.getPrimitiveType(TypeKind.BYTE);
            ArrayType arrayType = types.getArrayType(primitiveType);
            resolvedTypeName = MethodModelSupport.getTypeName(arrayType);
            assertEquals("byte[]", resolvedTypeName);
        }
    });
}
 
Example 35
Project: data-mediator   File: FieldData.java   Source Code and License 5 votes vote down vote up
public void replaceIfNeed(Elements elements, ProcessorPrinter pp) {
    //pp.note("TypeCompat", "replaceIfNeed", "start check element: " + tm.toString());
    Element te = getElement();
    //when TypeMirror is primitive , here te is null.
    if(te == null) {
        pp.note("TypeCompat", "replaceIfNeed", "Element = null");
    }else{
        boolean needReplace = false;
        //when depend another interface(@Fields) need replace. Note: @Retention CLASS
        List<? extends AnnotationMirror> mirrors = getElementAsType().getAnnotationMirrors();
        for(AnnotationMirror am : mirrors){
            DeclaredType type = am.getAnnotationType();
           // pp.note("TypeCompat", "replaceIfNeed", "type = " + type);
            if(type.toString().equals(Fields.class.getName())){
                needReplace = true;
                break;
            }
        }
        if(needReplace){
            TypeElement typeElement = getElementAsType();
            String packageName = elements.getPackageOf(typeElement).getQualifiedName().toString();
            mTypeName_impl = ClassName.get(packageName,
                    Util.getTargetClassName(packageName, typeElement.getQualifiedName().toString())
                            +  DataMediatorConstants.IMPL_SUFFIX );
        }
    }
}
 
Example 36
Project: incubator-netbeans   File: JFXProjectUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Returns set of names of classes of the classType type.
 * 
 * @param classpathMap map of classpaths of all project files
 * @param classType return only classes of this type
 * @return set of class names
 */
public static Set<String> getAppClassNames(@NonNull Collection<? extends FileObject> roots, final @NonNull String classType) {
    final Set<String> appClassNames = new HashSet<>();
    for (FileObject fo : roots) {
        final ClasspathInfo cpInfo = ClasspathInfo.create(fo);
        final JavaSource js = JavaSource.create(cpInfo);
        if (js != null) {
            try { 
                js.runUserActionTask(new Task<CompilationController>() {
                    @Override
                    public void run(CompilationController controller) throws Exception {
                        final ClassIndex classIndex = cpInfo.getClassIndex();
                        final Elements elems = controller.getElements();
                        TypeElement fxAppElement = elems.getTypeElement(classType);
                        ElementHandle<TypeElement> appHandle = ElementHandle.create(fxAppElement);
                        Set<ElementHandle<TypeElement>> appHandles = classIndex.getElements(appHandle, kinds, scopes);
                        for (ElementHandle<TypeElement> elemHandle : appHandles) {
                            appClassNames.add(elemHandle.getQualifiedName());
                        }
                    }
                }, true);
            } catch (Exception e) {

            }
        }
    }
    return appClassNames;
}
 
Example 37
Project: react4j   File: ProcessorUtil.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings( "SameParameterValue" )
@Nullable
static DeclaredType getTypeMirrorAnnotationParameter( @Nonnull final Elements elements,
                                                      @Nonnull final Element typeElement,
                                                      @Nonnull final String annotationClassName,
                                                      @Nonnull final String parameterName )
{
  final AnnotationValue annotationValue =
    findAnnotationValue( elements, typeElement, annotationClassName, parameterName );
  return null == annotationValue ? null : (DeclaredType) annotationValue.getValue();
}
 
Example 38
Project: incubator-netbeans   File: CompletionTestBase.java   Source Code and License 5 votes vote down vote up
@Override
public CI createArrayItem(CompilationInfo info, ArrayType type, int substitutionOffset, ReferencesCount referencesCount, Elements elements) {
    int dim = 0;
    TypeMirror tm = type;
    while(tm.getKind() == TypeKind.ARRAY) {
        tm = ((ArrayType)tm).getComponentType();
        dim++;
    }
    if (tm.getKind().isPrimitive()) {
        String kwd = tm.toString();
        StringBuilder sb = new StringBuilder(kwd);
        for(int i = 0; i < dim; i++) {
            sb.append("[]"); //NOI18N
        }
        return new CI(sb.toString(), 670 - SMART_TYPE, kwd);
    }
    if (tm.getKind() == TypeKind.DECLARED || tm.getKind() == TypeKind.ERROR) {
        DeclaredType dt = (DeclaredType)tm;
        TypeElement elem = (TypeElement)dt.asElement();
        String simpleName = elem.getSimpleName().toString();
        String fqn = elem.getQualifiedName().toString();
        int weight = 50;
        if (fqn.startsWith("java.lang") || fqn.startsWith("java.util")) { // NOI18N
            weight -= 10;
        } else if (fqn.startsWith("org.omg") || fqn.startsWith("org.apache")) { // NOI18N
            weight += 10;
        } else if (fqn.startsWith("com.sun") || fqn.startsWith("com.ibm") || fqn.startsWith("com.apple")) { // NOI18N
            weight += 20;
        } else if (fqn.startsWith("sun") || fqn.startsWith("sunw") || fqn.startsWith("netscape")) { // NOI18N
            weight += 30;
        }
        return new CI(simpleName, 800 - SMART_TYPE, referencesCount != null ? simpleName + '#' + weight + '#' + info.getElementUtilities().getElementName(elem.getEnclosingElement(), true) : simpleName);
    }
    throw new IllegalArgumentException("array element kind=" + tm.getKind());
}
 
Example 39
Project: incubator-netbeans   File: ElementOverlay.java   Source Code and License 5 votes vote down vote up
private Element createElement(ASTService ast, Elements elements, String name, Element original, ModuleElement modle) {
    Element el = elementCache.get(name);

    if (el == null) {
        if (original != null) {
            if (original.getKind().isClass() || original.getKind().isInterface()) {
                elementCache.put(name, el = new TypeElementWrapper(ast, elements, (TypeElement) original));
                return el;
            }
            if (original.getKind() == ElementKind.PACKAGE) {
                elementCache.put(name, el = new PackageElementWrapper(ast, elements, (PackageElement) original));
                return el;
            }

            return original;
        }
        
        int lastDot = name.lastIndexOf('.');
        Name simpleName = elements.getName(name.substring(lastDot + 1));
        Name fqnName = elements.getName(name);

        if (classes.containsKey(name)) {
            Element parent = lastDot > 0 ? resolve(ast, elements, name.substring(0, lastDot), modle) : elements.getPackageElement("");

            elementCache.put(name, el = new FakeTypeElement(ast, elements, simpleName, fqnName, name, parent, classes.get(name), modle));
        } else if (packages.contains(name)) {
            elementCache.put(name, el = new FakePackageElement(ast, elements, fqnName, name, simpleName, modle));
        } else {
            return null;//XXX: handling of this null in callers!
        }
    }

    return el;
}
 
Example 40
Project: openjdk-jdk10   File: DependenciesTest.java   Source Code and License 5 votes vote down vote up
public SearchAnnotations(Trees trees, Elements elements) {
    this.trees = trees;
    this.elements = elements;
    this.triggersCompleteAnnotation =
            elements.getTypeElement(TriggersComplete.class.getName());
    this.triggersCompleteRepeatAnnotation =
            elements.getTypeElement(TriggersCompleteRepeat.class.getName());
}
 
Example 41
Project: NullAway   File: NullAwayNativeModels.java   Source Code and License 5 votes vote down vote up
static void elementStuff(Element e, Elements elems) {
  // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required
  e.getAnnotation(null);
  // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required
  elems.getPackageElement(null);
  // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required
  elems.getTypeElement(null);
  // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required
  elems.getDocComment(null);
}
 
Example 42
Project: incubator-netbeans   File: ElementOverlay.java   Source Code and License 5 votes vote down vote up
private ModuleElement moduleOf(Elements elements, Element el) {
    if (el instanceof TypeElementWrapper)
        return moduleOf(elements, ((TypeElementWrapper) el).delegateTo);
    if (el instanceof FakeTypeElement)
        return ((FakeTypeElement) el).modle;
    if (el instanceof PackageElementWrapper)
        return moduleOf(elements, ((PackageElementWrapper) el).delegateTo);
    if (el instanceof FakePackageElement)
        return ((FakePackageElement) el).modle;
    if (el instanceof Symbol)
        return elements.getModuleOf(el);
    return null;
}
 
Example 43
Project: RxPay   File: MethodEntity.java   Source Code and License 5 votes vote down vote up
public MethodEntity(ExecutableElement methodElement, Types typeMirror, Elements elementUtils) {
    this.methodElement = methodElement;
    this.returnType = methodElement.getReturnType().toString();
    this.parameterElements = methodElement.getParameters();
    this.isVarArgs = methodElement.isVarArgs();
    this.methodName = methodElement.getSimpleName().toString();
    this.exceptionTypes = methodElement.getThrownTypes();
    this.typeParameterElements = methodElement.getTypeParameters();
    this.classSimpleName = methodElement.getEnclosingElement().getSimpleName().toString();
    this.classQualifiedName = ((TypeElement) methodElement.getEnclosingElement()).getQualifiedName().toString();
    this.packageName = elementUtils.getPackageOf(methodElement).getQualifiedName().toString();
}
 
Example 44
Project: incubator-netbeans   File: AnnotationParserTest.java   Source Code and License 5 votes vote down vote up
public void testEnumConstant() throws Exception {
    TestUtilities.copyStringToFileObject(srcFO, "Annotated.java",
            "import java.lang.annotation.*;" +
            "@interface Annotation {" +
            "   RetentionPolicy enumValue();" +
            "   RetentionPolicy enumValue2();" +
            "   RetentionPolicy enumValue3();" +
            "}" +
            "@Annotation(enumValue = RetentionPolicy.CLASS, enumValue2 = ElementType.TYPE)" +
            "public class Annotated {" +
            "}");
    IndexingManager.getDefault().refreshIndexAndWait(srcFO.getURL(), null);
    ClasspathInfo cpi = ClasspathInfo.create(srcFO);
    final AnnotationModelHelper helper = AnnotationModelHelper.create(cpi);
    helper.runJavaSourceTask(new Runnable() {
        public void run() {
            Elements elements = helper.getCompilationController().getElements();
            TypeElement annotated = elements.getTypeElement("Annotated");
            AnnotationMirror annotation = annotated.getAnnotationMirrors().iterator().next();
            AnnotationParser parser = AnnotationParser.create(helper);
            TypeMirror rpType = elements.getTypeElement("java.lang.annotation.RetentionPolicy").asType();
            parser.expectEnumConstant("enumValue", rpType, AnnotationParser.defaultValue("SOURCE"));
            parser.expectEnumConstant("enumValue2", rpType, AnnotationParser.defaultValue("CLASS"));
            parser.expectEnumConstant("enumValue3", rpType, AnnotationParser.defaultValue("RUNTIME"));
            ParseResult parseResult = parser.parse(annotation);
            assertEquals("CLASS", parseResult.get("enumValue", String.class));
            assertEquals("CLASS", parseResult.get("enumValue2", String.class));
            assertEquals("RUNTIME", parseResult.get("enumValue3", String.class));
        }
    });
}
 
Example 45
Project: incubator-netbeans   File: CheckSums.java   Source Code and License 5 votes vote down vote up
private static String getExtendedModifiers(Elements elements, Element el) {
    StringBuilder sb = new StringBuilder();
    for (Modifier m : el.getModifiers())
        sb.append(m.name());
    if (elements.isDeprecated(el))
        sb.append(DEPRECATED);
    if (el.getKind() == ElementKind.FIELD) {
        Object v = ((VariableElement) el).getConstantValue();
        if (v != null) {
            sb.append(v.getClass().getName());
            sb.append(String.valueOf(v));
        }
    }
    return sb.toString();
}
 
Example 46
Project: arez   File: ProcessorUtil.java   Source Code and License 5 votes vote down vote up
@Nonnull
static AnnotationValue getAnnotationValue( @Nonnull final Elements elements,
                                           @Nonnull final AnnotationMirror annotation,
                                           @Nonnull final String parameterName )
{
  final AnnotationValue value = findAnnotationValue( elements, annotation, parameterName );
  assert null != value;
  return value;
}
 
Example 47
Project: incubator-netbeans   File: CompilationInfo.java   Source Code and License 5 votes vote down vote up
/**
    * Return the {@link Elements} service of the javac represented by this {@link CompilationInfo}.
    * @return javac Elements service
    */
   public @NonNull Elements getElements() {
       checkConfinement();
       //use a working init order:
       com.sun.tools.javac.main.JavaCompiler.instance(impl.getJavacTask().getContext());
return impl.getJavacTask().getElements();
   }
 
Example 48
Project: incubator-netbeans   File: ModelUtils.java   Source Code and License 5 votes vote down vote up
/**
 * @param context Hints API context
 * @return managed type provider
 */
public static ManagedTypeProvider getOrCreateCachedMTP(HintContext hc, Project project, EntityMappingsMetadata metaData, Elements elements) {
    //return new ManagedTypeProvider(project, metaData, elements);
    
    Object cached = hc.getInfo().getCachedValue(CACHED_MTP);
    if (cached == null) {
        ManagedTypeProvider newContext = new ManagedTypeProvider(project, metaData, elements);
        hc.getInfo().putCachedValue(CACHED_MTP, newContext, CompilationInfo.CacheClearPolicy.ON_CHANGE);
        return newContext;
    } else {
        return (ManagedTypeProvider) cached;
    }
}
 
Example 49
Project: incubator-netbeans   File: JUnit3TestGenerator.java   Source Code and License 5 votes vote down vote up
/**
 */
private TypeElement getTestTypeElem(Elements elements) {
    if (testTypeElem == null) {
        testTypeElem = getElemForClassName(
                                    "junit.framework.Test",     //NOI18N
                                    elements);
    }
    return testTypeElem;
}
 
Example 50
Project: incubator-netbeans   File: LazyJavaCompletionItem.java   Source Code and License 5 votes vote down vote up
@Override
protected JavaCompletionItem getDelegate(CompilationInfo info, Scope scope, TypeElement te) {
    Elements elements = info.getElements();
    Trees trees = info.getTrees();
    if (te != null) {
        Element element = null;
        boolean multiVersion = false;
        for (Element e : te.getEnclosedElements()) {
            if ((e.getKind().isField() || e.getKind() == ElementKind.METHOD)
                    && name.contentEquals(Utilities.isCaseSensitive() ? e.getSimpleName() : e.getSimpleName().toString().toLowerCase())
                    && e.getModifiers().contains(Modifier.STATIC)
                    && (Utilities.isShowDeprecatedMembers() || !elements.isDeprecated(e))
                    && trees.isAccessible(scope, e, (DeclaredType) te.asType())) {
                if (element != null) {
                    multiVersion = true;
                    break;
                }
                element = e;
            }
        }
        if (element != null) {
            name = element.getSimpleName().toString();
            return createStaticMemberItem(info, (DeclaredType) te.asType(), element, element.asType(), multiVersion, substitutionOffset, elements.isDeprecated(element), addSemicolon, getWhiteList());
        }
    }
    return null;
}
 
Example 51
Project: vulture   File: TypeUtils.java   Source Code and License 5 votes vote down vote up
public static boolean isParcelableArrayList(Types typeUtils, Elements elementUtils, Element element) {
    TypeElement typeArrayList = elementUtils.getTypeElement(ArrayList.class.getName());
    TypeElement typeParcelable = elementUtils.getTypeElement(Parcelable.class.getName());
    WildcardType wildcardType = typeUtils.getWildcardType(typeParcelable.asType(), null);
    DeclaredType declaredType = typeUtils.getDeclaredType(typeArrayList, wildcardType);

    return typeUtils.isSubtype(element.asType(), declaredType);
}
 
Example 52
Project: incubator-netbeans   File: UseSuperTypeRefactoringPlugin.java   Source Code and License 5 votes vote down vote up
private boolean hidesSupTypeMember(Element methElement, TypeElement superTypeElement) {
    Elements elements = workingCopy.getElements();
    List<? extends Element> containedElements = elements.getAllMembers(superTypeElement);
    for (Element elem : containedElements) {
        boolean isPresentInSuperType = methElement.equals(elem) || 
                elements.hides(methElement, elem);
        if ((elem != null) && isStatic(elem) && isPresentInSuperType) {
            return true;
        }
    }
    return false;
}
 
Example 53
Project: incubator-netbeans   File: VarUsageVisitor.java   Source Code and License 5 votes vote down vote up
private boolean isHidingMember(TypeElement subTypeElement, Element variableElement, 
        TypeElement superTypeElement) {
    //TODO: We do not handle nested types yet (includes enums)
    Elements elements = workingCopy.getElements();
    List<? extends Element> memberElements = elements.getAllMembers(superTypeElement);
    for (Element elem : memberElements) {
        if(variableElement.equals(elem) || elements.hides(variableElement, elem)){
            return true;
        }
    }
    return false;
}
 
Example 54
Project: r-parser   File: RParser.java   Source Code and License 5 votes vote down vote up
private RParser(Trees trees, Types typesUtils, Elements elementUtils, Collection<Class<? extends Annotation>> supportedAnnotations, Collection<String> supportedTypes) {
    this.trees = trees;
    this.typeUtils = typesUtils;
    this.elementUtils = elementUtils;
    this.supportedAnnotations = supportedAnnotations;
    this.supportedTypes = supportedTypes;
    this.symbols = new LinkedHashMap<>();
}
 
Example 55
Project: incubator-netbeans   File: JavaCompletionTask.java   Source Code and License 5 votes vote down vote up
private void insideUnionType(Env env) throws IOException {
    TreePath path = env.getPath();
    UnionTypeTree dtt = (UnionTypeTree) path.getLeaf();
    CompilationController controller = env.getController();
    TokenSequence<JavaTokenId> last = findLastNonWhitespaceToken(env, dtt, env.getOffset());
    if (last != null && last.token().id() == JavaTokenId.BAR) {
        if (!options.contains(Options.ALL_COMPLETION)) {
            TreeUtilities tu = controller.getTreeUtilities();
            TreePath tryPath = tu.getPathElementOfKind(Tree.Kind.TRY, path);
            Set<TypeMirror> exs = tu.getUncaughtExceptions(tryPath);
            if (!exs.isEmpty()) {
                Trees trees = controller.getTrees();
                Types types = controller.getTypes();
                for (Tree t : dtt.getTypeAlternatives()) {
                    TypeMirror tm = trees.getTypeMirror(new TreePath(path, t));
                    if (tm != null && tm.getKind() != TypeKind.ERROR) {
                        for (Iterator<TypeMirror> it = exs.iterator(); it.hasNext();) {
                            if (types.isSubtype(tm, it.next())) {
                                it.remove();
                            }
                        }
                    }
                }
                Elements elements = controller.getElements();
                for (TypeMirror ex : exs) {
                    if (ex.getKind() == TypeKind.DECLARED && startsWith(env, ((DeclaredType) ex).asElement().getSimpleName().toString())
                            && (Utilities.isShowDeprecatedMembers() || !elements.isDeprecated(((DeclaredType) ex).asElement()))
                            && !Utilities.isExcluded(((TypeElement)((DeclaredType) ex).asElement()).getQualifiedName())) {
                        env.addToExcludes(((DeclaredType) ex).asElement());
                        results.add(itemFactory.createTypeItem(env.getController(), (TypeElement) ((DeclaredType) ex).asElement(), (DeclaredType) ex, anchorOffset, env.getReferencesCount(), elements.isDeprecated(((DeclaredType) ex).asElement()), false, false, false, true, false));
                    }
                }
            }
        }
        TypeElement te = controller.getElements().getTypeElement("java.lang.Throwable"); //NOI18N
        if (te != null) {
            addTypes(env, EnumSet.of(CLASS, INTERFACE, TYPE_PARAMETER), controller.getTypes().getDeclaredType(te));
        }
    }
}
 
Example 56
Project: datapipelines-java   File: GetProcessor.java   Source Code and License 4 votes vote down vote up
@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment environment) {
    for(final Element element : environment.getElementsAnnotatedWith(Get.class)) {
        final Get annotation = element.getAnnotation(Get.class);

        if(ElementKind.METHOD != element.getKind()) {
            throw new DataSourceDefinitionException(
                "Must use @Get with methods only! Tried to use with " + element.getSimpleName()
                    + ", which is not a method.");
        }

        final Set<Modifier> modifiers = element.getModifiers();
        if(!modifiers.contains(Modifier.PUBLIC)) {
            throw new DataSourceDefinitionException(
                "Must use @Get with public methods only! Tried to use with " + element.getSimpleName()
                    + ", which is not public.");
        }
        if(modifiers.contains(Modifier.STATIC)) {
            throw new DataSourceDefinitionException(
                "Must use @Get with non-static methods only! Tried to use with " + element.getSimpleName()
                    + ", which is static.");
        }

        final ExecutableType method = (ExecutableType)element.asType();
        final Types types = processingEnv.getTypeUtils();
        final Elements elements = processingEnv.getElementUtils();

        // annotation.value() will throw the exception because it doesn't have compiled class information yet, and is of type Class<?>.
        TypeMirror annotatedType = null;
        try {
            annotation.value();
        } catch(final MirroredTypeException e) {
            annotatedType = e.getTypeMirror();
        }

        if(!types.isAssignable(method.getReturnType(), annotatedType)) {
            throw new DataSourceDefinitionException("@Get method return type must be assignable from the annotation value! Tried to use with "
                + element.getSimpleName() + ", which returns " + method.getReturnType() + ".");
        }
        if(method.getParameterTypes().size() != 2) {
            throw new DataSourceDefinitionException(
                "@Get methods must take 2 arguments: Map<String, Object> query, PipelineContext context. Tried to use with "
                    + element.getSimpleName()
                    + ", which has a different signature.");
        }

        final TypeMirror stringType = elements.getTypeElement(String.class.getName()).asType();
        final TypeMirror objectType = elements.getTypeElement(Object.class.getName()).asType();
        final TypeElement mapType = elements.getTypeElement(Map.class.getName());
        final TypeMirror[] genericTypes = new TypeMirror[] {stringType, objectType};
        final DeclaredType queryType = types.getDeclaredType(mapType, genericTypes);
        final TypeMirror contextType = elements.getTypeElement(PipelineContext.class.getName()).asType();

        if(!types.isAssignable(method.getParameterTypes().get(0), queryType)) {
            throw new DataSourceDefinitionException("@Get method first argument must be assignable from " + queryType + ". Tried to use with "
                + element.getSimpleName() + ", which takes " + method.getParameterTypes().get(0) + ".");
        }
        if(!types.isAssignable(method.getParameterTypes().get(1), contextType)) {
            throw new DataSourceDefinitionException("@Get method second argument must be assignable from " + contextType + ". Tried to use with "
                + element.getSimpleName() + ", which takes " + method.getParameterTypes().get(1) + ".");
        }
    }

    return true;
}
 
Example 57
Project: PreferenceRoom   File: PreferenceComponentAnnotatedClass.java   Source Code and License 4 votes vote down vote up
public PreferenceComponentAnnotatedClass(@NonNull TypeElement annotatedElement, @NonNull Elements elementUtils, @NonNull Map<String, String> annotatedEntityTypeMap) throws VerifyException {
    PackageElement packageElement = elementUtils.getPackageOf(annotatedElement);
    this.packageName = packageElement.isUnnamed() ? null : packageElement.getQualifiedName().toString();
    this.annotatedElement = annotatedElement;
    this.typeName = TypeName.get(annotatedElement.asType());
    this.clazzName = annotatedElement.getSimpleName().toString();
    this.entities = new ArrayList<>();
    this.keyNames = new ArrayList<>();
    this.generatedClazzList = new ArrayList<>();

    annotatedElement.getEnclosedElements().stream()
            .filter(element -> element instanceof ExecutableElement)
            .map(element -> (ExecutableElement) element)
            .forEach(method -> {
                MethodSpec methodSpec = MethodSpec.overriding(method).build();
                if(methodSpec.returnType != TypeName.get(Void.TYPE)) {
                    throw new VerifyException(String.format("return type should be void : '%s' method with return type '%s'", methodSpec.name, methodSpec.returnType));
                } else if(methodSpec.parameters.size() > 1) {
                    throw new VerifyException(String.format("length of parameter should be 1 : '%s' method with parameters '%s'", methodSpec.name, methodSpec.parameters.toString()));
                }
            });

    Set<String> entitySet = new HashSet<>();
    annotatedElement.getAnnotationMirrors().stream()
            .filter(annotationMirror -> TypeName.get(annotationMirror.getAnnotationType()).equals(TypeName.get(PreferenceComponent.class)))
            .forEach(annotationMirror -> {
                annotationMirror.getElementValues().forEach((type, value) -> {
                    String[] values = value.getValue().toString().split(",");
                    List<String> valueList = Arrays.asList(values);
                    entitySet.addAll(valueList);
        });
    });

    entitySet.forEach(value -> {
        if(!annotatedEntityTypeMap.containsKey(value))
            throw new VerifyException(String.format("%s is not a preference entity.", value));
        else {
            keyNames.add(annotatedEntityTypeMap.get(value));
            generatedClazzList.add(ENTITY_PREFIX + annotatedEntityTypeMap.get(value));
        }
    });

    entities.addAll(entitySet);
}
 
Example 58
Project: Moco   File: SourceGenerator.java   Source Code and License 4 votes vote down vote up
public Elements elementUtil() {
    return processingEnvironment.getElementUtils();
}
 
Example 59
Project: LifecycleAware   File: ModifierRule.java   Source Code and License 4 votes vote down vote up
public ModifierRule(Elements elementUtils, Types typeUtils) {
    super(elementUtils, typeUtils);
}
 
Example 60
Project: GitHub   File: GeneratedTypes.java   Source Code and License 4 votes vote down vote up
public static final String getQualifiedName(Elements elements, TypeElement type) {
  return elements.getPackageOf(type).getQualifiedName() + "." + getSimpleName(type);
}