Java Code Examples for org.springframework.http.HttpHeaders#setLocation()

The following examples show how to use org.springframework.http.HttpHeaders#setLocation() . 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: ClusterRestController.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * Create cluster configuration.
 *
 * @param cluster contains the cluster information to create
 * @return The created cluster
 * @throws IdAlreadyExistsException If there is a conflict for the id
 */
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<Void> createCluster(
    @RequestBody @Valid final Cluster cluster
) throws IdAlreadyExistsException {
    log.info("[createCluster] Called to create new cluster {}", cluster);
    final String id = this.persistenceService.saveCluster(DtoConverters.toV4ClusterRequest(cluster));
    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(
        ServletUriComponentsBuilder
            .fromCurrentRequest()
            .path("/{id}")
            .buildAndExpand(id)
            .toUri()
    );
    return new ResponseEntity<>(httpHeaders, HttpStatus.CREATED);
}
 
Example 2
Source File: PortfolioController.java    From cf-SpringBootTrader with Apache License 2.0 6 votes vote down vote up
/**
 * Adds an order to the portfolio of the given account.
 * 
 * @param accountId the account to add the order to.
 * @param order The order to add.
 * @param builder
 * @return The order with HTTP CREATED or BAD REQUEST if it couldn't save.
 */
@RequestMapping(value = "/portfolio/{id}", method = RequestMethod.POST)
public ResponseEntity<Order> addOrder(@PathVariable("id") final String accountId, @RequestBody final Order order, UriComponentsBuilder builder) {
	logger.debug("Adding Order: " + order);
	
	//TODO: can do a test to ensure accountId == order.getAccountId();
	
	Order savedOrder = service.addOrder(order);
	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.setLocation(builder.path("/portfolio/{id}")
			.buildAndExpand(accountId).toUri());
	logger.debug("Order added: " + savedOrder);
	if (savedOrder != null && savedOrder.getOrderId() != null) {
		return new ResponseEntity<Order>(savedOrder, responseHeaders, HttpStatus.CREATED);
	} else {
		logger.warn("Order not saved: " + order);
		return new ResponseEntity<Order>(savedOrder, responseHeaders, HttpStatus.INTERNAL_SERVER_ERROR);
	}
}
 
Example 3
Source File: PostController.java    From angularjs-springmvc-sample-boot with Apache License 2.0 6 votes vote down vote up
@PostMapping()
@ApiOperation(nickname = "create-post", value = "Cretae a new post")
public ResponseEntity<Void> createPost(@RequestBody @Valid PostForm post, HttpServletRequest request) {

    log.debug("create a new post@" + post);

    PostDetails saved = blogService.savePost(post);

    log.debug("saved post id is @" + saved.getId());
    URI loacationHeader = ServletUriComponentsBuilder
            .fromContextPath(request)
            .path("/api/posts/{id}")
            .buildAndExpand(saved.getId())
            .toUri();

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

    return new ResponseEntity<>(headers, HttpStatus.CREATED);
}
 
Example 4
Source File: OrderController.java    From atsea-sample-shop-app with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@RequestMapping(value = "/order/", method = RequestMethod.POST)
public ResponseEntity<?> createOrder(@RequestBody Order order, UriComponentsBuilder ucBuilder) {
	logger.info("Creating order : {}", order);

	if (orderService.orderExists(order)) {
		logger.error("Unable to create. An order with id {} already exist", order.getOrderId());
		return new ResponseEntity(new CustomErrorType("Unable to create. An order with id " + 
		order.getOrderId() + " already exists."),HttpStatus.CONFLICT);
	}
			
	Order currentOrder = orderService.createOrder(order);
	Long currentOrderId = currentOrder.getOrderId();
	JSONObject orderInfo = new JSONObject();
	orderInfo.put("orderId", currentOrderId);

	HttpHeaders headers = new HttpHeaders();
	headers.setLocation(ucBuilder.path("/api/order/").buildAndExpand(order.getOrderId()).toUri());
	return new ResponseEntity<JSONObject>(orderInfo, HttpStatus.CREATED);
}
 
Example 5
Source File: FooBarController.java    From tutorials with MIT License 6 votes vote down vote up
@Operation(summary = "Create a foo")
@ApiResponses(value = {
        @ApiResponse(responseCode = "201", description = "foo created", content = { @
                Content(mediaType = "application/json", schema = @Schema(implementation = Foo.class))}),
        @ApiResponse(responseCode = "404", description = "Bad request", content = @Content) })
@PostMapping
public ResponseEntity<Foo> addFoo(@Parameter(description = "foo object to be created") @RequestBody @Valid Foo foo) {
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(linkTo(FooBarController.class).slash(foo.getId()).toUri());
    Foo savedFoo;
    try {
        savedFoo = repository.save(foo);
    } catch (Exception e) {
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

    return new ResponseEntity<>(savedFoo, httpHeaders, HttpStatus.CREATED);
}
 
Example 6
Source File: SpittleApiController.java    From Project with Apache License 2.0 6 votes vote down vote up
@RequestMapping(method=RequestMethod.POST, consumes="application/json")
//  @ResponseStatus(HttpStatus.CREATED)
  public ResponseEntity<Spittle> saveSpittle(@RequestBody Spittle spittle, UriComponentsBuilder ucb) {
    Spittle saved = spittleRepository.save(spittle);
    
    HttpHeaders headers = new HttpHeaders();
    URI locationUri = ucb.path("/spittles/")
        .path(String.valueOf(saved.getId()))
        .build()
        .toUri();
    headers.setLocation(locationUri);//设置location头部信息
    
    /*
     * ResponseEntity中可以包含响应相关的元数据(如头部信息和状态码)以及要转换成资源表述的对象,
     * 还包含了ResponseBody的语义
     */
    ResponseEntity<Spittle> responseEntity = new ResponseEntity<Spittle>(saved, headers, HttpStatus.CREATED);
    return responseEntity;
  }
 
Example 7
Source File: UserController.java    From java-starthere with MIT License 6 votes vote down vote up
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
@PostMapping(value = "/user",
             consumes = {"application/json"},
             produces = {"application/json"})
public ResponseEntity<?> addNewUser(HttpServletRequest request,
                                    @Valid
                                    @RequestBody
                                            User newuser) throws URISyntaxException
{
    logger.trace(request.getMethod()
                        .toUpperCase() + " " + request.getRequestURI() + " accessed");

    newuser = userService.save(newuser);

    // set the location header for the newly created resource
    HttpHeaders responseHeaders = new HttpHeaders();
    URI newUserURI = ServletUriComponentsBuilder.fromCurrentRequest()
                                                .path("/{userid}")
                                                .buildAndExpand(newuser.getUserid())
                                                .toUri();
    responseHeaders.setLocation(newUserURI);

    return new ResponseEntity<>(null,
                                responseHeaders,
                                HttpStatus.CREATED);
}
 
Example 8
Source File: UserRestController.java    From jeecg with Apache License 2.0 6 votes vote down vote up
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
@ApiOperation(value="创建用户信息")
public ResponseEntity<?> create(@ApiParam(name="用户对象")@RequestBody TSUser user, UriComponentsBuilder uriBuilder) {
	//调用JSR303 Bean Validator进行校验,如果出错返回含400错误码及json格式的错误信息.
	Set<ConstraintViolation<TSUser>> failures = validator.validate(user);
	if (!failures.isEmpty()) {
		return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
	}

	//保存用户
	userService.save(user);

	//按照Restful风格约定,创建指向新任务的url, 也可以直接返回id或对象.
	String id = user.getId();
	URI uri = uriBuilder.path("/rest/user/" + id).build().toUri();
	HttpHeaders headers = new HttpHeaders();
	headers.setLocation(uri);

	return new ResponseEntity(headers, HttpStatus.CREATED);
}
 
Example 9
Source File: ResponseHeadersHelper.java    From bonita-ui-designer with GNU General Public License v2.0 6 votes vote down vote up
public static ResponseEntity<Void> getMovedResourceResponse(HttpServletRequest request, String newObjectId, String currentURIAttributeSuffix) throws RepositoryException {
    HttpHeaders responseHeaders = new HttpHeaders();
    try {
        String currentURI = request.getRequestURI();
        String requestURI;
        if (currentURIAttributeSuffix != null && currentURI.lastIndexOf(currentURIAttributeSuffix) >= 0) {
            int indexOfSuffix = currentURI.lastIndexOf(currentURIAttributeSuffix);
            requestURI = currentURI.substring(0, indexOfSuffix);
        } else {
            requestURI = currentURI;
        }
        int currentURILastSeparatorIndex = requestURI.lastIndexOf("/");
        URI newLocation = new URI(requestURI.substring(0, currentURILastSeparatorIndex) + "/" + newObjectId);
        responseHeaders.setLocation(newLocation);
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
    } catch (URISyntaxException e) {
        throw new RepositoryException("Failed to generate new object URI", e);
    }
    return new ResponseEntity<>(responseHeaders, HttpStatus.OK);
}
 
Example 10
Source File: BookController.java    From springboot-learning-example with Apache License 2.0 6 votes vote down vote up
/**
 * 创建 Book
 * 处理 "/book/create" 的 POST 请求,用来新建 Book 信息
 * 通过 @RequestBody 绑定实体参数,也通过 @RequestParam 传递参数
 */
@RequestMapping(value = "/create", method = RequestMethod.POST)
public ResponseEntity<Void> postBook(@RequestBody Book book, UriComponentsBuilder ucBuilder) {

    LOG.info("creating new book: {}", book);

    if (book.getName().equals("conflict")){
        LOG.info("a book with name " + book.getName() + " already exists");
        return new ResponseEntity<>(HttpStatus.CONFLICT);
    }

    bookService.insertByBook(book);

    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(ucBuilder.path("/book/{id}").buildAndExpand(book.getId()).toUri());
    return new ResponseEntity<>(headers, HttpStatus.CREATED);
}
 
Example 11
Source File: RestTemplateTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void postForLocationEntityContentType() throws Exception {
	mockSentRequest(POST, "https://example.com");
	mockTextPlainHttpMessageConverter();
	mockResponseStatus(HttpStatus.OK);

	String helloWorld = "Hello World";
	HttpHeaders responseHeaders = new HttpHeaders();
	URI expected = new URI("https://example.com/hotels");
	responseHeaders.setLocation(expected);
	given(response.getHeaders()).willReturn(responseHeaders);

	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.setContentType(MediaType.TEXT_PLAIN);
	HttpEntity<String> entity = new HttpEntity<>(helloWorld, entityHeaders);

	URI result = template.postForLocation("https://example.com", entity);
	assertEquals("Invalid POST result", expected, result);

	verify(response).close();
}
 
Example 12
Source File: RestTemplateTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void postForLocation() throws Exception {
	mockSentRequest(POST, "https://example.com");
	mockTextPlainHttpMessageConverter();
	mockResponseStatus(HttpStatus.OK);
	String helloWorld = "Hello World";
	HttpHeaders responseHeaders = new HttpHeaders();
	URI expected = new URI("https://example.com/hotels");
	responseHeaders.setLocation(expected);
	given(response.getHeaders()).willReturn(responseHeaders);

	URI result = template.postForLocation("https://example.com", helloWorld);
	assertEquals("Invalid POST result", expected, result);

	verify(response).close();
}
 
Example 13
Source File: RequestPartIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@RequestMapping(value = "/test", method = POST, consumes = {"multipart/mixed", "multipart/form-data"})
public ResponseEntity<Object> create(@RequestPart(name = "json-data") TestData testData,
		@RequestPart("file-data") Optional<MultipartFile> file,
		@RequestPart(name = "empty-data", required = false) TestData emptyData,
		@RequestPart(name = "iso-8859-1-data") byte[] iso88591Data) {

	Assert.assertArrayEquals(new byte[]{(byte) 0xC4}, iso88591Data);

	String url = "http://localhost:8080/test/" + testData.getName() + "/" + file.get().getOriginalFilename();
	HttpHeaders headers = new HttpHeaders();
	headers.setLocation(URI.create(url));
	return new ResponseEntity<>(headers, HttpStatus.CREATED);
}
 
Example 14
Source File: JLineupController.java    From jlineup with Apache License 2.0 5 votes vote down vote up
@PostMapping("/runs/{runId}")
public ResponseEntity<Void> runAfter(@PathVariable String runId, HttpServletRequest request) throws Exception {
    jLineupService.startAfterRun(runId);

    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(URI.create(request.getContextPath() + "/runs/" + runId));
    return new ResponseEntity<>(headers, HttpStatus.ACCEPTED);
}
 
Example 15
Source File: FeatureServiceImpl.java    From pazuzu-registry with MIT License 5 votes vote down vote up
@RolesAllowed({Roles.USER})
public ResponseEntity<Feature> featuresPost(Feature feature) {
    if (feature.getMeta() == null)
        feature.setMeta(new FeatureMeta());
    ServletUriComponentsBuilder servletUriComponentsBuilder = ServletUriComponentsBuilder.fromCurrentContextPath();
    Feature newFeature = featureService.createFeature(
            feature.getMeta().getName(), feature.getMeta().getDescription(), getAuthenticatedUserName(),
            feature.getSnippet(), feature.getTestSnippet(), feature.getMeta().getDependencies(), FeatureConverter::asDto);
    URI uri = servletUriComponentsBuilder.path("/api/features/{featureName}").buildAndExpand(newFeature.getMeta().getName()).toUri();
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON.toString());
    responseHeaders.setLocation(uri);
    return new ResponseEntity<>(newFeature, responseHeaders, HttpStatus.CREATED);
}
 
Example 16
Source File: UserController.java    From pivotal-bank-demo with Apache License 2.0 5 votes vote down vote up
/**
 * REST call to save the user provided in the request body.
 * 
 * @param userRequest
 *            The user to save.
 * @param builder
 * @return
 */
@RequestMapping(value = "/users", method = RequestMethod.POST)
public ResponseEntity<String> save(@RequestBody User userRequest, UriComponentsBuilder builder) {

	logger.debug("UserController.save: userId=" + userRequest.getUserid());

	Integer accountProfileId = this.service.saveUser(userRequest);
	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.setLocation(builder.path("/users/{id}").buildAndExpand(accountProfileId).toUri());
	return new ResponseEntity<String>(responseHeaders, HttpStatus.CREATED);
}
 
Example 17
Source File: UserController.java    From OpenLRW with Educational Community License v2.0 5 votes vote down vote up
/**
 * POST /api/users
 *
 * Inserts a user into the DBMS (MongoDB).
 * @param token  JWT
 * @param user   user to insert
 * @param check  boolean to know if it has to check duplicates (takes more time)
 * @return       HTTP Response
 */
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<?> post(JwtAuthenticationToken token, @RequestBody User user, @RequestParam(value="check", required=false) Boolean check) {
  UserContext userContext = (UserContext) token.getPrincipal();
  User savedUser = this.userService.save(userContext.getTenantId(), userContext.getOrgId(), user, (check == null) ? true : check);
  HttpHeaders httpHeaders = new HttpHeaders();
  httpHeaders.setLocation(ServletUriComponentsBuilder
          .fromCurrentRequest().path("/{id}")
          .buildAndExpand(savedUser.getSourcedId()).toUri());

  return new ResponseEntity<>(savedUser, httpHeaders, HttpStatus.CREATED);
}
 
Example 18
Source File: FooController.java    From friendly-id with Apache License 2.0 5 votes vote down vote up
@PostMapping
public HttpEntity<FooResource> create(@RequestBody FooResource fooResource) {
	HttpHeaders headers = new HttpHeaders();
	Foo entity = new Foo(fooResource.getUuid(), "Foo");

	// ...

	headers.setLocation(entityLinks.linkToItemResource(FooResource.class, FriendlyId.toFriendlyId(entity.getId())).toUri());
	return new ResponseEntity<>(headers, HttpStatus.CREATED);
}
 
Example 19
Source File: ClassController.java    From OpenLRW with Educational Community License v2.0 5 votes vote down vote up
@RequestMapping(value= "/{classId:.+}/lineitems", method = RequestMethod.POST)
public ResponseEntity<?> postLineItem(JwtAuthenticationToken token, @RequestBody LineItem lineItem, @RequestParam(value="check", required=false) Boolean check) {
  UserContext userContext = (UserContext) token.getPrincipal();
  LineItem savedLineItem = this.lineItemService.save(userContext.getTenantId(), userContext.getOrgId(), lineItem, (check == null) ? true : check);
  HttpHeaders httpHeaders = new HttpHeaders();
  httpHeaders.setLocation(ServletUriComponentsBuilder
      .fromCurrentRequest().path("/{id}")
      .buildAndExpand(savedLineItem.getSourcedId()).toUri());
  return new ResponseEntity<>(savedLineItem, httpHeaders, HttpStatus.CREATED);
}
 
Example 20
Source File: IngredientController.java    From spring-in-action-5-samples with Apache License 2.0 5 votes vote down vote up
@PostMapping
public ResponseEntity<Ingredient> postIngredient(@RequestBody Ingredient ingredient) {
  Ingredient saved = repo.save(ingredient);
  HttpHeaders headers = new HttpHeaders();
  headers.setLocation(URI.create("http://localhost:8080/ingredients/" + ingredient.getId()));
  return new ResponseEntity<>(saved, headers, HttpStatus.CREATED);
}