Remove BotLogger

This commit is contained in:
rubenlagus 2019-07-27 13:19:54 +01:00 committed by Ruben Bermudez
parent 08bcf2bdac
commit 830b873776
18 changed files with 942 additions and 1396 deletions

View File

@ -1272,6 +1272,28 @@
<root url="jar://$MAVEN_REPOSITORY$/org/apache/httpcomponents/httpmime/4.5.9/httpmime-4.5.9-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.apache.logging.log4j:log4j-api:2.11.1">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/apache/logging/log4j/log4j-api/2.11.1/log4j-api-2.11.1.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/apache/logging/log4j/log4j-api/2.11.1/log4j-api-2.11.1-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/apache/logging/log4j/log4j-api/2.11.1/log4j-api-2.11.1-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.apache.logging.log4j:log4j-core:2.11.1">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/apache/logging/log4j/log4j-core/2.11.1/log4j-core-2.11.1.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/apache/logging/log4j/log4j-core/2.11.1/log4j-core-2.11.1-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/apache/logging/log4j/log4j-core/2.11.1/log4j-core-2.11.1-sources.jar!/" />
</SOURCES>
</library>
<library name="Maven: org.apache.shiro:shiro-cache:1.4.1">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/apache/shiro/shiro-cache/1.4.1/shiro-cache-1.4.1.jar!/" />

12
pom.xml
View File

@ -38,6 +38,7 @@
<mockito.version>3.0.0</mockito.version>
<mockitojupiter.version>2.23.4</mockitojupiter.version>
<jackson.version>2.9.9</jackson.version>
<log4j.version>2.11.1</log4j.version>
</properties>
<dependencyManagement>
@ -69,6 +70,11 @@
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
@ -93,5 +99,11 @@
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -11,7 +11,7 @@ import java.util.Set;
/**
* This interface represents the high-level methods exposed to the user when handling an {@link Update}.
* Example usage:
* <p><code>Ability.builder().action(ctx -> {db.getSet(USERS); doSomething();})* </code></p>
* <p><code>Ability.builder().action(ctx -> {db.getSet(USERS); doSomething();})</code></p>
* {@link BaseAbilityBot} contains a handle on the <code>db</code> that the user can use inside his declared abilities.
*
* @author Abbas Abou Daya

View File

@ -3,12 +3,13 @@ package org.telegram.abilitybots.api.db;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mapdb.Atomic;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.mapdb.Serializer;
import org.telegram.abilitybots.api.util.Pair;
import org.telegram.telegrambots.meta.logging.BotLogger;
import java.io.IOException;
import java.util.Collection;
@ -34,7 +35,7 @@ import static org.mapdb.Serializer.JAVA;
*/
@SuppressWarnings({"unchecked", "WeakerAccess"})
public class MapDBContext implements DBContext {
private static final String TAG = DBContext.class.getSimpleName();
private static final Logger log = LogManager.getLogger(MapDBContext.class);
private final DB db;
private final ObjectMapper objectMapper;
@ -125,7 +126,7 @@ public class MapDBContext implements DBContext {
doRecover(backupData);
return true;
} catch (IOException e) {
BotLogger.error(format("Could not recover DB data from file with String representation %s", backup), TAG, e);
log.error(format("Could not recover DB data from file with String representation %s", backup), e);
// Attempt to fallback to data snapshot before recovery
doRecover(snapshot);
return false;
@ -206,7 +207,7 @@ public class MapDBContext implements DBContext {
List entryList = (List) value;
getList(name).addAll(entryList);
} else {
BotLogger.error(TAG, format("Unable to identify object type during DB recovery, entry name: %s", name));
log.error(format("Unable to identify object type during DB recovery, entry name: %s", name));
}
});
commit();
@ -216,7 +217,7 @@ public class MapDBContext implements DBContext {
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
BotLogger.info(format("Failed to read the JSON representation of object: %s", obj), TAG, e);
log.info(format("Failed to read the JSON representation of object: %s", obj), e);
return "Error reading required data...";
}
}

View File

@ -2,8 +2,9 @@ package org.telegram.abilitybots.api.objects;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.logging.BotLogger;
import java.util.Arrays;
import java.util.List;
@ -34,7 +35,7 @@ import static org.apache.commons.lang3.StringUtils.*;
* @author Abbas Abou Daya
*/
public final class Ability {
private static final String TAG = Ability.class.getSimpleName();
private static final Logger log = LogManager.getLogger(Ability.class);
private final String name;
private final String info;
@ -63,7 +64,7 @@ public final class Ability {
this.action = checkNotNull(action, "Method action can't be empty. Please assign a function by using .action() method");
if (postAction == null)
BotLogger.info(TAG, format("No post action was detected for method with name [%s]", name));
log.info(format("No post action was detected for method with name [%s]", name));
this.flags = ofNullable(flags).map(Arrays::asList).orElse(newArrayList());

View File

@ -1,11 +1,12 @@
package org.telegram.abilitybots.api.sender;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ForceReplyKeyboard;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.logging.BotLogger;
import java.io.Serializable;
import java.util.Optional;
@ -17,7 +18,7 @@ import java.util.Optional;
* @author Abbas Abou Daya
*/
public class SilentSender {
private static final String TAG = SilentSender.class.getSimpleName();
private static final Logger log = LogManager.getLogger(SilentSender.class);
private final MessageSender sender;
@ -46,7 +47,7 @@ public class SilentSender {
try {
return Optional.ofNullable(sender.execute(method));
} catch (TelegramApiException e) {
BotLogger.error("Could not execute bot API method", TAG, e);
log.error("Could not execute bot API method", e);
return Optional.empty();
}
}
@ -55,7 +56,7 @@ public class SilentSender {
try {
return Optional.ofNullable(sender.execute(method));
} catch (TelegramApiException e) {
BotLogger.error("Could not execute bot API method", TAG, e);
log.error("Could not execute bot API method", e);
return Optional.empty();
}
}

View File

@ -11,9 +11,9 @@ import java.util.concurrent.atomic.AtomicBoolean;
* Created by Daniil Nikanov aka JetCoder
*/
@SuppressWarnings("unused")
public abstract class TimedSendLongPollingBot extends TelegramLongPollingBot
{
private static final long MANY_CHATS_SEND_INTERVAL = 33;
private static final long ONE_CHAT_SEND_INTERVAL = 1000;
private static final long CHAT_INACTIVE_INTERVAL = 1000 * 60 * 10;
private final Timer mSendTimer = new Timer(true);
@ -21,88 +21,29 @@ public abstract class TimedSendLongPollingBot extends TelegramLongPollingBot
private final ArrayList<MessageQueue> mSendQueues = new ArrayList<>();
private final AtomicBoolean mSendRequested = new AtomicBoolean(false);
private final class MessageSenderTask extends TimerTask
{
@Override
public void run()
{
//mSendRequested used for optimisation to not traverse all mMessagesMap 30 times per second all the time
if (!mSendRequested.getAndSet(false))
return;
long currentTime = System.currentTimeMillis();
mSendQueues.clear();
boolean processNext = false;
//First step - find all chats in which already allowed to send message (passed more than 1000 ms from previuos send)
Iterator<Map.Entry<Long,MessageQueue>> it = mMessagesMap.entrySet().iterator();
while (it.hasNext())
{
MessageQueue queue = it.next().getValue();
int state = queue.getCurrentState(currentTime); //Actual check here
if (state == MessageQueue.GET_MESSAGE)
{
mSendQueues.add(queue);
processNext = true;
}
else if (state == MessageQueue.WAIT)
{
processNext = true;
}
else if (state == MessageQueue.DELETE)
{
it.remove();
}
}
//If any of chats are in state WAIT or GET_MESSAGE, request another iteration
if (processNext)
mSendRequested.set(true);
//Second step - find oldest waiting queue and peek it's message
MessageQueue sendQueue = null;
long oldestPutTime = Long.MAX_VALUE;
for (int i = 0; i < mSendQueues.size(); i++)
{
MessageQueue queue = mSendQueues.get(i);
long putTime = queue.getPutTime();
if (putTime < oldestPutTime)
{
oldestPutTime = putTime;
sendQueue = queue;
}
}
if (sendQueue == null) //Possible if on first step wasn't found any chats in state GET_MESSAGE
return;
//Invoke the send callback. ChatId is passed for possible additional processing
sendMessageCallback(sendQueue.getChatId(), sendQueue.getMessage(currentTime));
}
}
private static class MessageQueue
{
public static final int EMPTY = 0; //Queue is empty
public static final int WAIT = 1; //Queue has message(s) but not yet allowed to send
public static final int DELETE = 2; //No one message of given queue was sent longer than CHAT_INACTIVE_INTERVAL, delete for optimisation
public static final int GET_MESSAGE = 3; //Queue has message(s) and ready to send
static final int EMPTY = 0; //Queue is empty
static final int WAIT = 1; //Queue has message(s) but not yet allowed to send
static final int DELETE = 2; //No one message of given queue was sent longer than CHAT_INACTIVE_INTERVAL, delete for optimisation
static final int GET_MESSAGE = 3; //Queue has message(s) and ready to send
private final ConcurrentLinkedQueue<Object> mQueue = new ConcurrentLinkedQueue<>();
private final Long mChatId;
private long mLastSendTime; //Time of last peek from queue
private volatile long mLastPutTime; //Time of last put into queue
public MessageQueue(Long chatId)
MessageQueue(Long chatId)
{
mChatId = chatId;
}
public synchronized void putMessage(Object msg)
synchronized void putMessage(Object msg)
{
mQueue.add(msg);
mLastPutTime = System.currentTimeMillis();
}
public synchronized int getCurrentState(long currentTime)
synchronized int getCurrentState(long currentTime)
{
//currentTime is passed as parameter for optimisation to do not recall currentTimeMillis() many times
long interval = currentTime - mLastSendTime;
@ -117,29 +58,23 @@ public abstract class TimedSendLongPollingBot extends TelegramLongPollingBot
return WAIT;
}
public synchronized Object getMessage(long currentTime)
synchronized Object getMessage(long currentTime)
{
mLastSendTime = currentTime;
return mQueue.poll();
}
public long getPutTime()
long getPutTime()
{
return mLastPutTime;
}
public Long getChatId()
Long getChatId()
{
return mChatId;
}
}
//Constructor
protected TimedSendLongPollingBot()
{
mSendTimer.schedule(new MessageSenderTask(), MANY_CHATS_SEND_INTERVAL, MANY_CHATS_SEND_INTERVAL);
}
//Something like destructor
public void finish()
{
@ -214,5 +149,5 @@ public abstract class TimedSendLongPollingBot extends TelegramLongPollingBot
}
}
*/
public abstract void sendMessageCallback(Long chatId, Object messageRequest);
abstract void sendMessageCallback(Long chatId, Object messageRequest);
}

View File

@ -4,8 +4,8 @@ import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import org.telegram.telegrambots.meta.logging.BotLogger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.text.MessageFormat;
import java.util.HashMap;
@ -16,6 +16,8 @@ import java.util.Map;
* @version 1.0
*/
public class ApiContext {
private static final Logger log = LogManager.getLogger(ApiContext.class);
private static final Object lock = new Object();
private static Injector INJECTOR;
private static Map<Class, Class> bindings = new HashMap<>();
@ -27,14 +29,14 @@ public class ApiContext {
public static <T, S extends T> void register(Class<T> type, Class<S> implementation) {
if (bindings.containsKey(type)) {
BotLogger.debug("ApiContext", MessageFormat.format("Class {0} already registered", type.getName()));
log.debug(MessageFormat.format("Class {0} already registered", type.getName()));
}
bindings.put(type, implementation);
}
public static <T, S extends T> void registerSingleton(Class<T> type, Class<S> implementation) {
if (singletonBindings.containsKey(type)) {
BotLogger.debug("ApiContext", MessageFormat.format("Class {0} already registered", type.getName()));
log.debug(MessageFormat.format("Class {0} already registered", type.getName()));
}
singletonBindings.put(type, implementation);
}

View File

@ -1,4 +0,0 @@
/**
* @deprecated Replaced by {@link org.telegram.telegrambots.meta.api.objects.inlinequery.result.cached}
*/
package org.telegram.telegrambots.meta.api.objects.inlinequery.result.chached;

View File

@ -18,11 +18,11 @@
package org.telegram.telegrambots.meta.exceptions;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONObject;
import org.telegram.telegrambots.meta.api.objects.ResponseParameters;
import org.telegram.telegrambots.meta.api.objects.ApiResponse;
import org.telegram.telegrambots.meta.logging.BotLogger;
import org.telegram.telegrambots.meta.api.objects.ResponseParameters;
import java.io.IOException;
@ -33,6 +33,8 @@ import java.io.IOException;
* Exception thrown when something goes wrong in the api
*/
public class TelegramApiRequestException extends TelegramApiException {
private static final Logger log = LogManager.getLogger(TelegramApiRequestException.class);
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private static final String ERRORDESCRIPTIONFIELD = "description";
private static final String ERRORCODEFIELD = "error_code";
@ -54,7 +56,7 @@ public class TelegramApiRequestException extends TelegramApiException {
try {
parameters = OBJECT_MAPPER.readValue(object.getJSONObject(PARAMETERSFIELD).toString(), ResponseParameters.class);
} catch (IOException e) {
BotLogger.severe("APIEXCEPTION", e);
log.fatal(e.getLocalizedMessage(), e);
}
}
}

View File

@ -1,171 +0,0 @@
package org.telegram.telegrambots.meta.logging;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Ruben Bermudez
* @version 2.0
* @brief Logger to file
* @date 21/01/15
*/
public class BotLogger {
private static final Logger logger = Logger.getLogger("Telegram Bots Api");
public static void setLevel(Level level) {
logger.setLevel(level);
}
public static Level getLevel() {
return logger.getLevel();
}
public static void registerLogger(Handler handler) {
logger.addHandler(handler);
}
public static void log(Level level, String tag, String msg) {
logger.log(level, String.format("%s - %s", tag, msg));
}
public static void severe(String tag, String msg) {
logger.severe(String.format("%s - %s", tag, msg));
}
public static void warn(String tag, String msg) {
warning(tag, msg);
}
public static void debug(String tag, String msg) {
fine(tag, msg);
}
public static void error(String tag, String msg) {
severe(tag, msg);
}
public static void trace(String tag, String msg) {
finer(tag, msg);
}
public static void warning(String tag, String msg) {
logger.warning(String.format("%s - %s", tag, msg));
}
public static void info(String tag, String msg) {
logger.info(String.format("%s - %s", tag, msg));
}
public static void config(String tag, String msg) {
logger.config(String.format("%s - %s", tag, msg));
}
public static void fine(String tag, String msg) {
logger.fine(String.format("%s - %s", tag, msg));
}
public static void finer(String tag, String msg) {
logger.finer(String.format("%s - %s", tag, msg));
}
public static void finest(String tag, String msg) {
logger.finest(String.format("%s - %s", tag, msg));
}
public static void log(Level level, String tag, Throwable throwable) {
logger.log(level, tag, throwable);
}
public static void log(Level level, String tag, String msg, Throwable thrown) {
logger.log(level, String.format("%s - %s", tag, msg), thrown);
}
public static void severe(String tag, Throwable throwable) {
logger.log(Level.SEVERE, tag, throwable);
}
public static void warning(String tag, Throwable throwable) {
logger.log(Level.WARNING, tag, throwable);
}
public static void info(String tag, Throwable throwable) {
logger.log(Level.INFO, tag, throwable);
}
public static void config(String tag, Throwable throwable) {
logger.log(Level.CONFIG, tag, throwable);
}
public static void fine(String tag, Throwable throwable) {
logger.log(Level.FINE, tag, throwable);
}
public static void finer(String tag, Throwable throwable) {
logger.log(Level.FINER, tag, throwable);
}
public static void finest(String tag, Throwable throwable) {
logger.log(Level.FINEST, tag, throwable);
}
public static void warn(String tag, Throwable throwable) {
warning(tag, throwable);
}
public static void debug(String tag, Throwable throwable) {
fine(tag, throwable);
}
public static void error(String tag, Throwable throwable) {
severe(tag, throwable);
}
public static void trace(String tag, Throwable throwable) {
finer(tag, throwable);
}
public static void severe(String msg, String tag, Throwable throwable) {
log(Level.SEVERE, tag, msg, throwable);
}
public static void warning(String msg, String tag, Throwable throwable) {
log(Level.WARNING, tag, msg, throwable);
}
public static void info(String msg, String tag, Throwable throwable) {
log(Level.INFO, tag, msg, throwable);
}
public static void config(String msg, String tag, Throwable throwable) {
log(Level.CONFIG, tag, msg, throwable);
}
public static void fine(String msg, String tag, Throwable throwable) {
log(Level.FINE, tag, msg, throwable);
}
public static void finer(String msg, String tag, Throwable throwable) {
log(Level.FINER, tag, msg, throwable);
}
public static void finest(String msg, String tag, Throwable throwable) {
log(Level.FINEST, tag, msg, throwable);
}
public static void warn(String msg, String tag, Throwable throwable) {
log(Level.WARNING, tag, msg, throwable);
}
public static void debug(String msg, String tag, Throwable throwable) {
log(Level.FINE, tag, msg, throwable);
}
public static void error(String msg, String tag, Throwable throwable) {
log(Level.SEVERE, tag, msg, throwable);
}
public static void trace(String msg, String tag, Throwable throwable) {
log(Level.FINER, tag, msg, throwable);
}
}

View File

@ -1,45 +0,0 @@
package org.telegram.telegrambots.meta.logging;
import java.io.IOException;
import java.util.logging.FileHandler;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Handler to use a file as logs destination with {@link BotLogger}
* @date 19 of May of 2016
*/
public class BotsFileHandler extends FileHandler {
private static final String filePattern = "./TelegramBots%g.%u.log";
public BotsFileHandler() throws IOException, SecurityException {
super(filePattern, 1024 * 1024 * 10, 50, true);
setFormatter(new FileFormatter());
}
public BotsFileHandler(int limit, int count) throws IOException, SecurityException {
super(filePattern, limit, count);
setFormatter(new FileFormatter());
}
public BotsFileHandler(String pattern) throws IOException, SecurityException {
super(pattern);
setFormatter(new FileFormatter());
}
public BotsFileHandler(String pattern, boolean append) throws IOException, SecurityException {
super(pattern, append);
setFormatter(new FileFormatter());
}
public BotsFileHandler(String pattern, int limit, int count) throws IOException, SecurityException {
super(pattern, limit, count);
setFormatter(new FileFormatter());
}
public BotsFileHandler(String pattern, int limit, int count, boolean append) throws IOException, SecurityException {
super(pattern, limit, count, append);
setFormatter(new FileFormatter());
}
}

View File

@ -1,52 +0,0 @@
package org.telegram.telegrambots.meta.logging;
import java.time.LocalDateTime;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Formatter for {@link BotsFileHandler}
* @date 19 of May of 2016
*/
class FileFormatter extends Formatter {
@Override
public String format(LogRecord record) {
final LocalDateTime currentDate = LocalDateTime.now();
final String dateForLog = dateFormatterForLogs(currentDate);
String result;
if (record.getThrown() == null) {
result = logMsgToFile(record.getLevel(), record.getMessage(), dateForLog);
} else {
result = logThrowableToFile(record.getLevel(), record.getMessage(), record.getThrown(), dateForLog);
}
return result;
}
private static String dateFormatterForLogs(LocalDateTime dateTime) {
String dateString = "[";
dateString += dateTime.getDayOfMonth() + "_";
dateString += dateTime.getMonthValue() + "_";
dateString += dateTime.getYear() + "_";
dateString += dateTime.getHour() + ":";
dateString += dateTime.getMinute() + ":";
dateString += dateTime.getSecond();
dateString += "] ";
return dateString;
}
private static String logMsgToFile(Level level, String msg, String dateForLog) {
return String.format("%s{%s} %s\n", dateForLog, level.toString(), msg);
}
private static String logThrowableToFile(Level level, String message, Throwable throwable, String dateForLog) {
String throwableLog = String.format("%s{%s} %s - %s\n", dateForLog, level.toString(), message, throwable.toString());
for (StackTraceElement element : throwable.getStackTrace()) {
throwableLog += "\tat " + element + "\n";
}
return throwableLog;
}
}

View File

@ -1,12 +1,13 @@
package org.telegram.telegrambots.starter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.generics.BotSession;
import org.telegram.telegrambots.meta.generics.LongPollingBot;
import org.telegram.telegrambots.meta.generics.WebhookBot;
import org.telegram.telegrambots.meta.logging.BotLogger;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@ -20,6 +21,7 @@ import static java.lang.String.format;
* Receives all beand which are #LongPollingBot and #WebhookBot and register them in #TelegramBotsApi.
*/
public class TelegramBotInitializer implements InitializingBean {
private static final Logger log = LogManager.getLogger(TelegramBotInitializer.class);
private final TelegramBotsApi telegramBotsApi;
private final List<LongPollingBot> longPollingBots;
@ -37,7 +39,7 @@ public class TelegramBotInitializer implements InitializingBean {
}
@Override
public void afterPropertiesSet() throws Exception {
public void afterPropertiesSet() {
try {
for (LongPollingBot bot : longPollingBots) {
BotSession session = telegramBotsApi.registerBot(bot);
@ -54,12 +56,8 @@ public class TelegramBotInitializer implements InitializingBean {
private void handleAnnotatedMethod(Object bot, Method method, BotSession session) {
try {
if (method.getParameterCount() > 1) {
BotLogger.warn(this.getClass().getSimpleName(),
format("Method %s of Type %s has too many parameters",
method.getName(),
method.getDeclaringClass().getCanonicalName()
)
);
log.warn(format("Method %s of Type %s has too many parameters",
method.getName(), method.getDeclaringClass().getCanonicalName()));
return;
}
if (method.getParameterCount() == 0) {
@ -70,18 +68,11 @@ public class TelegramBotInitializer implements InitializingBean {
method.invoke(bot, session);
return;
}
BotLogger.warn(this.getClass().getSimpleName(),
format("Method %s of Type %s has invalid parameter type",
method.getName(),
method.getDeclaringClass().getCanonicalName()
)
);
log.warn(format("Method %s of Type %s has invalid parameter type",
method.getName(), method.getDeclaringClass().getCanonicalName()));
} catch (InvocationTargetException | IllegalAccessException e) {
BotLogger.error(this.getClass().getSimpleName(),
format("Couldn't invoke Method %s of Type %s",
method.getName(), method.getDeclaringClass().getCanonicalName()
)
);
log.error(format("Couldn't invoke Method %s of Type %s",
method.getName(), method.getDeclaringClass().getCanonicalName()));
}
}

View File

@ -11,6 +11,8 @@ import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONException;
import org.telegram.telegrambots.meta.ApiConstants;
import org.telegram.telegrambots.meta.api.methods.updates.GetUpdates;
@ -19,7 +21,6 @@ import org.telegram.telegrambots.bots.DefaultBotOptions;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.facilities.TelegramHttpClientBuilder;
import org.telegram.telegrambots.meta.generics.*;
import org.telegram.telegrambots.meta.logging.BotLogger;
import java.io.IOException;
import java.io.InvalidObjectException;
@ -39,7 +40,7 @@ import static org.telegram.telegrambots.Constants.SOCKET_TIMEOUT;
* Thread to request updates with active wait
*/
public class DefaultBotSession implements BotSession {
private static final String LOGTAG = "BOTSESSION";
private static final Logger log = LogManager.getLogger(DefaultBotSession.class);
private AtomicBoolean running = new AtomicBoolean(false);
@ -170,7 +171,7 @@ public class DefaultBotSession implements BotSession {
try {
httpclient.close();
} catch (IOException e) {
BotLogger.warn(LOGTAG, e);
log.warn(e.getLocalizedMessage(), e);
}
}
super.interrupt();
@ -203,10 +204,10 @@ public class DefaultBotSession implements BotSession {
if (!running.get()) {
receivedUpdates.clear();
}
BotLogger.debug(LOGTAG, e);
log.debug(e.getLocalizedMessage(), e);
interrupt();
} catch (Exception global) {
BotLogger.severe(LOGTAG, global);
log.fatal(global.getLocalizedMessage(), global);
try {
synchronized (lock) {
lock.wait(exponentialBackOff.nextBackOffMillis());
@ -215,14 +216,14 @@ public class DefaultBotSession implements BotSession {
if (!running.get()) {
receivedUpdates.clear();
}
BotLogger.debug(LOGTAG, e);
log.debug(e.getLocalizedMessage(), e);
interrupt();
}
}
}
}
}
BotLogger.debug(LOGTAG, "Reader thread has being closed");
log.debug("Reader thread has being closed");
}
private List<Update> getUpdatesFromServer() throws IOException {
@ -248,7 +249,7 @@ public class DefaultBotSession implements BotSession {
String responseContent = EntityUtils.toString(buf, StandardCharsets.UTF_8);
if (response.getStatusLine().getStatusCode() >= 500) {
BotLogger.warn(LOGTAG, responseContent);
log.warn(responseContent);
synchronized (lock) {
lock.wait(500);
}
@ -258,15 +259,15 @@ public class DefaultBotSession implements BotSession {
exponentialBackOff.reset();
return updates;
} catch (JSONException e) {
BotLogger.severe(responseContent, LOGTAG, e);
log.error("Error deserializing update: " + responseContent, e);
}
}
} catch (SocketException | InvalidObjectException | TelegramApiRequestException e) {
BotLogger.severe(LOGTAG, e);
log.fatal(e.getLocalizedMessage(), e);
} catch (SocketTimeoutException e) {
BotLogger.fine(LOGTAG, e);
log.info(e.getLocalizedMessage(), e);
} catch (InterruptedException e) {
BotLogger.fine(LOGTAG, e);
log.info(e.getLocalizedMessage(), e);
interrupt();
}
return Collections.emptyList();
@ -305,13 +306,13 @@ public class DefaultBotSession implements BotSession {
}
callback.onUpdatesReceived(updates);
} catch (InterruptedException e) {
BotLogger.debug(LOGTAG, e);
log.debug(e.getLocalizedMessage(), e);
interrupt();
} catch (Exception e) {
BotLogger.severe(LOGTAG, e);
log.fatal(e.getLocalizedMessage(), e);
}
}
BotLogger.debug(LOGTAG, "Handler thread has being closed");
log.debug("Handler thread has being closed");
}
}
}

View File

@ -70,22 +70,22 @@ import com.google.common.base.Preconditions;
*/
public class ExponentialBackOff {
/** The default initial interval value in milliseconds (0.5 seconds). */
public static final int DEFAULT_INITIAL_INTERVAL_MILLIS = 500;
private static final int DEFAULT_INITIAL_INTERVAL_MILLIS = 500;
/**
* The default randomization factor (0.5 which results in a random period ranging between 50%
* below and 50% above the retry interval).
*/
public static final double DEFAULT_RANDOMIZATION_FACTOR = 0.5;
private static final double DEFAULT_RANDOMIZATION_FACTOR = 0.5;
/** The default multiplier value (1.5 which is 50% increase per back off). */
public static final double DEFAULT_MULTIPLIER = 1.5;
private static final double DEFAULT_MULTIPLIER = 1.5;
/** The default maximum back off time in milliseconds (15 minutes). */
public static final int DEFAULT_MAX_INTERVAL_MILLIS = 30000;
private static final int DEFAULT_MAX_INTERVAL_MILLIS = 30000;
/** The default maximum elapsed time in milliseconds (60 minutes). */
public static final int DEFAULT_MAX_ELAPSED_TIME_MILLIS = 3600000;
private static final int DEFAULT_MAX_ELAPSED_TIME_MILLIS = 3600000;
/** The current retry interval in milliseconds. */
private int currentIntervalMillis;
@ -116,7 +116,7 @@ public class ExponentialBackOff {
* The system time in nanoseconds. It is calculated when an ExponentialBackOffPolicy instance is
* created and is reset when {@link #reset()} is called.
*/
long startTimeNanos;
private long startTimeNanos;
/**
* The maximum elapsed time after instantiating {@link ExponentialBackOff} or calling
@ -139,14 +139,14 @@ public class ExponentialBackOff {
* <li>{@code maxElapsedTimeMillis} defaults in {@link #DEFAULT_MAX_ELAPSED_TIME_MILLIS}</li>
* </ul>
*/
public ExponentialBackOff() {
ExponentialBackOff() {
this(new Builder());
}
/**
* @param builder builder
*/
protected ExponentialBackOff(Builder builder) {
private ExponentialBackOff(Builder builder) {
initialIntervalMillis = builder.initialIntervalMillis;
randomizationFactor = builder.randomizationFactor;
multiplier = builder.multiplier;
@ -161,7 +161,7 @@ public class ExponentialBackOff {
}
/** Sets the interval back to the initial retry interval and restarts the timer. */
public final void reset() {
final void reset() {
currentIntervalMillis = initialIntervalMillis;
startTimeNanos = nanoTime();
}
@ -178,7 +178,7 @@ public class ExponentialBackOff {
* Subclasses may override if a different algorithm is required.
* </p>
*/
public long nextBackOffMillis() {
long nextBackOffMillis() {
// Make sure we have not gone over the maximum elapsed time.
if (getElapsedTimeMillis() > maxElapsedTimeMillis) {
return maxElapsedTimeMillis;
@ -193,7 +193,7 @@ public class ExponentialBackOff {
* Returns a random value from the interval [randomizationFactor * currentInterval,
* randomizationFactor * currentInterval].
*/
static int getRandomValueFromInterval(
private static int getRandomValueFromInterval(
double randomizationFactor, double random, int currentIntervalMillis) {
double delta = randomizationFactor * currentIntervalMillis;
double minInterval = currentIntervalMillis - delta;
@ -201,60 +201,7 @@ public class ExponentialBackOff {
// Get a random value from the range [minInterval, maxInterval].
// The formula used below has a +1 because if the minInterval is 1 and the maxInterval is 3 then
// we want a 33% chance for selecting either 1, 2 or 3.
int randomValue = (int) (minInterval + (random * (maxInterval - minInterval + 1)));
return randomValue;
}
/** Returns the initial retry interval in milliseconds. */
public final int getInitialIntervalMillis() {
return initialIntervalMillis;
}
/**
* Returns the randomization factor to use for creating a range around the retry interval.
*
* <p>
* A randomization factor of 0.5 results in a random period ranging between 50% below and 50%
* above the retry interval.
* </p>
*/
public final double getRandomizationFactor() {
return randomizationFactor;
}
/**
* Returns the current retry interval in milliseconds.
*/
public final int getCurrentIntervalMillis() {
return currentIntervalMillis;
}
/**
* Returns the value to multiply the current interval with for each retry attempt.
*/
public final double getMultiplier() {
return multiplier;
}
/**
* Returns the maximum value of the back off period in milliseconds. Once the current interval
* reaches this value it stops increasing.
*/
public final int getMaxIntervalMillis() {
return maxIntervalMillis;
}
/**
* Returns the maximum elapsed time in milliseconds.
*
* <p>
* If the time elapsed since an {@link ExponentialBackOff} instance is created goes past the
* max_elapsed_time then the method {@link #nextBackOffMillis()} starts returning
* this value. The elapsed time can be reset by calling {@link #reset()}.
* </p>
*/
public final int getMaxElapsedTimeMillis() {
return maxElapsedTimeMillis;
return (int) (minInterval + (random * (maxInterval - minInterval + 1)));
}
/**
@ -265,7 +212,7 @@ public class ExponentialBackOff {
* The elapsed time is computed using {@link System#nanoTime()}.
* </p>
*/
public final long getElapsedTimeMillis() {
private long getElapsedTimeMillis() {
return (nanoTime() - startTimeNanos) / 1000000;
}
@ -327,152 +274,12 @@ public class ExponentialBackOff {
*/
int maxElapsedTimeMillis = DEFAULT_MAX_ELAPSED_TIME_MILLIS;
public Builder() {
Builder() {
}
/** Builds a new instance of {@link ExponentialBackOff}. */
public ExponentialBackOff build() {
return new ExponentialBackOff(this);
}
/**
* Returns the initial retry interval in milliseconds. The default value is
* {@link #DEFAULT_INITIAL_INTERVAL_MILLIS}.
*/
public final int getInitialIntervalMillis() {
return initialIntervalMillis;
}
/**
* Sets the initial retry interval in milliseconds. The default value is
* {@link #DEFAULT_INITIAL_INTERVAL_MILLIS}. Must be {@code > 0}.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setInitialIntervalMillis(int initialIntervalMillis) {
this.initialIntervalMillis = initialIntervalMillis;
return this;
}
/**
* Returns the randomization factor to use for creating a range around the retry interval. The
* default value is {@link #DEFAULT_RANDOMIZATION_FACTOR}.
*
* <p>
* A randomization factor of 0.5 results in a random period ranging between 50% below and 50%
* above the retry interval.
* </p>
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public final double getRandomizationFactor() {
return randomizationFactor;
}
/**
* Sets the randomization factor to use for creating a range around the retry interval. The
* default value is {@link #DEFAULT_RANDOMIZATION_FACTOR}. Must fall in the range
* {@code 0 <= randomizationFactor < 1}.
*
* <p>
* A randomization factor of 0.5 results in a random period ranging between 50% below and 50%
* above the retry interval.
* </p>
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setRandomizationFactor(double randomizationFactor) {
this.randomizationFactor = randomizationFactor;
return this;
}
/**
* Returns the value to multiply the current interval with for each retry attempt. The default
* value is {@link #DEFAULT_MULTIPLIER}.
*/
public final double getMultiplier() {
return multiplier;
}
/**
* Sets the value to multiply the current interval with for each retry attempt. The default
* value is {@link #DEFAULT_MULTIPLIER}. Must be {@code >= 1}.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setMultiplier(double multiplier) {
this.multiplier = multiplier;
return this;
}
/**
* Returns the maximum value of the back off period in milliseconds. Once the current interval
* reaches this value it stops increasing. The default value is
* {@link #DEFAULT_MAX_INTERVAL_MILLIS}. Must be {@code >= initialInterval}.
*/
public final int getMaxIntervalMillis() {
return maxIntervalMillis;
}
/**
* Sets the maximum value of the back off period in milliseconds. Once the current interval
* reaches this value it stops increasing. The default value is
* {@link #DEFAULT_MAX_INTERVAL_MILLIS}.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setMaxIntervalMillis(int maxIntervalMillis) {
this.maxIntervalMillis = maxIntervalMillis;
return this;
}
/**
* Returns the maximum elapsed time in milliseconds. The default value is
* {@link #DEFAULT_MAX_ELAPSED_TIME_MILLIS}.
*
* <p>
* If the time elapsed since an {@link ExponentialBackOff} instance is created goes past the
* max_elapsed_time then the method {@link #nextBackOffMillis()} starts returning
* this value. The elapsed time can be reset by calling {@link #reset()}.
* </p>
*/
public final int getMaxElapsedTimeMillis() {
return maxElapsedTimeMillis;
}
/**
* Sets the maximum elapsed time in milliseconds. The default value is
* {@link #DEFAULT_MAX_ELAPSED_TIME_MILLIS}. Must be {@code > 0}.
*
* <p>
* If the time elapsed since an {@link ExponentialBackOff} instance is created goes past the
* max_elapsed_time then the method {@link #nextBackOffMillis()} starts returning
* this value. The elapsed time can be reset by calling {@link #reset()}.
* </p>
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setMaxElapsedTimeMillis(int maxElapsedTimeMillis) {
this.maxElapsedTimeMillis = maxElapsedTimeMillis;
return this;
}
}
}

View File

@ -1,12 +1,11 @@
package org.telegram.telegrambots.updatesreceivers;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
import org.telegram.telegrambots.meta.generics.WebhookBot;
import org.telegram.telegrambots.meta.logging.BotLogger;
import java.util.concurrent.ConcurrentHashMap;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
@ -16,15 +15,16 @@ import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Rest api to for webhook callback function
* @date 20 of June of 2015
* Rest api to for webhook callback function
*/
@Path("callback")
public class RestApi {
private static final Logger log = LogManager.getLogger(RestApi.class);
private final ConcurrentHashMap<String, WebhookBot> callbacks = new ConcurrentHashMap<>();
@ -50,7 +50,7 @@ public class RestApi {
}
return Response.ok(response).build();
} catch (TelegramApiValidationException e) {
BotLogger.severe("RESTAPI", e);
log.error(e.getLocalizedMessage(), e);
return Response.serverError().build();
}
}