From 5f41b668d38e835e245da4f7d285b5d90b3faa36 Mon Sep 17 00:00:00 2001 From: "Cristian \"SknZ\" Ferreira" Date: Mon, 21 Feb 2022 14:57:30 -0300 Subject: [PATCH 1/3] =?UTF-8?q?refactor:=20alterado=20m=C3=A9todos=20e=20c?= =?UTF-8?q?riado=20classes=20para=20cada=20storage?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../me/skiincraft/api/paladins/Paladins.java | 30 +------- .../paladins/entity/champions/Champions.java | 14 ++++ .../entity/champions/objects/Cards.java | 14 ++++ .../entity/champions/objects/Skins.java | 29 +++++--- .../api/paladins/impl/match/MatchImpl.java | 14 ++++ .../paladins/impl/paladins/EndpointImpl.java | 10 +-- .../api/paladins/storage/Storage.java | 5 -- .../paladins/storage/impl/CardsStorage.java | 17 +++++ .../storage/impl/ChampionsStorage.java | 24 ++++++ .../paladins/storage/impl/MatchStorage.java | 22 ++++++ .../impl}/PaladinsStorageImpl.java | 73 ++++++++++--------- .../paladins/storage/impl/SkinsStorage.java | 17 +++++ .../storage => storage/impl}/StorageImpl.java | 24 ++---- 13 files changed, 193 insertions(+), 100 deletions(-) create mode 100644 src/main/java/me/skiincraft/api/paladins/storage/impl/CardsStorage.java create mode 100644 src/main/java/me/skiincraft/api/paladins/storage/impl/ChampionsStorage.java create mode 100644 src/main/java/me/skiincraft/api/paladins/storage/impl/MatchStorage.java rename src/main/java/me/skiincraft/api/paladins/{impl/storage => storage/impl}/PaladinsStorageImpl.java (63%) create mode 100644 src/main/java/me/skiincraft/api/paladins/storage/impl/SkinsStorage.java rename src/main/java/me/skiincraft/api/paladins/{impl/storage => storage/impl}/StorageImpl.java (55%) diff --git a/src/main/java/me/skiincraft/api/paladins/Paladins.java b/src/main/java/me/skiincraft/api/paladins/Paladins.java index 0436e26..193dfa4 100644 --- a/src/main/java/me/skiincraft/api/paladins/Paladins.java +++ b/src/main/java/me/skiincraft/api/paladins/Paladins.java @@ -2,15 +2,10 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import me.skiincraft.api.paladins.entity.champions.Champions; -import me.skiincraft.api.paladins.entity.champions.objects.Cards; -import me.skiincraft.api.paladins.entity.champions.objects.Skins; -import me.skiincraft.api.paladins.entity.match.Match; import me.skiincraft.api.paladins.exceptions.ContextException; import me.skiincraft.api.paladins.exceptions.RequestException; import me.skiincraft.api.paladins.impl.paladins.SessionImpl; -import me.skiincraft.api.paladins.impl.storage.PaladinsStorageImpl; -import me.skiincraft.api.paladins.impl.storage.StorageImpl; +import me.skiincraft.api.paladins.storage.impl.PaladinsStorageImpl; import me.skiincraft.api.paladins.internal.logging.PaladinsLogger; import me.skiincraft.api.paladins.internal.requests.APIRequest; import me.skiincraft.api.paladins.internal.requests.impl.DefaultAPIRequest; @@ -43,7 +38,6 @@ public class Paladins { private static Paladins instance; private final AccessUtils accessUtils; - private final PaladinsStorage storage; private final List sessions; private OkHttpClient client; private final Logger logger; @@ -56,24 +50,6 @@ private Paladins() { this.sessions = new ArrayList<>(); this.client = new OkHttpClient(); this.logger = PaladinsLogger.getLogger(Paladins.class); - this.storage = new PaladinsStorageImpl( - new StorageImpl(new Champions[0]) { - public Champions getById(long id) { - return getAsList().stream().filter(i -> i.getLanguage().getLanguagecode() == id).findFirst().orElse(null); - } - }, new StorageImpl(new Match[0]) { - public Match getById(long id) { - return getAsList().stream().filter(i -> i.getMatchId() == id).findFirst().orElse(null); - } - }, new StorageImpl(new Cards[0]) { - public Cards getById(long id) { - return getAsList().stream().filter(i -> i.getChampionCardId() == id).findFirst().orElse(null); - } - }, new StorageImpl(new Skins[0]) { - public Skins getById(long id) { - return getAsList().stream().filter(i -> i.get(0).getChampionId() == id).findFirst().orElse(null); - } - }); } /** @@ -138,7 +114,7 @@ public synchronized APIRequest testSession(String sessionId) { return true; } Stream activeSessions = sessions.stream().filter((session) -> session.getSessionId().equalsIgnoreCase(sessionId)); - if (activeSessions.count() >= 1) { + if (activeSessions.findAny().isPresent()) { logger.warn("[{}] Sessions have been removed for being invalid.", activeSessions.count()); logger.debug("Session [{}] is invalid", sessionId); sessions.removeAll(activeSessions.collect(Collectors.toList())); @@ -206,7 +182,7 @@ public synchronized APIRequest getDataUsed(Session session) { * @return The storage such as Matches, Champions and Cards. */ public PaladinsStorage getStorage() { - return storage; + return PaladinsStorageImpl.getInstance(); } /** diff --git a/src/main/java/me/skiincraft/api/paladins/entity/champions/Champions.java b/src/main/java/me/skiincraft/api/paladins/entity/champions/Champions.java index fc24f82..556c952 100644 --- a/src/main/java/me/skiincraft/api/paladins/entity/champions/Champions.java +++ b/src/main/java/me/skiincraft/api/paladins/entity/champions/Champions.java @@ -7,6 +7,7 @@ import java.util.Arrays; import java.util.Iterator; import java.util.List; +import java.util.Objects; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -53,4 +54,17 @@ public String toString() { ", language=" + language + '}'; } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Champions champions = (Champions) o; + return language == champions.language; + } + + @Override + public int hashCode() { + return Objects.hash(language); + } } diff --git a/src/main/java/me/skiincraft/api/paladins/entity/champions/objects/Cards.java b/src/main/java/me/skiincraft/api/paladins/entity/champions/objects/Cards.java index 8e6b835..8a50169 100644 --- a/src/main/java/me/skiincraft/api/paladins/entity/champions/objects/Cards.java +++ b/src/main/java/me/skiincraft/api/paladins/entity/champions/objects/Cards.java @@ -8,6 +8,7 @@ import java.util.Arrays; import java.util.Iterator; import java.util.List; +import java.util.Objects; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -68,4 +69,17 @@ public String toString() { ", language=" + language + '}'; } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Cards cards = (Cards) o; + return championId == cards.championId && language == cards.language; + } + + @Override + public int hashCode() { + return Objects.hash(championId, language); + } } diff --git a/src/main/java/me/skiincraft/api/paladins/entity/champions/objects/Skins.java b/src/main/java/me/skiincraft/api/paladins/entity/champions/objects/Skins.java index a32681b..ffabe12 100644 --- a/src/main/java/me/skiincraft/api/paladins/entity/champions/objects/Skins.java +++ b/src/main/java/me/skiincraft/api/paladins/entity/champions/objects/Skins.java @@ -7,6 +7,7 @@ import java.util.Arrays; import java.util.Iterator; import java.util.List; +import java.util.Objects; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -21,10 +22,12 @@ public class Skins implements CustomList { private final ChampionSkin[] championSkins; + private final long championId; private final Language language; - public Skins(List ChampionSkin, Language language) { + public Skins(List ChampionSkin, long championId, Language language) { this.championSkins = new ChampionSkin[ChampionSkin.size()]; + this.championId = championId; this.language = language; AtomicInteger integer = new AtomicInteger(); for (ChampionSkin item : ChampionSkin) { @@ -32,15 +35,6 @@ public Skins(List ChampionSkin, Language language) { } } - public Skins(List ChampionSkin) { - this.championSkins = new ChampionSkin[ChampionSkin.size()]; - this.language = ChampionSkin.get(0).getLanguage(); - AtomicInteger integer = new AtomicInteger(); - for (ChampionSkin item : ChampionSkin) { - championSkins[integer.getAndIncrement()] = item; - } - } - @Nonnull public Iterator iterator() { return Arrays.stream(championSkins).iterator(); @@ -59,7 +53,7 @@ public ChampionSkin getById(long id) { } public long getChampionId() { - return championSkins[0].getChampionId(); + return championId; } public Language getLanguage() { @@ -74,4 +68,17 @@ public String toString() { ", language=" + language + '}'; } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Skins that = (Skins) o; + return championId == that.championId && language == that.language; + } + + @Override + public int hashCode() { + return Objects.hash(championId, language); + } } diff --git a/src/main/java/me/skiincraft/api/paladins/impl/match/MatchImpl.java b/src/main/java/me/skiincraft/api/paladins/impl/match/MatchImpl.java index 9166aa3..f854064 100644 --- a/src/main/java/me/skiincraft/api/paladins/impl/match/MatchImpl.java +++ b/src/main/java/me/skiincraft/api/paladins/impl/match/MatchImpl.java @@ -18,6 +18,7 @@ import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import java.util.concurrent.TimeUnit; public class MatchImpl implements Match { @@ -194,4 +195,17 @@ public String toString() { ", isRanked=" + isRanked() + '}'; } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MatchImpl match = (MatchImpl) o; + return matchId == match.matchId && queueId == match.queueId; + } + + @Override + public int hashCode() { + return Objects.hash(matchId, queueId); + } } diff --git a/src/main/java/me/skiincraft/api/paladins/impl/paladins/EndpointImpl.java b/src/main/java/me/skiincraft/api/paladins/impl/paladins/EndpointImpl.java index 03c6d27..f7da3ec 100644 --- a/src/main/java/me/skiincraft/api/paladins/impl/paladins/EndpointImpl.java +++ b/src/main/java/me/skiincraft/api/paladins/impl/paladins/EndpointImpl.java @@ -24,7 +24,7 @@ import me.skiincraft.api.paladins.impl.player.FriendImpl; import me.skiincraft.api.paladins.impl.player.LoadoutImpl; import me.skiincraft.api.paladins.impl.player.PlayerImpl; -import me.skiincraft.api.paladins.impl.storage.PaladinsStorageImpl; +import me.skiincraft.api.paladins.storage.impl.PaladinsStorageImpl; import me.skiincraft.api.paladins.internal.logging.PaladinsLogger; import me.skiincraft.api.paladins.internal.requests.APIRequest; import me.skiincraft.api.paladins.internal.requests.impl.DefaultAPIRequest; @@ -173,7 +173,7 @@ public APIRequest getChampions(Language language) { .create().fromJson(Objects.requireNonNull(response.body(), "json is null").string(), ChampionImpl[].class); Champions champions = new Champions(Arrays.asList(championsArray), language); - storageImpl.addChampion(champions); + storageImpl.store(champions); return champions; } catch (IOException e) { e.printStackTrace(); @@ -220,7 +220,7 @@ public APIRequest getChampionCards(long championsId, Language language) { .create(); Cards cards = new Cards(new ArrayList<>(Arrays.asList(gson.fromJson(array, Card[].class))), championsId, language); - storageImpl.addCard(cards); + storageImpl.store(cards); return cards; } catch (IOException e) { e.printStackTrace(); @@ -246,7 +246,7 @@ public APIRequest getChampionSkin(long championsId, Language language) { .setLanguage(language) .setEndPoint(this)); } - return new Skins(skin, language); + return new Skins(skin, championsId, language); } catch (IOException e) { e.printStackTrace(); return null; @@ -440,7 +440,7 @@ public APIRequest> getMatchDetails(@Nonnull List matchBatch) { Match match = gson.fromJson(matchArray.get(0), MatchImpl.class) .buildMethods(matchArray, this); - storageImpl.addMatch(match); + storageImpl.store(match); matchs.add(match); num.set(num.get() + 10); diff --git a/src/main/java/me/skiincraft/api/paladins/storage/Storage.java b/src/main/java/me/skiincraft/api/paladins/storage/Storage.java index 0c94679..6ae63b8 100644 --- a/src/main/java/me/skiincraft/api/paladins/storage/Storage.java +++ b/src/main/java/me/skiincraft/api/paladins/storage/Storage.java @@ -15,11 +15,6 @@ public interface Storage extends Iterable { */ List getAsList(); - /** - * Returns a copy of the set of T items saved in that class. - */ - Set getAsSet(); - /** * Quantity of items in the class */ diff --git a/src/main/java/me/skiincraft/api/paladins/storage/impl/CardsStorage.java b/src/main/java/me/skiincraft/api/paladins/storage/impl/CardsStorage.java new file mode 100644 index 0000000..ab54d75 --- /dev/null +++ b/src/main/java/me/skiincraft/api/paladins/storage/impl/CardsStorage.java @@ -0,0 +1,17 @@ +package me.skiincraft.api.paladins.storage.impl; + +import me.skiincraft.api.paladins.entity.champions.objects.Cards; + +import java.util.ArrayList; + +public class CardsStorage extends StorageImpl { + + public CardsStorage() { + super(new ArrayList<>()); + } + + @Override + public Cards getById(long id) { + return getAsList().stream().filter((cards) -> cards.getCardsLanguage().getLanguagecode() == id).findFirst().orElse(null); + } +} diff --git a/src/main/java/me/skiincraft/api/paladins/storage/impl/ChampionsStorage.java b/src/main/java/me/skiincraft/api/paladins/storage/impl/ChampionsStorage.java new file mode 100644 index 0000000..a590f6b --- /dev/null +++ b/src/main/java/me/skiincraft/api/paladins/storage/impl/ChampionsStorage.java @@ -0,0 +1,24 @@ +package me.skiincraft.api.paladins.storage.impl; + +import me.skiincraft.api.paladins.entity.champions.Champions; + +import java.util.ArrayList; +import java.util.List; + +public class ChampionsStorage extends StorageImpl { + + public ChampionsStorage(List item) { + super(item); + } + + public ChampionsStorage() { + super(new ArrayList<>()); + } + + @Override + public Champions getById(long id) { + return getAsList().stream().filter((champions -> champions.getLanguage().getLanguagecode() == id)).findFirst().orElse(null); + } +} + + diff --git a/src/main/java/me/skiincraft/api/paladins/storage/impl/MatchStorage.java b/src/main/java/me/skiincraft/api/paladins/storage/impl/MatchStorage.java new file mode 100644 index 0000000..f3b4a5d --- /dev/null +++ b/src/main/java/me/skiincraft/api/paladins/storage/impl/MatchStorage.java @@ -0,0 +1,22 @@ +package me.skiincraft.api.paladins.storage.impl; + +import me.skiincraft.api.paladins.entity.match.Match; + +import java.util.ArrayList; +import java.util.List; + +public class MatchStorage extends StorageImpl { + + public MatchStorage(List item) { + super(item); + } + + public MatchStorage() { + super(new ArrayList<>()); + } + + @Override + public Match getById(long id) { + return getAsList().stream().filter((match -> match.getMatchId() == id)).findFirst().orElse(null); + } +} \ No newline at end of file diff --git a/src/main/java/me/skiincraft/api/paladins/impl/storage/PaladinsStorageImpl.java b/src/main/java/me/skiincraft/api/paladins/storage/impl/PaladinsStorageImpl.java similarity index 63% rename from src/main/java/me/skiincraft/api/paladins/impl/storage/PaladinsStorageImpl.java rename to src/main/java/me/skiincraft/api/paladins/storage/impl/PaladinsStorageImpl.java index b290a45..3923692 100644 --- a/src/main/java/me/skiincraft/api/paladins/impl/storage/PaladinsStorageImpl.java +++ b/src/main/java/me/skiincraft/api/paladins/storage/impl/PaladinsStorageImpl.java @@ -1,4 +1,4 @@ -package me.skiincraft.api.paladins.impl.storage; +package me.skiincraft.api.paladins.storage.impl; import me.skiincraft.api.paladins.entity.champions.Champions; import me.skiincraft.api.paladins.entity.champions.objects.Cards; @@ -11,10 +11,7 @@ import org.slf4j.Logger; import javax.annotation.Nullable; -import java.util.ArrayList; -import java.util.Arrays; import java.util.List; -import java.util.stream.Collectors; /** *

Is the PaladinsStorage implementation class

@@ -25,7 +22,9 @@ public class PaladinsStorageImpl implements PaladinsStorage { private final Storage matchMemory; private final Storage cardsMemory; private final Storage skinMemory; - private final Logger logger = PaladinsLogger.getLogger(PaladinsStorage.class); + + private static final PaladinsStorage instance = getInstance(); + private static final Logger logger = PaladinsLogger.getLogger(PaladinsStorage.class); public PaladinsStorageImpl(Storage championMemory, Storage matchMemory, Storage cardsMemory, Storage skinMemory) { this.championMemory = championMemory; @@ -82,63 +81,61 @@ public Skins getSkinFromStorage(long championId, Language language) { /** *

This method is used to add Champions to the Storage

*/ - public synchronized void addChampion(Champions champion) { - StorageImpl impl = (StorageImpl) championMemory; - List cc = new ArrayList<>(Arrays.asList(impl.item)); - cc.removeAll(cc.stream().filter(cham -> cham.getLanguage() == champion.getLanguage()).collect(Collectors.toList())); - cc.add(champion); + public synchronized void store(Champions champion) { + StorageImpl storage = (StorageImpl) championMemory; + List data = storage.getAsList(); + data.removeIf(champion::equals); + data.add(champion); logger.debug("Champions: Added a new collection of champions in storage"); - logger.debug("Champions: Size={}, Language='{}'", champion.size(), champion.get(0).getLanguage()); + logger.debug("Champions: Size={}, Language='{}'", champion.size(), champion.getLanguage()); - impl.lastupdate = System.currentTimeMillis(); - impl.item = cc.toArray(new Champions[0]); + storage.lastupdate = System.currentTimeMillis(); + storage.item = data; } /** *

This method is used to add Match to the Storage

*/ - public synchronized void addMatch(Match match) { - StorageImpl impl = (StorageImpl) matchMemory; - List cc = new ArrayList<>(Arrays.asList(impl.item)); - cc.removeAll(cc.stream().filter(cham -> cham.getMatchId() == cham.getMatchId()).collect(Collectors.toList())); - cc.add(match); + public synchronized void store(Match match) { + StorageImpl storage = (StorageImpl) matchMemory; + List data = storage.getAsList(); + data.removeIf(match::equals); + data.add(match); logger.debug("Match: Added a new match in storage"); logger.debug("Match: MatchId={}, Queue='{}'", match.getMatchId(), match.getQueue()); - impl.lastupdate = System.currentTimeMillis(); - impl.item = cc.toArray(new Match[0]); + storage.lastupdate = System.currentTimeMillis(); + storage.item = data; } /** *

This method is used to add Cards to the Storage

*/ - public synchronized void addCard(Cards cards) { + public synchronized void store(Cards cards) { if (cards.size() == 0) { return; } - StorageImpl impl = (StorageImpl) cardsMemory; - List cc = new ArrayList<>(Arrays.asList(impl.item)); - cc.removeAll(cc.stream().filter(cham -> cham.get(0).getChampionId() == cards.get(0).getChampionId() - && cham.get(0).getLanguage() == cards.get(0).getLanguage()).collect(Collectors.toList())); - cc.add(cards); + StorageImpl storage = (StorageImpl) cardsMemory; + List data = storage.getAsList(); + data.removeIf(cards::equals); + data.add(cards); logger.debug("Cards: Added a new collections of cards in storage"); logger.debug("Cards: ChampionId={}, Language='{}'", cards.getChampionCardId(), cards.get(0).getLanguage()); - impl.lastupdate = System.currentTimeMillis(); - impl.item = cc.toArray(new Cards[0]); + storage.lastupdate = System.currentTimeMillis(); + storage.item = data; } - public synchronized void addSkin(Skins skin) { - StorageImpl impl = (StorageImpl) skinMemory; - List cc = new ArrayList<>(Arrays.asList(impl.item)); - cc.removeAll(cc.stream().filter(cham -> cham.get(0).getChampionId() == skin.get(0).getChampionId() - && cham.get(0).getLanguage() == skin.get(0).getLanguage()).collect(Collectors.toList())); - cc.add(skin); + public synchronized void store(Skins skin) { + StorageImpl storage = (StorageImpl) skinMemory; + List data = storage.getAsList(); + data.removeIf(skin::equals); + data.add(skin); logger.debug("Skins: Added a new collections of skins in storage"); logger.debug("Skins: ChampionId={}, Language='{}'", skin.getChampionId(), skin.get(0).getLanguage()); - impl.lastupdate = System.currentTimeMillis(); - impl.item = cc.toArray(new Skins[0]); + storage.lastupdate = System.currentTimeMillis(); + storage.item = data; } @Override @@ -150,4 +147,8 @@ public String toString() { ", skinMemory=" + skinMemory.size() + '}'; } + + public static PaladinsStorage getInstance() { + return (instance == null) ? new PaladinsStorageImpl(new ChampionsStorage(), new MatchStorage(), new CardsStorage(), new SkinsStorage()) : instance; + } } diff --git a/src/main/java/me/skiincraft/api/paladins/storage/impl/SkinsStorage.java b/src/main/java/me/skiincraft/api/paladins/storage/impl/SkinsStorage.java new file mode 100644 index 0000000..2a73fe7 --- /dev/null +++ b/src/main/java/me/skiincraft/api/paladins/storage/impl/SkinsStorage.java @@ -0,0 +1,17 @@ +package me.skiincraft.api.paladins.storage.impl; + +import me.skiincraft.api.paladins.entity.champions.objects.Skins; + +import java.util.ArrayList; + +public class SkinsStorage extends StorageImpl { + + public SkinsStorage() { + super(new ArrayList<>()); + } + + @Override + public Skins getById(long id) { + return getAsList().stream().filter((skins) -> skins.getChampionId() == id).findFirst().orElse(null); + } +} \ No newline at end of file diff --git a/src/main/java/me/skiincraft/api/paladins/impl/storage/StorageImpl.java b/src/main/java/me/skiincraft/api/paladins/storage/impl/StorageImpl.java similarity index 55% rename from src/main/java/me/skiincraft/api/paladins/impl/storage/StorageImpl.java rename to src/main/java/me/skiincraft/api/paladins/storage/impl/StorageImpl.java index 8bf6d16..76d96cd 100644 --- a/src/main/java/me/skiincraft/api/paladins/impl/storage/StorageImpl.java +++ b/src/main/java/me/skiincraft/api/paladins/storage/impl/StorageImpl.java @@ -1,41 +1,33 @@ -package me.skiincraft.api.paladins.impl.storage; +package me.skiincraft.api.paladins.storage.impl; import me.skiincraft.api.paladins.storage.Storage; import javax.annotation.Nonnull; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; +import java.util.*; /** *

Is the Storage implementation class

*/ public abstract class StorageImpl implements Storage { - public T[] item; + public List item; protected long lastupdate; - public StorageImpl(T[] item) { + public StorageImpl(List item) { this.item = item; } @Nonnull public Iterator iterator() { - return Arrays.stream(item).iterator(); + return item.iterator(); } public List getAsList() { - return Arrays.stream(item).collect(Collectors.toList()); - } - - public Set getAsSet() { - return Arrays.stream(item).collect(Collectors.toSet()); + return new ArrayList<>(item); } public int size() { - return item.length; + return item.size(); } public long lastUpdate() { @@ -47,7 +39,7 @@ public long lastUpdate() { @Override public String toString() { return "Storage{" + - "item=" + item.length + + "item=" + item.size() + ", lastupdate=" + lastupdate + '}'; } From f0bf763b0594d48e5d7f848466708c05e8c9900c Mon Sep 17 00:00:00 2001 From: "Cristian \"SknZ\" Ferreira" Date: Mon, 21 Feb 2022 15:01:27 -0300 Subject: [PATCH 2/3] test: adicionado testes ao paladins storage --- .../impl/champion/ChampionSkinTestImpl.java | 65 +++++++++++++ .../impl/champion/ChampionTestImpl.java | 96 +++++++++++++++++++ .../paladins/test/ChampionStorageTest.java | 74 ++++++++++++++ .../api/paladins/test/SkinsStorageTest.java | 76 +++++++++++++++ 4 files changed, 311 insertions(+) create mode 100644 src/test/java/me/skiincraft/api/paladins/impl/champion/ChampionSkinTestImpl.java create mode 100644 src/test/java/me/skiincraft/api/paladins/impl/champion/ChampionTestImpl.java create mode 100644 src/test/java/me/skiincraft/api/paladins/test/ChampionStorageTest.java create mode 100644 src/test/java/me/skiincraft/api/paladins/test/SkinsStorageTest.java diff --git a/src/test/java/me/skiincraft/api/paladins/impl/champion/ChampionSkinTestImpl.java b/src/test/java/me/skiincraft/api/paladins/impl/champion/ChampionSkinTestImpl.java new file mode 100644 index 0000000..bc6bac5 --- /dev/null +++ b/src/test/java/me/skiincraft/api/paladins/impl/champion/ChampionSkinTestImpl.java @@ -0,0 +1,65 @@ +package me.skiincraft.api.paladins.impl.champion; + +import me.skiincraft.api.paladins.entity.champions.Champion; +import me.skiincraft.api.paladins.entity.champions.objects.ChampionSkin; +import me.skiincraft.api.paladins.internal.requests.APIRequest; +import me.skiincraft.api.paladins.objects.miscellany.Language; +import me.skiincraft.api.paladins.objects.miscellany.Rarity; + +public class ChampionSkinTestImpl implements ChampionSkin { + + private long skinId1; + private long championId; + private Language language; + + public ChampionSkinTestImpl(long skinId1, long championId, Language language) { + this.skinId1 = skinId1; + this.championId =championId; + this.language = language; + } + + @Override + public APIRequest getChampion(Language language) { + return null; + } + + @Override + public long getChampionId() { + return championId; + } + + @Override + public String getChampionname() { + return null; + } + + @Override + public Rarity getRarity() { + return null; + } + + @Override + public long getSkinId1() { + return skinId1; + } + + @Override + public long getSkinId2() { + return 0; + } + + @Override + public String getSkinName() { + return null; + } + + @Override + public String getSkinNameEnglish() { + return null; + } + + @Override + public Language getLanguage() { + return language; + } +} diff --git a/src/test/java/me/skiincraft/api/paladins/impl/champion/ChampionTestImpl.java b/src/test/java/me/skiincraft/api/paladins/impl/champion/ChampionTestImpl.java new file mode 100644 index 0000000..0985a97 --- /dev/null +++ b/src/test/java/me/skiincraft/api/paladins/impl/champion/ChampionTestImpl.java @@ -0,0 +1,96 @@ +package me.skiincraft.api.paladins.impl.champion; + +import me.skiincraft.api.paladins.entity.champions.Champion; +import me.skiincraft.api.paladins.entity.champions.objects.Cards; +import me.skiincraft.api.paladins.entity.champions.objects.Skins; +import me.skiincraft.api.paladins.internal.requests.APIRequest; +import me.skiincraft.api.paladins.objects.champion.Ability; +import me.skiincraft.api.paladins.objects.miscellany.Language; + +import java.util.List; + +public class ChampionTestImpl implements Champion { + + private long id; + private String name; + + public ChampionTestImpl(long id, String name) { + this.id = id; + this.name = name; + } + + @Override + public long getId() { + return id; + } + + @Override + public String getName() { + return name; + } + + @Override + public String getIcon() { + return null; + } + + @Override + public String getTitle() { + return null; + } + + @Override + public String getRoleString() { + return null; + } + + @Override + public String getLore() { + return null; + } + + @Override + public int getHealth() { + return 0; + } + + @Override + public double getSpeed() { + return 0; + } + + @Override + public List getAbilities() { + return null; + } + + @Override + public boolean isLatestChampion() { + return false; + } + + @Override + public boolean inFreeRotation() { + return false; + } + + @Override + public boolean inFreeWeeklyRotation() { + return false; + } + + @Override + public APIRequest getCards() { + return null; + } + + @Override + public APIRequest getSkins() { + return null; + } + + @Override + public Language getLanguage() { + return null; + } +} diff --git a/src/test/java/me/skiincraft/api/paladins/test/ChampionStorageTest.java b/src/test/java/me/skiincraft/api/paladins/test/ChampionStorageTest.java new file mode 100644 index 0000000..2b3e929 --- /dev/null +++ b/src/test/java/me/skiincraft/api/paladins/test/ChampionStorageTest.java @@ -0,0 +1,74 @@ +package me.skiincraft.api.paladins.test; + +import me.skiincraft.api.paladins.entity.champions.Champion; +import me.skiincraft.api.paladins.entity.champions.Champions; +import me.skiincraft.api.paladins.impl.champion.ChampionTestImpl; +import me.skiincraft.api.paladins.storage.impl.PaladinsStorageImpl; +import me.skiincraft.api.paladins.objects.miscellany.Language; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; + +import java.util.Collections; + +public class ChampionStorageTest { + + @Test + @DisplayName("Add Champions to Storage") + @Order(1) + void Add_Champions_To_Storage() { + PaladinsStorageImpl storage = (PaladinsStorageImpl) PaladinsStorageImpl.getInstance(); + Champion champion = new ChampionTestImpl(1, "Ash"); + Champions champions = new Champions(Collections.singletonList(champion), Language.Portuguese); + + storage.store(champions); + storage.getChampionsStorage().size(); + assert storage.championsIsStored(Language.Portuguese); + } + + @Test + @DisplayName("Add existing champions to storage") + @Order(2) + void Add_Existing_Champions_To_Storage() { + PaladinsStorageImpl storage = (PaladinsStorageImpl) PaladinsStorageImpl.getInstance(); + Champion champion = new ChampionTestImpl(1, "Ash"); + Champions instance1 = new Champions(Collections.singletonList(champion), Language.Portuguese); + Champions instance2 = new Champions(Collections.singletonList(champion), Language.Portuguese); + + storage.store(instance1); + storage.store(instance2); + + assert storage.getChampionsStorage() + .getAsList() + .stream() + .filter((stored -> stored.getLanguage() == Language.Portuguese)) + .count() == 1; + } + + @Test + @DisplayName("Add multi-language champions to storage") + @Order(3) + void Add_Multi_Language_Champions_To_Storage() { + PaladinsStorageImpl storage = (PaladinsStorageImpl) PaladinsStorageImpl.getInstance(); + Champion champion = new ChampionTestImpl(1, "Ash"); + Champions portugueseChampions = new Champions(Collections.singletonList(champion), Language.Portuguese); + Champions englishChampions = new Champions(Collections.singletonList(champion), Language.English); + + storage.store(portugueseChampions); + storage.store(englishChampions); + + assert storage.getChampionsStorage().size() == 2; + } + + @Test + @DisplayName("Get champions from storage by language") + @Order(4) + void Get_Champions_From_Storage_By_Language() { + PaladinsStorageImpl storage = (PaladinsStorageImpl) PaladinsStorageImpl.getInstance(); + Champion champion = new ChampionTestImpl(1, "Ash"); + Champions portugueseChampions = new Champions(Collections.singletonList(champion), Language.Portuguese); + + storage.store(portugueseChampions); + assert storage.getChampionsFromStorage(Language.Portuguese) != null; + } +} \ No newline at end of file diff --git a/src/test/java/me/skiincraft/api/paladins/test/SkinsStorageTest.java b/src/test/java/me/skiincraft/api/paladins/test/SkinsStorageTest.java new file mode 100644 index 0000000..43f8c50 --- /dev/null +++ b/src/test/java/me/skiincraft/api/paladins/test/SkinsStorageTest.java @@ -0,0 +1,76 @@ +package me.skiincraft.api.paladins.test; + +import me.skiincraft.api.paladins.entity.champions.objects.ChampionSkin; +import me.skiincraft.api.paladins.entity.champions.objects.Skins; +import me.skiincraft.api.paladins.impl.champion.ChampionSkinTestImpl; +import me.skiincraft.api.paladins.storage.impl.PaladinsStorageImpl; +import me.skiincraft.api.paladins.objects.miscellany.Language; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; + +import java.util.Collections; + +public class SkinsStorageTest { + + @Test + @DisplayName("Add skins to Storage") + @Order(1) + void Add_Skins_To_Storage() { + PaladinsStorageImpl storage = (PaladinsStorageImpl) PaladinsStorageImpl.getInstance(); + ChampionSkin skin = new ChampionSkinTestImpl(1, 1, Language.Portuguese); + Skins skins = new Skins(Collections.singletonList(skin), 1, Language.Portuguese); + + storage.store(skins); + + storage.getChampionsStorage().size(); + assert storage.skinIsStored(1, Language.Portuguese); + } + + @Test + @DisplayName("Add existing skins to storage") + @Order(2) + void Add_Existing_Skins_To_Storage() { + PaladinsStorageImpl storage = (PaladinsStorageImpl) PaladinsStorageImpl.getInstance(); + ChampionSkin skin = new ChampionSkinTestImpl(1, 1, Language.Portuguese); + Skins instance1 = new Skins(Collections.singletonList(skin), 1, Language.Portuguese); + Skins instance2 = new Skins(Collections.singletonList(skin), 1, Language.Portuguese); + + storage.store(instance1); + storage.store(instance2); + + assert storage.getSkinStorage() + .getAsList() + .stream() + .filter((stored -> stored.getLanguage() == Language.Portuguese)) + .filter((stored) -> stored.getChampionId() == 1) + .count() == 1; + } + + @Test + @DisplayName("Add multi-language skins to storage") + @Order(3) + void Add_Multi_Language_Skins_To_Storage() { + PaladinsStorageImpl storage = (PaladinsStorageImpl) PaladinsStorageImpl.getInstance(); + ChampionSkin skin = new ChampionSkinTestImpl(1, 1, Language.Portuguese); + Skins portugueseChampions = new Skins(Collections.singletonList(skin), 1, Language.Portuguese); + Skins englishChampions = new Skins(Collections.singletonList(skin), 1, Language.English); + + storage.store(portugueseChampions); + storage.store(englishChampions); + + assert storage.getSkinStorage().size() == 2; + } + + @Test + @DisplayName("Get skins from storage by championId and language") + @Order(4) + void Get_Champions_From_Storage_By_Language() { + PaladinsStorageImpl storage = (PaladinsStorageImpl) PaladinsStorageImpl.getInstance(); + ChampionSkin skin = new ChampionSkinTestImpl(1, 1, Language.Portuguese); + Skins portugueseChampions = new Skins(Collections.singletonList(skin), 1, Language.Portuguese); + + storage.store(portugueseChampions); + assert storage.getSkinFromStorage(1, Language.Portuguese) != null; + } +} From 20d1be6dd76de5936b452c4d020e3c9253084ce0 Mon Sep 17 00:00:00 2001 From: "Cristian \"SknZ\" Ferreira" Date: Mon, 21 Feb 2022 16:30:33 -0300 Subject: [PATCH 3/3] =?UTF-8?q?feature:=20permitida=20m=C3=BAltiplas=20ins?= =?UTF-8?q?t=C3=A2ncias=20e=20novo=20endpoint=20de=20skins=20Agora=20?= =?UTF-8?q?=C3=A9=20poss=C3=ADvel=20obter=20todas=20as=20skins=20utilizand?= =?UTF-8?q?o=20o=20m=C3=A9todo=20Endpoint#getChampionsCards?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 8 +- .../me/skiincraft/api/paladins/Paladins.java | 72 +----- .../api/paladins/PaladinsBuilder.java | 4 +- .../entity/champions/objects/Skins.java | 4 +- .../paladins/impl/paladins/EndpointImpl.java | 223 +++++++++++------- .../paladins/impl/paladins/SessionImpl.java | 17 +- .../requests/impl/DefaultAPIRequest.java | 3 +- .../paladins/internal/session/EndPoint.java | 11 + .../{AccessUtils.java => HirezAPIUtils.java} | 37 +-- 9 files changed, 180 insertions(+), 199 deletions(-) rename src/main/java/me/skiincraft/api/paladins/objects/{AccessUtils.java => HirezAPIUtils.java} (71%) diff --git a/build.gradle b/build.gradle index 602a251..0e169cb 100644 --- a/build.gradle +++ b/build.gradle @@ -9,13 +9,14 @@ version '2021.0417.1' repositories { maven { url 'https://jitpack.io' } jcenter() + mavenCentral() } dependencies { - implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.6' + implementation group: 'com.google.code.gson', name: 'gson', version: '2.9.0' implementation group: 'com.squareup.okhttp3', name: 'okhttp', version: '3.9.0' implementation group: 'com.google.code.findbugs', name: 'jsr305', version: '3.0.2' - implementation group: 'org.slf4j', name: 'slf4j-api', version: '1.7.30' + implementation group: 'org.slf4j', name: 'slf4j-api', version: '1.7.36' testImplementation(platform('org.junit:junit-bom:5.7.0')) testImplementation('org.junit.jupiter:junit-jupiter') } @@ -39,5 +40,4 @@ shadowJar{ test { useJUnitPlatform() -} - +} \ No newline at end of file diff --git a/src/main/java/me/skiincraft/api/paladins/Paladins.java b/src/main/java/me/skiincraft/api/paladins/Paladins.java index 193dfa4..049ef15 100644 --- a/src/main/java/me/skiincraft/api/paladins/Paladins.java +++ b/src/main/java/me/skiincraft/api/paladins/Paladins.java @@ -2,19 +2,17 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import me.skiincraft.api.paladins.exceptions.ContextException; import me.skiincraft.api.paladins.exceptions.RequestException; import me.skiincraft.api.paladins.impl.paladins.SessionImpl; -import me.skiincraft.api.paladins.storage.impl.PaladinsStorageImpl; import me.skiincraft.api.paladins.internal.logging.PaladinsLogger; import me.skiincraft.api.paladins.internal.requests.APIRequest; import me.skiincraft.api.paladins.internal.requests.impl.DefaultAPIRequest; import me.skiincraft.api.paladins.internal.requests.impl.FakeAPIRequest; import me.skiincraft.api.paladins.internal.session.Session; import me.skiincraft.api.paladins.json.SessionJsonAdapter; -import me.skiincraft.api.paladins.objects.AccessUtils; import me.skiincraft.api.paladins.objects.miscellany.DataUsed; import me.skiincraft.api.paladins.storage.PaladinsStorage; +import me.skiincraft.api.paladins.storage.impl.PaladinsStorageImpl; import okhttp3.OkHttpClient; import org.slf4j.Logger; @@ -26,6 +24,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; +import static me.skiincraft.api.paladins.objects.HirezAPIUtils.checkResponse; /** *

Paladins

@@ -36,34 +35,21 @@ */ public class Paladins { - private static Paladins instance; - private final AccessUtils accessUtils; private final List sessions; private OkHttpClient client; private final Logger logger; - private int devId; - private String authkey; + private final int devId; + private final String authkey; - private Paladins() { - this.accessUtils = new AccessUtils(this); + protected Paladins(int devId, String authkey) { + this.devId = devId; + this.authkey = authkey; this.sessions = new ArrayList<>(); this.client = new OkHttpClient(); this.logger = PaladinsLogger.getLogger(Paladins.class); } - /** - *

Instance

- *

Method to get the instance of Paladins API

- */ - public static Paladins getInstance() { - if (instance == null) { - PaladinsLogger.getLogger(Paladins.class).debug("Creating a new instance of the Paladins class"); - instance = new Paladins(); - } - return instance; - } - public Logger getLogger() { return logger; } @@ -109,7 +95,7 @@ public synchronized APIRequest testSession(String sessionId) { return new DefaultAPIRequest<>("testsession", sessionId, null, (response) -> { try { String json = Objects.requireNonNull(response.body(), "response is null").string(); - if (AccessUtils.checkResponse(json)) { + if (checkResponse(json)) { logger.info("TestSession: Session {} is still valid", sessionId); return true; } @@ -156,7 +142,7 @@ public synchronized APIRequest getDataUsed(String sessionId) { return new DefaultAPIRequest<>("getdataused", sessionId, null, (response) -> { try { String json = Objects.requireNonNull(response.body(), "response is null").string(); - if (AccessUtils.checkResponse(json)) { + if (checkResponse(json)) { return new Gson().fromJson(json, DataUsed[].class)[0]; } throw new RequestException(json, json); @@ -185,13 +171,6 @@ public PaladinsStorage getStorage() { return PaladinsStorageImpl.getInstance(); } - /** - * Are the utils used in the API, this class does not interfere negatively in the functioning of the API - */ - public AccessUtils getAccessUtils() { - return accessUtils; - } - /** *

This method will return a copy of the list of active sessions

*

Remember that it is a copy, removing any object from this list will not delete the session

@@ -207,20 +186,6 @@ public int getDevId() { return devId; } - /** - *

Define DevId in this instance

- *

It cannot be changed if there is an active session

- * - * @param devId The Developer Id - * @throws ContextException If you have an active session. - */ - public Paladins setDevId(int devId) { - if (sessions.size() != 0) - throw new ContextException("You cannot change the data after a session has already been created!"); - this.devId = devId; - return this; - } - /** * @return The API authentication key present in this instance. */ @@ -228,21 +193,6 @@ public String getAuthkey() { return authkey; } - /** - *

Define Authkey in this instance

- *

It cannot be changed if there is an active session

- * - * @param authkey The API access token - * @throws ContextException If you have an active session. - */ - public Paladins setAuthkey(String authkey) { - if (sessions.size() != 0) { - throw new ContextException("You cannot change the data after a session has already been created!"); - } - this.authkey = authkey; - return this; - } - public OkHttpClient getClient() { return client; } @@ -252,6 +202,10 @@ public Paladins setClient(@Nonnull OkHttpClient client) { return this; } + public static PaladinsBuilder builder() { + return new PaladinsBuilder(); + } + @Override public String toString() { return "Paladins{" + diff --git a/src/main/java/me/skiincraft/api/paladins/PaladinsBuilder.java b/src/main/java/me/skiincraft/api/paladins/PaladinsBuilder.java index 32a1f06..1e20e8a 100644 --- a/src/main/java/me/skiincraft/api/paladins/PaladinsBuilder.java +++ b/src/main/java/me/skiincraft/api/paladins/PaladinsBuilder.java @@ -52,8 +52,6 @@ public PaladinsBuilder setAuthKey(String authKey) { } public Paladins build() { - return Paladins.getInstance() - .setAuthkey(authKey) - .setDevId(devId); + return new Paladins(devId, authKey); } } \ No newline at end of file diff --git a/src/main/java/me/skiincraft/api/paladins/entity/champions/objects/Skins.java b/src/main/java/me/skiincraft/api/paladins/entity/champions/objects/Skins.java index ffabe12..0ddcbdb 100644 --- a/src/main/java/me/skiincraft/api/paladins/entity/champions/objects/Skins.java +++ b/src/main/java/me/skiincraft/api/paladins/entity/champions/objects/Skins.java @@ -63,8 +63,8 @@ public Language getLanguage() { @Override public String toString() { return "Skins{" + - "championSkins=" + championSkins.length + - "championId=" + getChampionId() + + "championId=" + championId + + ", championSkins=" + championSkins.length + ", language=" + language + '}'; } diff --git a/src/main/java/me/skiincraft/api/paladins/impl/paladins/EndpointImpl.java b/src/main/java/me/skiincraft/api/paladins/impl/paladins/EndpointImpl.java index f7da3ec..f366924 100644 --- a/src/main/java/me/skiincraft/api/paladins/impl/paladins/EndpointImpl.java +++ b/src/main/java/me/skiincraft/api/paladins/impl/paladins/EndpointImpl.java @@ -24,7 +24,6 @@ import me.skiincraft.api.paladins.impl.player.FriendImpl; import me.skiincraft.api.paladins.impl.player.LoadoutImpl; import me.skiincraft.api.paladins.impl.player.PlayerImpl; -import me.skiincraft.api.paladins.storage.impl.PaladinsStorageImpl; import me.skiincraft.api.paladins.internal.logging.PaladinsLogger; import me.skiincraft.api.paladins.internal.requests.APIRequest; import me.skiincraft.api.paladins.internal.requests.impl.DefaultAPIRequest; @@ -44,23 +43,25 @@ import me.skiincraft.api.paladins.objects.ranking.Place; import me.skiincraft.api.paladins.objects.ranking.Tier; import me.skiincraft.api.paladins.storage.PaladinsStorage; +import me.skiincraft.api.paladins.storage.impl.PaladinsStorageImpl; import org.slf4j.Logger; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; import java.time.OffsetDateTime; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; +import java.util.*; import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collector; import java.util.stream.Collectors; +import static java.util.stream.Collectors.collectingAndThen; +import static java.util.stream.Collectors.groupingBy; + public class EndpointImpl implements EndPoint { - private final Session session; private final Paladins paladins; + private final Session session; private final PaladinsStorage paladinsStorage; private final Logger logger; @@ -75,7 +76,8 @@ public EndpointImpl(Session session) { } public APIRequest getPlayer(String player) { - return new DefaultAPIRequest<>("getplayer", session.getSessionId(), new String[]{player}, (response) -> { + String[] args = new String[]{player}; + return new DefaultAPIRequest<>("getplayer", session.getSessionId(), args, (response) -> { try { JsonArray array = JsonParser.parseString(Objects.requireNonNull(response.body(), "json is null").string()) .getAsJsonArray(); @@ -101,10 +103,11 @@ public APIRequest getPlayer(String player) { @Override public APIRequest getPlayer(String player, Platform platform) { - if (platform == Platform.PC || platform == Platform.Console){ + if (platform == Platform.PC || platform == Platform.Console) { throw new ContextException("You need to specify the subplatform!"); } - return new DefaultAPIRequest<>("getplayer", session.getSessionId(), new String[]{player, String.valueOf(platform.getPortalId()[0])}, (response) -> { + String[] args = new String[]{player, String.valueOf(platform.getPortalId()[0])}; + return new DefaultAPIRequest<>("getplayer", session.getSessionId(), args, (response) -> { try { JsonArray array = JsonParser.parseString(Objects.requireNonNull(response.body(), "json is null").string()) .getAsJsonArray(); @@ -129,7 +132,8 @@ public APIRequest getPlayer(String player, Platform platform) { } public APIRequest searchPlayer(String queue, Platform platform) { - return new DefaultAPIRequest<>("searchplayers", session.getSessionId(), new String[]{queue}, (response) -> { + String[] args = new String[]{queue}; + return new DefaultAPIRequest<>("searchplayers", session.getSessionId(), args, (response) -> { try { JsonArray array = JsonParser.parseString(Objects.requireNonNull(response.body(), "json is null").string()).getAsJsonArray(); if (array.size() == 0) @@ -147,7 +151,8 @@ public APIRequest searchPlayer(String queue, Platform platform) { } public APIRequest getPlayerStatus(String player) { - return new DefaultAPIRequest<>("getplayerstatus", session.getSessionId(), new String[]{player}, (response) -> { + String[] args = new String[]{player}; + return new DefaultAPIRequest<>("getplayerstatus", session.getSessionId(), args, (response) -> { try { JsonArray array = JsonParser.parseString(Objects.requireNonNull(response.body(), "json is null").string()).getAsJsonArray(); if (array.size() == 0) @@ -167,7 +172,8 @@ public APIRequest getChampions(Language language) { if (paladinsStorage.championsIsStored(language)) { return new FakeAPIRequest<>(paladinsStorage.getChampionsFromStorage(language), 200); } - return new DefaultAPIRequest<>("getchampions", session.getSessionId(), new String[]{String.valueOf(language.getLanguagecode())}, (response) -> { + String[] args = new String[]{String.valueOf(language.getLanguagecode())}; + return new DefaultAPIRequest<>("getchampions", session.getSessionId(), args, (response) -> { try { ChampionImpl[] championsArray = new GsonBuilder().registerTypeAdapter(ChampionImpl.class, new ChampionAdapter(language, this)) .create().fromJson(Objects.requireNonNull(response.body(), "json is null").string(), ChampionImpl[].class); @@ -193,7 +199,8 @@ public APIRequest getChampion(long championId, Language language) { @Nullable public APIRequest getChampion(String championName, Language language) { - Champion champion = getChampions(language).get().getAsStream().filter(ch -> ch.getName().equalsIgnoreCase(championName)) + Champion champion = getChampions(language).get().getAsStream() + .filter(ch -> ch.getName().equalsIgnoreCase(championName)) .findFirst() .orElse(null); @@ -207,62 +214,95 @@ public APIRequest getChampionCards(long championsId, Language language) { if (paladinsStorage.cardsIsStored(championsId, language)) { return new FakeAPIRequest<>(paladinsStorage.getCardsFromStorage(championsId, language), 200); } - return new DefaultAPIRequest<>("getchampioncards", session.getSessionId(), new String[]{String.valueOf(championsId), String.valueOf(language.getLanguagecode())}, - (response) -> { - try { - JsonArray array = JsonParser.parseString(Objects.requireNonNull(response.body(), "json is null").string()) - .getAsJsonArray(); - if (array.size() == 0) - throw new ChampionException("This requested champion does not exist."); - - Gson gson = new GsonBuilder() - .registerTypeAdapter(Card.class, new CardImpl(championsId, language)) - .create(); - - Cards cards = new Cards(new ArrayList<>(Arrays.asList(gson.fromJson(array, Card[].class))), championsId, language); - storageImpl.store(cards); - return cards; - } catch (IOException e) { - e.printStackTrace(); - return null; - } - }, paladins); + String[] args = new String[]{String.valueOf(championsId), String.valueOf(language.getLanguagecode())}; + return new DefaultAPIRequest<>("getchampioncards", session.getSessionId(), args, (response) -> { + try { + JsonArray array = JsonParser.parseString(Objects.requireNonNull(response.body(), "json is null").string()) + .getAsJsonArray(); + if (array.size() == 0) + throw new ChampionException("This requested champion does not exist."); + + Gson gson = new GsonBuilder() + .registerTypeAdapter(Card.class, new CardImpl(championsId, language)) + .create(); + + Cards cards = new Cards(new ArrayList<>(Arrays.asList(gson.fromJson(array, Card[].class))), championsId, language); + storageImpl.store(cards); + return cards; + } catch (IOException e) { + e.printStackTrace(); + return null; + } + }, paladins); + } + + public DefaultAPIRequest> getChampionsSkins(Language language) { + String[] args = new String[]{"-1", String.valueOf(language.getLanguagecode())}; + return new DefaultAPIRequest<>("getchampionskins", session.getSessionId(), args, (response) -> { + try { + JsonArray array = JsonParser.parseString(Objects.requireNonNull(response.body(), "json is null").string()).getAsJsonArray(); + if (array.size() == 0) + throw new ChampionException("This requested champion does not exist."); + + Map> champions = new HashMap<>(); + List skin = new ArrayList<>(); + for (JsonElement element : array) { + skin.add(new Gson().fromJson(element.getAsJsonObject(), ChampionSkinImpl.class) + .setLanguage(language) + .setEndPoint(this)); + } + + return skin.stream().collect(collectionChampionSkins(language)); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + }, paladins); + } + + private Collector> collectionChampionSkins(Language language) { + return collectingAndThen(groupingBy(ChampionSkin::getChampionId), (map) -> { + List skins = new ArrayList<>(); + for (Map.Entry> entry : map.entrySet()) { + skins.add(new Skins(entry.getValue(), entry.getKey(), language)); + } + return skins; + }); } public APIRequest getChampionSkin(long championsId, Language language) { if (paladinsStorage.skinIsStored(championsId, language)) { return new FakeAPIRequest<>(paladinsStorage.getSkinFromStorage(championsId, language), 200); } - return new DefaultAPIRequest<>("getchampionskins", session.getSessionId(), new String[]{String.valueOf(championsId), String.valueOf(language.getLanguagecode())}, - (response) -> { - try { - JsonArray array = JsonParser.parseString(Objects.requireNonNull(response.body(), "json is null").string()).getAsJsonArray(); - if (array.size() == 0) - throw new ChampionException("This requested champion does not exist."); - - List skin = new ArrayList<>(); - for (JsonElement element : array) { - skin.add(new Gson().fromJson(element.getAsJsonObject(), ChampionSkinImpl.class) - .setLanguage(language) - .setEndPoint(this)); - } - return new Skins(skin, championsId, language); - } catch (IOException e) { - e.printStackTrace(); - return null; - } - }, paladins); + String[] args = new String[]{String.valueOf(championsId), String.valueOf(language.getLanguagecode())}; + return new DefaultAPIRequest<>("getchampionskins", session.getSessionId(), args, (response) -> { + try { + JsonArray array = JsonParser.parseString(Objects.requireNonNull(response.body(), "json is null").string()).getAsJsonArray(); + if (array.size() == 0) + throw new ChampionException("This requested champion does not exist."); + + List skin = new ArrayList<>(); + for (JsonElement element : array) { + skin.add(new Gson().fromJson(element.getAsJsonObject(), ChampionSkinImpl.class) + .setLanguage(language) + .setEndPoint(this)); + } + return new Skins(skin, championsId, language); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + }, paladins); } public APIRequest getPlayerBatch(@Nonnull List idList) { if (idList.size() <= 1) throw new ContextException("There are only 1 or less players being requested, use the getPlayer() method!"); - String ids = idList.stream() - .map(String::valueOf) - .collect(Collectors.joining(",")); + String[] args = new String[]{idList.stream().map(String::valueOf) + .collect(Collectors.joining(","))}; - return new DefaultAPIRequest<>("getplayerbatch", session.getSessionId(), new String[]{ids}, (response) -> { + return new DefaultAPIRequest<>("getplayerbatch", session.getSessionId(), args, (response) -> { try { JsonArray array = JsonParser.parseString(Objects.requireNonNull(response.body(), "json is null").string()).getAsJsonArray(); List players = new ArrayList<>(); @@ -291,7 +331,8 @@ public APIRequest getPlayerBatch(@Nonnull List idList) { } public APIRequest getPlayerChampions(long userId) { - return new DefaultAPIRequest<>("getchampionranks", new String[]{String.valueOf(userId)}, (response) -> { + String[] args = new String[]{String.valueOf(userId)}; + return new DefaultAPIRequest<>("getchampionranks", args, (response) -> { try { JsonArray array = JsonParser.parseString(Objects.requireNonNull(response.body(), "json is null").string()).getAsJsonArray(); if (array.size() == 0) @@ -313,7 +354,8 @@ public APIRequest getPlayerChampions(long userId) { } public APIRequest getQueueStats(long userId, @Nonnull Queue queue) { - return new DefaultAPIRequest<>("getqueuestats", session.getSessionId(), new String[]{String.valueOf(userId), String.valueOf(queue.getQueueId())}, (response) -> { + String[] args = new String[]{String.valueOf(userId), String.valueOf(queue.getQueueId())}; + return new DefaultAPIRequest<>("getqueuestats", session.getSessionId(), args, (response) -> { try { JsonArray array = JsonParser.parseString(Objects.requireNonNull(response.body(), "json is null").string()).getAsJsonArray(); if (array.size() == 0) @@ -337,7 +379,8 @@ public APIRequest getQueueStats(long userId, @Nonnull Queue queu } public APIRequest getFriends(long userId) { - return new DefaultAPIRequest<>("getfriends", session.getSessionId(), new String[]{String.valueOf(userId)}, (response) -> { + String[] args = new String[]{String.valueOf(userId)}; + return new DefaultAPIRequest<>("getfriends", session.getSessionId(), args, (response) -> { try { JsonArray array = JsonParser.parseString(Objects.requireNonNull(response.body(), "json is null").string()).getAsJsonArray(); if (array.size() == 0) @@ -358,7 +401,8 @@ public APIRequest getFriends(long userId) { } public APIRequest getLoadouts(long userId, Language language) { - return new DefaultAPIRequest<>("getplayerloadouts", session.getSessionId(), new String[]{String.valueOf(userId), String.valueOf(language.getLanguagecode())}, (response) -> { + String[] args = new String[]{String.valueOf(userId), String.valueOf(language.getLanguagecode())}; + return new DefaultAPIRequest<>("getplayerloadouts", session.getSessionId(), args, (response) -> { try { JsonArray array = JsonParser.parseString(Objects.requireNonNull(response.body(), "json is null").string()).getAsJsonArray(); if (array.size() == 0) @@ -383,7 +427,8 @@ public APIRequest getMatchDetails(long matchId) { if (storageImpl.matchIsStored(matchId)) { return new FakeAPIRequest<>(storageImpl.getMatchFromStorage(matchId), 200); } - return new DefaultAPIRequest<>("getmatchdetails", session.getSessionId(), new String[]{String.valueOf(matchId)}, (response) -> { + String[] args = new String[]{String.valueOf(matchId)}; + return new DefaultAPIRequest<>("getmatchdetails", session.getSessionId(), args, (response) -> { try { JsonArray array = JsonParser.parseString(Objects.requireNonNull(response.body(), "json is null").string()).getAsJsonArray(); if (array.size() == 0) @@ -415,12 +460,12 @@ public APIRequest> getMatchDetails(@Nonnull List matchBatch) { return new FakeAPIRequest<>(matchs, 200); } - String ids = matchBatch.stream() + String[] args = new String[]{matchBatch.stream() .distinct() .filter(id -> matchs.stream().noneMatch(match -> match.getMatchId() == id)) - .map(String::valueOf).collect(Collectors.joining(",")); + .map(String::valueOf).collect(Collectors.joining(","))}; - return new DefaultAPIRequest<>("getmatchdetailsbatch", session.getSessionId(), new String[]{ids}, (response) -> { + return new DefaultAPIRequest<>("getmatchdetailsbatch", session.getSessionId(), args, (response) -> { try { JsonArray array = JsonParser.parseString(Objects.requireNonNull(response.body(), "json is null").string()).getAsJsonArray(); if (array.size() == 0) { @@ -454,7 +499,8 @@ public APIRequest> getMatchDetails(@Nonnull List matchBatch) { } public APIRequest> getMatchHistory(long userId) { - return new DefaultAPIRequest<>("getmatchhistory", session.getSessionId(), new String[]{String.valueOf(userId)}, (response) -> { + String[] args = new String[]{String.valueOf(userId)}; + return new DefaultAPIRequest<>("getmatchhistory", session.getSessionId(), args, (response) -> { try { JsonArray array = JsonParser.parseString(Objects.requireNonNull(response.body(), "json is null").string()).getAsJsonArray(); if (array.size() == 0) @@ -478,32 +524,33 @@ public APIRequest> getMatchHistory(long userId) { } public APIRequest getLeaderboard(@Nonnull Tier tier, int season) { - return new DefaultAPIRequest<>("getLeagueLeaderboard", session.getSessionId(), new String[]{Queue.Live_Competitive_Keyboard.getQueueId() + "", tier.getRankId() + "", season + ""}, - (response) -> { - try { - JsonArray array = JsonParser.parseString(Objects.requireNonNull(response.body(), "json is null").string()).getAsJsonArray(); - if (array.size() == 0) - throw new SearchException("It was not possible to find this leaderboard."); - - List place = new ArrayList<>(); - AtomicInteger integer = new AtomicInteger(1); - Gson gson = new Gson(); - for (JsonElement element : array) { - place.add(gson.fromJson(element, PlaceImpl.class) - .setTier(tier) - .setPosition(integer.getAndIncrement()) - .setEndPoint(this)); - } - return new LeaderboardImpl(place, tier); - } catch (IOException e) { - e.printStackTrace(); - return null; - } - }, paladins); + String[] args = new String[]{Queue.Live_Competitive_Keyboard.getQueueId() + "", tier.getRankId() + "", season + ""}; + return new DefaultAPIRequest<>("getLeagueLeaderboard", session.getSessionId(), args, (response) -> { + try { + JsonArray array = JsonParser.parseString(Objects.requireNonNull(response.body(), "json is null").string()).getAsJsonArray(); + if (array.size() == 0) + throw new SearchException("It was not possible to find this leaderboard."); + + List place = new ArrayList<>(); + AtomicInteger integer = new AtomicInteger(1); + Gson gson = new Gson(); + for (JsonElement element : array) { + place.add(gson.fromJson(element, PlaceImpl.class) + .setTier(tier) + .setPosition(integer.getAndIncrement()) + .setEndPoint(this)); + } + return new LeaderboardImpl(place, tier); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + }, paladins); } public APIRequest getMatchPlayerDetails(long matchId) { - return new DefaultAPIRequest<>("getmatchplayerdetails", session.getSessionId(), new String[]{String.valueOf(matchId)}, (response) -> { + String[] args = new String[]{String.valueOf(matchId)}; + return new DefaultAPIRequest<>("getmatchplayerdetails", session.getSessionId(), args, (response) -> { try { JsonArray array = JsonParser.parseString(Objects.requireNonNull(response.body(), "json is null").string()).getAsJsonArray(); if (array.size() == 0) diff --git a/src/main/java/me/skiincraft/api/paladins/impl/paladins/SessionImpl.java b/src/main/java/me/skiincraft/api/paladins/impl/paladins/SessionImpl.java index 8f638f8..a11fed5 100644 --- a/src/main/java/me/skiincraft/api/paladins/impl/paladins/SessionImpl.java +++ b/src/main/java/me/skiincraft/api/paladins/impl/paladins/SessionImpl.java @@ -32,7 +32,7 @@ public class SessionImpl implements Session { private final String requestMessage; private final EndPoint endPoint; private final Paladins paladins; - private Logger logger; + private final Logger logger; private Timer timer; private Consumer validating; private boolean testresponse; @@ -61,21 +61,6 @@ public SessionImpl(String sessionId, String timeStamp, String requestMessage, Pa worker(); } - /** - *

Session

- * - *

This class represents a session that was created.

- *

Contains information about the session and Endpoint

- * - * @param requestMessage Is the ret_msg - * @param sessionId Is the sessionId - * @param timeStamp Is the timestamp in UTC - * @see Paladins - */ - public SessionImpl(String sessionId, String timeStamp, String requestMessage) { - this(sessionId, timeStamp, requestMessage, Paladins.getInstance()); - } - /** * Generates an Id used in Worker. */ diff --git a/src/main/java/me/skiincraft/api/paladins/internal/requests/impl/DefaultAPIRequest.java b/src/main/java/me/skiincraft/api/paladins/internal/requests/impl/DefaultAPIRequest.java index f74f15b..e4a7c80 100644 --- a/src/main/java/me/skiincraft/api/paladins/internal/requests/impl/DefaultAPIRequest.java +++ b/src/main/java/me/skiincraft/api/paladins/internal/requests/impl/DefaultAPIRequest.java @@ -4,6 +4,7 @@ import me.skiincraft.api.paladins.exceptions.RequestException; import me.skiincraft.api.paladins.internal.requests.APIRequest; import me.skiincraft.api.paladins.internal.requests.ResponseParser; +import static me.skiincraft.api.paladins.objects.HirezAPIUtils.makeUrl; import okhttp3.Call; import okhttp3.OkHttpClient; import okhttp3.Request; @@ -135,7 +136,7 @@ private Request buildRequest() { return this.request; } String endPoint = Objects.requireNonNull(endpoint, "endpoint method is null"); - String url = (sessionId == null) ? api.getAccessUtils().makeUrl(endPoint, args) : api.getAccessUtils().makeUrl(endPoint, sessionId, args); + String url = (sessionId == null) ? makeUrl(api.getDevId(), api.getAuthkey(), endPoint, args) : makeUrl(api.getDevId(), api.getAuthkey(), endPoint, sessionId, args); logger.debug("Creating a API URL: " + url); Request.Builder request = new Request.Builder() .url(Objects.requireNonNull(url, "url is null")) diff --git a/src/main/java/me/skiincraft/api/paladins/internal/session/EndPoint.java b/src/main/java/me/skiincraft/api/paladins/internal/session/EndPoint.java index f15f2b3..9dad495 100644 --- a/src/main/java/me/skiincraft/api/paladins/internal/session/EndPoint.java +++ b/src/main/java/me/skiincraft/api/paladins/internal/session/EndPoint.java @@ -199,6 +199,17 @@ default APIRequest getChampionSkin(Champion champion) { */ APIRequest getChampionSkin(long championsId, Language language); + + /** + *

Make an API request to return all champion skins.

+ *

After the order is completed, the API will receive a Json, which will be converted into a class and returned

+ * + * @param language the language you want to receive the champions skins; + * @return {@link List} + * @throws me.skiincraft.api.paladins.exceptions.RequestException If anything is wrong with the session. + */ + APIRequest> getChampionsSkins(Language language); + /** *

Make an API request to return a batch of players.

*

After the order is completed, the API will receive a Json, which will be converted into a class and returned

diff --git a/src/main/java/me/skiincraft/api/paladins/objects/AccessUtils.java b/src/main/java/me/skiincraft/api/paladins/objects/HirezAPIUtils.java similarity index 71% rename from src/main/java/me/skiincraft/api/paladins/objects/AccessUtils.java rename to src/main/java/me/skiincraft/api/paladins/objects/HirezAPIUtils.java index 2c8b37d..6c7af84 100644 --- a/src/main/java/me/skiincraft/api/paladins/objects/AccessUtils.java +++ b/src/main/java/me/skiincraft/api/paladins/objects/HirezAPIUtils.java @@ -1,7 +1,5 @@ package me.skiincraft.api.paladins.objects; -import me.skiincraft.api.paladins.Paladins; - import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; @@ -10,14 +8,9 @@ import java.util.SimpleTimeZone; import java.util.stream.Collectors; -public class AccessUtils { +public class HirezAPIUtils { private static final String ENDPOINT = "https://api.paladins.com/paladinsapi.svc"; - private final Paladins paladins; - - public AccessUtils(Paladins paladins) { - this.paladins = paladins; - } public static boolean checkResponse(String body) { if (body.contains("Invalid Developer Id") || @@ -29,24 +22,16 @@ public static boolean checkResponse(String body) { return !body.contains("Exception - Timestamp"); } - public String getAuthKey() { - return paladins.getAuthkey(); - } - - public Integer getDevId() { - return paladins.getDevId(); - } - - private String complete(String... strings) { + private static String complete(String... strings) { return Arrays.stream(strings).map(str -> str.replace(" ", "_") .replace("/", "")) .collect(Collectors.joining("/")); } - public String makeUrl(String method, String[] args) { + public static String makeUrl(int devId, String authkey, String method, String[] args) { String url = String.format(ENDPOINT + "/%s%s/%s", method.toLowerCase(), "Json", - complete(String.valueOf(getDevId()), - getSignature(method.toLowerCase()), + complete(String.valueOf(devId), + getSignature(devId, method.toLowerCase(), authkey), getTimeStamp()) + ((args == null || args.length == 0) ? "" : "/")); if (args == null) { @@ -55,10 +40,10 @@ public String makeUrl(String method, String[] args) { return url + String.join("/", args); } - public String makeUrl(String method, String sessionId, String[] args) { + public static String makeUrl(int devId, String authkey, String method, String sessionId, String[] args) { String url = String.format(ENDPOINT + "/%s%s/%s", method.toLowerCase(), "Json", - complete(String.valueOf(getDevId()), - getSignature(method.toLowerCase()), + complete(String.valueOf(devId), + getSignature(devId, method.toLowerCase(), authkey), sessionId, getTimeStamp()) + ((args == null || args.length == 0) ? "" : "/")); @@ -68,15 +53,15 @@ public String makeUrl(String method, String sessionId, String[] args) { return url + String.join("/", args); } - public String getTimeStamp() { + public static String getTimeStamp() { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); sdf.setTimeZone(new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC")); return sdf.format(new Date()); } - public String getSignature(String method) { + public static String getSignature(int devId, String method, String authkey) { try { - String signature = getDevId() + method + getAuthKey() + getTimeStamp(); + String signature = devId + method + authkey + getTimeStamp(); MessageDigest digestor = MessageDigest.getInstance("MD5"); digestor.update(signature.getBytes()); byte[] bytes = digestor.digest();