diff --git a/build.gradle.kts b/build.gradle.kts index ee5dc69..7f64a8a 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,5 +1,6 @@ plugins { id("java") + application } group = "org.example" @@ -20,4 +21,8 @@ dependencies { tasks.test { useJUnitPlatform() +} + +application { + mainClass.set("org.example.Main") } \ No newline at end of file diff --git a/src/main/java/org/example/Main.java b/src/main/java/org/example/Main.java index e6c60a7..951dd2c 100644 --- a/src/main/java/org/example/Main.java +++ b/src/main/java/org/example/Main.java @@ -13,7 +13,7 @@ import org.jsoup.Connection; import org.jsoup.Jsoup; import java.io.FileInputStream; -import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -39,9 +39,62 @@ public class Main { return; } - int[] idsEscaloes = {1, 3, 2}; - String[] nomesEscaloes = {"seniores", "juniores", "feminino"}; Gson gson = new Gson(); + Map clubesMap = new HashMap<>(); + + // 1. Obter todos os Clubes e seus meta-dados iniciais + System.out.println("\n--- A EXTRAIR DADOS DE TODOS OS CLUBES ---"); + try { + String urlTodosClubes = "https://api.afavcd.pt/teams"; + String jsonTodosClubes = Jsoup.connect(urlTodosClubes) + .ignoreContentType(true) + .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64)") + .header("Referer", "https://www.afavcd.pt/") + .header("Origin", "https://www.afavcd.pt") + .method(Connection.Method.GET) + .execute() + .body(); + + List> dadosClubes = gson.fromJson(jsonTodosClubes, + new TypeToken>>() { + }.getType()); + + for (Map c : dadosClubes) { + if (c.get("teamID") != null) { + int clubId = (int) Double.parseDouble(c.get("teamID").toString()); + Club club = new Club(); + club.setId(clubId); + if (c.get("name") != null) + club.setName(c.get("name").toString()); + if (c.get("logoURL") != null) + club.setImageUrl(c.get("logoURL").toString()); + if (c.get("president") != null) + club.setPresident(c.get("president").toString()); + if (c.get("address") != null) + club.setAddress(c.get("address").toString()); + if (c.get("field") != null) + club.setStadium(c.get("field").toString()); + + if (c.get("dateFundation") != null) { + try { + club.setFoundationYear((int) Double.parseDouble(c.get("dateFundation").toString())); + } catch (NumberFormatException e) { + club.setFoundationYear(0); + } + } + clubesMap.put(clubId, club); + } + } + System.out.println("Encontrados " + clubesMap.size() + " clubes."); + } catch (Exception e) { + System.err.println("Erro ao obter lista de clubes."); + e.printStackTrace(); + return; + } + + // 2. Obter escalões + int[] idsEscaloes = { 1, 3, 2 }; + String[] nomesEscaloes = { "seniores", "juniores", "feminino" }; for (int i = 0; i < idsEscaloes.length; i++) { int idAtual = idsEscaloes[i]; @@ -63,19 +116,22 @@ public class Main { .execute() .body(); - List> dadosClubes = gson.fromJson(jsonResponse, new TypeToken>>() {}.getType()); + List> equipasEscalao = gson.fromJson(jsonResponse, + new TypeToken>>() { + }.getType()); - for (Map dadoClube : dadosClubes) { + for (Map equipa : equipasEscalao) { int clubId = -1; - // CORREÇÃO AQUI: Tratar o número como Double primeiro para evitar NumberFormatException - if (dadoClube.get("teamID") != null) { - clubId = (int) Double.parseDouble(dadoClube.get("teamID").toString()); + if (equipa.get("teamID") != null) { + clubId = (int) Double.parseDouble(equipa.get("teamID").toString()); } - if (clubId == -1) continue; // Salta se o ID for inválido + if (clubId == -1 || !clubesMap.containsKey(clubId)) + continue; - String urlJogadores = "https://api.afavcd.pt/teams/" + clubId + "/modality/" + idAtual + "/season/33"; + String urlJogadores = "https://api.afavcd.pt/teams/" + clubId + "/modality/" + idAtual + + "/season/33"; try { String jsonJogadores = Jsoup.connect(urlJogadores) @@ -87,36 +143,50 @@ public class Main { .execute() .body(); - List> dadosJogadores = gson.fromJson(jsonJogadores, new TypeToken>>() {}.getType()); - ArrayList listaJogadoresDoClube = new ArrayList<>(); + List> dadosJogadores = gson.fromJson(jsonJogadores, + new TypeToken>>() { + }.getType()); + + Club clubToUpdate = clubesMap.get(clubId); for (Map atleta : dadosJogadores) { if (atleta.get("fullName") != null) { Player p = new Player(); + + if (atleta.get("playerID") != null) { + p.setId((int) Double.parseDouble(atleta.get("playerID").toString())); + } + p.setName((String) atleta.get("fullName")); - String foto = (String) atleta.get("photoURL"); + String foto = null; + if (atleta.get("photoURL") != null) { + foto = (String) atleta.get("photoURL"); + } else if (atleta.get("photoURl") != null) { + foto = (String) atleta.get("photoURl"); + } + if (foto != null && !foto.startsWith("http")) { foto = "https://api.afavcd.pt" + foto; } p.setPhotoUrl(foto); - if (atleta.get("birth") != null) p.setBirthDate((String) atleta.get("birth")); - if (atleta.get("naturalness") != null) p.setNaturalness((String) atleta.get("naturalness")); + if (atleta.get("birth") != null) { + String date = (String) atleta.get("birth"); + if (date.contains("T")) { + date = date.split("T")[0]; + } + p.setBirthDate(date); + } + if (atleta.get("naturalness") != null) + p.setNaturalness((String) atleta.get("naturalness")); - listaJogadoresDoClube.add(p); + clubToUpdate.addJogador(nomeAtual, p); } } - DatabaseReference ref = FirebaseDatabase.getInstance() - .getReference("clubes") - .child(String.valueOf(clubId - 1)) // Mantive o teu -1, assume-se que é a tua lógica de IDs - .child("listaDeJogadores"); - - // CORREÇÃO AQUI: Gravar a listaJogadoresDoClube e não a listaParaFirebase que estava vazia - ref.setValueAsync(listaJogadoresDoClube); - - System.out.println("SUCESSO: Jogadores do Clube ID " + clubId + " (" + nomeAtual.toUpperCase() + ") enviados para o Firebase!"); + System.out.println("SUCESSO: Extraiu " + dadosJogadores.size() + " jogadores para o clube ID " + + clubId + " (" + nomeAtual + ")."); } catch (Exception e) { System.err.println("Erro ao processar jogadores do clube ID: " + clubId); @@ -125,7 +195,22 @@ public class Main { } } catch (Exception e) { - System.err.println("Erro a processar o escalão " + nomeAtual + ": HTTP error fetching URL."); + System.err.println("Erro a processar o escalão " + nomeAtual); + e.printStackTrace(); + } + } + + System.out.println("\n========================================"); + System.out.println("A ENVIAR DADOS PARA O FIREBASE..."); + System.out.println("========================================"); + + DatabaseReference refClubes = FirebaseDatabase.getInstance().getReference("clubes"); + for (Club club : clubesMap.values()) { + try { + refClubes.child(String.valueOf(club.getId())).setValueAsync(club); + System.out.println("Clube ID " + club.getId() + " - " + club.getName() + " enviado para o Firebase."); + } catch (Exception e) { + System.err.println("Erro a enviar clube ID " + club.getId()); e.printStackTrace(); } } diff --git a/src/main/java/org/example/models/Club.java b/src/main/java/org/example/models/Club.java index 4f8554f..794d733 100644 --- a/src/main/java/org/example/models/Club.java +++ b/src/main/java/org/example/models/Club.java @@ -2,7 +2,9 @@ package org.example.models; import com.google.firebase.database.PropertyName; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; public class Club { @PropertyName("id") @@ -17,7 +19,7 @@ public class Club { @PropertyName("campo") private String stadium; - @PropertyName("ano fundacao") + @PropertyName("ano_fundacao") private int foundationYear; @PropertyName("morada") @@ -27,11 +29,11 @@ public class Club { private String president; @PropertyName("jogadores") - private ArrayList players; + private Map> jogadores; public Club() { // Default constructor for Firebase - players = new ArrayList<>(); + jogadores = new HashMap<>(); } public Club(int id, String name, String imageUrl, String stadium, int foundationYear, String address, @@ -43,7 +45,7 @@ public class Club { this.foundationYear = foundationYear; this.address = address; this.president = president; - this.players = new ArrayList<>(); + this.jogadores = new HashMap<>(); } @PropertyName("id") @@ -86,12 +88,12 @@ public class Club { this.stadium = stadium; } - @PropertyName("ano fundacao") + @PropertyName("ano_fundacao") public int getFoundationYear() { return foundationYear; } - @PropertyName("ano fundacao") + @PropertyName("ano_fundacao") public void setFoundationYear(int foundationYear) { this.foundationYear = foundationYear; } @@ -117,18 +119,22 @@ public class Club { } @PropertyName("jogadores") - public ArrayList getPlayersMap() { - return players; + public Map> getJogadores() { + return jogadores; } @PropertyName("jogadores") - public void setPlayersMap(ArrayList players) { - this.players = players; + public void setJogadores(Map> jogadores) { + this.jogadores = jogadores; } - public List getPlayersList() { - if (players == null) - return new ArrayList<>(); - return new ArrayList<>(players); + public void addJogador(String escalao, Player player) { + if (this.jogadores == null) { + this.jogadores = new HashMap<>(); + } + if (!this.jogadores.containsKey(escalao)) { + this.jogadores.put(escalao, new ArrayList<>()); + } + this.jogadores.get(escalao).add(player); } }