Example usage for org.springframework.http HttpHeaders setLocation

List of usage examples for org.springframework.http HttpHeaders setLocation

Introduction

In this page you can find the example usage for org.springframework.http HttpHeaders setLocation.

Prototype

public void setLocation(@Nullable URI location) 

Source Link

Document

Set the (new) location of a resource, as specified by the Location header.

Usage

From source file:org.avidj.zuul.rs.Zuul.java

/**
 * Obtain, upgrade, or downgrade a lock for the given {@code session}. Upgrades and downgrades are
 * possible along two dimensions: type and scope. Lock types are read ({@literal aka.} shared) and
 * write ({@literal aka.} exclusive). Lock scopes are shallow and deep. A shallow lock is only 
 * with respect to the specified lock path, a deep lock also locks the whole subtree below that 
 * path./*from   w w w . j av a2  s  .  co m*/
 * 
 * @param session the session to obtain a lock for 
 * @param type the type of lock to obtain, possible values are ({@code r})ead and 
 *     ({@code w})rite, default is ({@code w})write  
 * @param scope the scope of lock to obtain, possible values are ({@code s})shallow and 
 *     ({@code d})eep, default is ({@code d})eep  
 * @param request the HTTP request, provided by the REST framework
 * @param uriBuilder builder for the result location URI
 * @return {@code true}, iff the operation was successful
 */
@RequestMapping(value = "/s/{id}/**", method = { RequestMethod.POST, RequestMethod.PUT })
public ResponseEntity<String> lock(@PathVariable("id") String session,
        @RequestParam(value = "t", defaultValue = "w") String type,
        @RequestParam(value = "s", defaultValue = "s") String scope, HttpServletRequest request,
        UriComponentsBuilder uriBuilder) {
    // TODO: POST: lock (create resource)
    // TODO: PUT: upscope, downscope, lock reentry (return 226 IM used, return 404 as appropriate)
    final List<String> path = getLockPath(request, session);
    final LockType lockType = getLockType(type);
    final LockScope lockScope = getLockScope(scope);

    final boolean created = lm.lock(session, path, lockType, lockScope);
    HttpStatus httpStatus = created ? HttpStatus.CREATED : HttpStatus.FORBIDDEN;

    UriComponents uriComponents = uriBuilder.path("/s/{id}/{lockPath}").buildAndExpand(session,
            Strings.join("/", path));
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(uriComponents.toUri());
    return new ResponseEntity<String>(headers, httpStatus);
}

From source file:ch.wisv.areafiftylan.users.controller.UserRestController.java

/**
 * This method accepts POST requests on /users. It will send the input to the {@link UserService} to create a new
 * user//w  w w  . j  a  v a2  s  . c o m
 *
 * @param input The user that has to be created. It consists of 3 fields. The username, the email and the plain-text
 *              password. The password is saved hashed using the BCryptPasswordEncoder
 *
 * @return The generated object, in JSON format.
 */
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<?> add(HttpServletRequest request, @Validated @RequestBody UserDTO input) {
    User save = userService.create(input, request);

    // Create headers to set the location of the created User object.
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
            .buildAndExpand(save.getId()).toUri());

    return createResponseEntity(HttpStatus.CREATED, httpHeaders,
            "User successfully created at " + httpHeaders.getLocation(), save);
}

From source file:org.zalando.riptide.ActionsTest.java

@Test
public void shouldNormalizeLocation() {
    final HttpHeaders headers = new HttpHeaders();
    headers.setLocation(URI.create("/accounts/456"));
    server.expect(requestTo(url)).andRespond(withSuccess().headers(headers));

    final URI location = unit.execute(GET, url)
            .dispatch(series(), on(SUCCESSFUL).map(normalize(url).andThen(location())).capture()).to(URI.class);

    assertThat(location, hasToString("https://api.example.com/accounts/456"));
}

From source file:org.zalando.riptide.ActionsTest.java

@Test
public void shouldMapLocation() {
    final HttpHeaders headers = new HttpHeaders();
    headers.setLocation(URI.create("http://example.org"));

    server.expect(requestTo(url)).andRespond(withSuccess().headers(headers));

    final URI uri = unit.execute(HEAD, url)
            .dispatch(status(), on(OK).capture(location()), anyStatus().call(this::fail)).to(URI.class);

    assertThat(uri, hasToString("http://example.org"));
}

From source file:org.zalando.riptide.ActionsTest.java

@Test
public void shouldNormalizeLocationAndContentLocation() {
    final HttpHeaders headers = new HttpHeaders();
    headers.setLocation(URI.create("/accounts/456"));
    headers.set(CONTENT_LOCATION, "/accounts/456");
    server.expect(requestTo(url)).andRespond(withSuccess().headers(headers));

    final ClientHttpResponse response = unit.execute(GET, url)
            .dispatch(series(), on(SUCCESSFUL).map(normalize(url)).capture()).to(ClientHttpResponse.class);

    assertThat(response.getHeaders().getLocation(), hasToString("https://api.example.com/accounts/456"));
    assertThat(response.getHeaders().getFirst(CONTENT_LOCATION), is("https://api.example.com/accounts/456"));
}

From source file:io.github.howiefh.jeews.modules.oauth2.controller.ClientController.java

@RequiresPermissions("clients:create")
@RequestMapping(value = "", method = RequestMethod.POST)
public ResponseEntity<ClientResource> create(HttpEntity<Client> entity, HttpServletRequest request)
        throws URISyntaxException {
    Client Client = entity.getBody();/*from   w  ww .  ja  v  a 2 s  .  c  o m*/
    clientService.save(Client);
    HttpHeaders headers = new HttpHeaders();
    ClientResource ClientResource = new ClientResourceAssembler().toResource(Client);
    headers.setLocation(entityLinks.linkForSingleResource(Client.class, Client.getId()).toUri());
    ResponseEntity<ClientResource> responseEntity = new ResponseEntity<ClientResource>(ClientResource, headers,
            HttpStatus.CREATED);
    return responseEntity;
}

From source file:net.eusashead.hateoas.response.argumentresolver.AsyncEntityControllerITCase.java

@Test
public void testPost() throws Exception {

    // Expected result
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(new URI("/path/to/foo"));
    ResponseEntity<Entity> expectedResult = new ResponseEntity<Entity>(headers, HttpStatus.CREATED);

    // Execute asynchronously
    MvcResult mvcResult = this.mockMvc
            .perform(post("http://localhost/async/foo").content(mapper.writeValueAsBytes(new Entity("foo")))
                    .contentType(MediaType.APPLICATION_JSON)
                    .characterEncoding(Charset.forName("UTF-8").toString()).accept(MediaType.APPLICATION_JSON))
            .andExpect(request().asyncStarted()).andExpect(request().asyncResult(expectedResult)).andReturn();

    // Perform asynchronous dispatch
    this.mockMvc.perform(asyncDispatch(mvcResult)).andDo(print()).andExpect(status().isCreated())
            .andExpect(header().string("Location", "/path/to/foo")).andExpect(status().isCreated());

}

From source file:io.github.howiefh.jeews.modules.sys.controller.OrganizationController.java

@RequiresPermissions("organization:create")
@RequestMapping(value = "", method = RequestMethod.POST)
public ResponseEntity<OrganizationResource> create(HttpEntity<Organization> entity, HttpServletRequest request)
        throws URISyntaxException {
    Organization organization = entity.getBody();
    organizationService.save(organization);
    HttpHeaders headers = new HttpHeaders();
    OrganizationResource organizationResource = new OrganizationResourceAssembler().toResource(organization);
    headers.setLocation(entityLinks.linkForSingleResource(Organization.class, organization.getId()).toUri());
    ResponseEntity<OrganizationResource> responseEntity = new ResponseEntity<OrganizationResource>(
            organizationResource, headers, HttpStatus.CREATED);
    return responseEntity;
}

From source file:com.baidu.stqa.signet.web.action.BaseAction.java

public HttpHeaders setLocationHeaders(String location) {
    HttpHeaders headers = new HttpHeaders();

    if (StringUtils.isNotBlank(location)) {
        URI uri = UriComponentsBuilder.fromPath(location).build().toUri();
        headers.setLocation(uri);
    }/*from   w ww  .  j ava2s  .  c  om*/
    return headers;
}

From source file:eu.supersede.dm.rest.RequirementRest.java

/**
 * Create a new requirement.//w w w .  ja va2s .c  o m
 * 
 * @param r
 */
@RequestMapping(value = "", method = RequestMethod.POST)
public ResponseEntity<?> createRequirement(@RequestBody Requirement r) {
    r.setRequirementId(null);
    DMGame.get().getJpa().requirements.save(r);

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
            .buildAndExpand(r.getRequirementId()).toUri());
    return new ResponseEntity<>(null, httpHeaders, HttpStatus.CREATED);
}