public SqlCreateStatement( Map<String, Element> elementMap, Element parent, SqlUpgradeScripts upgradeScripts) { this.tableName = parent.getSimpleName().toString(); columnDefinitions = new ArrayList<>(); columnDefinitions.add(ColumnDefinition.createPrimaryIdDefinition()); for (String key : elementMap.keySet()) { Element element = elementMap.get(key); ColumnDefinition columnDefinition = new ColumnDefinition(element); Column column = element.getAnnotation(Column.class); ForeignObject foreignObject = element.getAnnotation(ForeignObject.class); if (column != null && upgradeScripts != null) { int version = column.version(); if (version > 1) { upgradeScripts.addAlterAddColumn(columnDefinition, tableName, version); } } else if (foreignObject != null && upgradeScripts != null) { int version = foreignObject.version(); if (version > 1) { upgradeScripts.addAlterAddColumn(columnDefinition, tableName, version); } } columnDefinitions.add(columnDefinition); } }
private void parseOnChanged( Element element, Map<TypeElement, BindingClass> targetClassMap, Set<String> erasedTargetNames, Class annotationClass) { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement, false, false); TypeMirror mirror = element.asType(); if (!(mirror.getKind() == TypeKind.EXECUTABLE)) return; String method = element.toString().trim(); String methodName = method.substring(0, method.indexOf("(")); Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(method); if (m.find()) { String[] methodTypes = m.group(1).split(","); String key = null; if (annotationClass.equals(OnKStringChanged.class)) { KStringBinding binding = new KStringBinding(methodName, methodTypes); key = element.getAnnotation(OnKStringChanged.class).value(); bindingClass.putGeneric(key, binding); } else if (annotationClass.equals(OnKBooleanChanged.class)) { KBooleanBinding binding = new KBooleanBinding(methodName, methodTypes); key = element.getAnnotation(OnKBooleanChanged.class).value(); bindingClass.putGeneric(key, binding); } else { error(element, "unknow annotation class type @%s", annotationClass.getSimpleName()); } } erasedTargetNames.add(enclosingElement.toString()); }
private void parseConstructorParameterAnnotations(PropertyBuilder property, Element element) { if (element.getAnnotation(Nullable.class) != null) { property.setNullable(true); } if (element.getAnnotation(Volatile.class) != null) { property.setVolatile(true); } }
private void parseBind( Element element, Map<TypeElement, BindingClass> targetClassMap, Set<String> erasedTargetNames) { String data = element.getAnnotation(Bind.class).data(); int id = element.getAnnotation(Bind.class).id(); BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, (TypeElement) element, false, false); bindingClass.addDoubleBinding(id, data); }
@Override public Void visitBinary(BinaryTree node, Void p) { // No checking unless the operator is "==" or "!=". if (!(node.getKind() == Tree.Kind.EQUAL_TO || node.getKind() == Tree.Kind.NOT_EQUAL_TO)) return super.visitBinary(node, p); ExpressionTree leftOp = node.getLeftOperand(); ExpressionTree rightOp = node.getRightOperand(); // Check passes if either arg is null. if (leftOp.getKind() == Tree.Kind.NULL_LITERAL || rightOp.getKind() == Tree.Kind.NULL_LITERAL) return super.visitBinary(node, p); AnnotatedTypeMirror left = atypeFactory.getAnnotatedType(leftOp); AnnotatedTypeMirror right = atypeFactory.getAnnotatedType(rightOp); // If either argument is a primitive, check passes due to auto-unboxing if (left.getKind().isPrimitive() || right.getKind().isPrimitive()) return super.visitBinary(node, p); if (!(shouldCheckFor(leftOp) && shouldCheckFor(rightOp))) return super.visitBinary(node, p); // Syntactic checks for legal uses of == if (suppressInsideComparison(node)) return super.visitBinary(node, p); if (suppressEarlyEquals(node)) return super.visitBinary(node, p); if (suppressEarlyCompareTo(node)) return super.visitBinary(node, p); if (suppressClassAnnotation(left, right)) { return super.visitBinary(node, p); } Element leftElt = null; Element rightElt = null; if (left instanceof org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedDeclaredType) { leftElt = ((DeclaredType) left.getUnderlyingType()).asElement(); } if (right instanceof org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedDeclaredType) { rightElt = ((DeclaredType) right.getUnderlyingType()).asElement(); } // if neither @Interned or @UsesObjectEquals, report error if (!(left.hasEffectiveAnnotation(INTERNED) || (leftElt != null && leftElt.getAnnotation(UsesObjectEquals.class) != null))) checker.report(Result.failure("not.interned", left), leftOp); if (!(right.hasEffectiveAnnotation(INTERNED) || (rightElt != null && rightElt.getAnnotation(UsesObjectEquals.class) != null))) checker.report(Result.failure("not.interned", right), rightOp); return super.visitBinary(node, p); }
private <A extends Annotation> ActionModel processAction( int genericPosition, Element element, Element outputElement, Class<A> annotationClass) { A annotation = element.getAnnotation(annotationClass); if (annotation != null) { System.out.println("Element: " + element.getSimpleName()); if (elementTools.isMethod(element)) { TypeMirror outputGeneric = ((DeclaredType) outputElement.asType()).getTypeArguments().get(genericPosition); List<? extends VariableElement> parameters = ((ExecutableElement) element).getParameters(); if (parameters.size() == 1 && processingEnv.getTypeUtils().isSameType(parameters.get(0).asType(), outputGeneric)) { ActionModel actionModel = new ActionModel(); actionModel.setMethodName(elementTools.getFieldName(element)); actionModel.setType(element.asType()); if (element.getKind() == ElementKind.METHOD) { actionModel.setType(((ExecutableElement) element).getParameters().get(0).asType()); } System.out.println("It maches!!!" + actionModel); return actionModel; } else { System.out.println("Does not match"); } } } return null; }
boolean getTreatUnknownKeyAsError(Element element) { JsonModel model = element.getAnnotation(JsonModel.class); if (model == null) { throw new IllegalArgumentException(); } return model.treatUnknownKeyAsError(); }
@Override public void process(Element element, EComponentHolder holder) throws Exception { ExecutableElement executableElement = (ExecutableElement) element; JMethod delegatingMethod = codeModelHelper.overrideAnnotatedMethod(executableElement, holder); JBlock previousBody = codeModelHelper.removeBody(delegatingMethod); JDefinedClass anonymousRunnableClass = codeModelHelper.createDelegatingAnonymousRunnableClass(holder, previousBody); UiThread annotation = element.getAnnotation(UiThread.class); long delay = annotation.delay(); UiThread.Propagation propagation = annotation.propagation(); if (delay == 0) { if (propagation == UiThread.Propagation.REUSE) { // Put in the check for the UI thread. addUIThreadCheck(delegatingMethod, previousBody, holder); } delegatingMethod.body().invoke(holder.getHandler(), "post").arg(_new(anonymousRunnableClass)); } else { delegatingMethod .body() .invoke(holder.getHandler(), "postDelayed") .arg(_new(anonymousRunnableClass)) .arg(lit(delay)); } }
@Override public void process(Element element, EBeanHolder holder) { final ExecutableElement afterPutMethod = (ExecutableElement) element; final UseModelHolder useModelHolder = holder.getPluginHolder(new UseModelHolder(holder)); useModelHolder.setAfterPutMethod(afterPutMethod); List<Class<? extends Annotation>> annotations = Arrays.asList(UseModel.class, LocalDBModel.class, ServerModel.class); for (Class<? extends Annotation> annotation : annotations) { if (element.getAnnotation(annotation) != null) return; } List<? extends VariableElement> parameters = afterPutMethod.getParameters(); JInvocation invocation = useModelHolder .getPutModelInitBlock() ._if(ref("result").ne(_null())) ._then() .invoke(afterPutMethod.getSimpleName().toString()); for (VariableElement param : parameters) { final String paramName = param.getSimpleName().toString(); ParamUtils.injectParam(paramName, invocation); } }
private KeySpec getKey(Element element) { if (isDefaultAnnotationElement(element, BindExtra.class.getName(), "value")) { return new KeySpec( null, generateKey(IntentFieldBinding.KEY_PREFIX, element.getSimpleName().toString())); } return new KeySpec(null, element.getAnnotation(BindExtra.class).value()); }
private void parseBindExtra( Element element, Map<TypeElement, IntentBindingAdapterGenerator> targetClassMap, Set<String> erasedTargetNames) throws InvalidTypeException { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify that the target has all the appropriate information for type TypeMirror type = element.asType(); if (type instanceof TypeVariable) { TypeVariable typeVariable = (TypeVariable) type; type = typeVariable.getUpperBound(); } validateNotRequiredArguments(element); validateForCodeGeneration(BindExtra.class, element); validateBindingPackage(BindExtra.class, element); // Assemble information on the bind point String name = element.getSimpleName().toString(); String intentType = typeUtil.getIntentType(type); KeySpec key = getKey(element); boolean required = element.getAnnotation(NotRequired.class) == null; boolean hasDefault = typeUtil.isPrimitive(type); boolean needsToBeCast = typeUtil.needToCastIntentType(type); IntentBindingAdapterGenerator intentBindingAdapterGenerator = getOrCreateTargetClass(targetClassMap, enclosingElement); IntentFieldBinding binding = new IntentFieldBinding(name, type, intentType, key, needsToBeCast, hasDefault, required); intentBindingAdapterGenerator.addField(binding); // Add the type-erased version to the valid targets set. erasedTargetNames.add(enclosingElement.toString()); }
private void addResponseHeaders(RestActionClass actionClass, MethodSpec.Builder builder) { for (Element element : actionClass.getAnnotatedElements(ResponseHeader.class)) { ResponseHeader annotation = element.getAnnotation(ResponseHeader.class); String fieldAddress = getFieldAddress(actionClass, element); builder.addStatement( fieldAddress + " = $L.get($S)", element.toString(), BASE_HEADERS_MAP, annotation.value()); } }
private boolean hasRelevantAnnotation(Element element) { for (Class<? extends Annotation> annotation : annotations) { if (element.getAnnotation(annotation) != null) { return true; } } return false; }
public TableEndpointDefinition(Element typeElement, ProcessorManager processorManager) { super(typeElement, processorManager); TableEndpoint endpoint = typeElement.getAnnotation(TableEndpoint.class); tableName = endpoint.name(); contentProviderName = endpoint.contentProviderName(); isTopLevel = typeElement.getEnclosingElement() instanceof PackageElement; List<? extends Element> elements = processorManager.getElements().getAllMembers((TypeElement) typeElement); for (Element innerElement : elements) { if (innerElement.getAnnotation(ContentUri.class) != null) { ContentUriDefinition contentUriDefinition = new ContentUriDefinition(innerElement, processorManager); if (!pathValidationMap.containsKey(contentUriDefinition.path)) { contentUriDefinitions.add(contentUriDefinition); } else { processorManager.logError( "There must be unique paths for the specified @ContentUri" + " %1s from %1s", contentUriDefinition.name, contentProviderName); } } else if (innerElement.getAnnotation(Notify.class) != null) { NotifyDefinition notifyDefinition = new NotifyDefinition(innerElement, processorManager); for (String path : notifyDefinition.paths) { Map<Notify.Method, List<NotifyDefinition>> methodListMap = notifyDefinitionPathMap.get(path); if (methodListMap == null) { methodListMap = Maps.newHashMap(); notifyDefinitionPathMap.put(path, methodListMap); } List<NotifyDefinition> notifyDefinitionList = methodListMap.get(notifyDefinition.method); if (notifyDefinitionList == null) { notifyDefinitionList = Lists.newArrayList(); methodListMap.put(notifyDefinition.method, notifyDefinitionList); } notifyDefinitionList.add(notifyDefinition); } } } }
private void addRequestHeaders(RestActionClass actionClass, MethodSpec.Builder builder) { for (Element element : actionClass.getAnnotatedElements(RequestHeader.class)) { RequestHeader annotation = element.getAnnotation(RequestHeader.class); builder.beginControlFlow("if (action.$L != null)", element); builder.addStatement( "requestBuilder.addHeader($S, action.$L.toString())", annotation.value(), element); builder.endControlFlow(); } }
private void parseLBindLayout( Element element, Map<TypeElement, BindingClass> targetClassMap, Set<String> erasedTargetNames) { String id = element.getAnnotation(LBindLayout.class).value(); BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, (TypeElement) element, true, false); bindingClass.setLayoutId(id); }
public static <T extends Annotation> T getAnnotation( final Class<T> annotationClass, final Element... elements) { for (final Element element : elements) { final T annotation = element.getAnnotation(annotationClass); if (annotation != null) { return annotation; } } return null; }
/** * Check parameter annotations for being qualifiers. * * @param round The round environment. */ private void checkParameters(RoundEnvironment round) { Set<? extends Element> params = round.getElementsAnnotatedWith(Parameter.class); note("processing %d parameter annotations", params.size()); for (Element param : params) { Qualifier q = param.getAnnotation(Qualifier.class); if (q == null) { warning(param, "parameter %s is not annotated as a qualifier", param); } } }
@Override protected boolean handleProcess( Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { for (Element el : roundEnv.getElementsAnnotatedWith(EventDoc.class)) { EventDoc event = el.getAnnotation(EventDoc.class); debug("Found event: " + event.module() + " " + event.code() + " " + event.desc()); addLine(getLine(event), getFilePath(event)); } return true; }
/* * Method to implement the @UsesObjectEquals functionality. * If a class is marked @UsesObjectEquals, it must: * * -not override .equals(Object) * -be a subclass of Object or another class marked @UsesObjectEquals * * If a class is not marked @UsesObjectEquals, it must: * * -not have a superclass marked @UsesObjectEquals * * * @see org.checkerframework.common.basetype.BaseTypeVisitor#visitClass(com.sun.source.tree.ClassTree, java.lang.Object) */ @Override public Void visitClass(ClassTree node, Void p) { // Looking for an @UsesObjectEquals class declaration TypeElement elt = TreeUtils.elementFromDeclaration(node); UsesObjectEquals annotation = elt.getAnnotation(UsesObjectEquals.class); Tree superClass = node.getExtendsClause(); Element elmt = null; if (superClass != null && (superClass instanceof IdentifierTree || superClass instanceof MemberSelectTree)) { elmt = TreeUtils.elementFromUse((ExpressionTree) superClass); } // if it's there, check to make sure does not override equals // and supertype is Object or @UsesObjectEquals if (annotation != null) { // check methods to ensure no .equals if (overridesEquals(node)) { checker.report(Result.failure("overrides.equals"), node); } if (!(superClass == null || (elmt != null && elmt.getAnnotation(UsesObjectEquals.class) != null))) { checker.report(Result.failure("superclass.unmarked"), node); } } else { // the class is not marked @UsesObjectEquals -> make sure its superclass isn't either. // this is impossible after design change making @UsesObjectEquals inherited? // check left in case of future design change back to non-inherited. if (superClass != null && (elmt != null && elmt.getAnnotation(UsesObjectEquals.class) != null)) { checker.report(Result.failure("superclass.marked"), node); } } return super.visitClass(node, p); }
@Override public boolean process( final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) { System.out.println(roundEnv); System.out.println(annotations); for (Element elem : roundEnv.getElementsAnnotatedWith(Decoder.class)) { Decoder decoder = elem.getAnnotation(Decoder.class); String message = String.format( "Annotation found in %s with decoder %s.", elem.getSimpleName(), decoder.value()); processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, message); } return true; }
public ValidateDescriptor(ModelDescriptor modelDescriptor, Element field) { super(modelDescriptor, field); this.validateIf = field.getAnnotation(ValidateIf.class); this.validateIfValue = field.getAnnotation(ValidateIfValue.class); ProcessingEnvironment processingEnv = modelDescriptor.getProcessingEnvironment(); Types typeUtils = processingEnv.getTypeUtils(); this.isMethodValidation = getField().getKind().equals(ElementKind.METHOD); if (this.isMethodValidation) { // Make sure our method validation returns a boolean value if (!((ExecutableElement) this.field).getReturnType().getKind().equals(TypeKind.BOOLEAN)) { modelDescriptor .getMessager() .printMessage( Diagnostic.Kind.ERROR, "Methods annotated with @Validate must return a boolean value!", field); } methodAnnotation = getField().getAnnotation(Validate.class); if (this.methodAnnotation == null) { modelDescriptor .getMessager() .printMessage(Diagnostic.Kind.ERROR, "Could not retrieve method validation annotation"); } } else { this.isList = typeUtils.isAssignable( field.asType(), typeUtils.getDeclaredType( processingEnv .getElementUtils() .getTypeElement(ListContainer.class.getCanonicalName()), typeUtils.getWildcardType(null, null))); } }
private void addResponses(RestActionClass actionClass, MethodSpec.Builder builder) { List<Element> responseElements = actionClass.getAnnotatedElements(com.santarest.annotations.Response.class); for (Element element : responseElements) { int status = element.getAnnotation(com.santarest.annotations.Response.class).value(); if (status > 0) { builder.beginControlFlow("if(response.getStatus() == $L)", status); addResponseStatements(actionClass, builder, element); builder.endControlFlow(); } else { addResponseStatements(actionClass, builder, element); } } }
@Override public JsonElement visitUndefinedClass(DeclaredType t, Element el) { TypeMirror tm = t.asElement().asType(); Element type = processingEnv.getTypeUtils().asElement(tm); JsonModel model = type.getAnnotation(JsonModel.class); String converterClassName = getConverterClassName(el); if (model == null && converterClassName == null) { Log.e("expect for use decorated class by JsonModel annotation.", el); encountError = true; return defaultAction(t, el); } return genJsonElement(t, el, Kind.MODEL); }
String getElementKeyString(Element element) { JsonKey key = element.getAnnotation(JsonKey.class); JsonModel model = element.getEnclosingElement().getAnnotation(JsonModel.class); String keyStr; if (!"".equals(key.value())) { keyStr = key.value(); } else if ("".equals(key.value()) && key.decamelize()) { keyStr = decamelize(element.toString()); } else if ("".equals(key.value()) && model.decamelize()) { keyStr = decamelize(element.toString()); } else { keyStr = element.toString(); } return keyStr; }
private void processMethodsOfView(EnclosingView enclosingView, Element view) { List<? extends Element> enclosedElements = view.getEnclosedElements(); for (Element e : enclosedElements) { System.out.println("Method process: " + e.toString()); ViewMethod viewMethod = new ViewMethod(); viewMethod.setMethodName(elementTools.getFieldName(e)); viewMethod.setReturnType(((ExecutableElement) e).getReturnType()); viewMethod.setDecorate(e.getAnnotation(NoDecorate.class) == null); List<? extends VariableElement> parameters = ((ExecutableElement) e).getParameters(); for (VariableElement parameterElement : parameters) { viewMethod.getParameters().add(parameterElement.asType()); } enclosingView.getMethods().add(viewMethod); } }
private void addPathParams(RestActionClass actionClass, MethodSpec.Builder builder) { for (Element element : actionClass.getAnnotatedElements(Path.class)) { Path param = element.getAnnotation(Path.class); String path = param.value(); String name = element.getSimpleName().toString(); if (StringUtils.isEmpty(path)) { path = name; } boolean encode = param.encode(); builder.beginControlFlow("if (action.$L != null)", name); builder.addStatement( "requestBuilder.addPathParam($S, action.$L.toString(), $L)", path, name, encode); builder.endControlFlow(); } }
@Override public void process(Element element, EIntentServiceHolder holder) throws Exception { ExecutableElement executableElement = (ExecutableElement) element; String methodName = element.getSimpleName().toString(); ServiceAction annotation = element.getAnnotation(ServiceAction.class); String extraKey = annotation.value(); if (extraKey.isEmpty()) { extraKey = methodName; } JFieldVar actionKeyField = createStaticActionField(holder, extraKey, methodName); addActionInOnHandleIntent(holder, executableElement, methodName, actionKeyField); addActionToIntentBuilder(holder, executableElement, methodName, actionKeyField); }
JsonElement genJsonElement(TypeMirror t, Element el, Kind kind) { if (kind == null) { Log.e("invalid state. this is APT bugs."); encountError = true; return defaultAction(t, el); } JsonElement jsonElement = new JsonElement(); jsonElement.setKey(getElementKeyString(el)); JsonKey key = el.getAnnotation(JsonKey.class); String setter = getElementSetter(el); if (key.in() && setter == null) { Log.e("can't find setter method", el); encountError = true; return defaultAction(t, el); } String getter = getElementGetter(el); if (key.out() && getter == null) { Log.e("can't find getter method", el); encountError = true; return defaultAction(t, el); } String converterClassName = getConverterClassName(el); if (converterClassName != null) { TypeElement element = processingEnv.getElementUtils().getTypeElement(converterClassName); Log.d(element != null ? element.asType().toString() : null); if (element == null || !isMethodExists(element, "getInstance", Modifier.PUBLIC, Modifier.STATIC)) { Log.e("converter needs [public static getInstance()].", element); } kind = Kind.CONVERTER; } jsonElement.setIn(key.in()); jsonElement.setSetter(setter); jsonElement.setOut(key.out()); jsonElement.setGetter(getter); jsonElement.setModelName(t.toString()); jsonElement.setKind(kind); jsonElement.setConverter(converterClassName); return jsonElement; }
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { for (Element elem : roundEnv.getElementsAnnotatedWith(FixedRecord.class)) { String classPackage = processingEnv.getElementUtils().getPackageOf(elem).getQualifiedName().toString(); ClassWrapper classWrapper = new ClassWrapper(classPackage, elem.getSimpleName().toString()); List<Element> listGetter = getFixedFieldAnnotateMethod(elem); for (Element elemMethod : listGetter) { TypeWrapper typeWrapper; MethodWrapper methodWrapper = new MethodWrapper(); FixedField fixedField = elemMethod.getAnnotation(FixedField.class); String decoratorClass = getDecoratorClass(fixedField); methodWrapper.setName(elemMethod.getSimpleName().toString()); methodWrapper.setFixedField(fixedField); methodWrapper.setDecoratorClass(decoratorClass); String fullName = ((ExecutableType) elemMethod.asType()).getReturnType().toString(); if (fullName.contains("<") && fixedField.collectionSize() > 0) { fullName = fullName.substring(fullName.indexOf("<") + 1, fullName.indexOf(">")); } String packageName = fullName.substring(0, fullName.lastIndexOf(".")); String typeName = fullName.substring(packageName.length() + 1); if (fixedField.length() == 0 && fixedField.collectionSize() == 0) { methodWrapper.setBean(true); } else if (fixedField.collectionSize() > 0) { methodWrapper.setList(true); } typeWrapper = new TypeWrapper(packageName, typeName); methodWrapper.setType(typeWrapper); classWrapper.addMethod(methodWrapper); } parser.createParserClass(classWrapper); // TODO processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, ""); } if (roundEnv.processingOver()) { parser.getJavaFileBuilder().writeJavaFile(processingEnv); return false; } return true; // no further processing of this annotation type }