Skip to content

Commit e66eb91

Browse files
authored
Fix possible NPE in ProxyMethodExample (#2867)
1 parent 7485500 commit e66eb91

File tree

3 files changed

+50
-69
lines changed

3 files changed

+50
-69
lines changed

javagen/src/main/java/com/azure/autorest/model/clientmodel/ProxyMethodExample.java

Lines changed: 46 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
import com.azure.core.util.CoreUtils;
1111
import com.fasterxml.jackson.core.JsonProcessingException;
1212
import com.fasterxml.jackson.databind.ObjectMapper;
13-
import com.fasterxml.jackson.databind.SerializationFeature;
1413
import org.slf4j.Logger;
1514

1615
import java.net.MalformedURLException;
@@ -23,21 +22,18 @@
2322
import java.util.LinkedHashMap;
2423
import java.util.Map;
2524
import java.util.Objects;
26-
import java.util.Optional;
27-
import java.util.regex.Pattern;
2825
import java.util.stream.Collectors;
2926
import java.util.stream.Stream;
3027

3128
public class ProxyMethodExample {
3229

3330
private final Logger logger = new PluginLogger(Javagen.getPluginInstance(), ProxyMethodExample.class);
3431

35-
private static final ObjectMapper PRETTY_PRINTER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
3632
private static final ObjectMapper NORMAL_PRINTER = new ObjectMapper();
3733
private static final String SLASH = "/";
38-
private static final String QUOTED_SLASH = Pattern.quote(SLASH);
3934

4035
private static String tspDirectory = null;
36+
4137
public static void setTspDirectory(String tspDirectory) {
4238
ProxyMethodExample.tspDirectory = tspDirectory;
4339
}
@@ -61,7 +57,7 @@ public Object getObjectValue() {
6157

6258
/**
6359
* Gets the un-escaped query value.
64-
*
60+
* <p>
6561
* This is done by heuristic, and not guaranteed to be correct.
6662
*
6763
* @return the un-escaped query value
@@ -77,13 +73,9 @@ public Object getUnescapedQueryValue() {
7773
@Override
7874
public String toString() {
7975
try {
80-
return "ParameterValue{" +
81-
"objectValue=" + PRETTY_PRINTER.writeValueAsString(objectValue) +
82-
'}';
76+
return "ParameterValue{" + "objectValue=" + NORMAL_PRINTER.writeValueAsString(objectValue) + '}';
8377
} catch (JsonProcessingException e) {
84-
return "ParameterValue{" +
85-
"objectValue=" + objectValue +
86-
'}';
78+
return "ParameterValue{" + "objectValue=" + objectValue + '}';
8779
}
8880
}
8981

@@ -110,9 +102,8 @@ public Response(int statusCode, Object response) {
110102
Map<String, Object> responseMap = (Map<String, Object>) response;
111103
if (responseMap.containsKey("headers") && responseMap.get("headers") instanceof Map) {
112104
Map<String, Object> headersMap = (Map<String, Object>) responseMap.get("headers");
113-
headersMap.forEach((header, value) -> {
114-
httpHeaders.add(HttpHeaderName.fromString(header), value.toString());
115-
});
105+
headersMap.forEach(
106+
(header, value) -> httpHeaders.add(HttpHeaderName.fromString(header), String.valueOf(value)));
116107
}
117108
this.body = responseMap.getOrDefault("body", null);
118109
} else {
@@ -167,17 +158,11 @@ public String getJson(Object obj) {
167158
@Override
168159
public String toString() {
169160
try {
170-
return "Response{" +
171-
"statusCode=" + statusCode +
172-
", httpHeaders=" + httpHeaders +
173-
", body=" + PRETTY_PRINTER.writeValueAsString(body) +
174-
'}';
161+
return "Response{" + "statusCode=" + statusCode + ", httpHeaders=" + httpHeaders + ", body="
162+
+ NORMAL_PRINTER.writeValueAsString(body) + '}';
175163
} catch (JsonProcessingException e) {
176-
return "Response{" +
177-
"statusCode=" + statusCode +
178-
", httpHeaders=" + httpHeaders +
179-
", body=" + body +
180-
'}';
164+
return "Response{" + "statusCode=" + statusCode + ", httpHeaders=" + httpHeaders + ", body=" + body
165+
+ '}';
181166
}
182167
}
183168
}
@@ -206,18 +191,23 @@ public Map<Integer, Response> getResponses() {
206191
/**
207192
* @return the primary response
208193
*/
209-
public Optional<Response> getPrimaryResponse() {
194+
public Response getPrimaryResponse() {
210195
if (responses.isEmpty()) {
211-
return Optional.empty();
196+
return null;
212197
}
213198

214-
Optional<Response> response = responses.values().stream()
215-
.filter(r -> r.statusCode / 100 == 2)
216-
.findFirst();
217-
if (!response.isPresent()) {
218-
response = responses.values().stream().findFirst();
199+
Response firstResponse = null;
200+
for (Response response : responses.values()) {
201+
if (firstResponse == null) {
202+
firstResponse = response;
203+
}
204+
205+
if (response.statusCode / 100 == 2) {
206+
return response;
207+
}
219208
}
220-
return response;
209+
210+
return firstResponse;
221211
}
222212

223213
/**
@@ -229,8 +219,9 @@ public String getOriginalFile() {
229219

230220
/**
231221
* Heuristically find relative path of the original file to the repository.
232-
*
233-
* For instance, "specification/resources/resource-manager/Microsoft.Authorization/stable/2020-09-01/examples/getDataPolicyManifest.json"
222+
* <p>
223+
* For instance,
224+
* "specification/resources/resource-manager/Microsoft.Authorization/stable/2020-09-01/examples/getDataPolicyManifest.json"
234225
*
235226
* @return the relative path of the original file
236227
*/
@@ -241,32 +232,29 @@ public String getRelativeOriginalFileName() {
241232
URL url = new URI(originalFileName).toURL();
242233
switch (url.getProtocol()) {
243234
case "http":
244-
case "https":
245-
{
246-
String[] segments = url.getPath().split(QUOTED_SLASH);
235+
case "https": {
236+
String[] segments = url.getPath().split(SLASH);
247237
if (segments.length > 3) {
248238
// first 3 should be owner, name, branch
249239
originalFileName = Arrays.stream(segments)
250-
.filter(s -> !s.isEmpty())
251-
.skip(3)
252-
.collect(Collectors.joining(SLASH));
240+
.filter(s -> !s.isEmpty())
241+
.skip(3)
242+
.collect(Collectors.joining(SLASH));
253243
}
254244
break;
255245
}
256246

257-
case "file":
258-
{
247+
case "file": {
259248
String relativeFileName = tspDirectory != null
260-
? getRelativeOriginalFileNameForTsp(url)
261-
: getRelativeOriginalFileNameForSwagger(url);
249+
? getRelativeOriginalFileNameForTsp(url)
250+
: getRelativeOriginalFileNameForSwagger(url);
262251
if (relativeFileName != null) {
263252
originalFileName = relativeFileName;
264253
}
265254
break;
266255
}
267256

268-
default:
269-
{
257+
default: {
270258
logger.error("Unknown protocol in x-ms-original-file: '{}'", originalFileName);
271259
break;
272260
}
@@ -281,8 +269,10 @@ public String getRelativeOriginalFileName() {
281269

282270
/**
283271
* identifier of the codesnippet label from codesnippet-maven-plugin
284-
* @see <a href="https://github.com/Azure/azure-sdk-tools/blob/main/packages/java-packages/codesnippet-maven-plugin/README.md">codesnippet-maven-plugin</a>
272+
*
285273
* @return the identifier of the codesnippet label that wraps around the example code
274+
* @see <a
275+
* href="https://github.com/Azure/azure-sdk-tools/blob/main/packages/java-packages/codesnippet-maven-plugin/README.md">codesnippet-maven-plugin</a>
286276
*/
287277
public String getCodeSnippetIdentifier() {
288278
return codeSnippetIdentifier;
@@ -308,21 +298,19 @@ static String getRelativeOriginalFileNameForTsp(URL url) {
308298
* "specification/standbypool/StandbyPool.Management/examples/2023-12-01-preview/StandbyVirtualMachinePools_Update.json"
309299
*/
310300
String originalFileName = null;
311-
String[] directorySegments = tspDirectory.split(QUOTED_SLASH);
301+
String[] directorySegments = tspDirectory.split(SLASH);
312302
String directoryLastSegment = directorySegments[directorySegments.length - 1];
313303
int sharedDirectorySegment = -1;
314-
String[] segments = url.getPath().split(QUOTED_SLASH);
304+
String[] segments = url.getPath().split(SLASH);
315305
for (int i = segments.length - 1; i >= 0; --i) {
316306
if (Objects.equals(directoryLastSegment, segments[i])) {
317307
sharedDirectorySegment = i;
318308
break;
319309
}
320310
}
321311
if (sharedDirectorySegment >= 0) {
322-
originalFileName = Stream.concat(
323-
Arrays.stream(directorySegments),
324-
Arrays.stream(segments).skip(sharedDirectorySegment + 1)
325-
).collect(Collectors.joining(SLASH));
312+
originalFileName = Stream.concat(Arrays.stream(directorySegments),
313+
Arrays.stream(segments).skip(sharedDirectorySegment + 1)).collect(Collectors.joining(SLASH));
326314
}
327315
return originalFileName;
328316
}
@@ -334,7 +322,7 @@ static String getRelativeOriginalFileNameForSwagger(URL url) {
334322
* or "specification/<service>/data-plane"
335323
*/
336324
String originalFileName = null;
337-
String[] segments = url.getPath().split(QUOTED_SLASH);
325+
String[] segments = url.getPath().split(SLASH);
338326
int resourceManagerOrDataPlaneSegmentIndex = -1;
339327
for (int i = 0; i < segments.length; ++i) {
340328
if ("resource-manager".equals(segments[i]) || "data-plane".equals(segments[i])) {
@@ -344,18 +332,15 @@ static String getRelativeOriginalFileNameForSwagger(URL url) {
344332
}
345333
if (resourceManagerOrDataPlaneSegmentIndex > 2) {
346334
originalFileName = Arrays.stream(segments)
347-
.skip(resourceManagerOrDataPlaneSegmentIndex - 2)
348-
.collect(Collectors.joining(SLASH));
335+
.skip(resourceManagerOrDataPlaneSegmentIndex - 2)
336+
.collect(Collectors.joining(SLASH));
349337
}
350338
return originalFileName;
351339
}
352340

353341
@Override
354342
public String toString() {
355-
return "ProxyMethodExample{" +
356-
"parameters=" + parameters +
357-
", responses=" + responses +
358-
'}';
343+
return "ProxyMethodExample{" + "parameters=" + parameters + ", responses=" + responses + '}';
359344
}
360345

361346
public static final class Builder {

javagen/src/main/java/com/azure/autorest/template/example/ClientMethodExampleWriter.java

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,6 @@
3939
import java.util.List;
4040
import java.util.Map;
4141
import java.util.Objects;
42-
import java.util.Optional;
4342
import java.util.Set;
4443
import java.util.function.BiConsumer;
4544
import java.util.function.Consumer;
@@ -96,9 +95,8 @@ public ClientMethodExampleWriter(ClientMethod method, String clientVarName, Prox
9695
methodBlock.line(methodInvocation.toString());
9796
};
9897
responseAssertionWriter = methodBlock -> {
99-
Optional<ProxyMethodExample.Response> responseOpt = proxyMethodExample.getPrimaryResponse();
100-
if (responseOpt.isPresent()) {
101-
ProxyMethodExample.Response response = responseOpt.get();
98+
ProxyMethodExample.Response response = proxyMethodExample.getPrimaryResponse();
99+
if (response != null) {
102100
IType returnType = method.getReturnValue().getType();
103101
if (returnType instanceof GenericType) {
104102
GenericType responseType = (GenericType) returnType;

javagen/src/main/java/com/azure/autorest/template/example/ProtocolExampleWriter.java

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@
3737
import java.util.HashSet;
3838
import java.util.List;
3939
import java.util.Map;
40-
import java.util.Optional;
4140
import java.util.Set;
4241
import java.util.function.BiConsumer;
4342
import java.util.function.Consumer;
@@ -239,9 +238,8 @@ public ProtocolExampleWriter(ProtocolExample protocolExample) {
239238
};
240239

241240
this.assertionWriter = methodBlock -> {
242-
Optional<ProxyMethodExample.Response> responseOpt = proxyMethodExample.getPrimaryResponse();
243-
if (responseOpt.isPresent()) {
244-
ProxyMethodExample.Response response = responseOpt.get();
241+
ProxyMethodExample.Response response = proxyMethodExample.getPrimaryResponse();
242+
if (response != null) {
245243
IType returnType = method.getReturnValue().getType();
246244
if (returnType instanceof GenericType) {
247245
GenericType responseType = (GenericType) returnType;

0 commit comments

Comments
 (0)