Search in sources :

Example 1 with TypeSpec

use of com.squareup.javapoet.TypeSpec in project DeepLinkDispatch by airbnb.

the class DeepLinkProcessor method generateDeepLinkDelegate.

private void generateDeepLinkDelegate(String packageName, List<TypeElement> loaderClasses) throws IOException {
    MethodSpec notifyListenerMethod = MethodSpec.methodBuilder("notifyListener").addModifiers(Modifier.PRIVATE, Modifier.STATIC).returns(void.class).addParameter(ANDROID_CONTEXT, "context").addParameter(boolean.class, "isError").addParameter(ClassName.get("android.net", "Uri"), "uri").addParameter(String.class, "errorMessage").addStatement("$T intent = new Intent()", ANDROID_INTENT).addStatement("intent.setAction($T.ACTION)", DeepLinkHandler.class).addStatement("intent.putExtra($T.EXTRA_URI, uri != null ? uri.toString() : $S)", DeepLinkHandler.class, "").addStatement("intent.putExtra($T.EXTRA_SUCCESSFUL, !isError)", DeepLinkHandler.class).beginControlFlow("if (isError)").addStatement("intent.putExtra($T.EXTRA_ERROR_MESSAGE, errorMessage)", DeepLinkHandler.class).endControlFlow().addStatement("$T.getInstance(context).sendBroadcast(intent)", ClassName.get("android.support.v4.content", "LocalBroadcastManager")).build();
    ClassName deepLinkResult = ClassName.get(DLD_PACKAGE_NAME, "DeepLinkResult");
    MethodSpec createResultAndNotifyMethod = MethodSpec.methodBuilder("createResultAndNotify").addModifiers(Modifier.PRIVATE, Modifier.STATIC).returns(deepLinkResult).addParameter(ANDROID_CONTEXT, "context").addParameter(TypeName.BOOLEAN, "successful", Modifier.FINAL).addParameter(ANDROID_URI, "uri", Modifier.FINAL).addParameter(ClassName.get(String.class), "error", Modifier.FINAL).addStatement("notifyListener(context, !successful, uri, error)").addStatement("return new $T(successful, uri != null ? uri.toString() : null, error)", deepLinkResult).build();
    FieldSpec tag = FieldSpec.builder(String.class, "TAG", Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL).initializer("DeepLinkDelegate.class.getSimpleName()").build();
    FieldSpec loaders = FieldSpec.builder(ParameterizedTypeName.get(ClassName.get(List.class), WildcardTypeName.subtypeOf(Parser.class)), "loaders", Modifier.PRIVATE, Modifier.FINAL).build();
    CodeBlock.Builder loadersInitializer = CodeBlock.builder().add("this.loaders = $T.asList(\n", ClassName.get(Arrays.class)).indent();
    int totalElements = loaderClasses.size();
    for (int i = 0; i < totalElements; i++) {
        loadersInitializer.add("$L$L", decapitalize(moduleNameToLoaderName(loaderClasses.get(i))), i < totalElements - 1 ? "," : "");
    }
    MethodSpec constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addParameters(FluentIterable.from(loaderClasses).transform(new Function<TypeElement, ParameterSpec>() {

        @Override
        public ParameterSpec apply(TypeElement typeElement) {
            return ParameterSpec.builder(moduleElementToLoaderClassName(typeElement), decapitalize(moduleNameToLoaderName(typeElement))).build();
        }
    }).toList()).addCode(loadersInitializer.unindent().add(");\n").build()).build();
    MethodSpec supportsUri = MethodSpec.methodBuilder("supportsUri").addModifiers(Modifier.PUBLIC).returns(TypeName.BOOLEAN).addParameter(String.class, "uriString").addStatement("return findEntry(uriString) != null").build();
    MethodSpec findEntry = MethodSpec.methodBuilder("findEntry").addModifiers(Modifier.PRIVATE).returns(CLASS_DLD_ENTRY).addParameter(String.class, "uriString").beginControlFlow("for (Parser loader : loaders)").addStatement("$T entry = loader.parseUri(uriString)", CLASS_DLD_ENTRY).beginControlFlow("if (entry != null)").addStatement("return entry").endControlFlow().endControlFlow().addStatement("return null").build();
    MethodSpec dispatchFromMethod = MethodSpec.methodBuilder("dispatchFrom").addModifiers(Modifier.PUBLIC).returns(deepLinkResult).addParameter(ANDROID_ACTIVITY, "activity").beginControlFlow("if (activity == null)").addStatement("throw new $T($S)", NullPointerException.class, "activity == null").endControlFlow().addStatement("return dispatchFrom(activity, activity.getIntent())").build();
    MethodSpec dispatchFromMethodWithIntent = MethodSpec.methodBuilder("dispatchFrom").addModifiers(Modifier.PUBLIC).returns(deepLinkResult).addParameter(ANDROID_ACTIVITY, "activity").addParameter(ANDROID_INTENT, "sourceIntent").beginControlFlow("if (activity == null)").addStatement("throw new $T($S)", NullPointerException.class, "activity == null").endControlFlow().beginControlFlow("if (sourceIntent == null)").addStatement("throw new $T($S)", NullPointerException.class, "sourceIntent == null").endControlFlow().addStatement("$T uri = sourceIntent.getData()", ANDROID_URI).beginControlFlow("if (uri == null)").addStatement("return createResultAndNotify(activity, false, null, $S)", "No Uri in given activity's intent.").endControlFlow().addStatement("String uriString = uri.toString()").addStatement("$T entry = findEntry(uriString)", CLASS_DLD_ENTRY).beginControlFlow("if (entry != null)").addStatement("$T deepLinkUri = DeepLinkUri.parse(uriString)", CLASS_DLD_URI).addStatement("$T<String, String> parameterMap = entry.getParameters(uriString)", Map.class).beginControlFlow("for (String queryParameter : deepLinkUri.queryParameterNames())").beginControlFlow("for (String queryParameterValue : deepLinkUri.queryParameterValues(queryParameter))").beginControlFlow("if (parameterMap.containsKey(queryParameter))").addStatement("$T.w(TAG, \"Duplicate parameter name in path and query param: \" + queryParameter)", ClassName.get("android.util", "Log")).endControlFlow().addStatement("parameterMap.put(queryParameter, queryParameterValue)").endControlFlow().endControlFlow().addStatement("parameterMap.put($T.URI, uri.toString())", ClassName.get(DLD_PACKAGE_NAME, "DeepLink")).addStatement("$T parameters", ANDROID_BUNDLE).beginControlFlow("if (sourceIntent.getExtras() != null)").addStatement("parameters = new Bundle(sourceIntent.getExtras())").nextControlFlow("else").addStatement("parameters = new Bundle()").endControlFlow().beginControlFlow("for (Map.Entry<String, String> parameterEntry : parameterMap.entrySet())").addStatement("parameters.putString(parameterEntry.getKey(), parameterEntry.getValue())").endControlFlow().beginControlFlow("try").addStatement("Class<?> c = entry.getActivityClass()").addStatement("$T newIntent", ANDROID_INTENT).addStatement("$T taskStackBuilder = null", TASK_STACK_BUILDER).beginControlFlow("if (entry.getType() == DeepLinkEntry.Type.CLASS)").addStatement("newIntent = new Intent(activity, c)").nextControlFlow("else").addStatement("$T method", Method.class).beginControlFlow("try").addStatement("method = c.getMethod(entry.getMethod(), $T.class)", ANDROID_CONTEXT).beginControlFlow("if (method.getReturnType().equals($T.class))", TASK_STACK_BUILDER).addStatement("taskStackBuilder = (TaskStackBuilder) method.invoke(c, activity)").beginControlFlow("if (taskStackBuilder.getIntentCount() == 0)").addStatement("return createResultAndNotify(activity, false, uri, \"Could not deep " + "link to method: \" + entry.getMethod() + \" intents length == 0\" )").endControlFlow().addStatement("newIntent = taskStackBuilder." + "editIntentAt(taskStackBuilder.getIntentCount()-1)").nextControlFlow("else").addStatement("newIntent = (Intent) method.invoke(c, activity)").endControlFlow().nextControlFlow("catch ($T exception)", NoSuchMethodException.class).addStatement("method = c.getMethod(entry.getMethod(), $T.class, $T.class)", ANDROID_CONTEXT, ANDROID_BUNDLE).beginControlFlow("if (method.getReturnType().equals($T.class))", TASK_STACK_BUILDER).addStatement("taskStackBuilder = " + "(TaskStackBuilder) method.invoke(c, activity, parameters)").beginControlFlow("if (taskStackBuilder.getIntentCount() == 0)").addStatement("return createResultAndNotify(activity, false, uri, \"Could not deep " + "link to method: \" + entry.getMethod() + \" intents length == 0\" )").endControlFlow().addStatement("newIntent = taskStackBuilder." + "editIntentAt(taskStackBuilder.getIntentCount()-1)").nextControlFlow("else").addStatement("newIntent = (Intent) method.invoke(c, activity, parameters)").endControlFlow().endControlFlow().endControlFlow().beginControlFlow("if (newIntent.getAction() == null)").addStatement("newIntent.setAction(sourceIntent.getAction())").endControlFlow().beginControlFlow("if (newIntent.getData() == null)").addStatement("newIntent.setData(sourceIntent.getData())").endControlFlow().addStatement("newIntent.putExtras(parameters)").addStatement("newIntent.putExtra(DeepLink.IS_DEEP_LINK, true)").addStatement("newIntent.putExtra(DeepLink.REFERRER_URI, uri)").beginControlFlow("if (activity.getCallingActivity() != null)").addStatement("newIntent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT)").endControlFlow().beginControlFlow("if (taskStackBuilder != null)").addStatement("taskStackBuilder.startActivities()").nextControlFlow("else").addStatement("activity.startActivity(newIntent)").endControlFlow().addStatement("return createResultAndNotify(activity, true, uri, null)").nextControlFlow("catch (NoSuchMethodException exception)").addStatement("return createResultAndNotify(activity, false, uri, \"Deep link to " + "non-existent method: \" + entry.getMethod())").nextControlFlow("catch (IllegalAccessException exception)").addStatement("return createResultAndNotify(activity, false, uri, \"Could not deep " + "link to method: \" + entry.getMethod())").nextControlFlow("catch ($T  exception)", InvocationTargetException.class).addStatement("return createResultAndNotify(activity, false, uri, \"Could not deep " + "link to method: \" + entry.getMethod())").endControlFlow().nextControlFlow("else").addStatement("return createResultAndNotify(activity, false, uri, " + "\"No registered entity to handle deep link: \" + uri.toString())").endControlFlow().build();
    TypeSpec deepLinkDelegate = TypeSpec.classBuilder("DeepLinkDelegate").addModifiers(Modifier.PUBLIC, Modifier.FINAL).addField(tag).addField(loaders).addMethod(constructor).addMethod(findEntry).addMethod(dispatchFromMethod).addMethod(dispatchFromMethodWithIntent).addMethod(createResultAndNotifyMethod).addMethod(notifyListenerMethod).addMethod(supportsUri).build();
    JavaFile.builder(packageName, deepLinkDelegate).build().writeTo(filer);
}
Also used : MethodSpec(com.squareup.javapoet.MethodSpec) ParameterSpec(com.squareup.javapoet.ParameterSpec) TypeElement(javax.lang.model.element.TypeElement) CodeBlock(com.squareup.javapoet.CodeBlock) Method(java.lang.reflect.Method) FieldSpec(com.squareup.javapoet.FieldSpec) ClassName(com.squareup.javapoet.ClassName) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) HashMap(java.util.HashMap) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 2 with TypeSpec

use of com.squareup.javapoet.TypeSpec in project epoxy by airbnb.

the class EpoxyProcessor method generateClassForModel.

private void generateClassForModel(ClassToGenerateInfo info) throws IOException {
    if (!info.shouldGenerateSubClass()) {
        return;
    }
    TypeSpec generatedClass = TypeSpec.classBuilder(info.getGeneratedName()).addJavadoc("Generated file. Do not modify!").addModifiers(Modifier.PUBLIC).superclass(info.getOriginalClassName()).addTypeVariables(info.getTypeVariables()).addMethods(generateConstructors(info)).addMethods(generateSettersAndGetters(info)).addMethods(generateMethodsReturningClassType(info)).addMethods(generateDefaultMethodImplementations(info)).addMethod(generateReset(info)).addMethod(generateEquals(info)).addMethod(generateHashCode(info)).addMethod(generateToString(info)).build();
    JavaFile.builder(info.getGeneratedName().packageName(), generatedClass).build().writeTo(filer);
}
Also used : TypeSpec(com.squareup.javapoet.TypeSpec)

Example 3 with TypeSpec

use of com.squareup.javapoet.TypeSpec in project storio by pushtorefresh.

the class DeleteResolverGenerator method generateJavaFile.

@NotNull
public JavaFile generateJavaFile(@NotNull final StorIOContentResolverTypeMeta storIOContentResolverTypeMeta) {
    final ClassName storIOContentResolverTypeClassName = ClassName.get(storIOContentResolverTypeMeta.packageName, storIOContentResolverTypeMeta.simpleName);
    final TypeSpec deleteResolver = TypeSpec.classBuilder(generateName(storIOContentResolverTypeMeta)).addJavadoc("Generated resolver for Delete Operation\n").addModifiers(PUBLIC).superclass(ParameterizedTypeName.get(ClassName.get("com.pushtorefresh.storio.contentresolver.operations.delete", "DefaultDeleteResolver"), storIOContentResolverTypeClassName)).addMethod(createMapToDeleteQueryMethodSpec(storIOContentResolverTypeMeta, storIOContentResolverTypeClassName)).build();
    return JavaFile.builder(storIOContentResolverTypeMeta.packageName, deleteResolver).indent(INDENT).build();
}
Also used : ClassName(com.squareup.javapoet.ClassName) TypeSpec(com.squareup.javapoet.TypeSpec) NotNull(org.jetbrains.annotations.NotNull)

Example 4 with TypeSpec

use of com.squareup.javapoet.TypeSpec in project storio by pushtorefresh.

the class MappingGenerator method generateJavaFile.

@NotNull
@Override
public JavaFile generateJavaFile(@NotNull StorIOContentResolverTypeMeta storIOSQLiteTypeMeta) {
    final ClassName storIOSQLiteTypeClassName = ClassName.get(storIOSQLiteTypeMeta.packageName, storIOSQLiteTypeMeta.simpleName);
    ClassName superclass = ClassName.get("com.pushtorefresh.storio.contentresolver", SUFFIX);
    ParameterizedTypeName superclassParametrized = ParameterizedTypeName.get(superclass, storIOSQLiteTypeClassName);
    final TypeSpec mapping = TypeSpec.classBuilder(storIOSQLiteTypeMeta.simpleName + SUFFIX).addJavadoc("Generated mapping with collection of resolvers\n").addModifiers(PUBLIC).superclass(superclassParametrized).addMethod(createConstructor(storIOSQLiteTypeMeta)).build();
    return JavaFile.builder(storIOSQLiteTypeMeta.packageName, mapping).indent(INDENT).build();
}
Also used : ClassName(com.squareup.javapoet.ClassName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeSpec(com.squareup.javapoet.TypeSpec) NotNull(org.jetbrains.annotations.NotNull)

Example 5 with TypeSpec

use of com.squareup.javapoet.TypeSpec in project storio by pushtorefresh.

the class DeleteResolverGenerator method generateJavaFile.

@NotNull
public JavaFile generateJavaFile(@NotNull StorIOSQLiteTypeMeta storIOSQLiteTypeMeta) {
    final ClassName storIOSQLiteTypeClassName = ClassName.get(storIOSQLiteTypeMeta.packageName, storIOSQLiteTypeMeta.simpleName);
    final TypeSpec deleteResolver = TypeSpec.classBuilder(generateName(storIOSQLiteTypeMeta)).addJavadoc("Generated resolver for Delete Operation.\n").addModifiers(PUBLIC).superclass(ParameterizedTypeName.get(ClassName.get("com.pushtorefresh.storio.sqlite.operations.delete", "DefaultDeleteResolver"), storIOSQLiteTypeClassName)).addMethod(createMapToDeleteQueryMethodSpec(storIOSQLiteTypeMeta, storIOSQLiteTypeClassName)).build();
    return JavaFile.builder(storIOSQLiteTypeMeta.packageName, deleteResolver).indent(INDENT).build();
}
Also used : ClassName(com.squareup.javapoet.ClassName) TypeSpec(com.squareup.javapoet.TypeSpec) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

TypeSpec (com.squareup.javapoet.TypeSpec)44 ClassName (com.squareup.javapoet.ClassName)26 MethodSpec (com.squareup.javapoet.MethodSpec)20 ParameterizedTypeName (com.squareup.javapoet.ParameterizedTypeName)10 TypeName (com.squareup.javapoet.TypeName)8 NotNull (org.jetbrains.annotations.NotNull)8 FieldSpec (com.squareup.javapoet.FieldSpec)7 ArrayList (java.util.ArrayList)6 Type (com.squareup.wire.schema.Type)5 TypeElement (javax.lang.model.element.TypeElement)5 ByteString (okio.ByteString)5 WireField (com.squareup.wire.WireField)4 JavaGenerator (com.squareup.wire.java.JavaGenerator)4 Field (com.squareup.wire.schema.Field)4 MessageType (com.squareup.wire.schema.MessageType)4 ProtoType (com.squareup.wire.schema.ProtoType)4 Schema (com.squareup.wire.schema.Schema)4 CodeBlock (com.squareup.javapoet.CodeBlock)3 EnclosingType (com.squareup.wire.schema.EnclosingType)3 EnumType (com.squareup.wire.schema.EnumType)3