com.squareup.javapoet.CodeBlock Java Examples

The following examples show how to use com.squareup.javapoet.CodeBlock. 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: GsonDeserializer.java    From auto-value-bundle with MIT License 6 votes vote down vote up
@Override
public String deserializeUnknownParameterizedObject(
        String readFromBundle,
        ParameterizedTypeName parameterizedTypeName,
        VariableElement deserializerElement) {
    StringBuilder typeToken = new StringBuilder("new ")
            .append(TYPE_TOKEN_FULLY_QUALIFIED)
            .append("<")
            .append(parameterizedTypeName.rawType.simpleName())
            .append("<");
    for (TypeName typeName : parameterizedTypeName.typeArguments) {
        typeToken.append(deserializeParameterizedObject(typeName))
                .append(", ");
    }
    typeToken.deleteCharAt(typeToken.length() - 1);
    typeToken.deleteCharAt(typeToken.length() - 1);

    typeToken.append(">(){}.getType()");

    return CodeBlock.builder()
            .add("$L.$L($L, $L)", deserializerElement.getSimpleName().toString(), "fromJson", readFromBundle,
                    typeToken)
            .build()
            .toString();
}
 
Example #2
Source File: PaginationDocs.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs javadocs for the generated response classes in a paginated operation.
 * @param clientInterface A java poet {@link ClassName} type of the sync client interface
 */
public String getDocsForSyncResponseClass(ClassName clientInterface) {
    return CodeBlock.builder()
                    .add("<p>Represents the output for the {@link $T#$L($T)} operation which is a paginated operation."
                         + " This class is an iterable of {@link $T} that can be used to iterate through all the "
                         + "response pages of the operation.</p>",
                         clientInterface, getPaginatedMethodName(), requestType(), syncResponsePageType())
                    .add("<p>When the operation is called, an instance of this class is returned.  At this point, "
                         + "no service calls are made yet and so there is no guarantee that the request is valid. "
                         + "As you iterate through the iterable, SDK will start lazily loading response pages by making "
                         + "service calls until there are no pages left or your iteration stops. If there are errors in your "
                         + "request, you will see the failures only after you start iterating through the iterable.</p>")
                    .add(getSyncCodeSnippets())
                    .build()
                    .toString();
}
 
Example #3
Source File: MatcherGenerator.java    From litho with Apache License 2.0 6 votes vote down vote up
private static MethodSpec.Builder getMethodSpecBuilder(
    SpecModel specModel,
    final List<ParameterSpec> parameters,
    final CodeBlock codeBlock,
    final String name) {
  final MethodSpec.Builder builder =
      MethodSpec.methodBuilder(name)
          .addModifiers(Modifier.PUBLIC)
          .returns(getMatcherType(specModel))
          .addCode(codeBlock);

  for (final ParameterSpec param : parameters) {
    builder.addParameter(param);
  }

  builder.addStatement("return this");

  return builder;
}
 
Example #4
Source File: BindClass.java    From AndroidAll with Apache License 2.0 6 votes vote down vote up
private void addViewBinding(MethodSpec.Builder result, ViewBinding binding) {
    // Optimize the common case where there's a single binding directly to a field.
    //FieldViewBinding fieldBinding = bindings.getFieldBinding();
    CodeBlock.Builder builder = CodeBlock.builder()
            .add("target.$L = ", binding.getName());

    boolean requiresCast = requiresCast(binding.getType());
    if (!requiresCast) {
        builder.add("source.findViewById($L)", binding.getValue());
    } else {
        builder.add("$T.findViewByCast", UTILS);
        //builder.add(fieldBinding.isRequired() ? "RequiredView" : "OptionalView");
        //if (requiresCast) {
        //    builder.add("AsType");
        //}
        builder.add("(source, $L", binding.getValue());
        builder.add(", $T.class", binding.getRawType());
        builder.add(")");
    }
    result.addStatement("$L", builder.build());

}
 
Example #5
Source File: HashCodeMethod.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
static MethodSpec generate(TypeElement annotation) {
  MethodSpec.Builder hashCodeBuilder =
      MethodSpec.methodBuilder("hashCode")
          .addModifiers(Modifier.PUBLIC)
          .addAnnotation(Override.class)
          .returns(int.class);

  List<ExecutableElement> methods = ElementFilter.methodsIn(annotation.getEnclosedElements());
  if (methods.isEmpty()) {
    hashCodeBuilder.addCode("return 0;\n");
    return hashCodeBuilder.build();
  }

  CodeBlock.Builder code = CodeBlock.builder().add("return ");
  for (ExecutableElement method : methods) {
    code.add(
        "+ ($L ^ $L)\n",
        127 * method.getSimpleName().toString().hashCode(),
        hashExpression(method));
  }
  code.add(";\n");
  hashCodeBuilder.addCode(code.build());

  return hashCodeBuilder.build();
}
 
Example #6
Source File: MatcherGenerator.java    From litho with Apache License 2.0 6 votes vote down vote up
private static MethodSpec varArgBuilder(
    SpecModel specModel, final PropModel prop, final AnnotationSpec... extraAnnotations) {
  final ParameterizedTypeName parameterizedTypeName = (ParameterizedTypeName) prop.getTypeName();
  final TypeName singleParameterType = parameterizedTypeName.typeArguments.get(0);
  final String varArgName = prop.getVarArgsSingleName();

  final CodeBlock codeBlock =
      CodeBlock.builder()
          .beginControlFlow("if ($L == null)", varArgName)
          .addStatement("return this")
          .endControlFlow()
          .build();

  return getMethodSpecBuilder(
          specModel,
          Collections.singletonList(
              parameter(prop, singleParameterType, varArgName, extraAnnotations)),
          codeBlock,
          varArgName)
      .build();
}
 
Example #7
Source File: JavaFiler.java    From convalida with Apache License 2.0 6 votes vote down vote up
private static CodeBlock createCpfValidationCodeBlock(ValidationField field) {
    Element element = field.element;
    Class<Cpf> annotation = Cpf.class;
    boolean hasErrorMessageResId = element.getAnnotation(annotation).errorMessageResId() != -1;
    String errorMessage = element.getAnnotation(annotation).errorMessage();
    String block = "validatorSet.addValidator(new $T(target.$N, " +
            errorMessage(hasErrorMessageResId) +
            ", $L, $L))";

    return CodeBlock.builder()
            .addStatement(
                    block,
                    CPF_VALIDATOR,
                    field.name,
                    hasErrorMessageResId ? field.id.code : errorMessage,
                    field.autoDismiss,
                    field.element.getAnnotation(annotation).required()
            )
            .build();
}
 
Example #8
Source File: JavaFiler.java    From convalida with Apache License 2.0 6 votes vote down vote up
private static CodeBlock createPatternValidationCodeBlock(ValidationField field) {
    Element element = field.element;
    Class<Pattern> annotation = Pattern.class;
    boolean hasErrorMessageResId = element.getAnnotation(annotation).errorMessageResId() != -1;
    String errorMessage = element.getAnnotation(annotation).errorMessage();
    String block = "validatorSet.addValidator(new $T(target.$N, " +
            errorMessage(hasErrorMessageResId) +
            ", $S, $L, $L))";

    return CodeBlock.builder()
            .addStatement(
                    block,
                    PATTERN_VALIDATOR,
                    field.name,
                    hasErrorMessageResId ? field.id.code : errorMessage,
                    field.element.getAnnotation(annotation).pattern(),
                    field.autoDismiss,
                    field.element.getAnnotation(annotation).required()
            )
            .build();
}
 
Example #9
Source File: PaginationDocs.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs additional documentation on the client operation that is appended to the service documentation.
 *
 * TODO Add a link to our developer guide which will have more details and sample code. Write a blog post too.
 */
public String getDocsForSyncOperation() {
    return CodeBlock.builder()
                    .add("<p>This is a variant of {@link #$L($T)} operation. "
                         + "The return type is a custom iterable that can be used to iterate through all the pages. "
                         + "SDK will internally handle making service calls for you.\n</p>",
                         operationModel.getMethodName(), requestType())
                    .add("<p>\nWhen this operation is called, a custom iterable is returned but no service calls are "
                         + "made yet. So there is no guarantee that the request is valid. As you iterate "
                         + "through the iterable, SDK will start lazily loading response pages by making service calls until "
                         + "there are no pages left or your iteration stops. If there are errors in your request, you will "
                         + "see the failures only after you start iterating through the iterable.\n</p>")
                    .add(getSyncCodeSnippets())
                    .build()
                    .toString();
}
 
Example #10
Source File: MatcherGenerator.java    From litho with Apache License 2.0 6 votes vote down vote up
private static CodeBlock generateInjectedFieldExtractorBlock(
    FieldExtractorSpec fieldExtractorSpec) {
  final DependencyInjectionHelper diHelper =
      fieldExtractorSpec.specModel.getDependencyInjectionHelper();

  if (diHelper == null) {
    return CodeBlock.builder().build();
  }

  final String getterName =
      diHelper.generateTestingFieldAccessor(
              fieldExtractorSpec.specModel, new InjectPropModel(fieldExtractorSpec.propModel))
          .name;
  return CodeBlock.builder()
      .addStatement(
          "final $T $L = impl.$L()",
          fieldExtractorSpec.propModel.getTypeName(),
          fieldExtractorSpec.varName,
          getterName)
      .build();
}
 
Example #11
Source File: ClientClassUtils.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
static CodeBlock callApplySignerOverrideMethod(OperationModel opModel) {
    CodeBlock.Builder code = CodeBlock.builder();
    ShapeModel inputShape = opModel.getInputShape();

    if (inputShape.getRequestSignerClassFqcn() != null) {
        code.addStatement("$1L = applySignerOverride($1L, $2T.create())",
                          opModel.getInput().getVariableName(),
                          PoetUtils.classNameFromFqcn(inputShape.getRequestSignerClassFqcn()));
    } else if (opModel.hasEventStreamInput()) {
        code.addStatement("$1L = applySignerOverride($1L, $2T.create())",
                          opModel.getInput().getVariableName(), EventStreamAws4Signer.class);

    }

    return code.build();
}
 
Example #12
Source File: BuilderGenerator.java    From litho with Apache License 2.0 6 votes vote down vote up
private static MethodSpec varArgBuilderBuilder(
    SpecModel specModel, PropModel prop, int requiredIndex) {
  String varArgName = prop.getVarArgsSingleName();
  final ParameterizedTypeName varArgType = (ParameterizedTypeName) prop.getTypeName();
  final TypeName internalType = varArgType.typeArguments.get(0);
  CodeBlock codeBlock =
      CodeBlock.builder()
          .beginControlFlow("if ($L == null)", varArgName + "Builder")
          .addStatement("return this")
          .endControlFlow()
          .addStatement("$L($L.build())", varArgName, varArgName + "Builder")
          .build();
  TypeName builderParameterType =
      ParameterizedTypeName.get(
          ClassNames.COMPONENT_BUILDER,
          getBuilderGenericTypes(internalType, ClassNames.COMPONENT_BUILDER));
  return getMethodSpecBuilder(
          specModel,
          prop,
          requiredIndex,
          varArgName,
          Arrays.asList(parameter(prop, builderParameterType, varArgName + "Builder")),
          codeBlock)
      .build();
}
 
Example #13
Source File: ProtocolSpec.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
default CodeBlock streamingMarshallerCode(IntermediateModel model, OperationModel opModel, ClassName marshaller,
                                          String protocolFactory, boolean isAsync) {
    CodeBlock.Builder builder = CodeBlock
        .builder()
        .add("$T.builder().delegateMarshaller(new $T($L))",
             isAsync ? AsyncStreamingRequestMarshaller.class : StreamingRequestMarshaller.class,
             marshaller,
             protocolFactory)
        .add(".$L(requestBody)", isAsync ? "asyncRequestBody" : "requestBody");

    if (opModel.hasRequiresLengthInInput()) {
        builder.add(".requiresLength(true)");
    }

    if (AuthType.V4_UNSIGNED_BODY.equals(opModel.getAuthType())) {
        builder.add(".transferEncoding(true)");
    }

    if (model.getMetadata().supportsH2()) {
        builder.add(".useHttp2(true)");
    }

    builder.add(".build()");

    return builder.build();
}
 
Example #14
Source File: DefaultConfigProviderGenerator.java    From aircon with MIT License 6 votes vote down vote up
private Object createConfigValueValidationExpression(final Object value) {
	final List<CodeBlock> validationConditions = new ArrayList<>();

	final CodeBlock validationCondition = getValidationCondition(VAR_VALUE);
	if (validationCondition != null) {
		validationConditions.add(validationCondition);
	}

	if (mElement.hasValidator()) {
		validationConditions.add(createConfigAuxMethodCall(mElement.getValidator(), value));
	}

	if (validationConditions.isEmpty()) {
		return null;
	}

	final CodeBlock validationConditionCodeBlock = new CodeBlockBuilder().addAnd(validationConditions.toArray())
	                                                                     .build();

	return new CodeBlockBuilder().addConditionalExpression(validationConditionCodeBlock, value, VAR_DEFAULT_VALUE)
	                             .build();
}
 
Example #15
Source File: DeepLinkInterceptorProcessor.java    From OkDeepLink with Apache License 2.0 6 votes vote down vote up
private MethodSpec.Builder genePathInterceptorsBuilder(InterceptorElement interceptorElement) {
    CodeBlock.Builder builder = CodeBlock.builder();
    TypeName typeName = ParameterizedTypeName.get(ClassName.get(Map.class), ClassName.get(String.class), INTERCEPTOR);
    builder.add("$T result = ($T)joinPoint.proceed();\n", typeName, typeName);
    String path = interceptorElement.getPath();
    builder.add("result.put($S,new $T());\n",
            path,
            interceptorElement.getClassName());
    builder.add("return result;\n");
    return MethodSpec.methodBuilder("getPathInterceptors")
            .addModifiers(Modifier.PUBLIC)
            .addParameter(ProceedingJoinPoint.class, "joinPoint")
            .returns(typeName)
            .addException(Throwable.class)
            .addAnnotation(AnnotationSpec
                    .builder(Around.class)
                    .addMember("value", "$S", "execution(* " + PATH_INTERCEPTORS_METHOD_NAME + ")").build())
            .addCode(builder.build());
}
 
Example #16
Source File: MemberCopierSpec.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private MethodSpec builderCopyMethodForMap() {
    TypeName keyType = typeProvider.getTypeNameForSimpleType(memberModel.getMapModel().getKeyModel()
                                                                        .getVariable().getVariableType());
    ClassName valueParameter = poetExtensions.getModelClass(memberModel.getMapModel().getValueModel().getC2jShape());
    ClassName builderForParameter = valueParameter.nestedClass("Builder");
    TypeName parameterType =
        ParameterizedTypeName.get(ClassName.get(Map.class), keyType, WildcardTypeName.subtypeOf(builderForParameter));

    CodeBlock code =
        CodeBlock.builder()
                 .beginControlFlow("if ($N == null)", memberParamName())
                 .addStatement("return null")
                 .endControlFlow()
                 .addStatement("return $N($N.entrySet().stream().collect(toMap($T::getKey, e -> e.getValue().build())))",
                               serviceModelCopiers.copyMethodName(),
                               memberParamName(),
                               Map.Entry.class)
                 .build();

    return MethodSpec.methodBuilder(serviceModelCopiers.builderCopyMethodName())
                     .addModifiers(Modifier.STATIC)
                     .addParameter(parameterType, memberParamName())
                     .returns(typeProvider.fieldType(memberModel))
                     .addCode(code)
                     .build();
}
 
Example #17
Source File: JavaWriter.java    From lazythreetenbp with Apache License 2.0 6 votes vote down vote up
private FieldSpec regionId(Set<String> allRegionIds) {
    CodeBlock.Builder builder = CodeBlock.builder()
            .add("$T.asList(\n$>$>", Arrays.class);
    Iterator<String> iterator = allRegionIds.iterator();
    while (iterator.hasNext()) {
        builder.add("$S", iterator.next());
        if (iterator.hasNext()) {
            builder.add(",\n");
        }
    }
    builder.add("$<$<)");
    TypeName listType = ParameterizedTypeName.get(List.class, String.class);
    return FieldSpec.builder(listType, "REGION_IDS", STATIC, FINAL)
            .initializer(builder.build())
            .build();
}
 
Example #18
Source File: DeepLinkInterceptorProcessor.java    From OkDeepLink with Apache License 2.0 6 votes vote down vote up
private MethodSpec.Builder geneGlobalInterceptorsBuilder(InterceptorElement interceptorElement) {
    CodeBlock.Builder builder = CodeBlock.builder();
    TypeName typeName = ParameterizedTypeName.get(ClassName.get(List.class), INTERCEPTOR);
    builder.add("$T result = ($T)joinPoint.proceed();\n", typeName, typeName);
    builder.add("result.add(new $T());\n",
            interceptorElement.getClassName());
    builder.add("return result;\n");
    return MethodSpec.methodBuilder("getGlobalInterceptors")
            .addModifiers(Modifier.PUBLIC)
            .addParameter(ProceedingJoinPoint.class, "joinPoint")
            .returns(typeName)
            .addException(Throwable.class)
            .addAnnotation(AnnotationSpec
                    .builder(Around.class)
                    .addMember("value", "$S", "execution(* " + GLOBAL_INTERCEPTORS_METHOD_NAME + ")").build())
            .addCode(builder.build());
}
 
Example #19
Source File: JavaFiler.java    From convalida with Apache License 2.0 6 votes vote down vote up
private static CodeBlock createConfirmPasswordValidationCodeBlock(
        ValidationField passwordField,
        ValidationField confirmPasswordField
) {
    Element element = confirmPasswordField.element;
    Class<ConfirmPassword> annotation = ConfirmPassword.class;
    boolean hasErrorMessageResId = element.getAnnotation(annotation).errorMessageResId() != -1;
    String errorMessage = element.getAnnotation(annotation).errorMessage();
    String block = "validatorSet.addValidator(new $T(target.$N, target.$N, " +
            errorMessage(hasErrorMessageResId) +
            ", $L))";

    return CodeBlock.builder()
            .addStatement(
                    block,
                    CONFIRM_PASSWORD_VALIDATOR,
                    passwordField.name,
                    confirmPasswordField.name,
                    hasErrorMessageResId ? confirmPasswordField.id.code : errorMessage,
                    confirmPasswordField.autoDismiss
            )
            .build();
}
 
Example #20
Source File: MatcherGenerator.java    From litho with Apache License 2.0 6 votes vote down vote up
private static CodeBlock generateValuePropMatchBlock(
    FieldExtractorSpec fieldExtractorSpec,
    Function<FieldExtractorSpec, CodeBlock> fieldExtractorBlockFn) {
  final String matcherName = getPropMatcherName(fieldExtractorSpec.propModel);
  return CodeBlock.builder()
      .add(
          fieldExtractorBlockFn.apply(
              new FieldExtractorSpec(
                  fieldExtractorSpec.specModel,
                  fieldExtractorSpec.propModel,
                  fieldExtractorSpec.varName)))
      .beginControlFlow(
          "if ($1N != null && !$1N.matches($2L))", matcherName, fieldExtractorSpec.varName)
      .add(
          generateMatchFailureStatement(
              fieldExtractorSpec.specModel, matcherName, fieldExtractorSpec.propModel))
      .addStatement("return false")
      .endControlFlow()
      .build();
}
 
Example #21
Source File: DeepLinkServiceProcessor.java    From OkDeepLink with Apache License 2.0 5 votes vote down vote up
private MethodSpec generateInitMethod(List<AddressElement> addressElements) {

        CodeBlock.Builder initializer = CodeBlock.builder();
        for (AddressElement element : addressElements) {
            List<String> deepLinkPaths = element.getDeepLinkPaths();
            if (!element.isPathsEmpty()) {
                for (String deepLinkPath : deepLinkPaths) {
                    TypeMirror activityTypeMirror = element.getActivityTypeMirror();
                    TypeMirror supportTypeMirror = elements.getTypeElement(ACTIVITY).asType();
                    if (activityTypeMirror != null) {
                        if (!types.isSubtype(activityTypeMirror, supportTypeMirror)) {
                            logger.error(Activity.class.getName() + " only support class which extends " + ACTIVITY, element.getElement());
                        }
                    }
                    ClassName activityClassName = element.getActivityClassName();
                    if (activityClassName != null) {
                        initializer.add("$T.addAddress(new $T($S, $T.class));\n",
                                DEEP_LINK_CLIENT, DEEP_LINK_ENTRY, deepLinkPath, activityClassName);
                    }
                }
            }

        }
        MethodSpec.Builder initMethod = MethodSpec.methodBuilder("init")
                .addModifiers(Modifier.PUBLIC)
                .addAnnotation(AnnotationSpec.builder(After.class).addMember("value", "$S", "execution(* " + INIT_METHOD_NAME + ")").build())
                .addCode(initializer.build());

        return initMethod.build();
    }
 
Example #22
Source File: Bundlables.java    From auto-value-bundle with MIT License 5 votes vote down vote up
private String parsePrimitive(
        Class boxedClass,
        String method,
        String readFromBundle) {
    return CodeBlock.builder()
            .add("$L.$L($L)", boxedClass.getSimpleName(), method, readFromBundle)
            .build()
            .toString();
}
 
Example #23
Source File: PaginationDocs.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private CodeBlock noteAboutLimitConfigurationMethod() {
    return CodeBlock.builder()
                    .add("\n<p><b>Please notice that the configuration of $L won't limit the number of results "
                         + "you get with the paginator. It only limits the number of results in each page.</b></p>",
                         getPaginatorLimitKeyName())
                    .build();
}
 
Example #24
Source File: QueryProtocolSpec.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public CodeBlock responseHandler(IntermediateModel model,
                                 OperationModel opModel) {
    ClassName responseType = poetExtensions.getModelClass(opModel.getReturnType().getReturnType());

    return CodeBlock.builder()
                    .addStatement("\n\n$T<$T> responseHandler = protocolFactory.createResponseHandler($T::builder)",
                                  HttpResponseHandler.class,
                                  responseType,
                                  responseType)
                    .build();
}
 
Example #25
Source File: BuilderGenerator.java    From litho with Apache License 2.0 5 votes vote down vote up
private static MethodSpec.Builder resTypeRegularBuilder(
    SpecModel specModel,
    PropModel prop,
    int requiredIndex,
    String name,
    List<ParameterSpec> parameters,
    String statement,
    Object... formatObjects) {

  if (prop.hasVarArgs()) {
    final ParameterizedTypeName varArgType = (ParameterizedTypeName) prop.getTypeName();
    final TypeName singleParameterType = varArgType.typeArguments.get(0);

    CodeBlock.Builder codeBlockBuilder = CodeBlock.builder();

    createListIfDefault(codeBlockBuilder, specModel, prop, singleParameterType);

    codeBlockBuilder
        .add(
            "final $T res = ",
            singleParameterType.isBoxedPrimitive()
                ? singleParameterType.unbox()
                : singleParameterType)
        .addStatement(statement, formatObjects)
        .addStatement(
            "this.$L.$L.add(res)", getComponentMemberInstanceName(specModel), prop.getName());

    return getMethodSpecBuilder(
        specModel, prop, requiredIndex, name, parameters, codeBlockBuilder.build());
  }

  return getNoVarArgsMethodSpecBuilder(
      specModel, prop, requiredIndex, name, parameters, statement, formatObjects);
}
 
Example #26
Source File: TimeConfigProviderGenerator.java    From aircon with MIT License 5 votes vote down vote up
private CodeBlock getDuringDurationPredicateBodyCodeBlock() {
	final CodeBlock now = SystemClassDescriptor.currentTimeMillis()
	                                           .build();
	final CodeBlock configFirstLoadingTime = getConfigSourceClassDescriptor().getFirstLoadTimeMillis()
	                                                                         .build();
	final CodeBlock timeSinceFirstFetch = new CodeBlockBuilder().addBinaryOperator(CodeBlockBuilder.OPERATOR_MINUS, now, configFirstLoadingTime)
	                                                            .build();
	final CodeBlock getterCall = new CodeBlockBuilder().addGeneratedMethodCall(mElement.getProviderMethod())
	                                                   .build();
	return new CodeBlockBuilder().addReturn(new CodeBlockBuilder().addBinaryOperator(CodeBlockBuilder.OPERATOR_GREATER_THAN, getterCall, timeSinceFirstFetch)
	                                                              .build())
	                             .build();
}
 
Example #27
Source File: ClientClassUtils.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
static MethodSpec applySignerOverrideMethod(PoetExtensions poetExtensions, IntermediateModel model) {
    String signerOverrideVariable = "signerOverride";

    TypeVariableName typeVariableName =
        TypeVariableName.get("T", poetExtensions.getModelClass(model.getSdkRequestBaseClassName()));

    ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName
        .get(ClassName.get(Consumer.class), ClassName.get(AwsRequestOverrideConfiguration.Builder.class));

    CodeBlock codeBlock = CodeBlock.builder()
                                   .beginControlFlow("if (request.overrideConfiguration().flatMap(c -> c.signer())"
                                                     + ".isPresent())")
                                   .addStatement("return request")
                                   .endControlFlow()
                                   .addStatement("$T $L = b -> b.signer(signer).build()",
                                                 parameterizedTypeName,
                                                 signerOverrideVariable)
                                   .addStatement("$1T overrideConfiguration =\n"
                                                 + "            request.overrideConfiguration().map(c -> c.toBuilder()"
                                                 + ".applyMutation($2L).build())\n"
                                                 + "            .orElse((AwsRequestOverrideConfiguration.builder()"
                                                 + ".applyMutation($2L).build()))",
                                                 AwsRequestOverrideConfiguration.class,
                                                 signerOverrideVariable)
                                   .addStatement("return (T) request.toBuilder().overrideConfiguration"
                                                 + "(overrideConfiguration).build()")
                                   .build();

    return MethodSpec.methodBuilder("applySignerOverride")
                     .addModifiers(Modifier.PRIVATE)
                     .addParameter(typeVariableName, "request")
                     .addParameter(Signer.class, "signer")
                     .addTypeVariable(typeVariableName)
                     .addCode(codeBlock)
                     .returns(typeVariableName)
                     .build();
}
 
Example #28
Source File: SolidityFunctionWrapper.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
private FieldSpec createEventDefinition(
        String name,
        List<NamedTypeName> parameters) {

    CodeBlock initializer = buildVariableLengthEventInitializer(
            name, parameters);

    return FieldSpec.builder(Event.class, buildEventDefinitionName(name))
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
            .initializer(initializer)
            .build();
}
 
Example #29
Source File: CustomConfigProviderGenerator.java    From aircon with MIT License 5 votes vote down vote up
@Override
protected CodeBlock getGetterBodyCodeBlock() {
	final CodeBlockBuilder builder = new CodeBlockBuilder();
	final CodeBlock annotationClass = ClassDescriptor.clazz(mElement.getAnnotation())
	                                                 .build();
	final CodeBlock configClass = ClassDescriptor.clazz(mElement.getConfigClassTypeName())
	                                             .build();
	final CodeBlock annotation = AirConUtilsClassDescriptor.getCustomConfigAnnotation(configClass, annotationClass, "\"" + mElement.getName() + "\"")
	                                                       .build();
	builder.addLocalVariable(mElement.getAnnotation(), VAR_ANNOTATION, annotation, true);
	builder.add(super.getGetterBodyCodeBlock());
	return builder.build();
}
 
Example #30
Source File: ServiceMetadataGenerator.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private CodeBlock globalRegion(Partition partition) {
    ClassName region = ClassName.get(regionBasePackage, "Region");
    Service service = partition.getServices().get(this.serviceEndpointPrefix);
    boolean hasGlobalRegionForPartition = service.isRegionalized() != null &&
                                          !service.isRegionalized() &&
                                          service.isPartitionWideEndpointAvailable();
    String globalRegionForPartition = hasGlobalRegionForPartition ? service.getPartitionEndpoint() : null;
    return globalRegionForPartition == null
                                ? CodeBlock.of("null")
                                : CodeBlock.of("$T.of($S)", region, globalRegionForPartition);
}