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:cz.muni.fi.dndtroopsweb.controllers.HeroController.java

/**
 * Insert hero into troop/*from   ww w  . j  a  v a  2s  . c  o m*/
 *
 * @param formBean hero to be added into troop
 * @return Details of hero who has been inserted
 */
@RequestMapping(value = "/add/{id}", method = RequestMethod.POST)
public String add(@PathVariable long id, @Valid @ModelAttribute("hero") HeroDTO formBean,
        BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes,
        UriComponentsBuilder uriBuilder) {
    log.debug("add troop(hero={})", formBean);
    //in case of validation error forward back to the the form
    if (bindingResult.hasErrors()) {
        for (ObjectError ge : bindingResult.getGlobalErrors()) {
            log.trace("ObjectError: {}", ge);
        }
        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
            log.trace("FieldError: {}", fe);
        }
        return "hero/troop";
    }
    if (heroFacade.getHeroWithId(id).getTroop() != null) {
        redirectAttributes.addFlashAttribute("alert_warning",
                "Hero \"" + heroFacade.getHeroWithId(id).getName() + "\" is already in troop");
        return "redirect:" + uriBuilder.path("/hero/details/" + id).toUriString();
    }
    heroFacade.addTroop(id, formBean.getId());
    redirectAttributes.addFlashAttribute("alert_success", "Hero added into Troop");
    return "redirect:" + uriBuilder.path("/hero/details/{id}").buildAndExpand(id).encode().toUriString();
}

From source file:cz.muni.fi.pa165.mvc.controllers.PlayerController.java

@RequestMapping(value = "/create", method = RequestMethod.POST)
public String create(@Valid @ModelAttribute("playerCreate") PlayerCreateDTO formBean,
        BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes,
        UriComponentsBuilder uriBuilder) {
    log.debug("create(playerCreate={})", formBean);
    //in case of validation error forward back to the the form
    if (bindingResult.hasErrors()) {
        log.debug("some errror");
        for (ObjectError ge : bindingResult.getGlobalErrors()) {
            log.trace("ObjectError: {}", ge);

        }/*from   w ww .j av  a  2 s .  c om*/
        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
            log.trace("FieldError: {}", fe);
        }
        return "player/new";

    }

    //create player
    if (formBean.getName().equals("")) {
        redirectAttributes.addFlashAttribute("alert_warning",
                "Player creation failed - Player name cannot be emty string!");
        return "redirect:" + uriBuilder.path("/player/new").build().encode().toUriString();
    }

    if (formBean.getDateOfBirth().compareTo(new Date()) > 0) {
        redirectAttributes.addFlashAttribute("alert_warning",
                "Player creation failed - Player date cannot be bigger than actuall date!");
        return "redirect:" + uriBuilder.path("/player/new").build().encode().toUriString();
    }

    Long id = playerFacade.createPlayer(convertPlayerCreateDTO(formBean));

    //report success
    redirectAttributes.addFlashAttribute("alert_success",
            "Player " + playerFacade.findById(id).toString() + " was created");
    return "redirect:" + uriBuilder.path("/player/list").buildAndExpand(id).encode().toUriString();
}

From source file:cz.muni.fi.pa165.mvc.controllers.TeamController.java

@RequestMapping(value = "/edit", method = RequestMethod.POST)
public String edit(@Valid @ModelAttribute("teamEdit") TeamDTO formBean, BindingResult bindingResult,
        Model model, RedirectAttributes redirectAttributes, UriComponentsBuilder uriBuilder) {
    log.debug("edit(teamEdit={})", formBean);
    if (bindingResult.hasErrors()) {
        log.debug("some errror");
        for (ObjectError ge : bindingResult.getGlobalErrors()) {
            log.trace("ObjectError: {}", ge);

        }//from  ww  w  . j a v a  2 s .c  o  m
        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
            log.trace("FieldError: {}", fe);
        }
        return "team/edit";

    }
    try {
        teamFacade.updateTeam(formBean);
        redirectAttributes.addFlashAttribute("alert_success", "Team was edited");
    } catch (Exception ex) {
        log.warn("cannot edit this team {}");
        redirectAttributes.addFlashAttribute("alert_danger",
                "Team's name has already exited or any errors happen, please check again!");
    }
    return "redirect:" + uriBuilder.path("/team/list").toUriString();

}

From source file:cz.muni.fi.pa165.mvc.controllers.TeamController.java

@RequestMapping(value = "/create", method = RequestMethod.POST)
public String create(@Valid @ModelAttribute("teamCreate") TeamDTO formBean, BindingResult bindingResult,
        Model model, RedirectAttributes redirectAttributes, UriComponentsBuilder uriBuilder) {
    Long id = null;/*from   w  ww. j a v a 2s. com*/
    log.debug("create(teamCreate={})", formBean);
    if (bindingResult.hasErrors()) {
        for (ObjectError ge : bindingResult.getGlobalErrors()) {
            log.trace("ObjectError: {}", ge);
        }
        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
            log.trace("FieldError: {}", fe);
        }
        return "team/new";
    }
    try {
        id = teamFacade.createTeam(formBean);
        redirectAttributes.addFlashAttribute("alert_success",
                "Team: " + teamFacade.getTeamById(id) + " was created");
    } catch (Exception ex) {
        log.warn("cannot Create a team {}");
        redirectAttributes.addFlashAttribute("alert_danger",
                "This team cannot be created because it has already exited in La Liga now.");
    }
    return "redirect:" + uriBuilder.path("/team/list").buildAndExpand(id).encode().toUriString();
}

From source file:cz.muni.pa165.carparkapp.web.EmployeeController.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={}, employee={})", locale, employee);
    if (employee.getId() < 1) {
        employeeService.addEmployee(employee);
        redirectAttributes.addFlashAttribute("message", messageSource.getMessage("employee.add.message",
                new Object[] { employee.getFirstName(), employee.getLastName() }, locale));
        if (employee.getUserName() == null || employee.getUserName().isEmpty()) {
            employeeService.addEmployee(employee);
            redirectAttributes.addFlashAttribute("message",
                    messageSource.getMessage("employee.nullusername.message",
                            new Object[] { employee.getFirstName(), employee.getLastName() }, locale));
        }//from  w  w w.j a  va2 s.c om
    } else {

        employeeService.updateEmployee(employee);
        redirectAttributes.addFlashAttribute("message",
                messageSource.getMessage("employee.updated.message", new Object[] {}, locale));
    }
    return "redirect:" + uriBuilder.path("/serviceEmployee/addEmployee").build();
}

From source file:org.openmhealth.shim.ihealth.IHealthShim.java

@Override
protected ResponseEntity<ShimDataResponse> getData(OAuth2RestOperations restTemplate,
        ShimDataRequest shimDataRequest) throws ShimException {

    final IHealthDataTypes dataType;
    try {/*from  ww  w  .  ja v  a 2 s .c om*/
        dataType = valueOf(shimDataRequest.getDataTypeKey().trim().toUpperCase());
    } catch (NullPointerException | IllegalArgumentException e) {
        throw new ShimException("Null or Invalid data type parameter: " + shimDataRequest.getDataTypeKey()
                + " in shimDataRequest, cannot retrieve data.");
    }

    OffsetDateTime now = OffsetDateTime.now();
    OffsetDateTime startDate = shimDataRequest.getStartDateTime() == null ? now.minusDays(1)
            : shimDataRequest.getStartDateTime();
    OffsetDateTime endDate = shimDataRequest.getEndDateTime() == null ? now.plusDays(1)
            : shimDataRequest.getEndDateTime();

    /*
    The physical activity point handles start and end datetimes differently than the other endpoints. It
    requires use to include the range until the beginning of the next day.
     */
    if (dataType == PHYSICAL_ACTIVITY) {

        endDate = endDate.plusDays(1);
    }

    // SC and SV values are client-based keys that are unique to each endpoint within a project
    String scValue = getScValue();
    List<String> svValues = getSvValues(dataType);

    List<JsonNode> responseEntities = newArrayList();

    int i = 0;

    // We iterate because one of the measures (Heart rate) comes from multiple endpoints, so we submit
    // requests to each of these endpoints, map the responses separately and then combine them
    for (String endPoint : dataType.getEndPoint()) {

        UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(API_URL);

        // Need to use a dummy userId if we haven't authenticated yet. This is the case where we are using
        // getData to trigger Spring to conduct the OAuth exchange
        String userId = "uk";

        if (shimDataRequest.getAccessParameters() != null) {

            OAuth2AccessToken token = SerializationUtils
                    .deserialize(shimDataRequest.getAccessParameters().getSerializedToken());

            userId = Preconditions.checkNotNull((String) token.getAdditionalInformation().get("UserID"));
            uriBuilder.queryParam("access_token", token.getValue());
        }

        uriBuilder.path("/user/").path(userId + "/").path(endPoint)
                .queryParam("client_id", restTemplate.getResource().getClientId())
                .queryParam("client_secret", restTemplate.getResource().getClientSecret())
                .queryParam("start_time", startDate.toEpochSecond())
                .queryParam("end_time", endDate.toEpochSecond()).queryParam("locale", "default")
                .queryParam("sc", scValue).queryParam("sv", svValues.get(i));

        ResponseEntity<JsonNode> responseEntity;

        try {
            URI url = uriBuilder.build().encode().toUri();
            responseEntity = restTemplate.getForEntity(url, JsonNode.class);
        } catch (HttpClientErrorException | HttpServerErrorException e) {
            // FIXME figure out how to handle this
            logger.error("A request for iHealth data failed.", e);
            throw e;
        }

        if (shimDataRequest.getNormalize()) {

            IHealthDataPointMapper mapper;

            switch (dataType) {

            case PHYSICAL_ACTIVITY:
                mapper = new IHealthPhysicalActivityDataPointMapper();
                break;
            case BLOOD_GLUCOSE:
                mapper = new IHealthBloodGlucoseDataPointMapper();
                break;
            case BLOOD_PRESSURE:
                mapper = new IHealthBloodPressureDataPointMapper();
                break;
            case BODY_WEIGHT:
                mapper = new IHealthBodyWeightDataPointMapper();
                break;
            case BODY_MASS_INDEX:
                mapper = new IHealthBodyMassIndexDataPointMapper();
                break;
            case STEP_COUNT:
                mapper = new IHealthStepCountDataPointMapper();
                break;
            case SLEEP_DURATION:
                mapper = new IHealthSleepDurationDataPointMapper();
                break;
            case HEART_RATE:
                // there are two different mappers for heart rate because the data can come from two endpoints
                if (endPoint == "bp.json") {
                    mapper = new IHealthBloodPressureEndpointHeartRateDataPointMapper();
                    break;
                } else if (endPoint == "spo2.json") {
                    mapper = new IHealthBloodOxygenEndpointHeartRateDataPointMapper();
                    break;
                }
            case OXYGEN_SATURATION:
                mapper = new IHealthOxygenSaturationDataPointMapper();
                break;
            default:
                throw new UnsupportedOperationException();
            }

            responseEntities.addAll(mapper.asDataPoints(singletonList(responseEntity.getBody())));

        } else {
            responseEntities.add(responseEntity.getBody());
        }

        i++;

    }

    return ResponseEntity.ok().body(ShimDataResponse.result(SHIM_KEY, responseEntities));
}

From source file:it.scoppelletti.programmerpower.web.control.ActionBase.java

/**
 * Restituisce l&rsquo;indirizzo della pagina HTML di guida.
 * // w  w  w.  java2s . co m
 * <P>Questa implementazione del metodo {@code getHelpUrl} rileva il valore 
 * della propriet&agrave; {@code path.help} tra le risorse
 * associate all&rsquo;azione: se questa propriet&agrave; &egrave;
 * impostata, &egrave; considerata come un percorso relativo
 * all&rsquo;indirizzo di base della guida di riferimento di Programmer
 * Power ({@code http://www.scoppelletti.it/programmerpower/reference});
 * questo indirizzo di base pu&ograve; essere sovrascritto dal valore
 * impostato sulla propriet&agrave; di ambiente
 * {@code it.scoppelletti.programmerpower.web.help.url}.<BR>
 * Le classi derivate da terze parti dovrebbero implementare una versione
 * prevalente del metodo {@code getHelpUrl} per restituire l&rsquo;URL
 * opportuno.</P>
 * 
 * @return Valore. Se la guida non &egrave; prevista, restituisce
 *         {@code null}.
 * @see <A HREF="{@docRoot}/../reference/setup/envprops.html"
 *      TARGET="_top">Propriet&agrave; di ambiente</A>          
 */
public String getHelpUrl() {
    String base, path;
    UriComponentsBuilder uriBuilder;
    Environment env;

    path = getText(ActionBase.PROP_HELPPATH);
    if (Strings.isNullOrEmpty(path) || ActionBase.PROP_HELPPATH.equals(path)) {
        return null;
    }

    if (myApplCtx == null) {
        base = ActionBase.DEF_HELPURL;
    } else {
        env = myApplCtx.getEnvironment();
        base = env.getProperty(ActionBase.PROP_HELPURL, ActionBase.DEF_HELPURL);
    }

    if (!base.endsWith("/") && !path.startsWith("/")) {
        base = base.concat("/");
    }

    uriBuilder = UriComponentsBuilder.fromUriString(base);
    uriBuilder.path(path);

    return uriBuilder.build().toUriString();
}

From source file:net.es.sense.rm.api.SenseRmController.java

/**
 * Returns a list of available SENSE service API resource URLs.
 *
 * Operation: GET /api/sense/v1/*from  w  w  w  .  j  av  a  2 s  .co  m*/
 *
 * @return A RESTful response.
 * @throws java.net.MalformedURLException
 */
@ApiOperation(value = "Get a list of supported SENSE resources.", notes = "Returns a list of available SENSE resource URL.", response = DeltaResource.class, responseContainer = "List")
@ApiResponses(value = {
        @ApiResponse(code = HttpConstants.OK_CODE, message = HttpConstants.OK_MSG, response = Resource.class),
        @ApiResponse(code = HttpConstants.UNAUTHORIZED_CODE, message = HttpConstants.UNAUTHORIZED_MSG, response = Error.class),
        @ApiResponse(code = HttpConstants.FORBIDDEN_CODE, message = HttpConstants.FORBIDDEN_MSG, response = Error.class),
        @ApiResponse(code = HttpConstants.INTERNAL_ERROR_CODE, message = HttpConstants.INTERNAL_ERROR_MSG, response = Error.class), })
@RequestMapping(method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public ResponseEntity<?> getResources() throws MalformedURLException {
    try {
        // We need the request URL to build fully qualified resource URLs.
        final URI location = ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri();

        log.info("[SenseRmController] GET operation = {}", location);

        // We will populate some HTTP response headers.
        final HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Location", location.toASCIIString());

        List<Resource> resources = new ArrayList<>();
        Method[] methods = SenseRmController.class.getMethods();
        for (Method m : methods) {
            if (m.isAnnotationPresent(ResourceAnnotation.class)) {
                ResourceAnnotation ra = m.getAnnotation(ResourceAnnotation.class);
                RequestMapping rm = m.getAnnotation(RequestMapping.class);
                if (ra == null || rm == null) {
                    continue;
                }
                Resource resource = new Resource();
                resource.setId(ra.name());
                resource.setVersion(ra.version());
                UriComponentsBuilder path = utilities.getPath(location.toASCIIString());
                path.path(rm.value()[0]);
                resource.setHref(path.build().toUriString());
                resources.add(resource);
            }
        }

        return new ResponseEntity<>(resources, headers, HttpStatus.OK);
    } catch (SecurityException | MalformedURLException ex) {
        log.error("[SenseRmController] Exception caught", ex);
        Error error = Error.builder().error(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase())
                .error_description(ex.getMessage()).build();
        return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.woofenterprise.dogs.web.controllers.AppointmentsController.java

@RequestMapping(value = "/edit", method = RequestMethod.POST)
@RolesAllowed("ADMIN")
public String update(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 w  w.ja v a2s.  c o m*/

        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/edit";
    }
    Long id = appointmentDTO.getId();
    try {
        facade.updateAppointment(appointmentDTO);

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

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

@Page(mainNavigation = MainNavigation.CONNECTIONS)
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ModelAndView createNewConnection(
        @Valid @ModelAttribute("connection") final CreateConnectionFormModel model,
        final BindingResult bindingResult, final UriComponentsBuilder uriComponentsBuilder) {

    if (bindingResult.hasErrors()) {
        return new ModelAndView("page.new-connection").addObject("connection", model);
    }/*  w w w  .j  a v  a  2s .com*/

    final ProfiledConnectionConfiguration.Builder configBuilder = ProfiledConnectionConfiguration.build();

    try {
        parseHosts(model.getHosts(), configBuilder);
    } catch (ParseException e) {
        bindingResult.rejectValue("hosts", "invalidHostName", new Object[] { e.input },
                "Host name \"{0}\" is invalid!");
    } catch (InvalidHostException e) {
        bindingResult.rejectValue("hosts", "unknownHostName", new Object[] { e.input },
                "Host \"{0}\" is unknown!");
    }

    if (bindingResult.hasErrors()) {
        return new ModelAndView("page.new-connection").addObject("connection", model);
    }

    final ProfiledConnection connection;
    try {
        connection = getProfilerService().createConnection(model.getName(), configBuilder.toConfiguration());

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

        return new ModelAndView(new RedirectView(uri));

    } catch (InvalidConnectionNameException e) {
        bindingResult.rejectValue("name", "invalid", new Object[] { e.getName() },
                "The name \"{0}\" is invalid!");
        return new ModelAndView("page.new-connection").addObject("connection", model);
    }
}