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: UserSearchController.java From wallride with Apache License 2.0 | 7 votes |
@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
Source File: TodoJpaResource.java From pcf-crash-course-with-spring-boot with MIT License | 7 votes |
@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: TodoJpaResource.java From docker-crash-course with MIT License | 7 votes |
@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
Source File: CorsFilter.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 6 votes |
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: PageSearchController.java From wallride with Apache License 2.0 | 6 votes |
@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 File: CustomFieldSearchController.java From wallride with Apache License 2.0 | 6 votes |
@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: GenApiService.java From openapi-generator with Apache License 2.0 | 6 votes |
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
Source File: BuildURIFromHttpRequest.java From levelup-java-examples with Apache License 2.0 | 6 votes |
@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 File: AtomFeedView.java From wallride with Apache License 2.0 | 6 votes |
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
Source File: PostController.java From angularjs-springmvc-sample-boot with Apache License 2.0 | 6 votes |
@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 #11
Source File: BuildURIFromHttpRequest.java From levelup-java-examples with Apache License 2.0 | 6 votes |
@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
Source File: RestServiceTest.java From molgenis with GNU Lesser General Public License v3.0 | 6 votes |
@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 |
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: NFSService.java From modeldb with Apache License 2.0 | 5 votes |
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
Source File: RestControllerV2.java From molgenis with GNU Lesser General Public License v3.0 | 5 votes |
@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
Source File: RestControllerV2.java From molgenis with GNU Lesser General Public License v3.0 | 5 votes |
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
Source File: PersonPhotoRestController.java From building-microservices with Apache License 2.0 | 5 votes |
@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 File: FileController.java From code-examples with MIT License | 5 votes |
@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
Source File: RestControllerV2.java From molgenis with GNU Lesser General Public License v3.0 | 5 votes |
/** 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
Source File: JobExecutionUriUtils.java From molgenis with GNU Lesser General Public License v3.0 | 5 votes |
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 File: TaskController.java From spring4-sandbox with Apache License 2.0 | 5 votes |
@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 File: SwaggerWelcome.java From springdoc-openapi with Apache License 2.0 | 5 votes |
/** * 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 File: UriUtils.java From molgenis with GNU Lesser General Public License v3.0 | 5 votes |
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
Source File: RestControllerV2.java From molgenis with GNU Lesser General Public License v3.0 | 5 votes |
@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
Source File: BuildURIFromHttpRequest.java From levelup-java-examples with Apache License 2.0 | 5 votes |
@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 File: UriUtils.java From molgenis with GNU Lesser General Public License v3.0 | 5 votes |
/** @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 File: TenantController.java From OpenLRW with Educational Community License v2.0 | 5 votes |
@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 File: ClassController.java From OpenLRW with Educational Community License v2.0 | 5 votes |
@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
Source File: UriComponentsBuilderMethodArgumentResolver.java From java-technology-stack with MIT License | 5 votes |
@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
Source File: UriComponentsBuilderMethodArgumentResolverTests.java From java-technology-stack with MIT License | 5 votes |
@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()); }