private static MethodSpec getTagsBuilderMethod(ClassName name, ClassName tags, int size) { ParameterSpec parameter = ParameterSpec.builder(ArrayTypeName.of(tags), "tags").build(); return MethodSpec.methodBuilder("tags") .addModifiers(Modifier.PUBLIC) .addParameter(parameter) .varargs() .addStatement("$T clone = new $T[" + size + "]", ArrayTypeName.of(tags), tags) .beginControlFlow("if(this.tags != null)") .addStatement("System.arraycopy(this.tags, 0, clone, 0, " + size + ")") .endControlFlow() .beginControlFlow("for($T tag : tags)", tags) .addStatement("clone[tag.ordinal()] = tag") .endControlFlow() .addStatement("this.tags = clone") .returns(name) .addStatement("return this") .build(); }
private static boolean typeNeedsTypeVariable(TypeName type, TypeVariableName typeVariable) { if (typeVariable.equals(type)) { return true; } if (type instanceof ParameterizedTypeName) { ParameterizedTypeName parameterized = ((ParameterizedTypeName) type); for (TypeName typeArgument : parameterized.typeArguments) { if (typeVariable.equals(typeArgument)) { return true; } } } if (type instanceof ArrayTypeName) { ArrayTypeName arrayType = (ArrayTypeName) type; if (typeVariable.equals(arrayType.componentType)) { return true; } } return false; }
private MethodSpec generateUnboxMethod( ClassName className, TypeName typeName, String primitiveType) { String paramName = className.simpleName() + "Param"; paramName = Character.toLowerCase(paramName.charAt(0)) + paramName.substring(1); String primitiveArray = primitiveType + "s"; return MethodSpec.methodBuilder("toPrimitive") .addParameters(ImmutableList.of(ParameterSpec.builder(ArrayTypeName.of(className), paramName).build())) .returns(ArrayTypeName.of(typeName)) .addModifiers(PUBLIC) .addModifiers(STATIC) .addStatement("$L[] $L = new $L[$L.length]", primitiveType, primitiveArray, primitiveType, paramName) .beginControlFlow("for (int i = 0; i < $L.length; i++)", paramName) .addStatement("$L[i] = $L[i]", primitiveArray, paramName) .endControlFlow() .addStatement("return $L", primitiveArray) .build(); }
public static TypeName createIdSearch(ProcessingEnvironment processingEnvironment, LocalConfiguration localConfiguration) { TypeName idTypeName = TypeName.get(localConfiguration.getIdTypeMirror()); if (idTypeName.equals(ClassName.get("java.lang", "Boolean")) || idTypeName.equals(TypeName.BOOLEAN)) { return ClassName.get(GlobalConfiguration.BOOLEAN_ID_SEARCH_CLASS_PACKAGE, GlobalConfiguration.BOOLEAN_ID_SEARCH_CLASS_NAME); } else if (idTypeName.equals(ArrayTypeName.of(TypeName.BYTE))) { return ClassName.get(GlobalConfiguration.BYTE_ARRAY_ID_SEARCH_CLASS_PACKAGE, GlobalConfiguration.BYTE_ARRAY_ID_SEARCH_CLASS_NAME); } else if (idTypeName.equals(ClassName.get("java.lang", "Byte")) || idTypeName.equals(TypeName.BYTE)) { return ClassName.get(GlobalConfiguration.BOOLEAN_ID_SEARCH_CLASS_PACKAGE, GlobalConfiguration.BOOLEAN_ID_SEARCH_CLASS_NAME); } else if (idTypeName.equals(ClassName.get("java.util", "Date"))) { return ClassName.get(GlobalConfiguration.DATE_ID_SEARCH_CLASS_PACKAGE, GlobalConfiguration.DATE_ID_SEARCH_CLASS_NAME); } else if (idTypeName.equals(ClassName.get("java.lang", "Double")) || idTypeName.equals(TypeName.DOUBLE)) { return ClassName.get(GlobalConfiguration.DOUBLE_ID_SEARCH_CLASS_PACKAGE, GlobalConfiguration.DOUBLE_ID_SEARCH_CLASS_NAME); } else if (idTypeName.equals(ClassName.get("java.lang", "Float")) || idTypeName.equals(TypeName.FLOAT)) { return ClassName.get(GlobalConfiguration.FLOAT_ID_SEARCH_CLASS_PACKAGE, GlobalConfiguration.FLOAT_ID_SEARCH_CLASS_NAME); } else if (idTypeName.equals(ClassName.get("java.lang", "Integer")) || idTypeName.equals(TypeName.INT)) { return ClassName.get(GlobalConfiguration.INTEGER_ID_SEARCH_CLASS_PACKAGE, GlobalConfiguration.INTEGER_ID_SEARCH_CLASS_NAME); } else if (idTypeName.equals(ClassName.get("java.lang", "Long")) || idTypeName.equals(TypeName.LONG)) { return ClassName.get(GlobalConfiguration.LONG_ID_SEARCH_CLASS_PACKAGE, GlobalConfiguration.LONG_ID_SEARCH_CLASS_NAME); } else if (idTypeName.equals(ClassName.get("java.lang", "Short")) || idTypeName.equals(TypeName.SHORT)) { return ClassName.get(GlobalConfiguration.SHORT_ID_SEARCH_CLASS_PACKAGE, GlobalConfiguration.SHORT_ID_SEARCH_CLASS_NAME); } else if (idTypeName.equals(ClassName.get("java.lang", "String"))) { return ClassName.get(GlobalConfiguration.STRING_ID_SEARCH_CLASS_PACKAGE, GlobalConfiguration.STRING_ID_SEARCH_CLASS_NAME); } else { throw new RealmRepositoryException("Not supported id type " + idTypeName.toString() + " in " + localConfiguration.getDataRepositoryInterfaceTypeElement().getSimpleName().toString()); } }
public static Type valueOf(TypeName typeName) { if (ArrayTypeName.of(byte.class).equals(typeName)) { return CursorRowElement.Type.BLOB; } else if (TypeName.DOUBLE.equals(typeName) || TypeName.DOUBLE.box().equals(typeName)) { return CursorRowElement.Type.DOUBLE; } else if (TypeName.INT.equals(typeName) || TypeName.INT.box().equals(typeName)) { return CursorRowElement.Type.INT; } else if (TypeName.FLOAT.equals(typeName) || TypeName.FLOAT.box().equals(typeName)) { return CursorRowElement.Type.FLOAT; } else if (TypeName.LONG.equals(typeName) || TypeName.LONG.box().equals(typeName)) { return CursorRowElement.Type.LONG; } else if (ClassName.get(String.class).equals(typeName)) { return CursorRowElement.Type.STRING; } else if (TypeName.SHORT.equals(typeName) || TypeName.SHORT.box().equals(typeName)) { return CursorRowElement.Type.SHORT; } return null; }
protected void genNFieldInfo() { FieldInfo dynfieldinfo, fieldinfo; List<long[]> finfo = new ArrayList<long[]>(); for (String name : m_gettersinfo.keySet()) { dynfieldinfo = m_dynfieldsinfo.get(name); if (dynfieldinfo.id > 0) { finfo.add(new long[]{dynfieldinfo.id, dynfieldinfo.fieldoff, dynfieldinfo.fieldsize}); } } fieldinfo = new FieldInfo(); fieldinfo.name = String.format("m_nfieldinfo_%s", Utils.genRandomString()); fieldinfo.type = ArrayTypeName.of(ArrayTypeName.of(TypeName.LONG)); String initlstr = Utils.toInitLiteral(finfo); fieldinfo.specbuilder = FieldSpec.builder(fieldinfo.type, fieldinfo.name, Modifier.PRIVATE, Modifier.STATIC) .initializer("$1L", initlstr); m_fieldsinfo.put("nfieldinfo", fieldinfo); }
private MethodSpec buildGetSingleByRawQueryMethod() { final String cursorVarName = "cursor"; return MethodSpec.methodBuilder("getSingle") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(getClassNameOfElement()) .addParameter(CONTEXT, "context", Modifier.FINAL) .addParameter(STRING, "rawQueryClause", Modifier.FINAL) .addParameter(ArrayTypeName.of(STRING), "rawQueryArgs", Modifier.FINAL) .addParameter(TypeName.BOOLEAN, "fromCache", Modifier.FINAL) .addStatement("final $T $L = getReadableDatabase($L)" + ".rawQuery(rawQueryClause, rawQueryArgs)", CURSOR, cursorVarName, "context") .beginControlFlow("if (!$L.moveToFirst())", cursorVarName) .addStatement("$L.close()", cursorVarName) .addStatement("return null") .endControlFlow() .addStatement("$T ret = instantiateObject(cursor, context, fromCache)", getClassNameOfElement()) .addStatement("$L.close()", cursorVarName) .addStatement("return ret") .build(); }
private MethodSpec buildGetListByRawQueryMethod() { final String cursorVarName = "cursor"; return MethodSpec.methodBuilder("getList") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(ParameterizedTypeName.get(LIST, getClassNameOfElement())) .addParameter(CONTEXT, "context", Modifier.FINAL) .addParameter(STRING, "rawQueryClause", Modifier.FINAL) .addParameter(ArrayTypeName.of(STRING), "rawQueryArgs", Modifier.FINAL) .addParameter(TypeName.BOOLEAN, "fromCache", Modifier.FINAL) .addStatement("final $T<$T> ret = new $T<>()", LIST, getClassNameOfElement(), ARRAY_LIST) .addStatement("final $T $L = getReadableDatabase($L)" + ".rawQuery(rawQueryClause, rawQueryArgs)", CURSOR, cursorVarName, "context") .beginControlFlow("if (!$L.moveToFirst())", cursorVarName) .addStatement("$L.close()", cursorVarName) .addStatement("return ret") .endControlFlow() .beginControlFlow("do") .addStatement("ret.add(instantiateObject(cursor, context, fromCache))") .endControlFlow("while(cursor.moveToNext())") .addStatement("$L.close()", cursorVarName) .addStatement("return ret") .build(); }
private MethodSpec generateUpdateMethod() { MethodSpec.Builder saveMethodBuidler = MethodSpec.methodBuilder("update") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(TypeName.INT) .addParameter(ClassName.get(Class.class), "clazz") .addParameter(ClassName.get(ContentValuesWrapper.class), "valuesWrapper") .addParameter(ClassName.get(String.class), "where") .addParameter(ArrayTypeName.of(ClassName.get(String.class)), "whereArgs"); for (TableInfo table : tables) { String daoField = table.getDaoClassName().replace("$$", "").toLowerCase(); saveMethodBuidler.addStatement("if($L.class.equals(clazz)) return $L.update(valuesWrapper, where, whereArgs)", table.getClassName(), daoField); } saveMethodBuidler.addStatement("return 0"); return saveMethodBuidler.build(); }
private MethodSpec generateDeleteMethod() { MethodSpec.Builder saveMethodBuidler = MethodSpec.methodBuilder("delete") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(TypeName.INT) .addParameter(ClassName.get(Class.class), "clazz") .addParameter(ClassName.get(String.class), "where") .addParameter(ArrayTypeName.of(ClassName.get(String.class)), "whereArgs"); for (TableInfo table : tables) { String daoField = table.getDaoClassName().replace("$$", "").toLowerCase(); saveMethodBuidler.addStatement("if($L.class.equals(clazz)) return $L.delete(where, whereArgs)", table.getClassName(), daoField); } saveMethodBuidler.addStatement("return 0"); return saveMethodBuidler.build(); }
private MethodSpec generateRawQueryMethod() { MethodSpec.Builder queryMethodBuidler = MethodSpec.methodBuilder("rawQuery") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(ClassName.get("android.database", "Cursor")) .addParameter(ClassName.get(Class.class), "clazz") .addParameter(TypeName.BOOLEAN, "distinct") .addParameter(ArrayTypeName.of(ClassName.get(String.class)), "columns") .addParameter(ClassName.get(String.class), "selection") .addParameter(ArrayTypeName.of(ClassName.get(String.class)), "selectionArgs") .addParameter(ClassName.get(String.class), "groupBy") .addParameter(ClassName.get(String.class), "having") .addParameter(ClassName.get(String.class), "orderBy") .addParameter(ClassName.get(String.class), "limit"); for (TableInfo table : tables) { String daoField = table.getDaoClassName().replace("$$", "").toLowerCase(); queryMethodBuidler.addStatement("if($L.class.equals(clazz)) return $L.rawQuery(distinct, columns, selection, selectionArgs, groupBy, having, orderBy, limit)", table.getClassName(), daoField); } queryMethodBuidler.addStatement("return null"); return queryMethodBuidler.build(); }
private MethodSpec generatorQueryMethod() { MethodSpec.Builder queryBuilder = MethodSpec.methodBuilder("query") .addModifiers(Modifier.PUBLIC) .returns(ClassName.get(List.class)) .addParameter(TypeName.BOOLEAN, "distinct") .addParameter(ArrayTypeName.of(ClassName.get(String.class)), "columns") .addParameter(ClassName.get(String.class), "selection") .addParameter(ArrayTypeName.of(ClassName.get(String.class)), "selectionArgs") .addParameter(ClassName.get(String.class), "groupBy") .addParameter(ClassName.get(String.class), "having") .addParameter(ClassName.get(String.class), "orderBy") .addParameter(ClassName.get(String.class), "limit") .addStatement("$T cursor = this.rawQuery(distinct, columns, selection, selectionArgs, groupBy, having, orderBy, limit)", ClassName.get("android.database", "Cursor")); queryBuilder.addStatement("$T list = new $T()", ArrayList.class, ArrayList.class); queryBuilder.addCode("if (cursor.moveToFirst()) {"); queryBuilder.addCode(" do {"); queryBuilder.addCode(" list.add(fillData(cursor));"); queryBuilder.addCode(" } while (cursor.moveToNext());"); queryBuilder.addCode("}"); queryBuilder.addStatement("return list"); return queryBuilder.build(); }
@Override MethodSpec buildSignature(RDFSClazz domainClazz, OntGenerationConfig config) throws RepositoryException { if (getRanges() != null) { MethodSpec.Builder setter = buildParameterlessSetterSignature(domainClazz, config); // Get the vararg parameter type: TypeName paramType = ArrayTypeName.of(getParameterType(config, false)); return setter.addParameter(paramType, "values") .varargs() .build(); } else { return null; } }
private static String simpleName(TypeName typeName) { if (typeName instanceof ClassName) { return UPPER_CAMEL.to(LOWER_CAMEL, ((ClassName) typeName).simpleName()); } else if (typeName instanceof ParameterizedTypeName) { ParameterizedTypeName parameterizedTypeName = (ParameterizedTypeName) typeName; return UPPER_CAMEL.to(LOWER_CAMEL, parameterizedTypeName.rawType.simpleName()) + (parameterizedTypeName.typeArguments.isEmpty() ? "" : "__") + simpleName(parameterizedTypeName.typeArguments); } else if (typeName instanceof ArrayTypeName) { return "array__" + simpleName(((ArrayTypeName) typeName).componentType); } else if (typeName instanceof WildcardTypeName) { WildcardTypeName wildcardTypeName = (WildcardTypeName) typeName; return "wildcard__" + simpleName(ImmutableList.<TypeName>builder().addAll(wildcardTypeName.lowerBounds) .addAll(wildcardTypeName.upperBounds) .build()); } else if (typeName instanceof TypeVariableName) { TypeVariableName variable = (TypeVariableName) typeName; return variable.name + (variable.bounds.isEmpty() ? "" : "__") + simpleName(variable.bounds); } else { return typeName.toString(); } }
private FieldSpec buildProjectionField() { CodeBlock.Builder initializer = CodeBlock.builder(); initializer.add("{"); boolean first = true; for (RecordField field : parsed.fields) { if (!first) { initializer.add(", "); } initializer.add("$N.$L()", projectionsClass, field.name); first = false; } initializer.add("}"); TypeName arrayOfStrings = ArrayTypeName.of(ClassName.get(String.class)); return FieldSpec.builder(arrayOfStrings, "PROJECTION", Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .initializer(initializer.build().toString()) .build(); }
private MethodSpec collectionVarargSetter(final Descriptor d, final ExecutableElement field) { String fieldName = fieldName(field); TypeName itemType = genericArgument(field, 0); MethodSpec.Builder setter = MethodSpec.methodBuilder(fieldName) .addModifiers(PUBLIC) .addParameter(ArrayTypeName.of(itemType), fieldName) .varargs() .returns(builderType(d)); ensureSafeVarargs(setter); collectionNullGuard(setter, field); setter.addStatement("return $N($T.asList($N))", fieldName, ClassName.get(Arrays.class), fieldName); return setter.build(); }
private MethodSpec buildInitSerializersMethod( Map<PropertyInfo, JSerializerType> properties ) throws UnableToCompleteException { MethodSpec.Builder builder = MethodSpec.methodBuilder( "initSerializers" ) .addModifiers( Modifier.PROTECTED ) .addAnnotation( Override.class ) .returns( ArrayTypeName.of( BeanPropertySerializer.class ) ) .addStatement( "$T result = new $T[$L]", ArrayTypeName.of( BeanPropertySerializer.class ), BeanPropertySerializer.class, properties.size() ); int i = 0; for ( Entry<PropertyInfo, JSerializerType> entry : properties.entrySet() ) { builder.addStatement( "result[$L] = $L", i++, buildSerializer( entry.getKey(), entry.getValue() ) ); } builder.addStatement( "return result" ); return builder.build(); }
private static MethodSpec getTagsGetterMethod(ClassName tags) { return MethodSpec.methodBuilder("getTags") .addModifiers(Modifier.PUBLIC) .returns(ArrayTypeName.of(tags)) .addStatement("return tags") .build(); }
public static JavaFile markerBuilder(Domain ontology) { List<Key> keys = ontology.getKeys(); ClassName name = ClassName.get(ontology.getTargetPackage(), ontology.getName()+ MARKER_BUILDER); Builder builder = TypeSpec.classBuilder(name) .addJavadoc(composeJavadoc(ontology, name)) .addModifiers(Modifier.PUBLIC); ClassName markerName = getName(ontology); for(Key key : keys) { builder.addMethod(getBuilderMethod(markerName, key)); } if(ontology.hasTags()) { ClassName tagsName = TagGenerator.getName(ontology); ParameterSpec parameter = ParameterSpec.builder(ArrayTypeName.of(tagsName), "value").build(); builder.addMethod(MethodSpec.methodBuilder("tags") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addParameter(parameter).varargs() .addStatement("$T marker = new $T()", markerName, markerName) .addStatement("marker.tags($N)", parameter) .returns(markerName) .addStatement("return marker") .build()); } return JavaFile.builder(name.packageName(), builder.build()).build(); }
private static MethodSpec getTagsMethod(ClassName name, ClassName tags) { return MethodSpec.methodBuilder("tags") .addModifiers(Modifier.PUBLIC) .addParameter(ArrayTypeName.of(tags), "value") .varargs() .addStatement("marker.tags(value)") .returns(name) .addStatement("return this") .build(); }
public TypeSpec generate() { return TypeSpec.interfaceBuilder(Constants.QUERY_LOGGER) .addModifiers(Modifier.PUBLIC) .addMethod(MethodSpec.methodBuilder("onQuery") .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .addParameter(ClassName.get(String.class), "query") .addParameter(ArrayTypeName.get(String[].class), "datas") .build()) .build(); }
private <T extends Type> void generateStaticArrayTypes( Class<T> superclass, String path) throws IOException { String packageName = createPackageName(superclass); ClassName className; for (int length = 1; length <= StaticArray.MAX_SIZE_OF_STATIC_ARRAY; length++) { TypeVariableName typeVariableName = TypeVariableName.get("T").withBounds(Type.class); MethodSpec constructorSpec = MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addParameter(ParameterizedTypeName.get(ClassName.get(List.class), typeVariableName), "values") .addStatement("super($L, $N)", length, "values") .build(); MethodSpec arrayOverloadConstructorSpec = MethodSpec.constructorBuilder() .addAnnotation(SafeVarargs.class) .addModifiers(Modifier.PUBLIC) .addParameter(ArrayTypeName.of(typeVariableName), "values") .varargs() .addStatement("super($L, $N)", length, "values") .build(); className = ClassName.get(packageName, superclass.getSimpleName() + length); TypeSpec bytesType = TypeSpec .classBuilder(className.simpleName()) .addTypeVariable(typeVariableName) .addJavadoc(CODEGEN_WARNING) .superclass(ParameterizedTypeName.get(ClassName.get(superclass), typeVariableName)) .addModifiers(Modifier.PUBLIC) .addMethods(Arrays.asList(constructorSpec, arrayOverloadConstructorSpec)) .build(); write(packageName, bytesType, path); } }
private static TypeName getTypeNameOrArrayTypeName(String name) { if (name.endsWith("[]")) { String rawName = name.substring(0, name.length() - 2); TypeHelper rawTypeHelper = TypeHelper.getTypeHelper(rawName); return ArrayTypeName.of(rawTypeHelper.getTypeName()); } else { return ClassName.bestGuess(name); } }
private static MethodSpec createPermissionResultMethod(RuntimePermissionsElement element) { String targetParam = "target"; String requestCodeParam = "requestCode"; String grantResultsParam = "grantResults"; MethodSpec.Builder builder = MethodSpec.methodBuilder("onRequestPermissionsResult") .addTypeVariables(element.getTypeVariables()) .addModifiers(Modifier.STATIC) .returns(TypeName.VOID) .addParameter(element.getTypeName(), targetParam) .addParameter(TypeName.INT, requestCodeParam) .addParameter(ArrayTypeName.of(TypeName.INT), grantResultsParam); // For each @NeedsPermission method, add a switch case builder.beginControlFlow("switch ($N)", requestCodeParam); List<ExecutableElement> needsPermissionsMethods = element.getNeedsPermissionsMethods(); for (ExecutableElement needsMethod : needsPermissionsMethods) { String[] needsPermissionParameter = needsMethod.getAnnotation(NeedsPermission.class).value(); if (containsKey(ADD_WITH_CHECK_BODY_MAP,needsPermissionParameter)) { continue; } builder.addCode("case $N:\n", requestCodeFieldName(needsMethod)); // Delegate switch-case generation to implementing classes addResultCaseBody(builder, needsMethod, element, targetParam, grantResultsParam); } // Add the default case builder .addCode("default:\n") .addStatement("break") .endControlFlow(); return builder.build(); }
private static CodeBlock generateHashCodeExpression(ExecutableElement propertyElement) { String methodName = propertyElement.getSimpleName().toString(); TypeName propertyType = TypeName.get(propertyElement.getReturnType()); Set<String> propertyAnnotations = getAnnotations(propertyElement); boolean nullable = propertyAnnotations.contains("Nullable"); if (propertyType.equals(TypeName.BYTE) || propertyType.equals(TypeName.SHORT) || propertyType.equals(TypeName.CHAR) || propertyType.equals(TypeName.INT)) { return CodeBlock.of("this.$N()", methodName); } else if (propertyType.equals(TypeName.LONG)) { return CodeBlock.of("(this.$N() >>> 32) ^ this.$N()", methodName, methodName); } else if (propertyType.equals(TypeName.FLOAT)) { return CodeBlock.of("Float.floatToIntBits(this.$N())", methodName); } else if (propertyType.equals(TypeName.DOUBLE)) { return CodeBlock.of( "(Double.doubleToLongBits(this.$N()) >>> 32) ^ Double.doubleToLongBits(this.$N())", methodName, methodName); } else if (propertyType.equals(TypeName.BOOLEAN)) { return CodeBlock.of("this.$N() ? 1231 : 1237", methodName); } else if (propertyType instanceof ArrayTypeName) { return CodeBlock.of("$T.hashCode(this.$N())", Arrays.class, methodName); } else { if (nullable) { return CodeBlock.of("($N() == null) ? 0 : this.$N().hashCode()", methodName, methodName); } else { return CodeBlock.of("this.$N().hashCode()", methodName); } } }
private static CodeBlock generateEqualsExpression(ExecutableElement propertyElement) { String methodName = propertyElement.getSimpleName().toString(); TypeName propertyType = TypeName.get(propertyElement.getReturnType()); Set<String> propertyAnnotations = getAnnotations(propertyElement); boolean nullable = propertyAnnotations.contains("Nullable"); if (propertyType.equals(TypeName.FLOAT)) { return CodeBlock.of("(Float.floatToIntBits(this.$N()) == Float.floatToIntBits(that.$N()))", methodName, methodName); } else if (propertyType.equals(TypeName.DOUBLE)) { return CodeBlock.of( "(Double.doubleToLongBits(this.$N()) == Double.doubleToLongBits(that.$N()))", methodName, methodName); } else if (propertyType.isPrimitive()) { return CodeBlock.of("(this.$N() == that.$N())", methodName, methodName); } else if (propertyType instanceof ArrayTypeName) { return CodeBlock.of("($T.equals(this.$N(), that.$N()))", Arrays.class, methodName, methodName); } else { if (nullable) { return CodeBlock.of( "((this.$N() == null) ? (that.$N() == null) : this.$N().equals(that.$N()))", methodName, methodName, methodName, methodName); } else { return CodeBlock.of("(this.$N().equals(that.$N()))", methodName, methodName); } } }
@Test public void findGenericTypesShouldCollectGenericTypesRecursively() throws Exception { // setup final TypeElement element = elements.getTypeElement(CustomConverter.class.getCanonicalName()); // exercise final List<TypeName> actual = TypeElements.findGenericTypes(element, Converter.class.getSimpleName()); // verify assertThat(actual).hasSize(2); assertThat(actual.get(0)).isInstanceOf(ArrayTypeName.class); assertThat(actual.get(0).toString()).isEqualTo("java.lang.String[]"); assertThat(actual.get(1)).isInstanceOf(ClassName.class); assertThat(actual.get(1).toString()).isEqualTo("java.lang.String"); }
public TypeName getTypeNameByKind(VariableElement param) { switch (param.asType().getKind()) { case BOOLEAN: return TypeName.BOOLEAN; case BYTE: return TypeName.BYTE; case CHAR: return TypeName.CHAR; case DOUBLE: return TypeName.DOUBLE; case FLOAT: return TypeName.FLOAT; case INT: return TypeName.INT; case LONG: return TypeName.LONG; case SHORT: return TypeName.SHORT; case DECLARED: TypeMirror type = param.asType(); TypeName typeName = ClassName.get(type); typeName = applyAnnotations(typeName, param); return typeName; case ARRAY: ArrayType arrayType = (ArrayType) param.asType(); TypeName arrayTypeName = ArrayTypeName.get(arrayType); arrayTypeName = applyAnnotations(arrayTypeName, param); return arrayTypeName; default: throw new IllegalStateException("unsupported kind: " + param.asType().getKind()); } }
private MethodSpec buildDeleteByQueryMethod() { return MethodSpec.methodBuilder("deleteByQuery") .returns(TypeName.INT) .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addParameter(CONTEXT, "context", Modifier.FINAL) .addParameter(STRING, "whereClause", Modifier.FINAL) .addParameter(ArrayTypeName.of(STRING), "whereArgs", Modifier.FINAL) .addStatement("return getWritableDatabase($L)" + ".delete(\n$S, \nwhereClause, \nwhereArgs)", "context", getTableName(mElement)) .build(); }
private MethodSpec buildGetSingleMethod() { final String cursorVarName = "cursor"; return MethodSpec.methodBuilder("getSingle") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(getClassNameOfElement()) .addParameter(CONTEXT, "context", Modifier.FINAL) .addParameter(STRING, "whereClause", Modifier.FINAL) .addParameter(ArrayTypeName.of(STRING), "whereArgs", Modifier.FINAL) .addParameter(STRING, "groupBy", Modifier.FINAL) .addParameter(STRING, "having", Modifier.FINAL) .addParameter(STRING, "orderBy", Modifier.FINAL) .addParameter(TypeName.BOOLEAN, "fromCache", Modifier.FINAL) .addStatement("final String sql = $S \n" + "+ (whereClause != null ? $S + whereClause : $S)\n" + "+ (groupBy != null ? $S + groupBy : $S)\n" + "+ (having != null ? $S + groupBy : $S)\n" + "+ (orderBy != null ? $S + orderBy : $S)\n" + "+ $S", getJoinStatementForFetch(), " WHERE ", "", " GROUP BY ", "", " HAVING ", "", " ORDER BY ", "", " LIMIT 1 ") .addStatement("final $T $L = getReadableDatabase($L)" + ".rawQuery(sql, whereArgs)", CURSOR, cursorVarName, "context") .beginControlFlow("if (!$L.moveToFirst())", cursorVarName) .addStatement("$L.close()", cursorVarName) .addStatement("return null") .endControlFlow() .addStatement("$T ret = instantiateObject(cursor, context, fromCache)", getClassNameOfElement()) .addStatement("$L.close()", cursorVarName) .addStatement("return ret") .build(); }
private MethodSpec buildGetListMethod() { final String cursorVarName = "cursor"; return MethodSpec.methodBuilder("getList") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(ParameterizedTypeName.get(LIST, getClassNameOfElement())) .addParameter(CONTEXT, "context", Modifier.FINAL) .addParameter(STRING, "whereClause", Modifier.FINAL) .addParameter(ArrayTypeName.of(STRING), "whereArgs", Modifier.FINAL) .addParameter(STRING, "groupBy", Modifier.FINAL) .addParameter(STRING, "having", Modifier.FINAL) .addParameter(STRING, "orderBy", Modifier.FINAL) .addParameter(STRING, "limit", Modifier.FINAL) .addParameter(TypeName.BOOLEAN, "fromCache", Modifier.FINAL) .addStatement("final String sql = $S \n" + "+ (whereClause != null ? $S + whereClause : $S)\n" + "+ (groupBy != null ? $S + groupBy : $S)\n" + "+ (having != null ? $S + groupBy : $S)\n" + "+ (orderBy != null ? $S + orderBy : $S)\n" + "+ (limit != null ? $S + limit : $S)", getJoinStatementForFetch(), " WHERE ", "", " GROUP BY ", "", " HAVING ", "", " ORDER BY ", "", " LIMIT ", "") .addStatement("final $T<$T> ret = new $T<>()", LIST, getClassNameOfElement(), ARRAY_LIST) .addStatement("final $T $L = getReadableDatabase($L)" + ".rawQuery(sql, whereArgs)", CURSOR, cursorVarName, "context") .beginControlFlow("if (!$L.moveToFirst())", cursorVarName) .addStatement("$L.close()", cursorVarName) .addStatement("return ret") .endControlFlow() .beginControlFlow("do") .addStatement("ret.add(instantiateObject(cursor, context, fromCache))") .endControlFlow("while(cursor.moveToNext())") .addStatement("$L.close()", cursorVarName) .addStatement("return ret") .build(); }
private MethodSpec.Builder createProcessEventBuilder(TypeMirror dataClass) { ParameterizedTypeName targetType = ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(TypeName.OBJECT)); ArrayTypeName arrTargetType = ArrayTypeName.of(targetType); return MethodSpec.methodBuilder("processEvent") .addModifiers(Modifier.PRIVATE) .addParameter(TypeName.get(dataClass), "data", Modifier.FINAL) .addParameter(arrTargetType, "target", Modifier.FINAL); }
/** * Returns "com_Foo" for com.Foo, "com_Foo_com_Bar_com_Baz" for Foo<Bar, Baz>. * upper_bounds_UpperBound_Foo for "? extends Foo" and * lower_bounds_LowerBound_Foo for "? super Foo". Assuming raw types are not * used, there will be not conflicts. */ public static String getSourceCodeName(TypeName typeName) { Preconditions.checkNotNull(typeName); if (typeName.isPrimitive()) { return typeName.toString(); } else if (typeName instanceof ClassName) { return getClassCanonicalName((ClassName) typeName).replace(".", "_"); } else if (typeName instanceof ParameterizedTypeName) { ParameterizedTypeName p = (ParameterizedTypeName) typeName; StringBuilder builder = new StringBuilder(getSourceCodeName(p.rawType)); for (TypeName t : p.typeArguments) { builder.append("_").append(getSourceCodeName(t)); } return builder.toString(); } else if (typeName instanceof WildcardTypeName) { WildcardTypeName w = (WildcardTypeName) typeName; if (w.upperBounds.size() > 0) { return "upper_bounds_" + getSourceCodeName(w.upperBounds.get(0)); } else { Preconditions.checkState(w.lowerBounds.size() > 0); return "lower_bounds_" + getSourceCodeName(w.lowerBounds.get(0)); } } else if (typeName instanceof ArrayTypeName) { ArrayTypeName arrayTypeName = (ArrayTypeName) typeName; return "ArrayOf" + getSourceCodeName(arrayTypeName.componentType); } throw new RuntimeException("Unexpected type: " + typeName); }
public TypeName asTypeName() { final ClassName className = ClassName.get(getTypeElement()); if (isArrayElement) { return ArrayTypeName.of(className); } return className; }
@Override public MethodSpec methodSpec() { String sanitized = sanitizeParamName(name); return MethodSpec.methodBuilder(sanitizeParamName("with" + capitalize(sanitized))) .addJavadoc("required: $L\n", param.isRequired()) .addJavadoc("$L\n", isNotEmpty(param.getExample()) ? "example: " + param.getExample() : "") .addJavadoc("@param $L $L\n", sanitized, trimToEmpty(param.getDescription())) .addModifiers(Modifier.PUBLIC) .returns(ClassName.bestGuess(apiClass.name())) .varargs(param.isRepeat()) .addParameter(param.isRepeat() ? ArrayTypeName.of(ClassName.get(String.class)) : ClassName.get(String.class), sanitized) .addStatement("$L.addFormParam($S, $L)", req.name(), name, sanitized) .addStatement("return this", req.name()) .build(); }
@Override public MethodSpec methodSpec() { String sanitized = sanitizeParamName(name); return MethodSpec.methodBuilder(sanitizeParamName("with" + capitalize(sanitized))) .addJavadoc("required: $L\n", param.isRequired()) .addJavadoc("$L\n", isNotEmpty(param.getExample()) ? "example: " + param.getExample() : "") .addJavadoc("@param $L $L\n", sanitized, trimToEmpty(param.getDescription())) .addModifiers(Modifier.PUBLIC) .returns(ClassName.bestGuess(apiClass.name())) .varargs(param.isRepeat()) .addParameter(param.isRepeat() ? ArrayTypeName.of(ClassName.get(String.class)) : ClassName.get(String.class), sanitized) .addStatement("$L.addQueryParam($S, $L)", req.name(), name, sanitized) .addStatement("return this", req.name()) .build(); }
private MethodSpec generateQueryMethod(TypeSpec.Builder typeSpecBuilder) { MethodSpec.Builder queryMethodBuidler = MethodSpec.methodBuilder("query") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(ClassName.get(List.class)) .addParameter(ClassName.get(Class.class), "clazz") .addParameter(TypeName.BOOLEAN, "distinct") .addParameter(ArrayTypeName.of(ClassName.get(String.class)), "columns") .addParameter(ClassName.get(String.class), "selection") .addParameter(ArrayTypeName.of(ClassName.get(String.class)), "selectionArgs") .addParameter(ClassName.get(String.class), "groupBy") .addParameter(ClassName.get(String.class), "having") .addParameter(ClassName.get(String.class), "orderBy") .addParameter(ClassName.get(String.class), "limit"); for (TableInfo table : tables) { String daoField = table.getDaoClassName().replace("$$", "").toLowerCase(); MethodSpec methodSpec = MethodSpec.methodBuilder("query") .addModifiers(Modifier.PUBLIC) .returns(ClassName.get(List.class)) .addParameter(ClassName.get(table.getPackageName(), table.getClassName()), "bean") .addParameter(TypeName.BOOLEAN, "distinct") .addParameter(ArrayTypeName.of(ClassName.get(String.class)), "columns") .addParameter(ClassName.get(String.class), "selection") .addParameter(ArrayTypeName.of(ClassName.get(String.class)), "selectionArgs") .addParameter(ClassName.get(String.class), "groupBy") .addParameter(ClassName.get(String.class), "having") .addParameter(ClassName.get(String.class), "orderBy") .addParameter(ClassName.get(String.class), "limit") .addStatement("return $L.query(distinct, columns, selection, selectionArgs, groupBy, having, orderBy, limit)", daoField) .build(); typeSpecBuilder.addMethod(methodSpec); queryMethodBuidler.addStatement("if($L.class.equals(clazz)) return $L.query(distinct, columns, selection, selectionArgs, groupBy, having, orderBy, limit)", table.getClassName(), daoField); } queryMethodBuidler.addStatement("return null"); return queryMethodBuidler.build(); }
private MethodSpec generatorUpdateMethod() { MethodSpec.Builder updateBuilder = MethodSpec.methodBuilder("update") .addModifiers(Modifier.PUBLIC) .returns(TypeName.INT) .addParameter(ClassName.get(ContentValuesWrapper.class), "valuesWrapper") .addParameter(ClassName.get(String.class), "where") .addParameter(ArrayTypeName.of(ClassName.get(String.class)), "whereArgs"); updateBuilder.addStatement("return database.update(TABLE_NAME, valuesWrapper.getValues(), where, whereArgs)"); return updateBuilder.build(); }
private MethodSpec generatorDeleteMethod() { MethodSpec.Builder insertBuilder = MethodSpec.methodBuilder("delete") .addModifiers(Modifier.PUBLIC) .returns(TypeName.INT) .addParameter(ClassName.get(String.class), "where") .addParameter(ArrayTypeName.of(ClassName.get(String.class)), "whereArgs") .addStatement("return database.delete(TABLE_NAME, where, whereArgs)"); return insertBuilder.build(); }