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

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

Introduction

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

Prototype

@Override
public final String toString() 

Source Link

Document

A simple pass-through to #toUriString() .

Usage

From source file:org.wallride.job.UpdatePostViewsItemWriter.java

@Override
public void write(List<? extends List> items) throws Exception {
    WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext,
            "org.springframework.web.servlet.FrameworkServlet.CONTEXT.guestServlet");
    if (context == null) {
        throw new ServiceException("GuestServlet is not ready yet");
    }/*from ww w  . jav a  2 s  .  com*/

    final RequestMappingHandlerMapping mapping = context.getBean(RequestMappingHandlerMapping.class);

    for (List item : items) {
        UriComponents uriComponents = UriComponentsBuilder.fromUriString((String) item.get(0)).build();
        logger.info("Processing [{}]", uriComponents.toString());

        MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
        request.setMethod("GET");
        request.setRequestURI(uriComponents.getPath());
        request.setQueryString(uriComponents.getQuery());
        MockHttpServletResponse response = new MockHttpServletResponse();

        BlogLanguageRewriteRule rewriteRule = new BlogLanguageRewriteRule(blogService);
        BlogLanguageRewriteMatch rewriteMatch = (BlogLanguageRewriteMatch) rewriteRule.matches(request,
                response);
        try {
            rewriteMatch.execute(request, response);
        } catch (ServletException e) {
            throw new ServiceException(e);
        } catch (IOException e) {
            throw new ServiceException(e);
        }

        request.setRequestURI(rewriteMatch.getMatchingUrl());

        HandlerExecutionChain handler;
        try {
            handler = mapping.getHandler(request);
        } catch (Exception e) {
            throw new ServiceException(e);
        }

        if (!(handler.getHandler() instanceof HandlerMethod)) {
            continue;
        }

        HandlerMethod method = (HandlerMethod) handler.getHandler();
        if (!method.getBeanType().equals(ArticleDescribeController.class)
                && !method.getBeanType().equals(PageDescribeController.class)) {
            continue;
        }

        // Last path mean code of post
        String code = uriComponents.getPathSegments().get(uriComponents.getPathSegments().size() - 1);
        Post post = postRepository.findOneByCodeAndLanguage(code, rewriteMatch.getBlogLanguage().getLanguage());
        if (post == null) {
            logger.debug("Post not found [{}]", code);
            continue;
        }

        logger.info("Update the PageView. Post ID [{}]: {} -> {}", post.getId(), post.getViews(), item.get(1));
        post.setViews(Long.parseLong((String) item.get(1)));
        postRepository.saveAndFlush(post);
    }
}

From source file:org.moserp.infrastructure.gateway.filter.ResponseLinksMapper.java

Object fixLink(Object value) {
    if (!(value instanceof String)) {
        return value;
    }// w ww.  ja  va  2s .  c  o m
    String href = (String) value;
    Matcher urlWithServiceNameMatcher = urlWithServiceNamePattern.matcher(href);
    Matcher standardUrlMatcher = standardUrlPattern.matcher(href);
    if (!standardUrlMatcher.matches() && urlWithServiceNameMatcher.matches()) {
        String possibleServiceName = urlWithServiceNameMatcher.group(1);
        log.debug("Possible service name: " + possibleServiceName);
        if (services.contains(possibleServiceName)) {
            log.debug("Service found");
            String gatewayPath = serviceRouteMapper.apply(possibleServiceName);
            String originalRestPath = urlWithServiceNameMatcher.group(2);
            ServletUriComponentsBuilder servletUriComponentsBuilder = ServletUriComponentsBuilder
                    .fromCurrentRequest();
            UriComponents uriComponents = servletUriComponentsBuilder.replacePath(gatewayPath)
                    .path(originalRestPath).build();
            log.debug("Mapping " + value + " to " + uriComponents);
            return uriComponents.toString();
        }
    }
    return href;
}

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

public ApplicationDTO toDTO(Application app, UriComponents uriComponents) {

    ApplicationDTO dto = new ApplicationDTO();
    List<String> urls = new ArrayList<>();
    app.getBadges().stream().forEach((badge) -> {
        urls.add(uriComponents.toString() + badge.getId());
    });/*from  w  ww  .j a  va 2s . c  o m*/
    dto.setBadges(urls);
    dto.setId(app.getId());
    dto.setApplicationName(app.getName());

    return dto;

}

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 w  w  w  .j a v  a2 s.com

    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.GoogleSearchService.java

public GoogleSearchResponse search(String searchString, String referer) {
    try {/*from   w  w w. ja  va 2 s . com*/
        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:net.longfalcon.newsj.service.TmdbService.java

public TmdbFindResults findResultsByImdbId(int imdbId) {
    try {//from w w w .j ava 2s  .  c o  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:net.longfalcon.newsj.service.TraktService.java

/**
 * call ID lookup web service/* w w  w  .  j  a v a 2s. 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;
}

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

/**
 * call text search web service/*from   w  w  w.j  a  va2  s.  c om*/
 * @param name
 * @param type  Possible values:  movie , show , episode , person , list .
 * @return
 */
protected TraktResult[] searchByName(String name, String type) {
    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("query", name).queryParam("type", type).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;
}

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

public TraktEpisodeResult getEpisode(long traktId, int season, int episode) {
    try {//from w ww . j  a v  a  2 s  .com
        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 + "/shows/" + traktId + "/seasons/" + season + "/episodes/" + episode)
                .queryParam("extended", "full").build();
        ResponseEntity<TraktEpisodeResult> responseEntity = restTemplate.exchange(uriComponents.toUri(),
                HttpMethod.GET, requestEntity, TraktEpisodeResult.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;
}

From source file:sg.ncl.MainController.java

@RequestMapping(value = "/web_vnc/access_node/{teamName}/{expId}/{nodeId}", params = { "portNum" })
public String vncAccessNode(Model model, HttpSession session, RedirectAttributes redirectAttributes,
        @PathVariable String teamName, @PathVariable Long expId, @PathVariable String nodeId,
        @NotNull @RequestParam("portNum") Integer portNum)
        throws WebServiceRuntimeException, NoSuchAlgorithmException {
    Realization realization = invokeAndExtractRealization(teamName, expId);
    if (!checkPermissionRealizeExperiment(realization, session)) {
        log.warn("Permission denied to access experiment {} node for team: {}", realization.getExperimentName(),
                teamName);//  ww w  .j  av  a2 s . co  m
        redirectAttributes.addFlashAttribute(MESSAGE, permissionDeniedMessage);
        return REDIRECT_EXPERIMENTS;
    }
    HttpEntity<String> request = createHttpEntityHeaderOnly();
    ResponseEntity response = restTemplate.exchange(properties.getStatefulExperiment(expId.toString()),
            HttpMethod.GET, request, String.class);
    StatefulExperiment statefulExperiment = extractStatefulExperiment(response.getBody().toString());
    getDeterUid(model, session);
    Map attributes = model.asMap();
    UriComponents uriComponents = UriComponentsBuilder.fromUriString(vncProperties.getHttp())
            .queryParam("host", vncProperties.getHost())
            .queryParam("path", qencode(getNodeQualifiedName(statefulExperiment, nodeId) + ":" + portNum,
                    (String) attributes.get(DETER_UID)))
            .build();
    log.info("VNC URI: {}", uriComponents.toString());
    return "redirect:" + uriComponents.toString();
}