Skip to content

Keyboard improvements + generics #209

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 4, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion library/src/main/java/com/pengrad/telegrambot/BotUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public class BotUtils {

private BotUtils() {}

private static Gson gson = new Gson();
private static final Gson gson = new Gson();

public static Update parseUpdate(String update) {
return gson.fromJson(update, Update.class);
Expand All @@ -35,4 +35,11 @@ static byte[] getBytesFromInputStream(InputStream is) throws IOException {
return os.toByteArray();
}

public static <R> R fromJson(String jsonString, Class<R> resClass) {
return gson.fromJson(jsonString,resClass);
}

public static String toJson(Object obj) {
return gson.toJson(obj);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
* stas
* 5/3/16.
*/
public interface Callback<T extends BaseRequest, R extends BaseResponse> {
public interface Callback<T extends BaseRequest<T, R>, R extends BaseResponse> {

void onResponse(T request, R response);

Expand Down
19 changes: 9 additions & 10 deletions library/src/main/java/com/pengrad/telegrambot/TelegramBot.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,16 @@
import com.pengrad.telegrambot.request.BaseRequest;
import com.pengrad.telegrambot.request.GetUpdates;
import com.pengrad.telegrambot.response.BaseResponse;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

/**
* Stas Parshin
* 16 October 2015
Expand All @@ -38,7 +38,7 @@ public TelegramBot(String botToken) {
this.updatesHandler = builder.updatesHandler;
}

public <T extends BaseRequest, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
}

Expand All @@ -50,13 +50,12 @@ public String getFullFilePath(File file) {
return fileApi.getFullFilePath(file.filePath());
}

public byte[] getFileContent(File file) throws Exception {
public byte[] getFileContent(File file) throws IOException {
String fileUrl = getFullFilePath(file);
URLConnection connection = new URL(fileUrl).openConnection();
InputStream is = connection.getInputStream();
byte[] data = BotUtils.getBytesFromInputStream(is);
is.close();
return data;
try (InputStream is = connection.getInputStream()) {
return BotUtils.getBytesFromInputStream(is);
}
}

public void setUpdatesListener(UpdatesListener listener) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,15 @@ public interface UpdatesListener {
int CONFIRMED_UPDATES_ALL = -1;
int CONFIRMED_UPDATES_NONE = -2;

/**
* Callback handler with available updates
*
* @param updates available updates
* @return id of the last processed update which should not be re-delivered
* There are 2 convienient values:
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* There are 2 convienient values:
* There are 2 convenient values:

* @see #CONFIRMED_UPDATES_ALL
* @see #CONFIRMED_UPDATES_NONE
*/
int process(List<Update> updates);

}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,14 @@
import com.pengrad.telegrambot.Callback;
import com.pengrad.telegrambot.request.BaseRequest;
import com.pengrad.telegrambot.response.BaseResponse;
import okhttp3.*;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.io.File;
import java.io.IOException;
Expand All @@ -29,7 +36,7 @@ public TelegramBotClient(OkHttpClient client, Gson gson, String baseUrl) {
this.clientWithTimeout = client;
}

public <T extends BaseRequest, R extends BaseResponse> void send(final T request, final Callback<T, R> callback) {
public <T extends BaseRequest<T, R>, R extends BaseResponse> void send(final T request, final Callback<T, R> callback) {
OkHttpClient client = getOkHttpClient(request);
client.newCall(createRequest(request)).enqueue(new okhttp3.Callback() {
@Override
Expand Down Expand Up @@ -58,7 +65,7 @@ public void onFailure(Call call, IOException e) {
});
}

public <T extends BaseRequest, R extends BaseResponse> R send(final BaseRequest<T, R> request) {
public <T extends BaseRequest<T, R>, R extends BaseResponse> R send(final BaseRequest<T, R> request) {
try {
OkHttpClient client = getOkHttpClient(request);
Response response = client.newCall(createRequest(request)).execute();
Expand All @@ -68,7 +75,7 @@ public <T extends BaseRequest, R extends BaseResponse> R send(final BaseRequest<
}
}

private OkHttpClient getOkHttpClient(BaseRequest request) {
private OkHttpClient getOkHttpClient(BaseRequest<?, ?> request) {
int timeoutMillis = request.getTimeoutSeconds() * 1000;

if (client.readTimeoutMillis() == 0 || client.readTimeoutMillis() > timeoutMillis) return client;
Expand All @@ -78,7 +85,7 @@ private OkHttpClient getOkHttpClient(BaseRequest request) {
return clientWithTimeout;
}

private Request createRequest(BaseRequest request) {
private Request createRequest(BaseRequest<?, ?> request) {
return new Request.Builder()
.url(baseUrl + request.getMethod())
.post(createRequestBody(request))
Expand All @@ -99,17 +106,26 @@ private RequestBody createRequestBody(BaseRequest<?, ?> request) {
} else if (value instanceof File) {
builder.addFormDataPart(name, request.getFileName(), RequestBody.create(contentType, (File) value));
} else {
builder.addFormDataPart(name, String.valueOf(value));
builder.addFormDataPart(name, toParamValue(value));
}
}

return builder.build();
} else {
FormBody.Builder builder = new FormBody.Builder();
for (Map.Entry<String, Object> parameter : request.getParameters().entrySet()) {
builder.add(parameter.getKey(), String.valueOf(parameter.getValue()));
builder.add(parameter.getKey(), toParamValue(parameter.getValue()));
}
return builder.build();
}
}

private String toParamValue(Object obj) {
if (obj.getClass().isPrimitive() ||
obj.getClass().isEnum() ||
obj.getClass().getName().startsWith("java.lang")) {
return String.valueOf(obj);
}
return gson.toJson(obj);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

/**
Expand All @@ -28,7 +28,7 @@ private CheckTelegramAuth(String botToken, String authQueryParams) {
String hash = null;
long authDate = 0;
String[] params = authQueryParams.split("&");
TreeSet<String> set = new TreeSet<String>();
Set<String> set = new TreeSet<>();
for (String p : params) {
if (p.startsWith("hash=")) {
hash = p.substring(5);
Expand All @@ -41,7 +41,7 @@ private CheckTelegramAuth(String botToken, String authQueryParams) {
}
this.hash = hash;
this.authDate = authDate;
this.dataCheck = join(set, "\n");
this.dataCheck = String.join("\n", set);
this.botToken = botToken;
}

Expand Down Expand Up @@ -72,15 +72,4 @@ private static String hex(byte[] str) {
return String.format("%040x", new BigInteger(1, str));
}

private static String join(Iterable<String> elements, CharSequence separator) {
StringBuilder builder = new StringBuilder();
Iterator<String> it = elements.iterator();
if (it.hasNext()) {
builder.append(it.next());
while (it.hasNext()) {
builder.append(separator).append(it.next());
}
}
return builder.toString();
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package com.pengrad.telegrambot.model;

import com.google.gson.Gson;

import java.io.Serializable;

/**
Expand All @@ -10,7 +8,6 @@
*/
public class MaskPosition implements Serializable {
private final static long serialVersionUID = 0L;
private final static Gson gson = new Gson();

public enum Point {
forehead, eyes, mouth, chin
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package com.pengrad.telegrambot.model.request;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
* stas
Expand All @@ -10,28 +13,48 @@
public class InlineKeyboardMarkup extends Keyboard implements Serializable {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tests in ModelTest fails because this class now.
There are 2 things:

  • equalsVerifier fails, need to revert o instanceof InlineKeyboardMarkup in equals()
  • Keyboard before implemented custom toString, so testToString passed, need to generate it for this class

private final static long serialVersionUID = 0L;

private final InlineKeyboardButton[][] inline_keyboard;
private final List<List<InlineKeyboardButton>> inline_keyboard;

public InlineKeyboardMarkup(InlineKeyboardButton[]... keyboard) {
this.inline_keyboard = keyboard;
this.inline_keyboard = new ArrayList<>();
if(keyboard!=null) {
for (InlineKeyboardButton[] row : keyboard) {
addRow(row);
}
}
}

public InlineKeyboardMarkup addRow(InlineKeyboardButton... keyboard) {
this.inline_keyboard.add(Arrays.asList(keyboard));
return this;
}

public InlineKeyboardButton[][] inlineKeyboard() {
return inline_keyboard;
InlineKeyboardButton[][] res = new InlineKeyboardButton[inline_keyboard.size()][];
for (int i = 0; i < inline_keyboard.size(); i++) {
List<InlineKeyboardButton> line = inline_keyboard.get(i);
res[i] = line.toArray(new InlineKeyboardButton[]{});
}
return res;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;

InlineKeyboardMarkup that = (InlineKeyboardMarkup) o;

return Arrays.deepEquals(inline_keyboard, that.inline_keyboard);
return Objects.equals(inline_keyboard, that.inline_keyboard);
}

@Override
public int hashCode() {
return Arrays.deepHashCode(inline_keyboard);
return Objects.hash(inline_keyboard);
}

@Override
public String toString() {
return "InlineKeyboardMarkup{" +
"inline_keyboard=" + inline_keyboard +
'}';
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* stas
* 1/12/16.
*/
public abstract class InlineQueryResult<T extends InlineQueryResult> implements Serializable {
public abstract class InlineQueryResult<T extends InlineQueryResult<T>> implements Serializable {
private final static long serialVersionUID = 0L;

@SuppressWarnings("unchecked")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
* Stas Parshin
* 23 November 2017
*/
abstract public class InputMedia<T extends InputMedia> implements Serializable {
abstract public class InputMedia<T extends InputMedia<T>> implements Serializable {
private final static long serialVersionUID = 0L;

@SuppressWarnings("unchecked")
Expand All @@ -23,7 +23,7 @@ abstract public class InputMedia<T extends InputMedia> implements Serializable {
private String caption;
private String parse_mode;

transient private Map<String, Object> attachments = new HashMap<String, Object>();
transient private Map<String, Object> attachments = new HashMap<>();
transient private String filename;

InputMedia(String type, Object media) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package com.pengrad.telegrambot.model.request;

import com.google.gson.Gson;

import java.io.Serializable;

/**
Expand All @@ -10,13 +8,4 @@
*/
public abstract class Keyboard implements Serializable {
private final static long serialVersionUID = 0L;

// todo remove gson
private static Gson gson = new Gson();

@Override
public final String toString() {
return gson.toJson(this);
}

}
Loading