@@ -188,10 +188,11 @@ public void handle(final HttpExchange exchange) throws IOException {
188188
189189 } else if (request .isCompleteMultipartUploadRequest ()) {
190190 final byte [] responseBody ;
191- boolean preconditionFailed = false ;
191+ final boolean preconditionFailed ;
192192 synchronized (uploads ) {
193193 final var upload = getUpload (request .getQueryParamOnce ("uploadId" ));
194194 if (upload == null ) {
195+ preconditionFailed = false ;
195196 if (Randomness .get ().nextBoolean ()) {
196197 responseBody = null ;
197198 } else {
@@ -207,14 +208,7 @@ public void handle(final HttpExchange exchange) throws IOException {
207208 } else {
208209 final var blobContents = upload .complete (extractPartEtags (Streams .readFully (exchange .getRequestBody ())));
209210
210- if (isProtectOverwrite (exchange )) {
211- var previousValue = blobs .putIfAbsent (request .path (), blobContents );
212- if (previousValue != null ) {
213- preconditionFailed = true ;
214- }
215- } else {
216- blobs .put (request .path (), blobContents );
217- }
211+ preconditionFailed = updateBlobContents (exchange , request .path (), blobContents ) == false ;
218212
219213 if (preconditionFailed == false ) {
220214 responseBody = ("<?xml version=\" 1.0\" encoding=\" UTF-8\" ?>\n "
@@ -268,15 +262,7 @@ public void handle(final HttpExchange exchange) throws IOException {
268262 }
269263 } else {
270264 final Tuple <String , BytesReference > blob = parseRequestBody (exchange );
271- boolean preconditionFailed = false ;
272- if (isProtectOverwrite (exchange )) {
273- var previousValue = blobs .putIfAbsent (request .path (), blob .v2 ());
274- if (previousValue != null ) {
275- preconditionFailed = true ;
276- }
277- } else {
278- blobs .put (request .path (), blob .v2 ());
279- }
265+ final var preconditionFailed = updateBlobContents (exchange , request .path (), blob .v2 ()) == false ;
280266
281267 if (preconditionFailed ) {
282268 exchange .sendResponseHeaders (RestStatus .PRECONDITION_FAILED .getStatus (), -1 );
@@ -413,6 +399,20 @@ public void handle(final HttpExchange exchange) throws IOException {
413399 }
414400 }
415401
402+ /**
403+ * Update the blob contents if and only if the preconditions in the request are satisfied.
404+ *
405+ * @return whether the blob contents were updated: if {@code false} then a requested precondition was not satisfied.
406+ */
407+ private boolean updateBlobContents (HttpExchange exchange , String path , BytesReference newContents ) {
408+ if (isProtectOverwrite (exchange )) {
409+ return blobs .putIfAbsent (path , newContents ) == null ;
410+ } else {
411+ blobs .put (path , newContents );
412+ return true ;
413+ }
414+ }
415+
416416 public Map <String , BytesReference > blobs () {
417417 return blobs ;
418418 }
0 commit comments