Example usage for org.springframework.http MediaType APPLICATION_FORM_URLENCODED_VALUE

List of usage examples for org.springframework.http MediaType APPLICATION_FORM_URLENCODED_VALUE

Introduction

In this page you can find the example usage for org.springframework.http MediaType APPLICATION_FORM_URLENCODED_VALUE.

Prototype

String APPLICATION_FORM_URLENCODED_VALUE

To view the source code for org.springframework.http MediaType APPLICATION_FORM_URLENCODED_VALUE.

Click Source Link

Document

A String equivalent of MediaType#APPLICATION_FORM_URLENCODED .

Usage

From source file:com.traffitruck.web.HtmlController.java

@RequestMapping(value = "/newAlert", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
ModelAndView newAlert(@ModelAttribute("alert") Alert alert, BindingResult br1,
        @RequestParam("sourceLat") Double sourceLat, BindingResult br4,
        @RequestParam("sourceLng") Double sourceLng, BindingResult br5,
        @RequestParam("destinationLat") Double destinationLat, BindingResult br6,
        @RequestParam("destinationLng") Double destinationLng, BindingResult br7) throws IOException {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String username = authentication.getName();
    alert.setUsername(username);/*w  w w  . jav a 2  s.c o  m*/
    if (sourceLat != null && sourceLng != null) {
        alert.setSourceLocation(new Location(new double[] { sourceLng, sourceLat }));
    }
    if (destinationLat != null && destinationLng != null) {
        alert.setDestinationLocation(new Location(new double[] { destinationLng, destinationLat }));
    }
    dao.storeAlert(alert);
    return new ModelAndView("redirect:/myAlerts");
}

From source file:cu.uci.coj.restapi.controller.RestUserProfileController.java

@ApiOperation(value = "Modificar Perfil de Usuario", notes = "Modifica el perfil de usuario con los datos enviados.")
@ApiResponses(value = {/*from w w w.ja v  a  2 s  .  c om*/
        @ApiResponse(code = 401, message = "username token mismatch<br> hash incorrect<br> token expirated<br> username apikey mismatch<br> apikey hash incorrect<br> apikey expirated<br> apikey secret incorrect<br> token or apikey incorrect"),
        @ApiResponse(code = 400, message = "institution witout country<br> incorrect request"),
        @ApiResponse(code = 412, message = "Nick must not more than 25 characters<br> Nick must not less than 3 characters<br> The first name is too short<br> The first name is too long<br> The first name contains invalid characters<br> The last name is too long<br> The last name is too short<br> The last name contains invalid characters<br> Required field<br> This e-mail already exists<br> Invalid email."),
        @ApiResponse(code = 404, message = "bad user<br> bad institution id<br> bad language<br> bad locale<br> bad gender<br> bad country id"),
        @ApiResponse(code = 500, message = "failed send email"), })
@RequestMapping(value = "/update", method = RequestMethod.PUT, headers = "Accept=application/json", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
@ResponseBody
public ResponseEntity<?> UpdateProfile(
        @ApiParam(value = "Llave de desarrollador") @RequestParam(value = "apikey") String apikey,
        @ApiParam(value = "Token de usuario") @RequestParam(value = "token") String token,
        @ApiParam(value = "Ao de nacimiento") @RequestParam(value = "year", required = false) Integer year,
        @ApiParam(value = "Mes de nacimiento") @RequestParam(value = "month", required = false) Integer month,
        @ApiParam(value = "Da de nacimiento") @RequestParam(value = "day", required = false) Integer day,
        @ApiParam(value = "Apodo") @RequestParam(value = "nick", required = false) String nick,
        @ApiParam(value = "Nombre") @RequestParam(value = "name", required = false) String name,
        @ApiParam(value = "Apellido") @RequestParam(value = "lastname", required = false) String lastname,
        @ApiParam(value = "Correo") @RequestParam(value = "email", required = false) String email,
        @ApiParam(value = "Identificador del Pas") @RequestParam(value = "country_id", required = false) Integer country_id,
        @ApiParam(value = "Identificador de la Institucin") @RequestParam(value = "institution_id", required = false) Integer institution_id,
        @ApiParam(value = "Identificador del lenguaje favorito (Ver filters)") @RequestParam(value = "lid", required = false) Integer lid,
        @ApiParam(value = "Identificador del idioma favorito (Ver filters)") @RequestParam(value = "locale", required = false) Integer locale,
        @ApiParam(value = "Sexo:  (1)Hombre (2) Mujer", allowableValues = "1,2") @RequestParam(value = "gender", required = false) Integer gender) {

    try {

        int error = ValidateApiAndToken(apikey, token);
        if (error > 0) {
            return new ResponseEntity<>(TokenUtils.ErrorMessage(error), HttpStatus.UNAUTHORIZED);
        }

        String username = null;
        username = ExtractUser(token);

        User user = userDAO.loadAllUserData(username);
        if (year != null)
            user.setYear(year);
        if (month != null)
            user.setMonth(month);
        if (day != null)
            user.setDay(day);
        user.setUsername(username);
        if (nick != null)
            user.setNick(nick);
        if (name != null)
            user.setName(name);
        if (lastname != null)
            user.setLastname(lastname);
        if (email != null)
            user.setEmail(email);
        if (country_id != null)
            user.setCountry_id(country_id);
        if (institution_id != null)
            user.setInstitution_id(institution_id);
        if (lid != null)
            user.setLid(lid);
        if (locale != null)
            user.setLocale(locale);
        if (gender != null)
            user.setGender(gender);

        user.setUid(userDAO.integer("select.uid.by.username", username));
        user.setDob(new Date(user.getYear() - 1900, user.getMonth() - 1, user.getDay()));

        boolean is_team = !userDAO.bool("is.user", user.getUsername());
        if (is_team)
            return new ResponseEntity<>(ErrorUtils.BAD_USER, HttpStatus.NOT_FOUND);

        user.setTeam(false);

        String errors = ValidateUser(user);
        if (!errors.equals("0"))
            return new ResponseEntity<>(errors, HttpStatus.PRECONDITION_FAILED);

        if (country_id != null && !ValidateCountry(country_id))
            return new ResponseEntity<>(ErrorUtils.BAD_COUNTRY_ID, HttpStatus.NOT_FOUND);

        if (country_id != null && institution_id != null && !ValidateInstitutionID(country_id, institution_id))
            return new ResponseEntity<>(ErrorUtils.BAD_INSTITUTION_ID, HttpStatus.NOT_FOUND);

        if (country_id == null && institution_id != null)
            return new ResponseEntity<>(ErrorUtils.INSTITUTION_WITHOUT_COUNTRY, HttpStatus.BAD_REQUEST);

        if (lid != null && !ValidateLanguage(lid))
            return new ResponseEntity<>(ErrorUtils.BAD_LANGUAGE, HttpStatus.NOT_FOUND);

        if (locale != null && !ValidateLocale(locale))
            return new ResponseEntity<>(ErrorUtils.BAD_LOCALE, HttpStatus.NOT_FOUND);

        if (gender != null && gender != 1 && gender != 2)
            return new ResponseEntity<>(ErrorUtils.BAD_GENDER, HttpStatus.NOT_FOUND);

        try {
            userDAO.updateUser(user);
        } catch (Exception e) {
            return new ResponseEntity<>(ErrorUtils.FAILED_SEND_EMAIL, HttpStatus.INTERNAL_SERVER_ERROR);
        }

    } catch (IOException ex) {
        return new ResponseEntity<>(ErrorUtils.INCORRECT_JSON, HttpStatus.BAD_REQUEST);
    }

    return new ResponseEntity<>(HttpStatus.OK);
}

From source file:org.cloudfoundry.identity.uaa.integration.feature.AutologinIT.java

@Test
public void testAutologinFlow_FORM() throws Exception {
    testAutologinFlow(MediaType.APPLICATION_FORM_URLENCODED_VALUE, map);
}

From source file:org.cloudfoundry.identity.uaa.integration.feature.AutologinIT.java

@Test
public void testSimpleAutologinFlow() throws Exception {
    HttpHeaders headers = getAppBasicAuthHttpHeaders();

    LinkedMultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
    requestBody.add("username", testAccounts.getUserName());
    requestBody.add("password", testAccounts.getPassword());

    //generate an autologin code with our credentials
    ResponseEntity<Map> autologinResponseEntity = restOperations.exchange(baseUrl + "/autologin",
            HttpMethod.POST, new HttpEntity<>(requestBody.toSingleValueMap(), headers), Map.class);
    String autologinCode = (String) autologinResponseEntity.getBody().get("code");

    //start the authorization flow - this will issue a login event
    //by using the autologin code
    String authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize")
            .queryParam("redirect_uri", appUrl).queryParam("response_type", "code")
            .queryParam("client_id", "app").queryParam("code", autologinCode).build().toUriString();

    //rest template that does NOT follow redirects
    RestTemplate template = new RestTemplate(new DefaultIntegrationTestConfig.HttpClientFactory());
    headers.remove("Authorization");
    headers.add(HttpHeaders.ACCEPT, MediaType.TEXT_HTML_VALUE);
    ResponseEntity<String> authorizeResponse = template.exchange(authorizeUrl, HttpMethod.GET,
            new HttpEntity<>(new HashMap<String, String>(), headers), String.class);

    //we are now logged in. retrieve the JSESSIONID
    List<String> cookies = authorizeResponse.getHeaders().get("Set-Cookie");
    int cookiesAdded = 0;
    headers = getAppBasicAuthHttpHeaders();
    for (String cookie : cookies) {
        if (cookie.startsWith("X-Uaa-Csrf=") || cookie.startsWith("JSESSIONID=")) {
            headers.add("Cookie", cookie);
            cookiesAdded++;//  ww  w .  j a v  a2s  . com
        }
    }
    assertEquals(2, cookiesAdded);

    //if we receive a 200, then we must approve our scopes
    if (HttpStatus.OK == authorizeResponse.getStatusCode()) {
        authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize")
                .queryParam("user_oauth_approval", "true")
                .queryParam(DEFAULT_CSRF_COOKIE_NAME,
                        IntegrationTestUtils.extractCookieCsrf(authorizeResponse.getBody()))
                .build().toUriString();
        authorizeResponse = template.exchange(authorizeUrl, HttpMethod.POST,
                new HttpEntity<>(new HashMap<String, String>(), headers), String.class);
    }

    //approval is complete, we receive a token code back
    assertEquals(HttpStatus.FOUND, authorizeResponse.getStatusCode());
    List<String> location = authorizeResponse.getHeaders().get("Location");
    assertEquals(1, location.size());
    String newCode = location.get(0).substring(location.get(0).indexOf("code=") + 5);

    //request a token using our code
    String tokenUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/token").build().toUriString();

    MultiValueMap<String, String> tokenParams = new LinkedMultiValueMap<>();
    tokenParams.add("response_type", "token");
    tokenParams.add("grant_type", GRANT_TYPE_AUTHORIZATION_CODE);
    tokenParams.add("code", newCode);
    tokenParams.add("redirect_uri", appUrl);
    headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
    headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);

    RequestEntity<MultiValueMap<String, String>> requestEntity = new RequestEntity<>(tokenParams, headers,
            HttpMethod.POST, new URI(tokenUrl));
    ResponseEntity<Map> tokenResponse = template.exchange(requestEntity, Map.class);
    assertEquals(HttpStatus.OK, tokenResponse.getStatusCode());

    //here we must reset our state. we do that by following the logout flow.
    headers.clear();

    BasicCookieStore cookieStore = new BasicCookieStore();
    ResponseEntity<String> loginResponse = template.exchange(baseUrl + "/login", HttpMethod.GET,
            new HttpEntity<>(null, getHeaders(cookieStore)), String.class);

    setCookiesFromResponse(cookieStore, loginResponse);
    String csrf = IntegrationTestUtils.extractCookieCsrf(loginResponse.getBody());
    requestBody.add(DEFAULT_CSRF_COOKIE_NAME, csrf);

    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    loginResponse = restOperations.exchange(baseUrl + "/login.do", HttpMethod.POST,
            new HttpEntity<>(requestBody, getHeaders(cookieStore)), String.class);
    cookies = loginResponse.getHeaders().get("Set-Cookie");
    assertThat(cookies, hasItem(startsWith("JSESSIONID")));
    assertThat(cookies, hasItem(startsWith("X-Uaa-Csrf")));
    if (IdentityZoneHolder.get().getConfig().isAccountChooserEnabled()) {
        assertThat(cookies, hasItem(startsWith("Saved-Account-")));
    }
    assertThat(cookies, hasItem(startsWith("Current-User")));
    cookieStore.clear();
    setCookiesFromResponse(cookieStore, loginResponse);
    headers.add(HttpHeaders.ACCEPT, MediaType.TEXT_HTML_VALUE);
    ResponseEntity<String> profilePage = restOperations.exchange(baseUrl + "/profile", HttpMethod.GET,
            new HttpEntity<>(null, getHeaders(cookieStore)), String.class);

    setCookiesFromResponse(cookieStore, profilePage);
    String revokeApprovalsUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/profile").build()
            .toUriString();
    requestBody.clear();
    requestBody.add("clientId", "app");
    requestBody.add("delete", "");
    requestBody.add(DEFAULT_CSRF_COOKIE_NAME, IntegrationTestUtils.extractCookieCsrf(profilePage.getBody()));
    ResponseEntity<Void> revokeResponse = template.exchange(revokeApprovalsUrl, HttpMethod.POST,
            new HttpEntity<>(requestBody, getHeaders(cookieStore)), Void.class);
    assertEquals(HttpStatus.FOUND, revokeResponse.getStatusCode());
}

From source file:org.cloudfoundry.identity.uaa.mock.token.RefreshTokenMockMvcTests.java

@Test
void refreshTokenGrant_rejectsAccessTokens_ClientCredentialsGrantType() throws Exception {
    createClientAndUserInRandomZone();/*  w ww. ja va  2  s.c o m*/
    String tokenResponse = mockMvc
            .perform(post("/oauth/token").header("Host", getZoneHostUrl(zone))
                    .accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
                    .param(OAuth2Utils.GRANT_TYPE, GRANT_TYPE_CLIENT_CREDENTIALS).param("client_secret", SECRET)
                    .param(OAuth2Utils.CLIENT_ID, client.getClientId()))
            .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
    String accessToken = (String) JsonUtils.readValue(tokenResponse, new TypeReference<Map<String, Object>>() {
    }).get("access_token");

    mockMvc.perform(post("/oauth/token").header("Host", getZoneHostUrl(zone)).accept(MediaType.APPLICATION_JSON)
            .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
            .param(OAuth2Utils.GRANT_TYPE, REFRESH_TOKEN).param(REFRESH_TOKEN, accessToken)
            .param("client_secret", SECRET).param(OAuth2Utils.CLIENT_ID, client.getClientId()))
            .andExpect(status().isUnauthorized());
}

From source file:org.cloudfoundry.identity.uaa.mock.token.RefreshTokenMockMvcTests.java

@Test
void refreshTokenGrant_rejectsAccessTokens_PasswordGrantType() throws Exception {
    createClientAndUserInRandomZone();//from   w ww. j a  v a2 s.  c  o m
    String body = mockMvc
            .perform(post("/oauth/token").accept(MediaType.APPLICATION_JSON_VALUE)
                    .header("Host", getZoneHostUrl(zone))
                    .header("Authorization",
                            "Basic " + new String(
                                    Base64.encode((client.getClientId() + ":" + SECRET).getBytes())))
                    .param("grant_type", GRANT_TYPE_PASSWORD).param("client_id", client.getClientId())
                    .param("client_secret", SECRET).param("username", user.getUserName())
                    .param("password", SECRET))
            .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();

    Map<String, Object> bodyMap = JsonUtils.readValue(body, new TypeReference<Map<String, Object>>() {
    });
    String accessToken = (String) bodyMap.get("access_token");

    mockMvc.perform(post("/oauth/token").header("Host", getZoneHostUrl(zone)).accept(MediaType.APPLICATION_JSON)
            .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
            .param(OAuth2Utils.GRANT_TYPE, REFRESH_TOKEN).param(REFRESH_TOKEN, accessToken)
            .param("client_secret", SECRET).param(OAuth2Utils.CLIENT_ID, client.getClientId()))
            .andExpect(status().isUnauthorized());
}

From source file:org.cloudfoundry.identity.uaa.mock.token.RefreshTokenMockMvcTests.java

@Test
void refreshTokenGrant_rejectsIdTokens() throws Exception {
    createClientAndUserInRandomZone();//from   w ww.j ava 2 s  .  c  o m
    String body = mockMvc
            .perform(post("/oauth/token").accept(MediaType.APPLICATION_JSON_VALUE)
                    .header("Host", getZoneHostUrl(zone))
                    .header("Authorization",
                            "Basic " + new String(
                                    Base64.encode((client.getClientId() + ":" + SECRET).getBytes())))
                    .param("grant_type", GRANT_TYPE_PASSWORD).param("client_id", client.getClientId())
                    .param("client_secret", SECRET).param("username", user.getUserName())
                    .param("password", SECRET))
            .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();

    Map<String, Object> bodyMap = JsonUtils.readValue(body, new TypeReference<Map<String, Object>>() {
    });
    String idToken = (String) bodyMap.get("id_token");

    mockMvc.perform(post("/oauth/token").header("Host", getZoneHostUrl(zone)).accept(MediaType.APPLICATION_JSON)
            .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
            .param(OAuth2Utils.GRANT_TYPE, REFRESH_TOKEN).param(REFRESH_TOKEN, idToken)
            .param("client_secret", SECRET).param(OAuth2Utils.CLIENT_ID, client.getClientId()))
            .andExpect(status().isUnauthorized());
}

From source file:org.cloudfoundry.identity.uaa.mock.token.RefreshTokenMockMvcTests.java

@Test
void refreshTokenGrantType_requiresAuthorizedGrantType() throws Exception {
    client = setUpClients("clientwithrefresh", "", "scim.me", "password,refresh_token", true);
    ClientDetails clientWithoutRefresh = setUpClients("passwordclient", "", "scim.me", "password", true);
    user = setUpUser("joe-user", "", OriginKeys.UAA, "uaa");
    String refreshToken = getJwtRefreshToken(client.getClientId(), SECRET, user.getUserName(), SECRET,
            "localhost");

    mockMvc.perform(post("/oauth/token").header("Host", "localhost").accept(MediaType.APPLICATION_JSON)
            .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
            .param(OAuth2Utils.GRANT_TYPE, REFRESH_TOKEN).param(REFRESH_TOKEN, refreshToken)
            .param("client_secret", SECRET).param(OAuth2Utils.CLIENT_ID, clientWithoutRefresh.getClientId()))
            .andExpect(status().isUnauthorized())
            .andExpect(jsonPath("$.error_description").value("Unauthorized grant type: refresh_token"));
}

From source file:org.cloudfoundry.identity.uaa.mock.token.RefreshTokenMockMvcTests.java

MockHttpServletResponse useRefreshToken(String refreshToken, String clientId, String clientSecret, String host)
        throws Exception {
    return mockMvc
            .perform(post("/oauth/token").header("Host", host).accept(MediaType.APPLICATION_JSON)
                    .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
                    .param(OAuth2Utils.GRANT_TYPE, REFRESH_TOKEN).param(REFRESH_TOKEN, refreshToken)
                    .param("client_secret", clientSecret).param(OAuth2Utils.CLIENT_ID, clientId))
            .andReturn().getResponse();/*from w w w.  j  a va 2 s  .c  o m*/
}

From source file:org.cloudfoundry.identity.uaa.mock.token.RefreshTokenMockMvcTests.java

private CompositeToken getTokensWithPasswordGrant(String clientId, String clientSecret, String userName,
        String password, String host, String tokenFormat) throws Exception {
    String response = mockMvc/*from   w ww  .  j  ava 2s  .  c om*/
            .perform(post("/oauth/token").header("Host", host).accept(MediaType.APPLICATION_JSON)
                    .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
                    .param(OAuth2Utils.GRANT_TYPE, GRANT_TYPE_PASSWORD).param("username", userName)
                    .param("password", password).param("client_secret", clientSecret)
                    .param(REQUEST_TOKEN_FORMAT, tokenFormat).param(OAuth2Utils.CLIENT_ID, clientId))
            .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();

    return JsonUtils.readValue(response, CompositeToken.class);
}