1 2 Previous Next 20 Replies Latest reply on Jul 17, 2015 8:43 AM by Chris Rankin

    What is the correct usage of WELD's built-in HttpRequestContext bean?

    Chris Rankin Novice

      Hi,

       

      I have implemented a CDI bean with a @Produces method that extracts query parameter "traceId" from any/every HTTP request. This @Produces method is also likely to be called outside of request scope (by beans running in user-created threads), and so must return null in this case instead of throwing an exception. I am using the built-in HttpRequestContext bean to determine whether or not request scope is active:

       

      @ApplicationScoped
      public class TraceProducer {
      
          private final HttpRequestContext context;
      
          @Inject
          TraceProducer(HttpRequestContext context) {
              this.context = context;
          }
      
          @Produces
          @Trace
          String getTrace(HttpServletRequest request) {
              String traceId = null;
      
              if (context.isActive()) {
                  traceId = request.getParameter("traceId");
                  if (traceId == null) {
                      traceId = generateTraceId();
                  }
              }
      
              return traceId;
          }
      
          private static String generateTraceId() {
              return ...; // generates a random unique String
          }
      
      }
      
      
      
      

       

      Is this a legal / intended use of HttpRequestContext, please? My original implementation of this bean was @Dependent scoped instead of @ApplicationScoped, but then I noticed that the heap has begun accumulating CreationalContext objects associated with HttpRequestContextImpl with each HTTP request. I have also noticed that HttpRequestContext is specific to WELD rather than being an interface defined by CDI. Both of these things make me suspect that I am meddling with low-level WELDy things that aren't supposed to be exposed inside applications. However, using HttpRequestContext does seem like a neater solution to my problem that trying to catch a "request scope is not active" exception thrown by the built-in HttpServletRequest bean.

       

      The above code does appear to work as intended - at the moment. But I'd hate to think that I was ultimately relying on some undocumented behaviour that could disappear one day. Does anyone have any thoughts on this approach, please?

       

      Thanks,

      Chris

        1 2 Previous Next