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

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

Introduction

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

Prototype

public static UriComponentsBuilder fromUriString(String uri) 

Source Link

Document

Create a builder that is initialized with the given URI string.

Usage

From source file:com.nec.harvest.controller.SonekisController.java

/** {@inheritDoc} */
@Override/*ww  w.ja  v  a2  s  .c  o  m*/
@RequestMapping(value = "", method = RequestMethod.GET)
public String render(@SessionAttribute(Constants.SESS_ORGANIZATION_CODE) String userOrgCode,
        @SessionAttribute(Constants.SESS_BUSINESS_DAY) Date businessDay, @PathVariable String proGNo) {
    if (logger.isDebugEnabled()) {
        logger.debug("Redering sonekis page view without parameters...");
    }

    // Automatically build a redirect link
    UriComponents uriComponents = UriComponentsBuilder
            .fromUriString(Constants.SONEKIS_PATH + "/{orgCode}/{month}").build();
    String businessMonth = DateFormatUtil.format(businessDay, DateFormat.DATE_WITHOUT_DAY);
    URI uri = uriComponents.expand(proGNo, userOrgCode, businessMonth).encode().toUri();
    return "redirect:" + uri.toString();
}

From source file:org.workspace7.moviestore.utils.MovieDBHelper.java

/**
 * This method queries the external API and caches the movies, for the demo purpose we just query only first page
 *
 * @return - the status code of the invocation
 *///ww w  .  j  a v a 2  s. c  o  m
protected int queryAndCache() {

    if (this.moviesCache.isEmpty()) {

        log.info("No movies exist in cache, loading cache ..");

        UriComponentsBuilder moviesUri = UriComponentsBuilder
                .fromUriString(movieStoreProps.getApiEndpointUrl() + "/movie/popular")
                .queryParam("api_key", movieStoreProps.getApiKey());

        final URI requestUri = moviesUri.build().toUri();

        log.info("Request URI:{}", requestUri);

        ResponseEntity<String> response = restTemplate.getForEntity(requestUri, String.class);

        log.info("Response Status:{}", response.getStatusCode());

        Map<String, Movie> movieMap = new HashMap<>();

        if (200 == response.getStatusCode().value()) {
            String jsonBody = response.getBody();
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                JsonNode root = objectMapper.readTree(jsonBody);
                JsonNode results = root.path("results");
                results.elements().forEachRemaining(movieNode -> {
                    String id = movieNode.get("id").asText();
                    Movie movie = Movie.builder().id(id).overview(movieNode.get("overview").asText())
                            .popularity(movieNode.get("popularity").floatValue())
                            .posterPath("http://image.tmdb.org/t/p/w92" + movieNode.get("poster_path").asText())
                            .logoPath("http://image.tmdb.org/t/p/w45" + movieNode.get("poster_path").asText())
                            .title(movieNode.get("title").asText())
                            .price(ThreadLocalRandom.current().nextDouble(1.0, 10.0)).build();
                    movieMap.put(id, movie);
                });
            } catch (IOException e) {
                log.error("Error reading response:", e);
            }

            log.debug("Got {} movies", movieMap);
            moviesCache.putAll(movieMap);
        }
        return response.getStatusCode().value();
    } else {
        log.info("Cache already loaded with movies ... will use cache");
        return 200;
    }
}

From source file:info.joseluismartin.gtc.WmsCache.java

/**
 * {@inheritDoc}//from  w w w.j a v a2s.co  m
 * @throws IOException 
 */
@Override
public InputStream parseResponse(InputStream serverStream, String remoteUri, String localUri)
        throws IOException {
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(remoteUri);
    UriComponents remoteComponents = builder.build();
    String localUrl = localUri + "/" + getPath();

    InputStream is = serverStream;
    MultiValueMap<String, String> params = remoteComponents.getQueryParams();

    if (GET_CAPABILITIES.equals(params.getFirst(REQUEST))) {
        String response = IOUtils.toString(serverStream);

        Document doc = XMLUtils.newDocument(response);

        if (log.isDebugEnabled())
            XMLUtils.prettyDocumentToString(doc);

        // Fix GetMapUrl
        Element getMapElement = (Element) doc.getElementsByTagName(GET_MAP).item(0);
        if (getMapElement != null) {
            if (log.isDebugEnabled()) {
                log.debug("Found GetMapUrl: " + this.getMapUrl);
            }

            NodeList nl = getMapElement.getElementsByTagName(ONLINE_RESOURCE_ELEMENT);
            if (nl.getLength() > 0) {
                Element resource = (Element) nl.item(0);
                if (resource.hasAttributeNS(XLINK_NS, HREF_ATTRIBUTE)) {
                    this.getMapUrl = resource.getAttributeNS(XLINK_NS, HREF_ATTRIBUTE).replace("?", "");
                    resource.setAttributeNS(XLINK_NS, HREF_ATTRIBUTE, localUrl);
                }
            }
        }

        // Fix GetFeatureInfoUrl
        Element getFeatureElement = (Element) doc.getElementsByTagName(GET_FEATURE_INFO).item(0);
        if (getFeatureElement != null) {
            if (log.isDebugEnabled()) {
                log.debug("Found GetFeatureInfoUrl: " + this.getFeatureInfoUrl);
            }

            NodeList nl = getFeatureElement.getElementsByTagName(ONLINE_RESOURCE_ELEMENT);
            if (nl.getLength() > 0) {
                Element resource = (Element) nl.item(0);
                if (resource.hasAttributeNS(XLINK_NS, HREF_ATTRIBUTE)) {
                    this.getFeatureInfoUrl = resource.getAttributeNS(XLINK_NS, HREF_ATTRIBUTE).replace("?", "");
                    resource.setAttributeNS(XLINK_NS, HREF_ATTRIBUTE, localUrl);
                }
            }
        }

        response = XMLUtils.documentToString(doc);
        response = response.replaceAll(getServerUrl(), localUrl);
        //   response = "<?xml version='1.0' encoding='UTF-8'>" + response; 

        is = IOUtils.toInputStream(response);
    }

    return is;
}

From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderCleanerTests.java

@Test
public void testCleanStream() {
    final RabbitBindingCleaner cleaner = new RabbitBindingCleaner();
    final RestTemplate template = RabbitManagementUtils.buildRestTemplate("http://localhost:15672", "guest",
            "guest");
    final String stream1 = UUID.randomUUID().toString();
    String stream2 = stream1 + "-1";
    String firstQueue = null;/*from  ww  w.ja va 2  s  .  co m*/
    CachingConnectionFactory connectionFactory = rabbitWithMgmtEnabled.getResource();
    RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
    for (int i = 0; i < 5; i++) {
        String queue1Name = AbstractBinder.applyPrefix(BINDER_PREFIX, stream1 + ".default." + i);
        String queue2Name = AbstractBinder.applyPrefix(BINDER_PREFIX, stream2 + ".default." + i);
        if (firstQueue == null) {
            firstQueue = queue1Name;
        }
        URI uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues")
                .pathSegment("{vhost}", "{queue}").buildAndExpand("/", queue1Name).encode().toUri();
        template.put(uri, new AmqpQueue(false, true));
        uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues")
                .pathSegment("{vhost}", "{queue}").buildAndExpand("/", queue2Name).encode().toUri();
        template.put(uri, new AmqpQueue(false, true));
        uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues")
                .pathSegment("{vhost}", "{queue}")
                .buildAndExpand("/", AbstractBinder.constructDLQName(queue1Name)).encode().toUri();
        template.put(uri, new AmqpQueue(false, true));
        TopicExchange exchange = new TopicExchange(queue1Name);
        rabbitAdmin.declareExchange(exchange);
        rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(queue1Name)).to(exchange).with(queue1Name));
        exchange = new TopicExchange(queue2Name);
        rabbitAdmin.declareExchange(exchange);
        rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(queue2Name)).to(exchange).with(queue2Name));
    }
    final TopicExchange topic1 = new TopicExchange(
            AbstractBinder.applyPrefix(BINDER_PREFIX, stream1 + ".foo.bar"));
    rabbitAdmin.declareExchange(topic1);
    rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(firstQueue)).to(topic1).with("#"));
    String foreignQueue = UUID.randomUUID().toString();
    rabbitAdmin.declareQueue(new Queue(foreignQueue));
    rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(foreignQueue)).to(topic1).with("#"));
    final TopicExchange topic2 = new TopicExchange(
            AbstractBinder.applyPrefix(BINDER_PREFIX, stream2 + ".foo.bar"));
    rabbitAdmin.declareExchange(topic2);
    rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(firstQueue)).to(topic2).with("#"));
    new RabbitTemplate(connectionFactory).execute(new ChannelCallback<Void>() {

        @Override
        public Void doInRabbit(Channel channel) throws Exception {
            String queueName = AbstractBinder.applyPrefix(BINDER_PREFIX, stream1 + ".default." + 4);
            String consumerTag = channel.basicConsume(queueName, new DefaultConsumer(channel));
            try {
                waitForConsumerStateNot(queueName, 0);
                cleaner.clean(stream1, false);
                fail("Expected exception");
            } catch (RabbitAdminException e) {
                assertThat(e).hasMessageContaining("Queue " + queueName + " is in use");
            }
            channel.basicCancel(consumerTag);
            waitForConsumerStateNot(queueName, 1);
            try {
                cleaner.clean(stream1, false);
                fail("Expected exception");
            } catch (RabbitAdminException e) {
                assertThat(e).hasMessageContaining("Cannot delete exchange ");
                assertThat(e).hasMessageContaining("; it has bindings:");
            }
            return null;
        }

        private void waitForConsumerStateNot(String queueName, int state) throws InterruptedException {
            int n = 0;
            URI uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues")
                    .pathSegment("{vhost}", "{queue}").buildAndExpand("/", queueName).encode().toUri();
            while (n++ < 100) {
                @SuppressWarnings("unchecked")
                Map<String, Object> queueInfo = template.getForObject(uri, Map.class);
                if (!queueInfo.get("consumers").equals(Integer.valueOf(state))) {
                    break;
                }
                Thread.sleep(100);
            }
            assertThat(n < 100).withFailMessage("Consumer state remained at " + state + " after 10 seconds");
        }

    });
    rabbitAdmin.deleteExchange(topic1.getName()); // easier than deleting the binding
    rabbitAdmin.declareExchange(topic1);
    rabbitAdmin.deleteQueue(foreignQueue);
    connectionFactory.destroy();
    Map<String, List<String>> cleanedMap = cleaner.clean(stream1, false);
    assertThat(cleanedMap).hasSize(2);
    List<String> cleanedQueues = cleanedMap.get("queues");
    // should *not* clean stream2
    assertThat(cleanedQueues).hasSize(10);
    for (int i = 0; i < 5; i++) {
        assertThat(cleanedQueues.get(i * 2)).isEqualTo(BINDER_PREFIX + stream1 + ".default." + i);
        assertThat(cleanedQueues.get(i * 2 + 1)).isEqualTo(BINDER_PREFIX + stream1 + ".default." + i + ".dlq");
    }
    List<String> cleanedExchanges = cleanedMap.get("exchanges");
    assertThat(cleanedExchanges).hasSize(6);

    // wild card *should* clean stream2
    cleanedMap = cleaner.clean(stream1 + "*", false);
    assertThat(cleanedMap).hasSize(2);
    cleanedQueues = cleanedMap.get("queues");
    assertThat(cleanedQueues).hasSize(5);
    for (int i = 0; i < 5; i++) {
        assertThat(cleanedQueues.get(i)).isEqualTo(BINDER_PREFIX + stream2 + ".default." + i);
    }
    cleanedExchanges = cleanedMap.get("exchanges");
    assertThat(cleanedExchanges).hasSize(6);
}

From source file:org.lightadmin.core.config.StandardLightAdminConfiguration.java

@Override
public URI getApplicationRestBaseUrl() {
    return UriComponentsBuilder.fromUriString(LIGHT_ADMIN_REST_URL_DEFAULT).build().toUri();
}

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 . c  o  m*/

    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:tds.assessment.web.endpoints.AssessmentInfoControllerIntegrationTests.java

@Test
public void shouldReturnAssessmentInfo() throws Exception {
    final String clientName = "SBAC_PT";
    AssessmentInfo info1 = random(AssessmentInfo.class);
    AssessmentInfo info2 = random(AssessmentInfo.class);
    when(assessmentInfoService.findAssessmentInfo(clientName, info1.getKey(), info2.getKey()))
            .thenReturn(Arrays.asList(info1, info2));

    MvcResult result = http// ww  w . j a va  2 s.com
            .perform(get(UriComponentsBuilder.fromUriString("/SBAC_PT/assessments/").build().toUri())
                    .param("assessmentKeys", info1.getKey()).param("assessmentKeys", info2.getKey())
                    .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk()).andExpect(jsonPath("[0].key", is(info1.getKey())))
            .andExpect(jsonPath("[0].id", is(info1.getId())))
            .andExpect(jsonPath("[0].subject", is(info1.getSubject())))
            .andExpect(jsonPath("[0].grades", is(info1.getGrades())))
            .andExpect(jsonPath("[0].label", is(info1.getLabel())))
            .andExpect(jsonPath("[0].languages", is(info1.getLanguages())))
            .andExpect(jsonPath("[1].key", is(info2.getKey()))).andExpect(jsonPath("[1].id", is(info2.getId())))
            .andExpect(jsonPath("[1].subject", is(info2.getSubject())))
            .andExpect(jsonPath("[1].grades", is(info2.getGrades())))
            .andExpect(jsonPath("[1].label", is(info2.getLabel())))
            .andExpect(jsonPath("[1].languages", is(info2.getLanguages()))).andReturn();

    List<AssessmentInfo> parsedAssessments = objectMapper
            .readValue(result.getResponse().getContentAsByteArray(), new TypeReference<List<AssessmentInfo>>() {
            });
    assertThat(parsedAssessments.get(0)).isEqualTo(info1);
    assertThat(parsedAssessments.get(1)).isEqualTo(info2);
}

From source file:tds.assessment.web.endpoints.AccommodationControllerIntegrationTests.java

@Test
public void shouldFindAccommodationsByKey() throws Exception {
    Accommodation accommodation = new Accommodation.Builder().withDefaultAccommodation(true)
            .withAccommodationCode("code").withAccommodationType("type").withAccommodationValue("value")
            .withAllowChange(true).withDependsOnToolType("depends").withAllowCombine(false)
            .withDisableOnGuestSession(true).withEntryControl(false).withFunctional(true)
            .withSegmentPosition(99).withToolMode("toolMode").withToolTypeSortOrder(25)
            .withToolValueSortOrder(50).withVisible(true).build();

    when(mockAccommodationsService.findAccommodationsByAssessmentKey("SBAC", "key"))
            .thenReturn(singletonList(accommodation));
    String requestUri = UriComponentsBuilder.fromUriString("/SBAC/assessments/accommodations?assessmentKey=key")
            .build().toUriString();// www  .  java2  s . com

    http.perform(get(requestUri).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
            .andExpect(jsonPath("[0].defaultAccommodation", is(true)))
            .andExpect(jsonPath("[0].code", is("code"))).andExpect(jsonPath("[0].value", is("value")))
            .andExpect(jsonPath("[0].allowChange", is(true)))
            .andExpect(jsonPath("[0].dependsOnToolType", is("depends")))
            .andExpect(jsonPath("[0].allowCombine", is(false)))
            .andExpect(jsonPath("[0].disableOnGuestSession", is(true)))
            .andExpect(jsonPath("[0].entryControl", is(false))).andExpect(jsonPath("[0].functional", is(true)))
            .andExpect(jsonPath("[0].segmentPosition", is(99)))
            .andExpect(jsonPath("[0].toolMode", is("toolMode")))
            .andExpect(jsonPath("[0].toolTypeSortOrder", is(25)))
            .andExpect(jsonPath("[0].toolValueSortOrder", is(50))).andExpect(jsonPath("[0].visible", is(true)))
            .andExpect(jsonPath("[0].type", is("type")));
}

From source file:com.smartystreets.spring.SmartyStreetsAPI.java

private URI createURI(String uri) {

    return UriComponentsBuilder.fromUriString(uri).queryParam(AUTH_ID_KEY, authId)
            .queryParam(AUTH_TOKEN_KEY, apiToken).build().toUri();
}

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

/**
 * call ID lookup web service//  ww  w  . jav  a 2 s  . c  om
 * @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;
}