use of com.google.api.generator.gapic.model.Message in project gapic-generator-java by googleapis.
the class ServiceClientCallableMethodSampleComposer method composeStreamCallableMethod.
public static Sample composeStreamCallableMethod(Method method, TypeNode clientType, Map<String, ResourceName> resourceNames, Map<String, Message> messageTypes) {
VariableExpr clientVarExpr = VariableExpr.withVariable(Variable.builder().setName(JavaStyle.toLowerCamelCase(clientType.reference().name())).setType(clientType).build());
// Assign method's request variable with the default value.
VariableExpr requestVarExpr = VariableExpr.withVariable(Variable.builder().setName("request").setType(method.inputType()).build());
Message requestMessage = messageTypes.get(method.inputType().reference().fullName());
Preconditions.checkNotNull(requestMessage, String.format("Could not find the message type %s.", method.inputType().reference().fullName()));
Expr requestBuilderExpr = DefaultValueComposer.createSimpleMessageBuilderValue(requestMessage, resourceNames, messageTypes);
AssignmentExpr requestAssignmentExpr = AssignmentExpr.builder().setVariableExpr(requestVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(requestBuilderExpr).build();
RegionTag regionTag = null;
List<Statement> bodyStatements = new ArrayList<>();
if (method.stream().equals(Method.Stream.SERVER)) {
// e.g. ServerStream<EchoResponse> stream = echoClient.expandCallable().call(request);
Sample streamServer = composeStreamServerSample(method, clientVarExpr, requestAssignmentExpr);
bodyStatements.addAll(streamServer.body());
regionTag = streamServer.regionTag();
} else if (method.stream().equals(Method.Stream.BIDI)) {
// e.g. echoClient.collect().clientStreamingCall(responseObserver);
Sample streamBidi = composeStreamBidiSample(method, clientVarExpr, requestAssignmentExpr);
bodyStatements.addAll(streamBidi.body());
regionTag = streamBidi.regionTag();
} else if (method.stream().equals(Method.Stream.CLIENT)) {
Sample streamClient = composeStreamClientSample(method, clientVarExpr, requestAssignmentExpr);
bodyStatements.addAll(streamClient.body());
regionTag = streamClient.regionTag();
}
List<Statement> body = Arrays.asList(TryCatchStatement.builder().setTryResourceExpr(SampleComposerUtil.assignClientVariableWithCreateMethodExpr(clientVarExpr)).setTryBody(bodyStatements).setIsSampleCode(true).build());
return Sample.builder().setBody(body).setRegionTag(regionTag).build();
}
use of com.google.api.generator.gapic.model.Message 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.gapic.model.Message in project gapic-generator-java by googleapis.
the class ServiceClientMethodSampleComposer method composeCanonicalSample.
public static Sample composeCanonicalSample(Method method, TypeNode clientType, Map<String, ResourceName> resourceNames, Map<String, Message> messageTypes) {
VariableExpr clientVarExpr = VariableExpr.withVariable(Variable.builder().setName(JavaStyle.toLowerCamelCase(clientType.reference().name())).setType(clientType).build());
// Create request variable expression and assign with its default value.
VariableExpr requestVarExpr = VariableExpr.withVariable(Variable.builder().setName("request").setType(method.inputType()).build());
List<VariableExpr> rpcMethodArgVarExprs = Arrays.asList(requestVarExpr);
Message requestMessage = messageTypes.get(method.inputType().reference().fullName());
Preconditions.checkNotNull(requestMessage, String.format("Could not find the message type %s.", method.inputType().reference().fullName()));
Expr requestBuilderExpr = DefaultValueComposer.createSimpleMessageBuilderValue(requestMessage, resourceNames, messageTypes);
AssignmentExpr requestAssignmentExpr = AssignmentExpr.builder().setVariableExpr(requestVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(requestBuilderExpr).build();
List<Expr> bodyExprs = new ArrayList<>();
bodyExprs.add(requestAssignmentExpr);
List<Statement> bodyStatements = new ArrayList<>();
RegionTag regionTag;
if (method.isPaged()) {
// e.g. echoClient.pagedExpand(request).iterateAll()
Sample unaryPagedRpc = composePagedSample(method, clientVarExpr, rpcMethodArgVarExprs, bodyExprs, messageTypes);
bodyStatements.addAll(unaryPagedRpc.body());
regionTag = unaryPagedRpc.regionTag();
} else if (method.hasLro()) {
Sample unaryLroRpc = composeLroSample(method, clientVarExpr, rpcMethodArgVarExprs, bodyExprs);
bodyStatements.addAll(unaryLroRpc.body());
regionTag = unaryLroRpc.regionTag();
} else {
// e.g. echoClient.echo(request)
Sample unaryRpc = composeSample(method, clientVarExpr, rpcMethodArgVarExprs, bodyExprs);
bodyStatements.addAll(unaryRpc.body());
regionTag = unaryRpc.regionTag();
}
List<Statement> body = Arrays.asList(TryCatchStatement.builder().setTryResourceExpr(SampleComposerUtil.assignClientVariableWithCreateMethodExpr(clientVarExpr)).setTryBody(bodyStatements).setIsSampleCode(true).build());
return Sample.builder().setBody(body).setRegionTag(regionTag).setIsCanonical(true).build();
}
use of com.google.api.generator.gapic.model.Message 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);
}
use of com.google.api.generator.gapic.model.Message in project gapic-generator-java by googleapis.
the class Parser method updateResourceNamesInMessages.
/**
* Populates ResourceName objects in Message POJOs.
*
* @param messageTypes A map of the message type name (as in the protobuf) to Message POJOs.
* @param resources A list of ResourceName POJOs.
* @return The updated messageTypes map.
*/
public static Map<String, Message> updateResourceNamesInMessages(Map<String, Message> messageTypes, Collection<ResourceName> resources) {
Map<String, Message> updatedMessages = new HashMap<>(messageTypes);
for (ResourceName resource : resources) {
if (!resource.hasParentMessageName()) {
continue;
}
String messageKey = resource.parentMessageName();
Message messageToUpdate = updatedMessages.get(messageKey);
updatedMessages.put(messageKey, messageToUpdate.toBuilder().setResource(resource).build());
}
return updatedMessages;
}
Aggregations