Example usage for org.springframework.web.util UriComponents toUri

List of usage examples for org.springframework.web.util UriComponents toUri

Introduction

In this page you can find the example usage for org.springframework.web.util UriComponents toUri.

Prototype

public abstract URI toUri();

Source Link

Document

Create a URI from this instance as follows:

If the current instance is #encode() encoded , form the full URI String via #toUriString() , and then pass it to the single argument URI constructor which preserves percent encoding.

Usage

From source file:org.devefx.httpmapper.binding.MapperMethod.java

private URI appendUrlParams(URI uri, MultiValueMap<String, Object> body) throws URISyntaxException {
    UriComponentsBuilder builder = UriComponentsBuilder.fromUri(uri);
    for (Map.Entry<String, List<Object>> entry : body.entrySet()) {
        String key = entry.getKey();
        for (Object value : entry.getValue()) {
            if (value instanceof String) {
                builder.queryParam(key, (String) value);
            }//ww  w. j  a  v a 2  s. c om
        }
    }
    UriComponents uriComponents = builder.build();
    return uriComponents.toUri();
}

From source file:net.longfalcon.newsj.service.GoogleSearchService.java

public GoogleSearchResponse search(String searchString, String referer) {
    try {//from ww w .  j a va 2 s .c  o  m
        if (ValidatorUtil.isNull(referer)) {
            referer = "http://longfalcon.net";
        }

        String v = "1.0";
        String userip = "192.168.0.1";
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Referer", referer);

        HttpEntity<?> requestEntity = new HttpEntity(httpHeaders);

        UriComponents uriComponents = UriComponentsBuilder.fromUriString(_SEARCH_URL).queryParam("v", v)
                .queryParam("q", searchString).queryParam("userip", userip).build();
        ResponseEntity<GoogleSearchResponse> responseEntity = restTemplate.exchange(uriComponents.toUri(),
                HttpMethod.GET, requestEntity, GoogleSearchResponse.class);
        HttpStatus statusCode = responseEntity.getStatusCode();
        if (statusCode.is2xxSuccessful() || statusCode.is3xxRedirection()) {
            return responseEntity.getBody();
        } else {
            _log.error(String.format("Search request: \n%s\n failed with HTTP code %s : %s",
                    uriComponents.toString(), statusCode.toString(), statusCode.getReasonPhrase()));
            return null;
        }
    } catch (Exception e) {
        _log.error(e);
    }

    return null;
}

From source file:org.avidj.zuul.rs.Zuul.java

/**
 * Release the given lock if it is held by the given {@code session}.
 * @param session the session id to release the lock for
 * @param request the request/*  w ww . j av a 2 s  . com*/
 * @param uriBuilder a builder for the response location header URI
 * @return {@code true}, iff the lock was released
 */
@RequestMapping(value = "/s/{id}/**", method = RequestMethod.DELETE)
public ResponseEntity<String> release(@PathVariable("id") String session, HttpServletRequest request,
        UriComponentsBuilder uriBuilder) {
    final List<String> path = getLockPath(request, session);

    final boolean deleted = lm.release(session, path);
    HttpStatus httpStatus = deleted ? HttpStatus.NO_CONTENT : HttpStatus.FORBIDDEN;

    UriComponents uriComponents = uriBuilder.path("/s/{id}/{lockPath}").buildAndExpand(session,
            Strings.join("/", path));
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(uriComponents.toUri());
    return new ResponseEntity<String>(headers, httpStatus);
}

From source file:org.avidj.zuul.rs.Zuul.java

/**
 * Obtain, upgrade, or downgrade a lock for the given {@code session}. Upgrades and downgrades are
 * possible along two dimensions: type and scope. Lock types are read ({@literal aka.} shared) and
 * write ({@literal aka.} exclusive). Lock scopes are shallow and deep. A shallow lock is only 
 * with respect to the specified lock path, a deep lock also locks the whole subtree below that 
 * path.//from  w w w. j  ava2 s.  c o  m
 * 
 * @param session the session to obtain a lock for 
 * @param type the type of lock to obtain, possible values are ({@code r})ead and 
 *     ({@code w})rite, default is ({@code w})write  
 * @param scope the scope of lock to obtain, possible values are ({@code s})shallow and 
 *     ({@code d})eep, default is ({@code d})eep  
 * @param request the HTTP request, provided by the REST framework
 * @param uriBuilder builder for the result location URI
 * @return {@code true}, iff the operation was successful
 */
@RequestMapping(value = "/s/{id}/**", method = { RequestMethod.POST, RequestMethod.PUT })
public ResponseEntity<String> lock(@PathVariable("id") String session,
        @RequestParam(value = "t", defaultValue = "w") String type,
        @RequestParam(value = "s", defaultValue = "s") String scope, HttpServletRequest request,
        UriComponentsBuilder uriBuilder) {
    // TODO: POST: lock (create resource)
    // TODO: PUT: upscope, downscope, lock reentry (return 226 IM used, return 404 as appropriate)
    final List<String> path = getLockPath(request, session);
    final LockType lockType = getLockType(type);
    final LockScope lockScope = getLockScope(scope);

    final boolean created = lm.lock(session, path, lockType, lockScope);
    HttpStatus httpStatus = created ? HttpStatus.CREATED : HttpStatus.FORBIDDEN;

    UriComponents uriComponents = uriBuilder.path("/s/{id}/{lockPath}").buildAndExpand(session,
            Strings.join("/", path));
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(uriComponents.toUri());
    return new ResponseEntity<String>(headers, httpStatus);
}

From source file:com.haulmont.restapi.controllers.EntitiesController.java

@PostMapping("/{entityName}")
public ResponseEntity<String> createEntity(@RequestBody String entityJson, @PathVariable String entityName,
        @RequestParam(required = false) String modelVersion, HttpServletRequest request) {
    CreatedEntityInfo entityInfo = entitiesControllerManager.createEntity(entityJson, entityName, modelVersion);

    UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(request.getRequestURL().toString())
            .path("/{id}").buildAndExpand(entityInfo.getId().toString());

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(uriComponents.toUri());
    return new ResponseEntity<>(entityInfo.getJson(), httpHeaders, HttpStatus.CREATED);
}

From source file:com.haulmont.restapi.controllers.FileUploadController.java

protected ResponseEntity<FileInfo> createFileInfoResponseEntity(HttpServletRequest request, FileDescriptor fd) {
    FileInfo fileInfo = new FileInfo(fd.getId(), fd.getName(), fd.getSize());

    UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(request.getRequestURL().toString())
            .path("/{id}").buildAndExpand(fd.getId().toString());

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(uriComponents.toUri());
    return new ResponseEntity<>(fileInfo, httpHeaders, HttpStatus.CREATED);
}

From source file:org.openmhealth.shim.withings.WithingsShim.java

URI createWithingsRequestUri(ShimDataRequest shimDataRequest, String userid,
        WithingsDataType withingsDataType) {

    MultiValueMap<String, String> dateTimeMap = new LinkedMultiValueMap<>();
    if (withingsDataType.usesUnixEpochSecondsDate || isPartnerAccessActivityMeasure(withingsDataType)) {
        //the partner access endpoints for activity also use epoch secs

        dateTimeMap.add("startdate", String.valueOf(shimDataRequest.getStartDateTime().toEpochSecond()));
        dateTimeMap.add("enddate",
                String.valueOf(shimDataRequest.getEndDateTime().plusDays(1).toEpochSecond()));
    } else {//www .  java 2  s. c o m
        dateTimeMap.add("startdateymd", shimDataRequest.getStartDateTime().toLocalDate().toString());
        dateTimeMap.add("enddateymd", shimDataRequest.getEndDateTime().toLocalDate().toString());

    }

    UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(DATA_URL)
            .pathSegment(withingsDataType.getEndpoint());
    String measureParameter;
    if (isPartnerAccessActivityMeasure(withingsDataType)) {
        // partner level access allows greater detail around activity, but uses a different endpoint
        measureParameter = PARTNER_ACCESS_ACTIVITY_ENDPOINT;
    } else {
        measureParameter = withingsDataType.getMeasureParameter();
    }
    uriComponentsBuilder.queryParam("action", measureParameter).queryParam("userid", userid)
            .queryParams(dateTimeMap);

    // if it's a body measure
    if (Objects.equals(withingsDataType.getMeasureParameter(), "getmeas")) {

        /*
        The Withings API allows us to query for single body measures, which we take advantage of to reduce
        unnecessary data transfer. However, since blood pressure is represented as two separate measures,
        namely a diastolic and a systolic measure, when the measure type is blood pressure we ask for all
        measures and then filter out the ones we don't care about.
         */
        if (withingsDataType != WithingsDataType.BLOOD_PRESSURE) {

            WithingsBodyMeasureType measureType = WithingsBodyMeasureType.valueOf(withingsDataType.name());
            uriComponentsBuilder.queryParam("meastype", measureType.getMagicNumber());
        }

        uriComponentsBuilder.queryParam("category", 1); //filter out goal datapoints

    }

    UriComponents uriComponents = uriComponentsBuilder.build();
    return uriComponents.toUri();

}

From source file:net.longfalcon.newsj.service.TmdbService.java

public TmdbFindResults findResultsByImdbId(int imdbId) {
    try {/*from  ww  w  .ja va  2 s.co  m*/
        String tmdbUrlBase = config.getTmdbApiUrl();
        String apiKey = config.getDefaultSite().getTmdbKey();

        HttpHeaders httpHeaders = new HttpHeaders();
        HttpEntity<?> requestEntity = new HttpEntity(httpHeaders);

        UriComponents uriComponents = UriComponentsBuilder
                .fromUriString(tmdbUrlBase + "/find/tt" + String.format("%07d", imdbId))
                .queryParam("external_source", "imdb_id").queryParam("api_key", apiKey).build();
        ResponseEntity<TmdbFindResults> responseEntity = restTemplate.exchange(uriComponents.toUri(),
                HttpMethod.GET, requestEntity, TmdbFindResults.class);
        HttpStatus statusCode = responseEntity.getStatusCode();
        if (statusCode.is2xxSuccessful() || statusCode.is3xxRedirection()) {
            return responseEntity.getBody();
        } else {
            _log.error(String.format("Search request: \n%s\n failed with HTTP code %s : %s",
                    uriComponents.toString(), statusCode.toString(), statusCode.getReasonPhrase()));
            return null;
        }

    } catch (Exception e) {
        _log.error(e.toString(), e);
    }
    return null;
}

From source file:ch.heigvd.gamification.api.BadgesEndpoint.java

@Override
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Void> badgesPost(
        @ApiParam(value = "Badge to add", required = true) @RequestBody BadgeDTO body,
        @ApiParam(value = "token that identifies the app sending the request", required = true) @RequestHeader(value = "X-Gamification-Token", required = true) String xGamificationToken) {
    AuthenKey apiKey = authenKeyRepository.findByAppKey(xGamificationToken);

    if (apiKey == null) {
        return new ResponseEntity(HttpStatus.UNAUTHORIZED);
    }//from ww  w . j  a  v a  2 s.c  o m

    Application app = apiKey.getApp();

    if (body != null && app != null) {

        if (badgeRepository.findByNameAndApp(body.getName(), app) != null) {
            return new ResponseEntity("name already use", HttpStatus.UNPROCESSABLE_ENTITY);
        }
        Badge badge = new Badge();
        badge.setDescription(body.getDescription());
        badge.setName(body.getName());
        badge.setImage(body.getImageURI());
        badge.setApp(app);
        badgeRepository.save(badge);

        HttpHeaders responseHeaders = new HttpHeaders();

        UriComponents uriComponents = MvcUriComponentsBuilder
                .fromMethodName(BadgesEndpoint.class, "badgesBadgeIdGet", 1, badge.getId()).build();

        URI locationUri = uriComponents.toUri();
        responseHeaders.add("Location", uriComponents.toString());
        return new ResponseEntity<>(responseHeaders, HttpStatus.CREATED);

    } else {
        return new ResponseEntity("no content is available", HttpStatus.BAD_REQUEST);
    }
}

From source file:net.longfalcon.newsj.service.TraktService.java

/**
 * call ID lookup web service/*from  w w  w. j  a v  a2 s . c  o  m*/
 * @param id     id to look up that matches the id type. String to allow imdb queries "ttxxxxxx"
 * @param idType Possible values:  trakt-movie , trakt-show , trakt-episode , imdb , tmdb , tvdb , tvrage .
 * @return
 */
protected TraktResult[] searchById(String id, String idType) {
    try {
        String traktApiUrl = config.getTraktApiUrl();
        String traktAppId = config.getTraktAppId();

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Content-type", "application/json");
        httpHeaders.set("trakt-api-key", traktAppId);
        httpHeaders.set("trakt-api-version", "2");
        HttpEntity<?> requestEntity = new HttpEntity(httpHeaders);

        UriComponents uriComponents = UriComponentsBuilder.fromUriString(traktApiUrl + "/search")
                .queryParam("id_type", idType).queryParam("id", id).build();
        ResponseEntity<TraktResult[]> responseEntity = restTemplate.exchange(uriComponents.toUri(),
                HttpMethod.GET, requestEntity, TraktResult[].class);
        HttpStatus statusCode = responseEntity.getStatusCode();
        if (statusCode.is2xxSuccessful() || statusCode.is3xxRedirection()) {
            return responseEntity.getBody();
        } else {
            _log.error(String.format("Trakt Search request: \n%s\n failed with HTTP code %s : %s",
                    uriComponents.toString(), statusCode.toString(), statusCode.getReasonPhrase()));
            return null;
        }

    } catch (Exception e) {
        _log.error(e.toString(), e);
    }
    return null;
}