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

The following examples show how to use javax.lang.model.element.ElementKind#INTERFACE . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
@TriggerTreeKind(Tree.Kind.INTERFACE)
public static Collection<ErrorDescription> run(HintContext hintContext) {
    final EJBProblemContext ctx = HintsUtils.getOrCacheContext(hintContext);
    if (ctx == null || ctx.getClazz().getKind() != ElementKind.INTERFACE) {
        return Collections.emptyList();
    }

    AnnotationMirror annRemote = JavaUtils.findAnnotation(ctx.getClazz(), EJBAPIAnnotations.REMOTE);
    if (annRemote != null && JavaUtils.getAnnotationAttrValue(annRemote, EJBAPIAnnotations.VALUE) != null) {
        ErrorDescription err = HintsUtils.createProblem(
                ctx.getClazz(),
                hintContext.getInfo(),
                Bundle.ValueNotSpecifiedForRemoteAnnotationInterface_err());

        return Collections.singletonList(err);
    }
    return Collections.emptyList();
}
 
Example 2
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(Bridge.class)) {
        // Make sure element is an interface declaration
        if (annotatedElement.getKind() != ElementKind.INTERFACE) {
            error(annotatedElement, "Only interfaces can be annotated with @%s", Bridge.class.getSimpleName());
            return true;
        }

        try {
            new BridgeInterface(annotatedElement, elementUtils, typeUtils).writeToFiler(filer);
        } catch (Exception e) {
            error(annotatedElement, "%s", e.getMessage());
        }
    }
    return true;
}
 
Example 3
Source Project: dataenum   File: SpecParser.java    License: Apache License 2.0 6 votes vote down vote up
public static Spec parse(Element element, ProcessingEnvironment processingEnv) {
  Messager messager = processingEnv.getMessager();

  if (element.getKind() != ElementKind.INTERFACE) {
    messager.printMessage(
        Diagnostic.Kind.ERROR, "@DataEnum can only be used on interfaces.", element);
    return null;
  }

  TypeElement dataEnum = (TypeElement) element;

  List<TypeVariableName> typeVariableNames = new ArrayList<>();
  for (TypeParameterElement typeParameterElement : dataEnum.getTypeParameters()) {
    typeVariableNames.add(TypeVariableName.get(typeParameterElement));
  }

  List<Value> values = ValuesParser.parse(dataEnum, processingEnv);
  if (values == null) {
    return null;
  }

  ClassName enumInterface = ClassName.get(dataEnum);
  return new Spec(enumInterface, typeVariableNames, values);
}
 
Example 4
void visitCommandSpec(CommandSpec spec) {
    Object userObject = spec.userObject();
    if (Proxy.isProxyClass(userObject.getClass())) {
        Class<?>[] interfaces = userObject.getClass().getInterfaces();
        String names = "";
        for (Class<?> interf : interfaces) {
            if (names.length() > 0) { names += ","; }
            names += interf.getCanonicalName(); // TODO or Class.getName()?
        }
        if (names.length() > 0) {
            commandInterfaces.add(names);
        }
    } else if (spec.userObject() instanceof Element && ((Element) spec.userObject()).getKind() == ElementKind.INTERFACE) {
        commandInterfaces.add(((Element) spec.userObject()).asType().toString());
    }
    for (CommandSpec mixin : spec.mixins().values()) {
        visitCommandSpec(mixin);
    }
    for (CommandLine sub : spec.subcommands().values()) {
        visitCommandSpec(sub.getCommandSpec());
    }
}
 
Example 5
Source Project: netbeans   File: PatternAnalyser.java    License: Apache License 2.0 6 votes vote down vote up
private void resolveTypes(Parameters p) {
    
    List<TypeElement> types = ElementFilter.typesIn(p.element.getEnclosedElements());
    
    for (TypeElement typeElement : types) {
        if ( typeElement.getKind() == ElementKind.CLASS ||
             typeElement.getKind() == ElementKind.INTERFACE ) {
            PatternAnalyser pa = new PatternAnalyser( p.ci.getFileObject(), ui );
            pa.analyzeAll(p.ci, typeElement);
            ClassPattern cp = new ClassPattern(pa, typeElement.asType(), 
                                               BeanUtils.nameAsString(typeElement));
            currentClassesPatterns.add(cp);
        }
    }

    
}
 
Example 6
@Override
public ElementKind getKind() {
	if (null != _kindHint) {
		return _kindHint;
	}
	ReferenceBinding refBinding = (ReferenceBinding)_binding;
	// The order of these comparisons is important: e.g., enum is subset of class
	if (refBinding.isEnum()) {
		return ElementKind.ENUM;
	}
	else if (refBinding.isAnnotationType()) {
		return ElementKind.ANNOTATION_TYPE;
	}
	else if (refBinding.isInterface()) {
		return ElementKind.INTERFACE;
	}
	else if (refBinding.isClass()) {
		return ElementKind.CLASS;
	}
	else {
		throw new IllegalArgumentException("TypeElement " + new String(refBinding.shortReadableName()) +  //$NON-NLS-1$
				" has unexpected attributes " + refBinding.modifiers); //$NON-NLS-1$
	}
}
 
Example 7
Source Project: j2cl   File: JavaEnvironment.java    License: Apache License 2.0 6 votes vote down vote up
private List<String> getClassComponents(javax.lang.model.type.TypeVariable typeVariable) {
  Element enclosingElement = typeVariable.asElement().getEnclosingElement();
  if (enclosingElement.getKind() == ElementKind.CLASS
      || enclosingElement.getKind() == ElementKind.INTERFACE
      || enclosingElement.getKind() == ElementKind.ENUM) {
    return ImmutableList.<String>builder()
        .addAll(getClassComponents(enclosingElement))
        .add(
            // If it is a class-level type variable, use the simple name (with prefix "C_") as the
            // current name component.
            "C_" + typeVariable)
        .build();
  } else {
    return ImmutableList.<String>builder()
        .addAll(getClassComponents(enclosingElement.getEnclosingElement()))
        .add(
            "M_"
                + enclosingElement.getSimpleName()
                + "_"
                + typeVariable.asElement().getSimpleName())
        .build();
  }
}
 
Example 8
@Override public ErrorDescription[] apply(TypeElement subject, ProblemContext ctx){
    if(subject.getKind() == ElementKind.INTERFACE) {
        AnnotationMirror annEntity = Utilities.findAnnotation(subject,ANNOTATION_WEBSERVICE);
        AnnotationTree annotationTree = (AnnotationTree) ctx.getCompilationInfo().
                getTrees().getTree(subject, annEntity);
        //endpointInterface not allowed
        if(Utilities.getAnnotationAttrValue(annEntity, ANNOTATION_ATTRIBUTE_SEI)!=null) {
            String label = NbBundle.getMessage(InterfaceEndpointInterface.class, "MSG_IF_SEINotAllowed");
            Fix fix = new RemoveAnnotationArgument(ctx.getFileObject(),
                    subject, annEntity, ANNOTATION_ATTRIBUTE_SEI);
            Tree problemTree = Utilities.getAnnotationArgumentTree(annotationTree, ANNOTATION_ATTRIBUTE_SEI);
            ctx.setElementToAnnotate(problemTree);
            ErrorDescription problem = createProblem(subject, ctx, label, fix);
            ctx.setElementToAnnotate(null);
            return new ErrorDescription[]{problem};
        }
    }        
    return null;
}
 
Example 9
Source Project: netbeans   File: Utils.java    License: Apache License 2.0 5 votes vote down vote up
static boolean isProvider(TypeElement type, AnnotationModelHelper helper) {
    if (type.getKind() != ElementKind.INTERFACE) { // don't consider interfaces
        if (helper.hasAnnotation(type.getAnnotationMirrors(),
                RestConstants.PROVIDER_ANNOTATION)) { // NOI18N
            return true;
        }
    }
    return false;
}
 
Example 10
public boolean isInjectionTarget(CompilationController controller, TypeElement typeElement) {
    if (controller == null || typeElement==null) {
        throw new NullPointerException("Passed null to WSInjectionTargetQueryImplementation.isInjectionTarget(CompilationController, TypeElement)"); // NOI18N
    }
    FileObject fo = controller.getFileObject();
    Project project = FileOwnerQuery.getOwner(fo);
    
    if (ProjectUtil.isJavaEE5orHigher(project) && !isTomcatTargetServer(project) && !(ElementKind.INTERFACE==typeElement.getKind())) {
        
        List<? extends AnnotationMirror> annotations = typeElement.getAnnotationMirrors();
        boolean found = false;

        for (AnnotationMirror m : annotations) {
            Name qualifiedName = ((TypeElement)m.getAnnotationType().asElement()).getQualifiedName();
            if (qualifiedName.contentEquals("javax.jws.WebService")) { //NOI18N
                found = true;
                break;
            }
            if (qualifiedName.contentEquals("javax.jws.WebServiceProvider")) { //NOI18N
                found = true;
                break;
            }
        }
        if (found) return true;
    }
    return false;
}
 
Example 11
Source Project: netbeans   File: JavaUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static String extractClassNameFromType(TypeMirror type){
    if (type instanceof DeclaredType){
        Element elem = ((DeclaredType)type).asElement();
        
        if (elem.getKind() == ElementKind.CLASS
                || elem.getKind() == ElementKind.INTERFACE){
            return ((TypeElement)elem).getQualifiedName().toString();
        }
    }
    
    return null;
}
 
Example 12
Source Project: netbeans   File: Utils.java    License: Apache License 2.0 5 votes vote down vote up
static boolean isRestApplication(TypeElement type, AnnotationModelHelper helper) {
    boolean isRest = false;
    if (type != null && type.getKind() != ElementKind.INTERFACE) { // don't consider interfaces
        if (helper.hasAnnotation(type.getAnnotationMirrors(), RestConstants.APPLICATION_PATH)) { // NOI18N
            isRest = true;
        }
    }
    return isRest;
}
 
Example 13
Source Project: netbeans   File: CreateElement.java    License: Apache License 2.0 5 votes vote down vote up
private static ElementKind getClassType(Set<ElementKind> types) {
    if (types.contains(ElementKind.CLASS))
        return ElementKind.CLASS;
    if (types.contains(ElementKind.ANNOTATION_TYPE))
        return ElementKind.ANNOTATION_TYPE;
    if (types.contains(ElementKind.INTERFACE))
        return ElementKind.INTERFACE;
    if (types.contains(ElementKind.ENUM))
        return ElementKind.ENUM;

    return null;
}
 
Example 14
Source Project: netbeans   File: CallEjbCodeGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean isEnable(FileObject srcFile, TypeElement typeElement) {
    Project project = FileOwnerQuery.getOwner(srcFile);
    if (project == null) {
        return false;
    }
    J2eeModuleProvider j2eeModuleProvider = project.getLookup ().lookup (J2eeModuleProvider.class);
    if (j2eeModuleProvider != null) {
        if (project.getLookup().lookup(EnterpriseReferenceContainer.class) == null) {
            return false;
        }
        String serverInstanceId = j2eeModuleProvider.getServerInstanceID();
        if (serverInstanceId == null) {
            return true;
        }
        J2eePlatform platform = null;
        try {
            platform = Deployment.getDefault().getServerInstance(serverInstanceId).getJ2eePlatform();
        } catch (InstanceRemovedException ex) {
            Logger.getLogger(CallEjbCodeGenerator.class.getName()).log(Level.FINE, null, ex);
        }
        if (platform == null) {
            return true;
        }
        if (!EjbSupport.getInstance(platform).isEjb31LiteSupported(platform)
                && !platform.getSupportedTypes().contains(J2eeModule.Type.EJB)) {
            return false;
        }
    } else {
        return false;
    }

    return ElementKind.INTERFACE != typeElement.getKind();
}
 
Example 15
private List<AddressElement> generateAddressElements(RoundEnvironment roundEnv) {
    List<Element> annotationElements = new ArrayList<>();
    for (String annotationType : getSupportedAnnotationTypes()) {
        TypeElement typeElement = processingEnv.getElementUtils().getTypeElement(annotationType);
        Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(typeElement);
        for (Element annotatedElement : annotatedElements) {
            if (!annotationElements.contains(annotatedElement)) {
                annotationElements.add(annotatedElement);
            }
        }
    }

    List<AddressElement> serviceElements = new ArrayList<>();
    for (Element element : annotationElements) {
        ElementKind kind = element.getKind();
        if (kind != ElementKind.METHOD) {
            logger.error("Only classes and methods can be  with " + getSupportedAnnotationTypes(), element);
        }
        if (!isSupportReturnType((ExecutableElement) element)) {
            logger.error("method only support return type is " + SUPPORT_RETURN_TYPE.toString(), element);
        }

        Element enclosingElement = element.getEnclosingElement();
        String name = enclosingElement.getSimpleName().toString();
        if (!name.endsWith("Service")) {
            logger.error(name + "this class must be in end with Service", enclosingElement);
        }

        if (enclosingElement.getKind() != ElementKind.INTERFACE) {

            logger.error(name + "this class must be interface", enclosingElement);
        }
        serviceElements.add(new AddressElement(element));
    }
    return serviceElements;
}
 
Example 16
Source Project: RHub   File: ShieldProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private void checkIfOK1(Element annotatedElement) {
    if (annotatedElement.getKind() != ElementKind.METHOD) {
        throw new IllegalStateException(
                String.format("Only methods can be annotated with @%s",
                        ProxyTag.class.getSimpleName()));
    }
    if (annotatedElement.getEnclosingElement().getKind() != ElementKind.INTERFACE) {
        throw new IllegalStateException(
                String.format("Only Interfaces can contain annotation @%s",
                        ProxyTag.class.getSimpleName()));
    }
}
 
Example 17
Source Project: netbeans   File: CompilationUnit.java    License: Apache License 2.0 5 votes vote down vote up
private ClassNode createClassNode(String name, TypeElement typeElement) {
    ElementKind kind = typeElement.getKind();
    if (kind == ElementKind.ANNOTATION_TYPE) {
        return createAnnotationType(name, typeElement);
    } else if (kind == ElementKind.INTERFACE) {
        return createInterfaceKind(name, typeElement);
    } else {
        return createClassType(name, typeElement);
    }
}
 
Example 18
Source Project: FreeBuilder   File: MethodFinder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns all methods, declared and inherited, on {@code type}, except those specified by
 * {@link Object}.
 *
 * <p>If method B overrides method A, only method B will be included in the return set.
 * Additionally, if methods A and B have the same signature, but are on unrelated interfaces,
 * one will be arbitrarily picked to be returned.
 */
public static <E extends Exception> ImmutableSet<ExecutableElement> methodsOn(
    TypeElement type,
    Elements elements,
    ErrorTypeHandling<E> errorTypeHandling) throws E {
  TypeElement objectType = elements.getTypeElement(Object.class.getCanonicalName());
  Map<Signature, ExecutableElement> objectMethods = Maps.uniqueIndex(
      methodsIn(objectType.getEnclosedElements()), Signature::new);
  SetMultimap<Signature, ExecutableElement> methods = LinkedHashMultimap.create();
  for (TypeElement supertype : getSupertypes(type, errorTypeHandling)) {
    for (ExecutableElement method : methodsIn(supertype.getEnclosedElements())) {
      Signature signature = new Signature(method);
      if (method.getEnclosingElement().equals(objectType)) {
        continue;  // Skip methods specified by Object.
      }
      if (objectMethods.containsKey(signature)
          && method.getEnclosingElement().getKind() == ElementKind.INTERFACE
          && method.getModifiers().contains(Modifier.ABSTRACT)
          && elements.overrides(method, objectMethods.get(signature), type)) {
        continue;  // Skip abstract methods on interfaces redelaring Object methods.
      }
      Iterator<ExecutableElement> iterator = methods.get(signature).iterator();
      while (iterator.hasNext()) {
        ExecutableElement otherMethod = iterator.next();
        if (elements.overrides(method, otherMethod, type)
            || method.getParameters().equals(otherMethod.getParameters())) {
          iterator.remove();
        }
      }
      methods.put(signature, method);
    }
  }
  return ImmutableSet.copyOf(methods.values());
}
 
Example 19
Source Project: netbeans   File: ImportHelper.java    License: Apache License 2.0 5 votes vote down vote up
private static Set<ImportCandidate> findJavaImportCandidates(FileObject fo, String packageName, String missingClass) {
    final Set<ImportCandidate> candidates = new HashSet<>();
    final ClasspathInfo pathInfo = createClasspathInfo(fo);

    Set<ElementHandle<TypeElement>> typeNames = pathInfo.getClassIndex().getDeclaredTypes(
            missingClass, NameKind.SIMPLE_NAME, EnumSet.allOf(ClassIndex.SearchScope.class));

    for (ElementHandle<TypeElement> typeName : typeNames) {
        ElementKind kind = typeName.getKind();

        // Skip classes within the same package
        String pkgName = GroovyUtils.stripClassName(typeName.getQualifiedName());
        if (packageName == null && pkgName == null) {
            // Probably both in default package
            continue;
        }

        if (packageName != null && packageName.equals(pkgName)) {
            continue;
        }

        if (kind == ElementKind.CLASS || kind == ElementKind.INTERFACE || kind == ElementKind.ANNOTATION_TYPE) {
            candidates.add(createImportCandidate(missingClass, typeName.getQualifiedName(), kind));
        }
    }
    return candidates;
}
 
Example 20
/**
 * Create DAO definition.
 *
 * @param schema
 *            the schema
 * @param globalBeanElements
 *            the global bean elements
 * @param globalDaoElements
 *            the global dao elements
 * @param daoItem
 *            the dao item
 */
protected void createSQLDaoDefinition(SQLiteDatabaseSchema schema,
		final Map<String, TypeElement> globalBeanElements, final Map<String, TypeElement> globalDaoElements,
		String daoItem) {
	Element daoElement = globalDaoElements.get(daoItem);

	if (daoElement.getKind() != ElementKind.INTERFACE) {
		String msg = String.format("Class %s: only interfaces can be annotated with @%s annotation",
				daoElement.getSimpleName().toString(), BindDao.class.getSimpleName());
		throw (new InvalidKindForAnnotationException(msg));
	}

	M2MEntity entity = M2MEntity.extractEntityManagedByDAO((TypeElement) daoElement);

	// add to current schema generated entities too
	for (GeneratedTypeElement genItem : this.generatedEntities) {
		if (genItem.getQualifiedName().equals(entity.getQualifiedName())) {
			schema.generatedEntities.add(genItem);
		}
	}

	boolean generated = daoElement.getAnnotation(BindGeneratedDao.class) != null;

	final SQLiteDaoDefinition currentDaoDefinition = new SQLiteDaoDefinition(schema, daoItem,
			(TypeElement) daoElement, entity.getClassName().toString(), generated);

	// content provider management
	BindContentProviderPath daoContentProviderPath = daoElement.getAnnotation(BindContentProviderPath.class);
	if (daoContentProviderPath != null) {
		currentDaoDefinition.contentProviderEnabled = true;
		currentDaoDefinition.contentProviderPath = daoContentProviderPath.path();
		currentDaoDefinition.contentProviderTypeName = daoContentProviderPath.typeName();

		if (StringUtils.isEmpty(currentDaoDefinition.contentProviderTypeName)) {
			Converter<String, String> convert = CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.LOWER_UNDERSCORE);
			AssertKripton.assertTrue(currentDaoDefinition.getParent().contentProvider != null,
					"DAO '%s' has an inconsistent content provider definition, perhaps you forget to use @%s in data source interface?",
					currentDaoDefinition.getElement().getQualifiedName(),
					BindContentProvider.class.getSimpleName());
			currentDaoDefinition.contentProviderTypeName = currentDaoDefinition
					.getParent().contentProvider.authority + "."
					+ convert.convert(currentDaoDefinition.getSimpleEntityClassName());
		}
	}

	// dao is associated to an entity is not contained in analyzed class
	// set.
	if (!globalBeanElements.containsKey(currentDaoDefinition.getEntityClassName())
			&& !isGeneratedEntity(currentDaoDefinition.getEntityClassName())) {
		throw (new InvalidBeanTypeException(currentDaoDefinition));
	}

	schema.add(currentDaoDefinition);

	fillMethods(currentDaoDefinition, daoElement);

	// get @annotation associated to many 2 many relationship
	BindDaoMany2Many daoMany2Many = daoElement.getAnnotation(BindDaoMany2Many.class);

	// dao definition must have >0 method associated to query
	if (currentDaoDefinition.getCollection().size() == 0 && daoMany2Many == null) {
		throw (new DaoDefinitionWithoutAnnotatedMethodException(currentDaoDefinition));
	}
}