Java 11, initial version

This commit is contained in:
rubenlagus 2019-07-08 20:22:51 +01:00 committed by Ruben Bermudez
parent 7c11293d07
commit 679ad618b9
27 changed files with 1131 additions and 925 deletions

View File

@ -1,6 +1,10 @@
language: java language: java
jdk: jdk:
- oraclejdk8 - oraclejdk8
- oraclejdk11
- openjdk8
- openjdk11
- openjdk-ea
install: mvn install -Dgpg.skip install: mvn install -Dgpg.skip
script: mvn clean compile test script: mvn clean compile test
after_success: after_success:
@ -9,3 +13,6 @@ notifications:
webhooks: webhooks:
secure: "jC7dK/x67ONWQoeLZg4HfW0mHhcjDerJjsLLkrbcpltiqAbw2p7XfY8Pk4zHoD72a+5o6WKu5WvYvZ4OdldnjP8Y6ZUbliQ5RG3olg3gFDoe0+sc3geeb4HRYVcdI20O0z4Bup/qO0ZihxPBc0D5IpHmFxlaqlZG0WeST4CicU8PNnBh6aX9/VMrwXhkMb2vfzmjmIhMbx/uK5+93bnk/vR5Uwu00/Yd2cTAAWMaqK1MRdtR0WLbxlUNsprEfCjYiH3n9XZnlKXs6cLC8EOU436Wx7aepiAszW0wWFMe/7nVqOqztrQiKNvL0qXYwlQf0BLechJdt458EopL9QCu687TNDFYvg1yERAmCRiaayYZcX3PbUSMr6H5Q+Odntjs3XKyzfgSqqlkgf/SAND5jny1/1uteVoplZmFXuZFIiK4H8Rl2ezy1/8pnbp+JD3YEfiA2NuRjlou1BZXyMhiqqVXbrJqk/tXF6yZSkDlYJfNsWzRCGfra4B6JjEvUP927chIFm1ii3dgNstXDo1evV46+OQQO4HKvMPdtU2FPvWpPlkTxnmpZRZjB+bjmybluJdWT3E+e1C3wm7YbRe3vporhpfNPlnod6M0G10y9CKzl9Fbcku6X1FtM+IoPO/aqZ8S4/CBZoYEuR/Nk6bcvsYouxtyIl6PSuF9E8YjpJE=" secure: "jC7dK/x67ONWQoeLZg4HfW0mHhcjDerJjsLLkrbcpltiqAbw2p7XfY8Pk4zHoD72a+5o6WKu5WvYvZ4OdldnjP8Y6ZUbliQ5RG3olg3gFDoe0+sc3geeb4HRYVcdI20O0z4Bup/qO0ZihxPBc0D5IpHmFxlaqlZG0WeST4CicU8PNnBh6aX9/VMrwXhkMb2vfzmjmIhMbx/uK5+93bnk/vR5Uwu00/Yd2cTAAWMaqK1MRdtR0WLbxlUNsprEfCjYiH3n9XZnlKXs6cLC8EOU436Wx7aepiAszW0wWFMe/7nVqOqztrQiKNvL0qXYwlQf0BLechJdt458EopL9QCu687TNDFYvg1yERAmCRiaayYZcX3PbUSMr6H5Q+Odntjs3XKyzfgSqqlkgf/SAND5jny1/1uteVoplZmFXuZFIiK4H8Rl2ezy1/8pnbp+JD3YEfiA2NuRjlou1BZXyMhiqqVXbrJqk/tXF6yZSkDlYJfNsWzRCGfra4B6JjEvUP927chIFm1ii3dgNstXDo1evV46+OQQO4HKvMPdtU2FPvWpPlkTxnmpZRZjB+bjmybluJdWT3E+e1C3wm7YbRe3vporhpfNPlnod6M0G10y9CKzl9Fbcku6X1FtM+IoPO/aqZ8S4/CBZoYEuR/Nk6bcvsYouxtyIl6PSuF9E8YjpJE="
email: false email: false
matrix:
allow_failures:
- jdk: openjdk-ea

727
Bots.ipr

File diff suppressed because it is too large Load Diff

64
pom.xml
View File

@ -27,6 +27,70 @@
</licenses> </licenses>
<properties> <properties>
<java.version>11</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<maven.deploy.skip>true</maven.deploy.skip> <maven.deploy.skip>true</maven.deploy.skip>
<junit.version>5.5.0</junit.version>
<mockito.version>3.0.0</mockito.version>
<mockitojupiter.version>2.23.4</mockitojupiter.version>
<jackson.version>2.9.9</jackson.version>
</properties> </properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>${mockitojupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project> </project>

View File

@ -3,9 +3,15 @@
xmlns="http://maven.apache.org/POM/4.0.0" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.telegram</groupId> <groupId>org.telegram</groupId>
<artifactId>telegrambots-abilities</artifactId> <artifactId>Bots</artifactId>
<version>4.3.1</version> <version>4.3.1</version>
</parent>
<artifactId>telegrambots-abilities</artifactId>
<version>${project.parent.version}</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>Telegram Ability Bot</name> <name>Telegram Ability Bot</name>
@ -63,10 +69,15 @@
</distributionManagement> </distributionManagement>
<properties> <properties>
<java.version>11</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<commonslang.version>3.5</commonslang.version>
<mapdb.version>3.0.4</mapdb.version> <commonslang.version>3.9</commonslang.version>
<mapdb.version>3.0.7</mapdb.version>
</properties> </properties>
<dependencies> <dependencies>
@ -91,18 +102,6 @@
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>2.0.2-beta</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -112,10 +111,15 @@
<testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory> <testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory> <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
<plugins> <plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M3</version>
</plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId> <artifactId>maven-gpg-plugin</artifactId>
<version>1.5</version> <version>1.6</version>
<executions> <executions>
<execution> <execution>
<id>sign-artifacts</id> <id>sign-artifacts</id>
@ -129,7 +133,7 @@
<plugin> <plugin>
<groupId>org.sonatype.plugins</groupId> <groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId> <artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.3</version> <version>1.6.8</version>
<extensions>true</extensions> <extensions>true</extensions>
<configuration> <configuration>
<serverId>ossrh</serverId> <serverId>ossrh</serverId>
@ -139,7 +143,7 @@
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-clean-plugin</artifactId> <artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version> <version>3.1.0</version>
<executions> <executions>
<execution> <execution>
<id>clean-project</id> <id>clean-project</id>
@ -152,7 +156,7 @@
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-assembly-plugin</artifactId> <artifactId>maven-assembly-plugin</artifactId>
<version>2.6</version> <version>3.1.1</version>
<configuration> <configuration>
<descriptorRefs> <descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef> <descriptorRef>jar-with-dependencies</descriptorRef>
@ -171,7 +175,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId> <artifactId>maven-source-plugin</artifactId>
<version>3.0.0</version> <version>3.1.0</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
@ -183,14 +187,14 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId> <artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.3</version> <version>3.1.0</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
<goal>jar</goal> <goal>jar</goal>
</goals> </goals>
<configuration> <configuration>
<additionalparam>-Xdoclint:none</additionalparam> <doclint>none</doclint>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
@ -198,7 +202,7 @@
<plugin> <plugin>
<groupId>org.jacoco</groupId> <groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId> <artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.7.201606060606</version> <version>0.8.4</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
@ -217,7 +221,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId> <artifactId>maven-enforcer-plugin</artifactId>
<version>1.4.1</version> <version>3.0.0-M2</version>
<executions> <executions>
<execution> <execution>
<id>enforce-versions</id> <id>enforce-versions</id>
@ -235,7 +239,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId> <artifactId>maven-dependency-plugin</artifactId>
<version>2.4</version> <version>3.1.1</version>
<executions> <executions>
<execution> <execution>
<id>copy</id> <id>copy</id>
@ -249,9 +253,10 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration> <configuration>
<source>1.8</source> <source>${java.version}</source>
<target>1.8</target> <target>${java.version}</target>
<encoding>UTF-8</encoding> <encoding>UTF-8</encoding>
</configuration> </configuration>
</plugin> </plugin>

View File

@ -53,7 +53,6 @@ import static java.util.Optional.ofNullable;
import static java.util.regex.Pattern.CASE_INSENSITIVE; import static java.util.regex.Pattern.CASE_INSENSITIVE;
import static java.util.regex.Pattern.compile; import static java.util.regex.Pattern.compile;
import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.joining;
import static jersey.repackaged.com.google.common.base.Throwables.propagate;
import static org.apache.commons.lang3.StringUtils.isEmpty; import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.telegram.abilitybots.api.objects.Ability.builder; import static org.telegram.abilitybots.api.objects.Ability.builder;
import static org.telegram.abilitybots.api.objects.Flag.*; import static org.telegram.abilitybots.api.objects.Flag.*;
@ -281,7 +280,7 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
return getUser(username).getId(); return getUser(username).getId();
} catch (IllegalStateException ex) { } catch (IllegalStateException ex) {
silent.send(getLocalizedMessage(USER_NOT_FOUND, ctx.user().getLanguageCode(), username), ctx.chatId()); silent.send(getLocalizedMessage(USER_NOT_FOUND, ctx.user().getLanguageCode(), username), ctx.chatId());
throw propagate(ex); throw ex;
} }
} }
@ -308,11 +307,11 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
.privacy(CREATOR) .privacy(CREATOR)
.input(0) .input(0)
.action(ctx -> { .action(ctx -> {
String commands = abilities.entrySet().stream() String commands = abilities.values().stream()
.filter(entry -> nonNull(entry.getValue().info())) .filter(ability -> nonNull(ability.info()))
.map(entry -> { .map(ability -> {
String name = entry.getValue().name(); String name = ability.name();
String info = entry.getValue().info(); String info = ability.info();
return format("%s - %s", name, info); return format("%s - %s", name, info);
}) })
.sorted() .sorted()
@ -350,14 +349,14 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
.action(ctx -> { .action(ctx -> {
Privacy privacy = getPrivacy(ctx.update(), ctx.user().getId()); Privacy privacy = getPrivacy(ctx.update(), ctx.user().getId());
ListMultimap<Privacy, String> abilitiesPerPrivacy = abilities.entrySet().stream() ListMultimap<Privacy, String> abilitiesPerPrivacy = abilities.values().stream()
.map(entry -> { .map(ability -> {
String name = entry.getValue().name(); String name = ability.name();
String info = entry.getValue().info(); String info = ability.info();
if (!isEmpty(info)) if (!isEmpty(info))
return Pair.of(entry.getValue().privacy(), format("/%s - %s", name, info)); return Pair.of(ability.privacy(), format("/%s - %s", name, info));
return Pair.of(entry.getValue().privacy(), format("/%s", name)); return Pair.of(ability.privacy(), format("/%s", name));
}) })
.sorted(comparing(Pair::b)) .sorted(comparing(Pair::b))
.collect(() -> hashKeys().arrayListValues().build(), .collect(() -> hashKeys().arrayListValues().build(),
@ -652,7 +651,7 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
.build(); .build();
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
BotLogger.error(TAG, "Duplicate names found while registering abilities. Make sure that the abilities declared don't clash with the reserved ones.", e); BotLogger.error(TAG, "Duplicate names found while registering abilities. Make sure that the abilities declared don't clash with the reserved ones.", e);
throw propagate(e); throw new RuntimeException(e);
} }
} }
@ -676,7 +675,7 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
return (AbilityExtension) method.invoke(obj); return (AbilityExtension) method.invoke(obj);
} catch (IllegalAccessException | InvocationTargetException e) { } catch (IllegalAccessException | InvocationTargetException e) {
BotLogger.error("Could not add ability extension", TAG, e); BotLogger.error("Could not add ability extension", TAG, e);
throw propagate(e); throw new RuntimeException(e);
} }
}; };
} }
@ -693,7 +692,7 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
return (Ability) method.invoke(obj); return (Ability) method.invoke(obj);
} catch (IllegalAccessException | InvocationTargetException e) { } catch (IllegalAccessException | InvocationTargetException e) {
BotLogger.error("Could not add ability", TAG, e); BotLogger.error("Could not add ability", TAG, e);
throw propagate(e); throw new RuntimeException(e);
} }
}; };
} }
@ -710,7 +709,7 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability
return (Reply) method.invoke(obj); return (Reply) method.invoke(obj);
} catch (IllegalAccessException | InvocationTargetException e) { } catch (IllegalAccessException | InvocationTargetException e) {
BotLogger.error("Could not add reply", TAG, e); BotLogger.error("Could not add reply", TAG, e);
throw propagate(e); throw new RuntimeException(e);
} }
}; };
} }

View File

@ -11,17 +11,20 @@ import org.telegram.abilitybots.api.util.Pair;
import org.telegram.telegrambots.meta.logging.BotLogger; import org.telegram.telegrambots.meta.logging.BotLogger;
import java.io.IOException; import java.io.IOException;
import java.util.*; import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringJoiner;
import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Maps.newHashMap;
import static com.google.common.collect.Sets.newHashSet; import static com.google.common.collect.Sets.newHashSet;
import static java.lang.String.format; import static java.lang.String.format;
import static java.util.Objects.isNull; import static java.util.Objects.isNull;
import static java.util.stream.Collectors.toMap; import static java.util.stream.Collectors.toMap;
import static java.util.stream.StreamSupport.stream; import static java.util.stream.StreamSupport.stream;
import static org.mapdb.Serializer.JAVA; import static org.mapdb.Serializer.JAVA;
import static org.telegram.abilitybots.api.bot.BaseAbilityBot.USERS;
/** /**
* An implementation of {@link DBContext} that relies on a {@link DB}. * An implementation of {@link DBContext} that relies on a {@link DB}.
@ -71,7 +74,6 @@ public class MapDBContext implements DBContext {
.fileDB(name) .fileDB(name)
.fileMmapEnableIfSupported() .fileMmapEnableIfSupported()
.closeOnJvmShutdown() .closeOnJvmShutdown()
.cleanerHackEnable()
.transactionEnable() .transactionEnable()
.fileDeleteAfterClose() .fileDeleteAfterClose()
.make(); .make();

View File

@ -1,8 +1,8 @@
package org.telegram.abilitybots.api.bot; package org.telegram.abilitybots.api.bot;
import org.junit.After; import org.junit.jupiter.api.AfterEach;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.telegram.abilitybots.api.db.DBContext; import org.telegram.abilitybots.api.db.DBContext;
import org.telegram.abilitybots.api.objects.MessageContext; import org.telegram.abilitybots.api.objects.MessageContext;
import org.telegram.abilitybots.api.sender.MessageSender; import org.telegram.abilitybots.api.sender.MessageSender;
@ -18,7 +18,7 @@ import static org.mockito.internal.verification.VerificationModeFactory.times;
import static org.telegram.abilitybots.api.bot.AbilityBotTest.mockContext; import static org.telegram.abilitybots.api.bot.AbilityBotTest.mockContext;
import static org.telegram.abilitybots.api.db.MapDBContext.offlineInstance; import static org.telegram.abilitybots.api.db.MapDBContext.offlineInstance;
public class AbilityBotI18nTest { class AbilityBotI18nTest {
private static final User NO_LANGUAGE_USER = new User(1, "first", false, "last", "username", null); private static final User NO_LANGUAGE_USER = new User(1, "first", false, "last", "username", null);
private static final User ITALIAN_USER = new User(2, "first", false, "last", "username", "it-IT"); private static final User ITALIAN_USER = new User(2, "first", false, "last", "username", "it-IT");
@ -28,8 +28,8 @@ public class AbilityBotI18nTest {
private MessageSender sender; private MessageSender sender;
private SilentSender silent; private SilentSender silent;
@Before @BeforeEach
public void setUp() { void setUp() {
db = offlineInstance("db"); db = offlineInstance("db");
bot = new NoPublicCommandsBot(EMPTY, EMPTY, db); bot = new NoPublicCommandsBot(EMPTY, EMPTY, db);
@ -38,11 +38,16 @@ public class AbilityBotI18nTest {
bot.sender = sender; bot.sender = sender;
bot.silent = silent; bot.silent = silent;
}
@AfterEach
void tearDown() throws IOException {
db.clear();
db.close();
} }
@Test @Test
public void missingPublicCommandsLocalizedInEnglishByDefault() { void missingPublicCommandsLocalizedInEnglishByDefault() {
MessageContext context = mockContext(NO_LANGUAGE_USER); MessageContext context = mockContext(NO_LANGUAGE_USER);
bot.reportCommands().action().accept(context); bot.reportCommands().action().accept(context);
@ -52,7 +57,7 @@ public class AbilityBotI18nTest {
} }
@Test @Test
public void missingPublicCommandsLocalizedInItalian() { void missingPublicCommandsLocalizedInItalian() {
MessageContext context = mockContext(ITALIAN_USER); MessageContext context = mockContext(ITALIAN_USER);
bot.reportCommands().action().accept(context); bot.reportCommands().action().accept(context);
@ -61,15 +66,9 @@ public class AbilityBotI18nTest {
.send("Non sono presenti comandi disponibile.", ITALIAN_USER.getId()); .send("Non sono presenti comandi disponibile.", ITALIAN_USER.getId());
} }
@After
public void tearDown() throws IOException {
db.clear();
db.close();
}
public static class NoPublicCommandsBot extends AbilityBot { public static class NoPublicCommandsBot extends AbilityBot {
protected NoPublicCommandsBot(String botToken, String botUsername, DBContext db) { NoPublicCommandsBot(String botToken, String botUsername, DBContext db) {
super(botToken, botUsername, db); super(botToken, botUsername, db);
} }

View File

@ -3,9 +3,10 @@ package org.telegram.abilitybots.api.bot;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.io.Files; import com.google.common.io.Files;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.junit.After; import org.junit.jupiter.api.AfterEach;
import org.junit.Before; import org.junit.jupiter.api.Assertions;
import org.junit.Test; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.telegram.abilitybots.api.db.DBContext; import org.telegram.abilitybots.api.db.DBContext;
import org.telegram.abilitybots.api.objects.*; import org.telegram.abilitybots.api.objects.*;
import org.telegram.abilitybots.api.sender.MessageSender; import org.telegram.abilitybots.api.sender.MessageSender;
@ -13,7 +14,12 @@ import org.telegram.abilitybots.api.sender.SilentSender;
import org.telegram.abilitybots.api.util.Pair; import org.telegram.abilitybots.api.util.Pair;
import org.telegram.abilitybots.api.util.Trio; import org.telegram.abilitybots.api.util.Trio;
import org.telegram.telegrambots.meta.api.methods.groupadministration.GetChatAdministrators; import org.telegram.telegrambots.meta.api.methods.groupadministration.GetChatAdministrators;
import org.telegram.telegrambots.meta.api.objects.*; import org.telegram.telegrambots.meta.api.objects.ChatMember;
import org.telegram.telegrambots.meta.api.objects.Document;
import org.telegram.telegrambots.meta.api.objects.File;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.User;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import java.io.BufferedWriter; import java.io.BufferedWriter;
@ -32,9 +38,13 @@ import static java.util.Optional.empty;
import static org.apache.commons.io.FileUtils.deleteQuietly; import static org.apache.commons.io.FileUtils.deleteQuietly;
import static org.apache.commons.lang3.ArrayUtils.addAll; import static org.apache.commons.lang3.ArrayUtils.addAll;
import static org.apache.commons.lang3.StringUtils.EMPTY; import static org.apache.commons.lang3.StringUtils.EMPTY;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Matchers.any; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.Mockito.*; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.internal.verification.VerificationModeFactory.times; import static org.mockito.internal.verification.VerificationModeFactory.times;
import static org.telegram.abilitybots.api.bot.DefaultBot.getDefaultBuilder; import static org.telegram.abilitybots.api.bot.DefaultBot.getDefaultBuilder;
import static org.telegram.abilitybots.api.db.MapDBContext.offlineInstance; import static org.telegram.abilitybots.api.db.MapDBContext.offlineInstance;
@ -62,8 +72,8 @@ public class AbilityBotTest {
private MessageSender sender; private MessageSender sender;
private SilentSender silent; private SilentSender silent;
@Before @BeforeEach
public void setUp() { void setUp() {
db = offlineInstance("db"); db = offlineInstance("db");
bot = new DefaultBot(EMPTY, EMPTY, db); bot = new DefaultBot(EMPTY, EMPTY, db);
@ -74,8 +84,14 @@ public class AbilityBotTest {
bot.silent = silent; bot.silent = silent;
} }
@AfterEach
void tearDown() throws IOException {
db.clear();
db.close();
}
@Test @Test
public void sendsPrivacyViolation() { void sendsPrivacyViolation() {
Update update = mockFullUpdate(USER, "/admin"); Update update = mockFullUpdate(USER, "/admin");
bot.onUpdateReceived(update); bot.onUpdateReceived(update);
@ -84,7 +100,7 @@ public class AbilityBotTest {
} }
@Test @Test
public void sendsLocalityViolation() { void sendsLocalityViolation() {
Update update = mockFullUpdate(USER, "/group"); Update update = mockFullUpdate(USER, "/group");
bot.onUpdateReceived(update); bot.onUpdateReceived(update);
@ -94,7 +110,7 @@ public class AbilityBotTest {
} }
@Test @Test
public void sendsInputArgsViolation() { void sendsInputArgsViolation() {
Update update = mockFullUpdate(USER, "/count 1 2 3"); Update update = mockFullUpdate(USER, "/count 1 2 3");
bot.onUpdateReceived(update); bot.onUpdateReceived(update);
@ -103,7 +119,7 @@ public class AbilityBotTest {
} }
@Test @Test
public void canProcessRepliesIfSatisfyRequirements() { void canProcessRepliesIfSatisfyRequirements() {
Update update = mockFullUpdate(USER, "must reply"); Update update = mockFullUpdate(USER, "must reply");
// False means the update was not pushed down the stream since it has been consumed by the reply // False means the update was not pushed down the stream since it has been consumed by the reply
@ -112,7 +128,7 @@ public class AbilityBotTest {
} }
@Test @Test
public void canBackupDB() throws TelegramApiException { void canBackupDB() throws TelegramApiException {
MessageContext context = defaultContext(); MessageContext context = defaultContext();
bot.backupDB().action().accept(context); bot.backupDB().action().accept(context);
@ -122,7 +138,7 @@ public class AbilityBotTest {
} }
@Test @Test
public void canRecoverDB() throws TelegramApiException, IOException { void canRecoverDB() throws TelegramApiException, IOException {
Update update = mockBackupUpdate(); Update update = mockBackupUpdate();
Object backup = getDbBackup(); Object backup = getDbBackup();
java.io.File backupFile = createBackupFile(backup); java.io.File backupFile = createBackupFile(backup);
@ -131,12 +147,12 @@ public class AbilityBotTest {
bot.recoverDB().replies().get(0).actOn(update); bot.recoverDB().replies().get(0).actOn(update);
verify(silent, times(1)).send(RECOVER_SUCCESS, GROUP_ID); verify(silent, times(1)).send(RECOVER_SUCCESS, GROUP_ID);
assertEquals("Bot recovered but the DB is still not in sync", db.getSet(TEST), newHashSet(TEST)); assertEquals(db.getSet(TEST), newHashSet(TEST), "Bot recovered but the DB is still not in sync");
assertTrue("Could not delete backup file", backupFile.delete()); assertTrue(backupFile.delete(), "Could not delete backup file");
} }
@Test @Test
public void canFilterOutReplies() { void canFilterOutReplies() {
Update update = mock(Update.class); Update update = mock(Update.class);
when(update.hasMessage()).thenReturn(false); when(update.hasMessage()).thenReturn(false);
@ -144,7 +160,7 @@ public class AbilityBotTest {
} }
@Test @Test
public void canDemote() { void canDemote() {
addUsers(USER); addUsers(USER);
bot.admins().add(USER.getId()); bot.admins().add(USER.getId());
@ -154,11 +170,11 @@ public class AbilityBotTest {
Set<Integer> actual = bot.admins(); Set<Integer> actual = bot.admins();
Set<Integer> expected = emptySet(); Set<Integer> expected = emptySet();
assertEquals("Could not sudont super-admin", expected, actual); assertEquals(expected, actual, "Could not sudont super-admin");
} }
@Test @Test
public void canPromote() { void canPromote() {
addUsers(USER); addUsers(USER);
MessageContext context = defaultContext(); MessageContext context = defaultContext();
@ -167,11 +183,11 @@ public class AbilityBotTest {
Set<Integer> actual = bot.admins(); Set<Integer> actual = bot.admins();
Set<Integer> expected = newHashSet(USER.getId()); Set<Integer> expected = newHashSet(USER.getId());
assertEquals("Could not sudo user", expected, actual); assertEquals(expected, actual, "Could not sudo user");
} }
@Test @Test
public void canBanUser() { void canBanUser() {
addUsers(USER); addUsers(USER);
MessageContext context = defaultContext(); MessageContext context = defaultContext();
@ -179,11 +195,11 @@ public class AbilityBotTest {
Set<Integer> actual = bot.blacklist(); Set<Integer> actual = bot.blacklist();
Set<Integer> expected = newHashSet(USER.getId()); Set<Integer> expected = newHashSet(USER.getId());
assertEquals("The ban was not emplaced", expected, actual); assertEquals(expected, actual, "The ban was not emplaced");
} }
@Test @Test
public void canUnbanUser() { void canUnbanUser() {
addUsers(USER); addUsers(USER);
bot.blacklist().add(USER.getId()); bot.blacklist().add(USER.getId());
@ -193,7 +209,7 @@ public class AbilityBotTest {
Set<Integer> actual = bot.blacklist(); Set<Integer> actual = bot.blacklist();
Set<Integer> expected = newHashSet(); Set<Integer> expected = newHashSet();
assertEquals("The ban was not lifted", expected, actual); assertEquals(expected, actual, "The ban was not lifted");
} }
@NotNull @NotNull
@ -202,7 +218,7 @@ public class AbilityBotTest {
} }
@Test @Test
public void cannotBanCreator() { void cannotBanCreator() {
addUsers(USER, CREATOR); addUsers(USER, CREATOR);
MessageContext context = mockContext(USER, GROUP_ID, CREATOR.getUserName()); MessageContext context = mockContext(USER, GROUP_ID, CREATOR.getUserName());
@ -210,7 +226,7 @@ public class AbilityBotTest {
Set<Integer> actual = bot.blacklist(); Set<Integer> actual = bot.blacklist();
Set<Integer> expected = newHashSet(USER.getId()); Set<Integer> expected = newHashSet(USER.getId());
assertEquals("Impostor was not added to the blacklist", expected, actual); assertEquals(expected, actual, "Impostor was not added to the blacklist");
} }
private void addUsers(User... users) { private void addUsers(User... users) {
@ -221,18 +237,18 @@ public class AbilityBotTest {
} }
@Test @Test
public void creatorCanClaimBot() { void creatorCanClaimBot() {
MessageContext context = mockContext(CREATOR, GROUP_ID); MessageContext context = mockContext(CREATOR, GROUP_ID);
bot.claimCreator().action().accept(context); bot.claimCreator().action().accept(context);
Set<Integer> actual = bot.admins(); Set<Integer> actual = bot.admins();
Set<Integer> expected = newHashSet(CREATOR.getId()); Set<Integer> expected = newHashSet(CREATOR.getId());
assertEquals("Creator was not properly added to the super admins set", expected, actual); assertEquals(expected, actual, "Creator was not properly added to the super admins set");
} }
@Test @Test
public void bannedCreatorPassesBlacklistCheck() { void bannedCreatorPassesBlacklistCheck() {
bot.blacklist().add(CREATOR.getId()); bot.blacklist().add(CREATOR.getId());
Update update = mock(Update.class); Update update = mock(Update.class);
Message message = mock(Message.class); Message message = mock(Message.class);
@ -241,11 +257,11 @@ public class AbilityBotTest {
mockUser(update, message, user); mockUser(update, message, user);
boolean notBanned = bot.checkBlacklist(update); boolean notBanned = bot.checkBlacklist(update);
assertTrue("Creator is banned", notBanned); assertTrue(notBanned, "Creator is banned");
} }
@Test @Test
public void canAddUser() { void canAddUser() {
Update update = mock(Update.class); Update update = mock(Update.class);
Message message = mock(Message.class); Message message = mock(Message.class);
@ -255,12 +271,12 @@ public class AbilityBotTest {
Map<String, Integer> expectedUserIds = ImmutableMap.of(USER.getUserName(), USER.getId()); Map<String, Integer> expectedUserIds = ImmutableMap.of(USER.getUserName(), USER.getId());
Map<Integer, User> expectedUsers = ImmutableMap.of(USER.getId(), USER); Map<Integer, User> expectedUsers = ImmutableMap.of(USER.getId(), USER);
assertEquals("User was not added", expectedUserIds, bot.userIds()); assertEquals(expectedUserIds, bot.userIds(), "User was not added");
assertEquals("User was not added", expectedUsers, bot.users()); assertEquals(expectedUsers, bot.users(), "User was not added");
} }
@Test @Test
public void canEditUser() { void canEditUser() {
addUsers(USER); addUsers(USER);
Update update = mock(Update.class); Update update = mock(Update.class);
Message message = mock(Message.class); Message message = mock(Message.class);
@ -277,22 +293,22 @@ public class AbilityBotTest {
Map<String, Integer> expectedUserIds = ImmutableMap.of(changedUser.getUserName(), changedUser.getId()); Map<String, Integer> expectedUserIds = ImmutableMap.of(changedUser.getUserName(), changedUser.getId());
Map<Integer, User> expectedUsers = ImmutableMap.of(changedUser.getId(), changedUser); Map<Integer, User> expectedUsers = ImmutableMap.of(changedUser.getId(), changedUser);
assertEquals("User was not properly edited", bot.userIds(), expectedUserIds); assertEquals(bot.userIds(), expectedUserIds, "User was not properly edited");
assertEquals("User was not properly edited", expectedUsers, expectedUsers); assertEquals(expectedUsers, expectedUsers, "User was not properly edited");
} }
@Test @Test
public void canValidateAbility() { void canValidateAbility() {
Trio<Update, Ability, String[]> invalidPair = Trio.of(null, null, null); Trio<Update, Ability, String[]> invalidPair = Trio.of(null, null, null);
Ability validAbility = getDefaultBuilder().build(); Ability validAbility = getDefaultBuilder().build();
Trio<Update, Ability, String[]> validPair = Trio.of(null, validAbility, null); Trio<Update, Ability, String[]> validPair = Trio.of(null, validAbility, null);
assertFalse("Bot can't validate ability properly", bot.validateAbility(invalidPair)); assertFalse(bot.validateAbility(invalidPair), "Bot can't validate ability properly");
assertTrue("Bot can't validate ability properly", bot.validateAbility(validPair)); assertTrue(bot.validateAbility(validPair), "Bot can't validate ability properly");
} }
@Test @Test
public void canCheckInput() { void canCheckInput() {
Update update = mockFullUpdate(USER, "/something"); Update update = mockFullUpdate(USER, "/something");
Ability abilityWithOneInput = getDefaultBuilder() Ability abilityWithOneInput = getDefaultBuilder()
.build(); .build();
@ -303,19 +319,19 @@ public class AbilityBotTest {
Trio<Update, Ability, String[]> trioOneArg = Trio.of(update, abilityWithOneInput, TEXT); Trio<Update, Ability, String[]> trioOneArg = Trio.of(update, abilityWithOneInput, TEXT);
Trio<Update, Ability, String[]> trioZeroArg = Trio.of(update, abilityWithZeroInput, TEXT); Trio<Update, Ability, String[]> trioZeroArg = Trio.of(update, abilityWithZeroInput, TEXT);
assertTrue("Unexpected result when applying token filter", bot.checkInput(trioOneArg)); assertTrue(bot.checkInput(trioOneArg), "Unexpected result when applying token filter");
trioOneArg = Trio.of(update, abilityWithOneInput, addAll(TEXT, TEXT)); trioOneArg = Trio.of(update, abilityWithOneInput, addAll(TEXT, TEXT));
assertFalse("Unexpected result when applying token filter", bot.checkInput(trioOneArg)); assertFalse(bot.checkInput(trioOneArg), "Unexpected result when applying token filter");
assertTrue("Unexpected result when applying token filter", bot.checkInput(trioZeroArg)); assertTrue(bot.checkInput(trioZeroArg), "Unexpected result when applying token filter");
trioZeroArg = Trio.of(update, abilityWithZeroInput, EMPTY_ARRAY); trioZeroArg = Trio.of(update, abilityWithZeroInput, EMPTY_ARRAY);
assertTrue("Unexpected result when applying token filter", bot.checkInput(trioZeroArg)); assertTrue(bot.checkInput(trioZeroArg), "Unexpected result when applying token filter");
} }
@Test @Test
public void canCheckPrivacy() { void canCheckPrivacy() {
Update update = mock(Update.class); Update update = mock(Update.class);
Message message = mock(Message.class); Message message = mock(Message.class);
User user = mock(User.class); User user = mock(User.class);
@ -331,14 +347,14 @@ public class AbilityBotTest {
mockUser(update, message, user); mockUser(update, message, user);
assertTrue("Unexpected result when checking for privacy", bot.checkPrivacy(publicTrio)); assertTrue(bot.checkPrivacy(publicTrio), "Unexpected result when checking for privacy");
assertFalse("Unexpected result when checking for privacy", bot.checkPrivacy(groupAdminTrio)); assertFalse(bot.checkPrivacy(groupAdminTrio), "Unexpected result when checking for privacy");
assertFalse("Unexpected result when checking for privacy", bot.checkPrivacy(adminTrio)); assertFalse(bot.checkPrivacy(adminTrio), "Unexpected result when checking for privacy");
assertFalse("Unexpected result when checking for privacy", bot.checkPrivacy(creatorTrio)); assertFalse(bot.checkPrivacy(creatorTrio), "Unexpected result when checking for privacy");
} }
@Test @Test
public void canValidateGroupAdminPrivacy() { void canValidateGroupAdminPrivacy() {
Update update = mock(Update.class); Update update = mock(Update.class);
Message message = mock(Message.class); Message message = mock(Message.class);
User user = mock(User.class); User user = mock(User.class);
@ -355,11 +371,11 @@ public class AbilityBotTest {
when(silent.execute(any(GetChatAdministrators.class))).thenReturn(Optional.of(newArrayList(member))); when(silent.execute(any(GetChatAdministrators.class))).thenReturn(Optional.of(newArrayList(member)));
assertTrue("Unexpected result when checking for privacy", bot.checkPrivacy(groupAdminTrio)); assertTrue(bot.checkPrivacy(groupAdminTrio), "Unexpected result when checking for privacy");
} }
@Test @Test
public void canRestrictNormalUsersFromGroupAdminAbilities() { void canRestrictNormalUsersFromGroupAdminAbilities() {
Update update = mock(Update.class); Update update = mock(Update.class);
Message message = mock(Message.class); Message message = mock(Message.class);
User user = mock(User.class); User user = mock(User.class);
@ -372,11 +388,11 @@ public class AbilityBotTest {
when(silent.execute(any(GetChatAdministrators.class))).thenReturn(empty()); when(silent.execute(any(GetChatAdministrators.class))).thenReturn(empty());
assertFalse("Unexpected result when checking for privacy", bot.checkPrivacy(groupAdminTrio)); assertFalse(bot.checkPrivacy(groupAdminTrio), "Unexpected result when checking for privacy");
} }
@Test @Test
public void canBlockAdminsFromCreatorAbilities() { void canBlockAdminsFromCreatorAbilities() {
Update update = mock(Update.class); Update update = mock(Update.class);
Message message = mock(Message.class); Message message = mock(Message.class);
User user = mock(User.class); User user = mock(User.class);
@ -387,11 +403,11 @@ public class AbilityBotTest {
bot.admins().add(USER.getId()); bot.admins().add(USER.getId());
mockUser(update, message, user); mockUser(update, message, user);
assertFalse("Unexpected result when checking for privacy", bot.checkPrivacy(creatorTrio)); assertFalse(bot.checkPrivacy(creatorTrio), "Unexpected result when checking for privacy");
} }
@Test @Test
public void canCheckLocality() { void canCheckLocality() {
Update update = mock(Update.class); Update update = mock(Update.class);
Message message = mock(Message.class); Message message = mock(Message.class);
User user = mock(User.class); User user = mock(User.class);
@ -406,13 +422,13 @@ public class AbilityBotTest {
mockUser(update, message, user); mockUser(update, message, user);
when(message.isUserMessage()).thenReturn(true); when(message.isUserMessage()).thenReturn(true);
assertTrue("Unexpected result when checking for locality", bot.checkLocality(publicTrio)); assertTrue(bot.checkLocality(publicTrio), "Unexpected result when checking for locality");
assertTrue("Unexpected result when checking for locality", bot.checkLocality(userTrio)); assertTrue(bot.checkLocality(userTrio), "Unexpected result when checking for locality");
assertFalse("Unexpected result when checking for locality", bot.checkLocality(groupTrio)); assertFalse(bot.checkLocality(groupTrio), "Unexpected result when checking for locality");
} }
@Test @Test
public void canRetrieveContext() { void canRetrieveContext() {
Update update = mock(Update.class); Update update = mock(Update.class);
Message message = mock(Message.class); Message message = mock(Message.class);
Ability ability = getDefaultBuilder().build(); Ability ability = getDefaultBuilder().build();
@ -424,17 +440,17 @@ public class AbilityBotTest {
Pair<MessageContext, Ability> actualPair = bot.getContext(trio); Pair<MessageContext, Ability> actualPair = bot.getContext(trio);
Pair<MessageContext, Ability> expectedPair = Pair.of(newContext(update, USER, GROUP_ID, TEXT), ability); Pair<MessageContext, Ability> expectedPair = Pair.of(newContext(update, USER, GROUP_ID, TEXT), ability);
assertEquals("Unexpected result when fetching for context", expectedPair, actualPair); assertEquals(expectedPair, actualPair, "Unexpected result when fetching for context");
} }
@Test @Test
public void defaultGlobalFlagIsTrue() { void defaultGlobalFlagIsTrue() {
Update update = mock(Update.class); Update update = mock(Update.class);
assertTrue("Unexpected result when checking for the default global flags", bot.checkGlobalFlags(update)); assertTrue(bot.checkGlobalFlags(update), "Unexpected result when checking for the default global flags");
} }
@Test(expected = ArithmeticException.class) @Test
public void canConsumeUpdate() { void canConsumeUpdate() {
Ability ability = getDefaultBuilder() Ability ability = getDefaultBuilder()
.action((context) -> { .action((context) -> {
int x = 1 / 0; int x = 1 / 0;
@ -443,11 +459,13 @@ public class AbilityBotTest {
Pair<MessageContext, Ability> pair = Pair.of(context, ability); Pair<MessageContext, Ability> pair = Pair.of(context, ability);
Assertions.assertThrows(ArithmeticException.class, () -> {
bot.consumeUpdate(pair); bot.consumeUpdate(pair);
});
} }
@Test @Test
public void canFetchAbility() { void canFetchAbility() {
Update update = mock(Update.class); Update update = mock(Update.class);
Message message = mock(Message.class); Message message = mock(Message.class);
@ -462,11 +480,11 @@ public class AbilityBotTest {
Ability expected = bot.testAbility(); Ability expected = bot.testAbility();
Ability actual = trio.b(); Ability actual = trio.b();
assertEquals("Wrong ability was fetched", expected, actual); assertEquals(expected, actual, "Wrong ability was fetched");
} }
@Test @Test
public void canFetchAbilityCaseInsensitive() { void canFetchAbilityCaseInsensitive() {
Update update = mock(Update.class); Update update = mock(Update.class);
Message message = mock(Message.class); Message message = mock(Message.class);
@ -481,11 +499,11 @@ public class AbilityBotTest {
Ability expected = bot.testAbility(); Ability expected = bot.testAbility();
Ability actual = trio.b(); Ability actual = trio.b();
assertEquals("Wrong ability was fetched", expected, actual); assertEquals(expected, actual, "Wrong ability was fetched");
} }
@Test @Test
public void canFetchDefaultAbility() { void canFetchDefaultAbility() {
Update update = mock(Update.class); Update update = mock(Update.class);
Message message = mock(Message.class); Message message = mock(Message.class);
@ -498,11 +516,11 @@ public class AbilityBotTest {
Ability expected = bot.defaultAbility(); Ability expected = bot.defaultAbility();
Ability actual = trio.b(); Ability actual = trio.b();
assertEquals("Wrong ability was fetched", expected, actual); assertEquals(expected, actual, "Wrong ability was fetched");
} }
@Test @Test
public void canCheckAbilityFlags() { void canCheckAbilityFlags() {
Update update = mock(Update.class); Update update = mock(Update.class);
Message message = mock(Message.class); Message message = mock(Message.class);
@ -517,12 +535,12 @@ public class AbilityBotTest {
Trio<Update, Ability, String[]> docTrio = Trio.of(update, documentAbility, TEXT); Trio<Update, Ability, String[]> docTrio = Trio.of(update, documentAbility, TEXT);
Trio<Update, Ability, String[]> textTrio = Trio.of(update, textAbility, TEXT); Trio<Update, Ability, String[]> textTrio = Trio.of(update, textAbility, TEXT);
assertFalse("Unexpected result when checking for message flags", bot.checkMessageFlags(docTrio)); assertFalse(bot.checkMessageFlags(docTrio), "Unexpected result when checking for message flags");
assertTrue("Unexpected result when checking for message flags", bot.checkMessageFlags(textTrio)); assertTrue(bot.checkMessageFlags(textTrio), "Unexpected result when checking for message flags");
} }
@Test @Test
public void canReportCommands() { void canReportCommands() {
MessageContext context = mockContext(USER, GROUP_ID); MessageContext context = mockContext(USER, GROUP_ID);
bot.reportCommands().action().accept(context); bot.reportCommands().action().accept(context);
@ -531,12 +549,12 @@ public class AbilityBotTest {
} }
@NotNull @NotNull
public static MessageContext mockContext(User user) { static MessageContext mockContext(User user) {
return mockContext(user, user.getId()); return mockContext(user, user.getId());
} }
@NotNull @NotNull
public static MessageContext mockContext(User user, long groupId, String... args) { static MessageContext mockContext(User user, long groupId, String... args) {
Update update = mock(Update.class); Update update = mock(Update.class);
Message message = mock(Message.class); Message message = mock(Message.class);
@ -550,7 +568,7 @@ public class AbilityBotTest {
} }
@Test @Test
public void canPrintCommandsBasedOnPrivacy() { void canPrintCommandsBasedOnPrivacy() {
Update update = mock(Update.class); Update update = mock(Update.class);
Message message = mock(Message.class); Message message = mock(Message.class);
@ -566,7 +584,7 @@ public class AbilityBotTest {
} }
@Test @Test
public void printsOnlyPublicCommandsForNormalUser() { void printsOnlyPublicCommandsForNormalUser() {
Update update = mock(Update.class); Update update = mock(Update.class);
Message message = mock(Message.class); Message message = mock(Message.class);
@ -582,12 +600,6 @@ public class AbilityBotTest {
verify(silent, times(1)).send(expected, GROUP_ID); verify(silent, times(1)).send(expected, GROUP_ID);
} }
@After
public void tearDown() throws IOException {
db.clear();
db.close();
}
@NotNull @NotNull
private Update mockFullUpdate(User user, String args) { private Update mockFullUpdate(User user, String args) {
bot.users().put(USER.getId(), USER); bot.users().put(USER.getId(), USER);

View File

@ -1,45 +1,45 @@
package org.telegram.abilitybots.api.bot; package org.telegram.abilitybots.api.bot;
import org.junit.After; import org.junit.jupiter.api.AfterEach;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.telegram.abilitybots.api.objects.Ability; import org.telegram.abilitybots.api.objects.Ability;
import org.telegram.abilitybots.api.util.AbilityExtension; import org.telegram.abilitybots.api.util.AbilityExtension;
import java.io.IOException; import java.io.IOException;
import static junit.framework.TestCase.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.telegram.abilitybots.api.db.MapDBContext.offlineInstance; import static org.telegram.abilitybots.api.db.MapDBContext.offlineInstance;
import static org.telegram.abilitybots.api.objects.Locality.ALL; import static org.telegram.abilitybots.api.objects.Locality.ALL;
import static org.telegram.abilitybots.api.objects.Privacy.PUBLIC; import static org.telegram.abilitybots.api.objects.Privacy.PUBLIC;
public class ExtensionTest { class ExtensionTest {
private ExtensionUsingBot bot; private ExtensionUsingBot bot;
@Before @BeforeEach
public void setUp() { void setUp() {
bot = new ExtensionUsingBot(); bot = new ExtensionUsingBot();
} }
@Test @AfterEach
public void methodReturningAbilities() { void tearDown() throws IOException {
assertTrue("Failed to find Ability in directly declared in root extension/bot", hasAbilityNamed("direct"));
assertTrue("Failed to find Ability in directly declared in extension returned by method returning the AbilityExtension class", hasAbilityNamed("returningSuperClass0abc"));
assertTrue("Failed to find Ability in directly declared in extension returned by method returning the AbilityExtension subclass", hasAbilityNamed("returningSubClass0abc"));
}
@After
public void tearDown() throws IOException {
bot.db.clear(); bot.db.clear();
bot.db.close(); bot.db.close();
} }
@Test
void methodReturningAbilities() {
assertTrue(hasAbilityNamed("direct"), "Failed to find Ability in directly declared in root extension/bot");
assertTrue(hasAbilityNamed("returningSuperClass0abc"), "Failed to find Ability in directly declared in extension returned by method returning the AbilityExtension class");
assertTrue(hasAbilityNamed("returningSubClass0abc"), "Failed to find Ability in directly declared in extension returned by method returning the AbilityExtension subclass");
}
private boolean hasAbilityNamed(String name) { private boolean hasAbilityNamed(String name) {
return bot.abilities().values().stream().map(Ability::name).anyMatch(name::equals); return bot.abilities().values().stream().map(Ability::name).anyMatch(name::equals);
} }
public static class ExtensionUsingBot extends AbilityBot { public static class ExtensionUsingBot extends AbilityBot {
public ExtensionUsingBot() { ExtensionUsingBot() {
super("", "", offlineInstance("testing")); super("", "", offlineInstance("testing"));
} }
@ -71,7 +71,7 @@ public class ExtensionTest {
public static class AbilityBotExtension implements AbilityExtension { public static class AbilityBotExtension implements AbilityExtension {
private String name; private String name;
public AbilityBotExtension(String name) { AbilityBotExtension(String name) {
this.name = name; this.name = name;
} }

View File

@ -1,8 +1,9 @@
package org.telegram.abilitybots.api.db; package org.telegram.abilitybots.api.db;
import org.junit.After; import org.junit.jupiter.api.AfterEach;
import org.junit.Before; import org.junit.jupiter.api.Assertions;
import org.junit.Test; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.telegram.telegrambots.meta.api.objects.User; import org.telegram.telegrambots.meta.api.objects.User;
import java.io.IOException; import java.io.IOException;
@ -12,25 +13,33 @@ import java.util.Set;
import static com.google.common.collect.Maps.newHashMap; import static com.google.common.collect.Maps.newHashMap;
import static com.google.common.collect.Sets.newHashSet; import static com.google.common.collect.Sets.newHashSet;
import static java.lang.String.format; import static java.lang.String.format;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.telegram.abilitybots.api.bot.AbilityBotTest.CREATOR; import static org.telegram.abilitybots.api.bot.AbilityBotTest.CREATOR;
import static org.telegram.abilitybots.api.bot.AbilityBotTest.USER; import static org.telegram.abilitybots.api.bot.AbilityBotTest.USER;
import static org.telegram.abilitybots.api.db.MapDBContext.offlineInstance; import static org.telegram.abilitybots.api.db.MapDBContext.offlineInstance;
public class MapDBContextTest { class MapDBContextTest {
private static final String USERS = "USERS"; private static final String USERS = "USERS";
private static final String USER_ID = "USER_ID"; private static final String USER_ID = "USER_ID";
private static final String TEST = "TEST"; private static final String TEST = "TEST";
private DBContext db; private DBContext db;
@Before @BeforeEach
public void setUp() { void setUp() {
db = offlineInstance("db"); db = offlineInstance("db");
} }
@AfterEach
void tearDown() throws IOException {
db.clear();
db.close();
}
@Test @Test
public void canRecoverDB() { void canRecoverDB() {
Map<Integer, User> users = db.getMap(USERS); Map<Integer, User> users = db.getMap(USERS);
Map<String, Integer> userIds = db.getMap(USER_ID); Map<String, Integer> userIds = db.getMap(USER_ID);
users.put(CREATOR.getId(), CREATOR); users.put(CREATOR.getId(), CREATOR);
@ -49,30 +58,30 @@ public class MapDBContextTest {
Map<Integer, User> recoveredUsers = db.getMap(USERS); Map<Integer, User> recoveredUsers = db.getMap(USERS);
String afterRecoveryInfo = db.info(USERS); String afterRecoveryInfo = db.info(USERS);
assertTrue("Could not recover database successfully", recovered); assertTrue(recovered, "Could not recover database successfully");
assertEquals("Map info before and after recovery is different", beforeBackupInfo, afterRecoveryInfo); assertEquals(beforeBackupInfo, afterRecoveryInfo, "Map info before and after recovery is different");
assertEquals("Map before and after recovery are not equal", originalUsers, recoveredUsers); assertEquals(originalUsers, recoveredUsers, "Map before and after recovery are not equal");
} }
@Test @Test
public void canFallbackDBIfRecoveryFails() { void canFallbackDBIfRecoveryFails() {
Set<User> users = db.getSet(USERS); Set<User> users = db.getSet(USERS);
users.add(CREATOR); users.add(CREATOR);
users.add(USER); users.add(USER);
Set<User> originalSet = newHashSet(users); Set<User> originalSet = newHashSet(users);
Object jsonBackup = db.backup(); Object jsonBackup = db.backup();
String corruptBackup = "!@#$" + String.valueOf(jsonBackup); String corruptBackup = "!@#$" + jsonBackup;
boolean recovered = db.recover(corruptBackup); boolean recovered = db.recover(corruptBackup);
Set<User> recoveredSet = db.getSet(USERS); Set<User> recoveredSet = db.getSet(USERS);
assertFalse("Recovery was successful from a CORRUPT backup", recovered); assertFalse(recovered, "Recovery was successful from a CORRUPT backup");
assertEquals("Set before and after corrupt recovery are not equal", originalSet, recoveredSet); assertEquals(originalSet, recoveredSet, "Set before and after corrupt recovery are not equal");
} }
@Test @Test
public void canGetSummary() { void canGetSummary() {
String anotherTest = TEST + 1; String anotherTest = TEST + 1;
db.getSet(TEST).add(TEST); db.getSet(TEST).add(TEST);
db.getSet(anotherTest).add(anotherTest); db.getSet(anotherTest).add(anotherTest);
@ -85,7 +94,7 @@ public class MapDBContextTest {
} }
@Test @Test
public void canGetInfo() { void canGetInfo() {
db.getSet(TEST).add(TEST); db.getSet(TEST).add(TEST);
String actualInfo = db.info(TEST); String actualInfo = db.info(TEST);
@ -95,13 +104,13 @@ public class MapDBContextTest {
assertEquals("Actual DB structure info does not match that of the expected", expectedInfo, actualInfo); assertEquals("Actual DB structure info does not match that of the expected", expectedInfo, actualInfo);
} }
@Test(expected = IllegalStateException.class) @Test
public void cantGetInfoFromNonexistentDBStructureName() { void cantGetInfoFromNonexistentDBStructureName() {
db.info(TEST); Assertions.assertThrows(IllegalStateException.class, () -> db.info(TEST));
} }
@Test @Test
public void canGetAndSetVariables() { void canGetAndSetVariables() {
String varName = "somevar"; String varName = "somevar";
Var<User> var = db.getVar(varName); Var<User> var = db.getVar(varName);
var.set(CREATOR); var.set(CREATOR);
@ -116,10 +125,4 @@ public class MapDBContextTest {
Var<User> changedVar = db.getVar(varName); Var<User> changedVar = db.getVar(varName);
assertEquals(changedVar.get(), USER); assertEquals(changedVar.get(), USER);
} }
@After
public void tearDown() throws IOException {
db.clear();
db.close();
}
} }

View File

@ -1,58 +1,73 @@
package org.telegram.abilitybots.api.objects; package org.telegram.abilitybots.api.objects;
import org.junit.Test; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.telegram.abilitybots.api.bot.DefaultBot.getDefaultBuilder; import static org.telegram.abilitybots.api.bot.DefaultBot.getDefaultBuilder;
public class AbilityTest { class AbilityTest {
@Test(expected = IllegalArgumentException.class) @Test
public void argumentsCannotBeNegative() { void argumentsCannotBeNegative() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
getDefaultBuilder().input(-4).build(); getDefaultBuilder().input(-4).build();
} });
@Test(expected = IllegalArgumentException.class)
public void nameCannotBeEmpty() {
getDefaultBuilder().name("").build();
}
@Test(expected = IllegalArgumentException.class)
public void nameCannotBeNull() {
getDefaultBuilder().name(null).build();
}
@Test(expected = NullPointerException.class)
public void consumerCannotBeNull() {
getDefaultBuilder().action(null).build();
}
@Test(expected = NullPointerException.class)
public void localityCannotBeNull() {
getDefaultBuilder().locality(null).build();
}
@Test(expected = NullPointerException.class)
public void privacyCannotBeNull() {
getDefaultBuilder().privacy(null).build();
}
@Test(expected = IllegalArgumentException.class)
public void nameCannotContainSpaces() {
getDefaultBuilder().name("test test").build();
} }
@Test @Test
public void abilityEqualsMethod() { void nameCannotBeEmpty() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
getDefaultBuilder().name("").build();
});
}
@Test
void nameCannotBeNull() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
getDefaultBuilder().name(null).build();
});
}
@Test
void consumerCannotBeNull() {
Assertions.assertThrows(NullPointerException.class, () -> {
getDefaultBuilder().action(null).build();
});
}
@Test
void localityCannotBeNull() {
Assertions.assertThrows(NullPointerException.class, () -> {
getDefaultBuilder().locality(null).build();
});
}
@Test
void privacyCannotBeNull() {
Assertions.assertThrows(NullPointerException.class, () -> {
getDefaultBuilder().privacy(null).build();
});
}
@Test
void nameCannotContainSpaces() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
getDefaultBuilder().name("test test").build();
});
}
@Test
void abilityEqualsMethod() {
Ability ability1 = getDefaultBuilder().build(); Ability ability1 = getDefaultBuilder().build();
Ability ability2 = getDefaultBuilder().build(); Ability ability2 = getDefaultBuilder().build();
Ability ability3 = getDefaultBuilder().name("anotherconsumer").build(); Ability ability3 = getDefaultBuilder().name("anotherconsumer").build();
Ability ability4 = getDefaultBuilder().action((context) -> { Ability ability4 = getDefaultBuilder().action((context) -> {
}).build(); }).build();
assertEquals("Abilities should not be equal", ability1, ability2); assertEquals(ability1, ability2, "Abilities should not be equal");
assertEquals("Abilities should not be equal", ability1, ability4); assertEquals(ability1, ability4, "Abilities should not be equal");
assertNotEquals("Abilities should be equal", ability1, ability3); assertNotEquals(ability1, ability3, "Abilities should be equal");
} }
} }

View File

@ -1,43 +1,43 @@
package org.telegram.abilitybots.api.sender; package org.telegram.abilitybots.api.sender;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import java.util.Optional; import java.util.Optional;
import static junit.framework.TestCase.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static junit.framework.TestCase.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.Matchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
public class SilentSenderTest { class SilentSenderTest {
private SilentSender silent; private SilentSender silent;
private MessageSender sender; private MessageSender sender;
@Before @BeforeEach
public void setUp() { void setUp() {
sender = mock(MessageSender.class); sender = mock(MessageSender.class);
silent = new SilentSender(sender); silent = new SilentSender(sender);
} }
@Test @Test
public void returnsEmptyOnError() throws TelegramApiException { void returnsEmptyOnError() throws TelegramApiException {
when(sender.execute(any())).thenThrow(TelegramApiException.class); when(sender.execute(any())).thenThrow(TelegramApiException.class);
Optional execute = silent.execute(null); Optional execute = silent.execute(null);
assertFalse("Execution of a bot API method with execption results in a nonempty optional", execute.isPresent()); assertFalse(execute.isPresent(), "Execution of a bot API method with execption results in a nonempty optional");
} }
@Test @Test
public void returnOptionalOnSuccess() throws TelegramApiException { void returnOptionalOnSuccess() throws TelegramApiException {
String data = "data"; String data = "data";
when(sender.execute(any())).thenReturn(data); when(sender.execute(any())).thenReturn(data);
Optional execute = silent.execute(null); Optional execute = silent.execute(null);
assertEquals("Silent execution resulted in a different object", data, execute.get()); assertEquals(data, execute.get(), "Silent execution resulted in a different object");
} }
} }

View File

@ -3,9 +3,15 @@
xmlns="http://maven.apache.org/POM/4.0.0" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.telegram</groupId> <groupId>org.telegram</groupId>
<artifactId>telegrambots-chat-session-bot</artifactId> <artifactId>Bots</artifactId>
<version>4.3.1</version> <version>4.3.1</version>
</parent>
<artifactId>telegrambots-chat-session-bot</artifactId>
<version>${project.parent.version}</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>Telegram Bots Chat Session Bot</name> <name>Telegram Bots Chat Session Bot</name>
@ -63,9 +69,14 @@
</distributionManagement> </distributionManagement>
<properties> <properties>
<java.version>11</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<shiro.version>1.4.0</shiro.version>
<shiro.version>1.4.1</shiro.version>
</properties> </properties>
<dependencies> <dependencies>
@ -82,19 +93,6 @@
<artifactId>shiro-core</artifactId> <artifactId>shiro-core</artifactId>
<version>${shiro.version}</version> <version>${shiro.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>2.0.2-beta</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -104,10 +102,15 @@
<testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory> <testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory> <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
<plugins> <plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M3</version>
</plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId> <artifactId>maven-gpg-plugin</artifactId>
<version>1.5</version> <version>1.6</version>
<executions> <executions>
<execution> <execution>
<id>sign-artifacts</id> <id>sign-artifacts</id>
@ -121,7 +124,7 @@
<plugin> <plugin>
<groupId>org.sonatype.plugins</groupId> <groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId> <artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.3</version> <version>1.6.8</version>
<extensions>true</extensions> <extensions>true</extensions>
<configuration> <configuration>
<serverId>ossrh</serverId> <serverId>ossrh</serverId>
@ -131,7 +134,7 @@
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-clean-plugin</artifactId> <artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version> <version>3.1.0</version>
<executions> <executions>
<execution> <execution>
<id>clean-project</id> <id>clean-project</id>
@ -144,7 +147,7 @@
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-assembly-plugin</artifactId> <artifactId>maven-assembly-plugin</artifactId>
<version>2.6</version> <version>3.1.1</version>
<configuration> <configuration>
<descriptorRefs> <descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef> <descriptorRef>jar-with-dependencies</descriptorRef>
@ -163,7 +166,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId> <artifactId>maven-source-plugin</artifactId>
<version>3.0.0</version> <version>3.1.0</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
@ -175,14 +178,14 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId> <artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.3</version> <version>3.1.0</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
<goal>jar</goal> <goal>jar</goal>
</goals> </goals>
<configuration> <configuration>
<additionalparam>-Xdoclint:none</additionalparam> <doclint>none</doclint>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
@ -190,7 +193,7 @@
<plugin> <plugin>
<groupId>org.jacoco</groupId> <groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId> <artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.7.201606060606</version> <version>0.8.4</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
@ -209,7 +212,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId> <artifactId>maven-enforcer-plugin</artifactId>
<version>1.4.1</version> <version>3.0.0-M2</version>
<executions> <executions>
<execution> <execution>
<id>enforce-versions</id> <id>enforce-versions</id>
@ -227,7 +230,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId> <artifactId>maven-dependency-plugin</artifactId>
<version>2.4</version> <version>3.1.1</version>
<executions> <executions>
<execution> <execution>
<id>copy</id> <id>copy</id>
@ -241,9 +244,10 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration> <configuration>
<source>1.8</source> <source>${java.version}</source>
<target>1.8</target> <target>${java.version}</target>
<encoding>UTF-8</encoding> <encoding>UTF-8</encoding>
</configuration> </configuration>
</plugin> </plugin>

View File

@ -3,9 +3,15 @@
xmlns="http://maven.apache.org/POM/4.0.0" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.telegram</groupId> <groupId>org.telegram</groupId>
<artifactId>telegrambotsextensions</artifactId> <artifactId>Bots</artifactId>
<version>4.3.1</version> <version>4.3.1</version>
</parent>
<artifactId>telegrambotsextensions</artifactId>
<version>${project.parent.version}</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>Telegram Bots Extensions</name> <name>Telegram Bots Extensions</name>
@ -57,6 +63,10 @@
</distributionManagement> </distributionManagement>
<properties> <properties>
<java.version>11</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties> </properties>
@ -76,10 +86,15 @@
<testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory> <testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory> <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
<plugins> <plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M3</version>
</plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId> <artifactId>maven-gpg-plugin</artifactId>
<version>1.5</version> <version>1.6</version>
<executions> <executions>
<execution> <execution>
<id>sign-artifacts</id> <id>sign-artifacts</id>
@ -93,7 +108,7 @@
<plugin> <plugin>
<groupId>org.sonatype.plugins</groupId> <groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId> <artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.3</version> <version>1.6.8</version>
<extensions>true</extensions> <extensions>true</extensions>
<configuration> <configuration>
<serverId>ossrh</serverId> <serverId>ossrh</serverId>
@ -103,7 +118,7 @@
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-clean-plugin</artifactId> <artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version> <version>3.1.0</version>
<executions> <executions>
<execution> <execution>
<id>clean-project</id> <id>clean-project</id>
@ -116,7 +131,7 @@
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-assembly-plugin</artifactId> <artifactId>maven-assembly-plugin</artifactId>
<version>2.6</version> <version>3.1.1</version>
<configuration> <configuration>
<descriptorRefs> <descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef> <descriptorRef>jar-with-dependencies</descriptorRef>
@ -135,7 +150,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId> <artifactId>maven-source-plugin</artifactId>
<version>3.0.0</version> <version>3.1.0</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
@ -147,14 +162,14 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId> <artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.3</version> <version>3.1.0</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
<goal>jar</goal> <goal>jar</goal>
</goals> </goals>
<configuration> <configuration>
<additionalparam>-Xdoclint:none</additionalparam> <doclint>none</doclint>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
@ -162,7 +177,7 @@
<plugin> <plugin>
<groupId>org.jacoco</groupId> <groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId> <artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.7.201606060606</version> <version>0.8.4</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
@ -181,7 +196,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId> <artifactId>maven-enforcer-plugin</artifactId>
<version>1.4.1</version> <version>3.0.0-M2</version>
<executions> <executions>
<execution> <execution>
<id>enforce-versions</id> <id>enforce-versions</id>
@ -199,7 +214,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId> <artifactId>maven-dependency-plugin</artifactId>
<version>2.4</version> <version>3.1.1</version>
<executions> <executions>
<execution> <execution>
<id>copy</id> <id>copy</id>
@ -213,9 +228,10 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration> <configuration>
<source>1.8</source> <source>${java.version}</source>
<target>1.8</target> <target>${java.version}</target>
<encoding>UTF-8</encoding> <encoding>UTF-8</encoding>
</configuration> </configuration>
</plugin> </plugin>

View File

@ -3,9 +3,15 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.telegram</groupId> <groupId>org.telegram</groupId>
<artifactId>telegrambots-meta</artifactId> <artifactId>Bots</artifactId>
<version>4.3.1</version> <version>4.3.1</version>
</parent>
<artifactId>telegrambots-meta</artifactId>
<version>${project.parent.version}</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>Telegram Bots Meta</name> <name>Telegram Bots Meta</name>
@ -57,14 +63,17 @@
</distributionManagement> </distributionManagement>
<properties> <properties>
<java.version>11</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<guice.version>4.2.2</guice.version> <guice.version>4.2.2</guice.version>
<jackson.version>2.9.9</jackson.version> <jackson.version>2.9.9</jackson.version>
<jacksonanotation.version>2.9.0</jacksonanotation.version> <jacksonanotation.version>2.9.9</jacksonanotation.version>
<json.version>20180813</json.version> <json.version>20180813</json.version>
<junit.version>4.12</junit.version> <guava.version>28.0-jre</guava.version>
<guava.version>25.1-jre</guava.version>
</properties> </properties>
<dependencies> <dependencies>
@ -105,12 +114,6 @@
<artifactId>json</artifactId> <artifactId>json</artifactId>
<version>${json.version}</version> <version>${json.version}</version>
</dependency> </dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -123,7 +126,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId> <artifactId>maven-gpg-plugin</artifactId>
<version>1.5</version> <version>1.6</version>
<executions> <executions>
<execution> <execution>
<id>sign-artifacts</id> <id>sign-artifacts</id>
@ -137,7 +140,7 @@
<plugin> <plugin>
<groupId>org.sonatype.plugins</groupId> <groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId> <artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.3</version> <version>1.6.8</version>
<extensions>true</extensions> <extensions>true</extensions>
<configuration> <configuration>
<serverId>ossrh</serverId> <serverId>ossrh</serverId>
@ -147,7 +150,7 @@
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-clean-plugin</artifactId> <artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version> <version>3.1.0</version>
<executions> <executions>
<execution> <execution>
<id>clean-project</id> <id>clean-project</id>
@ -160,7 +163,7 @@
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-assembly-plugin</artifactId> <artifactId>maven-assembly-plugin</artifactId>
<version>2.6</version> <version>3.1.1</version>
<configuration> <configuration>
<descriptorRefs> <descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef> <descriptorRef>jar-with-dependencies</descriptorRef>
@ -179,7 +182,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId> <artifactId>maven-source-plugin</artifactId>
<version>3.0.0</version> <version>3.1.0</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
@ -191,14 +194,14 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId> <artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.3</version> <version>3.1.0</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
<goal>jar</goal> <goal>jar</goal>
</goals> </goals>
<configuration> <configuration>
<additionalparam>-Xdoclint:none</additionalparam> <doclint>none</doclint>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
@ -206,7 +209,7 @@
<plugin> <plugin>
<groupId>org.jacoco</groupId> <groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId> <artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.7.201606060606</version> <version>0.8.4</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
@ -225,7 +228,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId> <artifactId>maven-enforcer-plugin</artifactId>
<version>1.4.1</version> <version>3.0.0-M2</version>
<executions> <executions>
<execution> <execution>
<id>enforce</id> <id>enforce</id>
@ -243,7 +246,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId> <artifactId>maven-dependency-plugin</artifactId>
<version>2.4</version> <version>3.1.1</version>
<executions> <executions>
<execution> <execution>
<id>copy</id> <id>copy</id>
@ -251,15 +254,21 @@
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M3</version>
</plugin>
</plugins> </plugins>
<pluginManagement> <pluginManagement>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration> <configuration>
<source>1.8</source> <source>${java.version}</source>
<target>1.8</target> <target>${java.version}</target>
<encoding>UTF-8</encoding> <encoding>UTF-8</encoding>
</configuration> </configuration>
</plugin> </plugin>

View File

@ -1,25 +1,26 @@
package org.telegram.telegrambots.meta.api.methods.send; package org.telegram.telegrambots.meta.api.methods.send;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
public class SendMessageTest { class SendMessageTest {
@Test @Test
public void comparison() throws Exception { void comparison() {
SendMessage sm1 = new SendMessage().setChatId(1L).setText("Hello World"); SendMessage sm1 = new SendMessage().setChatId(1L).setText("Hello World");
SendMessage sm2 = new SendMessage().setChatId(1L).setText("Hello World"); SendMessage sm2 = new SendMessage().setChatId(1L).setText("Hello World");
SendMessage noMessage = new SendMessage().setChatId(1L); SendMessage noMessage = new SendMessage().setChatId(1L);
SendMessage disabledNotification = new SendMessage().setChatId(1L).setText("Hello World").disableNotification(); SendMessage disabledNotification = new SendMessage().setChatId(1L).setText("Hello World").disableNotification();
assertTrue(sm1.equals(sm2)); assertEquals(sm1, sm2);
assertFalse(sm1.equals(noMessage)); assertNotEquals(sm1, noMessage);
assertFalse(sm1.equals(disabledNotification)); assertNotEquals(sm1, disabledNotification);
assertTrue(sm1.hashCode() == sm2.hashCode()); assertEquals(sm1.hashCode(), sm2.hashCode());
assertFalse(sm1.hashCode() == noMessage.hashCode()); assertNotEquals(sm1.hashCode(), noMessage.hashCode());
assertFalse(sm1.hashCode() == disabledNotification.hashCode()); assertNotEquals(sm1.hashCode(), disabledNotification.hashCode());
} }
} }

View File

@ -1,31 +1,30 @@
package org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons; package org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import static java.util.Arrays.asList; import static java.util.Arrays.asList;
import static org.hamcrest.core.Is.is; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertThat; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.Assert.assertTrue;
public class KeyboardRowTest { class KeyboardRowTest {
private static final List<String> BUTTON_NAMES = asList("Carlotta Valdes", "Jimmy Stewart"); private static final List<String> BUTTON_NAMES = asList("Carlotta Valdes", "Jimmy Stewart");
@Test @Test
public void shouldAddAllButtons() { void shouldAddAllButtons() {
final KeyboardRow keyboardRow = new KeyboardRow(); final KeyboardRow keyboardRow = new KeyboardRow();
keyboardRow.addAll(BUTTON_NAMES); keyboardRow.addAll(BUTTON_NAMES);
assertThat(keyboardRow.size(), is(2)); assertEquals(2, keyboardRow.size());
assertThat(keyboardRow.get(0).getText(), is("Carlotta Valdes")); assertEquals("Carlotta Valdes", keyboardRow.get(0).getText());
assertThat(keyboardRow.get(1).getText(), is("Jimmy Stewart")); assertEquals("Jimmy Stewart", keyboardRow.get(1).getText());
} }
@Test @Test
public void shouldAddNoButtons() { void shouldAddNoButtons() {
final KeyboardRow keyboardRow = new KeyboardRow(); final KeyboardRow keyboardRow = new KeyboardRow();
keyboardRow.addAll(new ArrayList<String>()); keyboardRow.addAll(new ArrayList<String>());
assertTrue(keyboardRow.isEmpty()); assertTrue(keyboardRow.isEmpty());

View File

@ -3,9 +3,9 @@ package org.telegram.telegrambots.meta.test;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.telegram.telegrambots.meta.api.objects.ApiResponse;
import org.telegram.telegrambots.meta.api.objects.Audio; import org.telegram.telegrambots.meta.api.objects.Audio;
import org.telegram.telegrambots.meta.api.objects.CallbackQuery; import org.telegram.telegrambots.meta.api.objects.CallbackQuery;
import org.telegram.telegrambots.meta.api.objects.Chat; import org.telegram.telegrambots.meta.api.objects.Chat;
@ -18,63 +18,67 @@ import org.telegram.telegrambots.meta.api.objects.User;
import org.telegram.telegrambots.meta.api.objects.Voice; import org.telegram.telegrambots.meta.api.objects.Voice;
import org.telegram.telegrambots.meta.api.objects.inlinequery.ChosenInlineQuery; import org.telegram.telegrambots.meta.api.objects.inlinequery.ChosenInlineQuery;
import org.telegram.telegrambots.meta.api.objects.inlinequery.InlineQuery; import org.telegram.telegrambots.meta.api.objects.inlinequery.InlineQuery;
import org.telegram.telegrambots.meta.api.objects.ApiResponse;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** /**
* @author Ruben Bermudez * @author Ruben Bermudez
* @version 1.0 * @version 1.0
*/ */
public class TestDeserialization { class TestDeserialization {
private ObjectMapper mapper; private ObjectMapper mapper;
@Before @BeforeEach
public void setUp() { void setUp() {
mapper = new ObjectMapper(); mapper = new ObjectMapper();
} }
@Test @Test
public void TestUpdateDeserialization() throws Exception { void TestUpdateDeserialization() throws Exception {
Update update = mapper.readValue(TelegramBotsHelper.GetUpdate(), Update.class); Update update = mapper.readValue(TelegramBotsHelper.GetUpdate(), Update.class);
assertUpdate(update); assertUpdate(update);
} }
@Test @Test
public void TestUpdateDeserializationWithInlineKeyboard() throws Exception { void TestUpdateDeserializationWithInlineKeyboard() throws Exception {
Update update = mapper.readValue(TelegramBotsHelper.GetUpdateWithMessageInCallbackQuery(), Update.class); Update update = mapper.readValue(TelegramBotsHelper.GetUpdateWithMessageInCallbackQuery(), Update.class);
Assert.assertNotNull(update); assertNotNull(update);
Assert.assertNotNull(update.getCallbackQuery()); assertNotNull(update.getCallbackQuery());
Assert.assertNotNull(update.getCallbackQuery().getMessage()); assertNotNull(update.getCallbackQuery().getMessage());
Assert.assertNotNull(update.getCallbackQuery().getMessage().getReplyMarkup()); assertNotNull(update.getCallbackQuery().getMessage().getReplyMarkup());
} }
@Test @Test
public void TestResponseWithoutErrorDeserialization() throws IOException { void TestResponseWithoutErrorDeserialization() throws IOException {
ApiResponse<ArrayList<Update>> result = mapper.readValue(TelegramBotsHelper.GetResponseWithoutError(), new TypeReference<ApiResponse<ArrayList<Update>>>(){}); ApiResponse<ArrayList<Update>> result = mapper.readValue(TelegramBotsHelper.GetResponseWithoutError(), new TypeReference<ApiResponse<ArrayList<Update>>>(){});
Assert.assertNotNull(result); assertNotNull(result);
Assert.assertTrue(result.getOk()); assertTrue(result.getOk());
Assert.assertEquals(1, result.getResult().size()); assertEquals(1, result.getResult().size());
assertUpdate(result.getResult().get(0)); assertUpdate(result.getResult().get(0));
} }
@Test @Test
public void TestResponseWithErrorDeserialization() throws IOException { void TestResponseWithErrorDeserialization() throws IOException {
ApiResponse<ArrayList<Update>> result = mapper.readValue(TelegramBotsHelper.GetResponseWithError(), new TypeReference<ApiResponse<ArrayList<Update>>>(){}); ApiResponse<ArrayList<Update>> result = mapper.readValue(TelegramBotsHelper.GetResponseWithError(), new TypeReference<ApiResponse<ArrayList<Update>>>(){});
Assert.assertNotNull(result); assertNotNull(result);
Assert.assertFalse(result.getOk()); assertFalse(result.getOk());
Assert.assertEquals(Integer.valueOf(400), result.getErrorCode()); assertEquals(Integer.valueOf(400), result.getErrorCode());
Assert.assertEquals("Error descriptions", result.getErrorDescription()); assertEquals("Error descriptions", result.getErrorDescription());
Assert.assertNotNull(result.getParameters()); assertNotNull(result.getParameters());
Assert.assertEquals(Long.valueOf(12345), result.getParameters().getMigrateToChatId()); assertEquals(Long.valueOf(12345), result.getParameters().getMigrateToChatId());
Assert.assertEquals(Integer.valueOf(12), result.getParameters().getRetryAfter()); assertEquals(Integer.valueOf(12), result.getParameters().getRetryAfter());
} }
private void assertUpdate(Update update) { private void assertUpdate(Update update) {
Assert.assertNotNull(update); assertNotNull(update);
Assert.assertEquals((Integer) 10000, update.getUpdateId()); assertEquals((Integer) 10000, update.getUpdateId());
assertEditedMessage(update.getEditedMessage()); assertEditedMessage(update.getEditedMessage());
assertCallbackQuery(update.getCallbackQuery()); assertCallbackQuery(update.getCallbackQuery());
assertInlineQuery(update.getInlineQuery()); assertInlineQuery(update.getInlineQuery());
@ -83,11 +87,11 @@ public class TestDeserialization {
} }
private void assertMessage(Message message) { private void assertMessage(Message message) {
Assert.assertNotNull(message); assertNotNull(message);
Assert.assertEquals(Integer.valueOf(1441645532), message.getDate()); assertEquals(Integer.valueOf(1441645532), message.getDate());
Assert.assertEquals(Integer.valueOf(1365), message.getMessageId()); assertEquals(Integer.valueOf(1365), message.getMessageId());
Assert.assertEquals(Integer.valueOf(1441645550), message.getForwardDate()); assertEquals(Integer.valueOf(1441645550), message.getForwardDate());
Assert.assertEquals("Bold and italics", message.getText()); assertEquals("Bold and italics", message.getText());
assertPrivateChat(message.getChat()); assertPrivateChat(message.getChat());
assertFromUser(message.getFrom()); assertFromUser(message.getFrom());
assertForwardFrom(message.getForwardFrom()); assertForwardFrom(message.getForwardFrom());
@ -99,119 +103,119 @@ public class TestDeserialization {
} }
private void assertDocument(Document document) { private void assertDocument(Document document) {
Assert.assertNotNull(document); assertNotNull(document);
Assert.assertEquals("AwADBAADbXXXXXXXXXXXGBdhD2l6_XX", document.getFileId()); assertEquals("AwADBAADbXXXXXXXXXXXGBdhD2l6_XX", document.getFileId());
Assert.assertEquals("Testfile.pdf", document.getFileName()); assertEquals("Testfile.pdf", document.getFileName());
Assert.assertEquals("application/pdf", document.getMimeType()); assertEquals("application/pdf", document.getMimeType());
Assert.assertEquals(Integer.valueOf(536392), document.getFileSize()); assertEquals(Integer.valueOf(536392), document.getFileSize());
} }
private void assertVoice(Voice voice) { private void assertVoice(Voice voice) {
Assert.assertNotNull(voice); assertNotNull(voice);
Assert.assertEquals("AwADBAADbXXXXXXXXXXXGBdhD2l6_XX", voice.getFileId()); assertEquals("AwADBAADbXXXXXXXXXXXGBdhD2l6_XX", voice.getFileId());
Assert.assertEquals(Integer.valueOf(5), voice.getDuration()); assertEquals(Integer.valueOf(5), voice.getDuration());
Assert.assertEquals("audio/ogg", voice.getMimeType()); assertEquals("audio/ogg", voice.getMimeType());
Assert.assertEquals(Integer.valueOf(23000), voice.getFileSize()); assertEquals(Integer.valueOf(23000), voice.getFileSize());
} }
private void assertAudio(Audio audio) { private void assertAudio(Audio audio) {
Assert.assertNotNull(audio); assertNotNull(audio);
Assert.assertEquals("AwADBAADbXXXXXXXXXXXGBdhD2l6_XX", audio.getFileId()); assertEquals("AwADBAADbXXXXXXXXXXXGBdhD2l6_XX", audio.getFileId());
Assert.assertEquals(Integer.valueOf(243), audio.getDuration()); assertEquals(Integer.valueOf(243), audio.getDuration());
Assert.assertEquals("audio/mpeg", audio.getMimeType()); assertEquals("audio/mpeg", audio.getMimeType());
Assert.assertEquals(Integer.valueOf(3897500), audio.getFileSize()); assertEquals(Integer.valueOf(3897500), audio.getFileSize());
Assert.assertEquals("Testmusicfile", audio.getTitle()); assertEquals("Testmusicfile", audio.getTitle());
} }
private void assertEntities(List<MessageEntity> entities) { private void assertEntities(List<MessageEntity> entities) {
Assert.assertNotNull(entities); assertNotNull(entities);
Assert.assertEquals(2, entities.size()); assertEquals(2, entities.size());
Assert.assertEquals(EntityType.ITALIC, entities.get(0).getType()); assertEquals(EntityType.ITALIC, entities.get(0).getType());
Assert.assertEquals(Integer.valueOf(9), entities.get(0).getOffset()); assertEquals(Integer.valueOf(9), entities.get(0).getOffset());
Assert.assertEquals(Integer.valueOf(7), entities.get(0).getLength()); assertEquals(Integer.valueOf(7), entities.get(0).getLength());
Assert.assertEquals("italics", entities.get(0).getText()); assertEquals("italics", entities.get(0).getText());
Assert.assertEquals(EntityType.BOLD, entities.get(1).getType()); assertEquals(EntityType.BOLD, entities.get(1).getType());
Assert.assertEquals(Integer.valueOf(0), entities.get(1).getOffset()); assertEquals(Integer.valueOf(0), entities.get(1).getOffset());
Assert.assertEquals(Integer.valueOf(4), entities.get(1).getLength()); assertEquals(Integer.valueOf(4), entities.get(1).getLength());
Assert.assertEquals("Bold", entities.get(1).getText()); assertEquals("Bold", entities.get(1).getText());
} }
private void assertReplyToMessage(Message replyToMessage) { private void assertReplyToMessage(Message replyToMessage) {
Assert.assertNotNull(replyToMessage); assertNotNull(replyToMessage);
Assert.assertEquals(Integer.valueOf(1441645000), replyToMessage.getDate()); assertEquals(Integer.valueOf(1441645000), replyToMessage.getDate());
Assert.assertEquals(Integer.valueOf(1334), replyToMessage.getMessageId()); assertEquals(Integer.valueOf(1334), replyToMessage.getMessageId());
Assert.assertEquals("Original", replyToMessage.getText()); assertEquals("Original", replyToMessage.getText());
Assert.assertNotNull(replyToMessage.getChat()); assertNotNull(replyToMessage.getChat());
Assert.assertEquals("ReplyLastname", replyToMessage.getChat().getLastName()); assertEquals("ReplyLastname", replyToMessage.getChat().getLastName());
Assert.assertEquals("ReplyFirstname", replyToMessage.getChat().getFirstName()); assertEquals("ReplyFirstname", replyToMessage.getChat().getFirstName());
Assert.assertEquals("Testusername", replyToMessage.getChat().getUserName()); assertEquals("Testusername", replyToMessage.getChat().getUserName());
Assert.assertEquals(Long.valueOf(1111112), replyToMessage.getChat().getId()); assertEquals(Long.valueOf(1111112), replyToMessage.getChat().getId());
} }
private void assertForwardFrom(User forwardFrom) { private void assertForwardFrom(User forwardFrom) {
Assert.assertNotNull(forwardFrom); assertNotNull(forwardFrom);
Assert.assertEquals("ForwardLastname", forwardFrom.getLastName()); assertEquals("ForwardLastname", forwardFrom.getLastName());
Assert.assertEquals("ForwardFirstname", forwardFrom.getFirstName()); assertEquals("ForwardFirstname", forwardFrom.getFirstName());
Assert.assertEquals(Integer.valueOf(222222), forwardFrom.getId()); assertEquals(Integer.valueOf(222222), forwardFrom.getId());
} }
private void assertPrivateChat(Chat chat) { private void assertPrivateChat(Chat chat) {
Assert.assertNotNull(chat); assertNotNull(chat);
Assert.assertEquals(Long.valueOf(1111111), chat.getId()); assertEquals(Long.valueOf(1111111), chat.getId());
Assert.assertTrue(chat.isUserChat()); assertTrue(chat.isUserChat());
Assert.assertEquals("Test Lastname", chat.getLastName()); assertEquals("Test Lastname", chat.getLastName());
Assert.assertEquals("Test Firstname", chat.getFirstName()); assertEquals("Test Firstname", chat.getFirstName());
Assert.assertEquals("Testusername", chat.getUserName()); assertEquals("Testusername", chat.getUserName());
} }
private void assertChosenInlineQuery(ChosenInlineQuery chosenInlineQuery) { private void assertChosenInlineQuery(ChosenInlineQuery chosenInlineQuery) {
Assert.assertNotNull(chosenInlineQuery); assertNotNull(chosenInlineQuery);
Assert.assertEquals("12", chosenInlineQuery.getResultId()); assertEquals("12", chosenInlineQuery.getResultId());
Assert.assertEquals("inline query", chosenInlineQuery.getQuery()); assertEquals("inline query", chosenInlineQuery.getQuery());
Assert.assertEquals("1234csdbsk4839", chosenInlineQuery.getInlineMessageId()); assertEquals("1234csdbsk4839", chosenInlineQuery.getInlineMessageId());
assertFromUser(chosenInlineQuery.getFrom()); assertFromUser(chosenInlineQuery.getFrom());
} }
private void assertInlineQuery(InlineQuery inlineQuery) { private void assertInlineQuery(InlineQuery inlineQuery) {
Assert.assertNotNull(inlineQuery); assertNotNull(inlineQuery);
Assert.assertEquals("134567890097", inlineQuery.getId()); assertEquals("134567890097", inlineQuery.getId());
Assert.assertEquals("inline query", inlineQuery.getQuery()); assertEquals("inline query", inlineQuery.getQuery());
Assert.assertEquals("offset", inlineQuery.getOffset()); assertEquals("offset", inlineQuery.getOffset());
assertFromUser(inlineQuery.getFrom()); assertFromUser(inlineQuery.getFrom());
Assert.assertNotNull(inlineQuery.getLocation()); assertNotNull(inlineQuery.getLocation());
Assert.assertEquals(Float.valueOf("0.234242534"), inlineQuery.getLocation().getLatitude()); assertEquals(Float.valueOf("0.234242534"), inlineQuery.getLocation().getLatitude());
Assert.assertEquals(Float.valueOf("0.234242534"), inlineQuery.getLocation().getLongitude()); assertEquals(Float.valueOf("0.234242534"), inlineQuery.getLocation().getLongitude());
} }
private void assertCallbackQuery(CallbackQuery callbackQuery) { private void assertCallbackQuery(CallbackQuery callbackQuery) {
Assert.assertNotNull(callbackQuery); assertNotNull(callbackQuery);
Assert.assertEquals("4382bfdwdsb323b2d9", callbackQuery.getId()); assertEquals("4382bfdwdsb323b2d9", callbackQuery.getId());
Assert.assertEquals("Data from button callback", callbackQuery.getData()); assertEquals("Data from button callback", callbackQuery.getData());
Assert.assertEquals("1234csdbsk4839", callbackQuery.getInlineMessageId()); assertEquals("1234csdbsk4839", callbackQuery.getInlineMessageId());
assertFromUser(callbackQuery.getFrom()); assertFromUser(callbackQuery.getFrom());
} }
private void assertEditedMessage(Message message) { private void assertEditedMessage(Message message) {
Assert.assertEquals((Integer) 1441645532, message.getDate()); assertEquals((Integer) 1441645532, message.getDate());
Assert.assertEquals((Integer) 1441646600, message.getEditDate()); assertEquals((Integer) 1441646600, message.getEditDate());
Assert.assertEquals((Integer) 1365, message.getMessageId()); assertEquals((Integer) 1365, message.getMessageId());
Assert.assertEquals("Edited text", message.getText()); assertEquals("Edited text", message.getText());
assertChannelChat(message.getChat()); assertChannelChat(message.getChat());
assertFromUser(message.getFrom()); assertFromUser(message.getFrom());
} }
private void assertFromUser(User from) { private void assertFromUser(User from) {
Assert.assertNotNull(from); assertNotNull(from);
Assert.assertEquals((Integer) 1111111, from.getId()); assertEquals((Integer) 1111111, from.getId());
Assert.assertEquals("Test Lastname", from.getLastName()); assertEquals("Test Lastname", from.getLastName());
Assert.assertEquals("Test Firstname", from.getFirstName()); assertEquals("Test Firstname", from.getFirstName());
Assert.assertEquals("Testusername", from.getUserName()); assertEquals("Testusername", from.getUserName());
} }
private void assertChannelChat(Chat chat) { private void assertChannelChat(Chat chat) {
Assert.assertNotNull(chat); assertNotNull(chat);
Assert.assertEquals(Long.valueOf(-10000000000L), chat.getId()); assertEquals(Long.valueOf(-10000000000L), chat.getId());
Assert.assertTrue(chat.isChannelChat()); assertTrue(chat.isChannelChat());
Assert.assertEquals("Test channel", chat.getTitle()); assertEquals("Test channel", chat.getTitle());
} }
} }

View File

@ -1,46 +1,47 @@
package org.telegram.telegrambots.meta.test; package org.telegram.telegrambots.meta.test;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.telegram.telegrambots.meta.TelegramBotsApi; import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.test.base.TestBase;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.meta.test.base.TestBase;
import static org.junit.jupiter.api.Assertions.fail;
/** /**
* @author Ruben Bermudez * @author Ruben Bermudez
* @version 1.0 * @version 1.0
*/ */
public class TestTelegramApi extends TestBase { class TestTelegramApi extends TestBase {
@Test @Test
public void TestTelegramApiMustBeInitializableForLongPolling() { void TestTelegramApiMustBeInitializableForLongPolling() {
new TelegramBotsApi(); new TelegramBotsApi();
} }
@Test @Test
public void TestTelegramApiMustBeInitializableForWebhookWithoutSecureSupport() { void TestTelegramApiMustBeInitializableForWebhookWithoutSecureSupport() {
try { try {
new TelegramBotsApi("externalUrl", "internalUrl"); new TelegramBotsApi("externalUrl", "internalUrl");
} catch (TelegramApiRequestException e) { } catch (TelegramApiRequestException e) {
Assert.fail(); fail();
} }
} }
@Test @Test
public void TestTelegramApiMustBeInitializableForWebhook() { void TestTelegramApiMustBeInitializableForWebhook() {
try { try {
new TelegramBotsApi("keyStore", "keyStorePassword", "externalUrl", "internalUrl"); new TelegramBotsApi("keyStore", "keyStorePassword", "externalUrl", "internalUrl");
} catch (TelegramApiRequestException e) { } catch (TelegramApiRequestException e) {
Assert.fail(); fail();
} }
} }
@Test @Test
public void TestTelegramApiMustBeInitializableForWebhookWithSelfSignedCertificate() { void TestTelegramApiMustBeInitializableForWebhookWithSelfSignedCertificate() {
try { try {
new TelegramBotsApi("keyStore", "keyStorePassword", "externalUrl", "internalUrl", "selfSignedPath"); new TelegramBotsApi("keyStore", "keyStorePassword", "externalUrl", "internalUrl", "selfSignedPath");
} catch (TelegramApiRequestException e) { } catch (TelegramApiRequestException e) {
Assert.fail(); fail();
} }
} }
} }

View File

@ -1,56 +1,57 @@
package org.telegram.telegrambots.meta.test.apimethods; package org.telegram.telegrambots.meta.test.apimethods;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.telegram.telegrambots.meta.api.methods.AnswerInlineQuery; import org.telegram.telegrambots.meta.api.methods.AnswerInlineQuery;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
import java.util.ArrayList; import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.assertEquals;
/** /**
* @author Ruben Bermudez * @author Ruben Bermudez
* @version 1.0 * @version 1.0
*/ */
public class TestAnswerInlineQuery { class TestAnswerInlineQuery {
private AnswerInlineQuery answerInlineQuery; private AnswerInlineQuery answerInlineQuery;
@Before @BeforeEach
public void setUp() throws Exception { void setUp() {
answerInlineQuery = new AnswerInlineQuery(); answerInlineQuery = new AnswerInlineQuery();
} }
@Test @Test
public void TestInlineQueryIdMustBePresent() throws Exception { void TestInlineQueryIdMustBePresent() {
try { try {
answerInlineQuery.validate(); answerInlineQuery.validate();
} catch (TelegramApiValidationException e) { } catch (TelegramApiValidationException e) {
Assert.assertEquals("InlineQueryId can't be empty", e.getMessage()); assertEquals("InlineQueryId can't be empty", e.getMessage());
} }
} }
@Test @Test
public void TestInlineQueryIdCanNotBeEmpty() throws Exception { void TestInlineQueryIdCanNotBeEmpty() {
answerInlineQuery.setInlineQueryId(""); answerInlineQuery.setInlineQueryId("");
try { try {
answerInlineQuery.validate(); answerInlineQuery.validate();
} catch (TelegramApiValidationException e) { } catch (TelegramApiValidationException e) {
Assert.assertEquals("InlineQueryId can't be empty", e.getMessage()); assertEquals("InlineQueryId can't be empty", e.getMessage());
} }
} }
@Test @Test
public void TestResultsMustBePresent() throws Exception { void TestResultsMustBePresent() {
answerInlineQuery.setInlineQueryId("RANDOMEID"); answerInlineQuery.setInlineQueryId("RANDOMEID");
try { try {
answerInlineQuery.validate(); answerInlineQuery.validate();
} catch (TelegramApiValidationException e) { } catch (TelegramApiValidationException e) {
Assert.assertEquals("Results array can't be null", e.getMessage()); assertEquals("Results array can't be null", e.getMessage());
} }
} }
@Test @Test
public void TestSwitchPmTextCanNotBeEmpty() throws Exception { void TestSwitchPmTextCanNotBeEmpty() {
answerInlineQuery.setInlineQueryId("RANDOMEID"); answerInlineQuery.setInlineQueryId("RANDOMEID");
answerInlineQuery.setResults(new ArrayList<>()); answerInlineQuery.setResults(new ArrayList<>());
answerInlineQuery.setSwitchPmText(""); answerInlineQuery.setSwitchPmText("");
@ -58,12 +59,12 @@ public class TestAnswerInlineQuery {
try { try {
answerInlineQuery.validate(); answerInlineQuery.validate();
} catch (TelegramApiValidationException e) { } catch (TelegramApiValidationException e) {
Assert.assertEquals("SwitchPmText can't be empty", e.getMessage()); assertEquals("SwitchPmText can't be empty", e.getMessage());
} }
} }
@Test @Test
public void TestSwitchPmParameterIsMandatoryIfSwitchPmTextIsPresent() throws Exception { void TestSwitchPmParameterIsMandatoryIfSwitchPmTextIsPresent() {
answerInlineQuery.setInlineQueryId("RANDOMEID"); answerInlineQuery.setInlineQueryId("RANDOMEID");
answerInlineQuery.setResults(new ArrayList<>()); answerInlineQuery.setResults(new ArrayList<>());
answerInlineQuery.setSwitchPmText("Test Text"); answerInlineQuery.setSwitchPmText("Test Text");
@ -71,12 +72,12 @@ public class TestAnswerInlineQuery {
try { try {
answerInlineQuery.validate(); answerInlineQuery.validate();
} catch (TelegramApiValidationException e) { } catch (TelegramApiValidationException e) {
Assert.assertEquals("SwitchPmParameter can't be empty if switchPmText is present", e.getMessage()); assertEquals("SwitchPmParameter can't be empty if switchPmText is present", e.getMessage());
} }
} }
@Test @Test
public void TestSwitchPmParameterCanNotBeEmptyIfSwitchPmTextIsPresent() throws Exception { void TestSwitchPmParameterCanNotBeEmptyIfSwitchPmTextIsPresent() {
answerInlineQuery.setInlineQueryId("RANDOMEID"); answerInlineQuery.setInlineQueryId("RANDOMEID");
answerInlineQuery.setResults(new ArrayList<>()); answerInlineQuery.setResults(new ArrayList<>());
answerInlineQuery.setSwitchPmText("Test Text"); answerInlineQuery.setSwitchPmText("Test Text");
@ -85,12 +86,12 @@ public class TestAnswerInlineQuery {
try { try {
answerInlineQuery.validate(); answerInlineQuery.validate();
} catch (TelegramApiValidationException e) { } catch (TelegramApiValidationException e) {
Assert.assertEquals("SwitchPmParameter can't be empty if switchPmText is present", e.getMessage()); assertEquals("SwitchPmParameter can't be empty if switchPmText is present", e.getMessage());
} }
} }
@Test @Test
public void TestSwitchPmParameterContainsUpTo64Chars() throws Exception { void TestSwitchPmParameterContainsUpTo64Chars() {
answerInlineQuery.setInlineQueryId("RANDOMEID"); answerInlineQuery.setInlineQueryId("RANDOMEID");
answerInlineQuery.setResults(new ArrayList<>()); answerInlineQuery.setResults(new ArrayList<>());
answerInlineQuery.setSwitchPmText("Test Text"); answerInlineQuery.setSwitchPmText("Test Text");
@ -99,12 +100,12 @@ public class TestAnswerInlineQuery {
try { try {
answerInlineQuery.validate(); answerInlineQuery.validate();
} catch (TelegramApiValidationException e) { } catch (TelegramApiValidationException e) {
Assert.assertEquals("SwitchPmParameter can't be longer than 64 chars", e.getMessage()); assertEquals("SwitchPmParameter can't be longer than 64 chars", e.getMessage());
} }
} }
@Test @Test
public void TestSwitchPmParameterOnlyContainsAcceptedCharacters() throws Exception { void TestSwitchPmParameterOnlyContainsAcceptedCharacters() {
answerInlineQuery.setInlineQueryId("RANDOMEID"); answerInlineQuery.setInlineQueryId("RANDOMEID");
answerInlineQuery.setResults(new ArrayList<>()); answerInlineQuery.setResults(new ArrayList<>());
answerInlineQuery.setSwitchPmText("Test Text"); answerInlineQuery.setSwitchPmText("Test Text");
@ -113,7 +114,7 @@ public class TestAnswerInlineQuery {
try { try {
answerInlineQuery.validate(); answerInlineQuery.validate();
} catch (TelegramApiValidationException e) { } catch (TelegramApiValidationException e) {
Assert.assertEquals("SwitchPmParameter only allows A-Z, a-z, 0-9, _ and - characters", e.getMessage()); assertEquals("SwitchPmParameter only allows A-Z, a-z, 0-9, _ and - characters", e.getMessage());
} }
} }
} }

View File

@ -2,27 +2,29 @@ package org.telegram.telegrambots.meta.test.apimethods;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.telegram.telegrambots.meta.test.TelegramBotsHelper;
import org.telegram.telegrambots.meta.api.methods.updates.GetUpdates; import org.telegram.telegrambots.meta.api.methods.updates.GetUpdates;
import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.meta.test.TelegramBotsHelper;
import java.util.ArrayList; import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/** /**
* @author Ruben Bermudez * @author Ruben Bermudez
* @version 1.0 * @version 1.0
*/ */
public class TestGetUpdates { class TestGetUpdates {
private GetUpdates getUpdates; private GetUpdates getUpdates;
private ObjectMapper mapper = new ObjectMapper(); private ObjectMapper mapper = new ObjectMapper();
@Before @BeforeEach
public void setUp() throws Exception { void setUp() {
getUpdates = new GetUpdates(); getUpdates = new GetUpdates();
getUpdates.setOffset(15); getUpdates.setOffset(15);
getUpdates.setTimeout(50); getUpdates.setTimeout(50);
@ -30,28 +32,28 @@ public class TestGetUpdates {
} }
@Test @Test
public void TestGetUpdatesMustBeSerializable() throws Exception { void TestGetUpdatesMustBeSerializable() throws Exception {
String json = mapper.writeValueAsString(getUpdates); String json = mapper.writeValueAsString(getUpdates);
Assert.assertNotNull(json); assertNotNull(json);
Assert.assertEquals("{\"offset\":15,\"limit\":100,\"timeout\":50,\"method\":\"getupdates\"}", json); assertEquals("{\"offset\":15,\"limit\":100,\"timeout\":50,\"method\":\"getupdates\"}", json);
} }
@Test @Test
public void TestGetUpdatesMustDeserializeCorrectResponse() throws Exception { void TestGetUpdatesMustDeserializeCorrectResponse() throws Exception {
ArrayList<Update> result = ArrayList<Update> result =
getUpdates.deserializeResponse(TelegramBotsHelper.GetResponseWithoutError()); getUpdates.deserializeResponse(TelegramBotsHelper.GetResponseWithoutError());
Assert.assertNotNull(result); assertNotNull(result);
Assert.assertEquals(1, result.size()); assertEquals(1, result.size());
} }
@Test @Test
public void TestGetUpdatesMustThrowAnExceptionForInCorrectResponse() { void TestGetUpdatesMustThrowAnExceptionForInCorrectResponse() {
try { try {
getUpdates.deserializeResponse(TelegramBotsHelper.GetResponseWithError()); getUpdates.deserializeResponse(TelegramBotsHelper.GetResponseWithError());
} catch (TelegramApiRequestException e) { } catch (TelegramApiRequestException e) {
Assert.assertNotNull(e.getParameters()); assertNotNull(e.getParameters());
Assert.assertEquals(Integer.valueOf(400), e.getErrorCode()); assertEquals(Integer.valueOf(400), e.getErrorCode());
Assert.assertEquals("Error descriptions", e.getApiResponse()); assertEquals("Error descriptions", e.getApiResponse());
} }
} }
} }

View File

@ -2,26 +2,29 @@ package org.telegram.telegrambots.meta.test.apimethods;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.telegram.telegrambots.meta.test.TelegramBotsHelper;
import org.telegram.telegrambots.meta.api.methods.games.SetGameScore; import org.telegram.telegrambots.meta.api.methods.games.SetGameScore;
import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.test.TelegramBotsHelper;
import java.io.Serializable; import java.io.Serializable;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** /**
* @author Ruben Bermudez * @author Ruben Bermudez
* @version 1.0 * @version 1.0
*/ */
public class TestSetGameScore { class TestSetGameScore {
private SetGameScore setGameScore; private SetGameScore setGameScore;
private ObjectMapper mapper = new ObjectMapper(); private ObjectMapper mapper = new ObjectMapper();
@Before @BeforeEach
public void setUp() throws Exception { void setUp() {
setGameScore = new SetGameScore(); setGameScore = new SetGameScore();
setGameScore.setChatId("12345"); setGameScore.setChatId("12345");
setGameScore.setDisableEditMessage(true); setGameScore.setDisableEditMessage(true);
@ -31,25 +34,25 @@ public class TestSetGameScore {
} }
@Test @Test
public void TestGetUpdatesMustBeSerializable() throws Exception { void TestGetUpdatesMustBeSerializable() throws Exception {
String json = mapper.writeValueAsString(setGameScore); String json = mapper.writeValueAsString(setGameScore);
Assert.assertNotNull(json); assertNotNull(json);
Assert.assertEquals("{\"chat_id\":\"12345\",\"message_id\":54321,\"disable_edit_message\":true,\"user_id\":98765,\"score\":12,\"method\":\"setGameScore\"}", json); assertEquals("{\"chat_id\":\"12345\",\"message_id\":54321,\"disable_edit_message\":true,\"user_id\":98765,\"score\":12,\"method\":\"setGameScore\"}", json);
} }
@Test @Test
public void TestGetUpdatesMustDeserializeCorrectResponse() throws Exception { void TestGetUpdatesMustDeserializeCorrectResponse() throws Exception {
Serializable result = Serializable result =
setGameScore.deserializeResponse(TelegramBotsHelper.GetSetGameScoreBooleanResponse()); setGameScore.deserializeResponse(TelegramBotsHelper.GetSetGameScoreBooleanResponse());
Assert.assertNotNull(result); assertNotNull(result);
Assert.assertTrue(result instanceof Boolean); assertTrue(result instanceof Boolean);
Assert.assertTrue((Boolean) result); assertTrue((Boolean) result);
} }
@Test @Test
public void TestGetUpdatesMustThrowAnExceptionForInCorrectResponse() throws Exception { void TestGetUpdatesMustThrowAnExceptionForInCorrectResponse() throws Exception {
Serializable result = setGameScore.deserializeResponse(TelegramBotsHelper.GetSetGameScoreMessageResponse()); Serializable result = setGameScore.deserializeResponse(TelegramBotsHelper.GetSetGameScoreMessageResponse());
Assert.assertNotNull(result); assertNotNull(result);
Assert.assertTrue(result instanceof Message); assertTrue(result instanceof Message);
} }
} }

View File

@ -1,11 +1,11 @@
package org.telegram.telegrambots.meta.test.base; package org.telegram.telegrambots.meta.test.base;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeAll;
import org.telegram.telegrambots.meta.ApiContext; import org.telegram.telegrambots.meta.ApiContext;
import org.telegram.telegrambots.meta.test.fakes.FakeBotSession;
import org.telegram.telegrambots.meta.test.fakes.FakeWebhook;
import org.telegram.telegrambots.meta.generics.BotSession; import org.telegram.telegrambots.meta.generics.BotSession;
import org.telegram.telegrambots.meta.generics.Webhook; import org.telegram.telegrambots.meta.generics.Webhook;
import org.telegram.telegrambots.meta.test.fakes.FakeBotSession;
import org.telegram.telegrambots.meta.test.fakes.FakeWebhook;
/** /**
* @author Ruben Bermudez * @author Ruben Bermudez
@ -13,7 +13,7 @@ import org.telegram.telegrambots.meta.generics.Webhook;
*/ */
public abstract class TestBase { public abstract class TestBase {
@BeforeClass @BeforeAll
public static void beforeClass() { public static void beforeClass() {
ApiContext.register(BotSession.class, FakeBotSession.class); ApiContext.register(BotSession.class, FakeBotSession.class);
ApiContext.register(Webhook.class, FakeWebhook.class); ApiContext.register(Webhook.class, FakeWebhook.class);

View File

@ -3,9 +3,15 @@
xmlns="http://maven.apache.org/POM/4.0.0" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.telegram</groupId> <groupId>org.telegram</groupId>
<artifactId>telegrambots-spring-boot-starter</artifactId> <artifactId>Bots</artifactId>
<version>4.3.1</version> <version>4.3.1</version>
</parent>
<artifactId>telegrambots-spring-boot-starter</artifactId>
<version>${project.parent.version}</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>Telegram Bots Spring Boot Starter</name> <name>Telegram Bots Spring Boot Starter</name>
@ -57,9 +63,14 @@
</distributionManagement> </distributionManagement>
<properties> <properties>
<java.version>11</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.0.2.RELEASE</spring-boot.version>
<spring-boot.version>2.1.6.RELEASE</spring-boot.version>
</properties> </properties>
<dependencies> <dependencies>
@ -92,23 +103,8 @@
<groupId>org.assertj</groupId> <groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId> <artifactId>assertj-core</artifactId>
<scope>test</scope> <scope>test</scope>
<version>3.9.1</version> <version>3.12.2</version>
</dependency> </dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>2.0.2-beta</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -121,7 +117,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId> <artifactId>maven-gpg-plugin</artifactId>
<version>1.5</version> <version>1.6</version>
<executions> <executions>
<execution> <execution>
<id>sign-artifacts</id> <id>sign-artifacts</id>
@ -135,7 +131,7 @@
<plugin> <plugin>
<groupId>org.sonatype.plugins</groupId> <groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId> <artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.3</version> <version>1.6.8</version>
<extensions>true</extensions> <extensions>true</extensions>
<configuration> <configuration>
<serverId>ossrh</serverId> <serverId>ossrh</serverId>
@ -145,7 +141,7 @@
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-clean-plugin</artifactId> <artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version> <version>3.1.0</version>
<executions> <executions>
<execution> <execution>
<id>clean-project</id> <id>clean-project</id>
@ -158,7 +154,7 @@
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-assembly-plugin</artifactId> <artifactId>maven-assembly-plugin</artifactId>
<version>2.6</version> <version>3.1.1</version>
<configuration> <configuration>
<descriptorRefs> <descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef> <descriptorRef>jar-with-dependencies</descriptorRef>
@ -177,7 +173,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId> <artifactId>maven-source-plugin</artifactId>
<version>3.0.0</version> <version>3.1.0</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
@ -189,14 +185,14 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId> <artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.3</version> <version>3.1.0</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
<goal>jar</goal> <goal>jar</goal>
</goals> </goals>
<configuration> <configuration>
<additionalparam>-Xdoclint:none</additionalparam> <doclint>none</doclint>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
@ -204,7 +200,7 @@
<plugin> <plugin>
<groupId>org.jacoco</groupId> <groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId> <artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.7.201606060606</version> <version>0.8.4</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
@ -223,7 +219,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId> <artifactId>maven-enforcer-plugin</artifactId>
<version>1.4.1</version> <version>3.0.0-M2</version>
<executions> <executions>
<execution> <execution>
<id>enforce-versions</id> <id>enforce-versions</id>
@ -241,7 +237,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId> <artifactId>maven-dependency-plugin</artifactId>
<version>2.4</version> <version>3.1.1</version>
<executions> <executions>
<execution> <execution>
<id>copy</id> <id>copy</id>
@ -249,15 +245,21 @@
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M3</version>
</plugin>
</plugins> </plugins>
<pluginManagement> <pluginManagement>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration> <configuration>
<source>1.8</source> <source>${java.version}</source>
<target>1.8</target> <target>${java.version}</target>
<encoding>UTF-8</encoding> <encoding>UTF-8</encoding>
</configuration> </configuration>
</plugin> </plugin>

View File

@ -3,9 +3,15 @@
xmlns="http://maven.apache.org/POM/4.0.0" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.telegram</groupId> <groupId>org.telegram</groupId>
<artifactId>telegrambots</artifactId> <artifactId>Bots</artifactId>
<version>4.3.1</version> <version>4.3.1</version>
</parent>
<artifactId>telegrambots</artifactId>
<version>${project.parent.version}</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>Telegram Bots</name> <name>Telegram Bots</name>
@ -57,15 +63,20 @@
</distributionManagement> </distributionManagement>
<properties> <properties>
<java.version>11</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<glassfish.version>2.25.1</glassfish.version>
<glassfish.version>2.29</glassfish.version>
<jerseybundle.version>1.19.3</jerseybundle.version> <jerseybundle.version>1.19.3</jerseybundle.version>
<httpcompontents.version>4.5.3</httpcompontents.version> <httpcompontents.version>4.5.9</httpcompontents.version>
<json.version>20180813</json.version> <json.version>20180813</json.version>
<jackson.version>2.9.9</jackson.version> <jackson.version>2.9.9</jackson.version>
<jacksonanotation.version>2.9.0</jacksonanotation.version> <jacksonanotation.version>2.9.9</jacksonanotation.version>
<commonio.version>2.5</commonio.version> <commonio.version>2.6</commonio.version>
</properties> </properties>
<dependencyManagement> <dependencyManagement>
@ -96,26 +107,21 @@
<artifactId>jackson-jaxrs-json-provider</artifactId> <artifactId>jackson-jaxrs-json-provider</artifactId>
<version>${jackson.version}</version> <version>${jackson.version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
<version>2.9.9</version>
</dependency>
<dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId> <groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId> <artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version> <version>${jackson.version}</version>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.glassfish.jersey.media</groupId> <groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId> <artifactId>jersey-media-json-jackson</artifactId>
<version>${glassfish.version}</version> <version>${glassfish.version}</version>
<exclusions> <exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</exclusion>
<exclusion> <exclusion>
<groupId>com.fasterxml.jackson.jaxrs</groupId> <groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId> <artifactId>jackson-jaxrs-json-provider</artifactId>
@ -169,12 +175,6 @@
<version>${glassfish.version}</version> <version>${glassfish.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>2.0.2-beta</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -184,10 +184,15 @@
<testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory> <testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory> <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
<plugins> <plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M3</version>
</plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId> <artifactId>maven-gpg-plugin</artifactId>
<version>1.5</version> <version>1.6</version>
<executions> <executions>
<execution> <execution>
<id>sign-artifacts</id> <id>sign-artifacts</id>
@ -201,7 +206,7 @@
<plugin> <plugin>
<groupId>org.sonatype.plugins</groupId> <groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId> <artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.3</version> <version>1.6.8</version>
<extensions>true</extensions> <extensions>true</extensions>
<configuration> <configuration>
<serverId>ossrh</serverId> <serverId>ossrh</serverId>
@ -211,7 +216,7 @@
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-clean-plugin</artifactId> <artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version> <version>3.1.0</version>
<executions> <executions>
<execution> <execution>
<id>clean-project</id> <id>clean-project</id>
@ -224,7 +229,7 @@
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-assembly-plugin</artifactId> <artifactId>maven-assembly-plugin</artifactId>
<version>2.6</version> <version>3.1.1</version>
<configuration> <configuration>
<descriptorRefs> <descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef> <descriptorRef>jar-with-dependencies</descriptorRef>
@ -243,7 +248,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId> <artifactId>maven-source-plugin</artifactId>
<version>3.0.0</version> <version>3.1.0</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
@ -255,14 +260,14 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId> <artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.3</version> <version>3.1.0</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
<goal>jar</goal> <goal>jar</goal>
</goals> </goals>
<configuration> <configuration>
<additionalparam>-Xdoclint:none</additionalparam> <doclint>none</doclint>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
@ -270,7 +275,7 @@
<plugin> <plugin>
<groupId>org.jacoco</groupId> <groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId> <artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.7.201606060606</version> <version>0.8.4</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
@ -289,7 +294,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId> <artifactId>maven-enforcer-plugin</artifactId>
<version>1.4.1</version> <version>3.0.0-M2</version>
<executions> <executions>
<execution> <execution>
<id>enforce-versions</id> <id>enforce-versions</id>
@ -307,7 +312,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId> <artifactId>maven-dependency-plugin</artifactId>
<version>2.4</version> <version>3.1.1</version>
<executions> <executions>
<execution> <execution>
<id>copy</id> <id>copy</id>
@ -321,9 +326,10 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration> <configuration>
<source>1.8</source> <source>${java.version}</source>
<target>1.8</target> <target>${java.version}</target>
<encoding>UTF-8</encoding> <encoding>UTF-8</encoding>
</configuration> </configuration>
</plugin> </plugin>

View File

@ -4,7 +4,6 @@ package org.telegram.telegrambots.facilities.proxysocketfactorys;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpContext;
import sun.net.SocksProxy;
import java.io.IOException; import java.io.IOException;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
@ -14,10 +13,9 @@ import java.net.Socket;
public class SocksConnectionSocketFactory extends PlainConnectionSocketFactory { public class SocksConnectionSocketFactory extends PlainConnectionSocketFactory {
@Override @Override
public Socket createSocket(final HttpContext context) throws IOException { public Socket createSocket(final HttpContext context) {
InetSocketAddress socksaddr = (InetSocketAddress) context.getAttribute("socketAddress"); InetSocketAddress socksaddr = (InetSocketAddress) context.getAttribute("socketAddress");
int socksVersion = (Integer) context.getAttribute("socksVersion"); Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksaddr);
Proxy proxy = SocksProxy.create(socksaddr, socksVersion);
return new Socket(proxy); return new Socket(proxy);
} }

View File

@ -4,14 +4,14 @@ import org.apache.http.HttpHost;
import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpContext;
import sun.net.SocksProxy;
import javax.net.ssl.SSLContext;
import java.io.IOException; import java.io.IOException;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.Proxy; import java.net.Proxy;
import java.net.Socket; import java.net.Socket;
import javax.net.ssl.SSLContext;
public class SocksSSLConnectionSocketFactory extends SSLConnectionSocketFactory { public class SocksSSLConnectionSocketFactory extends SSLConnectionSocketFactory {
@ -20,10 +20,9 @@ public class SocksSSLConnectionSocketFactory extends SSLConnectionSocketFactory
} }
@Override @Override
public Socket createSocket(final HttpContext context) throws IOException { public Socket createSocket(final HttpContext context) {
InetSocketAddress socksaddr = (InetSocketAddress) context.getAttribute("socketAddress"); InetSocketAddress socksaddr = (InetSocketAddress) context.getAttribute("socketAddress");
int socksVersion = (Integer) context.getAttribute("socksVersion"); Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksaddr);
Proxy proxy = SocksProxy.create(socksaddr, socksVersion);
return new Socket(proxy); return new Socket(proxy);
} }