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:org.woofenterprise.dogs.web.controllers.AppointmentsController.java

@RequestMapping(value = "/new", method = RequestMethod.POST)
@RolesAllowed("ADMIN")
public String createAppointment(Model model,
        @Valid @ModelAttribute("appointment") AppointmentDTO appointmentDTO, BindingResult bindingResult,
        UriComponentsBuilder uriBuilder, RedirectAttributes redirectAttributes) {
    if (bindingResult.hasErrors()) {
        model.addAttribute("proceduresOptions", Procedure.values());

        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
            log.trace("FieldError: {}", fe);
        }/* w ww. ja v  a  2s.  com*/

        if (bindingResult.hasGlobalErrors()) {
            StringBuilder sb = new StringBuilder();
            for (ObjectError er : bindingResult.getGlobalErrors()) {
                sb.append(er.getDefaultMessage());
                sb.append('\n');
            }

            model.addAttribute("globalError", sb);
        }

        return "appointments/create";
    }
    try {
        appointmentDTO = facade.createAppointment(appointmentDTO);
        Long id = appointmentDTO.getId();

        redirectAttributes.addFlashAttribute("alert_success", "Appointment #" + id + " was created.");
        return "redirect:"
                + uriBuilder.path("/appointments/view/{id}").buildAndExpand(id).encode().toUriString();
    } catch (Exception e) {
        log.warn("Exception wile creating: " + e.getMessage());
        redirectAttributes.addFlashAttribute("alert_danger", "Appointment was not created.");
        return "redirect:/";
    }
}

From source file:cz.muni.pa165.carparkapp.web.PersonalInfoController.java

@RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(@Valid @ModelAttribute EmployeeDTO employee, BindingResult bindingResult,
        RedirectAttributes redirectAttributes, UriComponentsBuilder uriBuilder, Locale locale) {
    log.debug("update(locale={}, customer={})", locale, employee);
    if (bindingResult.hasErrors()) {
        log.debug("binding errors");
        for (ObjectError ge : bindingResult.getGlobalErrors()) {
            log.debug("ObjectError: {}", ge);
        }// www  .  java  2 s.com
        for (FieldError fe : bindingResult.getFieldErrors()) {
            log.debug("FieldError: {}", fe);
        }
        return employee.getId() < 1 ? "employee" : "employee/update";
    }
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String name = auth.getName();
    EmployeeDTO emp = null;

    for (EmployeeDTO employee1 : employeeService.getAllEmployees()) {
        if (employee1.getUserName().equals(name))
            emp = employee1;
    }
    employee.setUserName(name);
    employee.setPassword(emp.getPassword());
    employeeService.updateEmployee(employee);
    redirectAttributes.addFlashAttribute("message", messageSource.getMessage("employee.updated",
            new Object[] { employee.getFirstName(), employee.getLastName(), employee.getId() }, locale));
    return "redirect:" + uriBuilder.path("/employee").build();
}

From source file:de.otto.mongodb.profiler.web.CollectionProfileController.java

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

    final ProfiledDatabase database = requireDatabase(connectionId, databaseName);

    if (bindingResult.hasErrors()) {
        return showDatabasePageWith(model, database);
    }/*from   w w  w  .  ja v a  2s . c om*/

    final CollectionProfiler collectionProfiler = getProfilerService().getCollectionProfiler(database);
    final String uri;

    if (Boolean.TRUE.equals(model.getAddAll())) {
        final Set<String> collections = collectionProfiler.getAvailableCollections();
        for (String collection : collections) {
            try {
                collectionProfiler.addProfile(collection);
            } catch (CollectionDoesNotExistException e) {
                logger.debug(e, "Failed to add collection [%s]", collection);
            }
        }
        uri = uriComponentsBuilder.path("/connections/{connectionId}/databases/{databaseName}/collections")
                .buildAndExpand(connectionId, databaseName).toUriString();
    } else {
        final CollectionProfile collectionProfile;
        try {
            collectionProfile = collectionProfiler.addProfile(model.getName());
        } catch (CollectionDoesNotExistException e) {
            logger.debug(e, "Failed to add collection [%s]", model.getName());
            bindingResult.rejectValue("name", "collectionDoesNotExist");
            return showDatabasePageWith(model, database);
        }

        uri = uriComponentsBuilder
                .path("/connections/{connectionId}/databases/{databaseName}/collections/{collectionName}")
                .buildAndExpand(connectionId, databaseName, collectionProfile.getCollectionName())
                .toUriString();
    }

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

From source file:cz.muni.fi.mvc.controllers.DestinationController.java

/**
 * Creates a new Destination/*from   ww w.  j a v a2 s .  c  o  m*/
 * @param model display data
 * @return jsp page
 */
@RequestMapping(method = RequestMethod.POST, value = "/create")
public String create(@Valid @ModelAttribute("destinationCreate") DestinationCreationalDTO formBean,
        BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes,
        UriComponentsBuilder uriBuilder) {
    if (bindingResult.hasErrors()) {
        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
            log.trace("FieldError: {}", fe);
        }
        for (ObjectError ge : bindingResult.getGlobalErrors()) {
            log.trace("ObjectError: {}", ge);
        }
        return "destination/new";
    }
    try {
        if (destinationFacade.getDestinationWithLocation(formBean.getLocation()) == null) {
            bindingResult.addError(new FieldError("destinationCreate", "location",
                    "Destination was not created because it already exists."));
            model.addAttribute("location_error", true);
            return "destination/new";
        }

        Long id = destinationFacade.createDestination(formBean);
        redirectAttributes.addFlashAttribute("alert_info", "Destination with id: " + id + " was created");
    } catch (Exception ex) {
        model.addAttribute("alert_danger", "Destination was not created because of some unexpected error");
        redirectAttributes.addFlashAttribute("alert_danger",
                "Destination was not created because it already exists.");
    }
    return "redirect:" + uriBuilder.path("/destination").toUriString();
}

From source file:puma.sp.authentication.controllers.authentication.RequestController.java

@RequestMapping(value = "/AuthenticationRequestServlet", method = RequestMethod.GET)
public void handleRequest(ModelMap model, HttpServletResponse response,
        @RequestParam(value = "RelayState", defaultValue = "") String relayState,
        @RequestParam(value = "Tenant", defaultValue = "") String tenantId,
        @RequestParam(value = "Post", defaultValue = "false") Boolean post, HttpSession session,
        UriComponentsBuilder builder) {
    Tenant tenant = null;/*from w ww.  j  av a  2 s .com*/
    Boolean error = false;
    try {
        if (session.getAttribute("Post") != null)
            post = (Boolean) session.getAttribute("Post");
        if (session.getAttribute("Authenticated") == null
                || !((Boolean) session.getAttribute("Authenticated")).booleanValue()) {
            if (relayState == null || relayState.isEmpty())
                relayState = (String) session.getAttribute("RelayState");
            if (tenantId == null || tenantId.isEmpty())
                tenant = (Tenant) session.getAttribute("Tenant");
            else
                tenant = tenantService.findOne(Long.parseLong(tenantId));
            if (relayState == null)
                throw new FlowException("No relay state was found in the authentication process");
            if (tenant == null)
                throw new FlowException("No tenant could be identified in the authentication process");

            if (tenant.isAuthenticationLocallyManaged()) {
                logger.log(Level.INFO,
                        "Receiving local authentication request for tenant " + tenant.getName() + ".");
                session.setAttribute("FlowRedirectionElement",
                        new FlowDirecter("/AuthenticationResponseServlet"));
                response.sendRedirect(builder.path("/login").build().toString());
            } else {
                logger.log(Level.INFO,
                        "Receiving remote authentication request for tenant " + tenant.getName()
                                + ". Sending request to " + tenant.getAuthnRequestEndpoint()
                                + " (or ancestor if null)");
                AuthenticationRequestHandler handler = new AuthenticationRequestHandler(relayState, tenant);
                // Save the current session in a temporary DB and perform SAML request
                this.createSessionRequest(handler.getAssertionId(), relayState);
                handler.prepareResponse(response, handler.buildRequest(tenant.getName()));
            }
        } else {
            // Subject is already authenticated
            if (relayState != null && !relayState.isEmpty())
                session.setAttribute("RelayState", relayState);
            logger.log(Level.INFO,
                    "Got a request from an already authenticated user. Redirecting to response.");
            response.sendRedirect(builder.path("/AuthenticationResponseServlet").build().toString());
        }
    } catch (MessageEncodingException e) {
        error = true;
        logger.log(Level.SEVERE, e.getMessage(), e);
        MessageManager.getInstance().addMessage(session, "failure",
                "Failed to process the authentication process. Could not set up SAML message. Please retry and contact the administrator if this problem occurs again.");
    } catch (RequestConstructionException e) {
        error = true;
        logger.log(Level.SEVERE, e.getMessage(), e);
        MessageManager.getInstance().addMessage(session, "failure",
                "Failed to process the authentication process. Could not set up SAML message. Please retry and contact the administrator if this problem occurs again.");
    } catch (FlowException e) {
        error = true;
        logger.log(Level.SEVERE, e.getMessage(), e);
        MessageManager.getInstance().addMessage(session, "failure",
                "Failed to process the authentication process. " + e.getMessage()
                        + " Please retry and contact the administrator if this problem occurs again.");
    } catch (SAMLException e) {
        error = true;
        logger.log(Level.SEVERE, e.getMessage(), e);
        MessageManager.getInstance().addMessage(session, "failure",
                "Failed to process the authentication process. " + e.getMessage()
                        + " Please retry and contact the administrator if this problem occurs again.");
    } catch (IOException e) {
        error = true;
        logger.log(Level.SEVERE, e.getMessage(), e);
        MessageManager.getInstance().addMessage(session, "failure", "Could not redirect: " + e.getMessage()
                + " Please retry and contact the administrator if this problem occurs again.");
    }
    if (error) {
        try {
            //MessageManager.getInstance().addMessage(session, "failure", "Failed to process the authentication process. Could not process the request. Please retry and contact the administrator if this problem occurs again.");
            response.sendRedirect(builder.path("/error").build().toString());
        } catch (IOException ex) {
            logger.log(Level.SEVERE, "Could not redirect", ex);
        }
    }
}

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

/**
 * Creates the volunteer experience./*from w  w w. j  a  v  a2s  .  com*/
 *
 * @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:cz.muni.fi.mvc.controllers.StewardController.java

/**
 * Creates a new Steward/*w ww  .j a va2 s.com*/
 *
 * @param model display data
 * @return jsp page
 */
@RequestMapping(method = RequestMethod.POST, value = "/create")
public String create(@Valid @ModelAttribute("stewardCreate") StewardCreationalDTO formBean,
        BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes,
        UriComponentsBuilder uriBuilder, HttpServletRequest request) {
    if (bindingResult.hasErrors()) {
        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
            log.trace("FieldError: {}", fe);
        }
        for (ObjectError ge : bindingResult.getGlobalErrors()) {
            log.trace("ObjectError: {}", ge);
        }
        return "steward/new";
    }
    Long id = 0L;
    try {
        //            if (stewardFacade.getRelevantStewards(formBean.getPersonalIdentificator()) != null) {
        //                bindingResult.addError(new FieldError("stewardCreate", "personalIdentificator",
        //                        formBean.getPersonalIdentificator(), false, 
        //                        new String[]{"StewardCreationalDTOValidator.invalid.personalIdetificator"}, 
        //                        null, "Personal identificator already exists."));
        //                model.addAttribute("personalIdentificator_error", true);
        //                return "steward/new";
        //            }
        id = stewardFacade.createSteward(formBean);
        redirectAttributes.addFlashAttribute("alert_info", "Steward with id: " + id + " was created");
    } catch (Exception ex) {
        model.addAttribute("alert_danger", "Steward was not created because of some unexpected error");
        redirectAttributes.addFlashAttribute("alert_danger",
                "Steward was not created because of some unexpected error");
    }
    request.getSession().setAttribute("authenticated",
            stewardFacade.getStewardWithPersonalIdentificator(formBean.getPersonalIdentificator()));
    return "redirect:" + uriBuilder.path("/steward").toUriString();
}

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

/**
 * Created a qualification linked to a volunteer.
 *
 * @param volunteerId volunteer id/* w w w.  j av  a 2 s  .  com*/
 * @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:de.otto.mongodb.profiler.web.OpProfileController.java

@Page
@RequestMapping(value = "/control", method = RequestMethod.POST, params = "action=changeOutlierConfiguration", produces = MediaType.TEXT_HTML_VALUE, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ModelAndView changeOutlierConfiguration(@PathVariable("connectionId") final String connectionId,
        @PathVariable("databaseName") final String databaseName,
        @Valid @ModelAttribute("configuration") final OpOutlierConfigurationFormModel model,
        final BindingResult bindingResult, final UriComponentsBuilder uriComponentsBuilder)
        throws ResourceNotFoundException {

    final ProfiledDatabase database = requireDatabase(connectionId, databaseName);

    final OpProfiler opProfiler = getProfilerService().getOpProfiler(database);

    if (bindingResult.hasErrors()) {

        final boolean outlierConfiEnabled = model.isEnabled()
                || getProfilerService().getOpProfiler(database).getOutlierConfiguration() != null;

        return new ModelAndView("page.op-outlierconfig")
                .addObject("model", new OpOutlierConfigurationPageViewModel(database, outlierConfiEnabled))
                .addObject("configuration", model);
    }//from w ww.  j  a v a 2 s .c om

    final OpProfile.OutlierConfiguration outlierConfig;

    if (model.isEnabled()) {
        outlierConfig = new OpProfile.OutlierConfiguration() {
            @Override
            public boolean ignoreOutliers() {
                return Boolean.TRUE.equals(model.getIgnoreOutliers());
            }

            @Override
            public boolean captureOutliers() {
                return Boolean.TRUE.equals(model.getCaptureOutliers());
            }

            @Override
            public AverageMeasure.OutlierStrategy createStrategy() {
                return model.getStrategy().createStrategy(model);
            }
        };
    } else {
        outlierConfig = null;
    }

    opProfiler.setOutlierConfiguration(outlierConfig);
    opProfiler.reset();

    return new ModelAndView(new RedirectView(
            uriComponentsBuilder.path("/connections/{connectionId}/databases/{databaseName}/ops")
                    .queryParam("action", "changeOutlierConfiguration")
                    .buildAndExpand(connectionId, databaseName).toUriString()));
}

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

/**
 * Created a department skill linked to a volunteer.
 *
 * @param volunteerId volunteer id/*from  w ww  .ja  v  a2 s.  com*/
 * @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);

}