CookieParameterResolver implements ParameterResolver<CookieParam> { @Override public Object resolve(org.everrest.core.Parameter parameter, ApplicationContext context) throws Exception { String param = cookieParam.value(); if (Cookie.class.isAssignableFrom(parameter.getParameterClass())) { Cookie cookie = context.getHttpHeaders().getCookies().get(param); if (cookie == null && parameter.getDefaultValue() != null) { cookie = Cookie.valueOf(parameter.getDefaultValue()); } return cookie; } else { TypeProducer typeProducer = typeProducerFactory.createTypeProducer(parameter.getParameterClass(), parameter.getGenericType()); MultivaluedMap<String, String> cookieValues = new MultivaluedMapImpl(); for (Map.Entry<String, Cookie> entry : context.getHttpHeaders().getCookies().entrySet()) { cookieValues.putSingle(entry.getKey(), entry.getValue().getValue()); } return typeProducer.createValue(param, cookieValues, parameter.getDefaultValue()); } } CookieParameterResolver(CookieParam cookieParam, TypeProducerFactory typeProducerFactory); @Override Object resolve(org.everrest.core.Parameter parameter, ApplicationContext context);  }
@Test public void retrievesCookieFromRequest() throws Exception { when(parameter.getParameterClass()).thenReturn((Class)Cookie.class); Object resolvedCookie = cookieParameterResolver.resolve(parameter, applicationContext); assertSame(cookie1, resolvedCookie); }
@Test public void createsCookieFromDefaultValueWhenCookieNotFoundInRequest() throws Exception { when(cookieParam.value()).thenReturn("no cookie"); when(parameter.getParameterClass()).thenReturn((Class)Cookie.class); when(parameter.getDefaultValue()).thenReturn("default_cookie=xxx"); Cookie resolvedCookie = (Cookie)cookieParameterResolver.resolve(parameter, applicationContext); assertEquals("default_cookie", resolvedCookie.getName()); assertEquals("xxx", resolvedCookie.getValue()); }
@Test public void returnsNullWhenCookieNotFoundInRequestAndDefaultValueIsNotSet() throws Exception { when(cookieParam.value()).thenReturn("no cookie"); when(parameter.getParameterClass()).thenReturn((Class)Cookie.class); Object resolvedCookie = cookieParameterResolver.resolve(parameter, applicationContext); assertNull(resolvedCookie); }
@Test public void convertsCookieValueToTypeSpecifiedInParameter() throws Exception { when(cookieParam.value()).thenReturn("cookie1"); when(parameter.getParameterClass()).thenReturn((Class)String.class); when(typeProducer.createValue(eq("cookie1"), any(MultivaluedMap.class), any())).thenAnswer( invocation -> ((MultivaluedMap<String, String>)invocation.getArguments()[1]).getFirst("cookie1")); Object resolvedValue = cookieParameterResolver.resolve(parameter, applicationContext); assertEquals(cookie1.getValue(), resolvedValue); }