use of com.spotify.apollo.example.data.Track in project apollo by spotify.
the class ArtistResource method parseTopTracks.
/**
* Parses an artist top tracks response from the
* <a href="https://developer.spotify.com/web-api/get-artists-top-tracks/">Spotify API</a>
*
* @param json The json response
* @return A list of top tracks
*/
private ArrayList<Track> parseTopTracks(String json) {
ArrayList<Track> tracks = new ArrayList<>();
try {
JsonNode jsonNode = this.objectMapper.readTree(json);
for (JsonNode trackNode : jsonNode.get("tracks")) {
JsonNode albumNode = trackNode.get("album");
String albumName = albumNode.get("name").asText();
String artistName = trackNode.get("artists").get(0).get("name").asText();
String trackName = trackNode.get("name").asText();
tracks.add(new Track(trackName, new Album(albumName, new Artist(artistName))));
}
} catch (IOException e) {
throw new RuntimeException("Failed to parse JSON", e);
}
return tracks;
}
use of com.spotify.apollo.example.data.Track in project apollo by spotify.
the class ArtistResource method getArtistTopTracks.
CompletionStage<Response<ArrayList<Track>>> getArtistTopTracks(RequestContext requestContext) {
// Validate request
Optional<String> query = requestContext.request().parameter("q");
if (!query.isPresent()) {
return CompletableFuture.completedFuture(Response.forStatus(Status.BAD_REQUEST.withReasonPhrase("No search query")));
}
String country = requestContext.pathArgs().get("country");
// We need to first query the search API, parse the result, then query top-tracks.
Request searchRequest = Request.forUri(SEARCH_API + "?type=artist&q=" + query.get());
Client client = requestContext.requestScopedClient();
return client.send(searchRequest).thenComposeAsync(response -> {
String topArtistId = parseFirstArtistId(response.payload().get().utf8());
Request topTracksRequest = Request.forUri(String.format("%s/%s/top-tracks?country=%s", ARTIST_API, topArtistId, country));
return client.send(topTracksRequest);
}).thenApplyAsync(response -> Response.ok().withPayload(parseTopTracks(response.payload().get().utf8()))).exceptionally(throwable -> Response.forStatus(Status.INTERNAL_SERVER_ERROR.withReasonPhrase("Something failed")));
}
Aggregations