Example usage for org.springframework.http HttpStatus FOUND

List of usage examples for org.springframework.http HttpStatus FOUND

Introduction

In this page you can find the example usage for org.springframework.http HttpStatus FOUND.

Prototype

HttpStatus FOUND

To view the source code for org.springframework.http HttpStatus FOUND.

Click Source Link

Document

302 Found .

Usage

From source file:org.awesomeagile.testing.google.FakeGoogleController.java

@ResponseBody
@RequestMapping(method = RequestMethod.GET, path = "/oauth2/auth")
public ResponseEntity<?> authenticate(@RequestParam("client_id") String clientId,
        @RequestParam(value = "client_secret", required = false) String clientSecret,
        @RequestParam("response_type") String responseType, @RequestParam("redirect_uri") String redirectUri,
        @RequestParam("scope") String scope) {
    // Validate client_id and client_secret
    if (!this.clientId.equals(clientId) || (clientSecret != null && !this.clientSecret.equals(clientSecret))) {
        return ResponseEntity.<String>badRequest().body("Wrong client_id or client_secret!");
    }/*from ww w .  j  av  a  2 s  .com*/
    if (!prefixMatches(redirectUri)) {
        return wrongRedirectUriResponse();
    }
    String code = RandomStringUtils.randomAlphanumeric(64);
    String token = RandomStringUtils.randomAlphanumeric(64);
    codeToToken.put(code, new AccessToken(token, scope, "", System.currentTimeMillis() + EXPIRATION_MILLIS));
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(redirectUri).queryParam(CODE, code);
    return ResponseEntity.status(HttpStatus.FOUND).header(HttpHeaders.LOCATION, builder.build().toUriString())
            .build();
}

From source file:org.cloudfoundry.identity.uaa.login.feature.ImplicitGrantIT.java

@Test
public void testDefaultScopes() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>();
    postBody.add("client_id", "cf");
    postBody.add("redirect_uri", "https://uaa.cloudfoundry.com/redirect/cf");
    postBody.add("response_type", "token");
    postBody.add("source", "credentials");
    postBody.add("username", testAccounts.getUserName());
    postBody.add("password", testAccounts.getPassword());

    ResponseEntity<Void> responseEntity = restOperations.exchange(baseUrl + "/oauth/authorize", HttpMethod.POST,
            new HttpEntity<>(postBody, headers), Void.class);

    Assert.assertEquals(HttpStatus.FOUND, responseEntity.getStatusCode());

    UriComponents locationComponents = UriComponentsBuilder.fromUri(responseEntity.getHeaders().getLocation())
            .build();//from   w ww .j av a  2  s.  c o m
    Assert.assertEquals("uaa.cloudfoundry.com", locationComponents.getHost());
    Assert.assertEquals("/redirect/cf", locationComponents.getPath());

    MultiValueMap<String, String> params = parseFragmentParams(locationComponents);

    Assert.assertThat(params.get("jti"), not(empty()));
    Assert.assertEquals("bearer", params.getFirst("token_type"));
    Assert.assertThat(Integer.parseInt(params.getFirst("expires_in")), Matchers.greaterThan(40000));

    String[] scopes = UriUtils.decode(params.getFirst("scope"), "UTF-8").split(" ");
    Assert.assertThat(Arrays.asList(scopes), containsInAnyOrder("scim.userids", "password.write",
            "cloud_controller.write", "openid", "cloud_controller.read"));

    Jwt access_token = JwtHelper.decode(params.getFirst("access_token"));

    Map<String, Object> claims = new ObjectMapper().readValue(access_token.getClaims(),
            new TypeReference<Map<String, Object>>() {
            });

    Assert.assertThat((String) claims.get("jti"), is(params.getFirst("jti")));
    Assert.assertThat((String) claims.get("client_id"), is("cf"));
    Assert.assertThat((String) claims.get("cid"), is("cf"));
    Assert.assertThat((String) claims.get("user_name"), is(testAccounts.getUserName()));

    Assert.assertThat(((List<String>) claims.get("scope")), containsInAnyOrder(scopes));

    Assert.assertThat(((List<String>) claims.get("aud")),
            containsInAnyOrder("cf", "scim", "openid", "cloud_controller", "password"));
}

From source file:comsat.sample.ui.method.SampleMethodSecurityApplicationTests.java

@Test
public void testDenied() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
    MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
    form.set("username", "user");
    form.set("password", "user");
    getCsrf(form, headers);//from   ww  w.  j  av  a2  s .com
    ResponseEntity<String> entity = new TestRestTemplate().exchange("http://localhost:" + this.port + "/login",
            HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(form, headers), String.class);
    assertEquals(HttpStatus.FOUND, entity.getStatusCode());
    String cookie = entity.getHeaders().getFirst("Set-Cookie");
    headers.set("Cookie", cookie);
    ResponseEntity<String> page = new TestRestTemplate().exchange(entity.getHeaders().getLocation(),
            HttpMethod.GET, new HttpEntity<Void>(headers), String.class);
    assertEquals(HttpStatus.FORBIDDEN, page.getStatusCode());
    assertTrue("Wrong body (message doesn't match):\n" + entity.getBody(),
            page.getBody().contains("Access denied"));
}

From source file:org.cloudfoundry.identity.uaa.login.feature.LoginIT.java

@Test
public void testRedirectAfterFailedLogin() throws Exception {
    RestTemplate template = new RestTemplate();
    LinkedMultiValueMap<String, String> body = new LinkedMultiValueMap<>();
    body.add("username", testAccounts.getUserName());
    body.add("password", "invalidpassword");
    ResponseEntity<Void> loginResponse = template.exchange(baseUrl + "/login.do", HttpMethod.POST,
            new HttpEntity<>(body, null), Void.class);
    assertEquals(HttpStatus.FOUND, loginResponse.getStatusCode());
}

From source file:com.work.petclinic.SampleWebUiApplicationTests.java

@Test
public void testCreateUserAndLogin() throws Exception {
    ResponseEntity<String> page = getPage("http://localhost:" + this.port + "/users");

    assertTrue("Client or server error.",
            !page.getStatusCode().is4xxClientError() && !page.getStatusCode().is5xxServerError());

    if (page.getStatusCode() == HttpStatus.FOUND) {
        page = getPage(page.getHeaders().getLocation());
    }//from  w w  w  .j  a  v  a2s  . co m

    String body = page.getBody();
    assertNotNull("Body was null", body);

    String username = "newuser";
    String password = "password";
    String formAction = getFormAction(page);

    MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
    form.set("username", username);
    form.set("email", "newuser@newuser.org");
    form.set("name", "New User");
    form.set("uiPassword", password);
    form.set("verifyPassword", password);
    form.set("_eventId_saveUser", "Create User");
    form.set("_csrf", csrfValue);

    httpHeaders.set("X-CSRF-TOKEN", csrfValue);

    page = postPage(formAction, form);

    if (page.getStatusCode() == HttpStatus.FOUND) {
        page = getPage(page.getHeaders().getLocation());
    }

    assertEquals(HttpStatus.OK, page.getStatusCode());
    body = page.getBody();
    assertNotNull("Body was null", body);
    assertTrue("User not created:\n" + body, body.contains("User " + username + " saved"));

    executeLogin(username, password);
}

From source file:spring.AbstractAuthorizationCodeProviderTests.java

@Test
@OAuth2ContextConfiguration(resource = MyTrustedClient.class, initialize = false)
public void testUserDeniesConfirmation() throws Exception {
    approveAccessTokenGrant("http://anywhere", false);
    String location = null;//from   w ww. jav a 2s . com
    try {
        assertNotNull(context.getAccessToken());
        fail("Expected UserRedirectRequiredException");
    } catch (UserRedirectRequiredException e) {
        location = e.getRedirectUri();
    }
    assertTrue("Wrong location: " + location, location.contains("state="));
    assertTrue(location.startsWith("http://anywhere"));
    assertTrue(location.substring(location.indexOf('?')).contains("error=access_denied"));
    // It was a redirect that triggered our client redirect exception:
    assertEquals(HttpStatus.FOUND, getTokenEndpointResponse().getStatusCode());
}

From source file:plbtw.klmpk.barang.hilang.controller.BarangController.java

@RequestMapping(value = "/find/{id}", method = RequestMethod.GET, produces = "application/json")
public CustomResponseMessage findBarang(@RequestHeader String apiKey, @PathVariable("id") long id) {
    try {/*  w  w w  .  j a v a2  s .c o  m*/
        if (!authApiKey(apiKey)) {
            return new CustomResponseMessage(HttpStatus.FORBIDDEN, "Please use your api key to authentication");
        }
        LogRequest temp = DependencyFactory.createLog(apiKey, "Get");

        if (checkRateLimit(RATE_LIMIT, apiKey)) {
            return new CustomResponseMessage(HttpStatus.BANDWIDTH_LIMIT_EXCEEDED,
                    "Please wait a while, you have reached your rate limit");
        }

        Log log = new Log();
        log.setApiKey(temp.getApiKey());
        log.setStatus(temp.getStatus());
        log.setTimeRequest(temp.getTime_request());
        logService.addLog(log);

        List<Barang> rsBarang = new ArrayList<>();
        Barang barang = barangService.getBarang(id);
        Link selfLink = linkTo(UserController.class).withSelfRel();
        barang.add(selfLink);
        rsBarang.add(barang);
        CustomResponseMessage result = new CustomResponseMessage();
        result.add(linkTo(BarangController.class).withSelfRel());
        result.setHttpStatus(HttpStatus.FOUND);
        result.setMessage("Success");
        result.setResult(rsBarang);
        return result;
    } catch (NullPointerException ex) {
        return new CustomResponseMessage(HttpStatus.NOT_FOUND, "Data not found");
    } catch (Exception ex) {
        return new CustomResponseMessage(HttpStatus.BAD_REQUEST, ex.getMessage());
    }
}

From source file:org.venice.piazza.serviceregistry.controller.messaging.handlers.HandlerLoggingTest.java

@Test
@Ignore/*from   www.java2  s.  c o m*/
public void TestExecuteServiceHandlerMimeTypeErrorLogging() throws InterruptedException {
    String upperServiceDef = "{  \"name\":\"toUpper Params\","
            + "\"description\":\"Service to convert string to uppercase\","
            + "\"url\":\"http://localhost:8082/string/toUpper\"," + "\"method\":\"POST\","
            + "\"params\": [\"aString\"]" +
            /*
             * "\"params\": [\"aString\"]," +
             * "\"mimeType\":\"application/json\"" +
             */
            "}";

    ExecuteServiceData edata = new ExecuteServiceData();

    edata.setServiceId("8");

    HashMap<String, DataType> dataInputs = new HashMap<String, DataType>();
    String istring = "The rain in Spain falls mainly in the plain";
    BodyDataType body = new BodyDataType();
    body.content = istring;
    dataInputs.put("Body", body);
    edata.setDataInputs(dataInputs);

    URI uri = URI.create("http://localhost:8085//string/toUpper");
    when(template.postForEntity(Mockito.eq(uri), Mockito.any(Object.class), Mockito.eq(String.class)))
            .thenReturn(new ResponseEntity<String>("testExecuteService", HttpStatus.FOUND));
    String mimeError = "Body mime type not specified";
    ResponseEntity<String> retVal = esHandler.handle(edata);
    assertTrue(logString.contains("Body mime type not specified"));
}

From source file:com.alehuo.wepas2016projekti.controller.ImageController.java

/**
 * Kuvasta tykkys/*from ww  w. j a  va 2s. co m*/
 *
 * @param a Autentikointi
 * @param imageUuid Kuvan UUID
 * @param redirect Uudelleenohjaus
 * @param req HTTP Request
 * @return Onnistuiko pyynt vai ei (sek sen tyyppi; unlike vai like).
 */
@RequestMapping(value = "/like", method = RequestMethod.POST)
public ResponseEntity<String> likeImage(Authentication a, @RequestParam String imageUuid,
        @RequestParam int redirect, HttpServletRequest req) {
    //Kyttjn autentikoiminen
    UserAccount u = userService.getUserByUsername(a.getName());
    final HttpHeaders h = new HttpHeaders();
    //Jos kyttjtili ei ole tyhj
    if (u != null) {
        //Haetaan kuva
        Image i = imageService.findOneImageByUuid(imageUuid);

        //Jos kuva ei ole tyhj
        if (i != null && i.isVisible()) {
            //Lis / poista tykkys tilanteen mukaan
            if (i.getLikedBy().contains(u)) {
                LOG.log(Level.INFO, "Kayttaja ''{0}'' poisti tykkayksen kuvasta ''{1}''",
                        new Object[] { a.getName(), imageUuid });
                i.removeLike(u);
                imageService.saveImage(i);
                h.add("LikeType", "unlike");
            } else {
                i.addLike(u);
                LOG.log(Level.INFO, "Kayttaja ''{0}'' tykkasi kuvasta ''{1}''",
                        new Object[] { a.getName(), imageUuid });
                imageService.saveImage(i);
                h.add("LikeType", "like");
            }
            //Uudelleenohjaus
            if (redirect == 1) {
                h.add("Location", req.getHeader("Referer"));
                return new ResponseEntity<>(h, HttpStatus.FOUND);
            }
            return new ResponseEntity<>(h, HttpStatus.OK);
        } else {
            //Jos kuvaa ei ole olemassa mutta yritetn silti tykt
            LOG.log(Level.WARNING, "Kayttaja ''{0}'' yritti tykata kuvaa, mita ei ole olemassa. ({1})",
                    new Object[] { a.getName(), imageUuid });
            return new ResponseEntity<>(h, HttpStatus.BAD_REQUEST);
        }
    }
    //Jos ei olla kirjauduttu sisn ja yritetn tykt kuvasta
    LOG.log(Level.WARNING, "Yritettiin tykata kuvaa kirjautumatta sisaan ({0})", a.getName());
    return new ResponseEntity<>(h, HttpStatus.UNAUTHORIZED);
}