Java Code Examples for com.squareup.javapoet.ClassName

The following are top voted examples for showing how to use com.squareup.javapoet.ClassName. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: aws-sdk-java-v2   File: AwsServiceModel.java   Source Code and License 6 votes vote down vote up
private List<TypeName> modelSuperInterfaces() {
    List<TypeName> interfaces = new ArrayList<>();

    if (implementStructuredPojoInterface()) {
        interfaces.add(ClassName.get(StructuredPojo.class));
    }

    switch (shapeModel.getShapeType()) {
        case Exception:
        case Model:
        case Request:
        case Response:
            interfaces.add(toCopyableBuilderInterface());
            break;
        default:
            break;
    }

    return interfaces;
}
 
Example 2
Project: GitHub   File: BindingSet.java   Source Code and License 6 votes vote down vote up
static Builder newBuilder(TypeElement enclosingElement) {
  TypeMirror typeMirror = enclosingElement.asType();

  boolean isView = isSubtypeOfType(typeMirror, VIEW_TYPE);
  boolean isActivity = isSubtypeOfType(typeMirror, ACTIVITY_TYPE);
  boolean isDialog = isSubtypeOfType(typeMirror, DIALOG_TYPE);

  TypeName targetType = TypeName.get(typeMirror);
  if (targetType instanceof ParameterizedTypeName) {
    targetType = ((ParameterizedTypeName) targetType).rawType;
  }

  String packageName = getPackage(enclosingElement).getQualifiedName().toString();
  String className = enclosingElement.getQualifiedName().toString().substring(
      packageName.length() + 1).replace('.', '$');
  ClassName bindingClassName = ClassName.get(packageName, className + "_ViewBinding");

  boolean isFinal = enclosingElement.getModifiers().contains(Modifier.FINAL);
  return new Builder(targetType, bindingClassName, isFinal, isView, isActivity, isDialog);
}
 
Example 3
Project: butterknife-parent   File: BindingSet.java   Source Code and License 6 votes vote down vote up
private BindingSet(TypeName targetTypeName, ClassName bindingClassName, boolean isFinal,
                   boolean isView, boolean isActivity,boolean isFragment, boolean isDialog, ImmutableList<ViewBinding> viewBindings,
                   ImmutableList<FieldCollectionViewBinding> collectionBindings,
                   ImmutableList<ResourceBinding> resourceBindings, BindingSet parentBinding, @LayoutRes int layoutId) {
    this.isFinal = isFinal;
    this.targetTypeName = targetTypeName;
    this.bindingClassName = bindingClassName;
    this.isView = isView;
    this.isActivity = isActivity;
    this.isFragment = isFragment;
    this.isDialog = isDialog;
    this.viewBindings = viewBindings;
    this.collectionBindings = collectionBindings;
    this.resourceBindings = resourceBindings;
    this.parentBinding = parentBinding;
    this.layoutId = layoutId;
}
 
Example 4
Project: react4j   File: Generator.java   Source Code and License 6 votes vote down vote up
@Nonnull
private static TypeSpec buildDaggerModule( @Nonnull final ComponentDescriptor descriptor )
{
  final TypeSpec.Builder builder = TypeSpec.classBuilder( "DaggerModule" );

  builder.addModifiers( Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL );
  builder.addAnnotation( ClassName.bestGuess( Constants.DAGGER_MODULE_CLASSNAME ) );

  final MethodSpec.Builder method =
    MethodSpec.methodBuilder( "provideComponent" ).
      addAnnotation( ClassName.bestGuess( Constants.DAGGER_PROVIDES_CLASSNAME ) ).
      addModifiers( Modifier.STATIC ).
      addParameter( descriptor.getClassNameToConstruct(), "component", Modifier.FINAL ).
      returns( COMPONENT_CLASSNAME ).
      addStatement( "return component" );
  builder.addMethod( method.build() );

  return builder.build();
}
 
Example 5
Project: domino   File: EndpointsRegisterMethodWriter.java   Source Code and License 6 votes vote down vote up
@Override
protected void registerItem(EndpointsEntry entry, MethodSpec.Builder methodBuilder) {
    final FullClassName handlerEndpoint = new FullClassName(entry.element.fullQualifiedNoneGenericName() + "EndpointHandler");
    String path = entry.element.getAnnotation(Handler.class).value();

    ClassName handlerEndpointType = ClassName.get(handlerEndpoint.asPackage(), handlerEndpoint.asSimpleName());
    MethodSpec getMethod = MethodSpec.methodBuilder("get")
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC)
            .returns(handlerEndpointType)
            .addStatement("return new $T()", handlerEndpointType)
            .build();

    TypeSpec factoryType = TypeSpec.anonymousClassBuilder("")
            .addSuperinterface(ParameterizedTypeName.get(ClassName.get(Supplier.class), handlerEndpointType.box()))
            .addMethod(getMethod)
            .build();
    methodBuilder.addStatement("registry.registerEndpoint(\"" + path + "\", $L)", factoryType);
}
 
Example 6
Project: data-mediator   File: SharedPropertiesNGenerator.java   Source Code and License 6 votes vote down vote up
public static boolean generateSharedProperties(Collection<FieldData> fields,
                                               Elements elements, Filer filer, ProcessorPrinter pp){
    final ClassName cn_sp = ClassName.get(PKG_DM_INTERNAL, SIMPLE_NAME_SHARED_PROP);
    CodeBlock.Builder staticBuilder = CodeBlock.builder();
    for(FieldData fd : fields){
        staticBuilder.add("$T.putToCache($S, $S, $L);\n", cn_sp, fd.getTypeCompat().toString(),
                fd.getPropertyName(), fd.getComplexType());
    }
    String classSimpleName = SIMPLE_NAME_SHARED_PROP + "_" + findBestIndex(elements);
    TypeSpec typeSpec = TypeSpec.classBuilder(classSimpleName)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addStaticBlock(staticBuilder.build())
            .addJavadoc(CodeBlock.of(DOC))
            .build();

    try {
        JavaFile javaFile = JavaFile.builder(PKG_DM_INTERNAL, typeSpec)
                .build();
       // System.out.println(javaFile.toString());
        javaFile.writeTo(filer);
    } catch (IOException e) {
        pp.error(TAG, "generateSharedProperties", Util.toString(e));
        return false;
    }
    return true;
}
 
Example 7
Project: butterknife-parent   File: ButterKnifeProcessor.java   Source Code and License 6 votes vote down vote up
private void parseCompiledR(String respectivePackageName, TypeElement rClass) {
  for (Element element : rClass.getEnclosedElements()) {
    String innerClassName = element.getSimpleName().toString();
    if (SUPPORTED_TYPES.contains(innerClassName)) {
      for (Element enclosedElement : element.getEnclosedElements()) {
        if (enclosedElement instanceof VariableElement) {
          VariableElement variableElement = (VariableElement) enclosedElement;
          Object value = variableElement.getConstantValue();

          if (value instanceof Integer) {
            int id = (Integer) value;
            ClassName rClassName =
                ClassName.get(elementUtils.getPackageOf(variableElement).toString(), "R",
                    innerClassName);
            String resourceName = variableElement.getSimpleName().toString();
            QualifiedId qualifiedId = new QualifiedId(respectivePackageName, id);
            symbols.put(qualifiedId, new Id(id, rClassName, resourceName));
          }
        }
      }
    }
  }
}
 
Example 8
Project: aws-sdk-java-v2   File: MemberCopierSpec.java   Source Code and License 6 votes vote down vote up
private MethodSpec builderCopyMethodForList() {
    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 9
Project: json2java4idea   File: JavaConverter.java   Source Code and License 6 votes vote down vote up
@Nonnull
private TypeName generateListType(@Nonnull String className, @Nonnull JsonValue value, @Nonnull ClassBuilder builder) {
    if (value.isArray()) {
        final JsonValue firstValue = value.asArray()
                .stream()
                .findFirst()
                .orElse(new JsonNull());
        final TypeName type = generateListType(className, firstValue, builder);
        return ParameterizedTypeName.get(ClassName.get(List.class), type);
    }

    if (value.isObject()) {
        final TypeSpec innerClass = fromObject(className, value.asObject(), Modifier.PUBLIC, Modifier.STATIC);
        builder.addInnerType(innerClass);

        final TypeName innerClassType = ClassName.bestGuess(innerClass.name);
        return ParameterizedTypeName.get(ClassName.get(List.class), innerClassType);
    }

    return ParameterizedTypeName.get(ClassName.get(List.class), value.getType().box());
}
 
Example 10
Project: KiiAnnotation   File: BuilderGenerator.java   Source Code and License 6 votes vote down vote up
public static MethodSpec builderBuild(ClassName className, List<MethodSpec> methodSpecList, List<FieldSpec> fieldSpecList) {
    String name = className.simpleName();
    CodeBlock.Builder codeBlock = CodeBlock.builder();

    for (int i = 0; i < methodSpecList.size(); i++) {
        codeBlock.add("$N.$N(this.$N);\n", name.toLowerCase(), methodSpecList.get(i).name, fieldSpecList.get(i).name);
    }

    return MethodSpec
            .methodBuilder("build")
            .addModifiers(Modifier.PUBLIC)
            .addStatement("$N $N = new $N()", name, name.toLowerCase(), name)
            .addCode(codeBlock.build())
            .returns(className)
            .addStatement("return $N", name.toLowerCase())
            .build();
}
 
Example 11
Project: dataenum   File: MatchMethods.java   Source Code and License 6 votes vote down vote up
private MethodSpec.Builder createFoldVoidSignature(
    Iterable<TypeVariableName> availableTypeVariables) throws ParserException {
  MethodSpec.Builder builder =
      MethodSpec.methodBuilder("match").addModifiers(Modifier.PUBLIC).returns(void.class);

  for (OutputValue arg : values) {
    TypeName visitor =
        ParameterizedTypeName.get(
            ClassName.get(Consumer.class),
            withoutMissingTypeVariables(arg.parameterizedOutputClass(), availableTypeVariables));

    builder.addParameter(
        ParameterSpec.builder(visitor, asCamelCase(arg.name()))
            .addAnnotation(Nonnull.class)
            .build());
  }

  return builder;
}
 
Example 12
Project: prefpin   File: PrefPinProcessor.java   Source Code and License 6 votes vote down vote up
private void writeBinding(String targetClassName, Set<Element> annotationFields)
    throws IOException {
  String packageName = null;
  int lastDot = targetClassName.lastIndexOf('.');
  if (lastDot > 0) {
    packageName = targetClassName.substring(0, lastDot);
  }

  String targetSimpleClassName = targetClassName.substring(lastDot + 1);
  String bindingClassName = targetClassName + "_PrefBinding";
  String bindingSimpleClassName = bindingClassName.substring(lastDot + 1);

  ClassName targetClass = ClassName.get(packageName, targetSimpleClassName);

  TypeSpec binding = TypeSpec.classBuilder(bindingSimpleClassName)
      .addModifiers(Modifier.PUBLIC)
      .addMethod(buildConstructor(targetClass, annotationFields))
      .build();

  JavaFile javaFile = JavaFile.builder(packageName, binding).build();

  javaFile.writeTo(processingEnv.getFiler());
}
 
Example 13
Project: r-parser   File: IdScanner.java   Source Code and License 6 votes vote down vote up
@Override
public void visitClassDef(JCTree.JCClassDecl jcClassDecl) {
    for (JCTree tree : jcClassDecl.defs) {
        if (tree instanceof ClassTree) {
            ClassTree classTree = (ClassTree) tree;
            String className = classTree.getSimpleName().toString();
            if (supportedTypes.contains(className)) {
                ClassName rClassName = ClassName.get(rPackageName, "R", className);
                VarScanner scanner = new VarScanner(ids, rClassName, respectivePackageName);
                ((JCTree) classTree).accept(scanner);
            }
        }
    }
}
 
Example 14
Project: GitHub   File: RequestManagerGenerator.java   Source Code and License 6 votes vote down vote up
private MethodSpec generateAdditionalRequestManagerMethodNew(
    ExecutableElement extensionMethod) {
   String returnType = processorUtil.findClassValuesFromAnnotationOnClassAsNames(extensionMethod,
      GlideType.class).iterator().next();
  ClassName returnTypeClassName = ClassName.bestGuess(returnType);
  ParameterizedTypeName parameterizedTypeName =
      ParameterizedTypeName.get(generatedRequestBuilderClassName, returnTypeClassName);

  return MethodSpec.methodBuilder(extensionMethod.getSimpleName().toString())
      .addModifiers(Modifier.PUBLIC)
      .returns(parameterizedTypeName)
      .addJavadoc(processorUtil.generateSeeMethodJavadoc(extensionMethod))
      .addStatement(
          "return ($T) $T.$N(this.as($T.class))",
          parameterizedTypeName,
          extensionMethod.getEnclosingElement(),
          extensionMethod.getSimpleName(),
          returnTypeClassName)
      .build();
}
 
Example 15
Project: GitHub   File: GlideGenerator.java   Source Code and License 6 votes vote down vote up
private MethodSpec overrideGlideWithMethod(
    String packageName, TypeSpec generatedRequestManager, ExecutableElement methodToOverride) {
  ClassName generatedRequestManagerClassName =
      ClassName.get(packageName, generatedRequestManager.name);
  List<? extends VariableElement> parameters = methodToOverride.getParameters();
  Preconditions.checkArgument(
      parameters.size() == 1, "Expected size of 1, but got %s", methodToOverride);
  VariableElement parameter = parameters.iterator().next();
  return MethodSpec.methodBuilder(methodToOverride.getSimpleName().toString())
      .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
      .addJavadoc(processorUtil.generateSeeMethodJavadoc(methodToOverride))
      .returns(generatedRequestManagerClassName)
      .addParameter(ClassName.get(parameter.asType()), parameter.getSimpleName().toString())
      .addStatement("return ($T) $T.$N($L)",
          generatedRequestManagerClassName, glideType,
          methodToOverride.getSimpleName().toString(),
          parameter.getSimpleName())
      .build();
}
 
Example 16
Project: PreferenceRoom   File: PreferenceComponentGenerator.java   Source Code and License 6 votes vote down vote up
private List<MethodSpec> getSuperMethodSpecs() {
    List<MethodSpec> methodSpecs = new ArrayList<>();
    this.annotatedClazz.annotatedElement.getEnclosedElements().stream()
            .filter(element -> element instanceof ExecutableElement)
            .map(element -> (ExecutableElement) element)
            .forEach(method -> {
                ClassName preferenceRoom = ClassName.get(PreferenceRoom.class);
                MethodSpec.Builder builder = MethodSpec.overriding(method);
                MethodSpec methodSpec = builder.addStatement("$T.inject($N)", preferenceRoom, method.getParameters().get(0).getSimpleName()).build();
                if(methodSpec.returnType != TypeName.get(Void.TYPE)) {
                    throw new VerifyException(String.format("Returned '%s'. only return type can be void.", methodSpec.returnType.toString()));
                }
                methodSpecs.add(methodSpec);
            });
    return methodSpecs;
}
 
Example 17
Project: GitHub   File: RequestManagerGenerator.java   Source Code and License 6 votes vote down vote up
RequestManagerGenerator(ProcessingEnvironment processingEnv, ProcessorUtil processorUtil) {
  this.processingEnv = processingEnv;
  this.processorUtil = processorUtil;

  Elements elementUtils = processingEnv.getElementUtils();

  requestManagerType = elementUtils.getTypeElement(REQUEST_MANAGER_QUALIFIED_NAME);
  requestManagerClassName = ClassName.get(requestManagerType);

  lifecycleType = elementUtils.getTypeElement(LIFECYCLE_QUALIFIED_NAME);
  requestManagerTreeNodeType =
      elementUtils.getTypeElement(REQUEST_MANAGER_TREE_NODE_QUALIFIED_NAME);

  requestBuilderType =
      elementUtils.getTypeElement(RequestBuilderGenerator.REQUEST_BUILDER_QUALIFIED_NAME);

  glideType = elementUtils.getTypeElement(GLIDE_QUALIFIED_NAME);
}
 
Example 18
Project: aws-sdk-java-v2   File: SyncClientBuilderInterface.java   Source Code and License 5 votes vote down vote up
@Override
public TypeSpec poetSpec() {
    return PoetUtils.createInterfaceBuilder(builderInterfaceName)
                    .addSuperinterface(ParameterizedTypeName.get(ClassName.get(SyncClientBuilder.class),
                                                                 builderInterfaceName, clientInterfaceName))
                    .addSuperinterface(ParameterizedTypeName.get(baseBuilderInterfaceName,
                                                                 builderInterfaceName, clientInterfaceName))
                    .addJavadoc(getJavadoc())
                    .build();
}
 
Example 19
Project: RxAndroidOrm   File: ModelEntityProxyGenerator.java   Source Code and License 5 votes vote down vote up
public TypeSpec generate() {
    String idFieldName = Constants.FIELD_ID;
    Element idField = ProcessUtils.getIdField(element);
    if (idField != null)
        idFieldName = ProcessUtils.getObjectName(idField);

    TypeSpec.Builder builder = TypeSpec.classBuilder(ProcessUtils.getObjectName(element) + Constants.MODEL_ENTITY_PROXY)
            .addModifiers(Modifier.PUBLIC)
            .superclass(TypeName.get(element.asType()))
            .addSuperinterface(ClassName.get(Constants.DAO_PACKAGE, Constants.MODEL_ENTITY_PROXY_INTERFACE));

    if (idField == null) {
        builder.addField(TypeName.LONG, Constants.FIELD_ID);
    }

    builder.addMethod(MethodSpec.methodBuilder(Constants.MODEL_ENTITY_PROXY_GET_ID_METHOD)
            .addModifiers(Modifier.PUBLIC)
            .returns(TypeName.LONG)
            .addStatement("return $L", idFieldName)
            .build())
            .addMethod(MethodSpec.methodBuilder(Constants.MODEL_ENTITY_PROXY_SET_ID_METHOD)
                    .addModifiers(Modifier.PUBLIC)
                    .returns(TypeName.VOID)
                    .addParameter(TypeName.LONG, "id")
                    .addStatement("this.$L = id", idFieldName)
                    .build());

    return builder.build();
}
 
Example 20
Project: Spyglass   File: TestGetPlaceholderMethodGenerator.java   Source Code and License 5 votes vote down vote up
@Test
public void testGenerateFor_parameterWithUseShort() {
	final VariableElement parameter = avatarRule.getElementWithUniqueId("short");
	final AnnotationMirror useAnnotation = UseAnnoRetriever.getAnnotation(parameter);

	final MethodSpec generatedMethod = generator.generateFor(useAnnotation, 0);

	checkSignature(generatedMethod, ClassName.get(Number.class));
	checkCompiles(generatedMethod);
}
 
Example 21
Project: PreferenceRoom   File: PreferenceFieldMethodGenerator.java   Source Code and License 5 votes vote down vote up
private MethodSpec generateObjectSetter() {
    ClassName converterClazz = ClassName.get(keyField.converterPackage, keyField.converter);
    return MethodSpec.methodBuilder(getSetterPrefixName())
            .addModifiers(PUBLIC)
            .addParameter(keyField.typeName, keyField.keyName.toLowerCase())
            .addStatement("$T $N = new $T()", converterClazz, INSTANCE_CONVERTER, converterClazz)
            .addStatement(getSetterStatement(), preference, EDIT_METHOD, keyField.keyName, INSTANCE_CONVERTER + ".convertObject(" + keyField.keyName.toLowerCase() + ")", APPLY_METHOD)
            .build();
}
 
Example 22
Project: vxrifa   File: SenderGenerator.java   Source Code and License 5 votes vote down vote up
SenderGenerator generateHandler() {

        MethodSpec.Builder handlerBuilder = MethodSpec.methodBuilder("handle");

        TypeVariableName Tvariable = TypeVariableName.get("T");

        handlerBuilder.addModifiers(Modifier.PRIVATE)
                .addTypeVariable(Tvariable)
                .addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "unchecked").build());

        ParameterSpec futureParameter = ParameterSpec.builder(ParameterizedTypeName.get(ClassName.get(io.vertx.core.Future.class), Tvariable), "future").build();
        ParameterSpec asyncResultParameter = ParameterSpec.builder(
                ParameterizedTypeName.get(ClassName.get(io.vertx.core.AsyncResult.class),
                        ParameterizedTypeName.get(ClassName.get(io.vertx.core.eventbus.Message.class), TypeName.get(Object.class))),
                "asyncResult").build();

        handlerBuilder.addParameter(futureParameter)
                .addParameter(asyncResultParameter)
                .beginControlFlow("if ($N.succeeded())", asyncResultParameter)
                .addStatement("$T reply = ($T) $N.result().body()", RIFAMessage.class, RIFAMessage.class, asyncResultParameter)
                .addStatement("$N.complete(($T) reply.get(0))", futureParameter, Tvariable)
                .nextControlFlow("else")
                .addStatement("$N.fail($N.cause().getMessage())", futureParameter, asyncResultParameter)
                .endControlFlow()
                .returns(TypeName.VOID);

        classBuilder.addMethod(handlerBuilder.build());

        return this;

    }
 
Example 23
Project: aws-sdk-java-v2   File: QueryXmlProtocolSpec.java   Source Code and License 5 votes vote down vote up
@Override
public List<CodeBlock> errorUnmarshallers(IntermediateModel model) {
    List<ShapeModel> exceptions = model.getShapes()
                                       .values()
                                       .stream()
                                       .filter(s -> s.getType().equals("Exception"))
                                       .collect(Collectors.toList());

    return exceptions.stream().map(s -> {
        ClassName exceptionClass = poetExtensions.getTransformClass(s.getShapeName() + "Unmarshaller");
        return CodeBlock.builder()
                        .add("unmarshallers.add(new $T());", exceptionClass).build();
    }).collect(Collectors.toList());
}
 
Example 24
Project: aws-sdk-java-v2   File: AwsServiceModel.java   Source Code and License 5 votes vote down vote up
private MethodSpec serializableBuilderClass() {
    return MethodSpec.methodBuilder("serializableBuilderClass")
                     .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                     .returns(ParameterizedTypeName.get(ClassName.get(Class.class),
                                                        WildcardTypeName.subtypeOf(modelBuilderSpecs.builderInterfaceName())))
                     .addStatement("return $T.class", modelBuilderSpecs.builderImplName())
                     .build();
}
 
Example 25
Project: Spyglass   File: TestGetDefaultMethodGenerator.java   Source Code and License 5 votes vote down vote up
@Test
public void testGenerateFor_defaultToDimensionAnnotationSupplied() {
	final Element element = avatarRule.getElementWithUniqueId("dimension");
	final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, DefaultToDimension.class);

	final MethodSpec generatedMethod = generator.generateFor(mirror);

	assertThat(generatedMethod, is(notNullValue()));
	checkMethodSignature(generatedMethod, ClassName.get(Number.class));
	checkCompiles(generatedMethod);
}
 
Example 26
Project: limitjson   File: LimitJSONTypeArray.java   Source Code and License 5 votes vote down vote up
public void addStatement(MethodSpec.Builder builder, LIMITJSONVariable variable) {
    builder.beginControlFlow("if (root.has($S))", variable.jsonName());
    builder.addStatement("$T array = root.optJSONArray($S)", ClassName.bestGuess("org.json.JSONArray"), variable.jsonName());
    builder.addStatement("int size = array.length()");
    builder.addStatement("thisObj.$N = new $N[size]", variable.variableName(), type);
    builder.beginControlFlow("for (int i = 0; i < size; i++)");
    builder.addStatement(String.format("thisObj.$N[i] = array.%s(i)", format), variable.variableName());
    builder.endControlFlow();
    builder.endControlFlow();
}
 
Example 27
Project: jdoocsoup   File: DataClassBuilderHandler.java   Source Code and License 5 votes vote down vote up
private void parseDataFromDescriptor() {
    if (descriptor.getElementKind() == ElementKind.CLASS) {
        for (VariableElement var : descriptor.getFields()) {

            if (checkIfFieldForProcessing(var)) {
                continue;
            }

            DataClassBuilder.MethodDocs builderMethodDocsAnnotation = var.getAnnotation(DataClassBuilder.MethodDocs.class);
            DataClassBuilder.HasDefault hasDefaultAnnotation = var.getAnnotation(DataClassBuilder.HasDefault.class);

            FieldSpec.Builder fieldSpec = FieldSpec.builder(TypeName.get(var.asType()), var.getSimpleName().toString()).addModifiers(Modifier.PRIVATE);

            if (hasDefaultAnnotation != null) {
                fieldSpec.initializer(CodeBlock.of("$L", hasDefaultAnnotation.value()));
            }

            MethodSpec.Builder methodSpec = MethodSpec.methodBuilder(var.getSimpleName().toString()).addModifiers(Modifier.PUBLIC)
                    .addParameter(ParameterSpec.builder(TypeName.get(var.asType()), var.getSimpleName().toString()).build())
                    .addStatement("this.$N = $N", var.getSimpleName(), var.getSimpleName())
                    .addStatement("return this")
                    .returns(ClassName.get(descriptor.getPackageName(), descriptor.getDataClassBuilderName()));

            if (builderMethodDocsAnnotation != null) {
                methodSpec.addJavadoc(builderMethodDocsAnnotation.value() + "\n");
            }

            builderClassSpecBuilder.addField(fieldSpec.build());
            builderClassSpecBuilder.addMethod(methodSpec.build());
        }
    }

    builderClassSpecBuilder.addMethod(createBuilderMethodSpec());
    builderClassSpecBuilder.addMethod(createBuildMethodSpec());
    builderClassSpecBuilder.addMethod(createPrivateConstructor());
}
 
Example 28
Project: Hannibai   File: HandleImplGenerator.java   Source Code and License 5 votes vote down vote up
private MethodSpec createRemoveMethodSpec(Element enclosedElement, String formatName,
                                          AnnotationSpec submitAnnotation) {
    if (enclosedElement.getAnnotation(Commit.class) == null) {
        return MethodSpec.methodBuilder(REMOVE + formatName)
                .addModifiers(Modifier.PUBLIC)
                .returns(TypeName.VOID)
                .addAnnotation(submitAnnotation)
                .addJavadoc(String.format(REMOVE_METHOD_JAVA_DOC,
                        enclosedElement.getSimpleName())
                )
                .addStatement("$T.remove1($N, $L, $S)",
                        ClassName.get(PACKAGE_NAME, HANNIBAI),
                        "mSharedPreferencesName",
                        "mId",
                        enclosedElement.getSimpleName())
                .build();
    } else {
        return MethodSpec.methodBuilder(REMOVE + formatName)
                .addModifiers(Modifier.PUBLIC)
                .returns(TypeName.BOOLEAN)
                .addAnnotation(submitAnnotation)
                .addJavadoc(String.format(REMOVE_METHOD_JAVA_DOC,
                        enclosedElement.getSimpleName())
                )
                .addStatement("return $T.remove2($N, $L, $S)",
                        ClassName.get(PACKAGE_NAME, HANNIBAI),
                        "mSharedPreferencesName",
                        "mId",
                        enclosedElement.getSimpleName())
                .build();
    }
}
 
Example 29
Project: remoter   File: FieldBuilder.java   Source Code and License 5 votes vote down vote up
private void addCommonFields(TypeSpec.Builder classBuilder) {
    //Add descriptor
    classBuilder.addField(FieldSpec.builder(ClassName.get(String.class), "DESCRIPTOR")
            .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
            .initializer("\"" + getRemoterInterfacePackageName() + "." + getRemoterInterfaceClassName() + "\"")
            .build());
    classBuilder.addField(FieldSpec.builder(TypeName.INT, "REMOTER_EXCEPTION_CODE")
            .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
            .initializer("-99999")
            .build());

}
 
Example 30
Project: auto-nav   File: NavProcessor.java   Source Code and License 5 votes vote down vote up
private void createNavigator(Set<ActivityIntentModel> activityModels) {

        TypeSpec.Builder navigatorBuilder = TypeSpec.classBuilder(navigatorClassName)
                .addModifiers(Modifier.PUBLIC, Modifier.FINAL);

        for (ActivityIntentModel model : activityModels) {
            createActivityIntent(model);

            /**
             *         public static MainActivityIntent toMainActivity(Context context){
             *             MainActivityIntent intent = new MainActivityIntent(context, "com.com.MainActivity");
             *             return intent;
             *         }
             */

            ClassName returnType = ClassName.get(model.getPackageName(), model.getIntentClzName());
            MethodSpec.Builder methodSpecBuilder = MethodSpec
                    .methodBuilder(METHOD_PREFIX + model.getClzName());
            methodSpecBuilder.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                    .addParameter(classContext, "context")
                    .returns(ClassName.get(model.getPackageName(), model.getIntentClzName()))
                    .addStatement("$T intent = new $T($L,$S)", returnType, returnType, "context", model.getQualifiedName())
                    .addStatement("return intent");

            navigatorBuilder.addMethod(methodSpecBuilder.build());
        }

        addPreGoListener(navigatorBuilder);


        try {
            JavaFile.builder(navigatorPackageName, navigatorBuilder.build()).build().writeTo(filer);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
 
Example 31
Project: raml-java-tools   File: ObjectTypeHandlerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void usingComposedTypes() throws Exception {

    final Api api = RamlLoader.load(this.getClass().getResourceAsStream("using-composed-type.raml"), ".");
    ObjectTypeHandler handler = new ObjectTypeHandler(RamlLoader.findTypes("foo", api.types()));

    CreationResult r = handler.create(createGenerationContext(api));

    System.err.println(r.getInterface().toString());
    System.err.println(r.getImplementation().toString());

    assertThat(r.getInterface(), is(allOf(
            name(equalTo("Foo")),
            methods(contains(
                    allOf(methodName(equalTo("getName")), returnType(equalTo(ClassName.get("", "Composed")))),
                    allOf(methodName(equalTo("setName")), parameters(contains(type(equalTo(ClassName.get("", "Composed"))))))
            ))
    )));

    assertThat(r.getImplementation().get(), is(allOf(
            name(equalTo("FooImpl")),
            fields(contains(
                    allOf(fieldName(equalTo("name")), fieldType(equalTo(ClassName.get("", "Composed"))))
            )),
            methods(contains(
                    allOf(methodName(equalTo("getName")), returnType(equalTo(ClassName.get("", "Composed")))),
                    allOf(methodName(equalTo("setName")), parameters(contains(type(equalTo(ClassName.get("", "Composed")))))))
            ))
    ));
}
 
Example 32
Project: auto-adapter   File: AnnotatedModel.java   Source Code and License 5 votes vote down vote up
private ClassName getViewBinderClassName(final TypeElement model) {
    if (annotationValue.isPresent()) {
        Object value = annotationValue.get().getValue();
        if (value instanceof String) {
            return ClassName.bestGuess((String) value);
        } else {
            TypeMirror mirror = (TypeMirror) annotationValue.get().getValue();
            return getClassNameFrom(typeUtils.asElement(mirror));
        }

    } else {
        return ClassName.get(LIBRARY_PACKAGE, model.getSimpleName() + "ViewBinder");
    }
}
 
Example 33
Project: remoter   File: ClassBuilder.java   Source Code and License 5 votes vote down vote up
public JavaFile.Builder buildProxyClass() {
    ClassName proxyClassName = getProxyClassName();

    TypeSpec.Builder proxyClassBuilder = TypeSpec
            .classBuilder(proxyClassName.simpleName())
            .addModifiers(Modifier.PUBLIC)
            .addSuperinterface(TypeName.get(getRemoterInterfaceElement().asType()));


    for (TypeParameterElement typeParameterElement : ((TypeElement) getRemoterInterfaceElement()).getTypeParameters()) {
        proxyClassBuilder.addTypeVariable(TypeVariableName.get(typeParameterElement.toString()));
    }

    //constructor
    proxyClassBuilder.addMethod(MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PUBLIC)
            .addJavadoc("Initialize this {@link " + getProxyClassName().simpleName() + "} with the given {@link IBinder}\n\n")
            .addJavadoc("@param binder An {@link IBinder} that exposes a remote {@link " + getRemoterInterfaceClassName() + "}\n")
            .addParameter(ClassName.get("android.os", "IBinder"), "binder")
            .addStatement("this.mRemote = binder").build());


    getBindingManager().getFieldBuilder(getRemoterInterfaceElement()).addProxyFields(proxyClassBuilder);
    getBindingManager().getMethoddBuilder(getRemoterInterfaceElement()).addProxyMethods(proxyClassBuilder);

    proxyClassBuilder.addJavadoc("Wraps a remote {@link IBinder} that implements {@link " + getRemoterInterfaceClassName() + "} interface\n");
    proxyClassBuilder.addJavadoc("<p>\n");
    proxyClassBuilder.addJavadoc("Autogenerated by <a href=\"https://bit.ly/Remoter\">Remoter</a>\n");
    proxyClassBuilder.addJavadoc("@see " + getStubClassName().simpleName() + "\n");

    return JavaFile.builder(proxyClassName.packageName(), proxyClassBuilder.build());
}
 
Example 34
Project: gwt-jackson-apt   File: DeserializerGenerator.java   Source Code and License 5 votes vote down vote up
public String generate(TypeMirror beanType, String packageName, Name beanName) {
    String generatedClassName = Type.deserializerName(packageName, beanName.toString());
    if (!TypeRegistry.containsDeserializer(beanType.toString())) {
        try {
            new AptDeserializerBuilder(beanType, filer)
                    .generate(beanName, packageName);
            TypeRegistry.registerDeserializer(beanType.toString(), ClassName.bestGuess(generatedClassName));
        } catch (IOException e) {
            throw new DeserializerGenerator.DeserializerGenerationFailedException(beanType.toString());
        }
    }
    return generatedClassName;
}
 
Example 35
Project: arez   File: ComponentDescriptor.java   Source Code and License 5 votes vote down vote up
@Nonnull
private MethodSpec buildPreDisposeMethod()
{
  return MethodSpec.methodBuilder( "preDispose" ).
    addModifiers( Modifier.FINAL ).
    addAnnotation( ClassName.bestGuess( Constants.PRE_DISPOSE_ANNOTATION_CLASSNAME ) ).
    addStatement( "this.$N.forEach( e -> $T.dispose( e ) )",
                  ENTITYLIST_FIELD_NAME,
                  GeneratorUtil.DISPOSABLE_CLASSNAME ).
    addStatement( "this.$N.clear()", ENTITIES_FIELD_NAME ).
    addStatement( "$N().reportChanged()", GET_OBSERVABLE_METHOD ).
    build();
}
 
Example 36
Project: smartkey   File: SharePreferenceGenerator.java   Source Code and License 5 votes vote down vote up
void processGet(ElementDescription elem, MethodSpec.Builder builder) {
    if(elem.code != null && elem.code.isGeneric()) {
        String[] types = elem.code.genericTypes();
        Object[] args = new Object[types.length + 2];
        args[0] = ClazzNames.GSON_HELPER;
        args[1] = ClazzNames.STORAGE_HELPER;
        args[2] = ClazzNames.TYPE_TOKEN;
        for (int i=3; i<args.length; i++) {
            args[i] = ClassName.bestGuess(types[i-2]);
        }
        builder.addStatement("return $T.fromJson($T.get(app, \""
                + elem.key + "\"), new $T<" + elem.code.genericTypes()[0]+">(){}.getType())",
                args);
    } else if(isBool(elem)) {
        builder.addStatement("return $T.getBoolean(app, \"" + elem.key + "\")", ClazzNames.STORAGE_HELPER);
    } else if(isFloat(elem)) {
        builder.addStatement("return $T.getFloat(app, \"" + elem.key + "\")", ClazzNames.STORAGE_HELPER);
    } else if(isInt(elem)) {
        builder.addStatement("return $T.getInt(app, \"" + elem.key + "\")", ClazzNames.STORAGE_HELPER);
    } else if(isLong(elem)) {
        builder.addStatement("return $T.getLong(app, \"" + elem.key + "\")", ClazzNames.STORAGE_HELPER);
    } else if(isString(elem)) {
        builder.addStatement("return $T.get(app, \"" + elem.key + "\")", ClazzNames.STORAGE_HELPER);
    } else if(isStringSet(elem)) {
        builder.addStatement("return $T.getStringSet(app, \"" + elem.key + "\")", ClazzNames.STORAGE_HELPER);
    } else {
        builder.addStatement("return $T.fromJson($T.get(app, \""
                + elem.key + "\"), " + elem.fieldType.toString()+".class)",
                ClazzNames.GSON_HELPER,
                ClazzNames.STORAGE_HELPER);
    }
}
 
Example 37
Project: Spyglass   File: TestGetDefaultMethodGenerator.java   Source Code and License 5 votes vote down vote up
@Test
public void testGenerateFor_defaultToStringResourceAnnotationSupplied() {
	final Element element = avatarRule.getElementWithUniqueId("string resource");
	final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(
			element,
			DefaultToStringResource.class);

	final MethodSpec generatedMethod = generator.generateFor(mirror);

	assertThat(generatedMethod, is(notNullValue()));
	checkMethodSignature(generatedMethod, ClassName.get(String.class));
	checkCompiles(generatedMethod);
}
 
Example 38
Project: GitHub   File: AppModuleGenerator.java   Source Code and License 5 votes vote down vote up
private MethodSpec generateGetExcludedModuleClasses(Set<String> excludedClassNames) {
  TypeName wildCardOfObject = WildcardTypeName.subtypeOf(Object.class);
  ParameterizedTypeName classOfWildcardOfObjet =
      ParameterizedTypeName.get(ClassName.get(Class.class), wildCardOfObject);
  ParameterizedTypeName setOfClassOfWildcardOfObject =
      ParameterizedTypeName.get(ClassName.get(Set.class), classOfWildcardOfObjet);
  ParameterizedTypeName hashSetOfClassOfWildcardOfObject =
      ParameterizedTypeName.get(ClassName.get(HashSet.class), classOfWildcardOfObjet);
  MethodSpec.Builder builder = MethodSpec.methodBuilder("getExcludedModuleClasses")
      .addModifiers(Modifier.PUBLIC)
      .addAnnotation(Override.class)
      .returns(setOfClassOfWildcardOfObject);

  if (excludedClassNames.isEmpty()) {
    builder.addStatement("return $T.emptySet()", Collections.class);
  } else {
    builder.addStatement(
        "$T excludedClasses = new $T()", setOfClassOfWildcardOfObject,
        hashSetOfClassOfWildcardOfObject);
    for (String excludedClassName : excludedClassNames) {
      // TODO: Remove this when we no longer support manifest parsing.
      // Using a Literal ($L) instead of a type ($T) to get a fully qualified import that allows
      // us to suppress deprecation warnings. Aimed at deprecated GlideModules.
      builder.addStatement("excludedClasses.add($L.class)", excludedClassName);
    }
    builder.addStatement("return excludedClasses");
  }

  return builder.build();
}
 
Example 39
Project: GitHub   File: JsonObjectHolder.java   Source Code and License 5 votes vote down vote up
public TypeName getParameterizedParentTypeName() {
    if (parentUsedTypeParameters.size() > 0) {
        List<TypeName> usedParameters = new ArrayList<>();
        for (String parameter : parentUsedTypeParameters) {
            if (parameter.indexOf(".") > 0) {
                usedParameters.add(ClassName.bestGuess(parameter));
            } else {
                usedParameters.add(TypeVariableName.get(parameter));
            }
        }
        return ParameterizedTypeName.get((ClassName)parentTypeName, usedParameters.toArray(new TypeName[usedParameters.size()]));
    } else {
        return parentTypeName;
    }
}
 
Example 40
Project: Spyglass   File: GetDefaultMethodGenerator.java   Source Code and License 5 votes vote down vote up
@Override
public MethodSpec supplyFor(final AnnotationMirror anno) {
	final String enumClass = getLiteralFromAnnotation(anno, "enumClass");
	final String enumClassName = enumClass.substring(0, enumClass.lastIndexOf(".class"));

	final CodeBlock body = CodeBlock
			.builder()
			.addStatement("final int ordinal = $L", getLiteralFromAnnotation(anno, "ordinal"))
			.add("\n")
			.beginControlFlow(
					"if (ordinal < 0 || $1T.values().length - 1 < ordinal)",
					ClassName.bestGuess(enumClassName))
			.addStatement(
					"throw new $T($L)",
					RuntimeException.class,
					"\"Ordinal \" + ordinal + \" is out of bounds for enum " + enumClassName + "\"")
			.endControlFlow()
			.add("\n")
			.addStatement(
					"return $T.values()[ordinal]",
					ClassName.bestGuess(enumClassName))
			.build();

	return getBaseMethodSpec()
			.returns(ClassName.bestGuess(enumClassName))
			.addCode(body)
			.build();
}
 
Example 41
Project: limitjson   File: LJSONAnnotatedClass.java   Source Code and License 5 votes vote down vote up
public static void toWrite(ProcessorHelper helper, LJSONTypeElement ljsonElement, Filer filer) throws IOException {

        // create common ClassName
        ClassName thisObj = ClassName.bestGuess(ljsonElement.getTypeName());
        ClassName jsonObject = ClassName.get("org.json", "JSONObject");

        MethodSpec.Builder createMethod = MethodSpec.methodBuilder("create")
                .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                .returns(thisObj)
                .addParameter(ClassName.get(String.class), "json", Modifier.FINAL)
                .addParameter(TypeName.BOOLEAN, "allowNull", Modifier.FINAL)
                .addStatement("$T thisObj = new $T()", thisObj, thisObj)
                .beginControlFlow("try")
                .addStatement("$T root = new $T(json)", jsonObject, jsonObject);

        List<LIMITJSONVariable> ljsonVariableElements = ljsonElement.getVariableElements();
        addLJSONVariable(helper, createMethod, ljsonVariableElements);

        createMethod.nextControlFlow("catch (Exception e)")
                .beginControlFlow("if (allowNull)")
                .addStatement("return null")
                .endControlFlow()
                .endControlFlow();

        createMethod.addStatement("return thisObj");
        // generate whole class
        TypeSpec finderClass = TypeSpec.classBuilder(ljsonElement.getTypeName() + "$$CREATOR")
                .addModifiers(Modifier.PUBLIC)
//                .addSuperinterface(ParameterizedTypeName.get(ClassName.get(CORE_PACKAGE_NAME, "Core"), TypeName.get(classElement.asType())))
                .addMethod(createMethod.build())
//                .addMethod(parseIntentBuilder.build())
//                .addMethod(saveInstanceStateBuilder.build())
                .build();

        String packageName = ljsonElement.getTypePackageName();
        // generate file
        JavaFile.builder(packageName, finderClass).build().writeTo(filer);
    }
 
Example 42
Project: GankReader   File: OnceClickProcessor.java   Source Code and License 5 votes vote down vote up
private TypeSpec createPROXYType(ProxyInfo proxyInfo, MethodSpec... methodSpecs) {
    TypeSpec.Builder typeSpecBuilder = TypeSpec.classBuilder(proxyInfo.getProxyClassName())
            .addJavadoc("AutoCode by JuTao\n")
            .addField(TypeName.LONG, "intervalTime", Modifier.PUBLIC)
            .addSuperinterface(ParameterizedTypeName.get(ABSTRACTINJECTOR, ClassName.get(proxyInfo.getPackageName(), proxyInfo.getTargetClassName())));

    for (MethodSpec methodSpec : methodSpecs) {
        typeSpecBuilder.addMethod(methodSpec);
    }
    return typeSpecBuilder.build();
}
 
Example 43
Project: EgTest   File: ExceptionReader.java   Source Code and License 5 votes vote down vote up
private List<EgItem<?>> example(EgException a, ExecutableElement el, AnnotationMirror egExceptionMirror) {
    AnnotationValue value = getAnnotationValue(egExceptionMirror, "willThrow");
    final TypeName name;
    if (value == null) {
        name = ClassName.get(Throwable.class);
    }
    else {
        TypeMirror typeMirror = (TypeMirror)value.getValue();
        name = ClassName.get(typeMirror);
    }
    return Collections.singletonList(new ExceptionExample(el, a, name));
}
 
Example 44
Project: Spyglass   File: TestGetDefaultMethodGenerator.java   Source Code and License 5 votes vote down vote up
@Test
public void testGenerateFor_defaultToBooleanResourceAnnotationSupplied() {
	final Element element = avatarRule.getElementWithUniqueId("boolean resource");
	final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(
			element,
			DefaultToBooleanResource.class);

	final MethodSpec generatedMethod = generator.generateFor(mirror);

	assertThat(generatedMethod, is(notNullValue()));
	checkMethodSignature(generatedMethod, ClassName.BOOLEAN.box());
	checkCompiles(generatedMethod);
}
 
Example 45
Project: Spyglass   File: TestGetPlaceholderMethodGenerator.java   Source Code and License 5 votes vote down vote up
@Test
public void testGenerateFor_parameterWithUseInt() {
	final VariableElement parameter = avatarRule.getElementWithUniqueId("int");
	final AnnotationMirror useAnnotation = UseAnnoRetriever.getAnnotation(parameter);

	final MethodSpec generatedMethod = generator.generateFor(useAnnotation, 0);

	checkSignature(generatedMethod, ClassName.get(Number.class));
	checkCompiles(generatedMethod);
}
 
Example 46
Project: immu   File: ImmuClasser.java   Source Code and License 5 votes vote down vote up
/**
 * Returns the class name for the immutable implementation object.
 * @return the name, never null
 */
public final ClassName objectClass() {
  return ClassName.get(className.packageName(),
      "Immutable" + className.simpleNames()
        .stream()
        .collect(Collectors.joining()));
}
 
Example 47
Project: RxRetroJsoup   File: RetroJsoupProcessor.java   Source Code and License 5 votes vote down vote up
private void processSelect(Element element) {
    final ClassName classFullName = ClassName.get((TypeElement) element); //com.github.florent37.sample.TutoAndroidFrance
    final String className = element.getSimpleName().toString(); //TutoAndroidFrance

    final SelectHolder selectHolder = new SelectHolder(element, classFullName, className);

    final List<Element> methods = getMethods(element);
    for (Element method : methods) {
        selectHolder.addMethod(method);
    }

    selectHolders.put(classFullName, selectHolder);
}
 
Example 48
Project: KiiAnnotation   File: ConstructorGenerator.java   Source Code and License 5 votes vote down vote up
public static MethodSpec constructorGroup(String name) {
    ClassName className = ClassName.get("com.kii.cloud.storage", "KiiGroup");
    ParameterSpec parameterSpec = ParameterSpec.builder(className, "kiiGroup").build();

    return MethodSpec
            .constructorBuilder()
            .addModifiers(Modifier.PRIVATE)
            .addParameter(parameterSpec)
            .addStatement("this.kiiObject = kiiGroup.bucket(\"$N\").object()", name)
            .build();
}
 
Example 49
Project: easy-plugins   File: UserMarkerAnnotation.java   Source Code and License 5 votes vote down vote up
public TypeName getServiceInterfaceTypeName() {

        int paramCount = serviceParentType.getTypeParameters().size();
        if (paramCount > 0) {
            TypeName[] params = new TypeName[paramCount];
            for (int i = 0; i < paramCount; i++) {
                params[i] = Util.wildcardType();
            }

            return ParameterizedTypeName.get(ClassName.get(serviceParentType), params);
        } else {
            return TypeName.get(serviceParentType.asType());
        }
    }
 
Example 50
Project: vulture   File: TypeUtils.java   Source Code and License 5 votes vote down vote up
public static String getPrimitiveArrayClassName(Element element) {
    if (element.asType().getKind() != TypeKind.ARRAY) {
        throw new IllegalArgumentException("element is not array: " + element.toString());
    }

    ArrayType arrayType = (ArrayType) element.asType();
    TypeMirror componentType = arrayType.getComponentType();
    ClassName className = (ClassName) TypeName.get(componentType).box();
    return className.simpleName() + "Array";
}
 
Example 51
Project: ActivityBuilder   File: BuilderGenerator.java   Source Code and License 5 votes vote down vote up
private MethodSpec buildGetConsumer() {
  TypeName consumerType = ParameterizedTypeName.get(
      ClassName.get(targetPackage.getQualifiedName().toString(), consumer.name),
      TypeVariableName.get("A"));

  return MethodSpec.methodBuilder("getConsumer")
      .addAnnotation(Override.class)
      .addModifiers(Modifier.PROTECTED)
      .returns(consumerType)
      .beginControlFlow("if($L == null)", "consumer")
      .addStatement("$L = new $L<>()", "consumer", consumer.name)
      .endControlFlow()
      .addStatement("return ($T) $L", consumerType, "consumer").build();
}
 
Example 52
Project: json-log-domain   File: MarkerGenerator.java   Source Code and License 5 votes vote down vote up
public static JavaFile markerBuilder(Domain ontology) {
	List<Key> keys = ontology.getKeys();
	
	ClassName name = ClassName.get(ontology.getTargetPackage(), ontology.getName()+ MARKER_BUILDER);
	
	Builder builder = TypeSpec.classBuilder(name)
				.addJavadoc(composeJavadoc(ontology, name))
				.addModifiers(Modifier.PUBLIC);
			
	ClassName markerName = getName(ontology);
	
	for(Key key : keys) {
		builder.addMethod(getBuilderMethod(markerName, key));
	}
	
	if(ontology.hasTags()) {
		ClassName tagsName = TagGenerator.getName(ontology);
		
		ParameterSpec parameter = ParameterSpec.builder(ArrayTypeName.of(tagsName), "value").build();
		
		builder.addMethod(MethodSpec.methodBuilder("tags")
				.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
				.addParameter(parameter).varargs()
				.addStatement("$T marker = new $T()", markerName, markerName)
				.addStatement("marker.tags($N)", parameter)
				.returns(markerName)
				.addStatement("return marker")
				.build());
		
	}
	
	return JavaFile.builder(name.packageName(), builder.build()).build();
}
 
Example 53
Project: GitHub   File: RequestManagerGenerator.java   Source Code and License 5 votes vote down vote up
private MethodSpec generateRequestManagerRequestManagerMethodOverride(
    String generatedPackageName, ExecutableElement method) {
  ClassName generatedRequestManagerName =
      ClassName.get(generatedPackageName, GENERATED_REQUEST_MANAGER_SIMPLE_NAME);
  return ProcessorUtil.overriding(method)
      .returns(generatedRequestManagerName)
      .addCode(ProcessorUtil.generateCastingSuperCall(generatedRequestManagerName, method))
      .build();
}
 
Example 54
Project: aws-sdk-java-v2   File: SyncClientInterface.java   Source Code and License 5 votes vote down vote up
private MethodSpec paginatedSimpleMethod(OperationModel opModel) {
    String paginatedMethodName = PaginatorUtils.getSyncMethodName(opModel.getMethodName());
    ClassName requestType = ClassName.get(model.getMetadata().getFullModelPackageName(),
                                          opModel.getInput().getVariableType());

    return operationSimpleMethodSignature(model, opModel, paginatedMethodName)
            .returns(poetExtensions.getResponseClassForPaginatedSyncOperation(opModel.getOperationName()))
            .addStatement("return $L($T.builder().build())", paginatedMethodName, requestType)
            .addJavadoc(opModel.getDocs(model, ClientType.SYNC, SimpleMethodOverload.NO_ARG_PAGINATED))
            .build();
}
 
Example 55
Project: Spyglass   File: CallerDef.java   Source Code and License 5 votes vote down vote up
public static TypeSpec.Builder getNewAnonymousCallerPrototype(
		final TypeName targetType,
		final CodeBlock targetParameter,
		final CodeBlock contextParameter,
		final CodeBlock attrsParameter) {

	final ClassName genericCaller = CallerDef.getCallerAsClassName();
	final TypeName specificCaller = ParameterizedTypeName.get(genericCaller, targetType);

	return TypeSpec
			.anonymousClassBuilder(
					CodeBlock.of("$L, $L, $L", targetParameter, contextParameter, attrsParameter).toString())
			.addSuperinterface(specificCaller);
}
 
Example 56
Project: remoter   File: ClassBuilder.java   Source Code and License 5 votes vote down vote up
public JavaFile.Builder buildStubClass() {
    ClassName stubClassName = getStubClassName();

    TypeSpec.Builder stubClassBuilder = TypeSpec
            .classBuilder(stubClassName.simpleName())
            .addModifiers(Modifier.PUBLIC)
            .superclass(TypeName.get(getBindingManager().getType("android.os.Binder")));

    for (TypeParameterElement typeParameterElement : ((TypeElement) getRemoterInterfaceElement()).getTypeParameters()) {
        stubClassBuilder.addTypeVariable(TypeVariableName.get(typeParameterElement.toString()));
    }


    //constructor
    stubClassBuilder.addMethod(MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PUBLIC)
            .addJavadoc("Initialize this {@link " + getStubClassName().simpleName() + "} with the given {@link " + getRemoterInterfaceClassName() + "} implementation \n\n")
            .addJavadoc("@param serviceImpl An implementation of {@link " + getRemoterInterfaceClassName() + "}\n")
            .addParameter(TypeName.get(getRemoterInterfaceElement().asType()), "serviceImpl")
            .addStatement("this.serviceImpl = serviceImpl")
            .beginControlFlow("this.attachInterface(new $T()", ClassName.get("android.os", "IInterface"))
            .beginControlFlow("public $T asBinder()", ClassName.get("android.os", "IBinder"))
            .addStatement("return " + stubClassName.simpleName() + ".this")
            .endControlFlow()
            .endControlFlow()
            .addStatement(", DESCRIPTOR)")
            .build());


    getBindingManager().getFieldBuilder(getRemoterInterfaceElement()).addStubFields(stubClassBuilder);
    getBindingManager().getMethoddBuilder(getRemoterInterfaceElement()).addStubMethods(stubClassBuilder);

    stubClassBuilder.addJavadoc("Wraps a {@link " + getRemoterInterfaceClassName() + "} implementation and expose it as a remote {@link IBinder}\n");
    stubClassBuilder.addJavadoc("<p>\n");
    stubClassBuilder.addJavadoc("Autogenerated by <a href=\"https://bit.ly/Remoter\">Remoter</a>\n");
    stubClassBuilder.addJavadoc("@see " + getProxyClassName().simpleName() + "\n");

    return JavaFile.builder(stubClassName.packageName(), stubClassBuilder.build());
}
 
Example 57
Project: json-log-domain   File: TagGenerator.java   Source Code and License 5 votes vote down vote up
private static String composeJavadoc(Domain ontology, ClassName name) {
	StringBuilder builder = new StringBuilder();
	
	builder.append(ontology.getName());
	builder.append(" tags.");
	if(ontology.getDescription() != null) {
		builder.append("<br/>\n");
		builder.append(ontology.getDescription());
	}
	builder.append("\n");
	builder.append("\n");

	return builder.toString();
}
 
Example 58
Project: aws-sdk-java-v2   File: JsonProtocolSpec.java   Source Code and License 5 votes vote down vote up
@Override
public CodeBlock executionHandler(OperationModel opModel) {
    TypeName responseType = poetExtensions.getModelClass(opModel.getReturnType().getReturnType());
    ClassName requestType = poetExtensions.getModelClass(opModel.getInput().getVariableType());
    ClassName marshaller = poetExtensions.getRequestTransformClass(opModel.getInputShape().getShapeName() + "Marshaller");

    final CodeBlock.Builder codeBlock = CodeBlock
            .builder()
            .add("\n\nreturn clientHandler.execute(new $T<$T, $T>()\n" +
                 ".withResponseHandler($N)\n" +
                 ".withErrorResponseHandler($N)\n" +
                 ".withInput($L)\n",
                 ClientExecutionParams.class,
                 requestType,
                 responseType,
                 "responseHandler",
                 "errorResponseHandler",
                 opModel.getInput().getVariableName());

    if (opModel.hasStreamingInput()) {
        return codeBlock.add(".withMarshaller(new $T(new $T(protocolFactory), requestBody)));",
                             ParameterizedTypeName.get(ClassName.get(StreamingRequestMarshaller.class), requestType),
                             marshaller)
                        .build();
    }

    return codeBlock.add(".withMarshaller(new $T(protocolFactory))$L);", marshaller,
                         opModel.hasStreamingOutput() ? ", streamingResponseHandler" : "")
                    .build();
}
 
Example 59
Project: javabard   File: BuilderSpec.java   Source Code and License 5 votes vote down vote up
static MethodSpec builderSetter(ClassName builderName, FieldSpec field) {
    return MethodSpec.methodBuilder(field.name)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .returns(builderName)
            .addJavadoc(field.javadoc)
            .addParameter(field.type, "value")
            .addStatement("this.$N = value", field.name)
            .addStatement("return this")
            .build();
}
 
Example 60
Project: KiiAnnotation   File: ConstructorGenerator.java   Source Code and License 5 votes vote down vote up
public static MethodSpec constructorCreate(ClassName className) {
    return MethodSpec
            .methodBuilder("create")
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
            .addStatement("return new $L()", className)
            .returns(className)
            .build();
}