RequestScopedMdc { public static Map<String, String> getAll(RequestContext ctx) { requireNonNull(ctx, "ctx"); final Object2ObjectMap<String, String> map = getMap(ctx); final RequestContext rootCtx = ctx.root(); if (rootCtx == null || rootCtx == ctx) { return map; } final Object2ObjectMap<String, String> rootMap = getMap(rootCtx); if (rootMap.isEmpty()) { return map; } if (map.isEmpty()) { return rootMap; } final Object2ObjectMap<String, String> merged = new Object2ObjectOpenHashMap<>(rootMap.size() + map.size()); merged.putAll(rootMap); merged.putAll(map); return merged; } private  RequestScopedMdc(); @Nullable static String get(RequestContext ctx, String key); static Map<String, String> getAll(RequestContext ctx); static void put(RequestContext ctx, String key, @Nullable String value); static void putAll(RequestContext ctx, Map<String, String> map); static void copy(RequestContext ctx, String key); static void copyAll(RequestContext ctx); static void remove(RequestContext ctx, String key); static void clear(RequestContext ctx);  }
@Test void getAll() { final ServiceRequestContext ctx = newContext(); MDC.put("foo", "1"); MDC.put("bar", "2"); RequestScopedMdc.put(ctx, "bar", "3"); RequestScopedMdc.put(ctx, "baz", "4"); assertThat(MDC.getCopyOfContextMap()).containsOnly( Maps.immutableEntry("foo", "1"), Maps.immutableEntry("bar", "2")); assertThat(RequestScopedMdc.getAll(ctx)).containsOnly( Maps.immutableEntry("bar", "3"), Maps.immutableEntry("baz", "4")); try (SafeCloseable ignored = ctx.push()) { assertThat(MDC.getCopyOfContextMap()).containsOnly( Maps.immutableEntry("foo", "1"), Maps.immutableEntry("bar", "3"), Maps.immutableEntry("baz", "4")); MDC.clear(); assertThat(MDC.getCopyOfContextMap()).containsOnly( Maps.immutableEntry("bar", "3"), Maps.immutableEntry("baz", "4")); RequestScopedMdc.clear(ctx); assertThat(MDC.getCopyOfContextMap()).isIn(Collections.emptyMap(), null); MDC.put("qux", "5"); assertThat(MDC.getCopyOfContextMap()).containsOnly( Maps.immutableEntry("qux", "5")); } }