Java Examples for org.springframework.web.client.RestTemplate

The following java examples will help you to understand the usage of org.springframework.web.client.RestTemplate. These source code samples are taken from different open source projects.

Example 1
Project: spring-guides-master  File: Application.java View source code
private static List<String> searchTwitter(String query, String appToken) {
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add("Authorization", "Bearer " + appToken);
    HttpEntity<String> httpEntity = new HttpEntity<>("", httpHeaders);
    Map result = restTemplate.exchange("https://api.twitter.com/1.1/search/tweets.json?q={query}", HttpMethod.GET, httpEntity, Map.class, query).getBody();
    List<Map<String, String>> statuses = (List<Map<String, String>>) result.get("statuses");
    return statuses.stream().map( status -> status.get("text")).collect(Collectors.toList());
}
Example 2
Project: building-microservices-master  File: BasicSecurityApplicationTests.java View source code
@Test
public void contextLoaded() throws Throwable {
    RestTemplate restTemplate = this.restTemplateBuilder.basicAuthorization("pwebb", "boot").build();
    ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:" + this.port + "/hi", String.class);
    assertThat(response.getBody()).containsIgnoringCase("hello, pwebb");
    System.out.println("received: " + response.getBody());
}
Example 3
Project: compose-idm-master  File: PolicyManager.java View source code
public List<Map<String, Object>> getPolicyForNewServiceObject(String ownerId, ServiceObject serviceObject) throws IdManagementException {
    String url = this.pipUrl + pipGetNewPolicy;
    Map<String, Object> map = new HashMap<>();
    map.put("entityType", "SO");
    map.put("entityId", serviceObject.getId());
    map.put("private", true);
    map.put("ownerId", ownerId);
    HttpEntity<Map> getPolicy = new HttpEntity(map);
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<Object> responseEntity = null;
    try {
        responseEntity = restTemplate.exchange(url, HttpMethod.POST, getPolicy, Object.class);
        LinkedHashMap<String, Object> policyResponse = (LinkedHashMap<String, Object>) responseEntity.getBody();
        if (responseEntity.getStatusCode().equals(HttpStatus.OK))
            return (List<Map<String, Object>>) policyResponse.get("policy");
        else
            throw new IdManagementException("Unexpected http response value when getting policy for the service object ", null, LOG, "Unexpected error code :" + responseEntity.getStatusCode().toString() + " for the Service Object policy when accessing the Pip in the url: " + url + " after HTTP communication with " + url + " with owner id:" + ownerId + " and service object id: " + serviceObject.getId(), Level.ERROR, (responseEntity == null ? 500 : responseEntity.getStatusCode().value()));
    } catch (Exception ex) {
        throw new IdManagementException("An error ocurred while getting policy for the service object", null, LOG, "An error ocurred trying to access the Pip in the url: " + url + " after HTTP communication with " + url + " with owner id:" + ownerId + " and service object id: " + serviceObject.getId(), Level.ERROR, (responseEntity == null ? 500 : responseEntity.getStatusCode().value()));
    }
}
Example 4
Project: eventuate-master  File: RestaurantsIntegrationTestConfiguration.java View source code
@Bean
public RestTemplate restTemplate(HttpMessageConverters converters) {
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {

        @Override
        protected boolean hasError(HttpStatus statusCode) {
            return statusCode != HttpStatus.NOT_FOUND && super.hasError(statusCode);
        }
    });
    List<? extends HttpMessageConverter<?>> httpMessageConverters = Collections.singletonList(new MappingJackson2HttpMessageConverter());
    restTemplate.setMessageConverters((List<HttpMessageConverter<?>>) httpMessageConverters);
    return restTemplate;
}
Example 5
Project: osm-tools-master  File: TestUtils.java View source code
public static MockRestServiceServer prepareRestTemplateForState(RestTemplate restTemplate, String granularity) {
    MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(MediaType.APPLICATION_XML);
    mockServer.expect(RequestMatchers.requestTo("http://planet.openstreetmap.org/replication/" + granularity + "/state.txt")).andExpect(RequestMatchers.method(HttpMethod.GET)).andRespond(ResponseCreators.withResponse("#Fri Sep 13 20:02:08 UTC 2013\r\n" + "sequenceNumber=8797\r\n" + "timestamp=2013-09-13T20\\:00\\:00Z", responseHeaders));
    return mockServer;
}
Example 6
Project: spring-data-document-examples-master  File: RestTemplateActivity.java View source code
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    TextView view = new TextView(this);
    view.append("Running tests...\n\n");
    setContentView(view);
    try {
        List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
        converters.add(new MappingJacksonHttpMessageConverter());
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setMessageConverters(converters);
        Map response = restTemplate.getForObject("http://127.0.0.1:5984", Map.class);
        view.append(response.toString());
        /*
			URL url = new URL("http:/127.0.0.1:5984");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			List<String> lines= new ArrayList<String>();
			while((line = reader.readLine()) != null){
			    lines.add(line);
			}
			reader.close();
			view.append(lines.toString());*/
        view.append("all ok!");
    } catch (Exception e) {
        view.append(e.toString());
        Log.e("rest-template", "this is bad", e);
    }
}
Example 7
Project: spring-framework-issues-master  File: AsyncrestremplatebugApplicationTests.java View source code
@Test
public void testRestTemplate() throws Exception {
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    String authHeader = "Basic " + new String(Base64.getEncoder().encode(("user:password").getBytes()));
    headers.add(AUTHORIZATION, authHeader);
    ResponseEntity<String> resp = restTemplate.exchange("http://localhost:8080/sleepingendpoint", GET, new HttpEntity<String>(headers), String.class);
    assertTrue(resp.getStatusCode().is2xxSuccessful());
}
Example 8
Project: spring-social-slideshare-master  File: AbstractSlideshareTemplateTest.java View source code
@Before
public void setUp() {
    SlideShareTemplate slideShareTemplate = new SlideShareTemplate("key", "secret");
    RestTemplate restTemplate = slideShareTemplate.getRestTemplate();
    mockServer = MockRestServiceServer.createServer(restTemplate);
    // creating mockServer replaces RequestFactory in restTemplate to RequestMatcherClientHttpRequestFactory.
    // in order to support multiple reads in test, re-wrap the mock requestFactory and set to restTemplate.
    restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(restTemplate.getRequestFactory()));
    slideshowOperations = slideShareTemplate.slideshowOperations();
}
Example 9
Project: spring4-showcase-master  File: AbstractClientTest.java View source code
@Before
public void setUp() throws Exception {
    //需�添加jackson jar包
    objectMapper = new ObjectMapper();
    //需�添加jaxb2实现(如xstream)
    marshaller = new Jaxb2Marshaller();
    marshaller.setPackagesToScan(new String[] { "com.sishuok" });
    marshaller.afterPropertiesSet();
    restTemplate = new RestTemplate();
}
Example 10
Project: transgalactica-master  File: RestTemplateConfig.java View source code
@Bean
public RestTemplate getRestTemplate() {
    // credential
    Credentials credentials = new UsernamePasswordCredentials(restUsername, restPassword);
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, credentials);
    // accept header
    HttpRequestInterceptor acceptHeaderInterceptor = ( request,  context) -> request.addHeader("Accept", "application/xml");
    // build client
    HttpClient client = //
    HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider//
    ).addInterceptorFirst(acceptHeaderInterceptor).build();
    return new RestTemplate(new HttpComponentsClientHttpRequestFactory(client));
}
Example 11
Project: BikeMan-master  File: PsInterfaceConfiguration.java View source code
@Bean
public RestTemplate restTemplate() {
    List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
    interceptors.add(new ClientLogInterceptor());
    RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));
    restTemplate.setInterceptors(interceptors);
    return restTemplate;
}
Example 12
Project: callerid-for-android-master  File: CallerIDModule.java View source code
@Override
protected void configure() {
    bind(String.class).annotatedWith(SharedPreferencesName.class).toProvider(PreferencesNameProvider.class).in(Scopes.SINGLETON);
    bind(ContactsHelper.class).toProvider(ContactsHelperProvider.class).in(Scopes.SINGLETON);
    bind(CallerIDLookup.class).to(HttpCallerIDLookup.class).in(Scopes.SINGLETON);
    bind(Geocoder.class).toProvider(GeocoderHelperProvider.class).in(Scopes.SINGLETON);
    bind(NominatimGeocoder.class).in(Scopes.SINGLETON);
    bind(VersionInformationHelper.class).in(Scopes.SINGLETON);
    bind(TextToSpeechHelper.class).in(Scopes.SINGLETON);
    bind(CountryDetector.class).in(Scopes.SINGLETON);
    final ObjectMapper jsonObjectMapper = new ObjectMapper();
    jsonObjectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    bind(ObjectMapper.class).annotatedWith(Names.named(("jsonObjectMapper"))).toInstance(jsonObjectMapper);
    bind(RestTemplate.class).toProvider(RestTemplateProvider.class).in(Scopes.SINGLETON);
}
Example 13
Project: deprecate-tut-rest-master  File: OrderTests.java View source code
@Test
public void thatOrdersCannotBeAddedAndQueriedWithBadUser() {
    HttpEntity<String> requestEntity = new HttpEntity<String>(RestDataFixture.standardOrderJSON(), getHeaders("letsnosh" + ":" + "BADPASSWORD"));
    RestTemplate template = new RestTemplate();
    try {
        ResponseEntity<Order> entity = template.postForEntity("http://localhost:8080/aggregators/orders", requestEntity, Order.class);
        fail("Request Passed incorrectly with status " + entity.getStatusCode());
    } catch (HttpClientErrorException ex) {
        assertEquals(HttpStatus.UNAUTHORIZED, ex.getStatusCode());
    }
}
Example 14
Project: OpenETSMobile2-master  File: MyJackSpringAndroidSpiceService.java View source code
@Override
public RestTemplate createRestTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    // Set Converters
    final MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
    final List<HttpMessageConverter<?>> listHttpMessageConverters = restTemplate.getMessageConverters();
    listHttpMessageConverters.add(jsonConverter);
    restTemplate.setMessageConverters(listHttpMessageConverters);
    return restTemplate;
}
Example 15
Project: robospice-master  File: XmlSpringAndroidSpiceService.java View source code
@Override
public RestTemplate createRestTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    // web services support xml responses
    SimpleXmlHttpMessageConverter jsonConverter = new SimpleXmlHttpMessageConverter();
    final List<HttpMessageConverter<?>> listHttpMessageConverters = restTemplate.getMessageConverters();
    listHttpMessageConverters.add(jsonConverter);
    restTemplate.setMessageConverters(listHttpMessageConverters);
    return restTemplate;
}
Example 16
Project: sagan-master  File: BasicAcceptanceTests.java View source code
private RestTemplate getRestTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {

        @Override
        public boolean hasError(ClientHttpResponse response) throws IOException {
            return false;
        }
    });
    return restTemplate;
}
Example 17
Project: spring-for-android-starter-book-master  File: MainActivity.java View source code
@Override
protected Channel doInBackground(String... params) {
    RestTemplate restTemplate = new RestTemplate();
    // Configure the RSS message converter.
    RssChannelHttpMessageConverter rssChannelConverter = new RssChannelHttpMessageConverter();
    rssChannelConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.TEXT_XML));
    // Add the RSS message converter to the RestTemplate instance
    restTemplate.getMessageConverters().add(rssChannelConverter);
    // Make the HTTP GET request on the url (params[0]), marshaling the response to a String
    return restTemplate.getForObject(params[0], Channel.class);
}
Example 18
Project: javamelody-master  File: TestSpringRestTemplateInterceptor.java View source code
/** Test. */
@Test
public void testSpringAOP() {
    final Counter springCounter = MonitoringProxy.getSpringCounter();
    springCounter.clear();
    final ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { MONITORING_CONTEXT_FILENAME, TEST_CONTEXT_FILENAME });
    final RestTemplate restTemplate = context.getBean(RestTemplate.class);
    final String url = "https://gturnquist-quoters.cfapps.io/api/random";
    springCounter.setDisplayed(false);
    try {
        restTemplate.getForObject(url, Object.class);
    } catch (final RestClientException e) {
        assertSame("requestsCount", 0, springCounter.getRequestsCount());
    }
    springCounter.setDisplayed(true);
    try {
        restTemplate.getForObject(url, Object.class);
    } catch (final RestClientException e) {
        assertSame("requestsCount", 1, springCounter.getRequestsCount());
    }
    try {
        restTemplate.getForObject(url + "?var={0}", Object.class, "var value");
    } catch (final RestClientException e) {
        assertSame("requestsCount", 1, springCounter.getRequestsCount());
    }
}
Example 19
Project: restler-master  File: SpringDataSupport.java View source code
private RequestExecutor createExecutor() {
    RestTemplate restTemplate = new RestTemplate();
    List<MappingJackson2HttpMessageConverter> jacksonConverters = restTemplate.getMessageConverters().stream().filter( converter -> converter instanceof MappingJackson2HttpMessageConverter).map( converter -> (MappingJackson2HttpMessageConverter) converter).collect(Collectors.toList());
    jacksonModules.stream().forEach( module -> jacksonConverters.forEach( converter -> converter.getObjectMapper().registerModule(module)));
    restTemplate.getMessageConverters().add(0, new SpringDataRestMessageConverter());
    return new SpringMvcRequestExecutor(restTemplate);
}
Example 20
Project: androidannotations-master  File: HttpMethodServiceTest.java View source code
@Test
public void useDeleteHttpMethod() {
    HttpMethodsService_ service = new HttpMethodsService_(null);
    RestTemplate restTemplate = mock(RestTemplate.class);
    service.setRestTemplate(restTemplate);
    service.delete();
    verify(restTemplate).exchange(Matchers.anyString(), Matchers.<HttpMethod>eq(HttpMethod.DELETE), Matchers.<HttpEntity<?>>any(), Matchers.<Class<Object>>any());
}
Example 21
Project: apollo-master  File: RestTemplateFactory.java View source code
public void afterPropertiesSet() throws UnsupportedEncodingException {
    Collection<Header> defaultHeaders = new ArrayList<Header>();
    Header header = new BasicHeader("Authorization", "Basic " + BaseEncoding.base64().encode("apollo:".getBytes("UTF-8")));
    defaultHeaders.add(header);
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("apollo", ""));
    CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).setDefaultHeaders(defaultHeaders).build();
    restTemplate = new RestTemplate(httpMessageConverters.getConverters());
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
    requestFactory.setConnectTimeout(portalConfig.connectTimeout());
    requestFactory.setReadTimeout(portalConfig.readTimeout());
    restTemplate.setRequestFactory(requestFactory);
}
Example 22
Project: booties-master  File: TwintipCustomProfileApplicationIT.java View source code
@Test
public void isConfigured() {
    String endpointUrl = "http://localhost:" + port + "/.well-known/schema-discovery";
    LOG.info("ENDPOINT_URL : {}", endpointUrl);
    RestTemplate template = new RestTemplate();
    ResponseEntity<String> entity = template.getForEntity(endpointUrl, String.class);
    HttpStatus statusCode = entity.getStatusCode();
    String body = entity.getBody();
    Assertions.assertThat(statusCode).isEqualTo(HttpStatus.OK);
    Assertions.assertThat(body).contains("swagger-unreleased");
    LOG.info("BODY : {}", body);
}
Example 23
Project: btpka3.github.com-master  File: MyController.java View source code
@RequestMapping("/testProxy")
public // 这些��控制的注解也�以应用到接�上
String testProxy(Map<String, Object> modelMap, Principal principal) throws UnsupportedEncodingException {
    RestTemplate rest = new RestTemplate();
    rest.setErrorHandler(new ResponseErrorHandler() {

        public boolean hasError(ClientHttpResponse response) throws IOException {
            return false;
        }

        public void handleError(ClientHttpResponse response) throws IOException {
        }
    });
    CasAuthenticationToken token = null;
    if (principal instanceof CasAuthenticationToken) {
        token = (CasAuthenticationToken) principal;
    }
    // FIXME : Why SecurityContextHolder.getContext().getPrincipal() != httpServletRequest.getUserPrincipal();
    // Actually is User != CasAuthenticationToken
    // 调用 appointment �务
    String appointmentServiceUrl = appointmentUrl;
    if (token != null) {
        String proxyTicket = token.getAssertion().getPrincipal().getProxyTicketFor(appointmentUrl);
        appointmentServiceUrl = appointmentUrl + "?ticket=" + URLEncoder.encode(proxyTicket, "UTF-8");
    }
    ResponseEntity<String> respEntity = rest.getForEntity(appointmentServiceUrl, String.class);
    modelMap.put("appointmentServiceUrl", appointmentServiceUrl);
    modelMap.put("appointmentServiceRespCode", respEntity.getStatusCode().value());
    modelMap.put("appointmentServiceResp", respEntity.getBody());
    // 使用�一个 ProxyToken 应当会失败
    if (token != null) {
        respEntity = rest.getForEntity(appointmentServiceUrl, String.class);
        HttpStatus status = respEntity.getStatusCode();
        if (HttpStatus.OK.equals(respEntity.getStatusCode())) {
            // 测试�现,实际还是会�功的,若间隔一段时间之�,手工copy该URL,并在�览器中使用,会403
            // 貌似ProxyToken �是说使用一次之�就失效,而是有个很短的时间内�有效。
            // 原因:使用了Ehcache的缘故
            logger.error("Second call service with same proxy ticket should faild, but success with response code " + status + ", content =\n" + respEntity.getBody());
        } else {
            logger.info("Second call service with same proxy ticket should failded with response code " + status + ", content =\n" + respEntity.getBody());
        }
    }
    // 调用 staff �务
    String staffServiceUrl = staffUrl;
    if (token != null) {
        String proxyTicket = token.getAssertion().getPrincipal().getProxyTicketFor(staffUrl);
        staffServiceUrl = staffUrl + "?ticket=" + URLEncoder.encode(proxyTicket, "UTF-8");
    }
    respEntity = rest.getForEntity(staffServiceUrl, String.class);
    modelMap.put("staffServiceUrl", staffServiceUrl);
    modelMap.put("staffServiceRespCode", respEntity.getStatusCode().value());
    modelMap.put("staffServiceResp", respEntity.getBody());
    return "testProxy";
}
Example 24
Project: cas-master  File: CasRestAuthenticationConfiguration.java View source code
@Bean
@RefreshScope
public RestTemplate restAuthenticationTemplate() {
    try {
        final URI casHost = new URI(casProperties.getServer().getName());
        final HttpHost host = new HttpHost(casHost.getHost(), casHost.getPort(), casHost.getScheme());
        final ClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactoryBasicAuth(host);
        return new RestTemplate(factory);
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}
Example 25
Project: cats-master  File: DomainServiceConfiguration.java View source code
/**
     * To get rest template.
     * 
     * @return RestTemplate
     */
@Bean
public RestTemplate getRestTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
    messageConverters.add(new JaxbSerializedHttpMessageConverter<T>());
    messageConverters.add(new JaxbListHttpMessageConverter());
    messageConverters.add(new StringHttpMessageConverter());
    restTemplate.setMessageConverters(messageConverters);
    return restTemplate;
}
Example 26
Project: Google-I-O-extended-master  File: BaseGet.java View source code
@Override
public T performRequest() {
    HttpEntity<T> requestEntity = new HttpEntity<>(getHeaders());
    RestTemplate restTemplate = getRestTemplate();
    ResponseEntity<T> requestResult = restTemplate.exchange(getUrl(), HttpMethod.GET, requestEntity, getResponseClass());
    T result = requestResult.getBody();
    return result;
}
Example 27
Project: intermine-android-master  File: CreateGenesList.java View source code
@Override
public Void loadDataFromNetwork() throws Exception {
    RestTemplate rtp = getRestTemplate();
    HttpHeaders headers = getHeaders();
    String uriString = getUrl();
    Map<String, ?> params = getUrlParams();
    String post = generateBody();
    HttpEntity<?> req;
    if (null != post) {
        req = new HttpEntity<Object>(post, headers);
    } else {
        req = new HttpEntity<String>(headers);
    }
    ResponseEntity<String> res;
    String uri = Uris.expandQuery(uriString, params);
    rtp.exchange(uri, POST, req, String.class);
    return null;
}
Example 28
Project: j360-boot-master  File: SessionRedisApplicationTests.java View source code
@Test
public void sessionExpiry() throws Exception {
    String port = null;
    try {
        ConfigurableApplicationContext context = new SpringApplicationBuilder().sources(J360Configuration.class).properties("server.port:0").initializers(new ServerPortInfoApplicationContextInitializer()).run();
        port = context.getEnvironment().getProperty("local.server.port");
    } catch (RuntimeException ex) {
        if (!redisServerRunning(ex)) {
            return;
        }
    }
    URI uri = URI.create("http://localhost:" + port + "/");
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);
    String uuid1 = response.getBody();
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.set("Cookie", response.getHeaders().getFirst("Set-Cookie"));
    RequestEntity<Void> request = new RequestEntity<Void>(requestHeaders, HttpMethod.GET, uri);
    String uuid2 = restTemplate.exchange(request, String.class).getBody();
    assertThat(uuid1, is(equalTo(uuid2)));
    Thread.sleep(5000);
    String uuid3 = restTemplate.exchange(request, String.class).getBody();
    assertThat(uuid2, is(not(equalTo(uuid3))));
}
Example 29
Project: java-classic-playground-master  File: SendMailControllerIT.java View source code
@Test
public void happyPathSuccess() throws Exception {
    // Curl the resource, which causes the external process to send a mail.
    ResponseEntity<Void> entity = new RestTemplate().getForEntity(RESOURCE_LOCATION, Void.class);
    assertThat(entity.getStatusCode(), equalTo(OK));
    assertTrue("Should have received a mail", greenMail.waitForIncomingEmail(200, 1));
    Message[] messages = greenMail.getReceivedMessages();
    assertThat(messages.length, equalTo(1));
    assertThat(messages[0].getFrom(), equalTo(new Address[] { MY_MAIL }));
}
Example 30
Project: kurento-java-master  File: TimeoutTests.java View source code
@Test
public void playerAutoTerminationTest() throws Exception {
    String id = uploadFile(new File("test-files/sample.txt"));
    log.debug("File uploaded");
    RepositoryHttpPlayer player = getRepository().findRepositoryItemById(id).createRepositoryHttpPlayer();
    player.setAutoTerminationTimeout(1000);
    RestTemplate template = getRestTemplate();
    assertEquals(HttpStatus.OK, template.getForEntity(player.getURL(), byte[].class).getStatusCode());
    log.debug("Request 1 Passed");
    Thread.sleep(300);
    assertEquals(HttpStatus.OK, template.getForEntity(player.getURL(), byte[].class).getStatusCode());
    log.debug("Request 2 Passed");
    Thread.sleep(1500);
    assertEquals(HttpStatus.NOT_FOUND, template.getForEntity(player.getURL(), byte[].class).getStatusCode());
    log.debug("Request 3 Passed");
}
Example 31
Project: kurento-media-framework-master  File: OneRecordingServerTest.java View source code
protected void downloadFromURL(String urlToDownload, File downloadedFile) throws Exception {
    if (!downloadedFile.exists()) {
        downloadedFile.createNewFile();
    }
    log.info(urlToDownload);
    RestTemplate client = new RestTemplate();
    ResponseEntity<byte[]> response = client.getForEntity(urlToDownload, byte[].class);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    FileOutputStream os = new FileOutputStream(downloadedFile);
    os.write(response.getBody());
    os.close();
}
Example 32
Project: ManalithBot-master  File: GooGlProvider.java View source code
@Override
public String shorten(String url) {
    ShortenApiRequest req = new ShortenApiRequest();
    req.longUrl = url;
    RestTemplate rest = new RestTemplate();
    rest.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
    try {
        ShortenApiResponse data = rest.postForObject("https://www.googleapis.com/urlshortener/v1/url?key={key}", req, ShortenApiResponse.class, apiKey);
        return data.id;
    } catch (RestClientException e) {
        logger.error(e.getMessage(), e);
    }
    return null;
}
Example 33
Project: nextprot-api-master  File: SparqlProxyEndpointImpl.java View source code
private ResponseEntity<String> sparqlInternal(String queryString) {
    ResponseEntity<String> responseEntity;
    String url = sparqlEndpoint.getUrl() + ((queryString != null) ? ("?" + queryString) : "");
    try {
        RestTemplate template = new RestTemplate();
        responseEntity = template.getForEntity(new URI(url), String.class);
        return responseEntity;
    } catch (HttpServerErrorExceptionHttpClientErrorException |  e) {
        throw new NextProtException(e.getResponseBodyAsString(), e);
    } catch (RestClientExceptionURISyntaxException |  e) {
        throw new NextProtException(e);
    }
}
Example 34
Project: online-whatif-master  File: CouchDBClient.java View source code
/**
	 * Retrieve info.
	 */
public void retrieveInfo() {
    Map<String, String> vars = new HashMap<String, String>();
    vars.put("hotel", "42");
    vars.put("booking", "21");
    RestTemplate restTemplate = new RestTemplate();
    // String result = restTemplate.getForObject(uri, String.class, vars);
    String result = restTemplate.getForObject(uri, String.class);
    LOGGER.info("result: {}", result);
}
Example 35
Project: OpenClinica-master  File: PformSubmissionNotificationService.java View source code
public void notify(String studyOid, HashMap<String, String> subjectContext) {
    try {
        Integer studyEventDefnId = Integer.valueOf(subjectContext.get("studyEventDefinitionID"));
        Integer studyEventOrdinal = Integer.valueOf(subjectContext.get("studyEventOrdinal"));
        String crfVersionOid = subjectContext.get("crfVersionOID");
        String pManageUrl = CoreResources.getField("portalURL") + "/app/rest/oc/submission";
        Submission submission = new Submission();
        Study pManageStudy = new Study();
        pManageStudy.setInstanceUrl(CoreResources.getField("sysURL.base") + "rest2/openrosa/" + studyOid);
        pManageStudy.setStudyOid(studyOid);
        submission.setStudy(pManageStudy);
        submission.setStudy_event_def_id(studyEventDefnId);
        submission.setStudy_event_def_ordinal(studyEventOrdinal);
        submission.setCrf_version_id(crfVersionDao.findByOcOID(crfVersionOid).getCrfVersionId());
        RestTemplate rest = new RestTemplate();
        String result = rest.postForObject(pManageUrl, submission, String.class);
        logger.debug("Notified Participate of CRF submission with a result of: " + result);
    } catch (Exception e) {
        logger.error("Unable to notify Participate of successful CRF submission.");
        logger.error(e.getMessage());
        logger.error(ExceptionUtils.getStackTrace(e));
    }
}
Example 36
Project: quadriga-master  File: ViafServiceTest.java View source code
@Before
public void setUp() {
    template = Mockito.mock(RestTemplate.class);
    MockitoAnnotations.initMocks(this);
    ReflectionTestUtils.setField(viafService, "viafURL", "http://viaf.org/viaf/search");
    ReflectionTestUtils.setField(viafService, "searchViafURLPath", "?query=local.names all");
    ReflectionTestUtils.setField(viafService, "searchViafURLPath1", "+&maximumRecords=100&startRecord=");
    ReflectionTestUtils.setField(viafService, "searchViafURLPath2", "&sortKeys=holdingscount&httpAccept=application/rss+xml");
    ViafReply viafReply = new ViafReply();
    Channel channel = new Channel();
    Item item = new Item();
    item.setLink("http://viaf.org/viaf/27173507");
    item.setTitle("Pirckheimer, Willibald, 1470-1530.");
    item.setPubDate("Mon, 12 Jul 2015 18:51:56 GMT");
    List<Item> items = new ArrayList<Item>();
    items.add(item);
    channel.setItems(items);
    viafReply.setChannel(channel);
    Mockito.when(template.getForObject(Mockito.anyString(), Mockito.eq(ViafReply.class))).thenReturn(viafReply);
}
Example 37
Project: shopizer-master  File: SystemAPITest.java View source code
/**
	 * Contact us email
	 * @throws Exception
	 */
//@Test
@Ignore
public void createIntegrationModule() throws Exception {
    restTemplate = new RestTemplate();
    String json = "{" + "\"module\":\"SHIPPING\"," + "\"code\":\"priceByDistance\"," + "\"version\":\"1.0\"," + "\"regions\":[\"*\"]" + "}";
    System.out.println(json);
    HttpEntity<String> httpEntity = new HttpEntity<String>(json, getHeader());
    ResponseEntity<AjaxResponse> response = restTemplate.exchange("http://localhost:8080/sm-shop/services/private/system/module", HttpMethod.POST, httpEntity, AjaxResponse.class);
    if (response.getStatusCode() != HttpStatus.OK) {
        throw new Exception();
    } else {
        System.out.println(response.getBody() + " Success creating module");
    }
}
Example 38
Project: snomed-content-service-master  File: OTFServiceAuthenticationTest.java View source code
@Test
public void test() {
    RestTemplate rt = new RestTemplate();
    rt.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
    rt.getMessageConverters().add(new StringHttpMessageConverter());
    MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
    params.add("username", "pnema");
    params.add("password", "a5c527de-c77d-4b74-9186-efc3f29d65ef");
    params.add("queryName", "getUserByNameAuth");
    final User user = new User();
    try {
        JsonNode obj = rt.postForObject(OTF_SERVICE_URL, params, JsonNode.class);
        JsonNode userObj = obj.get("user");
        String userName = userObj.findValue("name").asText();
        String status = userObj.findValue("status").asText();
        Assert.notNull(status, "Status can not be empty");
        user.setUsername(userName);
        assertNotNull(user);
        //now check if user has access to Refset app.
        params = new LinkedMultiValueMap<String, String>();
        params.add("username", "pnema");
        params.add("queryName", "getUserApps");
        JsonNode appJson = rt.postForObject(OTF_SERVICE_URL, params, JsonNode.class);
        assertNotNull(appJson);
        JsonNode apps = appJson.get("apps");
        if (apps.isArray()) {
            for (Object object : apps) {
                System.out.println(object);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 39
Project: spring-batch-admin-master  File: ServerRunning.java View source code
@Override
public Statement apply(Statement base, FrameworkMethod method, Object target) {
    // Check at the beginning, so this can be used as a static field
    Assume.assumeTrue(serverOnline);
    try {
        RestTemplate template = new RestTemplate();
        ResponseEntity<String> result = template.exchange(url + "/home.json", HttpMethod.GET, null, String.class);
        String body = result.getBody();
        Assert.assertTrue("No home page found", body != null && body.length() > 0);
    } catch (Exception e) {
        logger.warn("Not executing tests because basic connectivity test failed", e);
        serverOnline = false;
        Assume.assumeNoException(e);
    }
    return super.apply(base, method, target);
}
Example 40
Project: spring-boot-master  File: SampleSessionRedisApplicationTests.java View source code
@Test
public void sessionExpiry() throws Exception {
    String port = null;
    try {
        ConfigurableApplicationContext context = new SpringApplicationBuilder().sources(SampleSessionRedisApplication.class).properties("server.port:0").initializers(new ServerPortInfoApplicationContextInitializer()).run();
        port = context.getEnvironment().getProperty("local.server.port");
    } catch (RuntimeException ex) {
        if (!redisServerRunning(ex)) {
            return;
        }
        throw ex;
    }
    URI uri = URI.create("http://localhost:" + port + "/");
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);
    String uuid1 = response.getBody();
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.set("Cookie", response.getHeaders().getFirst("Set-Cookie"));
    RequestEntity<Void> request = new RequestEntity<>(requestHeaders, HttpMethod.GET, uri);
    String uuid2 = restTemplate.exchange(request, String.class).getBody();
    assertThat(uuid1).isEqualTo(uuid2);
    Thread.sleep(5000);
    String uuid3 = restTemplate.exchange(request, String.class).getBody();
    assertThat(uuid2).isNotEqualTo(uuid3);
}
Example 41
Project: spring-cloud-netflix-master  File: LocalApplicationHealthIndicator.java View source code
@SuppressWarnings("unchecked")
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
    URI uri = this.properties.getHealthUri();
    if (uri == null) {
        builder.up();
        return;
    }
    Map<String, Object> map = new RestTemplate().getForObject(uri, Map.class);
    Object status = map.get("status");
    if (status != null && status instanceof String) {
        builder.status(status.toString());
    } else if (status != null && status instanceof Map) {
        Map<String, Object> statusMap = (Map<String, Object>) status;
        Object code = statusMap.get("code");
        if (code != null) {
            builder.status(code.toString());
        } else {
            getWarning(builder);
        }
    } else {
        getWarning(builder);
    }
}
Example 42
Project: spring-framework-master  File: ZeroCopyIntegrationTests.java View source code
@Test
public void zeroCopy() throws Exception {
    // Zero-copy only does not support servlet
    assumeTrue(server instanceof ReactorHttpServer || server instanceof UndertowHttpServer);
    RestTemplate restTemplate = new RestTemplate();
    RequestEntity<?> request = RequestEntity.get(new URI("http://localhost:" + port)).build();
    ResponseEntity<byte[]> response = restTemplate.exchange(request, byte[].class);
    Resource logo = new ClassPathResource("spring.png", ZeroCopyIntegrationTests.class);
    assertTrue(response.hasBody());
    assertEquals(logo.contentLength(), response.getHeaders().getContentLength());
    assertEquals(logo.contentLength(), response.getBody().length);
    assertEquals(MediaType.IMAGE_PNG, response.getHeaders().getContentType());
}
Example 43
Project: spring-hateoas-master  File: ChangelogCreator.java View source code
public static void main(String... args) throws Exception {
    RestTemplate template = new RestTemplate();
    String response = template.getForObject(URI_TEMPLATE, String.class, MILESTONE_ID);
    JsonPath titlePath = JsonPath.compile("$[*].title");
    JsonPath idPath = JsonPath.compile("$[*].number");
    JSONArray titles = titlePath.read(response);
    Iterator<Object> ids = ((JSONArray) idPath.read(response)).iterator();
    System.out.println("Milestone - " + JsonPath.read(response, "$[1].milestone.title"));
    for (Object title : titles) {
        String format = String.format("- #%s - %s", ids.next(), title);
        System.out.println(format.endsWith(".") ? format : format.concat("."));
    }
}
Example 44
Project: spring-reactive-master  File: ZeroCopyIntegrationTests.java View source code
@Test
public void zeroCopy() throws Exception {
    // Zero-copy only does not support servlet
    assumeTrue(server instanceof ReactorHttpServer || server instanceof UndertowHttpServer);
    RestTemplate restTemplate = new RestTemplate();
    RequestEntity request = RequestEntity.get(new URI("http://localhost:" + port)).build();
    ResponseEntity<byte[]> response = restTemplate.exchange(request, byte[].class);
    Resource logo = new ClassPathResource("spring.png", ZeroCopyIntegrationTests.class);
    assertTrue(response.hasBody());
    assertEquals(logo.contentLength(), response.getHeaders().getContentLength());
    assertEquals(logo.contentLength(), response.getBody().length);
    assertEquals(MediaType.IMAGE_PNG, response.getHeaders().getContentType());
}
Example 45
Project: spring-security-oauth-master  File: ClientCredentialsProviderTests.java View source code
/**
	 * No Basic authentication provided, only the hard coded client_id.
	 */
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testHardCodedAuthenticationFineClient() {
    RestTemplate restTemplate = new RestTemplate();
    MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
    params.add("grant_type", "client_credentials");
    params.add("client_id", "my-client-with-secret");
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    RequestEntity<MultiValueMap<String, String>> req = new RequestEntity<MultiValueMap<String, String>>(params, headers, HttpMethod.POST, tokenUri);
    ResponseEntity<Map> response = restTemplate.exchange(req, Map.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    Map<String, String> body = response.getBody();
    String accessToken = body.get("access_token");
    assertNotNull(accessToken);
}
Example 46
Project: spring-social-instagram-master  File: InstagramOAuth2Template.java View source code
@Override
protected RestTemplate createRestTemplate() {
    RestTemplate restTemplate = new RestTemplate(ClientHttpRequestFactorySelector.getRequestFactory());
    FormHttpMessageConverter messageConverter = new FormHttpMessageConverter() {

        public boolean canRead(Class<?> clazz, MediaType mediaType) {
            return true;
        }
    };
    restTemplate.setMessageConverters(Collections.<HttpMessageConverter<?>>singletonList(messageConverter));
    return restTemplate;
}
Example 47
Project: spring-social-live-master  File: LiveOAuth2Template.java View source code
/* On POST to /token Microsoft returns JSON as "text/html" (should be application/json), which results in:
    ---
    org.springframework.web.client.RestClientException: Could not extract response: no suitable
    HttpMessageConverter found for response type [interface java.util.Map] and content type
    [text/html;charset=utf-8]
    ---
    Adding support for handling text/html to the MappingJackson2HttpMessageConverter */
@Override
protected RestTemplate createRestTemplate() {
    RestTemplate template = super.createRestTemplate();
    for (HttpMessageConverter<?> converter : template.getMessageConverters()) {
        if (converter instanceof MappingJackson2HttpMessageConverter) {
            List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
            // Add all default
            supportedMediaTypes.addAll(converter.getSupportedMediaTypes());
            // And also handle text/html json returned on POST to /token
            supportedMediaTypes.add(new MediaType("text", "html", MappingJackson2HttpMessageConverter.DEFAULT_CHARSET));
            ((MappingJackson2HttpMessageConverter) converter).setSupportedMediaTypes(supportedMediaTypes);
        }
    }
    return template;
}
Example 48
Project: spring-xd-master  File: SingleNodeApplicationWithSslTest.java View source code
@Before
public void setUpRestTemplate() throws Exception {
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());
    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
    restTemplate = new RestTemplate(requestFactory);
}
Example 49
Project: springcamp2017-master  File: OrderConfig.java View source code
@Bean
public RestTemplate restTemplate() {
    final RestTemplate restTemplate = new RestTemplate();
    for (int i = 0; i < restTemplate.getMessageConverters().size(); i++) {
        final HttpMessageConverter<?> httpMessageConverter = restTemplate.getMessageConverters().get(i);
        if (httpMessageConverter instanceof MappingJackson2HttpMessageConverter) {
            restTemplate.getMessageConverters().set(i, httpMessageConverter);
        }
    }
    return restTemplate;
}
Example 50
Project: Stage-master  File: SpringRestTemplateContextPropagatingTransformerTest.java View source code
@Test
public void testRestTemplateHasInterceptor() throws Exception {
    final List<RestTemplate> restTemplates = Arrays.asList(new RestTemplate(), new RestTemplate(new SimpleClientHttpRequestFactory()), new RestTemplate(Collections.singletonList(new StringHttpMessageConverter())));
    for (RestTemplate restTemplate : restTemplates) {
        assertThat(restTemplate.getInterceptors().size(), is(1));
        assertThat(restTemplate.getInterceptors(), hasItem(isA(SpringRestTemplateContextPropagatingInterceptor.class)));
    }
}
Example 51
Project: stagemonitor-master  File: SpringRestTemplateContextPropagatingTransformerTest.java View source code
@Test
public void testRestTemplateHasInterceptor() throws Exception {
    final List<RestTemplate> restTemplates = Arrays.asList(new RestTemplate(), new RestTemplate(new SimpleClientHttpRequestFactory()), new RestTemplate(Collections.singletonList(new StringHttpMessageConverter())));
    for (RestTemplate restTemplate : restTemplates) {
        assertThat(restTemplate.getInterceptors().size(), is(1));
        assertThat(restTemplate.getInterceptors(), hasItem(isA(SpringRestTemplateContextPropagatingInterceptor.class)));
    }
}
Example 52
Project: swagger-codegen-tooling-master  File: StupsSwaggerCodegenIT.java View source code
@Test
public void getResources() {
    RestTemplate rest = new RestTemplate();
    ResponseEntity<List<SwaggerResource>> responseEntity = rest.exchange("http://localhost:" + port + "/swagger-resources", HttpMethod.GET, null, swaggerResourceParameterizedType);
    List<SwaggerResource> swaggerResourceList = responseEntity.getBody();
    Assertions.assertThat(swaggerResourceList).isNotEmpty();
    SwaggerResource resource = swaggerResourceList.get(0);
    Assertions.assertThat(resource).isNotNull();
    Assertions.assertThat(resource.getSwaggerVersion()).isEqualTo("2.0");
    Assertions.assertThat(resource.getName()).isEqualTo("default");
    Assertions.assertThat(resource.getLocation()).isEqualTo("/v2/api-docs");
}
Example 53
Project: spring-social-master  File: AbstractOAuth2ApiBindingTest.java View source code
@Test
public void testOriginalSocialTemplateToProveBackwardsCompatibility() throws Exception {
    MySocialTemplate template = new MySocialTemplate("some acces code");
    template.afterPropertiesSet();
    RestTemplate restTemplate = template.getRestTemplate();
    assertThat(ClassUtils.isCglibProxy(restTemplate), is(false));
    assertThat(template.getState(), equalTo("no state here"));
    assertThat(ClassUtils.isCglibProxy(template.getSubSocialTemplate().getRestTemplate()), is(false));
}
Example 54
Project: acheron-master  File: ClientCreationOperationSimple.java View source code
@Override
public ClientCreationResult result() throws TechnicalException {
    final ClientCreationResult result;
    final RestTemplate restTemplate = buildRestTemplate();
    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set("Authorization", "Bearer " + ownAccessToken);
    final HydraClient hydraClient = new HydraClient(client);
    final HttpEntity<HydraClient> hydraClientRequestHttpEntity = new HttpEntity<>(hydraClient, headers);
    try {
        final JSONResponse jsonResponse = restTemplate.postForObject(clientCreationEndpointURL, hydraClientRequestHttpEntity, JSONResponse.class);
        log.info("Hydra created client successfully: {}", jsonResponse.clientId());
        // NPE is possible, caught below
        result = new HydraClientCreationResult(jsonResponse);
    } catch (final HttpClientErrorException e) {
        if (HttpStatus.BAD_REQUEST.equals(e.getStatusCode())) {
            log.info("Bad request to Hydra: {}", e.getResponseBodyAsString());
            return new ClientCreationResult.NoResult();
        } else {
            log.error("Hydra rejected the client creation request", e);
            throw new TechnicalException();
        }
    } catch (final HttpServerErrorException e) {
        log.error("Client creation request caused Hydra server error", e.getResponseBodyAsString());
        throw new TechnicalException();
    } catch (final Exception e) {
        log.error("Could not create client in authorisation server", e);
        throw new TechnicalException();
    }
    return result;
}
Example 55
Project: Activiti-master  File: EndpointAutoConfigurationTest.java View source code
@Test
public void mvcEndpoint() throws Throwable {
    AnnotationConfigEmbeddedWebApplicationContext applicationContext = new AnnotationConfigEmbeddedWebApplicationContext(CallbackEmbeddedContainerCustomizer.class, EmbeddedContainerConfiguration.class, EndpointConfiguration.class);
    ProcessEngine processEngine = applicationContext.getBean(ProcessEngine.class);
    org.junit.Assert.assertNotNull("the processEngine should not be null", processEngine);
    ProcessEngineEndpoint processEngineEndpoint = applicationContext.getBean(ProcessEngineEndpoint.class);
    org.junit.Assert.assertNotNull("the processEngineEndpoint should not be null", processEngineEndpoint);
    RestTemplate restTemplate = applicationContext.getBean(RestTemplate.class);
    ResponseEntity<Map> mapResponseEntity = restTemplate.getForEntity("http://localhost:9091/activiti/", Map.class);
    Map map = mapResponseEntity.getBody();
    String[] criticalKeys = { "completedTaskCount", "openTaskCount", "cachedProcessDefinitionCount" };
    Map<?, ?> invokedResults = processEngineEndpoint.invoke();
    for (String k : criticalKeys) {
        org.junit.Assert.assertTrue(map.containsKey(k));
        org.junit.Assert.assertEquals(((Number) map.get(k)).longValue(), ((Number) invokedResults.get(k)).longValue());
    }
}
Example 56
Project: boot-it-up-master  File: ReservationRestControllerTests.java View source code
@Before
public void setup() {
    List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
    converters.add(new StringHttpMessageConverter());
    converters.add(new MappingJackson2HttpMessageConverter());
    this.restTemplate = new RestTemplate();
    this.restTemplate.setMessageConverters(converters);
    this.mockServer = MockRestServiceServer.createServer(this.restTemplate);
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
Example 57
Project: brave-master  File: ITTracingClientHttpRequestInterceptor.java View source code
@Test
public void currentSpanVisibleToUserInterceptors() throws Exception {
    server.enqueue(new MockResponse());
    RestTemplate restTemplate = new RestTemplate(client);
    restTemplate.setInterceptors(Arrays.asList(interceptor, ( request,  body,  execution) -> {
        request.getHeaders().add("my-id", currentTraceContext.get().traceIdString());
        return execution.execute(request, body);
    }));
    restTemplate.getForObject(server.url("/foo").toString(), String.class);
    RecordedRequest request = server.takeRequest();
    assertThat(request.getHeader("x-b3-traceId")).isEqualTo(request.getHeader("my-id"));
}
Example 58
Project: cloud-rest-service-master  File: UserServiceTest.java View source code
public static void requestRestApi(String access_token) {
    RestTemplate restTemplate = new RestTemplate();
    MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
    form.add("method", "user.get");
    form.add("version", "1.0.0");
    form.add("locale", "zh_CN");
    form.add("format", "json");
    //-Dexcludes.appkey=Hb0YhmOo
    form.add("appkey", "Hb0YhmOo");
    form.add("access_token", access_token);
    form.add("id", "10001");
    String result = restTemplate.postForObject("http://localhost:8090/api", form, String.class);
    System.out.println(result);
}
Example 59
Project: crowdsource-master  File: ProjectIT.java View source code
@Test
public void addProject_accessDenied() {
    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
    Project project = new Project();
    project.setTitle("title");
    project.setShortDescription("short description");
    project.setPledgeGoal(1);
    project.setDescription("description");
    try {
        restTemplate.postForObject(urlProvider.applicationUrl() + "/project", project, Void.class);
        Assert.fail("Accessing a protected resource should fail");
    } catch (HttpClientErrorException e) {
        assertThat(e.getStatusCode(), is(HttpStatus.UNAUTHORIZED));
    }
}
Example 60
Project: GeneDB-master  File: FeedbackController.java View source code
@RequestMapping(method = RequestMethod.POST)
public String processForm() {
    // Validate
    String uri = "http://api-verify.recaptcha.net/verify";
    RestTemplate template = new RestTemplate();
    String key = "fred";
    String s = template.postForObject(uri, key, String.class);
    //if (!"true".equals(s[0])) {
    //}
    SimpleMailMessage msg = new SimpleMailMessage();
    msg.setTo(CURATORS);
    //msg.setText(
    //    "Dear " + order.getCustomer().getFirstName()
    //        + order.getCustomer().getLastName()
    //        + ", thank you for placing order. Your order number is "
    //        + order.getOrderNumber());
    //try{
    this.mailSender.send(msg);
    //}
    //catch(MailException ex) {
    // simply log it and go on...
    //    System.err.println(ex.getMessage());
    //}
    String originalPage = null;
    if (originalPage != null) {
        return "redirect:" + originalPage;
    }
    return "redirect:/Homepage";
}
Example 61
Project: genie-master  File: AwsMvcConfigUnitTests.java View source code
/**
     * Make sure we attempt public hostname first.
     *
     * @throws IOException on any problem
     */
@Test
public void canGetPublicHostname() throws IOException {
    final RestTemplate restTemplate = Mockito.mock(RestTemplate.class);
    final String hostname = UUID.randomUUID().toString();
    Mockito.when(restTemplate.getForObject(this.awsMvcConfig.publicHostNameGet, String.class)).thenReturn(hostname);
    Assert.assertThat(this.awsMvcConfig.hostName(restTemplate), Matchers.is(hostname));
    Mockito.verify(restTemplate, Mockito.times(1)).getForObject(awsMvcConfig.publicHostNameGet, String.class);
    Mockito.verify(restTemplate, Mockito.never()).getForObject(awsMvcConfig.localIPV4HostNameGet, String.class);
}
Example 62
Project: jagger-master  File: JaasExecApiClient.java View source code
private <T> Optional<T> doWithRetries(Function<RestTemplate, T> function) {
    int retriesTimeout = 10;
    int retriesLeft = 5;
    do {
        try {
            return Optional.ofNullable(function.apply(restTemplate));
        } catch (// will retry in case that is a temporarily issue
        HttpServerErrorException // will retry in case that is a temporarily issue
        e) {
            LOGGER.warn("A server error during a request", e);
            try {
                TimeUnit.SECONDS.sleep(retriesTimeout);
                retriesLeft--;
                retriesTimeout *= 2;
            } catch (InterruptedException e1) {
                retriesLeft = 0;
            }
        }
    } while (retriesLeft > 0);
    return Optional.empty();
}
Example 63
Project: jbot-master  File: SlackDao.java View source code
public RTM startRTM(String slackToken) {
    try {
        restTemplate = new RestTemplate();
        rtm = new RTM();
        // Custom Deserializers
        List<HttpMessageConverter<?>> httpMessageConverters = new ArrayList<>();
        MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
        Jackson2ObjectMapperBuilder mapperBuilder = new Jackson2ObjectMapperBuilder();
        mapperBuilder.deserializerByType(RTM.class, new JsonDeserializer<RTM>() {

            @Override
            public RTM deserialize(JsonParser p, DeserializationContext ctxt) {
                try {
                    final ObjectMapper objectMapper = new ObjectMapper();
                    JsonNode node = p.readValueAsTree();
                    RTM rtm = new RTM();
                    rtm.setWebSocketUrl(node.get("url").asText());
                    rtm.setUser(objectMapper.treeToValue(node.get("self"), User.class));
                    List<String> dmChannels = new ArrayList<>();
                    Iterator<JsonNode> iterator = node.get("ims").iterator();
                    while (iterator.hasNext()) {
                        dmChannels.add(iterator.next().get("id").asText());
                    }
                    rtm.setDmChannels(dmChannels);
                    List<User> users = new ArrayList<>();
                    Iterator<JsonNode> userIterator = node.get("users").iterator();
                    while (userIterator.hasNext()) {
                        users.add(objectMapper.treeToValue(userIterator.next(), User.class));
                    }
                    rtm.setUsers(users);
                    return rtm;
                } catch (Exception e) {
                    logger.error("Error de-serializing RTM.start(): ", e);
                    return null;
                }
            }
        });
        jsonConverter.setObjectMapper(mapperBuilder.build());
        httpMessageConverters.add(jsonConverter);
        restTemplate.setMessageConverters(httpMessageConverters);
        ResponseEntity<RTM> response = restTemplate.getForEntity(rtmUrl, RTM.class, slackToken);
        if (response.getBody() != null) {
            rtm.setWebSocketUrl(response.getBody().getWebSocketUrl());
            rtm.setDmChannels(response.getBody().getDmChannels());
            rtm.setUser(response.getBody().getUser());
            rtm.setUsers(response.getBody().getUsers());
            logger.debug("RTM connection successful. WebSocket URL: {}", rtm.getWebSocketUrl());
        } else {
            logger.debug("RTM response invalid. Response: {}", response);
        }
    } catch (RestClientException e) {
        logger.error("RTM connection error. Exception: {}", e.getMessage());
    }
    return rtm;
}
Example 64
Project: mars-calendar-master  File: GreetingsControllerTest.java View source code
@Test
public void testHttpGet() throws IOException, URISyntaxException {
    RestTemplate restTemplate = new TestRestTemplate();
    int port = 8080;
    final URI url = new URI("http://localhost:" + port + "/rest/v1/greeting");
    final ResponseEntity<Greeting> entity = restTemplate.getForEntity(url, Greeting.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
    assertEquals("Hello, Anonymous!", entity.getBody().getText());
}
Example 65
Project: microservice-master  File: CustomerClient.java View source code
public boolean isValidCustomerId(long customerId) {
    RestTemplate restTemplate = new RestTemplate();
    try {
        ResponseEntity<String> entity = restTemplate.getForEntity(customerURL() + customerId, String.class);
        return entity.getStatusCode().is2xxSuccessful();
    } catch (final HttpClientErrorException e) {
        if (e.getStatusCode().value() == 404)
            return false;
        else
            throw e;
    }
}
Example 66
Project: microservices-hackathon-november-2014-master  File: ComboFactory.java View source code
private static RestTemplate restTemplate(final URI baseUrl, final RestTemplateVisitor... restTemplateVisitors) {
    final RestTemplate restTemplate = new RestTemplate(singletonList(new GsonHttpMessageConverter()));
    for (final RestTemplateVisitor visitor : restTemplateVisitors) {
        visitor.visit(restTemplate);
    }
    restTemplate.getInterceptors().add(new BaseUrlInterceptor(baseUrl));
    restTemplate.getInterceptors().add(new LoggingInterceptor());
    return restTemplate;
}
Example 67
Project: mockserver-master  File: BookServiceSpringRestTemplateClient.java View source code
private RestTemplate createRestTemplate() {
    // jackson message converter
    MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJackson2HttpMessageConverter();
    mappingJacksonHttpMessageConverter.setObjectMapper(objectMapper);
    // create message converters list
    List<HttpMessageConverter<?>> httpMessageConverters = new ArrayList<HttpMessageConverter<?>>();
    httpMessageConverters.add(mappingJacksonHttpMessageConverter);
    // create rest template
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setMessageConverters(httpMessageConverters);
    // configure proxy
    HttpHost httpHost = new HttpHost(System.getProperty("http.proxyHost"), Integer.parseInt(System.getProperty("http.proxyPort")));
    DefaultProxyRoutePlanner defaultProxyRoutePlanner = new DefaultProxyRoutePlanner(httpHost);
    HttpClient httpClient = HttpClients.custom().setRoutePlanner(defaultProxyRoutePlanner).build();
    restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));
    return restTemplate;
}
Example 68
Project: myconsumption-android-master  File: CreateAccountActivity.java View source code
private int createAccount() {
    RestTemplate template = new RestTemplate();
    template.getMessageConverters().add(new FormHttpMessageConverter());
    template.getMessageConverters().add(new StringHttpMessageConverter());
    MultiValueMap<String, String> postParams = new LinkedMultiValueMap<>();
    postParams.add("password", CryptoUtils.sha256(editTextPassword.getText().toString()));
    try {
        String result = template.postForObject(SingleInstance.getServerUrl() + "users/" + editTextUsername.getText().toString(), postParams, String.class);
        LOGD(TAG, result);
        SimpleResponseDTO response = new ObjectMapper().readValue(result, SimpleResponseDTO.class);
        return response.getStatus();
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    }
}
Example 69
Project: RoboSpice-samples-master  File: TweeterJsonSpringAndroidSpiceService.java View source code
@Override
public RestTemplate createRestTemplate() {
    RestTemplate restTemplate = new RestTemplate() {

        @Override
        protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException {
            ClientHttpRequest request = super.createRequest(url, method);
            HttpHeaders headers = request.getHeaders();
            headers.setAcceptEncoding(ContentCodingType.GZIP);
            return request;
        }
    };
    // bug on http connection for Android < 2.2
    // http://android-developers.blogspot.fr/2011/09/androids-http-clients.html
    // but still a problem for upload with Spring-android on android 4.1
    System.setProperty("http.keepAlive", "false");
    // set timeout for requests
    ClientHttpRequestFactory factory = restTemplate.getRequestFactory();
    if (factory instanceof HttpComponentsClientHttpRequestFactory) {
        HttpComponentsClientHttpRequestFactory advancedFactory = (HttpComponentsClientHttpRequestFactory) factory;
        advancedFactory.setConnectTimeout(WEBSERVICES_TIMEOUT);
        advancedFactory.setReadTimeout(WEBSERVICES_TIMEOUT);
    } else if (factory instanceof SimpleClientHttpRequestFactory) {
        SimpleClientHttpRequestFactory advancedFactory = (SimpleClientHttpRequestFactory) factory;
        advancedFactory.setConnectTimeout(WEBSERVICES_TIMEOUT);
        advancedFactory.setReadTimeout(WEBSERVICES_TIMEOUT);
    }
    // web services support json responses
    MappingJacksonHttpMessageConverter jsonConverter = new MappingJacksonHttpMessageConverter();
    FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
    StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
    final List<HttpMessageConverter<?>> listHttpMessageConverters = restTemplate.getMessageConverters();
    listHttpMessageConverters.add(jsonConverter);
    listHttpMessageConverters.add(formHttpMessageConverter);
    listHttpMessageConverters.add(stringHttpMessageConverter);
    restTemplate.setMessageConverters(listHttpMessageConverters);
    return restTemplate;
}
Example 70
Project: service-registration-and-discovery-master  File: Application.java View source code
@Override
public void run(String... strings) throws Exception {
    // use the "smart" Eureka-aware RestTemplate
    ResponseEntity<List<Bookmark>> exchange = this.restTemplate.exchange("http://bookmark-service/{userId}/bookmarks", HttpMethod.GET, null, new ParameterizedTypeReference<List<Bookmark>>() {
    }, (Object) "mstine");
    exchange.getBody().forEach(System.out::println);
}
Example 71
Project: spring-data-book-master  File: ClientConfiguration.java View source code
/**
	 * Configures the Jackson {@link ObjectMapper} to ignore unknown properties on the client side. E.g.
	 * {@link LineItem#getTotal()} causes Jackson to consider {@code total} a property and fails to bind the object as
	 * there's no setter accepting a value.
	 * 
	 * @return
	 */
@Bean
public RestOperations restOperations() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setObjectMapper(mapper);
    converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON));
    List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
    converters.add(converter);
    RestTemplate template = new RestTemplate();
    template.setMessageConverters(converters);
    return template;
}
Example 72
Project: spring-hadoop-master  File: YarnRestTemplateAutoConfiguration.java View source code
@Bean(name = YarnSystemConstants.DEFAULT_ID_RESTTEMPLATE)
public RestTemplate restTemplate() {
    HttpClientBuilder builder = HttpClientBuilder.create();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(securityProperties.getUser().getName(), securityProperties.getUser().getPassword());
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(null, -1, null), credentials);
    builder.setDefaultCredentialsProvider(credentialsProvider);
    HttpClient httpClient = builder.build();
    return new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
}
Example 73
Project: spring-ide-master  File: BasicAuthCredentials.java View source code
@Override
public RestTemplate apply(RestTemplate rest) {
    List<ClientHttpRequestInterceptor> interceptors = rest.getInterceptors();
    interceptors.add(new ClientHttpRequestInterceptor() {

        public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
            if (matchHost(request.getURI().getHost())) {
                HttpHeaders headers = request.getHeaders();
                if (!headers.containsKey("Authorization")) {
                    String authString = computeAuthString();
                    headers.add("Authorization", authString);
                }
            }
            return execution.execute(request, body);
        }
    });
    return rest;
}
Example 74
Project: spring-integration-samples-master  File: MultipartRestClient.java View source code
/**
	 * @param args
	 */
public static void main(String[] args) throws Exception {
    RestTemplate template = new RestTemplate();
    Resource s2logo = new ClassPathResource(resourcePath);
    MultiValueMap<String, Object> multipartMap = new LinkedMultiValueMap<String, Object>();
    multipartMap.add("company", "SpringSource");
    multipartMap.add("company-logo", s2logo);
    logger.info("Created multipart request: " + multipartMap);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(new MediaType("multipart", "form-data"));
    HttpEntity<Object> request = new HttpEntity<Object>(multipartMap, headers);
    logger.info("Posting request to: " + uri);
    ResponseEntity<?> httpResponse = template.exchange(uri, HttpMethod.POST, request, Object.class);
    if (!httpResponse.getStatusCode().equals(HttpStatus.OK)) {
        logger.error("Problems with the request. Http status: " + httpResponse.getStatusCode());
    }
}
Example 75
Project: spring-metrics-master  File: MetricsClientHttpRequestInterceptorTest.java View source code
@Test
void interceptRestTemplate() {
    MeterRegistry registry = new SimpleMeterRegistry();
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setInterceptors(singletonList(new MetricsClientHttpRequestInterceptor(registry, new DefaultWebMetricsTagProvider(), "http_client_requests")));
    MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);
    mockServer.expect(MockRestRequestMatchers.requestTo("/test/123")).andExpect(MockRestRequestMatchers.method(HttpMethod.GET)).andRespond(MockRestResponseCreators.withSuccess("OK", MediaType.APPLICATION_JSON));
    String s = restTemplate.getForObject("/test/{id}", String.class, 123);
    // the uri requires AOP to determine
    assertThat(registry.findMeter(Timer.class, "http_client_requests", "method", "GET", "uri", "none", "status", "200")).containsInstanceOf(Timer.class).hasValueSatisfying( t -> assertThat(t.count()).isEqualTo(1));
    assertEquals("OK", s);
    mockServer.verify();
}
Example 76
Project: spring-social-viadeo-master  File: ViadeoOAuth2Template.java View source code
@Override
protected RestTemplate createRestTemplate() {
    RestTemplate restTemplate = new RestTemplate(ClientHttpRequestFactorySelector.getRequestFactory());
    List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>(2);
    converters.add(new FormHttpMessageConverter());
    AbstractHttpMessageConverter<?> jsonConverter = new MappingJacksonHttpMessageConverter();
    List<MediaType> supportedMediaTypes = new ArrayList<MediaType>(3);
    supportedMediaTypes.add(new MediaType("application", "json", Charset.forName("UTF-8")));
    supportedMediaTypes.add(MediaType.APPLICATION_JSON);
    supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
    jsonConverter.setSupportedMediaTypes(supportedMediaTypes);
    converters.add(jsonConverter);
    restTemplate.setMessageConverters(converters);
    return restTemplate;
}
Example 77
Project: spring4-1-showcase-master  File: ProtoTest.java View source code
@BeforeClass
public static void beforeClass() throws Exception {
    //´´½¨Ò»¸öserver
    server = new Server(8080);
    WebAppContext context = new WebAppContext();
    String webapp = "spring4.1-mvc/src/main/webapp";
    //Ö¸¶¨web.xmlÅäÖÃÎļþ
    context.setDescriptor(webapp + "/WEB-INF/web.xml");
    //Ö¸¶¨webappĿ¼
    context.setResourceBase(webapp);
    context.setContextPath("/");
    context.setParentLoaderPriority(true);
    server.setHandler(context);
    server.start();
    restTemplate = new RestTemplate();
    ExtensionRegistryInitializer extensionRegistryInitializer = new MyExtensionRegistryInitializer();
    ProtobufHttpMessageConverter protobufHttpMessageConverter = new ProtobufHttpMessageConverter(extensionRegistryInitializer);
    restTemplate.getMessageConverters().add(0, protobufHttpMessageConverter);
}
Example 78
Project: thingsboard-master  File: RestApiCallMsgHandler.java View source code
@Override
public void process(PluginContext ctx, TenantId tenantId, RuleId ruleId, RuleToPluginMsg<?> msg) throws RuleException {
    if (!(msg instanceof RestApiCallActionMsg)) {
        throw new RuleException("Unsupported message type " + msg.getClass().getName() + "!");
    }
    RestApiCallActionPayload payload = ((RestApiCallActionMsg) msg).getPayload();
    try {
        ResponseEntity<String> exchangeResponse = new RestTemplate().exchange(baseUrl + payload.getActionPath(), payload.getHttpMethod(), new HttpEntity<>(payload.getMsgBody(), headers), String.class);
        if (exchangeResponse.getStatusCode().equals(payload.getExpectedResultCode()) && payload.isSync()) {
            ctx.reply(new ResponsePluginToRuleMsg(msg.getUid(), tenantId, ruleId, BasicStatusCodeResponse.onSuccess(payload.getMsgType(), payload.getRequestId())));
        } else if (!exchangeResponse.getStatusCode().equals(payload.getExpectedResultCode())) {
            throw new RuntimeException("Response Status Code '" + exchangeResponse.getStatusCode() + "' doesn't equals to Expected Status Code '" + payload.getExpectedResultCode() + "'");
        }
    } catch (RestClientException e) {
        throw new RuleException(e.getMessage(), e);
    }
}
Example 79
Project: uaa-master  File: FixedHttpMetaDataProvider.java View source code
public static FixedHttpMetaDataProvider buildProvider(Timer backgroundTaskTimer, HttpClientParams params, String metadataURL, RestTemplate template, UrlContentCache cache) throws MetadataProviderException {
    SimpleHttpConnectionManager connectionManager = new SimpleHttpConnectionManager(true);
    connectionManager.getParams().setDefaults(params);
    HttpClient client = new HttpClient(connectionManager);
    return new FixedHttpMetaDataProvider(backgroundTaskTimer, client, metadataURL, template, cache);
}
Example 80
Project: webofneeds-master  File: LinkedDataRestBridge.java View source code
private RestTemplate createRestTemplateForReadingLinkedData(String webID) throws Exception {
    RestTemplate template = CryptographyUtils.createSslRestTemplate(this.keyStoreService.getUnderlyingKeyStore(), this.keyStoreService.getPassword(), new PredefinedAliasPrivateKeyStrategy(webID), this.trustStoreService.getUnderlyingKeyStore(), this.trustStrategy, readTimeout, connectionTimeout, true);
    //prevent the RestTemplate from throwing an exception when the server responds with 4xx or 5xx status
    //because we want to hand the orginal response back to the original caller in BridgeForLinkedDataController
    template.setErrorHandler(new DefaultResponseErrorHandler() {

        @Override
        protected boolean hasError(final HttpStatus statusCode) {
            return false;
        }
    });
    return template;
}
Example 81
Project: android-viewer-for-khan-academy-master  File: KAEntityCollectionFetcherTask.java View source code
@Override
protected List<T> doInBackground(Void... arg0) {
    // call  API and fetch an entity tree (commonly the tree rooted at the root topic)
    RestTemplate restTemplate = new RestTemplate();
    if (consumer != null) {
        restTemplate.setRequestFactory(new SpringRequestFactory(consumer));
    }
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
    ResponseEntity<String> result = restTemplate.getForEntity(url, String.class);
    String body = result.getBody();
    // String tag = "~~~~~~~~~~~~~~~~";
    // Log.setLevel(tag, Log.VERBOSE);
    // Log.d(tag, "result body is a " + body.getClass().getCanonicalName());
    // Log.d(tag, "result is " + body);
    ObjectMapper mapper = new ObjectMapper();
    List<T> list = null;
    try {
        list = mapper.readValue(body, type);
    } catch (JsonParseException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return list;
}
Example 82
Project: APP-dashboard-master  File: RESTClientTest.java View source code
@Test
public void testMakeJsonRequestWHeaders() {
    //TODO: Change the overridden function to support HTTPEntity
    RESTClient client = new RESTClient() {

        public HttpEntity<String> exchange(RestTemplate template, String url, HttpMethod method, HttpEntity entity, Class cl) {
            return new HttpEntity<String>("fakeResponse");
        }
    };
    String s = client.makeJsonRequestWHeaders("http://www.google.com", "fakeToken");
    assertEquals(s, "fakeResponse");
}
Example 83
Project: Blogs-master  File: FindAddressActivity.java View source code
private RestTemplate getRestTemplate() {
    if (restTemplate == null) {
        restTemplate = new RestTemplate();
        MappingJacksonHttpMessageConverter jsonConverter = new MappingJacksonHttpMessageConverter();
        List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON);
        jsonConverter.setSupportedMediaTypes(supportedMediaTypes);
        List<HttpMessageConverter<?>> listHttpMessageConverters = restTemplate.getMessageConverters();
        listHttpMessageConverters.add(jsonConverter);
        restTemplate.setMessageConverters(listHttpMessageConverters);
    }
    return restTemplate;
}
Example 84
Project: chaos-lemur-master  File: StandardDirectorUtils.java View source code
private static RestTemplate createRestTemplate(String host, String username, String password, Set<ClientHttpRequestInterceptor> interceptors) throws GeneralSecurityException {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(host, 25555), new UsernamePasswordCredentials(username, password));
    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS().build();
    SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());
    HttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling().setDefaultCredentialsProvider(credentialsProvider).setSSLSocketFactory(connectionFactory).build();
    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
    restTemplate.getInterceptors().addAll(interceptors);
    return restTemplate;
}
Example 85
Project: DatabasesProject-master  File: CarJsonSpringAndroidSpiceService.java View source code
@Override
public RestTemplate createRestTemplate() {
    RestTemplate restTemplate = new RestTemplate() {

        @Override
        protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException {
            ClientHttpRequest request = super.createRequest(url, method);
            HttpHeaders headers = request.getHeaders();
            headers.setAcceptEncoding(ContentCodingType.GZIP);
            return request;
        }
    };
    // bug on http connection for Android < 2.2
    // http://android-developers.blogspot.fr/2011/09/androids-http-clients.html
    // but still a problem for upload with Spring-android on android 4.1
    System.setProperty("http.keepAlive", "false");
    // set timeout for requests
    ClientHttpRequestFactory factory = restTemplate.getRequestFactory();
    if (factory instanceof HttpComponentsClientHttpRequestFactory) {
        HttpComponentsClientHttpRequestFactory advancedFactory = (HttpComponentsClientHttpRequestFactory) factory;
        advancedFactory.setConnectTimeout(WEBSERVICES_TIMEOUT);
        advancedFactory.setReadTimeout(WEBSERVICES_TIMEOUT);
    } else if (factory instanceof SimpleClientHttpRequestFactory) {
        SimpleClientHttpRequestFactory advancedFactory = (SimpleClientHttpRequestFactory) factory;
        advancedFactory.setConnectTimeout(WEBSERVICES_TIMEOUT);
        advancedFactory.setReadTimeout(WEBSERVICES_TIMEOUT);
    }
    // web services support json responses
    MappingJacksonHttpMessageConverter jsonConverter = new MappingJacksonHttpMessageConverter();
    FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
    StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
    final List<HttpMessageConverter<?>> listHttpMessageConverters = restTemplate.getMessageConverters();
    listHttpMessageConverters.add(jsonConverter);
    listHttpMessageConverters.add(formHttpMessageConverter);
    listHttpMessageConverters.add(stringHttpMessageConverter);
    restTemplate.setMessageConverters(listHttpMessageConverters);
    return restTemplate;
}
Example 86
Project: DistributedSystemMonitoring-master  File: RestTemplateFactory.java View source code
RestTemplate restTemplate(UserCredentials user) {
    RestTemplate restTemplate = new RestTemplate();
    List<HttpMessageConverter<?>> converters = new ArrayList<>();
    converters.add(halConverter());
    if (user != null) {
        final List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
        interceptors.add(new BasicAuthInterceptor(user.getUsername(), user.getPassword()));
        restTemplate.setInterceptors(interceptors);
    }
    restTemplate.setMessageConverters(converters);
    return restTemplate;
}
Example 87
Project: DojoRioDroid-master  File: LocalActivity.java View source code
private GeoPoint setLocalMapCoordinates(String endereco) {
    String url = "http://maps.google.com/maps/geo?q={endereco}&output={output}&key={key}";
    String output = "json";
    String key = "0_CK7uBHqhyrxPsgFVRCpPU3_B_t3Egk54Q7xTQ";
    double longitude = 0;
    double latitude = 0;
    RestTemplate rest = new RestTemplate();
    String response = (String) rest.getForObject(url, String.class, endereco, output, key);
    Gson gson = new Gson();
    JsonResponse json = gson.fromJson(response, JsonResponse.class);
    for (PlacemarkEntity placemark : json.getPlacemark()) {
        longitude = placemark.getPoint().getCoordinates()[0];
        latitude = placemark.getPoint().getCoordinates()[1];
    }
    json.getPlacemark();
    return new GeoPoint(calculateLatLng(latitude), calculateLatLng(longitude));
}
Example 88
Project: eclipse-integration-commons-master  File: RestUtils.java View source code
////////////////////////////////////////////////////////////////////////////////////////////////////////////
//  Select methods, copied from cf-java-client lib's RestUtil with minor modifications to allow 
//  disabling redirect handling
public static RestTemplate createRestTemplate(HttpProxyConfiguration httpProxyConfiguration, boolean trustSelfSignedCerts, boolean disableRedirectHandling) {
    RestTemplate restTemplate = new LoggingRestTemplate();
    restTemplate.setRequestFactory(createRequestFactory(httpProxyConfiguration, trustSelfSignedCerts, disableRedirectHandling));
    restTemplate.setErrorHandler(new CloudControllerResponseErrorHandler());
    //TODO ^^^ But, we don't seem to need custom message convertors for what we do right now.
    return restTemplate;
}
Example 89
Project: enzymeportal-master  File: EbeyeSuggestionServiceTest.java View source code
@Before
public void setUp() {
    EbeyeIndexProps serverUrl = new EbeyeIndexProps();
    serverUrl.setChunkSize(CHUNK_SIZE);
    serverUrl.setMaxEbiSearchLimit(MAX_ENTRIES_IN_RESPONSE);
    serverUrl.setEnzymeCentricSearchUrl(SERVER_URL);
    RestTemplate restTemplate = new RestTemplate();
    restServerMock = MockRestServiceServer.createServer(restTemplate);
    ebeyeQueryService = new EbeyeSuggestionService(serverUrl, restTemplate);
}
Example 90
Project: fi-smp-master  File: JsonController.java View source code
@RequestMapping("/api/emreg")
@ResponseBody
public String emreg() throws URISyntaxException {
    String emreg = (String) context.getSession().getAttribute("emreg");
    if (emreg == null) {
        RestTemplate template = new RestTemplate();
        emreg = template.getForObject(new URI(emregUrl), String.class);
        context.getSession().setAttribute("emreg", emreg);
    }
    return emreg;
}
Example 91
Project: geoserver-master  File: GeoServerRestRoleServiceTest.java View source code
@Before
public void setUp() throws Exception {
    template = new RestTemplate();
    mockServer = MockRestServiceServer.createServer(template);
    mockServer.expect(requestTo(uri + "/api/roles")).andRespond(withSuccess("{\"groups\": [\"anonymous\", \"test\", \"admin\"]}", MediaType.APPLICATION_JSON));
    mockServer.expect(requestTo(uri + "/api/adminRole")).andRespond(withSuccess("{\"adminRole\": \"admin\"}", MediaType.APPLICATION_JSON));
    mockServer.expect(requestTo(uri + "/api/users/test")).andRespond(withSuccess("{\"users\": [{\"username\": \"test\", \"groups\": [\"test\"]}]}", MediaType.APPLICATION_JSON));
    mockServer.expect(requestTo(uri + "/api/adminRole")).andRespond(withSuccess("{\"adminRole\": \"admin\"}", MediaType.APPLICATION_JSON));
    mockServer.expect(requestTo(uri + "/api/users/test@geoserver.org")).andRespond(withSuccess("{\"users\": [{\"username\": \"test\", \"groups\": [\"test\"]}]}", MediaType.APPLICATION_JSON));
    mockServer.expect(requestTo(uri + "/api/adminRole")).andRespond(withSuccess("{\"adminRole\": \"admin\"}", MediaType.APPLICATION_JSON));
    mockServer.expect(requestTo(uri + "/api/users/admin")).andRespond(withSuccess("{\"users\": [{\"username\": \"admin\", \"groups\": [\"admin\"]}]}", MediaType.APPLICATION_JSON));
    mockServer.expect(requestTo(uri + "/api/adminRole")).andRespond(withSuccess("{\"adminRole\": \"admin\"}", MediaType.APPLICATION_JSON));
}
Example 92
Project: gina-puffinfeeder-android-viewer-master  File: JsonSpiceService.java View source code
@Override
public RestTemplate createRestTemplate() {
    RestTemplate restTemplate = new RestTemplate() {

        @Override
        protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException {
            ClientHttpRequest request = super.createRequest(url, method);
            HttpHeaders headers = request.getHeaders();
            headers.setAcceptEncoding(ContentCodingType.GZIP);
            return request;
        }
    };
    // bug on http connection for Android < 2.2
    // http://android-developers.blogspot.fr/2011/09/androids-http-clients.html
    // but still a problem for upload with Spring-android on android 4.1
    System.setProperty("http.keepAlive", "false");
    // set timeout for requests
    ClientHttpRequestFactory factory = restTemplate.getRequestFactory();
    if (factory instanceof HttpComponentsClientHttpRequestFactory) {
        HttpComponentsClientHttpRequestFactory advancedFactory = (HttpComponentsClientHttpRequestFactory) factory;
        advancedFactory.setConnectTimeout(WEBSERVICES_TIMEOUT);
        advancedFactory.setReadTimeout(WEBSERVICES_TIMEOUT);
    } else if (factory instanceof SimpleClientHttpRequestFactory) {
        SimpleClientHttpRequestFactory advancedFactory = (SimpleClientHttpRequestFactory) factory;
        advancedFactory.setConnectTimeout(WEBSERVICES_TIMEOUT);
        advancedFactory.setReadTimeout(WEBSERVICES_TIMEOUT);
    }
    // web services support json responses
    MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
    FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
    StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
    final List<HttpMessageConverter<?>> listHttpMessageConverters = restTemplate.getMessageConverters();
    listHttpMessageConverters.add(jsonConverter);
    listHttpMessageConverters.add(formHttpMessageConverter);
    listHttpMessageConverters.add(stringHttpMessageConverter);
    restTemplate.setMessageConverters(listHttpMessageConverters);
    return restTemplate;
}
Example 93
Project: github-java-api-master  File: RepositoryBrowser.java View source code
/**
     * Browse repositories for a user
     *
     * @param argUsername {@link String} username
     * @return {@link List} containing {@link Repository} instances, empty List if user exists, but has no repositories
     * @throws NullPointerException in case passed username is null
     * @throws HttpClientErrorException in case the user doesn't exist
     */
public List<Repository> browse(String argUsername) {
    RestTemplate template = initTemplate();
    RepositoriesResponse resp = template.getForObject(REPOSITORIES_URL, RepositoriesResponse.class, argUsername);
    if (resp == null || resp.getRepositories() == null || resp.getRepositories().length == 0) {
        return Collections.emptyList();
    } else {
        return Arrays.asList(resp.getRepositories());
    }
}
Example 94
Project: jdip-web-master  File: SocialConfig.java View source code
@Bean
public Facebook facebookApp() {
    // retrieve app access token
    RestTemplate restTemplate = new RestTemplate();
    String result = restTemplate.getForObject("https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=" + environment.getProperty("facebook.clientId") + "&client_secret=" + environment.getProperty("facebook.clientSecret"), String.class);
    String appAccessToken = result.replaceAll("access_token=", "");
    FacebookTemplate fbt = new FacebookTemplate(appAccessToken);
    return fbt;
}
Example 95
Project: jVoiD-master  File: UserAuthenticationProvider.java View source code
//	JSONObject userservice;
//	public UserAuthenticationProvider(JSONObject userservice) {
//		this.userservice = userservice;
//	}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    // Make an API Call to the Customer WAR to get the user data based on this email address.
    //JSONObject user = userservice.getCustomerByEmail(username);
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(ServerUris.CUSTOMER_SERVER_URI + URIConstants.GET_CUSTOMER_BY_EMAIL).queryParam("params", "{email: " + username + "}");
    HttpEntity<?> entity = new HttpEntity<>(headers);
    HttpEntity<String> returnString = restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, entity, String.class);
    SerializableJSONObject user = null;
    try {
        JSONObject temp = new JSONObject(returnString.getBody());
        user = new SerializableJSONObject(temp);
        System.out.println("User: " + user.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }
    if (user == null) {
        throw new UsernameNotFoundException(String.format("User %s not exist!", username));
    }
    return new UserRepositoryUserDetails(user);
}
Example 96
Project: login-server-master  File: NotificationsServiceTest.java View source code
@Before
public void setUp() {
    notificationsTemplate = new RestTemplate();
    mockNotificationsServer = MockRestServiceServer.createServer(notificationsTemplate);
    uaaTemplate = Mockito.mock(RestTemplate.class);
    notifications = new HashMap<>();
    HashMap<String, Object> passwordResetNotification = new HashMap<>();
    passwordResetNotification.put("id", "kind-id-01");
    passwordResetNotification.put("description", "password reset");
    passwordResetNotification.put("critical", true);
    notifications.put(MessageType.PASSWORD_RESET, passwordResetNotification);
    notificationsService = new NotificationsService(notificationsTemplate, "http://notifications.example.com", notifications, uaaTemplate, "http://uaa.com");
    response = new HashMap<>();
    List<Map<String, String>> resources = new ArrayList<>();
    Map<String, String> userDetails = new HashMap<>();
    userDetails.put("id", "user-id-01");
    resources.add(userDetails);
    response.put("resources", resources);
    mockNotificationsServer.expect(requestTo("http://notifications.example.com/registration")).andExpect(method(PUT)).andExpect(jsonPath("$.source_description").value("CF_Identity")).andExpect(jsonPath("$.kinds[0].id").value("kind-id-01")).andExpect(jsonPath("$.kinds[0].description").value("password reset")).andExpect(jsonPath("$.kinds[0].critical").value(true)).andRespond(withSuccess());
}
Example 97
Project: OpenESPI-ThirdParty-java-master  File: ResourceRESTRepositoryImplTests.java View source code
@SuppressWarnings("unchecked")
@Before
public void before() {
    repository = new ResourceRESTRepositoryImpl();
    marshaller = mock(Jaxb2Marshaller.class);
    template = mock(RestTemplate.class);
    ResponseEntity<String> response = new ResponseEntity<String>(HttpStatus.OK);
    when(template.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), any(Class.class))).thenReturn(response);
    repository.setRestTemplate(template);
    repository.setJaxb2Marshaller(marshaller);
    authorization = new Authorization();
    authorization.setAccessToken("token");
    uri = Routes.DATA_CUSTODIAN_REST_USAGE_POINT_GET;
}
Example 98
Project: PerformanceHat-master  File: FeedbackHandlerMonitoringClient.java View source code
/**
   * Sends monitoring data (i.e. the call trace) and its attached metrics to the Feedback Handler.
   * 
   * @param executions
   *          the {@link RunningProcedureExecution}'s (i.e. the call trace)
   * @return <code>true</code> if the data has been successfully sent to the Feedback Handler, <code>false</code>
   *         otherwise
   */
public boolean postData(final RunningProcedureExecution rootProcedureExecution) {
    final MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add(Headers.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
    headers.add(Headers.ACCESS_TOKEN, accessToken());
    headers.add(Headers.APPLICATION_ID, applicationId());
    final HttpEntity<MetricContainingProcedureExecutionDto> httpEntity = new HttpEntity<MetricContainingProcedureExecutionDto>(rootProcedureExecution, headers);
    final ResponseEntity<Boolean> result = new RestTemplate().exchange(url(), HttpMethod.POST, httpEntity, Boolean.class);
    return result.getBody();
}
Example 99
Project: resteeth-master  File: ResteethAutowireCandidateResolverDelegate.java View source code
private synchronized void ensueBeanProxyCreatorInitialized() {
    if (!initialized) {
        initialized = true;
        RestTemplate restTemplate = provideRestTemplate(this.beanFactory);
        final Collection<RestInvocationHandler> handlers = SpringUtils.getBeansOfType(RestInvocationHandler.class, this.beanFactory);
        beanProxyCreator = new BeanProxyCreator(restTemplate, handlers);
    }
}
Example 100
Project: saos-master  File: CommonCourtImportConfiguration.java View source code
@Bean
public RestTemplate ccImportRestTemplate() {
    SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
    clientHttpRequestFactory.setConnectTimeout(ccImportConnectionTimeoutMs);
    clientHttpRequestFactory.setReadTimeout(ccImportReadTimeoutMs);
    RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
    List<HttpMessageConverter<?>> converters = Lists.newArrayList();
    converters.add(utf8StringHttpMessageConverter());
    restTemplate.setMessageConverters(converters);
    return restTemplate;
}
Example 101
Project: spring-advanced-marhshallers-and-service-exporters-master  File: MessagePackHttpMessageConverterTest.java View source code
@Override
public void doWithServer(RestTemplate clientRestTemplate, Server server) throws Throwable {
    Assert.assertNotNull(clientRestTemplate);
    int id = 344;
    Map<String, Object> mapOfVars = new HashMap<String, Object>();
    mapOfVars.put("cat", id);
    Cat customer = clientRestTemplate.getForEntity("http://localhost:8080/ws/cats/{cat}", Cat.class, mapOfVars).getBody();
    Assert.assertTrue(customer.getId() == id);
    Assert.assertNotNull(customer.getName());
    if (log.isDebugEnabled()) {
        log.debug("response payload: " + ToStringBuilder.reflectionToString(customer));
    }
}