org.springframework.web.servlet.support.ServletUriComponentsBuilder Java Examples

The following examples show how to use org.springframework.web.servlet.support.ServletUriComponentsBuilder. 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: TodoJpaResource.java    From docker-crash-course with MIT License 7 votes vote down vote up
@PostMapping("/jpa/users/{username}/todos")
public ResponseEntity<Void> createTodo(
		@PathVariable String username, @RequestBody Todo todo){
	
	todo.setUsername(username);
	
	Todo createdTodo = todoJpaRepository.save(todo);
	
	//Location
	//Get current resource url
	///{id}
	URI uri = ServletUriComponentsBuilder.fromCurrentRequest()
			.path("/{id}").buildAndExpand(createdTodo.getId()).toUri();
	
	return ResponseEntity.created(uri).build();
}
 
Example #2
Source File: TodoJpaResource.java    From pcf-crash-course-with-spring-boot with MIT License 7 votes vote down vote up
@PostMapping("/jpa/users/{username}/todos")
public ResponseEntity<Void> createTodo(
		@PathVariable String username, @RequestBody Todo todo){
	
	todo.setUsername(username);
	
	Todo createdTodo = todoJpaRepository.save(todo);
	
	//Location
	//Get current resource url
	///{id}
	URI uri = ServletUriComponentsBuilder.fromCurrentRequest()
			.path("/{id}").buildAndExpand(createdTodo.getId()).toUri();
	
	return ResponseEntity.created(uri).build();
}
 
Example #3
Source File: UserSearchController.java    From wallride with Apache License 2.0 7 votes vote down vote up
@RequestMapping(method = RequestMethod.GET)
public String search(
		@PathVariable String language,
		@Validated @ModelAttribute("form") UserSearchForm form,
		BindingResult result,
		@PageableDefault(50) Pageable pageable,
		Model model,
		HttpServletRequest servletRequest) throws UnsupportedEncodingException {
	Page<User> users = userService.getUsers(form.toUserSearchRequest(), pageable);

	model.addAttribute("users", users);
	model.addAttribute("pageable", pageable);
	model.addAttribute("pagination", new Pagination<>(users, servletRequest));

	UriComponents uriComponents = ServletUriComponentsBuilder
			.fromRequest(servletRequest)
			.queryParams(ControllerUtils.convertBeanForQueryParams(form, conversionService))
			.build();
	if (!StringUtils.isEmpty(uriComponents.getQuery())) {
		model.addAttribute("query", URLDecoder.decode(uriComponents.getQuery(), "UTF-8"));
	}

	return "user/index";
}
 
Example #4
Source File: CorsFilter.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private boolean isOriginWhitelisted( HttpServletRequest request, String origin )
{
    HttpServletRequestEncodingWrapper encodingWrapper = new HttpServletRequestEncodingWrapper( request );
    UriComponentsBuilder uriBuilder = ServletUriComponentsBuilder.fromContextPath( encodingWrapper ).replacePath( "" );

    String forwardedProto = request.getHeader( "X-Forwarded-Proto" );

    if ( !StringUtils.isEmpty( forwardedProto ) )
    {
        uriBuilder.scheme( forwardedProto );
    }

    String localUrl = uriBuilder.build().toString();

    return !StringUtils.isEmpty( origin ) && (localUrl.equals( origin ) ||
        configurationService.isCorsWhitelisted( origin ));
}
 
Example #5
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 #6
Source File: CustomFieldSearchController.java    From wallride with Apache License 2.0 6 votes vote down vote up
@RequestMapping(method = RequestMethod.GET)
public String search(
        @PathVariable String language,
        @Validated @ModelAttribute("form") CustomFieldSearchForm form,
        BindingResult result,
        @PageableDefault(50) Pageable pageable,
        Model model,
        HttpServletRequest servletRequest) throws UnsupportedEncodingException {
    Page<CustomField> customFields = customfieldService.getCustomFields(form.toCustomFieldSearchRequest(), pageable);

    model.addAttribute("customFields", customFields);
    model.addAttribute("pageable", pageable);
    model.addAttribute("pagination", new Pagination<>(customFields, servletRequest));

    UriComponents uriComponents = ServletUriComponentsBuilder
            .fromRequest(servletRequest)
            .queryParams(ControllerUtils.convertBeanForQueryParams(form, conversionService))
            .build();
    if (!StringUtils.isEmpty(uriComponents.getQuery())) {
        model.addAttribute("query", URLDecoder.decode(uriComponents.getQuery(), "UTF-8"));
    }

    return "customfield/index";
}
 
Example #7
Source File: PageSearchController.java    From wallride with Apache License 2.0 6 votes vote down vote up
@RequestMapping(method = RequestMethod.GET)
public String search(
		@PathVariable String language,
		@Validated @ModelAttribute("form") PageSearchForm form,
		BindingResult result,
		@PageableDefault(50) Pageable pageable,
		Model model,
		HttpServletRequest servletRequest) throws UnsupportedEncodingException {
	org.springframework.data.domain.Page<Page> pages = pageService.getPages(form.toPageSearchRequest(), pageable);

	model.addAttribute("pages", pages);
	model.addAttribute("pageable", pageable);
	model.addAttribute("pagination", new Pagination<>(pages, servletRequest));

	UriComponents uriComponents = ServletUriComponentsBuilder
			.fromRequest(servletRequest)
			.queryParams(ControllerUtils.convertBeanForQueryParams(form, conversionService))
			.build();
	if (!StringUtils.isEmpty(uriComponents.getQuery())) {
		model.addAttribute("query", URLDecoder.decode(uriComponents.getQuery(), "UTF-8"));
	}

	return "page/index";
}
 
Example #8
Source File: AtomFeedView.java    From wallride with Apache License 2.0 6 votes vote down vote up
private String link(Article article) {
	UriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentContextPath();
	Map<String, Object> params = new HashMap<>();

	Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
	if (blog.getLanguages().size() > 1) {
		builder.path("/{language}");
		params.put("language", LocaleContextHolder.getLocale().getLanguage());
	}
	builder.path("/{year}/{month}/{day}/{code}");
	params.put("year", String.format("%04d", article.getDate().getYear()));
	params.put("month", String.format("%02d", article.getDate().getMonth().getValue()));
	params.put("day", String.format("%02d", article.getDate().getDayOfMonth()));
	params.put("code", article.getCode());
	return builder.buildAndExpand(params).encode().toUriString();
}
 
Example #9
Source File: BuildURIFromHttpRequest.java    From levelup-java-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void replace_path () {

	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setPathInfo("/java/examples");

	UriComponents ucb =
	        ServletUriComponentsBuilder
		        .fromRequest(request)
		        .replacePath("/java/exercises")
		        .build()
	            .encode();
	
	URI uri = ucb.toUri();
	
	assertEquals("http://localhost/java/exercises", uri.toString());
}
 
Example #10
Source File: BuildURIFromHttpRequest.java    From levelup-java-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void replace_query_parameter () {
	
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setQueryString("primaryKey=987");
	
	UriComponents ucb =
	        ServletUriComponentsBuilder
		        .fromRequest(request)
		        .replaceQueryParam("primaryKey", "{id}")
	        	.build()
	            .expand("123")
	            .encode();
	
	assertEquals("http://localhost?primaryKey=123", ucb.toString());
}
 
Example #11
Source File: GenApiService.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
private ResponseEntity<ResponseCode> getResponse(String filename, String friendlyName) {
    String host = System.getenv("GENERATOR_HOST");

    UriComponentsBuilder uriBuilder;
    if (!StringUtils.isBlank(host)) {
        uriBuilder = UriComponentsBuilder.fromUriString(host);
    } else {
        uriBuilder = ServletUriComponentsBuilder.fromCurrentContextPath();
    }

    if (filename != null) {
        String code = UUID.randomUUID().toString();
        Generated g = new Generated();
        g.setFilename(filename);
        g.setFriendlyName(friendlyName);
        fileMap.put(code, g);
        System.out.println(code + ", " + filename);
        String link = uriBuilder.path("/api/gen/download/").path(code).toUriString();
        return ResponseEntity.ok().body(new ResponseCode(code, link));
    } else {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
}
 
Example #12
Source File: RestServiceTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
void toEntityFileValueValid() throws ParseException {
  String generatedId = "id";
  String downloadUriAsString = "http://somedownloaduri";
  ServletUriComponentsBuilder mockBuilder = mock(ServletUriComponentsBuilder.class);
  UriComponents downloadUri = mock(UriComponents.class);
  FileMeta fileMeta = mock(FileMeta.class);

  Attribute fileAttr = when(mock(Attribute.class).getName()).thenReturn("fileAttr").getMock();
  when(fileAttr.getDataType()).thenReturn(FILE);
  when(idGenerator.generateId()).thenReturn(generatedId);
  when(fileMetaFactory.create(generatedId)).thenReturn(fileMeta);
  when(mockBuilder.replacePath(anyString())).thenReturn(mockBuilder);
  when(mockBuilder.replaceQuery(null)).thenReturn(mockBuilder);
  when(downloadUri.toUriString()).thenReturn(downloadUriAsString);
  when(mockBuilder.build()).thenReturn(downloadUri);
  when(servletUriComponentsBuilderFactory.fromCurrentRequest()).thenReturn(mockBuilder);

  byte[] content = {'a', 'b'};
  MockMultipartFile mockMultipartFile =
      new MockMultipartFile("name", "fileName", "contentType", content);

  assertEquals(fileMeta, restService.toEntityValue(fileAttr, mockMultipartFile, null));
}
 
Example #13
Source File: FeatureServiceImpl.java    From pazuzu-registry with MIT License 6 votes vote down vote up
private void addLinks(FeatureList features, FeaturesPage<?, Feature> page, Integer offset, Integer limit) {
    FeatureListLinks links = new FeatureListLinks();
    URI relative = ServletUriComponentsBuilder.fromCurrentContextPath().replacePath("").build().toUri();
    if (page.hasNext()) {
        Link next = new Link();
        next.setHref("/" + relative.relativize(ServletUriComponentsBuilder.fromCurrentRequest()
                .replaceQueryParam("offset", offset + limit)
                .build().toUri()).toString());
        links.setNext(next);
    }
    if (page.hasPrevious()) {
        Link previous = new Link();
        previous.setHref("/" + relative.relativize(ServletUriComponentsBuilder.fromCurrentRequest()
                .replaceQueryParam("offset", offset - limit)
                .build().toUri()).toString());
        links.setPrev(previous);
    }
    features.setLinks(links);
}
 
Example #14
Source File: ImportWizardController.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static String getUriPath(ImportRun importRun) {
  return ServletUriComponentsBuilder.fromCurrentRequestUri()
      .encode()
      .replacePath(null)
      .pathSegment(
          "api", "v2", importRun.getEntityType().getId(), importRun.getIdValue().toString())
      .build()
      .getPath();
}
 
Example #15
Source File: InvestorController.java    From Hands-On-RESTful-API-Design-Patterns-and-Best-Practices with MIT License 5 votes vote down vote up
@PostMapping("/investors/{investorId}/stocks")
public ResponseEntity<Void> addNewStockToTheInvestorPortfolio(@PathVariable String investorId,
		@RequestBody Stock newStock) {
	Stock insertedStock = investorService.addNewStockToTheInvestorPortfolio(investorId, newStock);
	if (insertedStock == null) {
		return ResponseEntity.noContent().build();
	}

	URI location = ServletUriComponentsBuilder.fromCurrentRequest().path(ID)
			.buildAndExpand(insertedStock.getSymbol()).toUri();
	return ResponseEntity.created(location).build();
}
 
Example #16
Source File: UserResource.java    From spring-web-services with MIT License 5 votes vote down vote up
@PostMapping("/users")
public ResponseEntity<Object> createUser(@Valid @RequestBody User user) {
	User savedUser = service.save(user);
	// CREATED
	// /user/{id}     savedUser.getId()
	
	URI location = ServletUriComponentsBuilder
		.fromCurrentRequest()
		.path("/{id}")
		.buildAndExpand(savedUser.getId()).toUri();
	
	return ResponseEntity.created(location).build();
	
}
 
Example #17
Source File: TodoController.java    From java-microservice with MIT License 5 votes vote down vote up
@PostMapping
public ResponseEntity<?> save(@RequestBody @Valid ToDo todo, BindingResult result) {
    if (result.hasErrors()) {
        return ResponseEntity.badRequest().build();
    }
    ToDo saved = this.todoService.save(todo);
    Long id = saved.getId();
    if (id != null) {
        URI location = ServletUriComponentsBuilder
                .fromCurrentRequest().path("/{id}")
                .buildAndExpand(id).toUri();
        return ResponseEntity.created(location).build();
    }
    return ResponseEntity.noContent().build();
}
 
Example #18
Source File: UserResource.java    From jhipster-online with Apache License 2.0 5 votes vote down vote up
/**
 * {@code GET /users} : get all users.
 *
 * @param pageable the pagination information.
 * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body all users.
 */
@GetMapping("/users")
public ResponseEntity<List<UserDTO>> getAllUsers(Pageable pageable) {
    final Page<UserDTO> page = userService.getAllManagedUsers(pageable);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
Example #19
Source File: AuditResource.java    From jhipster-online with Apache License 2.0 5 votes vote down vote up
/**
 * {@code GET  /audits} : get a page of {@link AuditEvent} between the {@code fromDate} and {@code toDate}.
 *
 * @param fromDate the start of the time period of {@link AuditEvent} to get.
 * @param toDate the end of the time period of {@link AuditEvent} to get.
 * @param pageable the pagination information.
 * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of {@link AuditEvent} in body.
 */
@GetMapping(params = {"fromDate", "toDate"})
public ResponseEntity<List<AuditEvent>> getByDates(
    @RequestParam(value = "fromDate") LocalDate fromDate,
    @RequestParam(value = "toDate") LocalDate toDate,
    Pageable pageable) {

    Instant from = fromDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
    Instant to = toDate.atStartOfDay(ZoneId.systemDefault()).plusDays(1).toInstant();

    Page<AuditEvent> page = auditEventService.findByDates(from, to, pageable);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
Example #20
Source File: AuditResource.java    From jhipster-online with Apache License 2.0 5 votes vote down vote up
/**
 * {@code GET /audits} : get a page of {@link AuditEvent}s.
 *
 * @param pageable the pagination information.
 * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of {@link AuditEvent}s in body.
 */
@GetMapping
public ResponseEntity<List<AuditEvent>> getAll(Pageable pageable) {
    Page<AuditEvent> page = auditEventService.findAll(pageable);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
Example #21
Source File: UiApplication.java    From spring-cloud-release-tools with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/upload", method = RequestMethod.GET)
public String upload() {
	ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentContextPath();
	return "<html><body>" + "<form method='post' enctype='multipart/form-data' action='"
			+ builder.path("/upload").build().toUriString() + "'>"
			+ "File to upload: <input type='file' name='file'>" + "<input type='submit' value='Upload'></form>"
			+ "</body></html>";
}
 
Example #22
Source File: MolgenisServletUriComponentsBuilder.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Creates a ServletUriComponentsBuilder from the current request with decoded query params. This
 * is needed to prevent double encoding for the query parameters when using
 * ServletUriComponentsBuilder.build(encoded=false)
 * ServletUriComponentsBuilder.build(encoded=true) cannot be used for RSQL since it throws an
 * exception on the use of '='
 */
// removing cast results in 'unclear varargs or non-varargs' warning
@SuppressWarnings("RedundantCast")
public static ServletUriComponentsBuilder fromCurrentRequestDecodedQuery() {
  ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentRequest();
  Map<String, String[]> params = getCurrentRequest().getParameterMap();
  for (Entry<String, String[]> param : params.entrySet()) {
    builder.replaceQueryParam(param.getKey(), (Object[]) param.getValue());
  }
  return builder;
}
 
Example #23
Source File: InvestorController.java    From Hands-On-RESTful-API-Design-Patterns-and-Best-Practices with MIT License 5 votes vote down vote up
@PatchMapping("/investors/{investorId}/stocks/{symbol}")
public ResponseEntity<Void> updateAStockOfTheInvestorPortfolio(@PathVariable String investorId,
		@PathVariable String symbol, @RequestBody Stock stockTobeUpdated) {
	Stock updatedStock = investorService.updateAStockByInvestorIdAndStock(investorId, symbol, stockTobeUpdated);
	if (updatedStock == null) {
		return ResponseEntity.noContent().build();
	}
	URI location = ServletUriComponentsBuilder.fromCurrentRequest().path(ID)
			.buildAndExpand(updatedStock.getSymbol()).toUri();
	return ResponseEntity.created(location).build();
}
 
Example #24
Source File: UriUtils.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static UriComponents createEntityTypeMetadataAttributeUriComponents(
    String entityTypeId, String attributeName) {
  ServletUriComponentsBuilder builder = createBuilder();
  builder.path(ApiNamespace.API_PATH);
  builder.pathSegment(RestController.API_VERSION, entityTypeId, "meta", attributeName);
  return builder.build();
}
 
Example #25
Source File: InvestorController.java    From Hands-On-RESTful-API-Design-Patterns-and-Best-Practices with MIT License 5 votes vote down vote up
@PatchMapping("/investors/{investorId}/stocks/{symbol}")
public ResponseEntity<Void> updateAStockOfTheInvestorPortfolio(@PathVariable String investorId,
		@PathVariable String symbol, @RequestBody Stock stockTobeUpdated) {
	Stock updatedStock = investorService.updateAStockByInvestorIdAndStock(investorId, symbol, stockTobeUpdated);
	if (updatedStock == null) {
		return ResponseEntity.noContent().build();
	}
	URI location = ServletUriComponentsBuilder.fromCurrentRequest().path(ID)
			.buildAndExpand(updatedStock.getSymbol()).toUri();
	return ResponseEntity.created(location).build();
}
 
Example #26
Source File: InvestorController.java    From Hands-On-RESTful-API-Design-Patterns-and-Best-Practices with MIT License 5 votes vote down vote up
@PutMapping("/investors/{investorId}/stocks")
public ResponseEntity<Void> updateAStockOfTheInvestorPortfolio(@PathVariable String investorId,
		@RequestBody Stock stockTobeUpdated) {
	Stock updatedStock = investorService.updateAStockByInvestorIdAndStock(investorId, stockTobeUpdated);
	if (updatedStock == null) {
		return ResponseEntity.noContent().build();
	}
	URI location = ServletUriComponentsBuilder.fromCurrentRequest().path(ID)
			.buildAndExpand(updatedStock.getSymbol()).toUri();
	return ResponseEntity.created(location).build();
}
 
Example #27
Source File: NFSService.java    From modeldb with Apache License 2.0 5 votes vote down vote up
private String getUrl(String artifactPath, String endpoint, String scheme) {

    String host =
        ModelDBAuthInterceptor.METADATA_INFO
            .get()
            .get(Metadata.Key.of("x-forwarded-host", Metadata.ASCII_STRING_MARSHALLER));
    if (host == null || host.isEmpty() || app.getPickNFSHostFromConfig()) {
      host = app.getNfsServerHost();
    }

    String[] hostArr = host.split(":");
    String finalHost = hostArr[0];

    UriComponentsBuilder uriComponentsBuilder =
        ServletUriComponentsBuilder.newInstance()
            .scheme(scheme)
            .host(finalHost)
            .path(endpoint)
            .queryParam("artifact_path", artifactPath);

    if (hostArr.length > 1) {
      String finalPort = hostArr[1];
      uriComponentsBuilder.port(finalPort);
    }

    return uriComponentsBuilder.toUriString();
  }
 
Example #28
Source File: StudentController.java    From tutorials with MIT License 5 votes vote down vote up
@PostMapping("/")
public ResponseEntity<Student> create(@RequestBody Student student) throws URISyntaxException {
    Student createdStudent = service.create(student);

    URI uri = ServletUriComponentsBuilder.fromCurrentRequest()
        .path("/{id}")
        .buildAndExpand(createdStudent.getId())
        .toUri();

    return ResponseEntity.created(uri)
        .body(createdStudent);

}
 
Example #29
Source File: UriUtils.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static UriComponents createEntityAttributeUriComponents(
    String entityTypeId, Object entityId, String attributeName) {
  ServletUriComponentsBuilder builder = createBuilder();
  builder.path(ApiNamespace.API_PATH);
  builder.pathSegment(
      RestController.API_VERSION, entityTypeId, entityId.toString(), attributeName);
  return builder.build();
}
 
Example #30
Source File: CustomerController.java    From cloud-espm-cloud-native with Apache License 2.0 5 votes vote down vote up
/**
 * To add a new customer
 * 
 * @param customer
 * @param uriComponentsBuilder
 * @return
 */
@PostMapping(CustomerController.API_CUSTOMER)
public ResponseEntity<Customer> addCustomer(@RequestBody final Customer customer, UriComponentsBuilder uriComponentsBuilder) {

	customerService.saveCustomer(customer);
	URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
			.buildAndExpand(customer.getCustomerId()).toUri();
	return ResponseEntity.created(uri).body(customer);
}