Skip to content

Commit

Permalink
Added an ability to set callback from controller method
Browse files Browse the repository at this point in the history
  • Loading branch information
kshashov committed Jan 5, 2021
1 parent 35aa3d7 commit 30d11d7
Show file tree
Hide file tree
Showing 6 changed files with 82 additions and 28 deletions.
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
package com.github.kshashov.telegram.api;

import com.github.kshashov.telegram.api.bind.annotation.BotRequest;
import com.pengrad.telegrambot.Callback;
import com.pengrad.telegrambot.TelegramBot;
import com.pengrad.telegrambot.model.Chat;
import com.pengrad.telegrambot.model.Message;
import com.pengrad.telegrambot.model.Update;
import com.pengrad.telegrambot.model.User;
import com.pengrad.telegrambot.request.BaseRequest;
import lombok.AllArgsConstructor;
import com.pengrad.telegrambot.response.BaseResponse;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;

import javax.annotation.Nullable;
import java.util.Map;

/**
Expand All @@ -18,7 +22,7 @@
* @see BaseRequest
*/
@Getter
@AllArgsConstructor
@RequiredArgsConstructor
public class TelegramRequest {
/**
* Bot instance that received the current telegram event.
Expand Down Expand Up @@ -79,6 +83,13 @@ public class TelegramRequest {
*/
private final User user;

/**
* Callback
*/
@Nullable
@Setter
private Callback<BaseRequest, BaseResponse> callback;

@Override
public String toString() {
final StringBuilder sb = new StringBuilder("TelegramRequest{");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.github.kshashov.telegram.handler;

import com.github.kshashov.telegram.config.TelegramBotGlobalProperties;
import com.github.kshashov.telegram.handler.processor.ProcessedTelegramCallback;
import com.github.kshashov.telegram.handler.processor.RequestDispatcher;
import com.github.kshashov.telegram.handler.processor.TelegramEvent;
import com.github.kshashov.telegram.metrics.MetricsService;
Expand Down Expand Up @@ -46,8 +47,8 @@ public void processUpdates(@NotNull String token, @NotNull TelegramBot bot, @Not
try {
TelegramEvent event = new TelegramEvent(token, update, bot);

BaseRequest executionResult = botRequestDispatcher.execute(event);
if (executionResult != null) {
ProcessedTelegramCallback executionResult = botRequestDispatcher.execute(event);
if ((executionResult != null) && (executionResult.getRequest() != null)) {
// Execute telegram request from controller response
log.debug("Controller returned Telegram request {}", executionResult);
postExecute(executionResult, bot);
Expand All @@ -64,16 +65,18 @@ public void processUpdates(@NotNull String token, @NotNull TelegramBot bot, @Not
}

@SuppressWarnings("unchecked")
private void postExecute(@NotNull BaseRequest baseRequest, @NotNull TelegramBot telegramBot) {
telegramBot.execute(baseRequest, new Callback<BaseRequest, BaseResponse>() {
private void postExecute(ProcessedTelegramCallback baseRequest, @NotNull TelegramBot telegramBot) {
telegramBot.execute(baseRequest.getRequest(), new Callback<BaseRequest, BaseResponse>() {
@Override
public void onResponse(BaseRequest request, BaseResponse response) {
baseRequest.onResponse(request, response);
globalProperties.getResponseCallback().onResponse(request, response);
log.debug("{} request was successfully executed", baseRequest);
}

@Override
public void onFailure(BaseRequest request, IOException e) {
baseRequest.onFailure(request, e);
globalProperties.getResponseCallback().onFailure(request, e);
metricsService.onUpdateError();
log.error(baseRequest + " request was failed", e);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.github.kshashov.telegram.handler.processor;

import com.pengrad.telegrambot.Callback;
import com.pengrad.telegrambot.request.BaseRequest;
import com.pengrad.telegrambot.response.BaseResponse;

import javax.annotation.Nullable;
import javax.validation.constraints.NotNull;
import java.io.IOException;

/**
* Result of the Telegram request processing. Includes callback methods to handle Telegram response.
*/
public class ProcessedTelegramCallback implements Callback<BaseRequest, BaseResponse> {
private final BaseRequest request;
private final Callback<BaseRequest, BaseResponse> nestedCallback;

public ProcessedTelegramCallback(@NotNull BaseRequest request, @Nullable Callback<BaseRequest, BaseResponse> nestedCallback) {
this.request = request;
this.nestedCallback = nestedCallback;
}

public BaseRequest getRequest() {
return request;
}

@Override
public void onResponse(BaseRequest request, BaseResponse response) {
if (nestedCallback == null) return;
nestedCallback.onResponse(request, response);
}

@Override
public void onFailure(BaseRequest request, IOException e) {
if (nestedCallback == null) return;
nestedCallback.onFailure(request, e);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public RequestDispatcher(@NotNull HandlerMethodContainer handlerMethodContainer,
* @return invocation result
* @throws IllegalStateException when it failed to execute the handler method correctly
*/
public BaseRequest execute(@NotNull TelegramEvent event) throws IllegalStateException {
public ProcessedTelegramCallback execute(@NotNull TelegramEvent event) throws IllegalStateException {
TelegramSessionResolver.TelegramSessionHolder sessionHolder = null;

HandlerMethodContainer.HandlerLookupResult lookupResult = handlerMethodContainer.lookupHandlerMethod(event);
Expand All @@ -56,10 +56,22 @@ public BaseRequest execute(@NotNull TelegramEvent event) throws IllegalStateExce

// Save execution time to metrics
Timer.Context timerContext = metricsService.onMethodHandlerStarted(method);
BaseRequest result = doExecute(event, lookupResult, sessionHolder.getSession());

TelegramRequest request = new TelegramRequest(
event.getTelegramBot(),
event.getUpdate(),
event.getMessageType(),
lookupResult.getBasePattern(),
lookupResult.getTemplateVariables(),
event.getMessage(),
event.getText(),
event.getChat(),
event.getUser());

BaseRequest result = doExecute(request, lookupResult, sessionHolder.getSession());
metricsService.onUpdateSuccess(method, timerContext);

return result;
return result == null ? null : new ProcessedTelegramCallback(result, request.getCallback());
} catch (Exception ex) {
if (method != null) {
metricsService.onUpdateError(method);
Expand All @@ -71,23 +83,12 @@ public BaseRequest execute(@NotNull TelegramEvent event) throws IllegalStateExce
}
}

private BaseRequest doExecute(@NotNull TelegramEvent event, @NotNull HandlerMethodContainer.HandlerLookupResult lookupResult, @NotNull TelegramSession session) throws IllegalStateException {
TelegramRequest request = new TelegramRequest(
event.getTelegramBot(),
event.getUpdate(),
event.getMessageType(),
lookupResult.getBasePattern(),
lookupResult.getTemplateVariables(),
event.getMessage(),
event.getText(),
event.getChat(),
event.getUser());

private BaseRequest doExecute(TelegramRequest request, @NotNull HandlerMethodContainer.HandlerLookupResult lookupResult, @NotNull TelegramSession session) throws IllegalStateException {
BaseRequest result = new TelegramInvocableHandlerMethod(lookupResult.getHandlerMethod(), argumentResolver, returnValueHandler)
.invokeAndHandle(request, session);

log.info("{} request has been executed by '{}' handler method with {} result",
event.getMessageType(),
request.getMessageType(),
lookupResult.getHandlerMethod().toString(),
result == null ? "null" : result.getClass().getSimpleName());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public class TelegramInvocableHandlerMethod extends HandlerMethod {
/**
* Create an instance from a bean instance and a method.
*
* @param handlerMethod method to invoke
* @param handlerMethod method to invoke
* @param argumentResolver resolvers list to resolve arguments
* @param returnValueHandler handlers list to handle return value
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ void init() {
@Test
void execute_HandlerNotFound_ReturnNull() throws Exception {
when(handlerMethodContainer.lookupHandlerMethod(any())).thenReturn(new HandlerMethodContainer.HandlerLookupResult());
BaseRequest result = doExecute();
ProcessedTelegramCallback result = doExecute();

assertNull(result);
verify(sessionResolver).resolveTelegramSession(any());
Expand Down Expand Up @@ -83,7 +83,7 @@ void execute_HandlerReturnNull_ReturnNull() throws Exception {
new HashMap<>()
);
when(handlerMethodContainer.lookupHandlerMethod(any())).thenReturn(lookupResult);
BaseRequest result = doExecute();
ProcessedTelegramCallback result = doExecute();

assertNull(result);

Expand All @@ -99,16 +99,17 @@ void execute() throws Exception {
new HashMap<>()
);
when(handlerMethodContainer.lookupHandlerMethod(any())).thenReturn(lookupResult);
BaseRequest result = doExecute();
ProcessedTelegramCallback result = doExecute();

assertNotNull(result);
assertEquals(sendMessage, result);
assertNotNull(result.getRequest());
assertEquals(sendMessage, result.getRequest());

verify(sessionResolver).resolveTelegramSession(any());
verify(sessionHolder).releaseSessionId();
}

BaseRequest doExecute() throws Exception {
ProcessedTelegramCallback doExecute() throws Exception {
RequestDispatcher dispatcher = new RequestDispatcher(
handlerMethodContainer,
sessionResolver,
Expand Down

0 comments on commit 30d11d7

Please sign in to comment.