specshield 3.4.15 → 3.4.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,532 @@
1
+ 'use strict';
2
+
3
+ const path = require('path');
4
+ const fsExtra = require('fs-extra');
5
+
6
+ /**
7
+ * Generates a Spring Boot 3 version layer from verified transforms:
8
+ *
9
+ * CompatTransform.java one rewrite (data) — fixed
10
+ * CompatVersion.java the transforms a version introduced — fixed
11
+ * CompatEngine.java applies transforms to Jackson trees — fixed
12
+ * CompatResponseAdvice.java old clients get the old response shape — fixed
13
+ * CompatRequestAdvice.java old request shapes are upgraded on the way in — fixed
14
+ * ApiVersion_<v>.java this change's transforms — generated per version
15
+ *
16
+ * The fixed files implement the same rules as shim/transforms.js, where the
17
+ * CLI verified every transform before generating anything. Re-running for a
18
+ * later version adds another ApiVersion_<v> class; the runtime applies every
19
+ * version newer than the one the client asked for, newest first.
20
+ *
21
+ * A client's version comes from a request header (X-API-Version by default).
22
+ * Clients that send none are treated as the version before the oldest
23
+ * change: existing integrations keep their shape without changing anything.
24
+ */
25
+ async function generateSpring(shim, { dir, pkg, header, version, basePath }) {
26
+ if (!/^[a-zA-Z_][\w]*(\.[a-zA-Z_][\w]*)*$/.test(pkg)) throw new Error(`--package "${pkg}" is not a Java package name`);
27
+ const out = path.join(dir, ...pkg.split('.'));
28
+ const files = {
29
+ 'CompatTransform.java': transformClass(pkg),
30
+ 'CompatVersion.java': versionInterface(pkg),
31
+ 'CompatEngine.java': engineClass(pkg),
32
+ 'CompatResponseAdvice.java': responseAdvice(pkg, header, basePath),
33
+ 'CompatRequestAdvice.java': requestAdvice(pkg, header, basePath),
34
+ [`${versionClassName(version)}.java`]: versionClass(pkg, version, shim.transforms),
35
+ };
36
+ const written = [];
37
+ for (const [name, content] of Object.entries(files)) {
38
+ const file = path.join(out, name);
39
+ await fsExtra.outputFile(file, content);
40
+ written.push(file);
41
+ }
42
+ return written;
43
+ }
44
+
45
+ function versionClassName(version) {
46
+ return `ApiVersion_${String(version).replace(/[^A-Za-z0-9]+/g, '_').replace(/^_+|_+$/g, '') || 'next'}`;
47
+ }
48
+
49
+ const j = (s) => JSON.stringify(s === undefined ? null : s);
50
+ const header = (pkg) => `// Generated by SpecShield (specshield fix --spring). Safe to edit; re-running overwrites it.\npackage ${pkg};\n`;
51
+
52
+ // ─── per-version transforms ─────────────────────────────────────────────────
53
+
54
+ function versionClass(pkg, version, transforms) {
55
+ // Renames and enum mappings are inferred from the spec diff (a field gone
56
+ // and a similar one added); say so where a reviewer will read it.
57
+ const lines = transforms.map((t) => ` ${t.kind === 'rename' || t.kind === 'enum' ? '/* inferred rename — check */ ' : ''}${call(t)}`);
58
+ return `${header(pkg)}
59
+ import java.util.List;
60
+ import org.springframework.stereotype.Component;
61
+
62
+ /**
63
+ * What changed in API version ${version}, as rewrites that give clients on an
64
+ * older version the shape they were built against. Each one was checked by
65
+ * SpecShield against the old schema on sample payloads.
66
+ */
67
+ @Component
68
+ public class ${versionClassName(version)} implements CompatVersion {
69
+
70
+ @Override
71
+ public String version() {
72
+ return ${j(String(version))};
73
+ }
74
+
75
+ @Override
76
+ public List<CompatTransform> transforms() {
77
+ return List.of(
78
+ ${lines.join(',\n')}
79
+ );
80
+ }
81
+ }
82
+ `;
83
+ }
84
+
85
+ function call(t) {
86
+ // A value rewrite of array elements (field null) addresses the array and
87
+ // uses the field "[]": "rewrite each element".
88
+ const elements = (t.kind === 'convert' || t.kind === 'enum') && t.field === null;
89
+ const steps = elements ? t.at.slice(0, -1) : t.at;
90
+ const field = elements ? '[]' : t.field;
91
+ t = { ...t, field };
92
+ const at = `CompatTransform.steps(${steps.map((s) => (s.prop !== undefined ? j(s.prop) : s.items ? '"[]"' : '"{}"')).join(', ')})`;
93
+ const head = `${j(t.method)}, ${j(t.path)}, ${j(t.code)}, ${at}`;
94
+ const side = t.side === 'response' ? 'response' : 'request';
95
+ switch (t.kind) {
96
+ case 'rename': return `CompatTransform.${side}Rename(${head}, ${j(t.from)}, ${j(t.to)})`;
97
+ case 'convert': return `CompatTransform.${side}Convert(${head}, ${j(t.field)}, ${j(t.to)})`;
98
+ case 'enum': return `CompatTransform.${side}Enum(${head}, ${j(t.field)}, ${j(JSON.stringify(t.from))}, ${j(JSON.stringify(t.to))})`;
99
+ case 'default': return `CompatTransform.${side}Default(${head}, ${j(t.field)}, ${j(JSON.stringify(t.value))})`;
100
+ case 'unwrap': return `CompatTransform.${side}Unwrap(${head}, ${j(t.property)})`;
101
+ default: throw new Error(`unknown transform ${t.kind}`);
102
+ }
103
+ }
104
+
105
+ // ─── fixed runtime ──────────────────────────────────────────────────────────
106
+
107
+ function transformClass(pkg) {
108
+ return `${header(pkg)}
109
+ import com.fasterxml.jackson.databind.JsonNode;
110
+ import com.fasterxml.jackson.databind.ObjectMapper;
111
+ import java.util.List;
112
+
113
+ /**
114
+ * One JSON rewrite for one operation. {@code at} addresses the object (or
115
+ * array) it acts on from the body root: a property name, "[]" for every
116
+ * array element, "{}" for every map value. A value rewrite with
117
+ * {@code field} "[]" rewrites the elements of the array at {@code at}.
118
+ */
119
+ public record CompatTransform(
120
+ String method, String path, String status, boolean response, Kind kind,
121
+ List<String> at, String from, String to, String field, JsonNode fromValue, JsonNode toValue) {
122
+
123
+ public enum Kind { RENAME, CONVERT, ENUM, DEFAULT, UNWRAP }
124
+
125
+ private static final ObjectMapper JSON = new ObjectMapper();
126
+
127
+ public static List<String> steps(String... steps) {
128
+ return List.of(steps);
129
+ }
130
+
131
+ public static CompatTransform responseRename(String m, String p, String s, List<String> at, String from, String to) {
132
+ return new CompatTransform(m, p, s, true, Kind.RENAME, at, from, to, null, null, null);
133
+ }
134
+
135
+ public static CompatTransform requestRename(String m, String p, String s, List<String> at, String from, String to) {
136
+ return new CompatTransform(m, p, s, false, Kind.RENAME, at, from, to, null, null, null);
137
+ }
138
+
139
+ public static CompatTransform responseConvert(String m, String p, String s, List<String> at, String field, String toType) {
140
+ return new CompatTransform(m, p, s, true, Kind.CONVERT, at, null, toType, field, null, null);
141
+ }
142
+
143
+ public static CompatTransform requestConvert(String m, String p, String s, List<String> at, String field, String toType) {
144
+ return new CompatTransform(m, p, s, false, Kind.CONVERT, at, null, toType, field, null, null);
145
+ }
146
+
147
+ public static CompatTransform responseEnum(String m, String p, String s, List<String> at, String field, String from, String to) {
148
+ return new CompatTransform(m, p, s, true, Kind.ENUM, at, null, null, field, json(from), json(to));
149
+ }
150
+
151
+ public static CompatTransform requestEnum(String m, String p, String s, List<String> at, String field, String from, String to) {
152
+ return new CompatTransform(m, p, s, false, Kind.ENUM, at, null, null, field, json(from), json(to));
153
+ }
154
+
155
+ public static CompatTransform requestDefault(String m, String p, String s, List<String> at, String field, String value) {
156
+ return new CompatTransform(m, p, s, false, Kind.DEFAULT, at, null, null, field, null, json(value));
157
+ }
158
+
159
+ public static CompatTransform responseUnwrap(String m, String p, String s, List<String> at, String property) {
160
+ return new CompatTransform(m, p, s, true, Kind.UNWRAP, at, property, null, null, null, null);
161
+ }
162
+
163
+ private static JsonNode json(String literal) {
164
+ try {
165
+ return JSON.readTree(literal);
166
+ } catch (Exception e) {
167
+ throw new IllegalArgumentException("Invalid JSON literal " + literal, e);
168
+ }
169
+ }
170
+ }
171
+ `;
172
+ }
173
+
174
+ function versionInterface(pkg) {
175
+ return `${header(pkg)}
176
+ import java.util.List;
177
+
178
+ /** The rewrites one API version introduced. Implementations are Spring beans. */
179
+ public interface CompatVersion {
180
+
181
+ /** The version that introduced these changes, e.g. "2.0.0" or "2026-11-01". */
182
+ String version();
183
+
184
+ List<CompatTransform> transforms();
185
+ }
186
+ `;
187
+ }
188
+
189
+ function engineClass(pkg) {
190
+ return `${header(pkg)}
191
+ import com.fasterxml.jackson.databind.JsonNode;
192
+ import com.fasterxml.jackson.databind.node.ArrayNode;
193
+ import com.fasterxml.jackson.databind.node.BooleanNode;
194
+ import com.fasterxml.jackson.databind.node.JsonNodeFactory;
195
+ import com.fasterxml.jackson.databind.node.ObjectNode;
196
+ import java.math.BigDecimal;
197
+ import java.util.ArrayList;
198
+ import java.util.Comparator;
199
+ import java.util.List;
200
+ import java.util.function.Consumer;
201
+ import java.util.function.UnaryOperator;
202
+ import java.util.regex.Pattern;
203
+ import org.springframework.stereotype.Component;
204
+ import org.springframework.util.AntPathMatcher;
205
+
206
+ /**
207
+ * Applies version transforms to Jackson trees. The rules match SpecShield's
208
+ * own implementation, where every transform was verified:
209
+ * responses are rewritten from the newest version down to the client's,
210
+ * requests from the client's version up; unwrap runs first; on responses
211
+ * renames run before value rewrites, on requests after them.
212
+ */
213
+ @Component
214
+ public class CompatEngine {
215
+
216
+ private static final Pattern NUMBER = Pattern.compile("\\\\s*-?\\\\d+(\\\\.\\\\d+)?([eE][+-]?\\\\d+)?\\\\s*");
217
+ private final List<CompatVersion> versions;
218
+ private final AntPathMatcher paths = new AntPathMatcher();
219
+
220
+ public CompatEngine(List<CompatVersion> versions) {
221
+ this.versions = new ArrayList<>(versions);
222
+ this.versions.sort(Comparator.comparing(CompatVersion::version, CompatEngine::compareVersions));
223
+ }
224
+
225
+ /** The version a client that sends no version header is on: the one before the oldest change. */
226
+ public String oldestVersion() {
227
+ return versions.isEmpty() ? null : versions.get(0).version();
228
+ }
229
+
230
+ public JsonNode response(String clientVersion, String method, String path, int status, JsonNode body) {
231
+ JsonNode root = body;
232
+ for (int i = versions.size() - 1; i >= 0; i--) {
233
+ CompatVersion v = versions.get(i);
234
+ if (!olderThan(clientVersion, v.version())) continue;
235
+ root = apply(root, select(v, true, method, path, status));
236
+ }
237
+ return root;
238
+ }
239
+
240
+ public JsonNode request(String clientVersion, String method, String path, JsonNode body) {
241
+ JsonNode root = body;
242
+ for (CompatVersion v : versions) {
243
+ if (!olderThan(clientVersion, v.version())) continue;
244
+ root = apply(root, select(v, false, method, path, -1));
245
+ }
246
+ return root;
247
+ }
248
+
249
+ /** True when there is anything to do for this request at all. */
250
+ public boolean applies(String clientVersion, boolean response, String method, String path) {
251
+ for (CompatVersion v : versions) {
252
+ if (!olderThan(clientVersion, v.version())) continue;
253
+ for (CompatTransform t : v.transforms()) {
254
+ if (t.response() == response && t.method().equalsIgnoreCase(method) && paths.match(t.path(), path)) return true;
255
+ }
256
+ }
257
+ return false;
258
+ }
259
+
260
+ private List<CompatTransform> select(CompatVersion v, boolean response, String method, String path, int status) {
261
+ List<CompatTransform> out = new ArrayList<>();
262
+ for (CompatTransform t : v.transforms()) {
263
+ if (t.response() != response || !t.method().equalsIgnoreCase(method) || !paths.match(t.path(), path)) continue;
264
+ if (response && t.status() != null && !t.status().equals(String.valueOf(status))) continue;
265
+ out.add(t);
266
+ }
267
+ out.sort(Comparator.comparingInt(t -> rank(t)));
268
+ return out;
269
+ }
270
+
271
+ private static int rank(CompatTransform t) {
272
+ return switch (t.kind()) {
273
+ case UNWRAP -> 0;
274
+ case RENAME -> t.response() ? 1 : 3;
275
+ case DEFAULT -> t.response() ? 2 : 4;
276
+ case CONVERT -> t.response() ? 3 : 1;
277
+ case ENUM -> t.response() ? 4 : 2;
278
+ };
279
+ }
280
+
281
+ JsonNode apply(JsonNode root, List<CompatTransform> transforms) {
282
+ for (CompatTransform t : transforms) {
283
+ if (t.kind() == CompatTransform.Kind.UNWRAP) {
284
+ if (root instanceof ObjectNode o && o.has(t.from())) root = o.get(t.from());
285
+ continue;
286
+ }
287
+ forEachAt(root, t.at(), 0, node -> applyOne(node, t));
288
+ }
289
+ return root;
290
+ }
291
+
292
+ private void forEachAt(JsonNode node, List<String> steps, int i, Consumer<JsonNode> fn) {
293
+ if (node == null) return;
294
+ if (i == steps.size()) { fn.accept(node); return; }
295
+ String s = steps.get(i);
296
+ if ("[]".equals(s)) {
297
+ if (node instanceof ArrayNode a) for (JsonNode el : a) forEachAt(el, steps, i + 1, fn);
298
+ } else if ("{}".equals(s)) {
299
+ if (node instanceof ObjectNode o) o.elements().forEachRemaining(v -> forEachAt(v, steps, i + 1, fn));
300
+ } else if (node instanceof ObjectNode o && o.has(s)) {
301
+ forEachAt(o.get(s), steps, i + 1, fn);
302
+ }
303
+ }
304
+
305
+ private void applyOne(JsonNode node, CompatTransform t) {
306
+ switch (t.kind()) {
307
+ case RENAME -> {
308
+ if (node instanceof ObjectNode o && o.has(t.from()) && !o.has(t.to())) {
309
+ o.set(t.to(), o.get(t.from()));
310
+ o.remove(t.from());
311
+ }
312
+ }
313
+ case DEFAULT -> {
314
+ if (node instanceof ObjectNode o && !o.has(t.field())) o.set(t.field(), t.toValue().deepCopy());
315
+ }
316
+ default -> {
317
+ UnaryOperator<JsonNode> rewrite = v -> t.kind() == CompatTransform.Kind.ENUM
318
+ ? (v.equals(t.fromValue()) ? t.toValue().deepCopy() : v)
319
+ : convert(v, t.to());
320
+ if ("[]".equals(t.field())) {
321
+ if (node instanceof ArrayNode a) for (int k = 0; k < a.size(); k++) a.set(k, rewrite.apply(a.get(k)));
322
+ } else if (node instanceof ObjectNode o && o.has(t.field())) {
323
+ o.set(t.field(), rewrite.apply(o.get(t.field())));
324
+ }
325
+ }
326
+ }
327
+ }
328
+
329
+ /** Converts a JSON scalar; leaves it untouched when it has no faithful form in the target type. */
330
+ static JsonNode convert(JsonNode v, String to) {
331
+ if (v == null || v.isNull()) return v;
332
+ JsonNodeFactory f = JsonNodeFactory.instance;
333
+ switch (to) {
334
+ case "string":
335
+ if (v.isTextual()) return v;
336
+ // 12.0 → "12", like JavaScript's String(12.0) where the transform was verified.
337
+ return f.textNode(v.isNumber() ? v.decimalValue().stripTrailingZeros().toPlainString() : v.asText());
338
+ case "boolean":
339
+ if (v.isBoolean()) return v;
340
+ if (v.isTextual() && "true".equals(v.asText()) || v.isNumber() && v.decimalValue().compareTo(BigDecimal.ONE) == 0) return BooleanNode.TRUE;
341
+ if (v.isTextual() && "false".equals(v.asText()) || v.isNumber() && v.decimalValue().signum() == 0) return BooleanNode.FALSE;
342
+ return v;
343
+ default:
344
+ BigDecimal n;
345
+ if (v.isNumber()) n = v.decimalValue();
346
+ else if (v.isTextual() && NUMBER.matcher(v.asText()).matches()) n = new BigDecimal(v.asText().trim());
347
+ else return v;
348
+ if ("integer".equals(to)) {
349
+ BigDecimal s = n.stripTrailingZeros();
350
+ return s.scale() > 0 ? v : f.numberNode(s.toBigIntegerExact());
351
+ }
352
+ return f.numberNode(n);
353
+ }
354
+ }
355
+
356
+ boolean olderThan(String client, String version) {
357
+ return client == null || compareVersions(client, version) < 0;
358
+ }
359
+
360
+ /** "1.10.0" > "1.9.2"; dates "2026-11-01" compare as numbers too. */
361
+ static int compareVersions(String a, String b) {
362
+ String[] x = a.trim().replaceFirst("^[vV]", "").split("[^A-Za-z0-9]+");
363
+ String[] y = b.trim().replaceFirst("^[vV]", "").split("[^A-Za-z0-9]+");
364
+ for (int i = 0; i < Math.max(x.length, y.length); i++) {
365
+ String p = i < x.length ? x[i] : "0";
366
+ String q = i < y.length ? y[i] : "0";
367
+ int c = p.matches("\\\\d+") && q.matches("\\\\d+")
368
+ ? new java.math.BigInteger(p).compareTo(new java.math.BigInteger(q))
369
+ : p.compareTo(q);
370
+ if (c != 0) return c;
371
+ }
372
+ return 0;
373
+ }
374
+ }
375
+ `;
376
+ }
377
+
378
+ function responseAdvice(pkg, headerName, basePath) {
379
+ return `${header(pkg)}
380
+ import com.fasterxml.jackson.databind.JsonNode;
381
+ import com.fasterxml.jackson.databind.ObjectMapper;
382
+ import jakarta.servlet.http.HttpServletRequest;
383
+ import org.springframework.beans.factory.annotation.Value;
384
+ import org.springframework.core.MethodParameter;
385
+ import org.springframework.http.MediaType;
386
+ import org.springframework.http.converter.HttpMessageConverter;
387
+ import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter;
388
+ import org.springframework.http.server.ServerHttpRequest;
389
+ import org.springframework.http.server.ServerHttpResponse;
390
+ import org.springframework.http.server.ServletServerHttpRequest;
391
+ import org.springframework.http.server.ServletServerHttpResponse;
392
+ import org.springframework.web.bind.annotation.ControllerAdvice;
393
+ import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
394
+
395
+ /** Rewrites JSON responses into the shape of the version the client asked for. */
396
+ @ControllerAdvice
397
+ public class CompatResponseAdvice implements ResponseBodyAdvice<Object> {
398
+
399
+ private final CompatEngine engine;
400
+ private final ObjectMapper mapper;
401
+ private final String header;
402
+ private final String basePath;
403
+
404
+ public CompatResponseAdvice(CompatEngine engine, ObjectMapper mapper,
405
+ @Value("\${specshield.compat.header:${headerName}}") String header,
406
+ @Value("\${specshield.compat.base-path:${basePath}}") String basePath) {
407
+ this.engine = engine;
408
+ this.mapper = mapper;
409
+ this.header = header;
410
+ this.basePath = basePath;
411
+ }
412
+
413
+ @Override
414
+ public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
415
+ return AbstractJackson2HttpMessageConverter.class.isAssignableFrom(converterType);
416
+ }
417
+
418
+ @Override
419
+ public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType contentType,
420
+ Class<? extends HttpMessageConverter<?>> converterType,
421
+ ServerHttpRequest request, ServerHttpResponse response) {
422
+ if (body == null || !(request instanceof ServletServerHttpRequest req)) return body;
423
+ HttpServletRequest http = req.getServletRequest();
424
+ String client = clientVersion(http);
425
+ String path = apiPath(http);
426
+ if (!engine.applies(client, true, http.getMethod(), path)) return body;
427
+ int status = response instanceof ServletServerHttpResponse r ? r.getServletResponse().getStatus() : 200;
428
+ JsonNode tree = mapper.valueToTree(body);
429
+ return engine.response(client, http.getMethod(), path, status, tree);
430
+ }
431
+
432
+ private String clientVersion(HttpServletRequest http) {
433
+ String v = http.getHeader(header);
434
+ return v == null || v.isBlank() ? null : v.trim();
435
+ }
436
+
437
+ private String apiPath(HttpServletRequest http) {
438
+ String p = http.getRequestURI().substring(http.getContextPath().length());
439
+ return !basePath.isEmpty() && p.startsWith(basePath) ? p.substring(basePath.length()) : p;
440
+ }
441
+ }
442
+ `;
443
+ }
444
+
445
+ function requestAdvice(pkg, headerName, basePath) {
446
+ return `${header(pkg)}
447
+ import com.fasterxml.jackson.databind.JsonNode;
448
+ import com.fasterxml.jackson.databind.ObjectMapper;
449
+ import jakarta.servlet.http.HttpServletRequest;
450
+ import java.io.ByteArrayInputStream;
451
+ import java.io.IOException;
452
+ import java.io.InputStream;
453
+ import java.lang.reflect.Type;
454
+ import org.springframework.beans.factory.annotation.Value;
455
+ import org.springframework.core.MethodParameter;
456
+ import org.springframework.http.HttpHeaders;
457
+ import org.springframework.http.HttpInputMessage;
458
+ import org.springframework.http.converter.HttpMessageConverter;
459
+ import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter;
460
+ import org.springframework.web.bind.annotation.ControllerAdvice;
461
+ import org.springframework.web.context.request.RequestContextHolder;
462
+ import org.springframework.web.context.request.ServletRequestAttributes;
463
+ import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;
464
+
465
+ /** Upgrades JSON request bodies sent in an older version's shape before Spring binds them. */
466
+ @ControllerAdvice
467
+ public class CompatRequestAdvice extends RequestBodyAdviceAdapter {
468
+
469
+ private final CompatEngine engine;
470
+ private final ObjectMapper mapper;
471
+ private final String header;
472
+ private final String basePath;
473
+
474
+ public CompatRequestAdvice(CompatEngine engine, ObjectMapper mapper,
475
+ @Value("\${specshield.compat.header:${headerName}}") String header,
476
+ @Value("\${specshield.compat.base-path:${basePath}}") String basePath) {
477
+ this.engine = engine;
478
+ this.mapper = mapper;
479
+ this.header = header;
480
+ this.basePath = basePath;
481
+ }
482
+
483
+ @Override
484
+ public boolean supports(MethodParameter parameter, Type targetType,
485
+ Class<? extends HttpMessageConverter<?>> converterType) {
486
+ return AbstractJackson2HttpMessageConverter.class.isAssignableFrom(converterType);
487
+ }
488
+
489
+ @Override
490
+ public HttpInputMessage beforeBodyRead(HttpInputMessage input, MethodParameter parameter, Type targetType,
491
+ Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
492
+ if (!(RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attrs)) return input;
493
+ HttpServletRequest http = attrs.getRequest();
494
+ String v = http.getHeader(header);
495
+ String client = v == null || v.isBlank() ? null : v.trim();
496
+ String p = http.getRequestURI().substring(http.getContextPath().length());
497
+ String path = !basePath.isEmpty() && p.startsWith(basePath) ? p.substring(basePath.length()) : p;
498
+ if (!engine.applies(client, false, http.getMethod(), path)) return input;
499
+
500
+ byte[] raw = input.getBody().readAllBytes();
501
+ if (raw.length == 0) return replay(input.getHeaders(), raw);
502
+ JsonNode tree;
503
+ try {
504
+ tree = mapper.readTree(raw);
505
+ } catch (IOException notJson) {
506
+ return replay(input.getHeaders(), raw); // let Spring report the bad body as usual
507
+ }
508
+ byte[] upgraded = mapper.writeValueAsBytes(engine.request(client, http.getMethod(), path, tree));
509
+ return replay(input.getHeaders(), upgraded);
510
+ }
511
+
512
+ private static HttpInputMessage replay(HttpHeaders original, byte[] body) {
513
+ HttpHeaders headers = new HttpHeaders();
514
+ headers.putAll(original);
515
+ headers.setContentLength(body.length);
516
+ return new HttpInputMessage() {
517
+ @Override
518
+ public InputStream getBody() {
519
+ return new ByteArrayInputStream(body);
520
+ }
521
+
522
+ @Override
523
+ public HttpHeaders getHeaders() {
524
+ return headers;
525
+ }
526
+ };
527
+ }
528
+ }
529
+ `;
530
+ }
531
+
532
+ module.exports = { generateSpring, versionClassName };