001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.rest.mock.classic;
018
019import static java.util.Collections.*;
020import static org.apache.juneau.commons.utils.Shorts.*;
021import static org.apache.juneau.commons.utils.StringUtils.*;
022import static org.apache.juneau.rest.server.util.RestUtils.*;
023
024import java.io.*;
025import java.net.*;
026import java.util.*;
027import java.util.concurrent.*;
028import java.util.logging.*;
029import java.util.zip.*;
030
031import org.apache.http.*;
032import org.apache.http.client.methods.*;
033import org.apache.http.conn.*;
034import org.apache.http.entity.*;
035import org.apache.http.message.*;
036import org.apache.juneau.commons.inject.*;
037import org.apache.juneau.http.classic.header.ContentType;
038import org.apache.juneau.http.remote.*;
039import org.apache.juneau.marshall.*;
040import org.apache.juneau.marshall.parser.*;
041import org.apache.juneau.rest.client.classic.*;
042import org.apache.juneau.rest.client.classic.RestRequest;
043import org.apache.juneau.rest.mock.*;
044import org.apache.juneau.rest.server.*;
045import org.apache.juneau.rest.server.logging.*;
046
047import jakarta.servlet.http.*;
048
049/**
050 * Mocked {@link RestClient}.
051 *
052 * <p>
053 *    This class is used for performing serverless unit testing of {@link Rest @Rest}-annotated and {@link Remote @Remote}-annotated classes.
054 *
055 * <p>
056 *    The class itself extends from {@link RestClient} providing it with the rich feature set of that API and combines
057 *    it with the Apache HttpClient {@link HttpClientConnection} interface for processing requests.
058 *  The class converts {@link HttpRequest} objects to instances of {@link MockServletRequest} and {@link MockServletResponse} which are passed directly
059 *  to the call handler on the resource class {@link RestContext#execute(Object,HttpServletRequest,HttpServletResponse)}.
060 *  In effect, you're fully testing your REST API as if it were running in a live servlet container, yet not
061 *  actually having to run in a servlet container.
062 *  All aspects of the client and server side code are tested, yet no servlet container is required.  The actual
063 *  over-the-wire transmission is the only aspect being bypassed.
064 *
065 * <p>
066 * The following shows a simple example of invoking a PUT method on a simple REST interface and asserting the correct status code and response body:
067 *
068 * <h2 class='figure'>Example:</h2>
069 * <p class='bjava'>
070 *    <jk>public class</jk> MockTest {
071 *
072 *       <jc>// A simple bean with one field.</jc>
073 *       <jk>public static class</jk> MyBean {
074 *          <jk>public int</jk> <jf>foo</jf> = 1;
075 *       }
076 *
077 *       <jc>// Our REST resource to test.</jc>
078 *       <jc>// Simply echos the response.</jc>
079 *       <ja>@Rest</ja>(
080 *          serializers=Json5Serializer.<jk>class</jk>,
081 *          parsers=JsonParser.<jk>class</jk>
082 *       )
083 *       <jk>public static class</jk> EchoRest {
084 *
085 *          <ja>@RestPut</ja>(
086 *             path=<js>"/echo"</js>
087 *          )
088 *          <jk>public</jk> MyBean echo(<ja>@Content</ja> MyBean <jv>bean</jv>) {
089 *             <jk>return</jk> <jv>bean</jv>;
090 *          }
091 *       }
092 *
093 *       <jc>// Our JUnit test.</jc>
094 *       <ja>@Test</ja>
095 *       <jk>public void</jk> testEcho() <jk>throws</jk> Exception {
096 *
097 *          MyBean <jv>myBean</jv> = <jk>new</jk> MyBean();
098 *
099 *          <jc>// Do a round-trip on the bean through the REST interface</jc>
100 *          <jv>myBean</jv> = MockRestClient
101 *             .<jsm>create</jsm>(EchoRest.<jk>class</jk>)
102 *             .json5()
103 *             .build()
104 *             .put(<js>"/echo"</js>, <jv>myBean</jv>)
105 *             .run()
106 *             .assertStatus().is(200)
107 *             .assertContent().is(<js>"{foo:1}"</js>)
108 *             .getContent().as(MyBean.<jk>class</jk>);
109 *
110 *          <jsm>assertEquals</jsm>(1, <jv>myBean</jv>.<jf>foo</jf>);
111 *       }
112 *    }
113 * </p>
114 * <p>
115 *    Breaking apart the fluent method call above will help you understand how this works.
116 *
117 * <p class='bjava'>
118 *    <ja>@Test</ja>
119 *    <jk>public void</jk> testEcho() <jk>throws</jk> Exception {
120 *
121 *       <jc>// Instantiate our mock client.</jc>
122 *       MockRestClient <jv>client</jv> = MockRestClient
123 *          .<jsm>create</jsm>(EchoRest.<jk>class</jk>)
124 *          .json5()
125 *          .build();
126 *
127 *       <jc>// Create a request.</jc>
128 *       RestRequest <jv>req</jv> = <jv>client</jv>.put(<js>"/echo"</js>, <jv>bean</jv>);
129 *
130 *       <jc>// Execute it (by calling RestCallHandler.service(...) and then returning the response object).</jc>
131 *       RestResponse <jv>res</jv> = <jv>req</jv>.run();
132 *
133 *       <jc>// Run assertion tests on the results.</jc>
134 *       <jv>res</jv>.assertStatus().is(200);
135 *       <jv>res</jv>.assertContent().is(<js>"'foo'"</js>);
136 *
137 *       <jc>// Convert the content of the response to a bean.</jc>
138 *       <jv>bean</jv> = <jv>res</jv>.getContent().as(MyBean.<jk>class</jk>);
139 *    }
140 * </p>
141 *
142 * <p>
143 *    The <c>create(Object)</c> method can take in either <c>Class</c> objects or pre-instantiated beans.
144 *    The latter is particularly useful for testing Spring beans.
145 *
146 * <p>
147 *    The {@link MockRestRequest} object has convenience methods provided to allow you to set any properties
148 *    directly on the underlying {@link HttpServletRequest} object.  The following example shows how
149 *    this can be used to directly set roles on the request object to perform security testing.
150 *
151 * <h2 class='figure'>Example:</h2>
152 * <p class='bjava'>
153 *    <ja>@Rest</ja>(roleGuard=<js>"ADMIN"</js>)
154 *    <jk>public class</jk> A {
155 *       <ja>@RestGet</ja>
156 *       <jk>public</jk> String get() {
157 *          <jk>return</jk> <js>"OK"</js>;
158 *       }
159 *    }
160 *
161 *    <ja>@Test</ja>
162 *    <jk>public void</jk> mytest() <jk>throws</jk> Exception {
163 *       MockRestClient <jv>client</jv> = MockRestClient.<jsm>build</jsm>(A.<jk>class</jk>);
164 *
165 *       <jc>// Admin user should get 200, but anyone else should get 403-Unauthorized.</jc>
166 *       <jv>client</jv>.get().roles(<js>"ADMIN"</js>).run().assertStatus().is(200);
167 *       <jv>client</jv>.get().roles(<js>"USER"</js>).run().assertStatus().is(403);
168 *    }
169 * </p>
170 *
171 * <p>
172 *    Debug mode is provided that will cause your HTTP requests and responses to be sent to the console:
173 *
174 * <h2 class='figure'>Example:</h2>
175 * <p class='bjava'>
176 *    MockRestClient <jv>client</jv> = MockRestClient
177 *       .<jsm>create</jsm>(MyRest.<jk>class</jk>)
178 *       .debug()
179 *       .json5()
180 *       .build();
181 * </p>
182 *
183 * <p>
184 *    The class can also be used for testing of {@link Remote @Remote}-annotated interfaces against {@link Rest @Rest}-annotated resources.
185 *
186 * <h2 class='figure'>Example:</h2>
187 * <p class='bjava'>
188 *    <jc>// Our remote resource to test.</jc>
189 *    <ja>@Remote</ja>
190 *    <jk>public interface</jk> MyRemoteInterface {
191 *
192 *       <ja>@RemoteGet</ja>(<js>"/echoQuery"</js>)
193 *       <jk>public int</jk> echoQuery(<ja>@Query</ja>(name=<js>"id"</js>) <jk>int</jk> <jv>id</jv>);
194 *    }
195 *
196 *    <jc>// Our mocked-up REST interface to test against.</jc>
197 *    <ja>@Rest</ja>
198 *    <jk>public class</jk> MyRest {
199 *
200 *       <ja>@RestGet</ja>(path=<js>"/echoQuery"</js>)
201 *       <jk>public int</jk> echoQuery(<ja>@Query</ja>(<js>"id"</js>) String <jv>id</jv>) {
202 *          <jk>return</jk> <jv>id</jv>;
203 *       }
204 *    }
205 *
206 *    <ja>@Test</ja>
207 *    <jk>public void</jk> testProxy() {
208 *       <jc>// A mock client cannot apply the SSRF guard of @Remote calls, so it needs the allowPrivateUrls opt-in.</jc>
209 *       MyRemoteInterface <jv>client</jv> = MockRestClient
210 *          .create(MyRest.<jk>class</jk>)
211 *          .json()
212 *          .allowPrivateUrls(<jk>true</jk>)
213 *          .build()
214 *          .getRemote(MyRemoteInterface.<jk>class</jk>);
215 *
216 *       <jsm>assertEquals</jsm>(123, <jv>client</jv>.echoQuery(123));
217 *    }
218 * </p>
219 *
220 * <h2 class='section'>Notes:</h2><ul>
221 *    <li class='note'>This class is thread safe and reusable.
222 * </ul>
223 *
224 * <h2 class='section'>See Also:</h2><ul>
225 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/JuneauRestMock">juneau-rest-mock</a>
226 * </ul>
227 */
228@SuppressWarnings({
229   "java:S3740", // Raw Class/Builder types used intentionally for fluent mock client construction where response type is unknown at build time
230   "resource", // Builders and requests returned to callers; lifecycle managed by the enclosing MockRestClient or test
231   "unchecked" // Type erasure requires cast for builder chain
232})
233public class MockRestClient extends RestClient implements HttpClientConnection {
234
235   /**
236    * Builder class.
237    */
238   public static class Builder extends RestClient.Builder<Builder> implements BeanStoreOverridable<Builder> {
239
240      Object restBean;
241      String contextPath;
242      String servletPath;
243      RestContext restContext;
244      Map<String,String> pathVars;
245      BeanStore overridingBeanStore;
246
247      /**
248       * No-arg constructor.
249       *
250       * <p>
251       * Provided so that this class can be easily subclassed.
252       */
253      protected Builder() {
254         connectionManager(new MockHttpClientConnectionManager());
255      }
256
257      @Override /* Overridden from Context.Builder<?> */
258      public MockRestClient build() {
259         return super.build(MockRestClient.class);
260      }
261
262      /**
263       * Identifies the context path for the REST resource.
264       *
265       * <p>
266       *    This value is used to deconstruct the request URL and set the appropriate URL getters on the {@link HttpServletRequest}
267       *    object correctly.
268       *
269       * <p>
270       *    Should either be a value such as <js>"/foo"</js> or an empty string.
271       *
272       * <p>
273       *    The following fixes are applied to non-conforming strings.
274       * <ul>
275       *    <li><jk>nulls</jk> and <js>"/"</js> are converted to empty strings.
276       *    <li>Trailing slashes are trimmed.
277       *    <li>Leading slash is added if needed.
278       * </ul>
279       *
280       * @param value The context path.
281       * @return This object.
282       */
283      public Builder contextPath(String value) {
284         contextPath = toValidContextPath(value);
285         return this;
286      }
287
288      @Override /* Overridden from Context.Builder<?> */
289      public Builder copy() {
290         throw new NoSuchMethodError("Not implemented.");
291      }
292
293      @Override /* Overridden from Context.Builder<?> */
294      public Builder debug() {
295         super.debug();
296         return this;
297      }
298
299      @Override /* Overridden from Builder */
300      public Builder parsers(Class<? extends Parser>...value) {
301         super.parsers(value);
302         return this;
303      }
304
305      /**
306       * Add resolved path variables to this client.
307       *
308       * <p>
309       * Allows you to add resolved parent path variables when performing tests on child resource classes.
310       *
311       * <h4 class='section'>Example:</h4>
312       * <p class='bjava'>
313       *    <jc>// A parent class with a path variable.</jc>
314       *    <ja>@Rest</ja>(
315       *       path=<js>"/parent/{foo}"</js>,
316       *       children={
317       *          Child.<jk>class</jk>
318       *       }
319       *    )
320       *    <jk>public class</jk> Parent { ... }
321       *
322       *    <jc>// A child class that uses the parent path variable.</jc>
323       *    <ja>@Rest</ja>
324       *    <jk>public class</jk> Child {
325       *
326       *       <jk>@RestGet</jk>
327       *       <jk>public</jk> String get(<ja>@Path</ja>(<js>"foo"</js>) String <jv>foo</jv>) {
328       *          <jk>return</jk> <jv>foo</jv>;
329       *       }
330       *    }
331       * </p>
332       * <p class='bjava'>
333       *    <jc>// Test the method that uses the parent path variable.</jc>
334       *    MockRestClient
335       *       .<jsm>create</jsm>(Child.<jk>class</jk>)
336       *       .json5()
337       *       .pathVars(<js>"foo"</js>,<js>"bar"</js>)
338       *       .build()
339       *       .get(<js>"/"</js>)
340       *       .run()
341       *       .assertStatus().asCode().is(200)
342       *       .assertContent().is(<js>"bar"</js>);
343       * </p>
344       *
345       * @param value The path variables.
346       * @return This object.
347       * @see MockServletRequest#pathVars(Map)
348       */
349      public Builder pathVars(Map<String,String> value) {
350         pathVars = value;
351         return this;
352      }
353
354      /**
355       * Add resolved path variables to this client.
356       *
357       * <p>
358       * Identical to {@link #pathVars(Map)} but allows you to specify as a list of key/value pairs.
359       *
360       * @param pairs The key/value pairs.  Must be an even number of parameters.
361       * @return This object.
362       */
363      public Builder pathVars(String...pairs) {
364         return pathVars(mb(String.class, String.class).addPairs((Object[])pairs).build());
365      }
366
367      /**
368       * Specifies the {@link Rest}-annotated bean class or instance to test against.
369       *
370       * @param value The {@link Rest}-annotated bean class or instance.
371       * @return This object.
372       */
373      public Builder restBean(Object value) {
374         restBean = value;
375         return this;
376      }
377
378      /**
379       * Specifies the {@link RestContext} created for the REST bean.
380       *
381       * @param value The {@link RestContext} created for the REST bean.
382       * @return This object.
383       */
384      public Builder restContext(RestContext value) {
385         restContext = value;
386         return this;
387      }
388
389      /**
390       * Installs a {@link BeanStore BeanStore} as the
391       * {@code overridingParent} of the {@link RestContext}'s bean store, so test-time overrides
392       * (e.g. {@code TestBeanStore}) resolve at tier 1 of the lookup chain &mdash; above the
393       * resource's local {@code @Bean} factory entries.
394       *
395       * <p>
396       * Setting this disables the per-resource {@link RestContext} cache for the duration of this
397       * build, so the overlay is not silently shared with a previously-cached instance.
398       *
399       * @param value The override layer. Can be <jk>null</jk> to clear a previously-set value.
400       * @return This object.
401       *
402       * @since 10.0.0
403       */
404      @Override
405      public Builder overridingBeanStore(BeanStore value) {
406         overridingBeanStore = value;
407         return this;
408      }
409
410      @Override /* Overridden from Builder */
411      public Builder serializers(Class<? extends org.apache.juneau.marshall.serializer.Serializer>...value) {
412         super.serializers(value);
413         return this;
414      }
415
416      /**
417       * Identifies the servlet path for the REST resource.
418       *
419       * <p>
420       *    This value is used to deconstruct the request URL and set the appropriate URL getters on the {@link HttpServletRequest}
421       *    object correctly.
422       *
423       * <p>
424       *    Should either be a value such as <js>"/foo"</js> or an empty string.
425       *
426       * <p>
427       *    The following fixes are applied to non-conforming strings.
428       * <ul>
429       *    <li><jk>nulls</jk> and <js>"/"</js> are converted to empty strings.
430       *    <li>Trailing slashes are trimmed.
431       *    <li>Leading slash is added if needed.
432       * </ul>
433       *
434       * @param value The context path.
435       * @return This object.
436       */
437      public Builder servletPath(String value) {
438         servletPath = toValidContextPath(value);
439         return this;
440      }
441
442      /**
443       * Suppress logging on this client.
444       *
445       * @return This object.
446       */
447      public Builder suppressLogging() {
448         return logRequests(DetailLevel.NONE, null, null);
449      }
450
451
452   }
453
454   private static Map<Class<?>,RestContext> restContexts = new ConcurrentHashMap<>();
455
456   /**
457    * Creates a new {@link RestClient} with no registered serializer or parser.
458    *
459    * <p>
460    * Equivalent to calling:
461    * <p class='bjava'>
462    *    MockRestClient.<jsm>create</jsm>(<jv>impl</jv>).build();
463    * </p>
464    *
465    * @param impl
466    *    The REST bean or bean class annotated with {@link Rest @Rest}.
467    *    <br>If a class, it must have a no-arg constructor.
468    * @return A new client.
469    */
470   public static MockRestClient build(Object impl) {
471      return create(impl).build();
472   }
473
474   /**
475    * Creates a new {@link RestClient} with JSON marshalling support.
476    *
477    * <p>
478    * Equivalent to calling:
479    * <p class='bjava'>
480    *    MockRestClient.<jsm>create</jsm>(<jv>impl</jv>).json().build();
481    * </p>
482    *
483    * @param impl
484    *    The REST bean or bean class annotated with {@link Rest @Rest}.
485    *    <br>If a class, it must have a no-arg constructor.
486    * @return A new client.
487    */
488   public static MockRestClient buildJson(Object impl) {
489      return create(impl).json().build();
490   }
491
492   /**
493    * Creates a new {@link RestClient} with Simplified-JSON marshalling support.
494    *
495    * <p>
496    * Equivalent to calling:
497    * <p class='bjava'>
498    *    MockRestClient.<jsm>create</jsm>(<jv>impl</jv>).json().build();
499    * </p>
500    *
501    * @param impl
502    *    The REST bean or bean class annotated with {@link Rest @Rest}.
503    *    <br>If a class, it must have a no-arg constructor.
504    * @return A new client.
505    */
506   public static MockRestClient buildJson5(Object impl) {
507      return create(impl).json5().build();
508   }
509
510   /**
511    * Creates a new {@link RestClient} with Simplified-JSON marshalling support.
512    *
513    * <p>
514    * Same as {@link #buildJson5(Object)} but HTTP 400+ codes don't trigger {@link RestCallException RestCallExceptions}.
515    *
516    * <p>
517    * Equivalent to calling:
518    * <p class='bjava'>
519    *    MockRestClient.<jsm>create</jsm>(<jv>impl</jv>).json().ignoreErrors().build();
520    * </p>
521    *
522    * @param impl
523    *    The REST bean or bean class annotated with {@link Rest @Rest}.
524    *    <br>If a class, it must have a no-arg constructor.
525    * @return A new client.
526    */
527   public static MockRestClient buildJson5Lax(Object impl) {
528      return create(impl).json5().ignoreErrors().noTrace().build();
529   }
530
531   /**
532    * Creates a new {@link RestClient} with JSON marshalling support.
533    *
534    * <p>
535    * Same as {@link #buildJson(Object)} but HTTP 400+ codes don't trigger {@link RestCallException RestCallExceptions}.
536    *
537    * <p>
538    * Equivalent to calling:
539    * <p class='bjava'>
540    *    MockRestClient.<jsm>create</jsm>(<jv>impl</jv>).json().ignoreErrors().build();
541    * </p>
542    *
543    * @param impl
544    *    The REST bean or bean class annotated with {@link Rest @Rest}.
545    *    <br>If a class, it must have a no-arg constructor.
546    * @return A new client.
547    */
548   public static MockRestClient buildJsonLax(Object impl) {
549      return create(impl).json().ignoreErrors().noTrace().build();
550   }
551
552   /**
553    * Creates a new {@link RestClient} with no registered serializer or parser.
554    *
555    * <p>
556    * Same as {@link #build(Object)} but HTTP 400+ codes don't trigger {@link RestCallException RestCallExceptions}.
557    *
558    * <p>
559    * Equivalent to calling:
560    * <p class='bjava'>
561    *    MockRestClient.<jsm>create</jsm>(<jv>impl</jv>).ignoreErrors().noTrace().build();
562    * </p>
563    *
564    * @param impl
565    *    The REST bean or bean class annotated with {@link Rest @Rest}.
566    *    <br>If a class, it must have a no-arg constructor.
567    * @return A new client.
568    */
569   public static MockRestClient buildLax(Object impl) {
570      return create(impl).ignoreErrors().noTrace().build();
571   }
572
573   /**
574    * Creates a new {@link org.apache.juneau.rest.client.classic.RestClient.Builder RestClient.Builder}configured with the specified REST implementation bean or bean class.
575    *
576    * @param impl
577    *    The REST bean or bean class annotated with {@link Rest @Rest}.
578    *    <br>If a class, it must have a no-arg constructor.
579    * @return A new builder.
580    */
581   public static Builder create(Object impl) {
582      return new Builder().restBean(impl);
583   }
584
585   /**
586    * Creates a new {@link org.apache.juneau.rest.client.classic.RestClient.Builder RestClient.Builder}configured with the specified REST implementation bean or bean class.
587    *
588    * <p>
589    * Same as {@link #create(Object)} but HTTP 400+ codes don't trigger {@link RestCallException RestCallExceptions}.
590    *
591    * @param impl
592    *    The REST bean or bean class annotated with {@link Rest @Rest}.
593    *    <br>If a class, it must have a no-arg constructor.
594    * @return A new builder.
595    */
596   public static Builder createLax(Object impl) {
597      return new Builder().restBean(impl).ignoreErrors().noTrace();
598   }
599
600   private static Builder preInit(Builder builder) {
601      try {
602         var restBean = builder.restBean;
603         var contextPath = builder.contextPath;
604         var servletPath = builder.servletPath;
605         var overlay = builder.overridingBeanStore;
606
607         var isClass = restBean instanceof Class;
608         // Only class-based contexts are cached; a caller-supplied instance always gets its own context.
609         var cacheable = isClass && overlay == null;
610         var restBeanCtx = cacheable ? restContexts.get(restBean) : null;
611         if (restBeanCtx == null) {
612            var o = isClass ? ((Class<?>)restBean).getDeclaredConstructor().newInstance() : restBean;
613            restBeanCtx = new RestContext(new RestContext.Args(o.getClass(), null, null, () -> o, "", bs -> {
614               bs.addBeanType(RestDebugFormatter.class, BasicTestRestDebugFormatter.class);
615            }, overlay, null, RestContext.ContextKind.ROOT)).postInit().postInitChildFirst();
616            if (cacheable)
617               restContexts.put((Class<?>)restBean, restBeanCtx);
618         }
619         builder.restContext(restBeanCtx);
620
621         if (servletPath == null)
622            servletPath = toValidContextPath(restBeanCtx.getFullPath());
623
624         final var suffix = emptyIfNull(contextPath) + emptyIfNull(servletPath);
625         final var existingSupplier = builder.getRootUrlSupplier();
626         if (existingSupplier != null) {
627            // Compose a new supplier that appends the fixed path suffix to whatever the original supplier returns.
628            builder.rootUrl(() -> existingSupplier.get() + suffix);
629         } else {
630            builder.rootUrl("http://localhost" + suffix);
631         }
632
633         builder.servletPath = servletPath;
634         return builder;
635      } catch (Exception e) {
636         throw new ConfigException(e, "Could not initialize MockRestClient");
637      }
638   }
639
640   private final RestContext restContext;
641   private final Object restObject;
642   private final String contextPath;
643   private final String servletPath;
644
645   private final Map<String,String> pathVars;
646   private final ThreadLocal<HttpRequest> rreq = new ThreadLocal<>();
647   private final ThreadLocal<MockRestResponse> rres = new ThreadLocal<>();
648   private final ThreadLocal<MockServletRequest> sreq = new ThreadLocal<>();
649
650   private final ThreadLocal<MockServletResponse> sres = new ThreadLocal<>();
651
652   /**
653    * Constructor.
654    *
655    * @param builder
656    *    The builder for this object.
657    */
658   public MockRestClient(Builder builder) {
659      super(preInit(builder));
660      restContext = builder.restContext;
661      contextPath = nn(builder.contextPath) ? builder.contextPath : "";
662      servletPath = nn(builder.servletPath) ? builder.servletPath : "";
663      pathVars = nn(builder.pathVars) ? builder.pathVars : emptyMap();
664      restObject = restContext.getResource();
665
666      HttpClientConnectionManager ccm = getHttpClientConnectionManager();
667      if (ccm instanceof MockHttpClientConnectionManager ccm2)
668         ccm2.init(this);
669   }
670
671   @Override /* Overridden from RestClient */
672   public MockRestRequest callback(String callString) throws RestCallException {
673      return (MockRestRequest)super.callback(callString);
674   }
675
676   @Override /* Overridden from HttpClientConnection */
677   public void close() throws IOException {
678      // Don't call super.close() because it will close the client.
679      rreq.remove();
680      rres.remove();
681      sreq.remove();
682      sres.remove();
683   }
684
685   @Override /* Overridden from RestClient */
686   public MockRestRequest delete(Object url) throws RestCallException {
687      return (MockRestRequest)super.delete(url);
688   }
689
690   @Override /* Overridden from HttpClientConnection */
691   public void flush() throws IOException {
692      // No-op: Mock implementation - full functionality not required
693   }
694
695   @Override /* Overridden from RestClient */
696   public MockRestRequest formPost(Object url) throws RestCallException {
697      return (MockRestRequest)super.formPost(url);
698   }
699
700   @Override /* Overridden from RestClient */
701   public MockRestRequest formPost(Object url, Object body) throws RestCallException {
702      return (MockRestRequest)super.formPost(url, body);
703   }
704
705   @Override /* Overridden from RestClient */
706   public MockRestRequest formPostPairs(Object url, String...parameters) throws RestCallException {
707      return (MockRestRequest)super.formPostPairs(url, parameters);
708   }
709
710   @Override /* Overridden from RestClient */
711   public MockRestRequest get() throws RestCallException {
712      return (MockRestRequest)super.get();
713   }
714
715   @Override /* Overridden from RestClient */
716   public MockRestRequest get(Object url) throws RestCallException {
717      return (MockRestRequest)super.get(url);
718   }
719
720   /**
721    * Returns the current client-side REST request.
722    *
723    * <p>
724    * Note that this uses a {@link ThreadLocal} object for storage and so will not work on requests executed in
725    * separate threads such as when using {@link Future Futures}.
726    *
727    * @return The current client-side REST request, or <jk>null</jk> if not set.
728    */
729   public HttpRequest getCurrentClientRequest() { return rreq.get(); }
730
731   /**
732    * Returns the current client-side REST response.
733    *
734    * <p>
735    * Note that this uses a {@link ThreadLocal} object for storage and so will not work on requests executed in
736    * separate threads such as when using {@link Future Futures}.
737    *
738    * @return The current client-side REST response, or <jk>null</jk> if not set.
739    */
740   public MockRestResponse getCurrentClientResponse() { return rres.get(); }
741
742   /**
743    * Returns the current server-side REST request.
744    *
745    * <p>
746    * Note that this uses a {@link ThreadLocal} object for storage and so will not work on requests executed in
747    * separate threads such as when using {@link Future Futures}.
748    *
749    * @return The current server-side REST request, or <jk>null</jk> if not set.
750    */
751   public MockServletRequest getCurrentServerRequest() { return sreq.get(); }
752
753   /**
754    * Returns the current server-side REST response.
755    *
756    * <p>
757    * Note that this uses a {@link ThreadLocal} object for storage and so will not work on requests executed in
758    * separate threads such as when using {@link Future Futures}.
759    *
760    * @return The current server-side REST response, or <jk>null</jk> if not set.
761    */
762   public MockServletResponse getCurrentServerResponse() { return sres.get(); }
763
764   @Override /* Overridden from HttpClientConnection */
765   public HttpConnectionMetrics getMetrics() { return null; }
766
767   @Override /* Overridden from HttpClientConnection */
768   public int getSocketTimeout() { return Integer.MAX_VALUE; }
769
770   @Override /* Overridden from RestClient */
771   public MockRestRequest head(Object url) throws RestCallException {
772      return (MockRestRequest)super.head(url);
773   }
774
775   @Override /* Overridden from HttpClientConnection */
776   public boolean isOpen() { return true; }
777
778   @Override /* Overridden from HttpClientConnection */
779   public boolean isResponseAvailable(int timeout) throws IOException {
780      return true;
781   }
782
783   @Override /* Overridden from HttpClientConnection */
784   public boolean isStale() { return false; }
785
786   @Override /* Overridden from RestClient */
787   public MockRestRequest options(Object url) throws RestCallException {
788      return (MockRestRequest)super.options(url);
789   }
790
791   @Override /* Overridden from RestClient */
792   public MockRestRequest patch(Object url) throws RestCallException {
793      return (MockRestRequest)super.patch(url);
794   }
795
796   @Override /* Overridden from RestClient */
797   public MockRestRequest patch(Object url, Object body) throws RestCallException {
798      return (MockRestRequest)super.patch(url, body);
799   }
800
801   @Override /* Overridden from RestClient */
802   public MockRestRequest patch(Object url, String body, ContentType contentType) throws RestCallException {
803      return (MockRestRequest)super.patch(url, body, contentType);
804   }
805
806   @Override /* Overridden from RestClient */
807   public MockRestRequest post(Object url) throws RestCallException {
808      return (MockRestRequest)super.post(url);
809   }
810
811   @Override /* Overridden from RestClient */
812   public MockRestRequest post(Object url, Object body) throws RestCallException {
813      return (MockRestRequest)super.post(url, body);
814   }
815
816   @Override /* Overridden from RestClient */
817   public MockRestRequest post(Object url, String body, ContentType contentType) throws RestCallException {
818      return (MockRestRequest)super.post(url, body, contentType);
819   }
820
821   @Override /* Overridden from RestClient */
822   public MockRestRequest put(Object url) throws RestCallException {
823      return (MockRestRequest)super.put(url);
824   }
825
826   @Override /* Overridden from RestClient */
827   public MockRestRequest put(Object url, Object body) throws RestCallException {
828      return (MockRestRequest)super.put(url, body);
829   }
830
831   @Override /* Overridden from RestClient */
832   public MockRestRequest put(Object url, String body, ContentType contentType) throws RestCallException {
833      return (MockRestRequest)super.put(url, body, contentType);
834   }
835
836   @Override /* Overridden from HttpClientConnection */
837   public void receiveResponseEntity(HttpResponse response) throws HttpException, IOException {
838      InputStream is = new ByteArrayInputStream(sres.get().getContent());
839      var contentEncoding = response.getLastHeader("Content-Encoding");
840      if (nn(contentEncoding) && eqic(contentEncoding.getValue(), "gzip"))
841         is = new GZIPInputStream(is);
842      response.setEntity(new InputStreamEntity(is));
843   }
844
845   @Override /* Overridden from HttpClientConnection */
846   public HttpResponse receiveResponseHeader() throws HttpException, IOException {
847      try {
848         var res = MockServletResponse.create();
849         var logLevel = sreq.get().getLogLevel();
850         if (logLevel != null) {
851            var target = Logger.getLogger(restObject.getClass().getName());
852            var prevLevel = target.getLevel();
853            target.setLevel(logLevel);
854            try {
855               restContext.execute(restObject, sreq.get(), res);
856            } finally {
857               target.setLevel(prevLevel);
858            }
859         } else {
860            restContext.execute(restObject, sreq.get(), res);
861         }
862
863         // A bug in HttpClient causes an infinite loop if the response is less than 200.
864         // As a workaround, just add 1000 to the status code (which is better than an infinite loop).
865         if (res.getStatus() < 200)
866            res.setStatus(1000 + res.getStatus());
867
868         sres.set(res);
869
870         var response = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, res.getStatus(), res.getMessage()));
871         res.getHeaders().forEach((k, v) -> {
872            for (var hv : v)
873               response.addHeader(k, hv);
874         });
875
876         return response;
877      } catch (Exception e) {
878         throw new HttpException(emptyIfNull(e.getMessage()), e);
879      }
880   }
881
882   @Override /* Overridden from RestClient */
883   public MockRestRequest request(RestOperation op) throws RestCallException {
884      return (MockRestRequest)super.request(op);
885   }
886
887   @Override /* Overridden from RestClient */
888   public MockRestRequest request(String method, Object url) throws RestCallException {
889      return (MockRestRequest)super.request(method, url);
890   }
891
892   @Override /* Overridden from RestClient */
893   public MockRestRequest request(String method, Object url, boolean hasBody) throws RestCallException {
894      return (MockRestRequest)super.request(method, url, hasBody);
895   }
896
897   @Override /* Overridden from RestClient */
898   public MockRestRequest request(String method, Object url, Object body) throws RestCallException {
899      return (MockRestRequest)super.request(method, url, body);
900   }
901
902   @Override /* Overridden from HttpClientConnection */
903   public void sendRequestEntity(HttpEntityEnclosingRequest request) throws HttpException, IOException {
904      byte[] body = {};
905      var entity = request.getEntity();
906      if (nn(entity)) {
907         var length = entity.getContentLength();
908         if (length < 0)
909            length = 1024;
910         var baos = new ByteArrayOutputStream((int)Math.min(length, 1024));
911         entity.writeTo(baos);
912         baos.flush();
913         body = baos.toByteArray();
914      }
915      sreq.get().content(body);
916   }
917
918   @Override /* Overridden from HttpClientConnection */
919   public void sendRequestHeader(HttpRequest request) throws HttpException, IOException {
920      try {
921         var rl = request.getRequestLine();
922         var path = rl.getUri();
923         var target = findTarget(request);
924
925         var req = findRestRequest(request);
926         rreq.set(req);
927         rres.remove();
928         sreq.remove();
929         sres.remove();
930
931         path = target + path;
932
933         var pr = new MockPathResolver(target, contextPath, servletPath, path, null);
934         if (nn(pr.getError()))
935            throw new IllegalStateException(pr.getError());
936
937         var r = MockServletRequest.create(request.getRequestLine().getMethod(), pr.getURI()).contextPath(pr.getContextPath()).servletPath(pr.getServletPath()).pathVars(pathVars).logLevel(isDebug() ? Level.FINEST : null);
938
939         for (var h : request.getAllHeaders())
940            r.header(h.getName(), h.getValue());
941
942         sreq.set(r);
943         sreq.get().applyOverrides(req);
944      } catch (Exception e) {
945         throw new HttpException(e.getMessage(), e);
946      }
947   }
948
949   @Override /* Overridden from HttpClientConnection */
950   public void setSocketTimeout(int timeout) {
951      // No-op: Mock implementation - full functionality not required
952   }
953
954   @Override /* Overridden from HttpClientConnection */
955   public void shutdown() throws IOException {
956      // No-op: Mock implementation - full functionality not required
957   }
958
959   /**
960    * Attempts to unwrap the request to find the underlying RestRequest object.
961    * Returns the same object if one of the low-level client methods are used (e.g. execute(HttpUriRequest)).
962    */
963   private HttpRequest findRestRequest(HttpRequest req) {
964      if (req instanceof RestRequestCreated req2)
965         return req2.getRestRequest();
966      if (req instanceof HttpRequestWrapper req2)
967         return findRestRequest(req2.getOriginal());
968      return req;
969   }
970
971   private static String findTarget(HttpRequest req) {
972      if (req instanceof HttpRequestWrapper req2) {
973         var httpHost = req2.getTarget();
974         if (nn(httpHost))
975            return httpHost.toURI();
976      }
977      return "http://localhost";
978   }
979
980   @Override /* Overridden from RestClient */
981   protected MockRestRequest createRequest(URI uri, String method, boolean hasBody) throws RestCallException {
982      return new MockRestRequest(this, uri, method, hasBody);
983   }
984
985   @Override /* Overridden from RestClient */
986   protected MockRestResponse createResponse(RestRequest req, HttpResponse httpResponse, Parser parser) throws RestCallException {
987      return new MockRestResponse(this, req, httpResponse, parser);
988   }
989
990   MockRestClient currentResponse(MockRestResponse value) {
991      rres.set(value);
992      return this;
993   }
994}