Java Code Examples for org.springframework.web.client.RestTemplate.getForObject()

The following are Jave code examples for showing how to use getForObject() of the org.springframework.web.client.RestTemplate class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: twitch4j   File: StreamEndpoint.java   Source Code and License Vote up 7 votes
/**
 * Get Featured Streams
 * <p>
 * Gets a list of all featured live streams.
 * Requires Scope: none
 *
 * @param limit  Maximum number of most-recent objects to return. Default: 25. Maximum: 100.
 * @param offset Object offset for pagination of results. Default: 0.
 * @return The requested range/amount of featured streams.
 */
public List<StreamFeatured> getFeatured(Optional<Long> limit, Optional<Long> offset) {
	// Endpoint
	String requestUrl = String.format("%s/streams/featured", Endpoints.API.getURL());
	RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate();

	// Parameters
	restTemplate.getInterceptors().add(new QueryRequestInterceptor("limit", limit.orElse(25l).toString()));
	restTemplate.getInterceptors().add(new QueryRequestInterceptor("offset", offset.orElse(0l).toString()));

	// REST Request
	try {
		StreamFeaturedList responseObject = restTemplate.getForObject(requestUrl, StreamFeaturedList.class);

		return responseObject.getFeatured();
	} catch (Exception ex) {
		Logger.error(this, "Request failed: " + ex.getMessage());
		Logger.trace(this, ExceptionUtils.getStackTrace(ex));
	}

	return new ArrayList<StreamFeatured>();
}
 
Example 2
Project: twitch4j   File: StreamEndpoint.java   Source Code and License Vote up 7 votes
/**
 * Get recommended streams for User (Unofficial)
 * Gets a list of recommended streams for a user.
 * Requires Scope: none
 *
 * @param credential OAuthCredential of the user, you want to request recommendations for.
 * @return StreamList of random Streams.
 */
@Unofficial
public List<Recommendation> getRecommendations(OAuthCredential credential) {
	// Endpoint
	String requestUrl = String.format("%s/streams/recommended", Endpoints.API.getURL());
	RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate();

	// Parameters
	restTemplate.getInterceptors().add(new QueryRequestInterceptor("oauth_token", credential.getToken()));

	// REST Request
	try {
		Logger.trace(this, "Rest Request to [%s]", requestUrl);
		RecommendationList responseObject = restTemplate.getForObject(requestUrl, RecommendationList.class);

		return responseObject.getRecommendedStreams();
	} catch (RestException restException) {
		Logger.error(this, "RestException: " + restException.getRestError().toString());
	} catch (Exception ex) {
		Logger.error(this, "Request failed: " + ex.getMessage());
		Logger.trace(this, ExceptionUtils.getStackTrace(ex));
	}

	return null;
}
 
Example 3
Project: twitch4j   File: SearchEndpoint.java   Source Code and License Vote up 7 votes
/**
 * Endpoint: Search Games
 * Searches for games based on a specified query parameter. A game is returned if the query parameter is matched entirely or partially, in the game name.
 * Requires Scope: none
 *
 * @param query search query
 * @param live Whether only games that are live should be returned. This argument is optional.
 * @return A list of games matching the query.
 */
public List<Game> getGames(String query, Optional<Boolean> live) {
	// Endpoint
	String requestUrl = String.format("%s/search/games", Endpoints.API.getURL());
	RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate();

	// Parameters
	restTemplate.getInterceptors().add(new QueryRequestInterceptor("query", query));
	restTemplate.getInterceptors().add(new QueryRequestInterceptor("live", live.orElse(false).toString()));

	// REST Request
	try {
		GameList responseObject = restTemplate.getForObject(requestUrl, GameList.class);

		return responseObject.getGames();
	} catch (RestException restException) {
		Logger.error(this, "RestException: " + restException.getRestError().toString());
	} catch (Exception ex) {
		Logger.error(this, "Request failed: " + ex.getMessage());
		Logger.trace(this, ExceptionUtils.getStackTrace(ex));
	}

	return null;
}
 
Example 4
Project: Java-9-Programming-By-Example   File: RestClientProductLookup.java   Source Code and License Vote up 6 votes
@Override
public ProductInformation byId(String id) {
    Map<String, String> uriParameters = new HashMap<>();
    uriParameters.put("id", id);
    RestTemplate rest = new RestTemplate();
    InventoryItemAmount amount =
            rest.getForObject(piSUBuilder.url("inventory"),
                    InventoryItemAmount.class,
                    uriParameters);
    log.info("amount {}.",amount);
    if ( amount.getAmount() > 0) {
        log.info("There items from {}. We are offering",id);
        return rest.getForObject(piSUBuilder.url("pi"),
                ProductInformation.class,
                uriParameters);
    } else {
        log.info("There are no items from {}. Amount is {}",id,amount);
        return ProductInformation.emptyProductInformation;
    }
}
 
Example 5
Project: twitch4j   File: StreamEndpoint.java   Source Code and License Vote up 6 votes
/**
 * Get Streams Summary
 * <p>
 * Gets a summary of all live streams.
 * Requires Scope: none
 *
 * @param game Restricts the summary stats to the specified game.
 * @return A <code>StreamSummary</code> object, that contains the total number of live streams and viewers.
 */
public StreamSummary getSummary(Optional<Game> game) {
	// Endpoint
	String requestUrl = String.format("%s/streams/summary", Endpoints.API.getURL());
	RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate();

	// Parameters
	restTemplate.getInterceptors().add(new QueryRequestInterceptor("game", game.map(Game::getName).orElse("")));

	// REST Request
	try {
		Logger.trace(this, "Rest Request to [%s]", requestUrl);
		StreamSummary responseObject = restTemplate.getForObject(requestUrl, StreamSummary.class);

		return responseObject;
	} catch (RestException restException) {
		Logger.error(this, "RestException: " + restException.getRestError().toString());
	} catch (Exception ex) {
		Logger.error(this, "Request failed: " + ex.getMessage());
		Logger.trace(this, ExceptionUtils.getStackTrace(ex));
	}

	return null;
}
 
Example 6
Project: twitch4j   File: ChannelFeedEndpoint.java   Source Code and License Vote up 6 votes
/**
 * Gets posts from a specified channel feed.
 *
 * @param channelId    The channel id, which the posts should be retrieved from.
 * @param limit        Maximum number of most-recent objects to return. Default: 10. Maximum: 100.
 * @param cursor       Tells the server where to start fetching the next set of results in a multi-page response.
 * @param commentLimit Specifies the number of most-recent comments on posts that are included in the response. Default: 5. Maximum: 5.
 * @return posts from a specified channel feed.
 */
public List<ChannelFeedPost> getFeedPosts(Long channelId, Optional<Long> limit, Optional<String> cursor, Optional<Long> commentLimit) {
	// Endpoint
	String requestUrl = String.format("%s/feed/%s/posts", Endpoints.API.getURL(), channelId);
	RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate();

	// Parameters
	restTemplate.getInterceptors().add(new QueryRequestInterceptor("limit", limit.orElse(10l).toString()));
	restTemplate.getInterceptors().add(new QueryRequestInterceptor("cursor", cursor.orElse("")));
	restTemplate.getInterceptors().add(new QueryRequestInterceptor("comments", commentLimit.orElse(5l).toString()));

	// REST Request
	try {
		Logger.trace(this, "Rest Request to [%s]", requestUrl);
		ChannelFeed responseObject = restTemplate.getForObject(requestUrl, ChannelFeed.class);

		return responseObject.getPosts();
	} catch (RestException restException) {
		Logger.error(this, "RestException: " + restException.getRestError().toString());
	} catch (Exception ex) {
		Logger.error(this, "Request failed: " + ex.getMessage());
		Logger.trace(this, ExceptionUtils.getStackTrace(ex));
	}

	return new ArrayList<ChannelFeedPost>();
}
 
Example 7
Project: spring-cloud-dashboard   File: DataFlowTemplate.java   Source Code and License Vote up 6 votes
/**
 * Setup a {@link DataFlowTemplate} using the provide {@link RestTemplate}. Any missing Mixins for Jackson will be
 * added implicitly. For more information, please see {@link #prepareRestTemplate(RestTemplate)}.
 *
 * @param baseURI Must not be null
 * @param restTemplate Must not be null
 */
public DataFlowTemplate(URI baseURI, RestTemplate restTemplate) {

	Assert.notNull(baseURI, "The provided baseURI must not be null.");
	Assert.notNull(restTemplate, "The provided restTemplate must not be null.");

	this.restTemplate = prepareRestTemplate(restTemplate);
	final ResourceSupport resourceSupport = restTemplate.getForObject(baseURI, ResourceSupport.class);
	this.runtimeOperations = new RuntimeTemplate(restTemplate, resourceSupport);
	this.appRegistryOperations = new AppRegistryTemplate(restTemplate, resourceSupport);
	this.completionOperations = new CompletionTemplate(restTemplate,
		resourceSupport.getLink("completions/stream"),
		resourceSupport.getLink("completions/task"));
	if (resourceSupport.hasLink(ApplicationTemplate.DEFINITIONS_REL)) {
		this.applicationOperations = new ApplicationTemplate(restTemplate, resourceSupport);
	}
	else {
		this.applicationOperations = null;
	}
}
 
Example 8
Project: waggle-dance   File: WaggleDanceIntegrationTest.java   Source Code and License Vote up 6 votes
@Test
public void restApiGetStatus() throws Exception {
  exit.expectSystemExitWithStatus(0);

  runner = WaggleDanceRunner
      .builder(configLocation)
      .primary("primary", localServer.getThriftConnectionUri(), READ_ONLY)
      .federate("waggle_remote", remoteServer.getThriftConnectionUri(), REMOTE_DATABASE)
      .build();

  runWaggleDance(runner);

  RestTemplate rest = new RestTemplateBuilder().build();
  PrimaryMetaStore primaryMetastore = rest.getForObject("http://localhost:18000/api/admin/federations/primary",
      PrimaryMetaStore.class);
  assertThat(primaryMetastore.getStatus(), is(MetaStoreStatus.AVAILABLE));
  FederatedMetaStore federatedMetastore = rest
      .getForObject("http://localhost:18000/api/admin/federations/waggle_remote", FederatedMetaStore.class);
  assertThat(federatedMetastore.getStatus(), is(MetaStoreStatus.AVAILABLE));
}
 
Example 9
Project: twitch4j   File: CommunityEndpoint.java   Source Code and License Vote up 6 votes
/**
 * Endpoint: Get Top Communities
 * Gets a specified community.
 * Requires Scope: none
 *
 * @param limit  Maximum number of most-recent objects to return. Default: 25. Maximum: 100.
 * @param cursor Tells the server where to start fetching the next set of results in a multi-page response.
 * @return The top communities.
 */
public CommunityList getTopCommunities(Optional<Long> limit, Optional<String> cursor) {
	// Endpoint
	String requestUrl = String.format("%s/communities/top", Endpoints.API.getURL());
	RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate();

	// Parameters
	restTemplate.getInterceptors().add(new QueryRequestInterceptor("limit", limit.orElse(25l).toString()));
	restTemplate.getInterceptors().add(new QueryRequestInterceptor("cursor", cursor.orElse("")));

	// REST Request
	try {
		CommunityList responseObject = restTemplate.getForObject(requestUrl, CommunityList.class);

		return responseObject;
	} catch (RestException restException) {
		Logger.error(this, "RestException: " + restException.getRestError().toString());
	} catch (Exception ex) {
		Logger.error(this, "Request failed: " + ex.getMessage());
		Logger.trace(this, ExceptionUtils.getStackTrace(ex));
	}

	return null;
}
 
Example 10
Project: Sound.je   File: YoutubeReader.java   Source Code and License Vote up 5 votes
/**
 * This is the method that actually makes the http request
 *
 * @param url              request url
 * @param deconstructClass class of request object
 * @param <T>              type of request object this is
 * @return request object
 */
private <T> T request(final String url, final Class<T> deconstructClass) {
    final RestTemplate restTemplate = new RestTemplate();
    T deconstructedResponse = null;

    try {
        deconstructedResponse = restTemplate.getForObject(url, deconstructClass);
    } catch (HttpClientErrorException err) {
        logger.info("[YoutubeReader] [request] Failure To Retrieve YouTube Resource (" + url + ")", err);
    }

    return deconstructedResponse;
}
 
Example 11
Project: keti   File: ACSTestUtil.java   Source Code and License Vote up 5 votes
public static boolean isServerListening(final URI url) {
    RestTemplate restTemplate = new RestTemplate();
    try {
        restTemplate.getForObject(url, String.class);
    } catch (RestClientException e) {
        if (e.getCause() instanceof ConnectException) {
            return false;
        }
    }
    return true;
}
 
Example 12
Project: cf-mta-deploy-service   File: CFOptimizedSpaceGetter.java   Source Code and License Vote up 5 votes
private CloudSpace executeFindSpaceRequest(RestTemplate restTemplate, String url, Map<String, Object> urlVariables) {
    String response = restTemplate.getForObject(url, String.class, urlVariables);
    Map<String, Object> parsedResponse = parseResponse(response);
    validateResponse(parsedResponse);
    return toCloudSpace(parsedResponse);
}
 
Example 13
Project: argument-reasoning-comprehension-task   File: LMClassifier.java   Source Code and License Vote up 5 votes
/**
 * Creates a new REST service client and connects to the language model
 *
 * @param server server
 * @param port   port
 */
public LMClassifier(String server, int port)
{
    uri = "http://" + server + ":" + port + "/logprob/{sentence}";

    Map<String, String> params = new HashMap<>();
    params.put("sentence", "This is a test");

    restTemplate = new RestTemplate();
    restTemplate.getForObject(uri, Double.class, params);
}
 
Example 14
Project: asw   File: TeamRestClient.java   Source Code and License Vote up 5 votes
public void run(String[] args) {
		RestTemplate restTemplate = new RestTemplate(); 
		Team team = restTemplate.getForObject("http://localhost:8080/team", Team.class);
		
		/* ripete tante volte, altrimenti si perde tra i log di Spring Boot */
		for (int i=0; i<10; i++) {
			logger.info( team.getName() );
//			System.out.println( team.getName() );
		}
	}
 
Example 15
Project: java-web-services-training   File: GetGeonamesApplication.java   Source Code and License Vote up 5 votes
public static void main(String[] args)
		throws IOException, URISyntaxException {
	RestTemplate restTemplate = new RestTemplate();
	GeonamesSearchResult searchResult = restTemplate.getForObject(
			"http://api.geonames.org/searchJSON?q={q}&username={username}",
		GeonamesSearchResult.class,
			ImmutableMap.of("q", "kabupaten garut", "username", "ceefour"));
	LOG.info("Body (GeonamesSearchResult): {}", searchResult);
	for (Geoname child : searchResult.getGeonames()) {
		LOG.info("Place: {} ({}, {})",
				child.getToponymName(), child.getLat(), child.getLng());
	}
}
 
Example 16
Project: MicroServiceProject   File: UserService.java   Source Code and License Vote up 5 votes
@HystrixCommand(fallbackMethod = "fallbackSearchAll")
public UserInfo getUserInfo(String userid) {
    restTemplate = new RestTemplate();
    return restTemplate.getForObject("http://"+SERVICE_NAME+"/user"+"?userid="+userid, UserInfo.class);
}
 
Example 17
Project: hippo-external-document-picker-example-implementation   File: DocumentServiceFacade.java   Source Code and License Vote up 5 votes
/**
 * Make a simple request to your rest webservice
 *
 * @param queryString
 */
private void getDocumentsFromExternalSource(String queryString) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    RestTemplate restTemplate = new RestTemplate();
    try {
        String result = restTemplate.getForObject(JSON_REST_URL + "?q=" + queryString, String.class);
        docArray = (JSONArray) JSONSerializer.toJSON(result);
        log.info("Retrieved {} documents from {}", docArray.size(), JSON_REST_URL + "?q=" + queryString);
    } catch (Exception e) {
        log.warn("Couldnt get from endpoint: {}", e.getMessage());
    }
}
 
Example 18
Project: cf-mta-deploy-service   File: LoggingEndpointGetter.java   Source Code and License Vote up 5 votes
private String attmeptToGetLoggingEndpoint(CloudFoundryOperations client) {
    RestTemplate restTemplate = getRestTemplate(client);
    String controllerUrl = client.getCloudControllerUrl().toString();
    String infoV2Url = getUrl(controllerUrl, V2_INFO_ENDPOINT);

    String infoV2Json = restTemplate.getForObject(infoV2Url, String.class);
    Map<String, Object> infoV2Map = JsonUtil.convertJsonToMap(infoV2Json);

    // The standard CloudFoundryOperations.getCloudInfo() method tries to retrieve the logging endpoint from a field named
    // 'logging_endpoint', which was replaced with 'doppler_logging_endpoint' in
    // https://github.com/cloudfoundry/cloud_controller_ng/commit/b02a23c38ebda79a3bbd2c78716c627147bf042f.
    return CloudUtil.parse(String.class, infoV2Map.get("doppler_logging_endpoint"));
}
 
Example 19
Project: edoras-one-initializr   File: EdorasoneMetadataReader.java   Source Code and License Vote up 4 votes
/**
 * Parse the content of the metadata at the specified url
 */
public EdorasoneMetadataReader(RestTemplate restTemplate, String url) {
	this.content = new JSONObject(restTemplate.getForObject(url, String.class));
}
 
Example 20
Project: csap-core   File: Docker_Java.java   Source Code and License Vote up 4 votes
private CreateContainerResponse startNginx ()
		throws InterruptedException, IOException {
	String imageName = "nginx";
	loadImageIfNeeded( imageName );
	String containerName = "/junit-nginx-"
			+ LocalDateTime.now().format( DateTimeFormatter.ofPattern( "MMM.d-HH.mm.ss" ) );

	List<String> entryParameters = Arrays.asList( "nginx", "-g", "daemon off;" );
	List<String> cmdParameters = Arrays.asList( "nginx", "-v" );

	ExposedPort exposedPort = ExposedPort.tcp( 7080 );
	List<ExposedPort> exposedList = new ArrayList<>();
	exposedList.add( exposedPort );

	Ports portBindings = new Ports();
	portBindings.bind(
		ExposedPort.tcp( 80 ),
		Ports.Binding.bindPort( exposedPort.getPort() ) );

	CreateContainerResponse createResponse = dockerClient
		.createContainerCmd( imageName )
		.withName( containerName )
		// .withCmd( cmdParameters )
		.withEntrypoint( entryParameters )
		.withExposedPorts( exposedList )
		.withPortBindings( portBindings )
		.exec();

	dockerClient
		.startContainerCmd( createResponse.getId() )
		.exec();

	Thread.sleep( 500 );
	RestTemplate springTemplate = new RestTemplate();
	String testUrl = "http://localhost:" + exposedPort.getPort();
	String response = springTemplate.getForObject( testUrl, String.class );

	logger.info( "Testing url: {} \n\t response: {}", testUrl, response );

	assertThat( response )
		.as( "welcome message" )
		.contains( "Welcome to nginx!" );

	int maxAttempts = 20;
	String startUpMessage = "GET";

	boolean foundStartMessage = waitForMessageInLogs(
		createResponse.getId(), maxAttempts, startUpMessage );

	assertThat( foundStartMessage )
		.as( "found in logs:" + startUpMessage )
		.isTrue();
	return createResponse;
}