use of com.google.api.generator.engine.ast.TypeNode in project gapic-generator-java by googleapis.
the class ServiceClientMethodSampleComposer method composePagedSample.
static Sample composePagedSample(Method method, VariableExpr clientVarExpr, List<VariableExpr> rpcMethodArgVarExprs, List<Expr> bodyExprs, Map<String, Message> messageTypes) {
// Find the repeated field.
Message methodOutputMessage = messageTypes.get(method.outputType().reference().fullName());
Preconditions.checkNotNull(methodOutputMessage, "Output message %s not found, keys: ", method.outputType().reference().fullName(), messageTypes.keySet().toString());
Field repeatedPagedResultsField = methodOutputMessage.findAndUnwrapPaginatedRepeatedField();
Preconditions.checkNotNull(repeatedPagedResultsField, String.format("No repeated field found on message %s for method %s", methodOutputMessage.name(), method.name()));
TypeNode repeatedResponseType = repeatedPagedResultsField.type();
// For loop paged response item on iterateAll method.
// e.g. for (LogEntry element : loggingServiceV2Client.ListLogs(parent).iterateAll()) {
// //doThingsWith(element);
// }
MethodInvocationExpr clientMethodIterateAllExpr = MethodInvocationExpr.builder().setExprReferenceExpr(clientVarExpr).setMethodName(JavaStyle.toLowerCamelCase(method.name())).setArguments(rpcMethodArgVarExprs.stream().map(e -> (Expr) e).collect(Collectors.toList())).build();
clientMethodIterateAllExpr = MethodInvocationExpr.builder().setExprReferenceExpr(clientMethodIterateAllExpr).setMethodName("iterateAll").setReturnType(repeatedResponseType).build();
ForStatement loopIteratorStatement = ForStatement.builder().setLocalVariableExpr(VariableExpr.builder().setVariable(Variable.builder().setName("element").setType(repeatedResponseType).build()).setIsDecl(true).build()).setCollectionExpr(clientMethodIterateAllExpr).setBody(Arrays.asList(CommentStatement.withComment(LineComment.withComment("doThingsWith(element);")))).build();
List<Statement> bodyStatements = bodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList());
bodyExprs.clear();
bodyStatements.add(loopIteratorStatement);
RegionTag regionTag = RegionTag.builder().setServiceName(clientVarExpr.variable().identifier().name()).setRpcName(method.name()).setOverloadDisambiguation(SampleComposerUtil.createOverloadDisambiguation(rpcMethodArgVarExprs)).build();
return Sample.builder().setBody(bodyStatements).setRegionTag(regionTag).build();
}
use of com.google.api.generator.engine.ast.TypeNode in project gapic-generator-java by googleapis.
the class HttpJsonServiceStubClassComposer method getRequestFormatterExpr.
private List<Expr> getRequestFormatterExpr(Method protoMethod) {
BiFunction<String, List<Expr>, Function<MethodInvocationExpr, MethodInvocationExpr>> methodMaker = getMethodMaker();
MethodInvocationExpr expr = MethodInvocationExpr.builder().setStaticReferenceType(FIXED_REST_TYPESTORE.get(ProtoMessageRequestFormatter.class.getSimpleName())).setMethodName("newBuilder").setGenerics(Collections.singletonList(protoMethod.inputType().reference())).build();
TypeNode extractorVarType = TypeNode.withReference(ConcreteReference.builder().setClazz(Map.class).setGenerics(TypeNode.STRING.reference(), TypeNode.STRING.reference()).build());
expr = methodMaker.apply("setPath", Arrays.asList(ValueExpr.withValue(StringObjectValue.withValue(protoMethod.httpBindings().lowerCamelPattern())), createFieldsExtractorClassInstance(protoMethod, extractorVarType, protoMethod.httpBindings().pathParameters(), "putPathParam"))).apply(expr);
TypeNode fieldsVarGenericType = TypeNode.withReference(ConcreteReference.builder().setClazz(List.class).setGenerics(TypeNode.STRING.reference()).build());
extractorVarType = TypeNode.withReference(ConcreteReference.builder().setClazz(Map.class).setGenerics(TypeNode.STRING.reference(), fieldsVarGenericType.reference()).build());
expr = methodMaker.apply("setQueryParamsExtractor", Arrays.asList(createFieldsExtractorClassInstance(protoMethod, extractorVarType, protoMethod.httpBindings().queryParameters(), "putQueryParam"))).apply(expr);
extractorVarType = TypeNode.STRING;
boolean asteriskBody = protoMethod.httpBindings().isAsteriskBody();
expr = methodMaker.apply("setRequestBodyExtractor", Arrays.asList(createBodyFieldsExtractorClassInstance(protoMethod, extractorVarType, asteriskBody ? protoMethod.httpBindings().pathParameters() : protoMethod.httpBindings().bodyParameters(), "toBody", asteriskBody))).apply(expr);
expr = methodMaker.apply("build", Collections.emptyList()).apply(expr);
return Collections.singletonList(expr);
}
use of com.google.api.generator.engine.ast.TypeNode in project gapic-generator-java by googleapis.
the class HttpJsonServiceStubClassComposer method createOperationsStubInitExpr.
@Override
protected List<Expr> createOperationsStubInitExpr(Service service, Expr thisExpr, VariableExpr operationsStubClassVarExpr, VariableExpr clientContextVarExpr, VariableExpr callableFactoryVarExpr) {
TypeNode operationsStubType = getTransportOperationsStubType(service);
String standardOpStub = HttpJsonOperationsStub.class.getName();
List<Expr> arguments = new ArrayList<>(Arrays.asList(clientContextVarExpr, callableFactoryVarExpr));
if (standardOpStub.equals(operationsStubType.reference().fullName())) {
arguments.add(TYPE_REGISTRY_VAR_EXPR);
}
return Collections.singletonList(AssignmentExpr.builder().setVariableExpr(operationsStubClassVarExpr.toBuilder().setExprReferenceExpr(thisExpr).build()).setValueExpr(MethodInvocationExpr.builder().setStaticReferenceType(operationsStubType).setMethodName("create").setArguments(arguments).setReturnType(operationsStubClassVarExpr.type()).build()).build());
}
use of com.google.api.generator.engine.ast.TypeNode in project gapic-generator-java by googleapis.
the class ServiceClientTestClassComposer method createStartStaticServerMethod.
@Override
protected MethodDefinition createStartStaticServerMethod(Service service, GapicContext context, Map<String, VariableExpr> classMemberVarExprs, TypeStore typeStore, String newBuilderMethod) {
VariableExpr mockServiceVarExpr = classMemberVarExprs.get(MOCK_SERVICE_VAR_NAME);
VariableExpr clientVarExpr = classMemberVarExprs.get(CLIENT_VAR_NAME);
TypeNode settingsType = typeStore.get(ClassNames.getServiceSettingsClassName(service));
TypeNode transportStubType = typeStore.get(getTransportContext().classNames().getTransportServiceStubClassName(service));
Function<Expr, BiFunction<String, Expr, MethodInvocationExpr>> methodBuilderFn = methodExpr -> (mName, argExpr) -> MethodInvocationExpr.builder().setExprReferenceExpr(methodExpr).setMethodName(mName).setArguments(Arrays.asList(argExpr)).build();
Expr initMockServiceExpr = AssignmentExpr.builder().setVariableExpr(mockServiceVarExpr).setValueExpr(NewObjectExpr.builder().setType(mockServiceVarExpr.type()).setArguments(MethodInvocationExpr.builder().setStaticReferenceType(transportStubType).setMethodName("getMethodDescriptors").build(), MethodInvocationExpr.builder().setStaticReferenceType(settingsType).setMethodName("getDefaultEndpoint").build()).build()).build();
VariableExpr localSettingsVarExpr = VariableExpr.withVariable(Variable.builder().setName("settings").setType(settingsType).build());
Expr settingsBuilderExpr = MethodInvocationExpr.builder().setStaticReferenceType(settingsType).setMethodName(newBuilderMethod).build();
Expr transportChannelProviderExpr = MethodInvocationExpr.builder().setStaticReferenceType(settingsType).setMethodName("defaultHttpJsonTransportProviderBuilder").build();
transportChannelProviderExpr = methodBuilderFn.apply(transportChannelProviderExpr).apply("setHttpTransport", mockServiceVarExpr);
transportChannelProviderExpr = MethodInvocationExpr.builder().setExprReferenceExpr(transportChannelProviderExpr).setMethodName("build").setReturnType(localSettingsVarExpr.type()).build();
settingsBuilderExpr = methodBuilderFn.apply(settingsBuilderExpr).apply("setTransportChannelProvider", transportChannelProviderExpr);
settingsBuilderExpr = methodBuilderFn.apply(settingsBuilderExpr).apply("setCredentialsProvider", MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("NoCredentialsProvider")).setMethodName("create").build());
settingsBuilderExpr = MethodInvocationExpr.builder().setExprReferenceExpr(settingsBuilderExpr).setMethodName("build").setReturnType(localSettingsVarExpr.type()).build();
Expr initLocalSettingsExpr = AssignmentExpr.builder().setVariableExpr(localSettingsVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(settingsBuilderExpr).build();
Expr initClientExpr = AssignmentExpr.builder().setVariableExpr(clientVarExpr).setValueExpr(MethodInvocationExpr.builder().setStaticReferenceType(typeStore.get(ClassNames.getServiceClientClassName(service))).setMethodName("create").setArguments(Arrays.asList(localSettingsVarExpr)).setReturnType(clientVarExpr.type()).build()).build();
return MethodDefinition.builder().setAnnotations(Arrays.asList(AnnotationNode.withType(FIXED_TYPESTORE.get("BeforeClass")))).setScope(ScopeNode.PUBLIC).setReturnType(TypeNode.VOID).setName("startStaticServer").setThrowsExceptions(Arrays.asList(FIXED_TYPESTORE.get("IOException"))).setIsStatic(true).setBody(Arrays.asList(initMockServiceExpr, initLocalSettingsExpr, initClientExpr).stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList())).build();
}
use of com.google.api.generator.engine.ast.TypeNode in project gapic-generator-java by googleapis.
the class MethodSignatureParser method parseTypeFromArgumentName.
private static Map<TypeNode, Field> parseTypeFromArgumentName(String argumentName, String servicePackage, Message inputMessage, Map<String, Message> messageTypes, Map<String, ResourceName> resourceNames, Map<String, ResourceName> patternsToResourceNames, List<Field> argumentFieldPathAcc, Set<ResourceName> outputArgResourceNames) {
Map<TypeNode, Field> typeToField = new HashMap<>();
int dotIndex = argumentName.indexOf(DOT);
if (dotIndex < 1) {
Field field = inputMessage.fieldMap().get(argumentName);
Preconditions.checkNotNull(field, String.format("Field %s not found from input message %s values %s", argumentName, inputMessage.name(), inputMessage.fieldMap().keySet()));
if (!field.hasResourceReference()) {
typeToField.put(field.type(), field);
return typeToField;
}
// Parse the resource name tyeps.
List<ResourceName> resourceNameArgs = ResourceReferenceParser.parseResourceNames(field.resourceReference(), servicePackage, field.description(), resourceNames, patternsToResourceNames);
outputArgResourceNames.addAll(resourceNameArgs);
typeToField.put(TypeNode.STRING, field);
typeToField.putAll(resourceNameArgs.stream().collect(Collectors.toMap(r -> r.type(), r -> field.toBuilder().setResourceReference(ResourceReference.withType(r.resourceTypeString())).build())));
// Only resource name helpers should have more than one entry.
if (typeToField.size() > 1) {
typeToField.entrySet().stream().forEach(e -> {
// Skip string-only variants or ResourceName generics.
if (e.getKey().equals(TypeNode.STRING) || e.getKey().reference().name().equals("ResourceName")) {
return;
}
String resourceJavaTypeName = e.getKey().reference().name();
String resourceTypeName = e.getValue().resourceReference().resourceTypeString();
int indexOfSlash = resourceTypeName.indexOf("/");
// We assume that the corresponding Java resource name helper type (i.e. the key)
// ends in *Name. Check that it matches the expeced resource name type.
Preconditions.checkState(resourceJavaTypeName.substring(0, resourceJavaTypeName.length() - 4).equals(resourceTypeName.substring(indexOfSlash + 1)), String.format("Resource Java type %s does not correspond to proto type %s", resourceJavaTypeName, resourceTypeName));
});
}
return typeToField;
}
Preconditions.checkState(dotIndex < argumentName.length() - 1, String.format("Invalid argument name found: dot cannot be at the end of name %s", argumentName));
String firstFieldName = argumentName.substring(0, dotIndex);
String remainingArgumentName = argumentName.substring(dotIndex + 1);
// Must be a sub-message for a type's subfield to be valid.
Field firstField = inputMessage.fieldMap().get(firstFieldName);
// Validate the field into which we're descending.
Preconditions.checkState(!firstField.isRepeated(), String.format("Cannot descend into repeated field %s", firstField.name()));
TypeNode firstFieldType = firstField.type();
Preconditions.checkState(TypeNode.isReferenceType(firstFieldType) && !firstFieldType.equals(TypeNode.STRING), String.format("Field reference on %s cannot be a primitive type", firstFieldName));
String firstFieldTypeName = firstFieldType.reference().fullName();
Message firstFieldMessage = messageTypes.get(firstFieldTypeName);
Preconditions.checkNotNull(firstFieldMessage, String.format("Message type %s for field reference %s invalid", firstFieldTypeName, firstFieldName));
argumentFieldPathAcc.add(firstField);
return parseTypeFromArgumentName(remainingArgumentName, servicePackage, firstFieldMessage, messageTypes, resourceNames, patternsToResourceNames, argumentFieldPathAcc, outputArgResourceNames);
}
Aggregations