use of com.google.api.generator.engine.ast.Statement in project gapic-generator-java by googleapis.
the class AbstractTransportServiceStubClassComposer method createConstructorMethods.
protected List<MethodDefinition> createConstructorMethods(GapicContext context, Service service, TypeStore typeStore, Map<String, VariableExpr> classMemberVarExprs, Map<String, VariableExpr> callableClassMemberVarExprs, Map<String, VariableExpr> protoMethodNameToDescriptorVarExprs, List<Statement> classStatements) {
TypeNode stubSettingsType = typeStore.get(getTransportContext().classNames().getServiceStubSettingsClassName(service));
VariableExpr settingsVarExpr = VariableExpr.withVariable(Variable.builder().setName("settings").setType(stubSettingsType).build());
TypeNode clientContextType = FIXED_TYPESTORE.get("ClientContext");
VariableExpr clientContextVarExpr = VariableExpr.withVariable(Variable.builder().setName("clientContext").setType(clientContextType).build());
VariableExpr callableFactoryVarExpr = VariableExpr.withVariable(Variable.builder().setName("callableFactory").setType(getTransportContext().stubCallableFactoryType()).build());
TypeNode thisClassType = typeStore.get(getTransportContext().classNames().getTransportServiceStubClassName(service));
TypeNode ioExceptionType = TypeNode.withReference(ConcreteReference.withClazz(IOException.class));
BiFunction<List<VariableExpr>, List<Statement>, MethodDefinition> ctorMakerFn = (args, body) -> MethodDefinition.constructorBuilder().setScope(ScopeNode.PROTECTED).setReturnType(thisClassType).setHeaderCommentStatements(Arrays.asList(createProtectedCtorComment(service))).setArguments(args.stream().map(v -> v.toBuilder().setIsDecl(true).build()).collect(Collectors.toList())).setThrowsExceptions(Arrays.asList(ioExceptionType)).setBody(body).build();
// First constructor method.
MethodDefinition firstCtor = ctorMakerFn.apply(Arrays.asList(settingsVarExpr, clientContextVarExpr), Arrays.asList(ExprStatement.withExpr(ReferenceConstructorExpr.thisBuilder().setType(thisClassType).setArguments(settingsVarExpr, clientContextVarExpr, NewObjectExpr.builder().setType(typeStore.get(getTransportContext().classNames().getTransportServiceCallableFactoryClassName(service))).build()).build())));
Expr thisExpr = ValueExpr.withValue(ThisObjectValue.withType(typeStore.get(getTransportContext().classNames().getTransportServiceStubClassName(service))));
// Body of the second constructor method.
List<Statement> secondCtorStatements = new ArrayList<>();
List<Expr> secondCtorExprs = new ArrayList<>();
secondCtorExprs.add(AssignmentExpr.builder().setVariableExpr(classMemberVarExprs.get("callableFactory").toBuilder().setExprReferenceExpr(thisExpr).build()).setValueExpr(callableFactoryVarExpr).build());
VariableExpr operationsStubClassVarExpr = classMemberVarExprs.get(getTransportContext().transportOperationsStubNames().get(0));
// TODO: refactor this
if (generateOperationsStubLogic(service)) {
secondCtorExprs.addAll(createOperationsStubInitExpr(service, thisExpr, operationsStubClassVarExpr, clientContextVarExpr, callableFactoryVarExpr));
}
secondCtorStatements.addAll(secondCtorExprs.stream().map(ExprStatement::withExpr).collect(Collectors.toList()));
secondCtorExprs.clear();
secondCtorStatements.add(EMPTY_LINE_STATEMENT);
// Transport settings local variables.
Map<String, VariableExpr> javaStyleMethodNameToTransportSettingsVarExprs = service.methods().stream().collect(Collectors.toMap(m -> JavaStyle.toLowerCamelCase(m.name()), m -> VariableExpr.withVariable(Variable.builder().setName(String.format("%sTransportSettings", JavaStyle.toLowerCamelCase(m.name()))).setType(TypeNode.withReference(ConcreteReference.builder().setClazz(getTransportContext().callSettingsClass()).setGenerics(Arrays.asList(m.inputType().reference(), m.outputType().reference())).build())).build())));
secondCtorExprs.addAll(service.methods().stream().map(m -> createTransportSettingsInitExpr(m, javaStyleMethodNameToTransportSettingsVarExprs.get(JavaStyle.toLowerCamelCase(m.name())), protoMethodNameToDescriptorVarExprs.get(m.name()), classStatements)).collect(Collectors.toList()));
secondCtorStatements.addAll(secondCtorExprs.stream().map(ExprStatement::withExpr).collect(Collectors.toList()));
secondCtorExprs.clear();
secondCtorStatements.add(EMPTY_LINE_STATEMENT);
// Initialize <method>Callable variables.
secondCtorExprs.addAll(callableClassMemberVarExprs.entrySet().stream().map(e -> createCallableInitExpr(context, service, e.getKey(), e.getValue(), callableFactoryVarExpr, settingsVarExpr, clientContextVarExpr, operationsStubClassVarExpr, thisExpr, javaStyleMethodNameToTransportSettingsVarExprs)).collect(Collectors.toList()));
secondCtorStatements.addAll(secondCtorExprs.stream().map(ExprStatement::withExpr).collect(Collectors.toList()));
secondCtorExprs.clear();
secondCtorStatements.add(EMPTY_LINE_STATEMENT);
secondCtorStatements.addAll(createLongRunningClient(service, typeStore));
// Instantiate backgroundResources.
MethodInvocationExpr getBackgroundResourcesMethodExpr = MethodInvocationExpr.builder().setExprReferenceExpr(clientContextVarExpr).setMethodName("getBackgroundResources").build();
VariableExpr backgroundResourcesVarExpr = classMemberVarExprs.get("backgroundResources");
secondCtorExprs.add(AssignmentExpr.builder().setVariableExpr(backgroundResourcesVarExpr.toBuilder().setExprReferenceExpr(thisExpr).build()).setValueExpr(NewObjectExpr.builder().setType(FIXED_TYPESTORE.get("BackgroundResourceAggregation")).setArguments(Arrays.asList(getBackgroundResourcesMethodExpr)).build()).build());
secondCtorStatements.addAll(secondCtorExprs.stream().map(ExprStatement::withExpr).collect(Collectors.toList()));
secondCtorExprs.clear();
// Second constructor method.
MethodDefinition secondCtor = ctorMakerFn.apply(Arrays.asList(settingsVarExpr, clientContextVarExpr, callableFactoryVarExpr), secondCtorStatements);
return Arrays.asList(firstCtor, secondCtor);
}
use of com.google.api.generator.engine.ast.Statement in project gapic-generator-java by googleapis.
the class AbstractServiceClientClassComposer method createMethodVariants.
private static List<MethodDefinition> createMethodVariants(Method method, String clientName, Map<String, Message> messageTypes, TypeStore typeStore, Map<String, ResourceName> resourceNames, List<Sample> samples) {
List<MethodDefinition> javaMethods = new ArrayList<>();
String methodName = JavaStyle.toLowerCamelCase(method.name());
TypeNode methodInputType = method.inputType();
TypeNode methodOutputType = method.isPaged() ? typeStore.get(String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, method.name())) : method.outputType();
if (method.hasLro()) {
LongrunningOperation lro = method.lro();
methodOutputType = TypeNode.withReference(typeStore.get("OperationFuture").reference().copyAndSetGenerics(Arrays.asList(lro.responseType().reference(), lro.metadataType().reference())));
}
for (List<MethodArgument> signature : method.methodSignatures()) {
// Get the argument list.
List<VariableExpr> arguments = signature.stream().map(methodArg -> VariableExpr.builder().setVariable(Variable.builder().setName(JavaStyle.toLowerCamelCase(methodArg.name())).setType(methodArg.type()).build()).setIsDecl(true).build()).collect(Collectors.toList());
// Request proto builder.
VariableExpr requestVarExpr = VariableExpr.builder().setVariable(Variable.builder().setName("request").setType(methodInputType).build()).setIsDecl(true).build();
Expr requestBuilderExpr = createRequestBuilderExpr(method, signature, typeStore);
AssignmentExpr requestAssignmentExpr = AssignmentExpr.builder().setVariableExpr(requestVarExpr).setValueExpr(requestBuilderExpr).build();
List<Statement> statements = new ArrayList<>();
statements.add(ExprStatement.withExpr(requestAssignmentExpr));
MethodInvocationExpr rpcInvocationExpr = MethodInvocationExpr.builder().setMethodName(String.format(method.hasLro() ? "%sAsync" : "%s", methodName)).setArguments(Arrays.asList(requestVarExpr.toBuilder().setIsDecl(false).build())).setReturnType(methodOutputType).build();
Optional<Sample> methodSample = Optional.of(ServiceClientHeaderSampleComposer.composeShowcaseMethodSample(method, typeStore.get(clientName), signature, resourceNames, messageTypes));
Optional<String> methodDocSample = Optional.empty();
if (methodSample.isPresent()) {
samples.add(methodSample.get());
methodDocSample = Optional.of(SampleCodeWriter.writeInlineSample(methodSample.get().body()));
}
MethodDefinition.Builder methodVariantBuilder = MethodDefinition.builder().setHeaderCommentStatements(ServiceClientCommentComposer.createRpcMethodHeaderComment(method, signature, methodDocSample)).setScope(ScopeNode.PUBLIC).setIsFinal(true).setName(String.format(method.hasLro() ? "%sAsync" : "%s", methodName)).setArguments(arguments);
if (isProtoEmptyType(methodOutputType)) {
statements.add(ExprStatement.withExpr(rpcInvocationExpr));
methodVariantBuilder = methodVariantBuilder.setReturnType(TypeNode.VOID);
} else {
methodVariantBuilder = methodVariantBuilder.setReturnType(methodOutputType).setReturnExpr(rpcInvocationExpr);
}
if (method.isDeprecated()) {
methodVariantBuilder = methodVariantBuilder.setAnnotations(Arrays.asList(AnnotationNode.withType(TypeNode.DEPRECATED)));
}
methodVariantBuilder = methodVariantBuilder.setBody(statements);
javaMethods.add(methodVariantBuilder.build());
}
return javaMethods;
}
use of com.google.api.generator.engine.ast.Statement in project gapic-generator-java by googleapis.
the class AbstractServiceClientTestClassComposer method createRpcExceptionTestStatements.
protected List<Statement> createRpcExceptionTestStatements(Method method, List<MethodArgument> methodSignature, Map<String, VariableExpr> classMemberVarExprs, Map<String, ResourceName> resourceNames, Map<String, Message> messageTypes) {
List<VariableExpr> argVarExprs = new ArrayList<>();
List<Expr> tryBodyExprs = new ArrayList<>();
if (methodSignature.isEmpty()) {
// Construct the actual request.
VariableExpr varExpr = VariableExpr.withVariable(Variable.builder().setType(method.inputType()).setName("request").build());
argVarExprs.add(varExpr);
Message requestMessage = messageTypes.get(method.inputType().reference().fullName());
Preconditions.checkNotNull(requestMessage);
Map<String, String> valuePatterns = Collections.emptyMap();
if (getTransportContext().useValuePatterns() && method.hasHttpBindings()) {
valuePatterns = method.httpBindings().getPathParametersValuePatterns();
}
Expr valExpr = DefaultValueComposer.createSimpleMessageBuilderValue(requestMessage, resourceNames, messageTypes, valuePatterns);
tryBodyExprs.add(AssignmentExpr.builder().setVariableExpr(varExpr.toBuilder().setIsDecl(true).build()).setValueExpr(valExpr).build());
} else {
Map<String, String> valuePatterns = Collections.emptyMap();
if (getTransportContext().useValuePatterns() && method.hasHttpBindings()) {
valuePatterns = method.httpBindings().getPathParametersValuePatterns();
}
for (MethodArgument methodArg : methodSignature) {
String methodArgName = JavaStyle.toLowerCamelCase(methodArg.name());
VariableExpr varExpr = VariableExpr.withVariable(Variable.builder().setType(methodArg.type()).setName(methodArgName).build());
argVarExprs.add(varExpr);
Expr valExpr = DefaultValueComposer.createMethodArgValue(methodArg, resourceNames, messageTypes, valuePatterns);
tryBodyExprs.add(AssignmentExpr.builder().setVariableExpr(varExpr.toBuilder().setIsDecl(true).build()).setValueExpr(valExpr).build());
}
}
String rpcJavaName = JavaStyle.toLowerCamelCase(method.name());
if (method.hasLro()) {
rpcJavaName += "Async";
}
MethodInvocationExpr rpcJavaMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(classMemberVarExprs.get("client")).setMethodName(rpcJavaName).setArguments(argVarExprs.stream().map(e -> (Expr) e).collect(Collectors.toList())).build();
if (method.hasLro()) {
rpcJavaMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(rpcJavaMethodInvocationExpr).setMethodName("get").build();
}
tryBodyExprs.add(rpcJavaMethodInvocationExpr);
VariableExpr catchExceptionVarExpr = VariableExpr.builder().setVariable(Variable.builder().setType(TypeNode.withExceptionClazz(method.hasLro() ? ExecutionException.class : InvalidArgumentException.class)).setName("e").build()).build();
List<Statement> catchBody = method.hasLro() ? createRpcLroExceptionTestCatchBody(catchExceptionVarExpr, false) : Arrays.asList(CommentStatement.withComment(LineComment.withComment("Expected exception.")));
// Assert a failure if no exception was raised.
tryBodyExprs.add(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Assert")).setMethodName("fail").setArguments(ValueExpr.withValue(StringObjectValue.withValue("No exception raised"))).build());
TryCatchStatement tryCatchBlock = TryCatchStatement.builder().setTryBody(tryBodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList())).addCatch(catchExceptionVarExpr.toBuilder().setIsDecl(true).build(), catchBody).build();
return Arrays.asList(EMPTY_LINE_STATEMENT, tryCatchBlock);
}
use of com.google.api.generator.engine.ast.Statement in project gapic-generator-java by googleapis.
the class MockServiceImplClassComposer method createHandleObjectStatement.
private static Statement createHandleObjectStatement(Method protoMethod, VariableExpr requestArgVarExpr, VariableExpr responseObserverVarExpr, VariableExpr localResponseVarExpr) {
List<Expr> ifBodyExprs = new ArrayList<>();
boolean isAnonymousClass = requestArgVarExpr == null;
if (!isAnonymousClass) {
ifBodyExprs.add(MethodInvocationExpr.builder().setMethodName("add").setArguments(Arrays.asList(requestArgVarExpr)).setExprReferenceExpr(requestsVarExpr).build());
}
ifBodyExprs.add(MethodInvocationExpr.builder().setMethodName("onNext").setArguments(Arrays.asList(CastExpr.builder().setType(protoMethod.outputType()).setExpr(localResponseVarExpr).build())).setExprReferenceExpr(responseObserverVarExpr).build());
if (!isAnonymousClass) {
ifBodyExprs.add(MethodInvocationExpr.builder().setMethodName("onCompleted").setExprReferenceExpr(responseObserverVarExpr).build());
}
TypeNode exceptionType = TypeNode.withReference(ConcreteReference.withClazz(Exception.class));
// Constructs `response == null ? "" : response.getClass().getName()`.
Expr actualResponseTypeString = TernaryExpr.builder().setConditionExpr(RelationalOperationExpr.equalToWithExprs(localResponseVarExpr, ValueExpr.createNullExpr())).setThenExpr(ValueExpr.withValue(StringObjectValue.withValue("null"))).setElseExpr(MethodInvocationExpr.builder().setExprReferenceExpr(MethodInvocationExpr.builder().setExprReferenceExpr(localResponseVarExpr).setMethodName("getClass").build()).setMethodName("getName").setReturnType(TypeNode.STRING).build()).build();
Function<TypeNode, Expr> typeToStrFn = t -> MethodInvocationExpr.builder().setExprReferenceExpr(VariableExpr.builder().setStaticReferenceType(t).setVariable(Variable.builder().setType(TypeNode.CLASS_OBJECT).setName("class").build()).build()).setMethodName("getName").setReturnType(TypeNode.STRING).build();
Expr expectedResponseTypeOneString = typeToStrFn.apply(protoMethod.outputType());
Expr expectedResponseTypeTwoString = typeToStrFn.apply(exceptionType);
Expr newExceptionExpr = NewObjectExpr.builder().setType(TypeNode.withReference(ConcreteReference.withClazz(IllegalArgumentException.class))).setArguments(// Operation.class.getName(), Exception.class.getName());
MethodInvocationExpr.builder().setStaticReferenceType(TypeNode.STRING).setMethodName("format").setArguments(ValueExpr.withValue(StringObjectValue.withValue("Unrecognized response type %s for method " + protoMethod.name() + ", expected %s or %s")), actualResponseTypeString, expectedResponseTypeOneString, expectedResponseTypeTwoString).build()).build();
return IfStatement.builder().setConditionExpr(InstanceofExpr.builder().setExpr(localResponseVarExpr).setCheckType(protoMethod.outputType()).build()).setBody(ifBodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList())).addElseIf(InstanceofExpr.builder().setExpr(localResponseVarExpr).setCheckType(exceptionType).build(), Arrays.asList(ExprStatement.withExpr(MethodInvocationExpr.builder().setMethodName("onError").setArguments(Arrays.asList(CastExpr.builder().setType(exceptionType).setExpr(localResponseVarExpr).build())).setExprReferenceExpr(responseObserverVarExpr).build()))).setElseBody(Arrays.asList(ExprStatement.withExpr(MethodInvocationExpr.builder().setMethodName("onError").setExprReferenceExpr(responseObserverVarExpr).setArguments(Arrays.asList(newExceptionExpr)).build()))).build();
}
use of com.google.api.generator.engine.ast.Statement in project gapic-generator-java by googleapis.
the class MockServiceImplClassComposer method createRequestResponseAssignStatements.
private static List<Statement> createRequestResponseAssignStatements() {
Expr assignRequestVarExpr = AssignmentExpr.builder().setVariableExpr(requestsVarExpr).setValueExpr(NewObjectExpr.builder().setType(TypeNode.withReference(ConcreteReference.withClazz(ArrayList.class))).setIsGeneric(true).build()).build();
Expr assignResponsesVarExpr = AssignmentExpr.builder().setVariableExpr(responsesVarExpr).setValueExpr(NewObjectExpr.builder().setType(TypeNode.withReference(ConcreteReference.withClazz(LinkedList.class))).setIsGeneric(true).build()).build();
return Arrays.asList(assignRequestVarExpr, assignResponsesVarExpr).stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList());
}
Aggregations