ResponseEntityIo.java

  1. /*
  2.  * *********************************************************************************************************************
  3.  *
  4.  * blueMarine II: Semantic Media Centre
  5.  * http://tidalwave.it/projects/bluemarine2
  6.  *
  7.  * Copyright (C) 2015 - 2021 by Tidalwave s.a.s. (http://tidalwave.it)
  8.  *
  9.  * *********************************************************************************************************************
  10.  *
  11.  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  12.  * the License. You may obtain a copy of the License at
  13.  *
  14.  *     http://www.apache.org/licenses/LICENSE-2.0
  15.  *
  16.  * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  17.  * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the
  18.  * specific language governing permissions and limitations under the License.
  19.  *
  20.  * *********************************************************************************************************************
  21.  *
  22.  * git clone https://bitbucket.org/tidalwave/bluemarine2-src
  23.  * git clone https://github.com/tidalwave-it/bluemarine2-src
  24.  *
  25.  * *********************************************************************************************************************
  26.  */
  27. package it.tidalwave.bluemarine2.rest;

  28. import java.io.ByteArrayOutputStream;
  29. import javax.annotation.Nonnull;
  30. import java.util.List;
  31. import java.util.Map;
  32. import java.util.Optional;
  33. import java.util.function.Function;
  34. import java.io.IOException;
  35. import java.io.OutputStreamWriter;
  36. import java.io.PrintWriter;
  37. import java.nio.file.Files;
  38. import java.nio.file.Path;
  39. import org.springframework.util.LinkedMultiValueMap;
  40. import org.springframework.util.MultiValueMap;
  41. import org.springframework.http.ResponseEntity;
  42. import org.springframework.http.HttpStatus;
  43. import lombok.extern.slf4j.Slf4j;
  44. import static java.util.Comparator.*;
  45. import static java.util.stream.Collectors.*;
  46. import static java.nio.charset.StandardCharsets.*;

  47. /***********************************************************************************************************************
  48.  *
  49.  * @author  Fabrizio Giudici
  50.  *
  51.  **********************************************************************************************************************/
  52. @Slf4j
  53. public class ResponseEntityIo
  54.   {
  55.     /*******************************************************************************************************************
  56.      *
  57.      *
  58.      ******************************************************************************************************************/
  59.     public static void store (@Nonnull final Path path,
  60.                               @Nonnull final ResponseEntity<?> response,
  61.                               @Nonnull final List<String> ignoredHeaders)
  62.       {
  63.           store(path, response, ignoredHeaders, Function.identity());
  64.       }

  65.     /*******************************************************************************************************************
  66.      *
  67.      *
  68.      ******************************************************************************************************************/
  69.     public static void store (@Nonnull final Path path,
  70.                               @Nonnull final ResponseEntity<?> response,
  71.                               @Nonnull final List<String> ignoredHeaders,
  72.                               @Nonnull final Function<String, String> postProcessor)
  73.       {
  74.         try
  75.           {
  76.             log.trace("store({}, ..., ...)", path);

  77.             Files.createDirectories(path.getParent());
  78.             final ByteArrayOutputStream baos = new ByteArrayOutputStream();

  79.             try (final PrintWriter pw = new PrintWriter(new OutputStreamWriter(baos, UTF_8)))
  80.               {
  81.                 pw.printf("HTTP/1.1 %d %s%n", response.getStatusCode().value(), response.getStatusCode().name());
  82.                 response.getHeaders().entrySet().stream()
  83.                         .filter(e -> !ignoredHeaders.contains(e.getKey()))
  84.                         .sorted(comparing(Map.Entry::getKey))
  85.                         .forEach(e -> pw.printf("%s: %s%n", e.getKey(), e.getValue().get(0)));
  86.                 pw.println();
  87.                 pw.flush();
  88.                 final Object body = response.getBody();
  89.                 log.info(">>>> TYPE {}", body.getClass());

  90.                 if (body instanceof String)
  91.                   {
  92.                     pw.print(postProcessor.apply((String)body));
  93.                   }
  94.                 else
  95.                   {
  96.                     baos.write((byte[])body);
  97.                   }
  98.               }

  99.             Files.write(path, baos.toByteArray());
  100.           }
  101.         catch (IOException e)
  102.           {
  103.             log.error("Coundln't store a cache item {}", path);
  104.           }
  105.       }

  106.     /*******************************************************************************************************************
  107.      *
  108.      *
  109.      ******************************************************************************************************************/
  110.     @Nonnull
  111.     /* package */ static Optional<ResponseEntity<String>> load (@Nonnull final Path path)
  112.       throws IOException
  113.       {
  114.         log.trace("load({})", path);

  115.         if (!Files.exists(path))
  116.           {
  117.             return Optional.empty();
  118.           }

  119.         final List<String> lines = Files.readAllLines(path, UTF_8);
  120.         final HttpStatus status = HttpStatus.valueOf(Integer.parseInt(lines.get(0).split(" ")[1]));
  121.         final MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();

  122.         int i = 1;

  123.         for (; (i < lines.size()) && !lines.get(i).equals(""); i++)
  124.           {
  125.             final String[] split = lines.get(i).split(":");
  126.             headers.add(split[0], split[1].trim());
  127.           }

  128.         final String body = lines.stream().skip(i + 1).collect(joining("\n"));
  129.         final ResponseEntity<String> response = new ResponseEntity<>(body, headers, status);
  130. //        log.trace(">>>> returning {}", response);

  131.         return Optional.of(response);
  132.       }
  133.   }