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

The following examples show how to use org.springframework.web.servlet.support.ServletUriComponentsBuilder. These examples are extracted from open source projects. 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 Project: wallride   Source File: UserSearchController.java    License: 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 2
@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 Project: docker-crash-course   Source File: TodoJpaResource.java    License: 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 4
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 Project: wallride   Source File: PageSearchController.java    License: 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 6
Source Project: wallride   Source File: CustomFieldSearchController.java    License: 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 Project: openapi-generator   Source File: GenApiService.java    License: 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 8
@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 9
Source Project: wallride   Source File: AtomFeedView.java    License: 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 10
@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 [email protected]" + 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 11
@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 12
@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 Project: pazuzu-registry   Source File: FeatureServiceImpl.java    License: 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 Project: modeldb   Source File: NFSService.java    License: 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 15
@Transactional(readOnly = true)
@PostMapping(
    value = "/{entityTypeId}/meta/{attributeName}",
    params = "_method=GET",
    produces = APPLICATION_JSON_VALUE)
public AttributeResponseV2 retrieveEntityAttributeMetaPost(
    @PathVariable("entityTypeId") String entityTypeId,
    @PathVariable("attributeName") String attributeName) {
  ServletUriComponentsBuilder uriBuilder = createUriBuilder();
  return createAttributeResponse(uriBuilder, entityTypeId, attributeName);
}
 
Example 16
private void createEntityValuesResponse(
    ServletUriComponentsBuilder uriBuilder,
    Entity entity,
    Fetch fetch,
    Map<String, Object> responseData) {
  Iterable<Attribute> attrs = entity.getEntityType().getAtomicAttributes();
  createEntityValuesResponseRec(uriBuilder, entity, attrs, fetch, responseData);
}
 
Example 17
@RequestMapping(method = { RequestMethod.POST, RequestMethod.PUT })
public ResponseEntity<?> write(@PathVariable Long id,
		@RequestParam MultipartFile file) throws Exception {
	Person person = this.personRepository.findOne(id);
	FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(fileFor(person)));
	URI location = ServletUriComponentsBuilder.fromCurrentRequest().buildAndExpand(id)
			.toUri();
	return ResponseEntity.created(location).build();
}
 
Example 18
Source Project: code-examples   Source File: FileController.java    License: MIT License 5 votes vote down vote up
@GetMapping("/")
public String listAllFiles(Model model) {

    model.addAttribute("files", storageService.loadAll().map(
            path -> ServletUriComponentsBuilder.fromCurrentContextPath()
                    .path("/download/")
                    .path(path.getFileName().toString())
                    .toUriString())
            .collect(Collectors.toList()));

    return "listFiles";
}
 
Example 19
/** Retrieve attribute meta data */
@Transactional(readOnly = true)
@GetMapping(value = "/{entityTypeId}/meta/{attributeName}", produces = APPLICATION_JSON_VALUE)
public AttributeResponseV2 retrieveEntityAttributeMeta(
    @PathVariable("entityTypeId") String entityTypeId,
    @PathVariable("attributeName") String attributeName) {
  ServletUriComponentsBuilder uriBuilder = createUriBuilder();
  return createAttributeResponse(uriBuilder, entityTypeId, attributeName);
}
 
Example 20
public static String getUriPath(JobExecution jobExecution) {
  return ServletUriComponentsBuilder.fromCurrentRequestUri()
      .encode()
      .replacePath(null)
      .pathSegment(
          "api", "v2", jobExecution.getEntityType().getId(), jobExecution.getIdValue().toString())
      .build()
      .getPath();
}
 
Example 21
Source Project: spring4-sandbox   Source File: TaskController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "", method = RequestMethod.POST)
public ResponseEntity<Void> createTask(@RequestBody TaskForm fm) {
	Task task = new Task();
	task.setName(fm.getName());
	task.setDescription(fm.getDescription());

	task = taskRepository.save(task);

	HttpHeaders headers = new HttpHeaders();
	headers.setLocation(ServletUriComponentsBuilder.fromCurrentContextPath().path("/api/tasks/{id}")
			.buildAndExpand(task.getId()).toUri());

	return new ResponseEntity<>(headers, HttpStatus.CREATED);
}
 
Example 22
Source Project: springdoc-openapi   Source File: SwaggerWelcome.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Openapi yaml map.
 *
 * @param request the request
 * @return the map
 */
@Operation(hidden = true)
@GetMapping(value = SWAGGER_CONFIG_URL, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Map<String, Object> openapiJson(HttpServletRequest request) {
	buildConfigUrl(request.getContextPath(), ServletUriComponentsBuilder.fromCurrentContextPath());
	return swaggerUiConfigParameters.getConfigParameters();
}
 
Example 23
Source Project: molgenis   Source File: UriUtils.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
private static UriComponents createEntityUriComponents(
    ServletUriComponentsBuilder builder, String entityTypeId, Object entityId) {
  builder = builder.cloneBuilder();
  builder.path(ApiNamespace.API_PATH);
  builder.pathSegment(RestControllerV2.API_VERSION, entityTypeId, entityId.toString());
  return builder.build();
}
 
Example 24
@Transactional(readOnly = true)
@PostMapping(value = "/{entityTypeId}", params = "_method=GET")
public EntityCollectionResponseV2 retrieveEntityCollectionPost(
    @PathVariable("entityTypeId") String entityTypeId,
    @Valid EntityCollectionRequestV2 request,
    HttpServletRequest httpRequest,
    @RequestParam(value = "includeCategories", defaultValue = "false")
        boolean includeCategories) {
  ServletUriComponentsBuilder uriBuilder = createUriBuilder();
  return createEntityCollectionResponse(
      uriBuilder, entityTypeId, request, httpRequest, includeCategories);
}
 
Example 25
@Test
public void create_URI_from_http_request () {
	
	MockHttpServletRequest request = new MockHttpServletRequest();
	
	UriComponents ucb =
	        ServletUriComponentsBuilder
		        .fromContextPath(request)
		        .path("/examples/java")
		        .build();

	URI uri = ucb.toUri();
	
	assertEquals("http://localhost/examples/java", uri.toString());
}
 
Example 26
Source Project: molgenis   Source File: UriUtils.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/** @return <servletMappingPath>/v2/<entityTypeId>/<entityId>/<attributeName> */
static String createEntityAttributeUriPath(
    ServletUriComponentsBuilder builder,
    String entityTypeId,
    Object entityId,
    String attributeName) {
  return createEntityAttributeUriComponents(builder, entityTypeId, entityId, attributeName)
      .getPath();
}
 
Example 27
Source Project: OpenLRW   Source File: TenantController.java    License: Educational Community License v2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<?> post(@RequestBody Tenant tenant) {
  Tenant savedTenant = this.tenantService.save(tenant);
  HttpHeaders httpHeaders = new HttpHeaders();
  httpHeaders.setLocation(ServletUriComponentsBuilder
      .fromCurrentRequest().path("/{id}")
      .buildAndExpand(savedTenant.getId()).toUri());
  return new ResponseEntity<>(savedTenant, httpHeaders, HttpStatus.CREATED);
}
 
Example 28
Source Project: OpenLRW   Source File: ClassController.java    License: Educational Community License v2.0 5 votes vote down vote up
@RequestMapping(value= "/{classId:.+}/enrollments", method = RequestMethod.POST)
public ResponseEntity<?> postEnrollment(JwtAuthenticationToken token, @PathVariable final String classId, @RequestBody Enrollment enrollment, @RequestParam(value="check", required=false) Boolean check) {
  UserContext userContext = (UserContext) token.getPrincipal();
  Enrollment savedEnrollment = enrollmentService.save(userContext.getTenantId(), userContext.getOrgId(), classId, enrollment, (check == null) ? true : check);
  HttpHeaders httpHeaders = new HttpHeaders();
  httpHeaders.setLocation(ServletUriComponentsBuilder
      .fromCurrentRequest().path("/{id}")
      .buildAndExpand(savedEnrollment.getSourcedId()).toUri());
  return new ResponseEntity<>(savedEnrollment, httpHeaders, HttpStatus.CREATED);
}
 
Example 29
@Override
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
		NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {

	HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
	Assert.state(request != null, "No HttpServletRequest");
	return ServletUriComponentsBuilder.fromServletMapping(request);
}
 
Example 30
@Test
public void resolveArgument() throws Exception {
	this.servletRequest.setContextPath("/myapp");
	this.servletRequest.setServletPath("/main");
	this.servletRequest.setPathInfo("/accounts");

	Object actual = this.resolver.resolveArgument(this.builderParam, new ModelAndViewContainer(), this.webRequest, null);

	assertNotNull(actual);
	assertEquals(ServletUriComponentsBuilder.class, actual.getClass());
	assertEquals("http://localhost/myapp/main", ((ServletUriComponentsBuilder) actual).build().toUriString());
}