use of com.squareup.javapoet.ParameterSpec 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);
}
use of com.squareup.javapoet.ParameterSpec in project epoxy by airbnb.
the class ProcessorUtils method areParamsTheSame.
private static boolean areParamsTheSame(ExecutableElement method1, MethodSpec method2) {
List<? extends VariableElement> params1 = method1.getParameters();
List<ParameterSpec> params2 = method2.parameters;
if (params1.size() != params2.size()) {
return false;
}
for (int i = 0; i < params1.size(); i++) {
VariableElement param1 = params1.get(i);
ParameterSpec param2 = params2.get(i);
if (!TypeName.get(param1.asType()).equals(param2.type)) {
return false;
}
}
return true;
}
use of com.squareup.javapoet.ParameterSpec in project EasyRouter by Xiasm.
the class RouterProcessor method generatedRoot.
/**
* 生成Root类 作用:记录<分组,对应的Group类>
* @param iRouteRoot
* @param iRouteGroup
*/
private void generatedRoot(TypeElement iRouteRoot, TypeElement iRouteGroup) {
// 创建参数类型 Map<String,Class<? extends IRouteGroup>> routes>
// Wildcard 通配符
ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName.get(ClassName.get(Map.class), ClassName.get(String.class), ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(ClassName.get(iRouteGroup))));
// 参数 Map<String,Class<? extends IRouteGroup>> routes> routes
ParameterSpec parameter = ParameterSpec.builder(parameterizedTypeName, "routes").build();
// 函数 public void loadInfo(Map<String,Class<? extends IRouteGroup>> routes> routes)
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(Constant.METHOD_LOAD_INTO).addModifiers(Modifier.PUBLIC).addAnnotation(Override.class).addParameter(parameter);
// 函数体
for (Map.Entry<String, String> entry : rootMap.entrySet()) {
methodBuilder.addStatement("routes.put($S, $T.class)", entry.getKey(), ClassName.get(Constant.PACKAGE_OF_GENERATE_FILE, entry.getValue()));
}
// 生成$Root$类
String className = Constant.NAME_OF_ROOT + moduleName;
TypeSpec typeSpec = TypeSpec.classBuilder(className).addSuperinterface(ClassName.get(iRouteRoot)).addModifiers(Modifier.PUBLIC).addMethod(methodBuilder.build()).build();
try {
JavaFile.builder(Constant.PACKAGE_OF_GENERATE_FILE, typeSpec).build().writeTo(filerUtils);
log.i("Generated RouteRoot:" + Constant.PACKAGE_OF_GENERATE_FILE + "." + className);
} catch (IOException e) {
e.printStackTrace();
}
}
use of com.squareup.javapoet.ParameterSpec in project glide by bumptech.
the class GlideGenerator method overrideGlideWithMethod.
private MethodSpec overrideGlideWithMethod(String packageName, TypeSpec generatedRequestManager, ExecutableElement methodToOverride) {
ClassName generatedRequestManagerClassName = ClassName.get(packageName, generatedRequestManager.name);
List<ParameterSpec> parameters = ProcessorUtil.getParameters(methodToOverride);
Preconditions.checkArgument(parameters.size() == 1, "Expected size of 1, but got %s", methodToOverride);
ParameterSpec parameter = parameters.iterator().next();
Builder builder = MethodSpec.methodBuilder(methodToOverride.getSimpleName().toString()).addModifiers(Modifier.PUBLIC, Modifier.STATIC).addJavadoc(processorUtil.generateSeeMethodJavadoc(methodToOverride)).addParameters(parameters).returns(generatedRequestManagerClassName).addStatement("return ($T) $T.$N($L)", generatedRequestManagerClassName, glideType, methodToOverride.getSimpleName().toString(), parameter.name);
return addReturnAnnotations(builder, methodToOverride).build();
}
use of com.squareup.javapoet.ParameterSpec in project glide by bumptech.
the class GlideGenerator method overrideGlideStaticMethod.
private MethodSpec overrideGlideStaticMethod(ExecutableElement methodToOverride) {
List<ParameterSpec> parameters = ProcessorUtil.getParameters(methodToOverride);
TypeElement element = (TypeElement) processingEnv.getTypeUtils().asElement(methodToOverride.getReturnType());
MethodSpec.Builder builder = MethodSpec.methodBuilder(methodToOverride.getSimpleName().toString()).addModifiers(Modifier.PUBLIC, Modifier.STATIC).addJavadoc(processorUtil.generateSeeMethodJavadoc(methodToOverride)).addParameters(parameters);
addReturnAnnotations(builder, methodToOverride);
boolean returnsValue = element != null;
if (returnsValue) {
builder.returns(ClassName.get(element));
}
StringBuilder code = new StringBuilder(returnsValue ? "return " : "");
code.append("$T.$N(");
List<Object> args = new ArrayList<>();
args.add(ClassName.get(glideType));
args.add(methodToOverride.getSimpleName());
if (!parameters.isEmpty()) {
for (ParameterSpec param : parameters) {
code.append("$L, ");
args.add(param.name);
}
code = new StringBuilder(code.substring(0, code.length() - 2));
}
code.append(")");
builder.addStatement(code.toString(), args.toArray(new Object[0]));
return builder.build();
}
Aggregations