Skip to content

Commit

Permalink
Adicao de conteudo da Aula 02
Browse files Browse the repository at this point in the history
  • Loading branch information
durvalprintes committed Jul 21, 2022
1 parent d7a43b2 commit cd8f4d5
Show file tree
Hide file tree
Showing 10 changed files with 201 additions and 75 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
target
.vscode
.vscode
sticker/
14 changes: 10 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,13 @@
<img width=400px height=200px src="https://i.ytimg.com/vi/WdT90ffB-0Q/maxresdefault.jpg" alt="Project logo"></a>
</p>

<h3 align="center">Projeto de Imersão em Java</h3>
<h3 align="center">PROJETO DE IMERSÃO EM JAVA</h3>

<div align="center">

[![Status](https://img.shields.io/badge/Status-Em%20Desenvolvimento-green)]()

</div>

---

Expand Down Expand Up @@ -75,9 +81,9 @@ Exemplos da saída atual:

Conteúdo a partir da Aula 02:
- [x] Limpeza da classe Main (com.alura.App) e reorganização do projeto.
- [ ] Extração da imagem da uma URL (campo do objeto de retorno da API IMDB);
- [ ] Manipulação de imagens;
- [ ] Salvar nova imagem em disco;
- [x] Extração da imagem da uma URL (campo do objeto de retorno da API IMDB);
- [x] Manipulação de imagens;
- [x] Salvar imagens em disco;
- [ ] Desafios;


Expand Down
File renamed without changes
File renamed without changes
Binary file added data/image/readme/Aula2.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
14 changes: 8 additions & 6 deletions src/main/java/com/alura/App.java
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
package com.alura;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import com.alura.model.Endpoint;
import com.alura.service.WebService;
import com.alura.service.impl.ImdbService;

@SuppressWarnings("squid:S125")
public class App {

public static void main(String[] args) {
try {
WebService imdb = new WebService(Endpoint.IMDB_MOST_POPULAR_TV, System.getProperty("key"));
imdb.updateWithMyRating(new FileInputStream(new File("data/rating.json")));
imdb.printMovies();
ImdbService api = new ImdbService(Endpoint.IMDB_MOST_POPULAR_TV, System.getProperty("key"));
// api.updateMoviesWithMyRating(new FileInputStream(new
// File("data/rating.json")));
api.shrinkListMovies(5);
// api.printMovies();
api.generateStickerPosterImage("data/image/sticker/");
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/com/alura/model/Endpoint.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ public enum Endpoint {
IMDB_TOP_250_MOVIES("https://imdb-api.com/en/API/Top250Movies/"),
IMDB_MOST_POPULAR_MOVIES("https://imdb-api.com/en/API/MostPopularMovies/"),
IMDB_TOP_250_TV("https://imdb-api.com/en/API/Top250TVs/"),
IMDB_MOST_POPULAR_TV("https://imdb-api.com/en/API/MostPopularTVs/");
IMDB_MOST_POPULAR_TV("https://imdb-api.com/en/API/MostPopularTVs/"),
IMDB_POSTERS("https://imdb-api.com/en/API/Posters/");

private String url;

Expand Down
20 changes: 20 additions & 0 deletions src/main/java/com/alura/model/Poster.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.alura.model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
public class Poster {

private String idMovie;
private String id;
private String link;
private Double aspectRatio;
private Integer width;
private Integer length;

}
105 changes: 42 additions & 63 deletions src/main/java/com/alura/service/WebService.java
Original file line number Diff line number Diff line change
@@ -1,86 +1,65 @@
package com.alura.service;

import static java.awt.Transparency.TRANSLUCENT;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.font.TextLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import com.alura.model.Endpoint;
import com.alura.model.Movie;
import com.alura.model.Rating;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.Getter;
import lombok.Setter;

@SuppressWarnings({ "squid:S106", "squid:S2325" })
@Getter
@Setter
public class WebService {
import javax.imageio.ImageIO;

private List<Movie> movies;
@SuppressWarnings("squid:S106")
public interface WebService {

public WebService(Endpoint api, String key) throws IOException, InterruptedException {
var mapper = new ObjectMapper();
this.movies = mapper.treeToValue(
mapper.readTree(jsonFromApi(api.getUrl() + key)).get("items"),
mapper.getTypeFactory().constructCollectionType(
List.class,
Movie.class));
}

private String jsonFromApi(String api) throws IOException, InterruptedException {
default String jsonFromGet(String url) throws IOException, InterruptedException {
return HttpClient.newHttpClient()
.send(HttpRequest.newBuilder(URI.create(api)).GET().build(),
.send(HttpRequest.newBuilder(URI.create(url)).GET().build(),
BodyHandlers.ofString())
.body();
}

private void printField(String format, String field) {
default void printField(String format, String field) {
System.out.println(format + field + "\033[0m");
}

private String countStarRating(Double rating) {
StringBuilder star = new StringBuilder();
for (int i = 0; i < Math.round(rating); i++) {
star.append("\u2605 ");
}
return star.toString();
}
default void createSticker(InputStream inputImage, String title, String output) throws IOException {

public void printMovies() {
for (Movie movie : this.movies) {
printField("\033[1;37m", "\nTitulo: " + movie.getTitle());
printField("\033[1;37m", "Image: " + movie.getImage());
Optional.ofNullable(movie.getImDbRating()).ifPresentOrElse(
rating -> {
printField("\033[0;105m", "Classificacao: " + rating);
printField("\033[1;33m", countStarRating(rating));
},
() -> printField("\033[0;105m", "Sem classificacao"));
Optional.ofNullable(movie.getMyRating()).ifPresent(
rating -> printField("\033[1;31m", "Minha nota: " + rating));
}
}
final Integer heightPlus = 200;
final String text = "IMERSÃO JAVA";
final String format = "png";

BufferedImage movieImage = ImageIO.read(inputImage);
BufferedImage sticker = new BufferedImage(movieImage.getWidth(), movieImage.getHeight() + heightPlus,
TRANSLUCENT);

Graphics2D graphic = (Graphics2D) sticker.getGraphics();
graphic.drawImage(movieImage, 0, 0, null);

public void updateWithMyRating(InputStream inputRating) throws IOException {
List<Rating> listRating = new ObjectMapper().readValue(inputRating, new TypeReference<List<Rating>>() {
});
if (!listRating.isEmpty()) {
this.movies = this.movies.stream()
.map(movie -> {
listRating.stream()
.filter(myRating -> myRating.getId().equals(movie.getId()))
.findFirst().ifPresent(rating -> movie.setMyRating(rating.getMyRating()));
return movie;
})
.collect(Collectors.toList());
}
var font = new Font("Impact", Font.PLAIN, 128);
Shape textShape = new TextLayout(text, font, graphic.getFontRenderContext()).getOutline(null);

FontMetrics metrics = graphic.getFontMetrics(font);
graphic.translate((sticker.getWidth() - textShape.getBounds().width) / 2,
((heightPlus - textShape.getBounds().height) / 2) + metrics.getAscent() + movieImage.getHeight());
graphic.setColor(Color.BLACK);
graphic.fill(textShape);
graphic.setStroke(new BasicStroke(5));
graphic.setColor(Color.YELLOW);
graphic.draw(textShape);

ImageIO.write(sticker, format, new File(output + title + "." + format));
}

}
117 changes: 117 additions & 0 deletions src/main/java/com/alura/service/impl/ImdbService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package com.alura.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.Optional;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import com.alura.model.Endpoint;
import com.alura.model.Movie;
import com.alura.model.Poster;
import com.alura.model.Rating;
import com.alura.service.WebService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@SuppressWarnings("squid:S106")
public class ImdbService implements WebService {

private String key;
private List<Movie> movies;

public ImdbService(Endpoint endpoint, String key) throws IOException, InterruptedException {
this.key = key;
this.movies = this.getListImdb(endpoint);
}

private List<Movie> getListImdb(Endpoint endpoint) throws IOException, InterruptedException {
var mapper = new ObjectMapper();
return mapper.treeToValue(
mapper.readTree(jsonFromGet(endpoint.getUrl() + this.key)).get("items"),
mapper.getTypeFactory().constructCollectionType(
List.class,
Movie.class));
}

public void printMovies() {
for (Movie movie : this.movies) {
printField("\033[1;37m", "\nTitulo: " + movie.getTitle());
printField("\033[1;37m", "Image: " + movie.getImage());
Optional.ofNullable(movie.getImDbRating()).ifPresentOrElse(
rating -> {
printField("\033[0;105m", "Classificacao: " + rating);
printField("\033[1;33m", "\u2605 ".repeat((int) Math.round(rating)));
},
() -> printField("\033[0;105m", "Sem classificacao"));
Optional.ofNullable(movie.getMyRating()).ifPresent(
rating -> printField("\033[1;31m", "Minha nota: " + rating));
}
}

public void shrinkListMovies(int max) {
setMovies(this.movies.subList(0, max));
}

public void updateMoviesWithMyRating(InputStream inputRating) throws IOException {
List<Rating> listRating = new ObjectMapper().readValue(inputRating, new TypeReference<List<Rating>>() {
});
if (!listRating.isEmpty()) {
this.movies = this.movies.stream()
.map(movie -> {
listRating.stream()
.filter(myRating -> myRating.getId().equals(movie.getId()))
.findFirst().ifPresent(rating -> movie.setMyRating(rating.getMyRating()));
return movie;
})
.collect(Collectors.toList());
}
}

public void generateStickerPosterImage(String output) {
System.out.print("Iniciando geração...");
this.movies.stream().forEach(
movie -> {
try {
createSticker(
new URL(Pattern.compile("\\._(.+).jpg$").matcher(movie.getImage()).replaceAll(".jpg")).openStream(),
movie.getTitle(), output);
} catch (IOException e) {
e.printStackTrace();
}
});
System.out.println("Finalizado!");
}

/**
* @param movie
* @return The Poster object at the IMDB Poster Endpoint
* @see Poster
*/
private Poster getMoviePoster(Movie movie) {
try {
var mapper = new ObjectMapper();
var url = String.format("%s%s/%s", Endpoint.IMDB_POSTERS.getUrl(), this.key, movie.getId());
Poster poster = mapper.treeToValue(
mapper
.readTree(jsonFromGet(url))
.get("posters")
.get(0),
Poster.class);
poster.setIdMovie(movie.getId());
return poster;
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return null;
}
}

0 comments on commit cd8f4d5

Please sign in to comment.