Advertisement
Guest User

Untitled

a guest
May 15th, 2024
391
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.61 KB | None | 0 0
  1. record Bar(int id);
  2.  
  3. interface Foo {
  4.     // returns some domain entity
  5.     // if it doesnt exist return null
  6.     // if it cannot be obtained due to system error throw runtime exception
  7.     Bar getBarById(int id);
  8. }
  9.  
  10. class ConcreteFoo implements Foo {
  11.     public Bar getBarById(int id) {
  12.         return new Bar(id);
  13.     }
  14. }
  15.  
  16. class HttpClientFoo implements Foo {
  17.     private HttpClient client;
  18.     public HttpClientFoo(HttpClient client) {
  19.         this.client = client;
  20.     }
  21.  
  22.     public Bar getBarById(int id) {
  23.         // suppose client is raw http client that returns string
  24.         try {
  25.             Response<String> externalResult = this.client.get("/api/foo/" + id);
  26.             if(externalResult.isSuccessful()) {
  27.                 String body = externalResult.body();
  28.                 // suppose some parsing method exists and returns Bar
  29.                 return parseBody(body);
  30.             }
  31.             return null;
  32.         }
  33.         catch (Exception e) {
  34.             throw new RuntimeException(e);
  35.         }
  36.     }
  37. }
  38.  
  39. class ControllerFoo implements Foo {
  40.     private Foo delegate;
  41.     public ControllerFoo(Foo delegate) {
  42.         this.delegate = delegate;
  43.     }
  44.  
  45.     @GET
  46.     @Path("/api/foo/{id}")
  47.     public Bar getBarById(@PathParam("id") int id) {
  48.         return delegate.getBarById(id);
  49.     }
  50. }
  51.  
  52. class Main {
  53.     public static void main(String args[]) {
  54.         Foo concreteFoo = new ConcreteFoo();
  55.         Foo controller = new ControllerFoo(concreteFoo);
  56.         Server.listen(3000)
  57.             .controler(controler) // suppose theres a server utility class to host servers
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement