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:com.itn.webservices.AdminControllerWebservice.java

@RequestMapping(value = "/food", method = RequestMethod.POST)
public ResponseEntity<Void> createFood(@RequestBody FoodInventory food, UriComponentsBuilder ucBuilder) {
    logger.info("Creating Food " + food.getFoodName());

    if (foodInventoryService.isFoodExist(food)) {
        logger.info("A Food already exist");
        return new ResponseEntity<Void>(HttpStatus.CONFLICT);
    }//from  w  ww  . ja va 2s . co  m

    foodInventoryService.save(food);

    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(ucBuilder.path("/food/{id}").buildAndExpand(food.getId()).toUri());
    return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}

From source file:com.nebhale.springone2014.web.GamesController.java

@RequestMapping(method = RequestMethod.POST, value = "")
// TODO 2: CREATED Status Code
@ResponseStatus(HttpStatus.CREATED)/*w  w  w  . j ava  2  s  .  c om*/
HttpHeaders createGame() {
    Game game = this.gameRepository.create();

    HttpHeaders headers = new HttpHeaders();
    // TODO 1: Location: /games/{gameId}
    headers.setLocation(linkTo(GamesController.class).slash(game.getId()).toUri());

    return headers;
}

From source file:com.nebhale.cyclinglibrary.web.PointController.java

@RequestMapping(method = RequestMethod.GET, produces = ApplicationMediaType.POINTS_PNG_VALUE)
@ResponseBody/*ww  w.j  av  a 2  s .  c  o  m*/
ResponseEntity<Void> read(@PathVariable Long itemId,
        @RequestParam(value = "maptype", defaultValue = "roadmap") String mapType,
        @RequestParam(defaultValue = "250") Integer width, @RequestParam(defaultValue = "250") Integer height,
        @Value("#{request.getRemoteAddr()}") String userIp) {

    Item item = this.itemRepository.read(itemId);

    URI uri = UriComponentsBuilder.newInstance() //
            .scheme("http") //
            .host("maps.googleapis.com") //
            .path("/maps/api/staticmap") //
            .queryParam("key", this.apiKey) //
            .queryParam("sensor", false) //
            .queryParam("userIp", userIp) //
            .queryParam("size", String.format("%dx%d", width, height)) //
            .queryParam("maptype", mapType) //
            .queryParam("scale", 2) //
            .queryParam("path",
                    String.format("color:0xff0000ff|weight:2|%s",
                            this.polylineEncoder.encodeSingle(MAX_ENCODED_LENGTH, item.getPoints()))) //
            .build().toUri();

    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(uri);

    return new ResponseEntity<>(headers, HttpStatus.SEE_OTHER);
}

From source file:web.ClientsRESTController.java

/**
 * Adds a client to the database through a REST API
 * @param client/*from  ww  w  .ja  va  2 s.c  o m*/
 * @param ucBuilder
 * @return
 */
@RequestMapping(value = "/api/clients/", method = RequestMethod.POST)
public ResponseEntity<Void> addClient(@RequestBody Clients client, UriComponentsBuilder ucBuilder) {
    dao.addClient(client);
    //returns newly added Client info
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(
            ucBuilder.path("/api/clients/clientinfo/{id}").buildAndExpand(client.getClientid()).toUri());
    return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}

From source file:su90.mybatisdemo.web.endpoints.EmployeesEndpoints.java

@RequestMapping(value = "/set/", method = RequestMethod.POST, consumes = {
        MediaType.APPLICATION_JSON_UTF8_VALUE }, produces = { MediaType.TEXT_PLAIN_VALUE })
@ApiOperation(value = "create one employee if possible")
public ResponseEntity<Void> createEmployee(@RequestBody EmployeeIn employeeIn) {
    if (employeeIn.email == null) {
        return new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE);
    }//from   w  ww.  j  a va 2 s  .co  m
    if (employeesService.hasEntityWithEmail(employeeIn.email)) {
        return new ResponseEntity<>(HttpStatus.CONFLICT);
    }

    if (employeeIn.job_id != null && jobsService.getEntryById(employeeIn.job_id) == null) {
        return new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE);
    }

    if (employeeIn.manager_id != null && employeesService.getEntryById(employeeIn.manager_id) == null) {
        return new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE);
    }

    if (employeeIn.department_id != null && departmentsService.getEntryById(employeeIn.department_id) == null) {
        return new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE);
    }

    Long thekey = employeesService.saveEntry(employeeIn.getDomain());

    if (thekey != null) {
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(
                UriUtils.generateUri(MvcUriComponentsBuilder.on(EmployeesEndpoints.class).getOne(thekey)));
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    } else {
        return new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE);
    }

}

From source file:com.tamnd2.basicwebapp.rest.mvc.AccountController.java

@RequestMapping(value = "/{accountId}/blogs", method = RequestMethod.POST)
@PreAuthorize("permitAll")
public ResponseEntity<BlogResource> createBlog(@PathVariable Long accountId, @RequestBody BlogResource res) {
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    if (principal instanceof UserDetails) {
        UserDetails details = (UserDetails) principal;
        Account loggedIn = accountService.findByAccountName(details.getUsername());
        if (loggedIn.getId().equals(accountId)) {
            try {
                Blog createdBlog = accountService.createBlog(accountId, res.toBlog());
                BlogResource createdBlogRes = new BlogResourceAsm().toResource(createdBlog);
                HttpHeaders headers = new HttpHeaders();
                headers.setLocation(URI.create(createdBlogRes.getLink("self").getHref()));
                return new ResponseEntity<BlogResource>(createdBlogRes, headers, HttpStatus.CREATED);
            } catch (AccountDoesNotExistException exception) {
                throw new NotFoundException(exception);
            } catch (BlogExistException exception) {
                throw new ConflictException(exception);
            }//w  w w  . j a v  a  2  s  .c  om
        } else {
            throw new ForbiddenException();
        }
    } else {
        throw new ForbiddenException();
    }
}

From source file:com.gazbert.bxbot.rest.api.StrategyConfigController.java

/**
 * Creates a new Strategy configuration.
 *
 * @param user the authenticated user.// w  w  w  .j a  v a 2 s . c om
 * @param strategyId id of the Strategy config to create.
 * @param config the new Strategy config.
 * @return 201 'Created' HTTP status code if create successful, 409 'Conflict' HTTP status code if Strategy config already exists.
 */
@RequestMapping(value = "/strategy/{strategyId}", method = RequestMethod.POST)
ResponseEntity<?> createStrategy(@AuthenticationPrincipal User user, @PathVariable String strategyId,
        @RequestBody StrategyConfig config) {

    if (config == null || config.getId() == null || !strategyId.equals(config.getId())) {
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

    final StrategyConfig createdConfig = strategyConfigService.createStrategy(config);
    if (createdConfig.getId() != null) {
        final HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/{strategyId}")
                .buildAndExpand(createdConfig.getId()).toUri());
        return new ResponseEntity<>(null, httpHeaders, HttpStatus.CREATED);

    } else {
        return new ResponseEntity<>(HttpStatus.CONFLICT);
    }
}

From source file:com.haulmont.restapi.controllers.FileUploadController.java

protected ResponseEntity<FileInfo> createFileInfoResponseEntity(HttpServletRequest request, FileDescriptor fd) {
    FileInfo fileInfo = new FileInfo(fd.getId(), fd.getName(), fd.getSize());

    UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(request.getRequestURL().toString())
            .path("/{id}").buildAndExpand(fd.getId().toString());

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(uriComponents.toUri());
    return new ResponseEntity<>(fileInfo, httpHeaders, HttpStatus.CREATED);
}

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

/**
 * Release the given lock if it is held by the given {@code session}.
 * @param session the session id to release the lock for
 * @param request the request//from  ww  w. ja v a  2 s . c o  m
 * @param uriBuilder a builder for the response location header URI
 * @return {@code true}, iff the lock was released
 */
@RequestMapping(value = "/s/{id}/**", method = RequestMethod.DELETE)
public ResponseEntity<String> release(@PathVariable("id") String session, HttpServletRequest request,
        UriComponentsBuilder uriBuilder) {
    final List<String> path = getLockPath(request, session);

    final boolean deleted = lm.release(session, path);
    HttpStatus httpStatus = deleted ? HttpStatus.NO_CONTENT : 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:io.github.howiefh.jeews.modules.sys.controller.RoleController.java

@RequiresPermissions("role:create")
@RequestMapping(value = "", method = RequestMethod.POST)
public ResponseEntity<RoleResource> create(HttpEntity<Role> entity, HttpServletRequest request)
        throws URISyntaxException {
    Role role = entity.getBody();
    roleService.save(role);//from  w ww .java 2s . co  m
    HttpHeaders headers = new HttpHeaders();
    RoleResource roleResource = new RoleResourceAssembler().toResource(role);
    headers.setLocation(entityLinks.linkForSingleResource(Role.class, role.getId()).toUri());
    ResponseEntity<RoleResource> responseEntity = new ResponseEntity<RoleResource>(roleResource, headers,
            HttpStatus.CREATED);
    return responseEntity;
}