Example usage for org.springframework.web.util UriComponentsBuilder path

List of usage examples for org.springframework.web.util UriComponentsBuilder path

Introduction

In this page you can find the example usage for org.springframework.web.util UriComponentsBuilder path.

Prototype

@Override
public UriComponentsBuilder path(String path) 

Source Link

Document

Append the given path to the existing path of this builder.

Usage

From source file:uk.org.rbc1b.roms.controller.volunteer.VolunteersController.java

/**
 * Created a department assignment linked to a volunteer.
 *
 * @param volunteerId volunteer id/*from w  w  w  .  j a  va  2 s .c  o 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//  ww w .j  av  a 2s  .  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:de.otto.mongodb.profiler.web.DatabaseController.java

@Page(mainNavigation = MainNavigation.DATABASES)
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ModelAndView addDatabase(@Valid @ModelAttribute("database") final AddDatabaseFormModel model,
        final BindingResult bindingResult, @PathVariable("connectionId") String connectionId,
        final UriComponentsBuilder uriComponentsBuilder) throws ResourceNotFoundException {

    final ProfiledConnection connection = requireConnection(connectionId);

    if (bindingResult.hasErrors()) {
        final List<? extends ProfiledDatabase> databases = getProfilerService().getDatabases(connection);
        final ConnectionPageViewModel viewModel = new ConnectionPageViewModel(connection, databases);
        return new ModelAndView("page.connection").addObject("model", viewModel).addObject("database", model);
    }//from  w w w .j  av  a2s  . co m

    final ProfiledDatabase database;
    try {
        if (model.isCredentialsAvailable()) {
            database = getProfilerService().addDatabase(connection, model.getName(), model.getUsername(),
                    model.getPassword().toCharArray());
        } else {
            database = getProfilerService().addDatabase(connection, model.getName());
        }
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {

        if (e instanceof DatabaseDoesNotExistException) {
            logger.debug(e, "Failed to authenticate against database [%s]!", model.getName());
            bindingResult.rejectValue("name", "databaseDoesNotExist", "Database does not exist!");
        } else if (e instanceof DatabaseAlreadyConfiguredException) {
            logger.debug(e, "Failed to authenticate against database [%s]!", model.getName());
            bindingResult.rejectValue("name", "databaseAlreadyConfigured", "Database is already configured!");
        } else if (e instanceof AuthenticationException) {
            logger.info(e, "Failed to authenticate against database [%s]!", model.getName());
            bindingResult.reject("failedToAuthenticateDatabase",
                    "Failed to authenticate or authentication is required!");
        } else if (e instanceof ConnectivityException) {
            logger.warn(e, "There was a connectivity issue!", model.getName());
            bindingResult.reject("connectivityIssue", new Object[] { e.getMessage() },
                    "Failed to interact with the database: {0}!");
        } else {
            logger.warn(e, "Failed to authenticate against database [%s]!", model.getName());
            bindingResult.reject("unknownError");
        }

        final List<? extends ProfiledDatabase> databases = getProfilerService().getDatabases(connection);
        final ConnectionPageViewModel viewModel = new ConnectionPageViewModel(connection, databases);
        return new ModelAndView("page.connection").addObject("model", viewModel).addObject("database", model);
    }

    final String uri = uriComponentsBuilder.path("/connections/{id}/databases/{name}")
            .buildAndExpand(connection.getId(), database.getName()).toUriString();

    return new ModelAndView(new RedirectView(uri));
}

From source file:org.geoserver.importer.rest.ImportTransformController.java

@PostMapping(path = { "/tasks/{taskId}/transforms" })
public ResponseEntity postTransform(@PathVariable Long importId, @PathVariable Integer taskId,
        @RequestParam(value = "expand", required = false) String expand,
        @RequestBody ImportTransform importTransform, UriComponentsBuilder builder) {

    ImportTransform tx = importTransform;
    ImportTask task = task(importId, taskId);
    task.getTransform().add(tx);//from   w  w  w  .  j  ava  2s.  co  m

    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(builder.path("/imports/{importId}/tasks/{taskId}/transforms/{transformId}")
            .buildAndExpand(importId.toString(), taskId.toString(),
                    task.getTransform().getTransforms().size() - 1)
            .toUri());
    return new ResponseEntity<String>("", headers, HttpStatus.CREATED);
}

From source file:org.geoserver.rest.catalog.StyleController.java

private UriComponents getUriComponents(String name, String workspace, UriComponentsBuilder builder) {
    UriComponents uriComponents;/*  w  w  w  .ja  v a 2s  .c o  m*/
    if (workspace != null) {
        uriComponents = builder.path("/workspaces/{workspaceName}/styles/{styleName}").buildAndExpand(workspace,
                name);
    } else {
        uriComponents = builder.path("/styles/{id}").buildAndExpand(name);
    }
    return uriComponents;
}

From source file:org.haiku.haikudepotserver.pkg.PkgServiceImpl.java

@Override
public String createHpkgDownloadUrl(PkgVersion pkgVersion) {
    return pkgVersion.tryGetHpkgURL().filter(u -> ImmutableSet.of("http", "https").contains(u.getProtocol()))
            .map(URL::toString).orElseGet(() -> {
                UriComponentsBuilder builder = UriComponentsBuilder.fromPath(URL_SEGMENT_PKGDOWNLOAD);
                pkgVersion.appendPathSegments(builder);
                builder.path("package.hpkg");
                return builder.build().toUriString();
            });// w  ww .  j av  a2s  . co  m
}

From source file:org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.java

/**
 * An alternative to {@link #fromController(Class)} that accepts a
 * {@code UriComponentsBuilder} representing the base URL. This is useful
 * when using MvcUriComponentsBuilder outside the context of processing a
 * request or to apply a custom baseUrl not matching the current request.
 * <p><strong>Note:</strong> This method extracts values from "Forwarded"
 * and "X-Forwarded-*" headers if found. See class-level docs.
 * @param builder the builder for the base URL; the builder will be cloned
 * and therefore not modified and may be re-used for further calls.
 * @param controllerType the controller to build a URI for
 * @return a UriComponentsBuilder instance (never {@code null})
 *///from w  ww.  j av a2  s.  c o  m
public static UriComponentsBuilder fromController(@Nullable UriComponentsBuilder builder,
        Class<?> controllerType) {

    builder = getBaseUrlToUse(builder);
    String mapping = getTypeRequestMapping(controllerType);
    return builder.path(mapping);
}

From source file:org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.java

private static UriComponentsBuilder fromMethodInternal(@Nullable UriComponentsBuilder baseUrl,
        Class<?> controllerType, Method method, Object... args) {

    baseUrl = getBaseUrlToUse(baseUrl);/*from w  w w  .j  av  a 2s  . co  m*/
    String typePath = getTypeRequestMapping(controllerType);
    String methodPath = getMethodRequestMapping(method);
    String path = pathMatcher.combine(typePath, methodPath);
    baseUrl.path(path);
    UriComponents uriComponents = applyContributors(baseUrl, method, args);
    return UriComponentsBuilder.newInstance().uriComponents(uriComponents);
}