@PostMapping public ResponseEntity<?> saveMedic(@RequestBody Medic medic, BindingResult result) { medicValidator.validate(medic, result); if (result.hasErrors()) { return new ResponseEntity<>(result.getAllErrors(), HttpStatus.NOT_ACCEPTABLE); } Medic newMedic = medicService.save(medic); if (newMedic != null) { final URI location = ServletUriComponentsBuilder.fromCurrentServletMapping().path("/v1/medics/{id}").build() .expand(newMedic.getId()).toUri(); final HttpHeaders headers = new HttpHeaders(); headers.setLocation(location); return new ResponseEntity<Void>(headers, HttpStatus.CREATED); } return new ResponseEntity<Void>(HttpStatus.SERVICE_UNAVAILABLE); }
@CrossOrigin @RequestMapping(value = "/{id}/users/{userId}", method = RequestMethod.POST) @ApiOperation(value = "Create a relation between user and project") @ApiResponses(value = { @ApiResponse(code = 404, message = "ID of project or user invalid") }) //TODO: Replace explicit user{id} with AuthN user id. public ResponseEntity<?> createUserProject(@ApiParam(value = "ID of user", required = true) @PathVariable("userId") Integer userId, @ApiParam(value = "ID of project", required = true) @PathVariable("id") Integer projectId) { try { projectService.saveUserProject(userId, projectId); URI location = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}/users/{userId}") .buildAndExpand(projectId, userId).toUri(); return ResponseEntity.created(location).build(); }catch (NullPointerException | UserProjectException e){ throw new NotFoundException("ID of project or user invalid"); } }
@RequestMapping(method = RequestMethod.POST) public ResponseEntity<Void> createPlugin(@RequestBody PluginIdContainer pluginIdContainer) { if (null != pluginRepository.findByPluginNameEquals(pluginIdContainer.getPluginId())) { return new ResponseEntity<>(HttpStatus.CONFLICT); } PluginEntity pluginEntity = new PluginEntity(pluginIdContainer.getPluginId(), pluginIdContainer.getDefaultVersion(), pluginIdContainer.getDocumentationLink(), new ArrayList<>()); pluginEntity = pluginRepository.save(pluginEntity); for (PluginVersion pluginVersion : pluginIdContainer.getVersions().values()) { pluginEntity.getVersions().add(Transformer.fromPluginVersion(pluginEntity, pluginVersion)); } pluginRepository.save(pluginEntity); URI uri = ServletUriComponentsBuilder .fromCurrentRequest().path("/{id}") .buildAndExpand(pluginIdContainer.getPluginId()).toUri(); return ResponseEntity.created(uri).build(); }
@RequestMapping(value = "/{id:.+}", method = RequestMethod.POST) public ResponseEntity<Void> addVersion(@PathVariable("id") String id, @RequestBody PluginVersion version) { PluginEntity plugin = pluginRepository.findByPluginNameEquals(id); if (null == plugin) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } if (null != versionRepository.findByPluginEntityAndPluginVersionEquals(plugin, version.getVersion())) { return new ResponseEntity<>(HttpStatus.CONFLICT); } PluginVersionEntity versionEntity = Transformer.fromPluginVersion(plugin, version); plugin.getVersions().add(versionEntity); pluginRepository.save(plugin); URI uri = ServletUriComponentsBuilder .fromCurrentRequest().path("/{id}") .buildAndExpand(version.getVersion()).toUri(); return ResponseEntity.created(uri).build(); }
public String getLocaleUrl(String locale) throws Exception { UriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentRequest().replaceQueryParam("locale", locale); RequestAttributes attributes = org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(); if (attributes instanceof ServletRequestAttributes) { int statusCode = ((ServletRequestAttributes) attributes).getResponse().getStatus(); switch (statusCode) { case 200: break; case 404: builder.replacePath("" + statusCode); break; default: builder.replacePath("error"); } } URI serverUri = new URI(this.casConfigurationProperties.getServer().getName()); if ("https".equalsIgnoreCase(serverUri.getScheme())) { builder.port((serverUri.getPort() == -1) ? 443 : serverUri.getPort()); } return builder.scheme(serverUri.getScheme()).host(serverUri.getHost()).build(true).toUriString(); }
@BeforeClass public static void setup() { UriComponentsBuilder builder = ServletUriComponentsBuilder.fromUriString("dummy"); linkHeaderBuilder = new HateoasLinkHeaderBuilder(builder); Pageable nextPageable = mock(Pageable.class); when(nextPageable.getPageNumber()).thenReturn(4); Pageable prevPageable = mock(Pageable.class); when(prevPageable.getPageNumber()).thenReturn(2); page = mock(Page.class); when(page.nextPageable()).thenReturn(nextPageable); when(page.previousPageable()).thenReturn(prevPageable); when(page.getTotalPages()).thenReturn(6); }
@CrossOrigin @RequestMapping(value = "/{id}/users/{userId}", method = RequestMethod.POST) @ApiOperation(value = "Create a relation between user and organization") @ApiResponses(value = { @ApiResponse(code = 404, message = "ID of organization or user invalid") }) // TODO: Replace explicit user{id} with AuthN user id. public ResponseEntity<?> createUserOrganization( @ApiParam(value = "ID of user", required = true) @PathVariable("userId") Integer userId, @ApiParam(value = "ID of organization", required = true) @PathVariable("id") Integer organizationId) { System.out.println("************** OrganizationController.createUserOrganization()" + ": userId=" + userId + "; organizationId=" + organizationId + " **************"); try { organizationService.saveUserOrganization(userId, organizationId); URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}/users/{userId}") .buildAndExpand(organizationId, userId).toUri(); return ResponseEntity.created(location).build(); } catch (NullPointerException | UserOrganizationException e) { throw new NotFoundException("ID of organization or user invalid, or relationship already exist"); } }
@ApiOperation(value = "新增用户") @PostMapping public ResponseEntity<?> postUser(@RequestBody User user) { Optional<User> result = userService.getUserByName(user.getUsername()); if (!result.isPresent()) { userService.addUser(user); URI location = ServletUriComponentsBuilder .fromCurrentRequest() .path("/{id}") .buildAndExpand(user.getId()) .toUri(); return ResponseEntity.created(location).body(user); } else { return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).build(); } }
private void connectToProxiedTarget(WebSocketSession session) { URI sessionUri = session.getUri(); ZuulWebSocketProperties.WsBrokerage wsBrokerage = getWebSocketBrokarage( sessionUri); Assert.notNull(wsBrokerage, "wsBrokerage"); String path = getWebSocketServerPath(wsBrokerage, sessionUri); Assert.notNull(path, "Web socket uri path"); String routeHost = zuulPropertiesResolver.getRouteHost(wsBrokerage); Assert.notNull(routeHost, "routeHost"); String uri = ServletUriComponentsBuilder .fromHttpUrl(routeHost) .path(path) .replaceQuery(sessionUri.getQuery()) .toUriString(); ProxyWebSocketConnectionManager connectionManager = new ProxyWebSocketConnectionManager( messagingTemplate, stompClient, session, headersCallback, uri); connectionManager.errorHandler(this.errorHandler); managers.put(session, connectionManager); connectionManager.start(); }
@RequestMapping(method = RequestMethod.POST) public ResponseEntity<?> postClass(JwtAuthenticationToken token, @RequestBody Class klass) { UserContext userContext = (UserContext) token.getPrincipal(); Class saved = classService.save(userContext.getTenantId(), userContext.getOrgId(), klass); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setLocation(ServletUriComponentsBuilder .fromCurrentRequest().path("/{id}") .buildAndExpand(saved.getSourcedId()).toUri()); return new ResponseEntity<>(saved, httpHeaders, HttpStatus.CREATED); }
/** * Process POST /tags request * Create a tag * * @param tag tag to create * @return response entity */ @Override public ResponseEntity<Object> createTag(@ApiParam(value = "Create a tag", required = true) @RequestBody Tag tag) { // Create tag in database TagEntity entity = toTagEntity(tag); tagRepository.save(entity); URI location = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}") .buildAndExpand(entity.getId()) .toUri(); // Update tag's URL in database entity.setUrl(location.toString()); tagRepository.save(entity); return ResponseEntity.created(location).build(); }
/** * Process POST /templates request * Create a template * * @param template template to create * @return response entity */ @Override public ResponseEntity<Object> createTemplate(@ApiParam(value = "Create a template", required = true) @RequestBody TemplateBody template) { // Create template in database TemplateEntity entity = toTemplateEntity(template); templateRepository.save(entity); URI location = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}") .buildAndExpand(entity.getId()) .toUri(); // Update template's URL in database entity.setUrl(location.toString()); templateRepository.save(entity); return ResponseEntity.created(location).build(); }
@RequestMapping(method = RequestMethod.GET) Collection<Resource<String>> readPhotos(@PathVariable String key) { Profile profile = this.profilesRepository.findOne(key); Collection<Resource<String>> coll = new LinkedList<>(); profile.photosList().forEach(photoId -> { Resource<String> resource = new Resource<>(photoId); resource.add(new Link(ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}/photo").buildAndExpand(photoId).toString(), photoId)); coll.add(resource); }); return coll; }
@RequestMapping(method = {RequestMethod.POST, RequestMethod.PUT}) ResponseEntity<Resource<Profile>> insertPhoto(@PathVariable String key, @RequestParam MultipartFile file) throws IOException { Photo photo = file::getInputStream; Profile profile = this.profilesRepository.findOne(key); String id = key + profile.getPhotoCount(); try (InputStream inputStream = photo.getInputStream()) { this.fs.store(inputStream, id); } profile.addPhotoReference(id); this.profilesRepository.save(profile); URI uri = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}/photo").buildAndExpand(id).toUri(); HttpHeaders headers = new HttpHeaders(); headers.setLocation(uri); return new ResponseEntity<>( this.readPhoto(key), headers, HttpStatus.CREATED); }
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); }
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 )); }
private void populateContextPath( Model model, HttpServletRequest request ) { UriComponents contextPath = ServletUriComponentsBuilder.fromContextPath( request ).build(); String contextPathString = contextPath.toString(); String xForwardedProto = request.getHeader( "X-Forwarded-Proto" ); if ( xForwardedProto != null ) { if ( contextPathString.contains( "http://" ) && xForwardedProto.equalsIgnoreCase( "https" ) ) { contextPathString = contextPathString.replace( "http://", "https://" ); } else if ( contextPathString.contains( "https://" ) && xForwardedProto.equalsIgnoreCase( "http" ) ) { contextPathString = contextPathString.replace( "https://", "http://" ); } } model.addAttribute( "contextPath", contextPathString ); }
@RequestMapping( // path = "/", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE ) public ResponseEntity<Void> createContact( @RequestBody Contact contact) { contactDao.createContactByUserId(getUserId(), contact); // returns the URI of the new resource in the HTTP header Location field URI uri = ServletUriComponentsBuilder.fromCurrentServletMapping() .path("/contacts/{id}").build() .expand(contact.getId()).toUri(); return ResponseEntity.created(uri).build(); }
Object fixLink(Object value) { if (!(value instanceof String)) { return value; } String href = (String) value; Matcher urlWithServiceNameMatcher = urlWithServiceNamePattern.matcher(href); Matcher standardUrlMatcher = standardUrlPattern.matcher(href); if (!standardUrlMatcher.matches() && urlWithServiceNameMatcher.matches()) { String possibleServiceName = urlWithServiceNameMatcher.group(1); log.debug("Possible service name: " + possibleServiceName); if (services.contains(possibleServiceName)) { log.debug("Service found"); String gatewayPath = serviceRouteMapper.apply(possibleServiceName); String originalRestPath = urlWithServiceNameMatcher.group(2); ServletUriComponentsBuilder servletUriComponentsBuilder = ServletUriComponentsBuilder.fromCurrentRequest(); UriComponents uriComponents = servletUriComponentsBuilder.replacePath(gatewayPath).path(originalRestPath).build(); log.debug("Mapping " + value + " to " + uriComponents); return uriComponents.toString(); } } return href; }
private boolean isOriginWhitelisted( HttpServletRequest request, String origin ) { UriComponentsBuilder uriBuilder = ServletUriComponentsBuilder.fromContextPath( request ).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 ) ); }
public static void populateContextPath( Model model, HttpServletRequest request ) { UriComponents contextPath = ServletUriComponentsBuilder.fromContextPath( request ).build(); String contextPathString = contextPath.toString(); String xForwardedProto = request.getHeader( "X-Forwarded-Proto" ); if ( xForwardedProto != null ) { if ( contextPathString.contains( "http://" ) && xForwardedProto.equalsIgnoreCase( "https" ) ) { contextPathString = contextPathString.replace( "http://", "https://" ); } else if ( contextPathString.contains( "https://" ) && xForwardedProto.equalsIgnoreCase( "http" ) ) { contextPathString = contextPathString.replace( "https://", "http://" ); } } model.addAttribute( "contextPath", contextPathString ); }
/** * When a User does a POST request to /orders, a new Order is created. The requestbody is a TicketDTO, so an order * always contains at least one ticket. Optional next tickets should be added to the order by POSTing to the * location provided. * * @param ticketDTO Object containing information about the Ticket that is being ordered. * * @return A message informing about the result of the request */ @PostMapping @JsonView(View.OrderOverview.class) public ResponseEntity<?> createOrder(@RequestBody @Validated TicketDTO ticketDTO) { HttpHeaders headers = new HttpHeaders(); Order order = orderService.create(ticketDTO.getType(), ticketDTO.getOptions()); headers.setLocation( ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(order.getId()).toUri()); log.info(controllerMarker, "Order created with id:{}", order.getId(), StructuredArguments.v("order_id", order.getId()), StructuredArguments.v("ticket_type", ticketDTO.getType())); return createResponseEntity(HttpStatus.CREATED, headers, "Ticket available and order successfully created at " + headers.getLocation(), order); }
@ApiOperation( value = "Creates the given mainrun connection. Needs user role admin.", notes = "Creates the given mainrun connection. Needs user role admin." ) @RequestMapping(method = POST, value = "") public ResponseEntity createConnection(@Valid @RequestBody MainRunConnectionDto dto, Errors errors) { if (errors.hasErrors()) { throw new ValidationException(errors); } MainRunConnectionDto savedDto = connectionApiDtoService.save(dto); URI location = ServletUriComponentsBuilder.fromCurrentServletMapping() .path("/../web/connections/{id}") .build() .expand(savedDto.getId()) .toUri(); HttpHeaders headers = new HttpHeaders(); headers.setLocation(location); return new ResponseEntity<>(headers, CREATED); }
/** * Download File. * * @param path the path * @param file the file * @param mediaType the media type * @return the response entity */ public static ResponseEntity<byte[]> downloadFile(String path, String file, MediaType mediaType) { Path pathAux = Paths.get(path + file); byte[] contents = null; try { contents = Files.readAllBytes(pathAux); } catch (IOException e) { logger.error("downloadFile: ", e); } HttpHeaders headers = new HttpHeaders(); headers.setContentType(mediaType); headers.setCacheControl("must-revalidate, post-check=0, pre-check=0"); headers.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/{file}").buildAndExpand(file).toUri()); headers.add("content-disposition", "attachment; filename=" + file + ";"); return new ResponseEntity<>(contents, headers, HttpStatus.OK); }
/** * View txt. * * @param path the path * @param file the file * @return the response entity */ public static ResponseEntity<byte[]> viewTxt(String path, String file) { Path path2 = Paths.get(path); byte[] contents = null; try { contents = Files.readAllBytes(path2); } catch (IOException e) { logger.error("viewTxt: ", e); } HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_PLAIN); headers.setCacheControl("must-revalidate, post-check=0, pre-check=0"); headers.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/{file}").buildAndExpand(file).toUri()); // Download PDF // headers.setContentDispositionFormData(pathForm.getFile(), // pathForm.getFile()) // View PDF headers.add("content-disposition", "attachment; filename=" + file + ";"); return new ResponseEntity<>(contents, headers, HttpStatus.OK); }
/** * View pdf. * * @param path the path * @param file the file * @return the response entity */ public static ResponseEntity<byte[]> viewPdf(String path, String file) { Path path2 = Paths.get(path); byte[] contents = null; try { contents = Files.readAllBytes(path2); } catch (IOException e) { logger.error("viewPdf", e); } HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType("application/pdf")); headers.setCacheControl("must-revalidate, post-check=0, pre-check=0"); headers.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/{file}").buildAndExpand(file).toUri()); headers.add("content-disposition", "attachment; filename=" + file + ";"); return new ResponseEntity<>(contents, headers, HttpStatus.OK); }