List of usage examples for org.springframework.http HttpHeaders setLocation
public void setLocation(@Nullable URI location)
From source file:ch.wisv.areafiftylan.products.controller.OrderRestController.java
/** * 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.//from w w w .java2 s .c o m * * @param auth The User that is currently logged in * @param ticketDTO Object containing information about the Ticket that is being ordered. * * @return A message informing about the result of the request */ @PreAuthorize("isAuthenticated()") @RequestMapping(value = "/orders", method = RequestMethod.POST) @JsonView(View.OrderOverview.class) public ResponseEntity<?> createOrder(Authentication auth, @RequestBody @Validated TicketDTO ticketDTO) { HttpHeaders headers = new HttpHeaders(); User user = (User) auth.getPrincipal(); // You can't buy non-buyable Tickts for yourself, this should be done via the createAdminOrder() method. if (!ticketDTO.getType().isBuyable()) { return createResponseEntity(HttpStatus.FORBIDDEN, "Can't order tickets with type " + ticketDTO.getType().getText()); } Order order = orderService.create(user.getId(), ticketDTO); headers.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}") .buildAndExpand(order.getId()).toUri()); return createResponseEntity(HttpStatus.CREATED, headers, "Ticket available and order successfully created at " + headers.getLocation(), order); }
From source file:org.jbr.commons.rest.RestEndpointAspect.java
/** * Aspect that surrounds a bound RESTful controller method to provide the * following enhanced functionality://w w w . ja v a 2s . c o m * * @param joinPoint * Provides reflective access to both the state available at a * join point and static information about it. * @param responseType * the {@link ResponseType} annotation which is used to specify * the response class for the bound controller method * @throws Throwable * any encountered error is passed through */ @SuppressWarnings({ "rawtypes", "unchecked" }) @Around(value = "@annotation(responseTimer)", argNames = "joinPoint, responseTimer") public Object around(final ProceedingJoinPoint joinPoint, final RestEndpoint responseTimer) throws Throwable { // start execution timer final Date startTime = startTimer(); // execute wrapped method final Object returnValue = joinPoint.proceed(); // halt and record execution timer final long elapsedTime = System.currentTimeMillis() - startTime.getTime(); LOG.debug("elapsed time for {} is {}ms", joinPoint, elapsedTime); // handle response entity if (returnValue instanceof ResponseEntity<?>) { final ResponseEntity<?> entity = (ResponseEntity<?>) returnValue; final HttpHeaders headers = new HttpHeaders(); // transfer any existing headers, if enabled if (responseTimer.transferHeaders()) { headers.putAll(entity.getHeaders()); } // transfer self link as Location header, if CREATED reponse if (entity.getStatusCode().equals(HttpStatus.CREATED)) { if (entity.getBody() instanceof ResourceSupport) { final ResourceSupport resource = (ResourceSupport) entity.getBody(); if (resource.getId() != null) { headers.setLocation(new URI(resource.getId().getHref())); } } } // save elapsed time header headers.add(HEADER_RESPONSE_ID, generatedResponseIdentifier()); headers.add(HEADER_START_TIME, DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(startTime)); headers.add(HEADER_ELAPSED_TIME, String.valueOf(elapsedTime)); // return new response entity return new ResponseEntity(entity.getBody(), headers, entity.getStatusCode()); } // handle non-response entity else { return returnValue; } }
From source file:uk.org.rbc1b.roms.controller.volunteer.VolunteersController.java
/** * Creates the volunteer experience./* w w w. j a v a 2 s . c om*/ * * @param volunteerId the volunteer id * @param form the form data * @param builder the builder * @return response status */ @RequestMapping(value = "{volunteerId}/experience", method = RequestMethod.POST) @ResponseStatus(HttpStatus.NO_CONTENT) public ResponseEntity<Void> createVolunteerExperience(@PathVariable Integer volunteerId, @Valid VolunteerExperienceForm form, UriComponentsBuilder builder) { Volunteer volunteer = volunteerDao.findVolunteer(volunteerId, null); if (volunteer == null) { throw new ResourceNotFoundException("No volunteer #" + volunteerId + " found"); } VolunteerTrade trade = new VolunteerTrade(); trade.setVolunteer(volunteer); trade.setName(form.getName()); trade.setExperienceDescription(form.getExperienceDescription()); trade.setExperienceYears(Integer.parseInt(form.getExperienceYears())); volunteerDao.createTrade(trade); HttpHeaders headers = new HttpHeaders(); headers.setLocation(builder.path("/volunteers/{volunteerId}/experience/{experienceId}") .buildAndExpand(volunteerId, trade.getVolunteerTradeId()).toUri()); return new ResponseEntity<Void>(headers, HttpStatus.CREATED); }
From source file:uk.org.rbc1b.roms.controller.volunteer.VolunteersController.java
/** * Created a qualification linked to a volunteer. * * @param volunteerId volunteer id/*from w ww.j a va2 s. c o m*/ * @param form qualification information * @param builder uri builder, for building the response header * @return created status, with the qualification url * is not found */ @RequestMapping(value = "{volunteerId}/qualifications", method = RequestMethod.POST) @ResponseStatus(HttpStatus.NO_CONTENT) public ResponseEntity<Void> createVolunteerQualification(@PathVariable Integer volunteerId, @Valid VolunteerQualificationForm form, UriComponentsBuilder builder) { Volunteer volunteer = volunteerDao.findVolunteer(volunteerId, null); if (volunteer == null) { throw new ResourceNotFoundException("No volunteer #" + volunteerId + " found"); } VolunteerQualification volunteerQualification = new VolunteerQualification(); volunteerQualification.setComments(form.getComments()); volunteerQualification.setPersonId(volunteerId); volunteerQualification.setQualificationId(form.getQualificationId()); volunteerDao.createQualification(volunteerQualification); HttpHeaders headers = new HttpHeaders(); headers.setLocation(builder.path("/volunteers/{volunteerId}/qualifications/{qualificationId}") .buildAndExpand(volunteerId, volunteerQualification.getVolunteerQualificationId()).toUri()); return new ResponseEntity<Void>(headers, HttpStatus.CREATED); }
From source file:uk.org.rbc1b.roms.controller.volunteer.VolunteersController.java
/** * Created a department skill linked to a volunteer. * * @param volunteerId volunteer id//from ww w . j a v a 2 s . c o m * @param form skill information * @param builder uri builder, for building the response header * @return created status, with the skill url * assignment is not found */ @RequestMapping(value = "{volunteerId}/skills", method = RequestMethod.POST) @ResponseStatus(HttpStatus.NO_CONTENT) public ResponseEntity<Void> createVolunteerSkill(@PathVariable Integer volunteerId, @Valid VolunteerSkillForm form, UriComponentsBuilder builder) { Volunteer volunteer = volunteerDao.findVolunteer(volunteerId, null); if (volunteer == null) { throw new ResourceNotFoundException("No volunteer #" + volunteerId + " found"); } VolunteerSkill volunteerSkill = new VolunteerSkill(); volunteerSkill.setComments(form.getComments()); volunteerSkill.setLevel(form.getLevel()); volunteerSkill.setPersonId(volunteerId); volunteerSkill.setSkillId(form.getSkillId()); volunteerSkill.setTrainingDate(DataConverterUtil.toSqlDate(form.getTrainingDate())); volunteerSkill.setTrainingResults(form.getTrainingResults()); volunteerDao.createSkill(volunteerSkill); HttpHeaders headers = new HttpHeaders(); headers.setLocation(builder.path("/volunteers/{volunteerId}/skills/{skillId}") .buildAndExpand(volunteerId, volunteerSkill.getVolunteerSkillId()).toUri()); return new ResponseEntity<Void>(headers, HttpStatus.CREATED); }
From source file:uk.org.rbc1b.roms.controller.volunteer.VolunteersController.java
/** * Created a department assignment linked to a volunteer. * * @param volunteerId volunteer id/*w w w . j av a 2 s . co m*/ * @param form assignment information * @param builder uri builder, for building the response header * @return created status, with the assignment url * assignment is not found */ @RequestMapping(value = "{volunteerId}/assignments", method = RequestMethod.POST) @ResponseStatus(HttpStatus.NO_CONTENT) public ResponseEntity<Void> createVolunteerAssignment(@PathVariable Integer volunteerId, @Valid VolunteerAssignmentForm form, UriComponentsBuilder builder) { Volunteer volunteer = volunteerDao.findVolunteer(volunteerId, null); if (volunteer == null) { throw new ResourceNotFoundException("No volunteer #" + volunteerId + " found"); } Assignment volunteerAssignment = new Assignment(); volunteerAssignment.setAssignedDate(DataConverterUtil.toSqlDate(form.getAssignedDate())); volunteerAssignment.setDepartmentId(form.getDepartmentId()); volunteerAssignment.setPerson(volunteer.getPerson()); AssignmentRole role = new AssignmentRole(); role.setAssignmentRoleCode(form.getAssignmentRoleCode()); volunteerAssignment.setRole(role); Team team = new Team(); team.setTeamId(form.getTeamId()); volunteerAssignment.setTeam(team); volunteerAssignment.setTradeNumberId(form.getTradeNumberId()); departmentDao.createAssignment(volunteerAssignment); HttpHeaders headers = new HttpHeaders(); headers.setLocation(builder.path("/volunteers/{volunteerId}/assignments/{assignmentId}") .buildAndExpand(volunteerId, volunteerAssignment.getAssignmentId()).toUri()); return new ResponseEntity<Void>(headers, HttpStatus.CREATED); }
From source file:uk.org.rbc1b.roms.controller.volunteer.VolunteersController.java
/** * Created an emergency contact to a volunteer. * * @param volunteerId volunteer id/*from w ww . ja v a2 s . c om*/ * @param form emergency contact information * @param builder uri builder, for building the response header * @return created status, with the emergency contact url */ @RequestMapping(value = "{volunteerId}/emergencycontacts", method = RequestMethod.POST) @ResponseStatus(HttpStatus.NO_CONTENT) public ResponseEntity<Void> createVolunteerEmergencyContact(@PathVariable Integer volunteerId, @Valid VolunteerEmergencyContactForm form, UriComponentsBuilder builder) { Volunteer volunteer = volunteerDao.findVolunteer(volunteerId, null); if (volunteer == null) { throw new ResourceNotFoundException("No volunteer #" + volunteerId + " found"); } volunteer.setEmergencyContactRelationshipCode(form.getRelationshipCode()); Person emergencyContact; int emergencyContactId = form.getEmergencyContactId(); if (emergencyContactId == -1) { // create a new Person emergencyContact = new Person(); emergencyContact.setForename(form.getFirstName()); emergencyContact.setSurname(form.getSurName()); emergencyContact.setTelephone(PhoneNumberFormatter.format(form.getHomePhone())); emergencyContact.setMobile(PhoneNumberFormatter.format(form.getMobilePhone())); emergencyContact.setWorkPhone(PhoneNumberFormatter.format(form.getWorkPhone())); personDao.createPerson(emergencyContact); } else { emergencyContact = personDao.findPerson(emergencyContactId); } volunteer.setEmergencyContact(emergencyContact); volunteerDao.updateVolunteer(volunteer); HttpHeaders headers = new HttpHeaders(); headers.setLocation(builder.path("/volunteers/{volunteerId}/emergencycontacts/{emergencyContactId}") .buildAndExpand(volunteerId, 1).toUri()); return new ResponseEntity<Void>(headers, HttpStatus.CREATED); }
From source file:net.paslavsky.springrest.HttpHeadersHelper.java
public HttpHeaders getHttpHeaders(Map<String, Integer> headerParameters, Object[] arguments) { HttpHeaders headers = new HttpHeaders(); for (String headerName : headerParameters.keySet()) { Object headerValue = arguments[headerParameters.get(headerName)]; if (headerValue != null) { if (ACCEPT.equalsIgnoreCase(headerName)) { headers.setAccept(toList(headerValue, MediaType.class)); } else if (ACCEPT_CHARSET.equalsIgnoreCase(headerName)) { headers.setAcceptCharset(toList(headerValue, Charset.class)); } else if (ALLOW.equalsIgnoreCase(headerName)) { headers.setAllow(toSet(headerValue, HttpMethod.class)); } else if (CONNECTION.equalsIgnoreCase(headerName)) { headers.setConnection(toList(headerValue, String.class)); } else if (CONTENT_DISPOSITION.equalsIgnoreCase(headerName)) { setContentDisposition(headers, headerName, headerValue); } else if (CONTENT_LENGTH.equalsIgnoreCase(headerName)) { headers.setContentLength(toLong(headerValue)); } else if (CONTENT_TYPE.equalsIgnoreCase(headerName)) { headers.setContentType(toMediaType(headerValue)); } else if (DATE.equalsIgnoreCase(headerName)) { headers.setDate(toLong(headerValue)); } else if (ETAG.equalsIgnoreCase(headerName)) { headers.setETag(toString(headerValue)); } else if (EXPIRES.equalsIgnoreCase(headerName)) { headers.setExpires(toLong(headerValue)); } else if (IF_MODIFIED_SINCE.equalsIgnoreCase(headerName)) { headers.setIfModifiedSince(toLong(headerValue)); } else if (IF_NONE_MATCH.equalsIgnoreCase(headerName)) { headers.setIfNoneMatch(toList(headerValue, String.class)); } else if (LAST_MODIFIED.equalsIgnoreCase(headerName)) { headers.setLastModified(toLong(headerValue)); } else if (LOCATION.equalsIgnoreCase(headerName)) { headers.setLocation(toURI(headerValue)); } else if (ORIGIN.equalsIgnoreCase(headerName)) { headers.setOrigin(toString(headerValue)); } else if (PRAGMA.equalsIgnoreCase(headerName)) { headers.setPragma(toString(headerValue)); } else if (UPGRADE.equalsIgnoreCase(headerName)) { headers.setUpgrade(toString(headerValue)); } else if (headerValue instanceof String) { headers.set(headerName, (String) headerValue); } else if (headerValue instanceof String[]) { headers.put(headerName, Arrays.asList((String[]) headerValue)); } else if (instanceOf(headerValue, String.class)) { headers.put(headerName, toList(headerValue, String.class)); } else { headers.set(headerName, conversionService.convert(headerValue, String.class)); }//from www .ja v a 2 s .c om } } return headers; }
From source file:com.netflix.genie.web.controllers.JobRestController.java
private ResponseEntity<Void> handleSubmitJob(final JobRequest jobRequest, final MultipartFile[] attachments, final String clientHost, final String userAgent, final HttpServletRequest httpServletRequest) throws GenieException { if (jobRequest == null) { throw new GeniePreconditionException("No job request entered. Unable to submit."); }/*from w w w. j av a 2 s .c o m*/ // get client's host from the context final String localClientHost; if (StringUtils.isNotBlank(clientHost)) { localClientHost = clientHost.split(",")[0]; } else { localClientHost = httpServletRequest.getRemoteAddr(); } final JobRequest jobRequestWithId; // If the job request does not contain an id create one else use the one provided. final String jobId; final Optional<String> jobIdOptional = jobRequest.getId(); if (jobIdOptional.isPresent() && StringUtils.isNotBlank(jobIdOptional.get())) { jobId = jobIdOptional.get(); jobRequestWithId = jobRequest; } else { jobId = UUID.randomUUID().toString(); final JobRequest.Builder builder = new JobRequest.Builder(jobRequest.getName(), jobRequest.getUser(), jobRequest.getVersion(), jobRequest.getCommandArgs(), jobRequest.getClusterCriterias(), jobRequest.getCommandCriteria()).withId(jobId) .withDisableLogArchival(jobRequest.isDisableLogArchival()) .withTags(jobRequest.getTags()).withDependencies(jobRequest.getDependencies()) .withApplications(jobRequest.getApplications()); jobRequest.getCpu().ifPresent(builder::withCpu); jobRequest.getMemory().ifPresent(builder::withMemory); jobRequest.getGroup().ifPresent(builder::withGroup); jobRequest.getSetupFile().ifPresent(builder::withSetupFile); jobRequest.getDescription().ifPresent(builder::withDescription); jobRequest.getEmail().ifPresent(builder::withEmail); jobRequest.getTimeout().ifPresent(builder::withTimeout); jobRequestWithId = builder.build(); } // Download attachments int numAttachments = 0; long totalSizeOfAttachments = 0L; if (attachments != null) { log.info("Saving attachments for job {}", jobId); numAttachments = attachments.length; for (final MultipartFile attachment : attachments) { totalSizeOfAttachments += attachment.getSize(); log.debug("Attachment name: {} Size: {}", attachment.getOriginalFilename(), attachment.getSize()); try { this.attachmentService.save(jobId, attachment.getOriginalFilename(), attachment.getInputStream()); } catch (final IOException ioe) { throw new GenieServerException(ioe); } } } final JobMetadata metadata = new JobMetadata.Builder().withClientHost(localClientHost) .withUserAgent(userAgent).withNumAttachments(numAttachments) .withTotalSizeOfAttachments(totalSizeOfAttachments).build(); this.jobCoordinatorService.coordinateJob(jobRequestWithId, metadata); final HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setLocation( ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(jobId).toUri()); return new ResponseEntity<>(httpHeaders, HttpStatus.ACCEPTED); }