com.squareup.javapoet.MethodSpec.Builder Java Examples

The following examples show how to use com.squareup.javapoet.MethodSpec.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: AutoMatterProcessor.java    From auto-matter with Apache License 2.0 6 votes vote down vote up
private MethodSpec valueDefaultToString(final Descriptor d) {
  MethodSpec.Builder toString = MethodSpec.methodBuilder("toString")
      .addAnnotation(Override.class)
      .addModifiers(PUBLIC)
      .returns(ClassName.get(String.class));

  toString.addCode("return \"$L{\" +\n", d.valueTypeName());

  for (int i = 0; i < d.fields().size(); i++) {
    final ExecutableElement field = d.fields().get(i);
    final String comma = (i == 0) ? "" : ", ";
    final String name = fieldName(field);

    if (field.getReturnType().getKind() == ARRAY) {
      toString.addCode("\"$L$L=\" + $T.toString($L) +\n", comma, name, ClassName.get(Arrays.class), name);
    } else {
      toString.addCode("\"$L$L=\" + $L +\n", comma, name, name);
    }
  }

  toString.addStatement("'}'");
  return toString.build();
}
 
Example #2
Source File: AutoMatterProcessor.java    From auto-matter with Apache License 2.0 6 votes vote down vote up
private MethodSpec valueEquals(final Descriptor d) throws AutoMatterProcessorException {
  MethodSpec.Builder equals = MethodSpec.methodBuilder("equals")
      .addAnnotation(Override.class)
      .addModifiers(PUBLIC)
      .addParameter(ClassName.get(Object.class), "o")
      .returns(TypeName.BOOLEAN);

  equals.beginControlFlow("if (this == o)")
      .addStatement("return true")
      .endControlFlow();

  equals.beginControlFlow("if (!(o instanceof $T))", rawValueType(d))
      .addStatement("return false")
      .endControlFlow();

  if (!d.fields().isEmpty()) {
    equals.addStatement("final $T that = ($T) o", unboundedValueType(d), unboundedValueType(d));

    for (ExecutableElement field : d.fields()) {
      equals.addCode(fieldNotEqualCheck(field));
    }
  }

  return equals.addStatement("return true").build();
}
 
Example #3
Source File: AbstractNumberBindTransform.java    From kripton with Apache License 2.0 6 votes vote down vote up
@Override
public void generateParseOnJackson(BindTypeContext context, Builder methodBuilder, String parserName, TypeName beanClass, String beanName, BindProperty property) {
	if (property.isNullable()) {
		methodBuilder.beginControlFlow("if ($L.currentToken()!=$T.VALUE_NULL)", parserName, JsonToken.class);
	}

	if (property.hasTypeAdapter()) {
		methodBuilder.addStatement(setter(beanClass, beanName, property, PRE_TYPE_ADAPTER_TO_JAVA + "$T.read($L.getText())" + POST_TYPE_ADAPTER), TypeAdapterUtils.class,
				TypeUtility.typeName(property.typeAdapter.adapterClazz), NUMBER_UTIL_CLAZZ, parserName);
	} else {
		methodBuilder.addStatement(setter(beanClass, beanName, property, "$T.read($L.getText())"), NUMBER_UTIL_CLAZZ, parserName);
	}

	if (property.isNullable()) {
		methodBuilder.endControlFlow();
	}

}
 
Example #4
Source File: ObjectBindTransform.java    From kripton with Apache License 2.0 6 votes vote down vote up
@Override
public void generateParseOnJacksonAsString(BindTypeContext context, MethodSpec.Builder methodBuilder, String parserName, TypeName beanClass, String beanName, BindProperty property) {
	// TODO QUA
	// TypeName typeName = resolveTypeName(property.getParent(),
	// property.getPropertyType().getTypeName());
	TypeName typeName = property.getPropertyType().getTypeName();

	String bindName = context.getBindMapperName(context, typeName);

	if (property.isNullable()) {
		methodBuilder.beginControlFlow("if ($L.currentToken()==$T.START_OBJECT || $L.currentToken()==$T.VALUE_STRING)", parserName, JsonToken.class, parserName, JsonToken.class);
	}
	methodBuilder.addStatement(setter(beanClass, beanName, property, "$L.parseOnJacksonAsString(jacksonParser)"), bindName);
	if (property.isNullable()) {
		methodBuilder.endControlFlow();
	}
}
 
Example #5
Source File: AutoMatterProcessor.java    From auto-matter with Apache License 2.0 6 votes vote down vote up
private MethodSpec collectionAdder(final Descriptor d, final ExecutableElement field) {
  final String fieldName = fieldName(field);
  final String singular = singular(fieldName);
  if (singular == null || singular.isEmpty()) {
    return null;
  }

  final String appendMethodName = "add" + capitalizeFirstLetter(singular);
  final TypeName itemType = genericArgument(d, field, 0);
  MethodSpec.Builder adder = MethodSpec.methodBuilder(appendMethodName)
      .addModifiers(PUBLIC)
      .addParameter(itemType, singular)
      .returns(builderType(d));

  if (shouldEnforceNonNull(field)) {
    assertNotNull(adder, singular);
  }
  lazyCollectionInitialization(d, adder, field);

  adder.addStatement("$L.add($L)", fieldName, singular);
  return adder.addStatement("return this").build();
}
 
Example #6
Source File: ResourceMethodExtensionPlugin.java    From raml-module-builder with Apache License 2.0 6 votes vote down vote up
private void addRoutingContext(Builder methodSpec, GMethod method) {
  //add routingContext param if indicated in generate runner plugin in pom
  String endpoints2addRoutingContext = PomReader.INSTANCE.getProps().getProperty("generate_routing_context");
  if(endpoints2addRoutingContext != null){
    String []rcFuncs = endpoints2addRoutingContext.split(",");
    for (int i = 0; i < rcFuncs.length; i++) {
      try {
        if(rcFuncs[i].equalsIgnoreCase(method.resource().resourcePath())){
          methodSpec.addParameter(io.vertx.ext.web.RoutingContext.class, "routingContext");
        }
      } catch (Exception e) {
        log.error(e.getMessage(), e);
      }
    }
  }
}
 
Example #7
Source File: TypeUtility.java    From kripton with Apache License 2.0 6 votes vote down vote up
/**
 * generate end string to translate in code to used in content value or parameter need to be converted in string through String.valueOf
 *
 * @param methodBuilder
 *            the method builder
 * @param typeMirror
 *            the type mirror
 */
public static void endStringConversion(Builder methodBuilder, TypeName typeMirror) {
	SQLTransform transform = SQLTransformer.lookup(typeMirror);

	switch (transform.getColumnType()) {
	case TEXT:
		return;
	case BLOB:
		methodBuilder.addCode(",$T.UTF_8)", StandardCharsets.class);
		break;
	case INTEGER:
	case REAL:
		methodBuilder.addCode(")");
		break;
	default:
		break;
	}
}
 
Example #8
Source File: ResourceMethodExtensionPlugin.java    From raml-module-builder with Apache License 2.0 6 votes vote down vote up
private MethodSpec.Builder cloneMethodWithoutParams(Builder methodSpec){
  MethodSpec spec = methodSpec.build();
  MethodSpec.Builder newBuilder = MethodSpec.methodBuilder(methodSpec.build().name);
  newBuilder.addAnnotations(spec.annotations);
  newBuilder.addCode(spec.code);
  newBuilder.addExceptions(spec.exceptions);
  newBuilder.addTypeVariables(spec.typeVariables);
  newBuilder.addModifiers(spec.modifiers);
  newBuilder.returns(spec.returnType);
  if(spec.defaultValue != null){
    newBuilder.defaultValue(spec.defaultValue);
  }
  newBuilder.varargs(spec.varargs);
  newBuilder.addCode(spec.javadoc);
  return newBuilder;
}
 
Example #9
Source File: AutoMatterProcessor.java    From auto-matter with Apache License 2.0 6 votes vote down vote up
private MethodSpec collectionVarargSetter(final Descriptor d, final ExecutableElement field) {
  String fieldName = fieldName(field);
  TypeName itemType = genericArgument(d, 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();
}
 
Example #10
Source File: SensorAnnotationsFileBuilder.java    From SensorAnnotations with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the implementation of {@code SensorEventListener#onSensorChanged(SensorEvent)} which
 * calls the annotated method on our target class.
 *
 * @param annotatedMethod Method annotated with {@code OnSensorChanged}.
 * @return {@link MethodSpec} of {@code SensorEventListener#onSensorChanged(SensorEvent)}.
 */
@NonNull
private static MethodSpec createOnSensorChangedListenerMethod(
    @Nullable AnnotatedMethod annotatedMethod) {
    ParameterSpec sensorEventParameter = ParameterSpec.builder(SENSOR_EVENT, "event").build();
    Builder methodBuilder =
        getBaseMethodBuilder("onSensorChanged").addParameter(sensorEventParameter);

    if (annotatedMethod != null) {
        ExecutableElement sensorChangedExecutableElement =
            annotatedMethod.getExecutableElement();
        methodBuilder.addStatement("target.$L($N)",
            sensorChangedExecutableElement.getSimpleName(), sensorEventParameter);
    }

    return methodBuilder.build();
}
 
Example #11
Source File: ToStringMethod.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
static MethodSpec generate(TypeElement element) {
  ClassName.get(element).reflectionName();
  Builder result =
      MethodSpec.methodBuilder("toString")
          .addModifiers(Modifier.PUBLIC)
          .returns(String.class)
          .addAnnotation(Override.class)
          .addCode(
              CodeBlock.builder()
                  .add(
                      "StringBuilder sb = new StringBuilder(\"@$L\");\n",
                      ClassName.get(element).reflectionName().replace('$', '.'))
                  .build());
  List<ExecutableElement> methods = ElementFilter.methodsIn(element.getEnclosedElements());
  if (!methods.isEmpty()) {
    result.addCode("sb.append('(');\n");
  }
  for (ExecutableElement method : methods) {
    result.addCode("sb.append(\"$1L=\").append($1L);\n", method.getSimpleName());
  }
  if (!methods.isEmpty()) {
    result.addCode("sb.append(')');\n");
  }
  result.addCode("return sb.toString();\n");
  return result.build();
}
 
Example #12
Source File: StringBindTransform.java    From kripton with Apache License 2.0 6 votes vote down vote up
@Override
public void generateParseOnJacksonAsString(BindTypeContext context, MethodSpec.Builder methodBuilder, String parserName, TypeName beanClass, String beanName, BindProperty property) {
	methodBuilder.beginControlFlow("if ($L.currentToken()!=$T.VALUE_NULL)", parserName, JsonToken.class);
	
	if (property.hasTypeAdapter())
	{
		// there's an type adapter
		methodBuilder.addCode("// using type adapter $L\n", property.typeAdapter.adapterClazz);
	
		methodBuilder.addStatement(setter(beanClass, beanName, property, PRE_TYPE_ADAPTER_TO_JAVA+"$L.getText()"+POST_TYPE_ADAPTER), TypeAdapterUtils.class, typeName(property.typeAdapter.adapterClazz),parserName);
	
	} else {
		// there's no type adapter
		methodBuilder.addStatement(setter(beanClass, beanName, property, "$L.getText()"), parserName);
	}
	
	methodBuilder.endControlFlow();
}
 
Example #13
Source File: CodeBuilderUtility.java    From kripton with Apache License 2.0 6 votes vote down vote up
/**
 * Generate code necessary to put bean properties in content values map.
 * Return primary key
 *
 * @param methodBuilder
 *            used to code generation
 * @param method
 *            the method
 * @param annotationClazz
 *            the annotation clazz
 * @return primary key.
 */
public static List<SQLProperty> extractUsedProperties(Builder methodBuilder, SQLiteModelMethod method, Class<? extends Annotation> annotationClazz) {
	SQLiteEntity entity = method.getEntity();
	List<SQLProperty> listPropertyInContentValue = new ArrayList<SQLProperty>();

	Set<String> foundColumns = JQLChecker.getInstance().extractColumnsToInsertOrUpdate(method, method.jql.value, entity);

	// for each property in entity except primaryKey and excluded properties
	for (SQLProperty item : entity.getCollection()) {
		if (foundColumns.size() > 0 && !foundColumns.contains(item.getName())) {
			continue;
		}

		// add property to list of used properties
		listPropertyInContentValue.add(item);
	}

	return listPropertyInContentValue;

}
 
Example #14
Source File: WrappedBindTransform.java    From kripton with Apache License 2.0 6 votes vote down vote up
@Override
public void generateParseOnJacksonAsString(BindTypeContext context, MethodSpec.Builder methodBuilder, String parserName, TypeName beanClass, String beanName, BindProperty property) {
	if (property.isNullable()) {
		methodBuilder.beginControlFlow("if ($L.currentToken()!=$T.VALUE_NULL)", parserName, JsonToken.class);
	}

	if (property.hasTypeAdapter()) {
		methodBuilder.addStatement(setter(beanClass, beanName, property, PRE_TYPE_ADAPTER_TO_JAVA + "$T.read($L.getText())" + POST_TYPE_ADAPTER), TypeAdapterUtils.class,
				TypeUtility.typeName(property.typeAdapter.adapterClazz), utilClazz, parserName);
	} else {
		methodBuilder.addStatement(setter(beanClass, beanName, property, "$T.read($L.getText())"), utilClazz, parserName);
	}

	if (property.isNullable()) {
		methodBuilder.endControlFlow();
	}
}
 
Example #15
Source File: AbstractNumberPrefsTransform.java    From kripton with Apache License 2.0 6 votes vote down vote up
@Override
public void generateWriteProperty(Builder methodBuilder, String editorName, TypeName beanClass, String beanName, PrefsProperty property) {
	if (beanClass!=null)
	{
		methodBuilder.addCode("if ($L!=null) ", getter(beanName, beanClass, property));
			methodBuilder.addCode("$L.putString($S,$L.$L() );", editorName, property.getPreferenceKey(), getter(beanName, beanClass, property), METHOD_CONVERSION);			
		methodBuilder.addCode(" else ");
			methodBuilder.addCode("$L.putString($S, null);", editorName, property.getPreferenceKey());

	} else {
		methodBuilder.addCode("if ($L!=null) ", beanName);
			methodBuilder.addCode("$L.putString($S,$L.$L());", editorName, property.getPreferenceKey(), beanName, METHOD_CONVERSION);			
		methodBuilder.addCode(" else ");
			methodBuilder.addCode("$L.remove($S);", editorName, property.getPreferenceKey());
	}
		
}
 
Example #16
Source File: AutoMatterProcessor.java    From auto-matter with Apache License 2.0 6 votes vote down vote up
private MethodSpec optionalSetter(final Descriptor d, final ExecutableElement field) {
  String fieldName = fieldName(field);
  TypeName valueType = genericArgument(d, field, 0);
  ClassName optionalType = ClassName.bestGuess(optionalType(field));
  TypeName parameterType = ParameterizedTypeName.get(optionalType, subtypeOf(valueType));

  AnnotationSpec suppressUncheckedAnnotation = AnnotationSpec.builder(SuppressWarnings.class)
      .addMember("value", "$S", "unchecked")
      .build();

  MethodSpec.Builder setter = MethodSpec.methodBuilder(fieldName)
      .addAnnotation(suppressUncheckedAnnotation)
      .addModifiers(PUBLIC)
      .addParameter(parameterType, fieldName)
      .returns(builderType(d));

  if (shouldEnforceNonNull(field)) {
    assertNotNull(setter, fieldName);
  }

  setter.addStatement("this.$N = ($T)$N", fieldName, fieldType(d, field), fieldName);

  return setter.addStatement("return this").build();
}
 
Example #17
Source File: ImmutableUtility.java    From kripton with Apache License 2.0 6 votes vote down vote up
/**
 * used for example for dao select result
 * 
 * @param entity
 * @param methodBuilder
 * @param name
 * @param typeName
 */
public static void generateImmutableCollectionIfPossible(ModelClass<?> entity, Builder methodBuilder, String name,
		TypeName typeName) {
	if (TypeUtility.isList(typeName)
			&& ((ParameterizedTypeName) typeName).rawType.equals(ClassName.get(List.class))) {
		methodBuilder.addCode("($L==null ? null : $T.unmodifiableList($L))", name, Collections.class, name);
	} else if (TypeUtility.isSet(typeName)
			&& ((ParameterizedTypeName) typeName).rawType.equals(ClassName.get(SortedSet.class))) {
		methodBuilder.addCode("($L==null ? null : $T.unmodifiableSortedSet($L))", name, Collections.class, name);
	} else if (TypeUtility.isSet(typeName)
			&& ((ParameterizedTypeName) typeName).rawType.equals(ClassName.get(Set.class))) {
		methodBuilder.addCode("($L==null ? null : $T.unmodifiableSet($L))", name, Collections.class, name);
	} else if (TypeUtility.isMap(typeName)
			&& ((ParameterizedTypeName) typeName).rawType.equals(ClassName.get(SortedMap.class))) {
		methodBuilder.addCode("($L==null ? null : $T.unmodifiableSortedMap($L))", name, Collections.class, name);
	} else if (TypeUtility.isMap(typeName)
			&& ((ParameterizedTypeName) typeName).rawType.equals(ClassName.get(Map.class))) {
		methodBuilder.addCode("($L==null ? null : $T.unmodifiableMap($L))", name, Collections.class, name);
	} else {
		methodBuilder.addCode(name);
	}
}
 
Example #18
Source File: AutoMatterProcessor.java    From auto-matter with Apache License 2.0 5 votes vote down vote up
private MethodSpec valueToBuilder(final Descriptor d) {
  MethodSpec.Builder toBuilder = MethodSpec.methodBuilder("builder")
      .addModifiers(PUBLIC)
      .returns(builderType(d))
      .addStatement("return new $T(this)", builderType(d));

  // Always emit toBuilder, but only annotate it with @Override if the target asked for it.
  if (d.hasToBuilder()) {
    toBuilder.addAnnotation(Override.class);
  }

  return toBuilder.build();
}
 
Example #19
Source File: ByteArrayBindTransform.java    From kripton with Apache License 2.0 5 votes vote down vote up
@Override
public void generateSerializeOnJackson(BindTypeContext context, MethodSpec.Builder methodBuilder, String serializerName, TypeName beanClass, String beanName, BindProperty property) {
	if (property.isNullable()) {
		methodBuilder.beginControlFlow("if ($L!=null) ", getter(beanName, beanClass, property));
	}

	if (property.isProperty()) {
		methodBuilder.addStatement("fieldCount++");
	}

	if (property.hasTypeAdapter()) {
		// in a collection we need to insert only value, not field typeName
		if (property.isInCollection()) {
			methodBuilder.addStatement("$L.writeBinary(" + PRE_TYPE_ADAPTER_TO_DATA + "$L" + POST_TYPE_ADAPTER + ")", serializerName, TypeAdapterUtils.class,
					TypeUtility.typeName(property.typeAdapter.adapterClazz), getter(beanName, beanClass, property));
		} else {
			methodBuilder.addStatement("$L.writeBinaryField($S, " + PRE_TYPE_ADAPTER_TO_DATA + "$L" + POST_TYPE_ADAPTER + ")", serializerName, property.label, TypeAdapterUtils.class,
					TypeUtility.typeName(property.typeAdapter.adapterClazz), getter(beanName, beanClass, property));
		}
	} else {
		// in a collection we need to insert only value, not field typeName
		if (property.isInCollection()) {
			methodBuilder.addStatement("$L.writeBinary($L)", serializerName, getter(beanName, beanClass, property));
		} else {
			methodBuilder.addStatement("$L.writeBinaryField($S, $L)", serializerName, property.label, getter(beanName, beanClass, property));
		}

	}

	if (property.isNullable()) {
		methodBuilder.endControlFlow();
	}
}
 
Example #20
Source File: TypeAdapterAwareSQLTransform.java    From kripton with Apache License 2.0 5 votes vote down vote up
@Override
public void generateWriteProperty2WhereCondition(Builder methodBuilder, String beanName, TypeName beanClass, ModelProperty property) {
	if (property != null && property.hasTypeAdapter()) {
		methodBuilder.addCode(WRITE_COSTANT+PRE_TYPE_ADAPTER_TO_STRING+ "$L" + POST_TYPE_ADAPTER, SQLTypeAdapterUtils.class, TypeUtility.typeName(property.typeAdapter.adapterClazz),
				getter(beanName, beanClass, property));
	} else {
		methodBuilder.addCode(WRITE_COSTANT+"$L", getter(beanName, beanClass, property));
	}
}
 
Example #21
Source File: DoublePrefsTransform.java    From kripton with Apache License 2.0 5 votes vote down vote up
@Override
public void generateWriteProperty(Builder methodBuilder, String editorName, TypeName beanClass, String beanName, PrefsProperty property) {
	if (nullable) {
		methodBuilder.beginControlFlow("if ($L!=null) ", getter(beanName, beanClass, property));
	}
	methodBuilder.addStatement("$L.putString($S,String.valueOf($L))", editorName, property.getPreferenceKey(), getter(beanName, beanClass, property));
	if (nullable) {
		methodBuilder.nextControlFlow("else");
		methodBuilder.addStatement("$L.remove($S)", editorName, property.getName());
		methodBuilder.endControlFlow();
		
	}

}
 
Example #22
Source File: AutoMatterProcessor.java    From auto-matter with Apache License 2.0 5 votes vote down vote up
private CodeBlock fieldNotEqualCheck(final ExecutableElement field) throws AutoMatterProcessorException {
  final String name = fieldName(field);
  final CodeBlock.Builder result = CodeBlock.builder();
  final TypeMirror returnType = field.getReturnType();
  switch (returnType.getKind()) {
    case LONG:
    case INT:
    case BOOLEAN:
    case BYTE:
    case SHORT:
    case CHAR:
      result.beginControlFlow("if ($L != that.$L())", name, name);
      break;
    case FLOAT:
    case DOUBLE:
      final TypeName boxed = ClassName.get(returnType).box();
      result.beginControlFlow("if ($T.compare($L, that.$L()) != 0)", boxed, name, name);
      break;
    case ARRAY:
      result.beginControlFlow("if (!$T.equals($L, that.$L()))", ClassName.get(Arrays.class), name, name);
      break;
    case TYPEVAR:
    case DECLARED:
    case ERROR:
      result.beginControlFlow(
          "if ($L != null ? !$L.equals(that.$L()) : that.$L() != null)",
          name, name, name, name);
      break;
    default:
      throw fail("Unsupported type: " + returnType, field);
  }

  result.addStatement("return false").endControlFlow();
  return result.build();
}
 
Example #23
Source File: AutoMatterProcessor.java    From auto-matter with Apache License 2.0 5 votes vote down vote up
private MethodSpec valueCustomToString(ExecutableElement toStringMethod, Descriptor d) {
  MethodSpec.Builder toString = MethodSpec.methodBuilder("toString")
      .addAnnotation(Override.class)
      .addModifiers(PUBLIC)
      .returns(ClassName.get(String.class));
  if (toStringMethod.getModifiers().contains(STATIC)) {
    toString.addCode("return $L.$N(this);\n", d.valueTypeName(), toStringMethod.getSimpleName());
  } else if (toStringMethod.getModifiers().contains(DEFAULT)) {
    toString.addCode("return $N();\n", toStringMethod.getSimpleName());
  }
  return toString.build();
}
 
Example #24
Source File: EnumPrefsTransform.java    From kripton with Apache License 2.0 5 votes vote down vote up
@Override
public void generateWriteProperty(Builder methodBuilder, String editorName, TypeName beanClass, String beanName, PrefsProperty property) {
	methodBuilder.beginControlFlow("if ($L!=null) ", getter(beanName, beanClass, property));
	methodBuilder.addStatement("$L.putString($S,$L.toString() )", editorName, property.getPreferenceKey(), getter(beanName, beanClass, property));		
	methodBuilder.nextControlFlow("else");
	methodBuilder.addStatement("$L.remove($S)", editorName, property.getName());
	methodBuilder.endControlFlow();

}
 
Example #25
Source File: ObjectBindTransform.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * Generate serialize internal.
 *
 * @param context the context
 * @param methodBuilder the method builder
 * @param serializerName the serializer name
 * @param beanClass the bean class
 * @param beanName the bean name
 * @param property the property
 * @param onString the on string
 */
void generateSerializeInternal(BindTypeContext context, MethodSpec.Builder methodBuilder, String serializerName, TypeName beanClass, String beanName, BindProperty property, boolean onString) {
	TypeName typeName = property.getPropertyType().getTypeName();

	String bindName = context.getBindMapperName(context, typeName);

	// @formatter:off
	if (property.isNullable()) {
		methodBuilder.beginControlFlow("if ($L!=null) ", getter(beanName, beanClass, property));
	}

	if (property.isProperty()) {
		methodBuilder.addStatement("fieldCount++");
	}

	if (!property.isInCollection()) {
		methodBuilder.addStatement("$L.writeFieldName($S)", serializerName, property.label);
	}

	if (onString) {
		methodBuilder.beginControlFlow("if ($L.serializeOnJacksonAsString($L, jacksonSerializer)==0)", bindName,
				getter(beanName, beanClass, property));
		// KRITPON-38: in a collection, for null object we write
		methodBuilder.addStatement("$L.writeNullField($S)", serializerName, property.label);
		methodBuilder.endControlFlow();
	} else {
		methodBuilder.addStatement("$L.serializeOnJackson($L, jacksonSerializer)", bindName, getter(beanName, beanClass, property));
	}

	if (property.isNullable()) {
		methodBuilder.endControlFlow();
	}
	// @formatter:on
}
 
Example #26
Source File: WrappedBindTransform.java    From kripton with Apache License 2.0 5 votes vote down vote up
@Override
public void generateParseOnXml(BindTypeContext context, MethodSpec.Builder methodBuilder, String parserName, TypeName beanClass, String beanName, BindProperty property) {
	XmlType xmlType = property.xmlInfo.xmlType;

	if (property.hasTypeAdapter()) {
		switch (xmlType) {
		case ATTRIBUTE:
			methodBuilder.addStatement(setter(beanClass, beanName, property, PRE_TYPE_ADAPTER_TO_JAVA + "$T.read($L.getAttributeValue(attributeIndex))" + POST_TYPE_ADAPTER),
					TypeAdapterUtils.class, TypeUtility.typeName(property.typeAdapter.adapterClazz), utilClazz, parserName);
			break;
		case TAG:
			methodBuilder.addStatement(setter(beanClass, beanName, property, PRE_TYPE_ADAPTER_TO_JAVA + "$T.read($T.unescapeXml($L.getElementText()))" + POST_TYPE_ADAPTER), TypeAdapterUtils.class,
					TypeUtility.typeName(property.typeAdapter.adapterClazz), utilClazz, StringEscapeUtils.class, parserName);
			break;
		case VALUE:
		case VALUE_CDATA:
			methodBuilder.addStatement(setter(beanClass, beanName, property, PRE_TYPE_ADAPTER_TO_JAVA + "$T.read($T.unescapeXml($L.getText()))" + POST_TYPE_ADAPTER), TypeAdapterUtils.class,
					TypeUtility.typeName(property.typeAdapter.adapterClazz), utilClazz, StringEscapeUtils.class, parserName);
			break;			
		}
	} else {
		switch (xmlType) {
		case ATTRIBUTE:
			methodBuilder.addStatement(setter(beanClass, beanName, property, "$T.read($L.getAttributeValue(attributeIndex))"), utilClazz, parserName);
			break;
		case TAG:
			methodBuilder.addStatement(setter(beanClass, beanName, property, "$T.read($T.unescapeXml($L.getElementText()))"), utilClazz, StringEscapeUtils.class, parserName);
			break;
		case VALUE:
		case VALUE_CDATA:
			methodBuilder.addStatement(setter(beanClass, beanName, property, "$T.read($T.unescapeXml($L.getText()))"), utilClazz, StringEscapeUtils.class, parserName);
			break;
		default:
			break;
		}
	}

}
 
Example #27
Source File: AbstractNumberBindTransform.java    From kripton with Apache License 2.0 5 votes vote down vote up
@Override
public void generateParseOnXml(BindTypeContext context, MethodSpec.Builder methodBuilder, String parserName, TypeName beanClass, String beanName, BindProperty property) {
	XmlType xmlType = property.xmlInfo.xmlType;

	if (property.hasTypeAdapter()) {
		switch (xmlType) {
		case ATTRIBUTE:
			methodBuilder.addStatement(setter(beanClass, beanName, property, PRE_TYPE_ADAPTER_TO_JAVA + "$L.getAttributeAs$L(attributeIndex)" + POST_TYPE_ADAPTER), TypeAdapterUtils.class,
					TypeUtility.typeName(property.typeAdapter.adapterClazz), parserName, ATTRIBUTE_METHOD);
			break;
		case TAG:
			methodBuilder.addStatement(setter(beanClass, beanName, property, PRE_TYPE_ADAPTER_TO_JAVA + "$T.read($T.unescapeXml($L.getElementText()))" + POST_TYPE_ADAPTER), TypeAdapterUtils.class,
					TypeUtility.typeName(property.typeAdapter.adapterClazz), NUMBER_UTIL_CLAZZ, StringEscapeUtils.class, parserName);
			break;
		case VALUE:
		case VALUE_CDATA:
			methodBuilder.addStatement(setter(beanClass, beanName, property, PRE_TYPE_ADAPTER_TO_JAVA + "$T.read($T.unescapeXml($L.getText()))" + POST_TYPE_ADAPTER), TypeAdapterUtils.class,
					TypeUtility.typeName(property.typeAdapter.adapterClazz), NUMBER_UTIL_CLAZZ, StringEscapeUtils.class, parserName);
			break;
		}
	} else {
		switch (xmlType) {
		case ATTRIBUTE:
			methodBuilder.addStatement(setter(beanClass, beanName, property, "$L.getAttributeAs$L(attributeIndex)"), parserName, ATTRIBUTE_METHOD);
			break;
		case TAG:
			methodBuilder.addStatement(setter(beanClass, beanName, property, "$T.read($T.unescapeXml($L.getElementText()))"), NUMBER_UTIL_CLAZZ, StringEscapeUtils.class, parserName);
			break;
		case VALUE:
		case VALUE_CDATA:
			methodBuilder.addStatement(setter(beanClass, beanName, property, "$T.read($T.unescapeXml($L.getText()))"), NUMBER_UTIL_CLAZZ, StringEscapeUtils.class, parserName);
			break;
		}
	}

}
 
Example #28
Source File: ImmutableUtility.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param entity
 * @param methodBuilder
 * @param entityName
 */
public static void generateImmutableVariableCopyFromEntity(ModelClass<?> entity, Builder methodBuilder,
		String entityName) {
	methodBuilder.addComment(
			"immutable object: initialize temporary variables for properties with entity propertiy values");
	for (Pair<String, TypeName> property : entity.getImmutableConstructors()) {
		ModelProperty item = entity.findImmutablePropertyByName(property.value0);
		AssertKripton.assertTrue(item != null, "Can not found property '%s' (type %s) in class '%s'",
				property.value0, property.value1, entity.getName());

		methodBuilder.addCode("$L$L=$L.$L;\n", IMMUTABLE_PREFIX, property.value0, entityName,
				PropertyUtility.getter(item));
	}
}
 
Example #29
Source File: AbstractNumberBindTransform.java    From kripton with Apache License 2.0 5 votes vote down vote up
@Override
public void generateSerializeOnJackson(BindTypeContext context, MethodSpec.Builder methodBuilder, String serializerName, TypeName beanClass, String beanName, BindProperty property) {
	if (property.isNullable()) {
		methodBuilder.beginControlFlow("if ($L!=null) ", getter(beanName, beanClass, property));
	}

	if (property.isProperty()) {
		methodBuilder.addStatement("fieldCount++");
	}

	if (property.hasTypeAdapter()) {
		// if in collection, we need to write only the value
		if (property.isInCollection()) {
			methodBuilder.addStatement("$L.writeString($T.write(" + PRE_TYPE_ADAPTER_TO_DATA + "$L" + POST_TYPE_ADAPTER + "))", serializerName, NUMBER_UTIL_CLAZZ, TypeAdapterUtils.class,
					TypeUtility.typeName(property.typeAdapter.adapterClazz), getter(beanName, beanClass, property));
		} else {
			methodBuilder.addStatement("$L.writeStringField($S, $T.write(" + PRE_TYPE_ADAPTER_TO_DATA + "$L" + POST_TYPE_ADAPTER + "))", serializerName, property.label, NUMBER_UTIL_CLAZZ,
					TypeAdapterUtils.class, TypeUtility.typeName(property.typeAdapter.adapterClazz), getter(beanName, beanClass, property));
		}
	} else {
		// if in collection, we need to write only the value
		if (property.isInCollection()) {
			methodBuilder.addStatement("$L.writeString($T.write($L))", serializerName, NUMBER_UTIL_CLAZZ, getter(beanName, beanClass, property));
		} else {
			methodBuilder.addStatement("$L.writeStringField($S, $T.write($L))", serializerName, property.label, NUMBER_UTIL_CLAZZ, getter(beanName, beanClass, property));
		}
	}

	if (property.isNullable()) {
		methodBuilder.endControlFlow();
	}
}
 
Example #30
Source File: DoublePrefsTransform.java    From kripton with Apache License 2.0 5 votes vote down vote up
@Override
public void generateReadProperty(Builder methodBuilder, String preferenceName, TypeName beanClass, String beanName, PrefsProperty property, boolean readAll, ReadType readType) {
	if (readAll) {
		methodBuilder.beginControlFlow("");
	}

	methodBuilder.addStatement("String temp=$L.getString($S, null)", preferenceName, property.getPreferenceKey());

	if (readAll) {
		methodBuilder.addCode(setter(beanClass, beanName, property) + (!property.isPublicField() && beanName!=null ? "(" : "="));
	} 
	
	switch (readType) {
	case NONE:
		break;
	case RETURN:
		methodBuilder.addCode("return ");
		break;
	case VALUE:
		methodBuilder.addCode("$T _value=", property.getPropertyType().getTypeName());
		break;
	}

	methodBuilder.addCode("($T.hasText(temp)) ? ", StringUtils.class);
	methodBuilder.addCode("$T.valueOf(temp)", Double.class);
	methodBuilder.addCode(": $L", getter(DEFAULT_BEAN_NAME, beanClass, property));

	if (readAll) {
		methodBuilder.addCode(!property.isPublicField() && beanName!=null ? ")" : "");
	}

	methodBuilder.addCode(";\n");

	if (readAll) {
		methodBuilder.endControlFlow();
	}
}