Skip to content

http-client-java, bug fix, spread of optional body #7044

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import com.microsoft.typespec.http.client.generator.core.util.MethodUtil;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -411,16 +410,6 @@ public void addImportsTo(Set<String> imports, boolean includeImplementationImpor

if (proxyMethod != null) {
proxyMethod.addImportsTo(imports, includeImplementationImports, settings);
for (ProxyMethodParameter parameter : proxyMethod.getParameters()) {
parameter.getClientType().addImportsTo(imports, true);

if (parameter.getExplode()) {
imports.add("java.util.Optional");
imports.add("java.util.stream.Stream");
imports.add(ArrayList.class.getName());
imports.add("java.util.Collection");
}
}
}

if (getReturnValue().getType() == ClassType.INPUT_STREAM) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,11 @@ public void addImportsTo(Set<String> imports, boolean includeImplementationImpor
annotation.addImportsTo(imports, includeImplementationImports);
}
getClientType().addImportsTo(imports, includeImplementationImports);
if (includeImplementationImports && getRawType() != null) {
getRawType().addImportsTo(imports, includeImplementationImports);
if (includeImplementationImports) {
getWireType().addImportsTo(imports, includeImplementationImports);
if (getRawType() != null) {
getRawType().addImportsTo(imports, includeImplementationImports);
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -464,7 +464,7 @@ public void addImportsTo(Set<String> imports, boolean includeImplementationImpor
Annotation.FORM_PARAM.addImportsTo(imports);
}

for (ProxyMethodParameter parameter : parameters) {
for (ProxyMethodParameter parameter : allParameters) {
parameter.addImportsTo(imports, includeImplementationImports, settings);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import com.microsoft.typespec.http.client.generator.core.extension.plugin.JavaSettings;
import com.microsoft.typespec.http.client.generator.core.util.CodeNamer;
import com.microsoft.typespec.http.client.generator.core.util.MethodUtil;
import java.util.ArrayList;
import java.util.Set;

/**
Expand Down Expand Up @@ -249,7 +250,19 @@ public void addImportsTo(Set<String> imports, boolean includeImplementationImpor
imports.add("io.clientcore.core.http.models.HttpMethod");
}

getWireType().addImportsTo(imports, includeImplementationImports);
if (includeImplementationImports) {
getWireType().addImportsTo(imports, includeImplementationImports);
if (getRawType() != null) {
getRawType().addImportsTo(imports, includeImplementationImports);
}

if (getExplode()) {
imports.add("java.util.Optional");
imports.add("java.util.stream.Stream");
imports.add(ArrayList.class.getName());
imports.add("java.util.Collection");
}
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,14 @@ protected void writeMethodImplementation(ClientMethod protocolMethod, ClientMeth
// parameter transformation
final ParameterTransformations transformations = convenienceMethod.getParameterTransformations();
if (!transformations.isEmpty()) {
transformations.asStream()
.forEach(d -> writeParameterTransformation(d, convenienceMethod, protocolMethod, methodBlock,
parametersMap));
transformations.asStream().forEach(d -> {
ClientMethodParameter requestBodyClientParameter
= writeParameterTransformation(d, convenienceMethod, protocolMethod, methodBlock, parametersMap);
if (requestBodyClientParameter != null && !requestBodyClientParameter.isRequired()) {
// protocol method parameter does not exist, set the parameter via RequestOptions
methodBlock.line("requestOptions.setBody(" + requestBodyClientParameter.getName() + ");");
}
});
}

writeValidationForVersioning(convenienceMethod, parametersMap.keySet(), methodBlock);
Expand All @@ -139,7 +144,7 @@ protected void writeMethodImplementation(ClientMethod protocolMethod, ClientMeth
protocolMethod.getProxyMethod().getRequestContentType());
parameterExpressionsMap.put(protocolParameter.getName(), expression);
} else if (parameter.getProxyMethodParameter() != null) {
// protocol method parameter not exist, set the parameter via RequestOptions
// protocol method parameter does not exist, set the parameter via RequestOptions
switch (parameter.getProxyMethodParameter().getRequestParameterLocation()) {
case HEADER:
writeHeader(parameter, methodBlock);
Expand Down Expand Up @@ -234,11 +239,30 @@ protected void writeValidationForVersioning(ClientMethod convenienceMethod, Set<

abstract void writeThrowException(ClientMethodType methodType, String exceptionExpression, JavaBlock methodBlock);

private static void writeParameterTransformation(ParameterTransformation transformation,
/**
* Writes the code for parameter transformation.
* Return the client parameter of the request body, if the BinaryData of the object is written.
*
* @param transformation the parameter transformation
* @param convenienceMethod the convenience method
* @param protocolMethod the protocol method
* @param methodBlock the block to write code
* @param parametersMap the map of matched parameters from convenience method to protocol method
* @return the client parameter of request body, if the BinaryData of the object is written.
*/
private static ClientMethodParameter writeParameterTransformation(ParameterTransformation transformation,
ClientMethod convenienceMethod, ClientMethod protocolMethod, JavaBlock methodBlock,
Map<MethodParameter, MethodParameter> parametersMap) {

ClientMethodParameter requestBodyClientParameter = null;

if (transformation.isGroupBy()) {
// grouping
// parameter grouping
/*
* sample code:
* String id = options.getId();
* String header = options.getHeader();
*/
final ClientMethodParameter sourceParameter = transformation.getGroupByInParameter();

boolean sourceParameterInMethod = false;
Expand Down Expand Up @@ -280,9 +304,19 @@ private static void writeParameterTransformation(ParameterTransformation transfo
}
}
} else {
// flatten (possible with grouping)
// request body flatten (possible with parameter grouping, handled in "mapping.getInParameterProperty()")
/*
* sample code:
* Body bodyObj = new Body(name).setProperty(options.getProperty());
* BinaryData body = BinaryData.fromObject(bodyObj);
*/
ClientMethodParameter targetParameter = transformation.getOutParameter();
if (targetParameter.getWireType() == ClassType.BINARY_DATA) {

// if the request body is optional, when this client method overload contains only required parameters,
// body expression is not needed (as there is no property in this overload for the request body)
final boolean noBodyPropertyForOptionalBody
= !targetParameter.isRequired() && convenienceMethod.getOnlyRequiredParameters();
if (!noBodyPropertyForOptionalBody && targetParameter.getWireType() == ClassType.BINARY_DATA) {
IType targetType = targetParameter.getRawType();

StringBuilder ctorExpression = new StringBuilder();
Expand Down Expand Up @@ -338,21 +372,22 @@ private static void writeParameterTransformation(ParameterTransformation transfo
protocolMethod.getProxyMethod().getRequestContentType());
}
methodBlock.line(String.format("BinaryData %1$s = %2$s;", targetParameterName, expression));

requestBodyClientParameter = targetParameter;
}
}
return requestBodyClientParameter;
}

protected void addImports(Set<String> imports, List<ConvenienceMethod> convenienceMethods) {
// methods
JavaSettings settings = JavaSettings.getInstance();
convenienceMethods.stream().flatMap(m -> m.getConvenienceMethods().stream()).forEach(m -> {
m.addImportsTo(imports, false, settings);
// hack, add wire type of parameters, as they are not added in ClientMethod, even when
// includeImplementationImports=true
for (ClientMethodParameter p : m.getParameters()) {
p.getWireType().addImportsTo(imports, false);
// we need classes many of its parameters and models, hence "includeImplementationImports=true"
m.addImportsTo(imports, true, settings);

// add imports from models, as some convenience API need to process model properties
// add imports from models, as some convenience API need to process model properties
for (ClientMethodParameter p : m.getParameters()) {
if (p.getWireType() instanceof ClassType) {
ClientModel model = ClientModelUtil.getClientModel(p.getWireType().toString());
if (model != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import tsptest.flatten.implementation.FlattenClientImpl;
import tsptest.flatten.implementation.JsonMergePatchHelper;
import tsptest.flatten.implementation.models.SendLongRequest;
import tsptest.flatten.implementation.models.SendOptionalBodyRequest;
import tsptest.flatten.implementation.models.SendProjectedNameRequest;
import tsptest.flatten.implementation.models.SendRequest;
import tsptest.flatten.models.SendLongOptions;
Expand Down Expand Up @@ -211,6 +212,39 @@ public Mono<Response<BinaryData>> updateWithResponse(long id, BinaryData updateR
return this.serviceClient.updateWithResponseAsync(id, updateRequest, requestOptions);
}

/**
* The sendOptionalBody operation.
* <p><strong>Header Parameters</strong></p>
* <table border="1">
* <caption>Header Parameters</caption>
* <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr>
* <tr><td>Content-Type</td><td>String</td><td>No</td><td>The content type. Allowed values:
* "application/json".</td></tr>
* </table>
* You can add these to a request with {@link RequestOptions#addHeader}
* <p><strong>Request Body Schema</strong></p>
*
* <pre>
* {@code
* {
* name: String (Optional)
* }
* }
* </pre>
*
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return the {@link Response} on successful completion of {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> sendOptionalBodyWithResponse(RequestOptions requestOptions) {
return this.serviceClient.sendOptionalBodyWithResponseAsync(requestOptions);
}

/**
* The send operation.
*
Expand Down Expand Up @@ -349,4 +383,45 @@ public Mono<TodoItem> update(long id, UpdatePatchRequest updateRequest) {
return updateWithResponse(id, updateRequestInBinaryData, requestOptions).flatMap(FluxUtil::toMono)
.map(protocolMethodData -> protocolMethodData.toObject(TodoItem.class));
}

/**
* The sendOptionalBody operation.
*
* @param name The name parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return A {@link Mono} that completes when a successful response is received.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> sendOptionalBody(String name) {
// Generated convenience method for sendOptionalBodyWithResponse
RequestOptions requestOptions = new RequestOptions();
SendOptionalBodyRequest sendOptionalBodyRequestObj = new SendOptionalBodyRequest().setName(name);
BinaryData sendOptionalBodyRequest = BinaryData.fromObject(sendOptionalBodyRequestObj);
requestOptions.setBody(sendOptionalBodyRequest);
return sendOptionalBodyWithResponse(requestOptions).flatMap(FluxUtil::toMono);
}

/**
* The sendOptionalBody operation.
*
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return A {@link Mono} that completes when a successful response is received.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> sendOptionalBody() {
// Generated convenience method for sendOptionalBodyWithResponse
RequestOptions requestOptions = new RequestOptions();
return sendOptionalBodyWithResponse(requestOptions).flatMap(FluxUtil::toMono);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import tsptest.flatten.implementation.FlattenClientImpl;
import tsptest.flatten.implementation.JsonMergePatchHelper;
import tsptest.flatten.implementation.models.SendLongRequest;
import tsptest.flatten.implementation.models.SendOptionalBodyRequest;
import tsptest.flatten.implementation.models.SendProjectedNameRequest;
import tsptest.flatten.implementation.models.SendRequest;
import tsptest.flatten.models.SendLongOptions;
Expand Down Expand Up @@ -207,6 +208,39 @@ public Response<BinaryData> updateWithResponse(long id, BinaryData updateRequest
return this.serviceClient.updateWithResponse(id, updateRequest, requestOptions);
}

/**
* The sendOptionalBody operation.
* <p><strong>Header Parameters</strong></p>
* <table border="1">
* <caption>Header Parameters</caption>
* <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr>
* <tr><td>Content-Type</td><td>String</td><td>No</td><td>The content type. Allowed values:
* "application/json".</td></tr>
* </table>
* You can add these to a request with {@link RequestOptions#addHeader}
* <p><strong>Request Body Schema</strong></p>
*
* <pre>
* {@code
* {
* name: String (Optional)
* }
* }
* </pre>
*
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return the {@link Response}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> sendOptionalBodyWithResponse(RequestOptions requestOptions) {
return this.serviceClient.sendOptionalBodyWithResponse(requestOptions);
}

/**
* The send operation.
*
Expand Down Expand Up @@ -340,4 +374,43 @@ public TodoItem update(long id, UpdatePatchRequest updateRequest) {
JsonMergePatchHelper.getUpdatePatchRequestAccessor().prepareModelForJsonMergePatch(updateRequest, false);
return updateWithResponse(id, updateRequestInBinaryData, requestOptions).getValue().toObject(TodoItem.class);
}

/**
* The sendOptionalBody operation.
*
* @param name The name parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public void sendOptionalBody(String name) {
// Generated convenience method for sendOptionalBodyWithResponse
RequestOptions requestOptions = new RequestOptions();
SendOptionalBodyRequest sendOptionalBodyRequestObj = new SendOptionalBodyRequest().setName(name);
BinaryData sendOptionalBodyRequest = BinaryData.fromObject(sendOptionalBodyRequestObj);
requestOptions.setBody(sendOptionalBodyRequest);
sendOptionalBodyWithResponse(requestOptions).getValue();
}

/**
* The sendOptionalBody operation.
*
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public void sendOptionalBody() {
// Generated convenience method for sendOptionalBodyWithResponse
RequestOptions requestOptions = new RequestOptions();
sendOptionalBodyWithResponse(requestOptions).getValue();
}
}
Loading
Loading