Skip to content

Commit

Permalink
[feature] Implementado SFL4J-API como Logger
Browse files Browse the repository at this point in the history
- Foram corrigido alguns métodos e documentação.
- Adicionado SimpleLogger.java como alternativa caso não encontre a classe StaticLoggerBinder
  • Loading branch information
Cristian-Sknz committed Apr 18, 2021
1 parent 781039e commit d5f4da7
Show file tree
Hide file tree
Showing 10 changed files with 518 additions and 41 deletions.
3 changes: 2 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ plugins {
}

group 'me.skiincraft'
version '2021.0313.0'
version '2021.0417.0'

repositories {
maven { url 'https://jitpack.io' }
Expand All @@ -15,6 +15,7 @@ dependencies {
implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.6'
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'
testImplementation(platform('org.junit:junit-bom:5.7.0'))
testImplementation('org.junit.jupiter:junit-jupiter')
}
Expand Down
26 changes: 23 additions & 3 deletions src/main/java/me/skiincraft/api/paladins/Paladins.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
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.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;
Expand All @@ -20,7 +21,9 @@
import me.skiincraft.api.paladins.objects.miscellany.DataUsed;
import me.skiincraft.api.paladins.storage.PaladinsStorage;
import okhttp3.OkHttpClient;
import org.slf4j.Logger;

import javax.annotation.Nonnull;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
Expand All @@ -42,7 +45,8 @@ public class Paladins {
private final AccessUtils accessUtils;
private final PaladinsStorage storage;
private final List<Session> sessions;
private final OkHttpClient client;
private OkHttpClient client;
private final Logger logger;

private int devId;
private String authkey;
Expand All @@ -51,6 +55,7 @@ private Paladins() {
this.accessUtils = new AccessUtils(this);
this.sessions = new ArrayList<>();
this.client = new OkHttpClient();
this.logger = PaladinsLogger.getLogger(Paladins.class);
this.storage = new PaladinsStorageImpl(
new StorageImpl<Champions>(new Champions[0]) {
public Champions getById(long id) {
Expand All @@ -77,11 +82,16 @@ public Skins getById(long id) {
*/
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;
}

/**
* <p>Method used to create a new session</p>
* <p>
Expand All @@ -99,8 +109,10 @@ public synchronized APIRequest<Session> createSession() throws RequestException
.fromJson(Objects.requireNonNull(response.body(), "response is null")
.string(), SessionImpl.class);
sessions.add(session);
logger.info("A new session has been created {}", session.getSessionId());
return session;
} catch (IOException e) {
logger.error("There was a problem connecting with the API:", e);
e.printStackTrace();
return null;
}
Expand All @@ -122,11 +134,13 @@ public synchronized APIRequest<Boolean> testSession(String sessionId) {
try {
String json = Objects.requireNonNull(response.body(), "response is null").string();
if (AccessUtils.checkResponse(json)) {
logger.info("TestSession: Session {} is still valid", sessionId);
return true;
}
Stream<Session> activeSessions = sessions.stream().filter((session) -> session.getSessionId().equalsIgnoreCase(sessionId));
if (activeSessions.count() >= 1) {
System.err.println(activeSessions.count() + " Sessions have been removed for being invalid.");
logger.warn("[{}] Sessions have been removed for being invalid.", activeSessions.count());
logger.debug("Session [{}] is invalid", sessionId);
sessions.removeAll(activeSessions.collect(Collectors.toList()));
}
throw new RequestException(json, json);
Expand All @@ -149,6 +163,7 @@ public synchronized APIRequest<Boolean> testSession(String sessionId) {
*/
public synchronized APIRequest<Session> resumeSession(String sessionId) {
if (testSession(sessionId).get()) {
logger.info("Session [{}] was successfully resumed", sessionId);
return new FakeAPIRequest<>(new SessionImpl(sessionId, null, null, this), 200);
}
throw new RequestException("You tried to resume an invalid session.");
Expand All @@ -162,7 +177,7 @@ public synchronized APIRequest<Session> resumeSession(String sessionId) {
* @throws RequestException Will throw an exception if the session is invalid.
*/
public synchronized APIRequest<DataUsed> getDataUsed(String sessionId) {
return new DefaultAPIRequest<>("testsession", sessionId, null, (response) -> {
return new DefaultAPIRequest<>("getdataused", sessionId, null, (response) -> {
try {
String json = Objects.requireNonNull(response.body(), "response is null").string();
if (AccessUtils.checkResponse(json)) {
Expand Down Expand Up @@ -256,6 +271,11 @@ public OkHttpClient getClient() {
return client;
}

public Paladins setClient(@Nonnull OkHttpClient client) {
this.client = client;
return this;
}

@Override
public String toString() {
return "Paladins{" +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
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.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;
Expand All @@ -43,6 +44,7 @@
import me.skiincraft.api.paladins.objects.ranking.Place;
import me.skiincraft.api.paladins.objects.ranking.Tier;
import me.skiincraft.api.paladins.storage.PaladinsStorage;
import org.slf4j.Logger;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
Expand All @@ -60,6 +62,7 @@ public class EndpointImpl implements EndPoint {
private final Session session;
private final Paladins paladins;
private final PaladinsStorage paladinsStorage;
private final Logger logger;

private final PaladinsStorageImpl storageImpl;

Expand All @@ -68,18 +71,14 @@ public EndpointImpl(Session session) {
this.paladins = session.getPaladins();
this.paladinsStorage = paladins.getStorage();
this.storageImpl = (PaladinsStorageImpl) paladinsStorage;
}

private String makeUrl(String method, String[] args) {
return paladins.getAccessUtils().makeUrl(method, session.getSessionId(), args);
this.logger = PaladinsLogger.getLogger(EndPoint.class);
}

public APIRequest<Player> getPlayer(String player) {
return new DefaultAPIRequest<>("getplayer", session.getSessionId(), new String[]{player}, (response) -> {
try {
JsonArray array = JsonParser.parseString(Objects.requireNonNull(response.body(), "json is null").string())
.getAsJsonArray();

if (array.size() == 0) {
throw new PlayerException(String.format("The player '%s' does not exist.", player), PlayerException.PlayerExceptionType.NOT_EXIST);
}
Expand Down Expand Up @@ -107,8 +106,8 @@ public APIRequest<SearchPlayers> searchPlayer(String queue, Platform platform) {
if (array.size() == 0)
throw new SearchException("No players found");

logger.debug("SearchPlayers: found {} total results for {}", array.size(), queue);
SearchPlayer[] search = new Gson().fromJson(array, SearchPlayer[].class);

return (platform != null) ? new SearchPlayers(Arrays.stream(search).filter(s -> Platform.getPlatformByPortalId(s.getPortalId()) == platform)
.toArray(SearchPlayer[]::new)) : new SearchPlayers(search);
} catch (IOException e) {
Expand Down Expand Up @@ -490,6 +489,7 @@ public APIRequest<LiveMatch> getMatchPlayerDetails(long matchId) {
}

@Override
@Deprecated
public APIRequest<List<BountyItem>> getBountyItems() {
return new DefaultAPIRequest<>("getBountyItems", session.getSessionId(), null, (response) -> {
try {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package me.skiincraft.api.paladins.impl.paladins;

import me.skiincraft.api.paladins.Paladins;
import me.skiincraft.api.paladins.internal.logging.PaladinsLogger;
import me.skiincraft.api.paladins.internal.session.EndPoint;
import me.skiincraft.api.paladins.internal.session.Session;
import org.slf4j.Logger;

import javax.annotation.Nullable;
import java.util.Timer;
Expand Down Expand Up @@ -30,6 +32,7 @@ public class SessionImpl implements Session {
private final String requestMessage;
private final EndPoint endPoint;
private final Paladins paladins;
private Logger logger;
private Timer timer;
private Consumer<Session> validating;
private boolean testresponse;
Expand All @@ -54,7 +57,7 @@ public SessionImpl(String sessionId, String timeStamp, String requestMessage, Pa
this.testresponse = true;

endPoint = new EndpointImpl(this);

this.logger = PaladinsLogger.getLogger(Session.class);
worker();
}

Expand Down Expand Up @@ -128,19 +131,20 @@ private void worker() {
timer = null;
}
final int worker = serialNumber();
final Session api = this;
timer = new Timer("SessionWorker-" + worker);
timer.schedule(new TimerTask() {

public void run() {
logger.debug("Checking if the session is still valid");
testresponse = testSession().get();
if (testresponse) {
if (validating != null) {
validating.accept(null);
validating.accept(api);
}
System.err.println("[SessionWorker-" + worker + "] Session [" + sessionId + "] is still valid.");
return;
}
System.err.println("[SessionWorker-" + worker + "] Session [" + sessionId + "] is no longer valid, and will be removed from the storage.");
logger.warn("Session [{}] is no longer valid, and will be removed from the storage.", sessionId);
}
}, TimeUnit.MINUTES.toMillis(10), TimeUnit.MINUTES.toMillis(14));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@
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.internal.logging.PaladinsLogger;
import me.skiincraft.api.paladins.objects.miscellany.Language;
import me.skiincraft.api.paladins.storage.PaladinsStorage;
import me.skiincraft.api.paladins.storage.Storage;
import org.slf4j.Logger;

import javax.annotation.Nullable;
import java.util.ArrayList;
Expand All @@ -23,6 +25,7 @@ public class PaladinsStorageImpl implements PaladinsStorage {
private final Storage<Match> matchMemory;
private final Storage<Cards> cardsMemory;
private final Storage<Skins> skinMemory;
private final Logger logger = PaladinsLogger.getLogger(PaladinsStorage.class);

public PaladinsStorageImpl(Storage<Champions> championMemory, Storage<Match> matchMemory, Storage<Cards> cardsMemory, Storage<Skins> skinMemory) {
this.championMemory = championMemory;
Expand Down Expand Up @@ -83,8 +86,9 @@ public synchronized void addChampion(Champions champion) {
StorageImpl<Champions> impl = (StorageImpl<Champions>) championMemory;
List<Champions> cc = new ArrayList<>(Arrays.asList(impl.item));
cc.removeAll(cc.stream().filter(cham -> cham.getLanguage() == champion.getLanguage()).collect(Collectors.toList()));

cc.add(champion);
logger.debug("Champions: Added a new collection of champions in storage");
logger.debug("Champions: Size={}, Language='{}'", champion.size(), champion.get(0).getLanguage());

impl.lastupdate = System.currentTimeMillis();
impl.item = cc.toArray(new Champions[0]);
Expand All @@ -97,8 +101,9 @@ public synchronized void addMatch(Match match) {
StorageImpl<Match> impl = (StorageImpl<Match>) matchMemory;
List<Match> cc = new ArrayList<>(Arrays.asList(impl.item));
cc.removeAll(cc.stream().filter(cham -> cham.getMatchId() == cham.getMatchId()).collect(Collectors.toList()));

cc.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]);
Expand All @@ -116,6 +121,8 @@ public synchronized void addCard(Cards cards) {
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);
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]);
Expand All @@ -127,6 +134,8 @@ public synchronized void addSkin(Skins skin) {
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);
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]);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package me.skiincraft.api.paladins.internal.logging;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;

public class PaladinsLogger {

private static PaladinsLogger instance;
private static final Map<String, Logger> simpleLoggers = new HashMap<>();
private static boolean SLFJ4_ENABLED;

private PaladinsLogger() {
boolean found = false;
try {
Class.forName("org.slf4j.impl.StaticLoggerBinder");
found = true;
} catch (ClassNotFoundException impl){
try {
Class<?> serviceProviderClass = Class.forName("org.slf4j.spi.SLF4JServiceProvider");
found = ServiceLoader.load(serviceProviderClass).iterator().hasNext();
} catch (ClassNotFoundException spi){
lockAndWaitForWarning();
}
}
SLFJ4_ENABLED = found;
}

private void lockAndWaitForWarning(){
try {
LoggerFactory.getLogger(PaladinsLogger.class);
Thread.sleep(2500);
} catch (Exception ignored){}
}

public Logger getLoggerInstance(String name){
if (SLFJ4_ENABLED)
return LoggerFactory.getLogger(name);

synchronized (simpleLoggers) {
return simpleLoggers.computeIfAbsent(name, SimpleLogger::new);
}
}

public Logger getLoggerInstance(Class<?> clazz){
if (SLFJ4_ENABLED)
return LoggerFactory.getLogger(clazz);

synchronized (simpleLoggers) {
return simpleLoggers.computeIfAbsent(clazz.getSimpleName(), SimpleLogger::new);
}
}

public static Logger getLogger(String name){
return getInstance().getLoggerInstance(name);
}

public static Logger getLogger(Class<?> clazz){
return getInstance().getLoggerInstance(clazz);
}

public static PaladinsLogger getInstance() {
if (instance == null) {
instance = new PaladinsLogger();
return instance;
}
return instance;
}
}
Loading

0 comments on commit d5f4da7

Please sign in to comment.