org.glassfish.jersey.internal.util.collection.MultivaluedStringMap Java Examples

The following examples show how to use org.glassfish.jersey.internal.util.collection.MultivaluedStringMap. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SparseFieldSetFilterTest.java    From alchemy with MIT License 6 votes vote down vote up
private void doFilter(String ... fields) {
    final MultivaluedMap<String, String> queryParams = new MultivaluedStringMap();
    queryParams.put("fields", Lists.newArrayList(fields));
    doReturn(queryParams).when(request).getHeaders();

    final ObjectNode entity = mapper.createObjectNode();
    entity.put("name", "foo");

    final ArrayNode arrayNode = mapper.createArrayNode();
    entity.put("array", arrayNode);

    final ObjectNode personNode = mapper.createObjectNode();
    arrayNode.add(personNode);

    personNode.put("age", 32);
    personNode.put("name", "Gene");
    entity.put("person", personNode);

    doReturn(entity).when(response).getEntity();
    doAnswer(invocation -> {
        responseEntity = (ObjectNode) invocation.getArguments()[0];
        return null;
    }).when(response).setEntity(any());

    filter.filter(request, response);
}
 
Example #2
Source File: RequestUtils.java    From mrgeo with Apache License 2.0 6 votes vote down vote up
public static MultivaluedMap<String, String> replaceParam(String name, List<String> values,
    MultivaluedMap<String, String> params)
{

  MultivaluedStringMap sm = new MultivaluedStringMap(params);

  for (Map.Entry<String, List<String>> es : params.entrySet())
  {
    if (es.getKey().equalsIgnoreCase(name))
    {
      sm.remove(es.getKey());
      break;
    }
  }

  sm.putIfAbsent(name, values);

  return sm;
}
 
Example #3
Source File: WnsClient.java    From java-wns with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Based on <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh465407.aspx">http://msdn.microsoft.com/en-us/library/windows/apps/hh465407.aspx</a>
 *
 * @throws WnsException when authentication fails
 */
public void refreshAccessToken() throws WnsException {
    WebTarget target = client.target(getAuthenticationUri());

    MultivaluedStringMap formData = new MultivaluedStringMap();
    formData.add("grant_type", GRANT_TYPE_CLIENT_CREDENTIALS);
    formData.add("client_id", this.sid);
    formData.add("client_secret", this.clientSecret);
    formData.add("scope", SCOPE);
    Response response = target.request(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept(MediaType.APPLICATION_JSON_TYPE).post(Entity.form(formData));

    if (response.getStatus() != 200) {
        throw new WnsException("Authentication failed. HTTP error code: " + response.getStatus());
    }

    this.token = response.readEntity(WnsOAuthToken.class);
}
 
Example #4
Source File: OAuth2AuthenticationResource.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response exchangeAuthorizationCode(
        @PathParam(value = "identity") String identity,
        @Valid @NotNull final Payload payload,
        @Context final HttpServletResponse servletResponse) throws IOException {
    SocialIdentityProviderEntity identityProvider = socialIdentityProviderService.findById(identity);

    if (identityProvider != null) {
        // Step 1. Exchange authorization code for access token.
        final MultivaluedStringMap accessData = new MultivaluedStringMap();
        accessData.add(CLIENT_ID_KEY, payload.getClientId());
        accessData.add(REDIRECT_URI_KEY, payload.getRedirectUri());
        accessData.add(CLIENT_SECRET, identityProvider.getClientSecret());
        accessData.add(CODE_KEY, payload.getCode());
        accessData.add(GRANT_TYPE_KEY, AUTH_CODE);

        Response response = client.target(identityProvider.getTokenEndpoint())
                .request(javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE)
                .post(Entity.form(accessData));
        accessData.clear();

        if (response.getStatus() == Response.Status.OK.getStatusCode()) {
            final String accessToken = (String) getResponseEntity(response).get(ACCESS_TOKEN_PROPERTY);
            return authenticateUser(identityProvider, servletResponse, accessToken, payload.getState());
        } else {
            LOGGER.error("Exchange authorization code failed with status {}: {}\n{}", response.getStatus(), response.getStatusInfo(), getResponseEntityAsString(response));
        }
        return Response
                .status(Response.Status.UNAUTHORIZED)
                .build();
    }

    return Response.status(Response.Status.NOT_FOUND).build();
}
 
Example #5
Source File: OAuth2AuthenticationResource.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response exchangeAuthorizationCode(
        @PathParam(value = "identity") String identity,
        @Valid @NotNull(message = "Input must not be null.") final PayloadInput payloadInput,
        @Context final HttpServletResponse servletResponse) throws IOException {
    
    SocialIdentityProviderEntity identityProvider = socialIdentityProviderService.findById(identity);

    if (identityProvider != null) {
        // Step 1. Exchange authorization code for access token.
        final MultivaluedStringMap accessData = new MultivaluedStringMap();
        accessData.add(CLIENT_ID_KEY, payloadInput.getClientId());
        accessData.add(REDIRECT_URI_KEY, payloadInput.getRedirectUri());
        accessData.add(CLIENT_SECRET, identityProvider.getClientSecret());
        accessData.add(CODE_KEY, payloadInput.getCode());
        accessData.add(CODE_VERIFIER_KEY, payloadInput.getCodeVerifier());
        accessData.add(GRANT_TYPE_KEY, payloadInput.getGrantType());

        Response response = client.target(identityProvider.getTokenEndpoint())
                .request(javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE)
                .post(Entity.form(accessData));
        accessData.clear();

        if (response.getStatus() == Response.Status.OK.getStatusCode()) {
            final String accessToken = (String) getResponseEntity(response).get(ACCESS_TOKEN_PROPERTY);
            return authenticateUser(identityProvider, servletResponse, accessToken, payloadInput.getState());
        } else {
            LOGGER.error("Exchange authorization code failed with status {}: {}\n{}", response.getStatus(), response.getStatusInfo(), getResponseEntityAsString(response));
        }
        return Response
                .status(Response.Status.UNAUTHORIZED)
                .build();
    }

    return Response.status(Response.Status.NOT_FOUND).build();
}
 
Example #6
Source File: StandardWebSocketSession.java    From ameba with MIT License 5 votes vote down vote up
/**
 * Class constructor that associates a user with the WebSocket session.
 *
 * @param headers       the headers of the handshake request
 * @param attributes    attributes from the HTTP handshake to associate with the WebSocket session
 * @param localAddress  the address on which the request was received
 * @param remoteAddress the address of the remote client
 * @param user          the user associated with the session; if {@code null} we'll
 *                      fallback on the user available in the underlying WebSocket session
 */
public StandardWebSocketSession(MultivaluedMap<String, String> headers,
                                Map<String, List<String>> requestParameters,
                                Map<String, String> pathParameters, Map<String, Object> attributes,
                                InetSocketAddress localAddress, InetSocketAddress remoteAddress, Principal user) {
    super(attributes, requestParameters, pathParameters);
    this.handshakeHeaders = (headers != null) ? headers : new MultivaluedStringMap();
    this.user = user;
    this.localAddress = localAddress;
    this.remoteAddress = remoteAddress;
}
 
Example #7
Source File: OptionalFormParamResourceTest.java    From dropwizard-java8 with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnDefaultMessageWhenMessageIsNotPresent() throws IOException {
    final String defaultMessage = "Default Message";
    final Response response = target("/optional/message").request().post(Entity.form(new MultivaluedStringMap()));

    assertThat(response.readEntity(String.class)).isEqualTo(defaultMessage);
}
 
Example #8
Source File: OptionalFormParamResourceTest.java    From dropwizard-java8 with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnDefaultMessageWhenMyMessageIsNotPresent() throws IOException {
    final String defaultMessage = "My Default Message";
    final Response response = target("/optional/my-message").request().post(Entity.form(new MultivaluedStringMap()));

    assertThat(response.readEntity(String.class)).isEqualTo(defaultMessage);
}
 
Example #9
Source File: OptionalFormParamResourceTest.java    From dropwizard-java8 with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnDefaultUUIDWhenUUIDIsNotPresent() throws IOException {
    final String defaultUUID = "d5672fa8-326b-40f6-bf71-d9dacf44bcdc";
    final Response response = target("/optional/uuid").request().post(Entity.form(new MultivaluedStringMap()));

    assertThat(response.readEntity(String.class)).isEqualTo(defaultUUID);
}
 
Example #10
Source File: ApiIntegrationTest.java    From dropwizard-experiment with MIT License 5 votes vote down vote up
protected static MultivaluedMap<String, String> formParameters(String... keyValues) {
    Preconditions.checkArgument(keyValues.length % 2 == 0, "Must have an even number of arguments.");
    MultivaluedMap<String, String> parameters = new MultivaluedStringMap();

    for (int i = 0; i < keyValues.length; i = i + 2) {
        parameters.add(keyValues[i], keyValues[i + 1]);
    }

    return parameters;
}
 
Example #11
Source File: OAuth2IntegrationTest.java    From dropwizard-experiment with MIT License 5 votes vote down vote up
private static MultivaluedMap<String, String> loginParameters(String username, String password) {
    MultivaluedMap<String, String> parameters = new MultivaluedStringMap();
    parameters.add("grant_type", "password");
    if (username != null) {
        parameters.add("username", username);
    }
    if (password != null) {
        parameters.add("password", password);
    }
    return parameters;
}
 
Example #12
Source File: OAuth2AuthenticationResource.java    From gravitee-management-rest-api with Apache License 2.0 4 votes vote down vote up
@POST
@Path("exchange")
@Produces(MediaType.APPLICATION_JSON)
public Response tokenExchange(
        @PathParam(value = "identity") final String identity,
        @QueryParam(value = "token") final String token,
        @Context final HttpServletResponse servletResponse) throws IOException {
    SocialIdentityProviderEntity identityProvider = socialIdentityProviderService.findById(identity);

    if (identityProvider != null) {
        if (identityProvider.getTokenIntrospectionEndpoint() != null) {
            // Step1. Check the token by invoking the introspection endpoint
            final MultivaluedStringMap introspectData = new MultivaluedStringMap();
            introspectData.add(TOKEN, token);
            Response response = client
                    //TODO: what is the correct introspection URL here ?
                    .target(identityProvider.getTokenIntrospectionEndpoint())
                    .request(javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE)
                    .header(HttpHeaders.AUTHORIZATION,
                            String.format("Basic %s",
                                    Base64.getEncoder().encodeToString(
                                            (identityProvider.getClientId() + ':' + identityProvider.getClientSecret()).getBytes())))
                    .post(Entity.form(introspectData));
            introspectData.clear();

            if (response.getStatus() == Response.Status.OK.getStatusCode()) {
                JsonNode introspectPayload = response.readEntity(JsonNode.class);
                boolean active = introspectPayload.path("active").asBoolean(true);

                if (active) {
                    return authenticateUser(identityProvider, servletResponse, token, null);
                } else {
                    return Response
                            .status(Response.Status.UNAUTHORIZED)
                            .entity(introspectPayload)
                            .build();
                }
            } else {
                LOGGER.error("Token exchange failed with status {}: {}\n{}", response.getStatus(), response.getStatusInfo(), getResponseEntityAsString(response));
            }

            return Response
                    .status(response.getStatusInfo())
                    .entity(response.getEntity())
                    .build();
        } else {
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity("Token exchange is not supported for this identity provider")
                    .build();
        }
    }

    return Response.status(Response.Status.NOT_FOUND).build();
}
 
Example #13
Source File: OAuth2AuthenticationResource.java    From gravitee-management-rest-api with Apache License 2.0 4 votes vote down vote up
@POST
@Path("_exchange")
@Produces(MediaType.APPLICATION_JSON)
public Response tokenExchange(
        @PathParam(value = "identity") final String identity,
        @QueryParam(value = "token") final String token,
        @Context final HttpServletResponse servletResponse) {
    SocialIdentityProviderEntity identityProvider = socialIdentityProviderService.findById(identity);

    if (identityProvider != null) {
        if (identityProvider.getTokenIntrospectionEndpoint() != null) {
            // Step1. Check the token by invoking the introspection endpoint
            final MultivaluedStringMap introspectData = new MultivaluedStringMap();
            introspectData.add(TOKEN, token);
            Response response = client
                    //TODO: what is the correct introspection URL here ?
                    .target(identityProvider.getTokenIntrospectionEndpoint())
                    .request(javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE)
                    .header(HttpHeaders.AUTHORIZATION,
                            String.format("Basic %s",
                                    Base64.getEncoder().encodeToString(
                                            (identityProvider.getClientId() + ':' + identityProvider.getClientSecret()).getBytes())))
                    .post(Entity.form(introspectData));
            introspectData.clear();

            if (response.getStatus() == Response.Status.OK.getStatusCode()) {
                JsonNode introspectPayload = response.readEntity(JsonNode.class);
                boolean active = introspectPayload.path("active").asBoolean(true);

                if (active) {
                    return authenticateUser(identityProvider, servletResponse, token, null);
                } else {
                    return Response
                            .status(Response.Status.UNAUTHORIZED)
                            .entity(introspectPayload)
                            .build();
                }
            } else {
                LOGGER.error("Token exchange failed with status {}: {}\n{}", response.getStatus(), response.getStatusInfo(), getResponseEntityAsString(response));
            }

            return Response
                    .status(response.getStatusInfo())
                    .entity(response.getEntity())
                    .build();
        } else {
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity("Token exchange is not supported for this identity provider")
                    .build();
        }
    }

    return Response.status(Response.Status.NOT_FOUND).build();
}