com.squareup.javapoet.TypeSpec.Builder Java Examples

The following examples show how to use com.squareup.javapoet.TypeSpec.Builder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BindSharedPreferencesBuilder.java    From kripton with Apache License 2.0 6 votes vote down vote up
/**
 * Generate instance of shared preferences.
 *
 * @param className
 *            the class name
 */
private static void generateInstance(String className) {
	builder.addField(FieldSpec.builder(className(className), "instance", Modifier.PRIVATE, Modifier.STATIC).addJavadoc("instance of shared preferences\n").build());
	// instance
	MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("getInstance").addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.SYNCHRONIZED)
			.addJavadoc("get instance of shared preferences\n").returns(className(className));

	methodBuilder.beginControlFlow("if (instance==null)");
	methodBuilder.addStatement("instance=new $L()", className(className));
	methodBuilder.addComment("read and write instance to sync with default values");
	methodBuilder.addStatement("instance.write(instance.read())");
	methodBuilder.endControlFlow();
	methodBuilder.addCode("return instance;\n");

	builder.addMethod(methodBuilder.build());
}
 
Example #2
Source File: ArgumentBuilderModel.java    From Akatsuki with Apache License 2.0 6 votes vote down vote up
private void extendConcludingBuilder(ProcessorContext context, Builder builderTypeBuilder,
		DeclaredType concludingBuilder) {
	if (context.utils().isAssignable(concludingBuilder,
			context.utils().of(ClassArgBuilder.class), true)) {
		// implement the constructor with class parameters
		// TODO that bundle part is redundant... consider improving
		builderTypeBuilder.addMethod(MethodSpec.constructorBuilder()
				.addParameter(ClassName.get(AndroidTypes.Bundle.asMirror(context)),
						"bundle")
				.addCode("super(bundle, $L.class);", targetClassName).build());
	} else if (context.utils().isAssignable(concludingBuilder,
			context.utils().of(ArgConcludingBuilder.class), true)) {
		// this is probably an user implemented one
		builderTypeBuilder.addMethod(MethodSpec.constructorBuilder()
				.addCode("this.bundle = new Bundle();").build());
	} else {
		throw new AssertionError(concludingBuilder + " is not supported, @ArgConfig should"
				+ " not allow this in the first place...");
	}
}
 
Example #3
Source File: DynamicEntityBuilder.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private void createDateField(Builder builder, Field field) {

		AnnotationSpec column = AnnotationSpec.builder(Column.class)
				.addMember("name", "ColumnNamePrefix + " + field.fieldName()).build();

		AnnotationSpec temporal = AnnotationSpec.builder(Temporal.class)
				.addMember("value", "javax.persistence.TemporalType.DATE").build();
		FieldSpec fieldSpec = FieldSpec.builder(Date.class, field.getName(), Modifier.PRIVATE)
				.addAnnotation(this.fieldDescribe(field)).addAnnotation(this.index(field))
				.addAnnotation(this.checkPersist(field)).addAnnotation(column).addAnnotation(temporal).build();
		MethodSpec get = MethodSpec.methodBuilder("get" + StringUtils.capitalize(field.getName()))
				.addModifiers(Modifier.PUBLIC).returns(Date.class).addStatement("return this." + field.getName())
				.build();
		MethodSpec set = MethodSpec.methodBuilder("set" + StringUtils.capitalize(field.getName()))
				.addModifiers(Modifier.PUBLIC).returns(void.class).addParameter(Date.class, field.getName())
				.addStatement("this." + field.getName() + " = " + field.getName()).build();
		builder.addField(this.fieldName(field)).addField(fieldSpec).addMethod(get).addMethod(set);

	}
 
Example #4
Source File: AkatsukiProcessorSourceNameTest.java    From Akatsuki with Apache License 2.0 6 votes vote down vote up
private static GeneratedClassWithName staticInnerClass(String... classes) {
	// maybe (String first, String...more) ?
	if (classes.length == 0)
		throw new IllegalArgumentException("");
	String[] generatedClasses = new String[classes.length];
	TypeSpec.Builder lastBuilder = null;
	for (int i = classes.length - 1; i >= 0; i--) {
		String clazz = classes[i];
		final Builder currentBuilder = TypeSpec.classBuilder(clazz)
				.addModifiers((i == 0 ? Modifier.PUBLIC : Modifier.STATIC))
				.addField(field(STRING_TYPE, clazz.toLowerCase(), Retained.class));
		if (lastBuilder != null) {
			currentBuilder.addType(lastBuilder.build());
		}
		// we generate static inner class names eg A.B -> A$B
		generatedClasses[i] = IntStream.range(0, i + 1).boxed().map(n -> classes[n])
				.collect(Collectors.joining("$"));
		lastBuilder = currentBuilder;
	}
	final JavaFile file = JavaFile.builder(TEST_PACKAGE, lastBuilder.build()).build();
	final JavaFileObject object = JavaFileObjects
			.forSourceString(TEST_PACKAGE + "." + classes[0], file.toString());

	return new GeneratedClassWithName(object, generatedClasses);
}
 
Example #5
Source File: EnumClass.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public TypeSpec poetSpec() {
    Builder enumBuilder = createEnumBuilder(className)
        .addField(String.class, VALUE, Modifier.PRIVATE, Modifier.FINAL)
        .addMethod(toStringBuilder().addStatement("return $T.valueOf($N)", String.class, VALUE).build())
        .addMethod(fromValueSpec())
        .addMethod(knownValuesSpec())
        .addMethod(createConstructor());

    addDeprecated(enumBuilder::addAnnotation, shape);
    addJavadoc(enumBuilder::addJavadoc, shape);

    shape.getEnums().forEach(
        e -> enumBuilder.addEnumConstant(e.getName(), TypeSpec.anonymousClassBuilder("$S", e.getValue()).build())
    );
    enumBuilder.addEnumConstant(UNKNOWN_TO_SDK_VERSION, TypeSpec.anonymousClassBuilder("null").build());

    return enumBuilder.build();
}
 
Example #6
Source File: DynamicEntityBuilder.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private void createTimeField(Builder builder, Field field) {

		AnnotationSpec column = AnnotationSpec.builder(Column.class)
				.addMember("name", "ColumnNamePrefix + " + field.fieldName()).build();

		AnnotationSpec temporal = AnnotationSpec.builder(Temporal.class)
				.addMember("value", "javax.persistence.TemporalType.TIME").build();

		FieldSpec fieldSpec = FieldSpec.builder(Date.class, field.getName(), Modifier.PRIVATE)
				.addAnnotation(this.fieldDescribe(field)).addAnnotation(this.index(field))
				.addAnnotation(this.checkPersist(field)).addAnnotation(column).addAnnotation(temporal).build();
		MethodSpec get = MethodSpec.methodBuilder("get" + StringUtils.capitalize(field.getName()))
				.addModifiers(Modifier.PUBLIC).returns(Date.class).addStatement("return this." + field.getName())
				.build();
		MethodSpec set = MethodSpec.methodBuilder("set" + StringUtils.capitalize(field.getName()))
				.addModifiers(Modifier.PUBLIC).returns(void.class).addParameter(Date.class, field.getName())
				.addStatement("this." + field.getName() + " = " + field.getName()).build();
		builder.addField(this.fieldName(field)).addField(fieldSpec).addMethod(get).addMethod(set);

	}
 
Example #7
Source File: DynamicEntityBuilder.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private void createDateTimeField(Builder builder, Field field) {

		AnnotationSpec column = AnnotationSpec.builder(Column.class)
				.addMember("name", "ColumnNamePrefix + " + field.fieldName()).build();

		AnnotationSpec temporal = AnnotationSpec.builder(Temporal.class)
				.addMember("value", "javax.persistence.TemporalType.TIMESTAMP").build();

		FieldSpec fieldSpec = FieldSpec.builder(Date.class, field.getName(), Modifier.PRIVATE)
				.addAnnotation(this.fieldDescribe(field)).addAnnotation(this.index(field))
				.addAnnotation(this.checkPersist(field)).addAnnotation(column).addAnnotation(temporal).build();
		MethodSpec get = MethodSpec.methodBuilder("get" + StringUtils.capitalize(field.getName()))
				.addModifiers(Modifier.PUBLIC).returns(Date.class).addStatement("return this." + field.getName())
				.build();
		MethodSpec set = MethodSpec.methodBuilder("set" + StringUtils.capitalize(field.getName()))
				.addModifiers(Modifier.PUBLIC).returns(void.class).addParameter(Date.class, field.getName())
				.addStatement("this." + field.getName() + " = " + field.getName()).build();
		builder.addField(this.fieldName(field)).addField(fieldSpec).addMethod(get).addMethod(set);

	}
 
Example #8
Source File: DynamicEntityBuilder.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private void createIdField(Builder builder) {
//		public String getId() {
//			return id;
//		}
//		public void setId(String id) {
//			this.id = id;
//		}
//		@FieldDescribe("数据库主键,自动生成.")
//		@Id
//		@Column(length = length_id, name = ColumnNamePrefix + id_FIELDNAME)
//		private String id = createId();
		AnnotationSpec fieldDescribe = AnnotationSpec.builder(FieldDescribe.class).addMember("value", "\"数据库主键,自动生成.\"")
				.build();
		AnnotationSpec id = AnnotationSpec.builder(Id.class).build();
		AnnotationSpec column = AnnotationSpec.builder(Column.class).addMember("length", "length_id")
				.addMember("name", "ColumnNamePrefix + id_FIELDNAME").build();
		MethodSpec get = MethodSpec.methodBuilder("getId").addModifiers(Modifier.PUBLIC).returns(String.class)
				.addStatement("return this.id").build();
		MethodSpec set = MethodSpec.methodBuilder("setId").addModifiers(Modifier.PUBLIC).returns(void.class)
				.addParameter(String.class, "id").addStatement("this.id = id").build();
		FieldSpec fieldSpec = FieldSpec.builder(String.class, JpaObject.id_FIELDNAME, Modifier.PRIVATE)
				.initializer("createId()").addAnnotation(fieldDescribe).addAnnotation(id).addAnnotation(column).build();
		builder.addField(fieldSpec).addMethod(set).addMethod(get);
	}
 
Example #9
Source File: BindSharedPreferencesBuilder.java    From kripton with Apache License 2.0 6 votes vote down vote up
private static void generateCreate(String sharedPreferenceName, String beanClassName, boolean generateRx, boolean generateLiveData) {
	MethodSpec.Builder method = MethodSpec.methodBuilder("createPrefs").addModifiers(Modifier.PRIVATE).addJavadoc("create prefs\n");
	if (StringUtils.hasText(sharedPreferenceName)) {
		method.addCode("// using typeName attribute of annotation @BindSharedPreferences as typeName\n");
		method.addStatement("prefs=$T.getContext().getSharedPreferences(SHARED_PREFERENCE_NAME, $T.MODE_PRIVATE)", KriptonLibrary.class, Context.class);
	} else {
		method.addCode("// no typeName specified, using default shared preferences\n");
		method.addStatement("prefs=$T.getDefaultSharedPreferences($T.getContext())", KriptonDynamicClassManager.getInstance().getPreferenceManagerClazz(), KriptonLibrary.class);
	}

	if (generateRx) {
		method.addStatement("prefs.registerOnSharedPreferenceChangeListener(rxListener)");
	}

	if (generateLiveData) {
		method.addStatement("prefs.registerOnSharedPreferenceChangeListener(liveDataListener)");
	}
	builder.addMethod(method.build());
}
 
Example #10
Source File: BindSharedPreferencesBuilder.java    From kripton with Apache License 2.0 6 votes vote down vote up
private static void generateMethodAsLiveData(Converter<String, String> converter, TypeName typeName, PrefsProperty property) {

		ParameterizedTypeName liveDataType = ParameterizedTypeName.get(KriptonDynamicClassManager.getInstance().getLiveDataHandlerClazz(), typeName);
		String className = getBuildPreferenceName(property.getParent());

		// generate compute
		MethodSpec.Builder computeBuilder = MethodSpec.methodBuilder("compute").addModifiers(Modifier.PROTECTED).returns(typeName).addAnnotation(Override.class);
		computeBuilder.addStatement("$L.this.refresh()", className);
		computeBuilder.addStatement("return $L.this.get$L()", className, converter.convert(property.getName()));

		// generate builder
		TypeSpec liveDataBuilder = TypeSpec.anonymousClassBuilder("").addSuperinterface(liveDataType).addMethod(computeBuilder.build()).build();

		MethodSpec ms = MethodSpec.methodBuilder("get" + converter.convert(property.getName()) + "AsLiveData").addModifiers(Modifier.PUBLIC)
				.returns(ParameterizedTypeName.get(KriptonDynamicClassManager.getInstance().getMutableLiveDataClazz(), typeName))
				.addJavadoc("Obtains an LiveData to <code>$L</code> property\n\n", property.getName()).addJavadoc("@return\nan LiveData to <code>$L</code> property\n", property.getName())
				.addStatement("$T liveData=$L", liveDataType, liveDataBuilder).addStatement("registryLiveData($S, liveData)", property.getPreferenceKey()).addStatement("return liveData.getLiveData()")
				.build();

		builder.addMethod(ms);
	}
 
Example #11
Source File: SyncClientClass.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private MethodSpec constructor() {
    MethodSpec.Builder builder = MethodSpec.constructorBuilder()
                                           .addModifiers(Modifier.PROTECTED)
                                           .addParameter(SdkClientConfiguration.class, "clientConfiguration")
                                           .addStatement("this.clientHandler = new $T(clientConfiguration)",
                                                         protocolSpec.getClientHandlerClass())
                                           .addStatement("this.clientConfiguration = clientConfiguration");
    FieldSpec protocolFactoryField = protocolSpec.protocolFactory(model);
    if (model.getMetadata().isJsonProtocol()) {
        builder.addStatement("this.$N = init($T.builder()).build()", protocolFactoryField.name,
                             protocolFactoryField.type);
    } else {
        builder.addStatement("this.$N = init()", protocolFactoryField.name);
    }

    if (model.getEndpointOperation().isPresent()) {
        builder.beginControlFlow("if (clientConfiguration.option(SdkClientOption.ENDPOINT_DISCOVERY_ENABLED))");
        builder.addStatement("this.endpointDiscoveryCache = $T.create($T.create(this))",
                             EndpointDiscoveryRefreshCache.class,
                             poetExtensions.getClientClass(model.getNamingStrategy().getServiceName() +
                                                           "EndpointDiscoveryCacheLoader"));
        builder.endControlFlow();
    }

    return builder.build();
}
 
Example #12
Source File: BindSharedPreferencesBuilder.java    From kripton with Apache License 2.0 6 votes vote down vote up
/**
 * Generate write method.
 *
 * @param entity
 *            the entity
 */
private static void generateWriteMethod(PrefsEntity entity) {
	// write method
	MethodSpec.Builder method = MethodSpec.methodBuilder("write").addJavadoc("write bean entirely\n\n").addJavadoc("@param bean bean to entirely write\n").addModifiers(Modifier.PUBLIC)
			.addParameter(typeName(entity.getName()), "bean").returns(Void.TYPE);
	method.addStatement("$T editor=prefs.edit()", SharedPreferences.Editor.class);

	PrefsTransform transform;
	for (PrefsProperty item : entity.getCollection()) {
		if (item.hasTypeAdapter()) {
			transform = PrefsTransformer.lookup(item.typeAdapter.getDataTypeTypename());
		} else {
			transform = PrefsTransformer.lookup(item);
		}

		transform.generateWriteProperty(method, "editor", typeName(entity.getElement()), "bean", item);
		method.addCode("\n");
	}
	method.addCode("\n");
	method.addStatement("editor.commit()");
	builder.addMethod(method.build());
}
 
Example #13
Source File: InitializerSpec.java    From spring-init with Apache License 2.0 6 votes vote down vote up
private void addBeanMethods(MethodSpec.Builder builder, TypeElement type) {
	boolean conditional = utils.hasAnnotation(type, SpringClassNames.CONDITIONAL.toString());
	if (this.hasEnabled) {
		builder.beginControlFlow("if ($T.enabled)", this.className);
	}
	if (conditional) {
		builder.addStatement("$T conditions = context.getBeanFactory().getBean($T.class)",
				SpringClassNames.CONDITION_SERVICE, SpringClassNames.CONDITION_SERVICE);
		builder.beginControlFlow("if (conditions.matches($T.class))", type);
	}
	builder.beginControlFlow("if (context.getBeanFactory().getBeanNamesForType($T.class).length==0)", type);
	boolean conditionsAvailable = addScannedComponents(builder, conditional);
	addNewBeanForConfig(builder, type);
	for (ExecutableElement method : getBeanMethods(type)) {
		conditionsAvailable |= createBeanMethod(builder, method, type, conditionsAvailable);
	}
	addResources(builder);
	addRegistrarInvokers(builder);
	builder.endControlFlow();
	if (conditional) {
		builder.endControlFlow();
	}
	if (this.hasEnabled) {
		builder.endControlFlow();
	}
}
 
Example #14
Source File: InitializerSpec.java    From spring-init with Apache License 2.0 6 votes vote down vote up
private void addImportInvokers(MethodSpec.Builder builder, TypeElement element) {
	Set<TypeElement> registrarInitializers = imports.getImports().get(element);
	if (registrarInitializers != null) {
		for (TypeElement imported : registrarInitializers) {
			if (utils.isImporter(imported)) {
				builder.addStatement("context.getBeanFactory().getBean($T.class).add($T.class, \"$L\")",
						SpringClassNames.IMPORT_REGISTRARS, configurationType, imported.getQualifiedName());
			}
			else if (utils.getPackage(imported).equals(pkg) || components.getAll().contains(imported)) {
				builder.addStatement("new $T().initialize(context)",
						InitializerSpec.toInitializerNameFromConfigurationName(imported));
			}
			else {
				builder.addStatement("context.getBeanFactory().getBean($T.class).add($T.class, \"$L\")",
						SpringClassNames.IMPORT_REGISTRARS, configurationType, imported.getQualifiedName());
			}
		}
	}
}
 
Example #15
Source File: BindSharedPreferencesBuilder.java    From kripton with Apache License 2.0 6 votes vote down vote up
/**
 * Generate single read method.
 *
 * @param entity
 *            the entity
 */
private static void generateSingleReadMethod(PrefsEntity entity) {
	// read method
	PrefsTransform transform;
	Converter<String, String> converter = CaseFormat.LOWER_CAMEL.converterTo(CaseFormat.UPPER_CAMEL);

	for (PrefsProperty item : entity.getCollection()) {
		MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("get" + converter.convert(item.getName())).addModifiers(Modifier.PUBLIC)
				.addJavadoc("reads property <code>$L</code> from shared pref with key <code>$L</code>\n\n", item.getName(), item.getPreferenceKey())
				.addJavadoc("@return property $L value\n", item.getName()).returns(item.getPropertyType().getTypeName());

		if (item.hasTypeAdapter()) {
			transform = PrefsTransformer.lookup(item.typeAdapter.getDataTypeTypename());
		} else {
			transform = PrefsTransformer.lookup(item);
		}

		transform.generateReadProperty(methodBuilder, "prefs", typeName(item.getElement().asType()), "defaultBean", item, false, ReadType.RETURN);

		builder.addMethod(methodBuilder.build());
	}

}
 
Example #16
Source File: SqlModifyBuilder.java    From kripton with Apache License 2.0 6 votes vote down vote up
/**
 * Generate init for dynamic where variables.
 *
 * @param method
 *            the method
 * @param methodBuilder
 *            the method builder
 * @param dynamiWhereName
 *            the dynami where name
 * @param dynamicWhereArgsName
 *            the dynamic where args name
 */
static void generateInitForDynamicWhereVariables(SQLiteModelMethod method, MethodSpec.Builder methodBuilder,
		String dynamiWhereName, String dynamicWhereArgsName) {
	GenerationPartMarks.begin(methodBuilder, GenerationPartMarks.CODE_001);
	// where _sqlDynamicWhere and _sqlDynamicWhereArgs
	if (method.hasDynamicWhereConditions()) {
		methodBuilder.addCode("// initialize dynamic where\n");
		methodBuilder.addStatement("String _sqlDynamicWhere=$L", dynamiWhereName);
	}
	if (method.hasDynamicWhereArgs()) {
		methodBuilder.addCode("// initialize dynamic where args\n");
		methodBuilder.addStatement("String[] _sqlDynamicWhereArgs=$L", dynamicWhereArgsName);
	}
	GenerationPartMarks.end(methodBuilder, GenerationPartMarks.CODE_001);

}
 
Example #17
Source File: SqlSelectBuilder.java    From kripton with Apache License 2.0 6 votes vote down vote up
/**
 * Generate select.
 *
 * @param builder
 *            the builder
 * @param method
 *            the method
 * @throws ClassNotFoundException
 *             the class not found exception
 */
public static void generateSelect(Builder builder, SQLiteModelMethod method) throws ClassNotFoundException {
	SelectType selectResultType = SelectBuilderUtility.detectSelectType(method);

	// generate select method
	selectResultType.generate(builder, method);

	if (method.hasLiveData()) {
		// generate
		selectResultType.generateLiveData(builder, method);
	}

	if (method.contentProviderEntryPathEnabled) {
		// we need to generate UPDATE or DELETE for content provider to
		generateSelectForContentProvider(builder, method, selectResultType);
	}
}
 
Example #18
Source File: SimpleProcessorTests.java    From spring-init with Apache License 2.0 6 votes vote down vote up
private static InputFileDescriptor createType(String classname, boolean markAtConfiguration, String... imports) {
	Builder builder = TypeSpec.classBuilder(classname);
	if (markAtConfiguration) {
		builder.addAnnotation(CONFIGURATION);
	}
	if (imports.length > 0) {
		importAnnotation(builder, imports);
	}
	// builder.addSuperinterface(SpringClassNames.INITIALIZER_TYPE);
	builder.addModifiers(Modifier.PUBLIC);
	// builder.addMethod(createInitializer());
	TypeSpec ts = builder.build();
	JavaFile file = JavaFile.builder("", ts).build();
	StringBuilder sb = new StringBuilder();
	try {
		file.writeTo(sb);
	}
	catch (IOException e) {
		throw new IllegalStateException("Unable to write out source file: " + classname, e);
	}
	return new InputFileDescriptor(classname, sb.toString());
}
 
Example #19
Source File: JSupplierCodeGenerator.java    From jackdaw with Apache License 2.0 5 votes vote down vote up
private void addFunction(
    final Builder builder, final TypeElement typeElement,
    final Element element, final JSupplier annotation
) {
    final JSupplierType functionType = annotation.type();
    final String packageName = getFunctionPackageName(functionType);
    final String caller = ModelUtils.getCaller(element);
    final TypeName typeName = TypeUtils.getTypeName(element, true);

    final ClassName supplierClass = ClassName.get(packageName, CLASS_NAME);
    final TypeName parameterClass = TypeUtils.getTypeName(typeElement);
    final ParameterizedTypeName fieldTypeName =
        ParameterizedTypeName.get(supplierClass, typeName);

    builder.addMethod(
        MethodSpec.methodBuilder(TypeUtils.getName(element))
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
            .addParameter(parameterClass, "o", Modifier.FINAL)
            .returns(fieldTypeName)
            .addCode(
                SourceTextUtils.lines(
                    "return new $T() {",
                        "@Override",
                        "public $T get() {",
                            "return o.$L;",
                        "}",
                    "};",
                    ""
                ),
                fieldTypeName, typeName, caller
            )
            .build()
    );
}
 
Example #20
Source File: DynamicEntityBuilder.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private void createStringLobField(Builder builder, Field field) {

//		public static final String stringLobValue_FIELDNAME = "stringLobValue";
//		@FieldDescribe("长文本.")
//		@Lob
//		@Basic(fetch = FetchType.EAGER)
//		@Column(length = JpaObject.length_10M, name = ColumnNamePrefix + stringLobValue_FIELDNAME)

		AnnotationSpec lob = AnnotationSpec.builder(Lob.class).build();

		AnnotationSpec basic = AnnotationSpec.builder(Basic.class)
				.addMember("fetch", "javax.persistence.FetchType.EAGER").build();

		AnnotationSpec column = AnnotationSpec.builder(Column.class).addMember("length", "length_100M")
				.addMember("name", "ColumnNamePrefix + " + field.fieldName()).build();

		FieldSpec fieldSpec = FieldSpec.builder(String.class, field.getName(), Modifier.PRIVATE)
				.addAnnotation(this.fieldDescribe(field)).addAnnotation(lob).addAnnotation(basic).addAnnotation(column)
				.build();
		MethodSpec get = MethodSpec.methodBuilder("get" + StringUtils.capitalize(field.getName()))
				.addModifiers(Modifier.PUBLIC).returns(String.class).addStatement("return this." + field.getName())
				.build();
		MethodSpec set = MethodSpec.methodBuilder("set" + StringUtils.capitalize(field.getName()))
				.addModifiers(Modifier.PUBLIC).returns(void.class).addParameter(String.class, field.getName())
				.addStatement("this." + field.getName() + " = " + field.getName()).build();
		builder.addField(this.fieldName(field)).addField(fieldSpec).addMethod(get).addMethod(set);

	}
 
Example #21
Source File: SyncClientClass.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private List<MethodSpec> operationMethodSpecs(OperationModel opModel) {
    List<MethodSpec> methods = new ArrayList<>();

    MethodSpec.Builder method = SyncClientInterface.operationMethodSignature(model, opModel)
                                                   .addAnnotation(Override.class)
                                                   .addCode(ClientClassUtils.callApplySignerOverrideMethod(opModel))
                                                   .addCode(ClientClassUtils.addEndpointTraitCode(opModel))
                                                   .addCode(protocolSpec.responseHandler(model, opModel));

    protocolSpec.errorResponseHandler(opModel).ifPresent(method::addCode);

    if (opModel.getEndpointDiscovery() != null) {
        method.addStatement("$T cachedEndpoint = null", URI.class);
        method.beginControlFlow("if (clientConfiguration.option(SdkClientOption.ENDPOINT_DISCOVERY_ENABLED))");
        method.addStatement("\n\nString key = clientConfiguration.option($T.CREDENTIALS_PROVIDER)." +
                            "resolveCredentials().accessKeyId()", AwsClientOption.class);
        method.addStatement("EndpointDiscoveryRequest endpointDiscoveryRequest = $T.builder().required($L)" +
                            ".defaultEndpoint(clientConfiguration.option($T.ENDPOINT)).build()",
                            EndpointDiscoveryRequest.class,
                            opModel.getInputShape().getEndpointDiscovery().isRequired(),
                            SdkClientOption.class);
        method.addStatement("cachedEndpoint = $L.get(key, endpointDiscoveryRequest)",
                            "endpointDiscoveryCache");
        method.endControlFlow();
    }

    method.addCode(protocolSpec.executionHandler(opModel));

    methods.add(method.build());

    methods.addAll(paginatedMethods(opModel));

    return methods;
}
 
Example #22
Source File: InitializerSpec.java    From spring-init with Apache License 2.0 5 votes vote down vote up
private void addRegistrarInvokers(MethodSpec.Builder builder) {
	addImportInvokers(builder, configurationType);
	List<? extends AnnotationMirror> annotationMirrors = configurationType.getAnnotationMirrors();
	for (AnnotationMirror am : annotationMirrors) {
		// Looking up something like @EnableBar
		TypeElement element = (TypeElement) am.getAnnotationType().asElement();
		addImportInvokers(builder, element);
	}
}
 
Example #23
Source File: TestSource.java    From Akatsuki with Apache License 2.0 5 votes vote down vote up
private Builder specBuilder() {
	Builder builder = TypeSpec.classBuilder(className).addModifiers(modifiers).addFields(specs)
			.addTypes(innerClasses.stream().map(s -> s.specBuilder().build())
					.collect(Collectors.toList()));

	if (superClass != null)
		builder.superclass(ClassName.get(superClass.packageName, superClass.className));

	for (BiFunction<Builder, TestSource, Builder> function : builderTransformers) {
		builder = function.apply(builder, this);
	}

	return builder;
}
 
Example #24
Source File: JFunctionCodeGenerator.java    From jackdaw with Apache License 2.0 5 votes vote down vote up
@Override
protected final void generateBody(
    final CodeGeneratorContext context, final Builder builder
) throws Exception {
    final TypeElement typeElement = context.getTypeElement();
    SourceCodeUtils.processSimpleMethodsAndVariables(
        builder, typeElement, JFunction.class,
        new AnnotatedElementCallback<JFunction>() {
            @Override
            public void process(final Element element, final JFunction annotation) {
                addFunction(builder, typeElement, element, annotation);
            }
        }
    );
}
 
Example #25
Source File: JFunctionCodeGenerator.java    From jackdaw with Apache License 2.0 5 votes vote down vote up
private void addFunction(
    final Builder builder, final TypeElement typeElement,
    final Element element, final JFunction annotation
) {
    final JFunctionType functionType = annotation.type();
    final String packageName = getFunctionPackageName(functionType);
    final String caller = ModelUtils.getCaller(element);
    final TypeName typeName = TypeUtils.getTypeName(element, true);

    final boolean nullable = annotation.nullable();
    final String operation = nullable ? "(input != null) ? input.$L : null" : "input.$L";

    final ParameterizedTypeName fieldTypeName = ParameterizedTypeName.get(
        ClassName.get(packageName, CLASS_NAME),
        TypeUtils.getTypeName(typeElement),
        typeName
    );

    builder.addField(
        FieldSpec.builder(
            fieldTypeName,
            SourceCodeUtils.normalizeName(TypeUtils.getName(element)),
            Modifier.PUBLIC, Modifier.FINAL, Modifier.STATIC
        )
        .initializer(
            SourceTextUtils.lines(
                "new $T() {",
                    "@Override",
                    "public $T apply(final $T input) {",
                    "return " + operation + ";",
                    "}",
                "}"
            ),
            fieldTypeName,
            typeName, typeElement,
            caller
        )
        .build()
    );
}
 
Example #26
Source File: JSupplierCodeGenerator.java    From jackdaw with Apache License 2.0 5 votes vote down vote up
@Override
protected final void generateBody(
    final CodeGeneratorContext context, final Builder builder
) throws Exception {
    final TypeElement typeElement = context.getTypeElement();
    SourceCodeUtils.processSimpleMethodsAndVariables(
        builder, typeElement, JSupplier.class,
        new AnnotatedElementCallback<JSupplier>() {
            @Override
            public void process(final Element element, final JSupplier annotation) {
                addFunction(builder, typeElement, element, annotation);
            }
        }
    );
}
 
Example #27
Source File: ArgumentBuilderModel.java    From Akatsuki with Apache License 2.0 5 votes vote down vote up
public Optional<TypeSpec> build() {
	Optional<SourceClassModel> superModel = classModel()
			.directSuperModelWithAnnotation(Arg.class);
	if (!classModel().containsAnyAnnotation(Arg.class) && !superModel.isPresent())
		return Optional.empty();
	return createBuilderForModel(classModel(), superModel).map(Builder::build);
}
 
Example #28
Source File: BindSharedPreferencesBuilder.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * Generate constructor.
 * 
 * @param entity
 *
 * @param sharedPreferenceName
 *            the shared preference name
 * @param beanClassName
 *            the bean class name
 */
private static void generateConstructor(PrefsEntity entity, String sharedPreferenceName, String beanClassName) {
	MethodSpec.Builder method = MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE).addJavadoc("constructor\n");

	method.addStatement("createPrefs()");

	if (entity.isImmutablePojo()) {
		ImmutableUtility.generateImmutableVariableInit(entity, method);
		ImmutableUtility.generateImmutableEntityCreation(entity, method, "defaultBean", false);
	} else {
		method.addStatement("defaultBean=new $T()", className(beanClassName));
	}

	builder.addMethod(method.build());
}
 
Example #29
Source File: BindSharedPreferencesBuilder.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * Generate reset method.
 *
 * @param entity
 *            the entity
 */
private static void generateResetMethod(PrefsEntity entity) {
	// write method
	MethodSpec.Builder method = MethodSpec.methodBuilder("reset").addModifiers(Modifier.PUBLIC).addJavadoc("reset shared preferences\n").returns(Void.TYPE);

	if (entity.isImmutablePojo()) {
		ImmutableUtility.generateImmutableVariableInit(entity, method);
		ImmutableUtility.generateImmutableEntityCreation(entity, method, "bean", true);
	} else {
		method.addStatement("$T bean=new $T()", entity.getElement(), entity.getElement());
	}

	method.addStatement("write(bean)");
	builder.addMethod(method.build());
}
 
Example #30
Source File: JavadocUtility.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * Generate javadoc generated by.
 *
 * @param builder
 *            the builder
 */
public static void generateJavadocGeneratedBy(Builder builder) {
	if (!BindDataSourceSubProcessor.JUNIT_TEST_MODE) {
		builder.addJavadoc("<p><strong>This class is generated by Kripton Annotation Processor - v. $L</strong></p>\n", Version.getVersion());
		builder.addJavadoc("<p><strong>Generation-time: $L</strong></p>\n\n", (new Date()).toString());
	}
}