Search in sources :

Example 1 with Cookie

use of javax.ws.rs.core.Cookie in project camel by apache.

the class BonitaAuthFilterConnectionTest method setup.

@Before
public void setup() {
    Mockito.when(requestContext.getCookies()).thenReturn(new HashMap<String, Cookie>());
    Mockito.when(requestContext.getHeaders()).thenReturn(new MultivaluedHashMap());
}
Also used : Cookie(javax.ws.rs.core.Cookie) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Before(org.junit.Before)

Example 2 with Cookie

use of javax.ws.rs.core.Cookie in project jersey by jersey.

the class CookieImplTest method testCookieValueOf.

@Test
public void testCookieValueOf() {
    Cookie cookie = Cookie.valueOf("$Version=2;fred=flintstone");
    assertEquals("fred", cookie.getName());
    assertEquals("flintstone", cookie.getValue());
    assertEquals(2, cookie.getVersion());
    cookie = Cookie.valueOf("$Version=1;fred=flintstone;$Path=/path");
    assertEquals("fred", cookie.getName());
    assertEquals("flintstone", cookie.getValue());
    assertEquals(1, cookie.getVersion());
    assertEquals("/path", cookie.getPath());
    cookie = Cookie.valueOf("$Version=1;fred=flintstone;$Domain=.sun.com;$Path=/path");
    assertEquals("fred", cookie.getName());
    assertEquals("flintstone", cookie.getValue());
    assertEquals(1, cookie.getVersion());
    assertEquals(".sun.com", cookie.getDomain());
    assertEquals("/path", cookie.getPath());
}
Also used : NewCookie(javax.ws.rs.core.NewCookie) Cookie(javax.ws.rs.core.Cookie) Test(org.junit.Test)

Example 3 with Cookie

use of javax.ws.rs.core.Cookie in project jersey by jersey.

the class ResponseTest method cloneTest.

/*
     * Create an instance of Response using
     * Response.ResponseBuilder.clone()
     * verify that correct status code is returned
     */
@Test
public void cloneTest() throws CloneNotSupportedException {
    StringBuilder sb = new StringBuilder();
    int status = 200;
    List<String> type = Arrays.asList("text/plain", "text/html");
    List<String> encoding = Arrays.asList("gzip", "compress");
    List<String> lang = Arrays.asList("en-US", "en-GB", "zh-CN");
    String name = "name_1";
    String value = "value_1";
    Cookie ck1 = new Cookie(name, value);
    NewCookie nck1 = new NewCookie(ck1);
    List<String> cookies = Arrays.asList(nck1.toString().toLowerCase());
    Response.ResponseBuilder respb1 = Response.status(status).header("Content-type", "text/plain").header("Content-type", "text/html").header("Content-Language", "en-US").header("Content-Language", "en-GB").header("Content-Language", "zh-CN").header("Cache-Control", "no-transform").header("Set-Cookie", "name_1=value_1;version=1");
    Response.ResponseBuilder respb2 = respb1.clone();
    Response resp2 = respb2.build();
    String tmp = verifyResponse(resp2, null, status, encoding, lang, type, null, null, cookies);
    if (tmp.endsWith("false")) {
        System.out.println("### " + sb.toString());
        fail();
    }
    sb.append(tmp).append(newline);
    String content = "TestOnly";
    Response resp1 = respb1.entity(content).cookie((NewCookie) null).build();
    tmp = verifyResponse(resp1, content, status, encoding, lang, type, null, null, null);
    if (tmp.endsWith("false")) {
        System.out.println("### " + sb.toString());
        fail();
    }
    MultivaluedMap<java.lang.String, java.lang.Object> mvp = resp1.getMetadata();
    if (mvp.containsKey("Set-Cookie")) {
        sb.append("Response contains unexpected Set-Cookie: ").append(mvp.getFirst("Set-Cookie").toString()).append(newline);
        System.out.println("### " + sb.toString());
        fail();
    }
    sb.append(tmp).append(newline);
}
Also used : NewCookie(javax.ws.rs.core.NewCookie) Cookie(javax.ws.rs.core.Cookie) Response(javax.ws.rs.core.Response) NewCookie(javax.ws.rs.core.NewCookie) Test(org.junit.Test)

Example 4 with Cookie

use of javax.ws.rs.core.Cookie in project jersey by jersey.

the class WebResourceFactory method invoke.

@Override
@SuppressWarnings("unchecked")
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
    if (args == null && method.getName().equals("toString")) {
        return toString();
    }
    if (args == null && method.getName().equals("hashCode")) {
        //unique instance in the JVM, and no need to override
        return hashCode();
    }
    if (args != null && args.length == 1 && method.getName().equals("equals")) {
        //unique instance in the JVM, and no need to override
        return equals(args[0]);
    }
    // get the interface describing the resource
    final Class<?> proxyIfc = proxy.getClass().getInterfaces()[0];
    // response type
    final Class<?> responseType = method.getReturnType();
    // determine method name
    String httpMethod = getHttpMethodName(method);
    if (httpMethod == null) {
        for (final Annotation ann : method.getAnnotations()) {
            httpMethod = getHttpMethodName(ann.annotationType());
            if (httpMethod != null) {
                break;
            }
        }
    }
    // create a new UriBuilder appending the @Path attached to the method
    WebTarget newTarget = addPathFromAnnotation(method, target);
    if (httpMethod == null) {
        if (newTarget == target) {
            // no path annotation on the method -> fail
            throw new UnsupportedOperationException("Not a resource method.");
        } else if (!responseType.isInterface()) {
            // not interface - can't help here
            throw new UnsupportedOperationException("Return type not an interface");
        }
    }
    // process method params (build maps of (Path|Form|Cookie|Matrix|Header..)Params
    // and extract entity type
    final MultivaluedHashMap<String, Object> headers = new MultivaluedHashMap<String, Object>(this.headers);
    final LinkedList<Cookie> cookies = new LinkedList<>(this.cookies);
    final Form form = new Form();
    form.asMap().putAll(this.form.asMap());
    final Annotation[][] paramAnns = method.getParameterAnnotations();
    Object entity = null;
    Type entityType = null;
    for (int i = 0; i < paramAnns.length; i++) {
        final Map<Class, Annotation> anns = new HashMap<>();
        for (final Annotation ann : paramAnns[i]) {
            anns.put(ann.annotationType(), ann);
        }
        Annotation ann;
        Object value = args[i];
        if (!hasAnyParamAnnotation(anns)) {
            entityType = method.getGenericParameterTypes()[i];
            entity = value;
        } else {
            if (value == null && (ann = anns.get(DefaultValue.class)) != null) {
                value = ((DefaultValue) ann).value();
            }
            if (value != null) {
                if ((ann = anns.get(PathParam.class)) != null) {
                    newTarget = newTarget.resolveTemplate(((PathParam) ann).value(), value);
                } else if ((ann = anns.get((QueryParam.class))) != null) {
                    if (value instanceof Collection) {
                        newTarget = newTarget.queryParam(((QueryParam) ann).value(), convert((Collection) value));
                    } else {
                        newTarget = newTarget.queryParam(((QueryParam) ann).value(), value);
                    }
                } else if ((ann = anns.get((HeaderParam.class))) != null) {
                    if (value instanceof Collection) {
                        headers.addAll(((HeaderParam) ann).value(), convert((Collection) value));
                    } else {
                        headers.addAll(((HeaderParam) ann).value(), value);
                    }
                } else if ((ann = anns.get((CookieParam.class))) != null) {
                    final String name = ((CookieParam) ann).value();
                    Cookie c;
                    if (value instanceof Collection) {
                        for (final Object v : ((Collection) value)) {
                            if (!(v instanceof Cookie)) {
                                c = new Cookie(name, v.toString());
                            } else {
                                c = (Cookie) v;
                                if (!name.equals(((Cookie) v).getName())) {
                                    // is this the right thing to do? or should I fail? or ignore the difference?
                                    c = new Cookie(name, c.getValue(), c.getPath(), c.getDomain(), c.getVersion());
                                }
                            }
                            cookies.add(c);
                        }
                    } else {
                        if (!(value instanceof Cookie)) {
                            cookies.add(new Cookie(name, value.toString()));
                        } else {
                            c = (Cookie) value;
                            if (!name.equals(((Cookie) value).getName())) {
                                // is this the right thing to do? or should I fail? or ignore the difference?
                                cookies.add(new Cookie(name, c.getValue(), c.getPath(), c.getDomain(), c.getVersion()));
                            }
                        }
                    }
                } else if ((ann = anns.get((MatrixParam.class))) != null) {
                    if (value instanceof Collection) {
                        newTarget = newTarget.matrixParam(((MatrixParam) ann).value(), convert((Collection) value));
                    } else {
                        newTarget = newTarget.matrixParam(((MatrixParam) ann).value(), value);
                    }
                } else if ((ann = anns.get((FormParam.class))) != null) {
                    if (value instanceof Collection) {
                        for (final Object v : ((Collection) value)) {
                            form.param(((FormParam) ann).value(), v.toString());
                        }
                    } else {
                        form.param(((FormParam) ann).value(), value.toString());
                    }
                }
            }
        }
    }
    if (httpMethod == null) {
        // the method is a subresource locator
        return WebResourceFactory.newResource(responseType, newTarget, true, headers, cookies, form);
    }
    // accepted media types
    Produces produces = method.getAnnotation(Produces.class);
    if (produces == null) {
        produces = proxyIfc.getAnnotation(Produces.class);
    }
    final String[] accepts = (produces == null) ? EMPTY : produces.value();
    // determine content type
    String contentType = null;
    if (entity != null) {
        final List<Object> contentTypeEntries = headers.get(HttpHeaders.CONTENT_TYPE);
        if ((contentTypeEntries != null) && (!contentTypeEntries.isEmpty())) {
            contentType = contentTypeEntries.get(0).toString();
        } else {
            Consumes consumes = method.getAnnotation(Consumes.class);
            if (consumes == null) {
                consumes = proxyIfc.getAnnotation(Consumes.class);
            }
            if (consumes != null && consumes.value().length > 0) {
                contentType = consumes.value()[0];
            }
        }
    }
    Invocation.Builder builder = newTarget.request().headers(// this resets all headers so do this first
    headers).accept(// if @Produces is defined, propagate values into Accept header; empty array is NO-OP
    accepts);
    for (final Cookie c : cookies) {
        builder = builder.cookie(c);
    }
    final Object result;
    if (entity == null && !form.asMap().isEmpty()) {
        entity = form;
        contentType = MediaType.APPLICATION_FORM_URLENCODED;
    } else {
        if (contentType == null) {
            contentType = MediaType.APPLICATION_OCTET_STREAM;
        }
        if (!form.asMap().isEmpty()) {
            if (entity instanceof Form) {
                ((Form) entity).asMap().putAll(form.asMap());
            } else {
            // TODO: should at least log some warning here
            }
        }
    }
    final GenericType responseGenericType = new GenericType(method.getGenericReturnType());
    if (entity != null) {
        if (entityType instanceof ParameterizedType) {
            entity = new GenericEntity(entity, entityType);
        }
        result = builder.method(httpMethod, Entity.entity(entity, contentType), responseGenericType);
    } else {
        result = builder.method(httpMethod, responseGenericType);
    }
    return result;
}
Also used : MatrixParam(javax.ws.rs.MatrixParam) Invocation(javax.ws.rs.client.Invocation) Form(javax.ws.rs.core.Form) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) ParameterizedType(java.lang.reflect.ParameterizedType) Consumes(javax.ws.rs.Consumes) PathParam(javax.ws.rs.PathParam) Cookie(javax.ws.rs.core.Cookie) GenericType(javax.ws.rs.core.GenericType) Annotation(java.lang.annotation.Annotation) LinkedList(java.util.LinkedList) CookieParam(javax.ws.rs.CookieParam) MediaType(javax.ws.rs.core.MediaType) GenericType(javax.ws.rs.core.GenericType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) QueryParam(javax.ws.rs.QueryParam) Produces(javax.ws.rs.Produces) GenericEntity(javax.ws.rs.core.GenericEntity) Collection(java.util.Collection) WebTarget(javax.ws.rs.client.WebTarget) FormParam(javax.ws.rs.FormParam)

Example 5 with Cookie

use of javax.ws.rs.core.Cookie in project jersey by jersey.

the class ParamExceptionMappingTest method testGeneralParamException.

@Test
public void testGeneralParamException() throws ExecutionException, InterruptedException {
    initiateWebApplication(ParamExceptionMapperResource.class, ParamExceptionMapper.class);
    ContainerResponse responseContext = getResponseContext(UriBuilder.fromPath("/").path("path/ 123").build().toString());
    assertEquals("param", responseContext.getEntity());
    responseContext = getResponseContext(UriBuilder.fromPath("/").path("matrix;x= 123").build().toString());
    assertEquals("param", responseContext.getEntity());
    responseContext = getResponseContext(UriBuilder.fromPath("/").path("query").queryParam("x", " 123").build().toString());
    assertEquals("param", responseContext.getEntity());
    responseContext = getResponseContext(UriBuilder.fromPath("/").path("cookie").build().toString(), new Cookie("x", " 123"));
    assertEquals("param", responseContext.getEntity());
    responseContext = apply(RequestContextBuilder.from("/header", "GET").header("x", " 123").build());
    assertEquals("param", responseContext.getEntity());
    Form f = new Form();
    f.param("x", " 123");
    responseContext = apply(RequestContextBuilder.from("/form", "POST").type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).entity(f).build());
    assertEquals("param", responseContext.getEntity());
}
Also used : Cookie(javax.ws.rs.core.Cookie) ContainerResponse(org.glassfish.jersey.server.ContainerResponse) Form(javax.ws.rs.core.Form) Test(org.junit.Test)

Aggregations

Cookie (javax.ws.rs.core.Cookie)49 Test (org.junit.Test)28 HashMap (java.util.HashMap)7 ContainerResponse (org.glassfish.jersey.server.ContainerResponse)7 NewCookie (javax.ws.rs.core.NewCookie)6 Entitlement (com.sun.identity.entitlement.Entitlement)4 EntitlementSubject (com.sun.identity.entitlement.EntitlementSubject)4 Privilege (com.sun.identity.entitlement.Privilege)4 PrivilegeManager (com.sun.identity.entitlement.PrivilegeManager)4 ClientResponse (com.sun.jersey.api.client.ClientResponse)4 BeforeClass (org.testng.annotations.BeforeClass)4 SSOToken (com.iplanet.sso.SSOToken)3 Form (javax.ws.rs.core.Form)3 AuthenticatedUsers (org.forgerock.openam.entitlement.conditions.subject.AuthenticatedUsers)3 JSONEntitlement (com.sun.identity.entitlement.JSONEntitlement)2 UniformInterfaceException (com.sun.jersey.api.client.UniformInterfaceException)2 MalformedURLException (java.net.MalformedURLException)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Consumes (javax.ws.rs.Consumes)2