From b6ebac703c457d0d304fad077f2dab1128a35075 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C3=ADas=20J=2E=20Schilling?= Date: Wed, 19 Jun 2024 10:08:55 +0200 Subject: [PATCH] Add spotless check --- .github/workflows/build.yml | 2 +- build.gradle | 137 +- settings.gradle | 2 +- .../java/io/chucknorris/api/Application.java | 4 +- .../api/ApplicationExceptionHandler.java | 20 +- .../AmazonWebServicesConfig.java | 11 +- .../CrossOriginResourceSharingConfig.java | 6 +- .../DataSourceConfiguration.java | 31 +- .../configuration/DataSourceProperties.java | 8 +- .../DefaultDataSourceProperties.java | 29 +- .../HerokuDataSourceProperties.java | 68 +- .../api/configuration/LayoutConfig.java | 8 +- .../api/configuration/MailchimpConfig.java | 8 +- .../api/configuration/RestTemplateConfig.java | 6 +- .../chucknorris/api/feed/FeedController.java | 24 +- .../api/feed/dailychuck/DailyChuck.java | 13 +- .../api/feed/dailychuck/DailyChuckRss.java | 29 +- .../feed/dailychuck/DailyChuckService.java | 9 +- .../chucknorris/api/home/HomeController.java | 11 +- .../java/io/chucknorris/api/joke/Joke.java | 9 +- .../chucknorris/api/joke/JokeController.java | 92 +- .../chucknorris/api/joke/JokeRepository.java | 143 +- .../chucknorris/api/joke/JokeSerializer.java | 9 +- .../io/chucknorris/api/joke/JokeService.java | 38 +- .../api/postcard/PostcardController.java | 4 +- .../api/privacy/PrivacyController.java | 7 +- .../io/chucknorris/api/slack/AccessToken.java | 2 +- .../api/slack/CommandResponseAttachment.java | 2 +- .../java/io/chucknorris/api/slack/Help.java | 36 +- .../io/chucknorris/api/slack/Request.java | 9 +- .../api/slack/RequestArgumentResolver.java | 3 +- .../api/slack/SlackController.java | 158 ++- .../chucknorris/api/slack/SlackService.java | 54 +- .../chucknorris/lib/event/EventService.java | 13 +- .../lib/mailchimp/MailchimpService.java | 15 +- .../lib/mailchimp/MailingList.java | 1 - .../HerokuDataSourcePropertiesTest.java | 37 +- .../api/feed/FeedControllerTest.java | 289 ++--- .../feed/dailychuck/DailyChuckRssTest.java | 4 +- .../api/feed/dailychuck/DailyChuckTest.java | 74 +- .../api/joke/JokeControllerTest.java | 142 +- .../chucknorris/api/joke/JokeServiceTest.java | 44 +- .../api/slack/SlackControllerTest.java | 1145 ++++++++--------- .../api/slack/SlackServiceTest.java | 187 ++- .../lib/event/EventServiceTest.java | 10 +- 45 files changed, 1344 insertions(+), 1609 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index a5b1d0b..804430c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -23,4 +23,4 @@ jobs: distribution: ${{ env.JAVA_DISTRIBUTION }} java-version: ${{ env.JAVA_VERSION }} ref: ${{ inputs.version }} - - run: ./gradlew test \ No newline at end of file + - run: ./gradlew test spotlessCheck \ No newline at end of file diff --git a/build.gradle b/build.gradle index 4fb3238..c46114e 100644 --- a/build.gradle +++ b/build.gradle @@ -1,19 +1,20 @@ plugins { - id 'com.palantir.docker' version '0.36.0' - id 'io.spring.dependency-management' version '1.1.5' - id 'java' - id 'org.springframework.boot' version '2.7.18' + id 'com.diffplug.spotless' version '7.0.0.BETA1' + id 'com.palantir.docker' version '0.36.0' + id 'io.spring.dependency-management' version '1.1.5' + id 'java' + id 'org.springframework.boot' version '2.7.18' } def gitRev = { -> - def stdout = new ByteArrayOutputStream() + def stdout = new ByteArrayOutputStream() - exec { - commandLine 'git', 'rev-parse', 'HEAD' - standardOutput = stdout - } + exec { + commandLine 'git', 'rev-parse', 'HEAD' + standardOutput = stdout + } - return stdout.toString().trim() + return stdout.toString().trim() } String appName = "api" @@ -24,68 +25,74 @@ version = appVer java.sourceCompatibility = JavaVersion.VERSION_17 repositories { - mavenCentral() + mavenCentral() } // versions def lombokVersion = "1.18.30" dependencies { - annotationProcessor "org.projectlombok:lombok:${lombokVersion}" - - implementation "com.amazonaws:aws-java-sdk:1.11.561" - implementation "com.fasterxml.jackson.core:jackson-core:2.17.1" - implementation "com.rometools:rome:1.12.0" - implementation "com.vladmihalcea:hibernate-types-52:2.4.0" - implementation "nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect:2.3.0" - implementation "org.hibernate:hibernate-validator:6.0.16.Final" - implementation "org.postgresql:postgresql:42.2.9" - implementation "org.projectlombok:lombok:${lombokVersion}" - implementation "org.springframework.boot:spring-boot-starter-data-jpa" - implementation "org.springframework.boot:spring-boot-starter-thymeleaf" - implementation "org.springframework.boot:spring-boot-starter-web" - implementation 'com.google.guava:guava:33.2.1-jre' - - testImplementation "org.springframework.boot:spring-boot-starter-test" - testImplementation 'junit:junit:4.12' + annotationProcessor "org.projectlombok:lombok:${lombokVersion}" + + implementation "com.amazonaws:aws-java-sdk:1.11.561" + implementation "com.fasterxml.jackson.core:jackson-core:2.17.1" + implementation "com.rometools:rome:1.12.0" + implementation "com.vladmihalcea:hibernate-types-52:2.4.0" + implementation "nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect:2.3.0" + implementation "org.hibernate:hibernate-validator:6.0.16.Final" + implementation "org.postgresql:postgresql:42.2.9" + implementation "org.projectlombok:lombok:${lombokVersion}" + implementation "org.springframework.boot:spring-boot-starter-data-jpa" + implementation "org.springframework.boot:spring-boot-starter-thymeleaf" + implementation "org.springframework.boot:spring-boot-starter-web" + implementation 'com.google.guava:guava:33.2.1-jre' + + testImplementation "org.springframework.boot:spring-boot-starter-test" + testImplementation 'junit:junit:4.12' } tasks { - bootJar { - manifest.attributes( - 'Multi-Release': 'true' - ) - - archiveBaseName.set(appName) - archiveVersion.set(appVer) - - if (project.hasProperty("archiveName")) { - archiveFileName.set(project.properties["archiveName"] as String) - } - } - - docker { - dependsOn bootJar - - def imageName = "${project.properties.group}/${appName}" - name = "${imageName}:latest" - - tag("current", "${imageName}:${appVer}") - tag("latest", "${imageName}:latest") - tag("herokuProduction", "registry.heroku.com/chucky/web") - - dockerfile file("${projectDir}/src/main/docker/Dockerfile") - files tasks.bootJar.outputs - buildArgs([JAR_FILE: bootJar.getArchiveFileName().get()]) - } - - springBoot { - buildInfo { - properties { - artifact = "${appName}-${appVer}.jar" - version = appVer - name = appName - } - } - } + bootJar { + manifest.attributes( + 'Multi-Release': 'true' + ) + + archiveBaseName.set(appName) + archiveVersion.set(appVer) + + if (project.hasProperty("archiveName")) { + archiveFileName.set(project.properties["archiveName"] as String) + } + } + + docker { + dependsOn bootJar + + def imageName = "${project.properties.group}/${appName}" + name = "${imageName}:latest" + + tag("current", "${imageName}:${appVer}") + tag("latest", "${imageName}:latest") + tag("herokuProduction", "registry.heroku.com/chucky/web") + + dockerfile file("${projectDir}/src/main/docker/Dockerfile") + files tasks.bootJar.outputs + buildArgs([JAR_FILE: bootJar.getArchiveFileName().get()]) + } + + springBoot { + buildInfo { + properties { + artifact = "${appName}-${appVer}.jar" + version = appVer + name = appName + } + } + } + + spotless { + java { + googleJavaFormat() + } + } } diff --git a/settings.gradle b/settings.gradle index dcf0d60..484b309 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1 +1 @@ -rootProject.name = 'io.chucknorris.api' \ No newline at end of file +rootProject.name = 'io.chucknorris.api' diff --git a/src/main/java/io/chucknorris/api/Application.java b/src/main/java/io/chucknorris/api/Application.java index a542457..5b6e859 100644 --- a/src/main/java/io/chucknorris/api/Application.java +++ b/src/main/java/io/chucknorris/api/Application.java @@ -5,9 +5,7 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; -@ComponentScan(basePackages = { - "io.chucknorris" -}) +@ComponentScan(basePackages = {"io.chucknorris"}) @EnableJpaAuditing @SpringBootApplication public class Application { diff --git a/src/main/java/io/chucknorris/api/ApplicationExceptionHandler.java b/src/main/java/io/chucknorris/api/ApplicationExceptionHandler.java index 24eb4c7..2419ec5 100644 --- a/src/main/java/io/chucknorris/api/ApplicationExceptionHandler.java +++ b/src/main/java/io/chucknorris/api/ApplicationExceptionHandler.java @@ -18,16 +18,13 @@ public class ApplicationExceptionHandler extends ResponseEntityExceptionHandler @ExceptionHandler(value = {ConstraintViolationException.class}) protected ResponseEntity handleConstraintViolationException( - ConstraintViolationException exception, ServletWebRequest request - ) { + ConstraintViolationException exception, ServletWebRequest request) { switch (request.getHeader(HttpHeaders.ACCEPT)) { case MediaType.TEXT_PLAIN_VALUE: StringBuilder stringBuilder = new StringBuilder(); for (ConstraintViolation violation : exception.getConstraintViolations()) { stringBuilder.append( - violation.getPropertyPath().toString() + ": " + violation.getMessage() - + '\n' - ); + violation.getPropertyPath().toString() + ": " + violation.getMessage() + '\n'); } return handleExceptionInternal( @@ -35,13 +32,11 @@ protected ResponseEntity handleConstraintViolationException( stringBuilder.toString(), new HttpHeaders(), HttpStatus.BAD_REQUEST, - request - ); + request); default: LinkedHashMap constraintViolations = new LinkedHashMap<>(); for (ConstraintViolation violation : exception.getConstraintViolations()) { - constraintViolations - .put(violation.getPropertyPath().toString(), violation.getMessage()); + constraintViolations.put(violation.getPropertyPath().toString(), violation.getMessage()); } LinkedHashMap body = new LinkedHashMap<>(); @@ -52,12 +47,7 @@ protected ResponseEntity handleConstraintViolationException( body.put("violations", constraintViolations); return handleExceptionInternal( - exception, - body, - new HttpHeaders(), - HttpStatus.BAD_REQUEST, - request - ); + exception, body, new HttpHeaders(), HttpStatus.BAD_REQUEST, request); } } } diff --git a/src/main/java/io/chucknorris/api/configuration/AmazonWebServicesConfig.java b/src/main/java/io/chucknorris/api/configuration/AmazonWebServicesConfig.java index ab592d4..54e495f 100644 --- a/src/main/java/io/chucknorris/api/configuration/AmazonWebServicesConfig.java +++ b/src/main/java/io/chucknorris/api/configuration/AmazonWebServicesConfig.java @@ -22,22 +22,17 @@ public class AmazonWebServicesConfig { @Value("${aws.region}") private String region; - /** - * Returns a new {@link AmazonS3} instance. - */ + /** Returns a new {@link AmazonS3} instance. */ public @Bean AmazonS3 amazonS3() { AWSCredentials credentials = new BasicAWSCredentials(accessKeyId, accessKeySecret); - return AmazonS3ClientBuilder - .standard() + return AmazonS3ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(credentials)) .withRegion(region) .build(); } - /** - * Returns a new {@link AmazonSNSClient} instance. - */ + /** Returns a new {@link AmazonSNSClient} instance. */ public @Bean AmazonSNSClient snsClient() { AWSCredentials credentials = new BasicAWSCredentials(accessKeyId, accessKeySecret); diff --git a/src/main/java/io/chucknorris/api/configuration/CrossOriginResourceSharingConfig.java b/src/main/java/io/chucknorris/api/configuration/CrossOriginResourceSharingConfig.java index 677796b..7307af0 100644 --- a/src/main/java/io/chucknorris/api/configuration/CrossOriginResourceSharingConfig.java +++ b/src/main/java/io/chucknorris/api/configuration/CrossOriginResourceSharingConfig.java @@ -10,9 +10,7 @@ @Configuration public class CrossOriginResourceSharingConfig { - /** - * Returns cors filter registration bean {@link CorsConfiguration}. - */ + /** Returns cors filter registration bean {@link CorsConfiguration}. */ public @Bean FilterRegistrationBean corsFilter() { CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); @@ -27,4 +25,4 @@ public class CrossOriginResourceSharingConfig { return bean; } -} \ No newline at end of file +} diff --git a/src/main/java/io/chucknorris/api/configuration/DataSourceConfiguration.java b/src/main/java/io/chucknorris/api/configuration/DataSourceConfiguration.java index b556bf4..f91d676 100644 --- a/src/main/java/io/chucknorris/api/configuration/DataSourceConfiguration.java +++ b/src/main/java/io/chucknorris/api/configuration/DataSourceConfiguration.java @@ -1,6 +1,7 @@ package io.chucknorris.api.configuration; import com.zaxxer.hikari.HikariDataSource; +import javax.sql.DataSource; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; @@ -8,28 +9,28 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.transaction.annotation.EnableTransactionManagement; -import javax.sql.DataSource; - @Configuration @EnableJpaRepositories(basePackages = "io.chucknorris") @EnableTransactionManagement @Slf4j public class DataSourceConfiguration { - @Bean - public DataSource dataSource(DataSourceProperties dataSourceProperties) { - log.info("Loading data source properties from {}", dataSourceProperties.getClass().getSimpleName()); + @Bean + public DataSource dataSource(DataSourceProperties dataSourceProperties) { + log.info( + "Loading data source properties from {}", dataSourceProperties.getClass().getSimpleName()); - DataSource datasource = DataSourceBuilder.create() - .driverClassName(dataSourceProperties.getDriverClassName()) - .password(dataSourceProperties.getPassword()) - .type(HikariDataSource.class) - .url(dataSourceProperties.getUrl()) - .username(dataSourceProperties.getUsername()) - .build(); + DataSource datasource = + DataSourceBuilder.create() + .driverClassName(dataSourceProperties.getDriverClassName()) + .password(dataSourceProperties.getPassword()) + .type(HikariDataSource.class) + .url(dataSourceProperties.getUrl()) + .username(dataSourceProperties.getUsername()) + .build(); - log.info(String.format("DataSource({url=%s})", dataSourceProperties.getUrl())); + log.info(String.format("DataSource({url=%s})", dataSourceProperties.getUrl())); - return datasource; - } + return datasource; + } } diff --git a/src/main/java/io/chucknorris/api/configuration/DataSourceProperties.java b/src/main/java/io/chucknorris/api/configuration/DataSourceProperties.java index e239a6b..5cd59dd 100644 --- a/src/main/java/io/chucknorris/api/configuration/DataSourceProperties.java +++ b/src/main/java/io/chucknorris/api/configuration/DataSourceProperties.java @@ -5,11 +5,11 @@ @Configuration public abstract class DataSourceProperties { - abstract String getDriverClassName(); + abstract String getDriverClassName(); - abstract String getPassword(); + abstract String getPassword(); - abstract String getUrl(); + abstract String getUrl(); - abstract String getUsername(); + abstract String getUsername(); } diff --git a/src/main/java/io/chucknorris/api/configuration/DefaultDataSourceProperties.java b/src/main/java/io/chucknorris/api/configuration/DefaultDataSourceProperties.java index e65b912..06b6138 100644 --- a/src/main/java/io/chucknorris/api/configuration/DefaultDataSourceProperties.java +++ b/src/main/java/io/chucknorris/api/configuration/DefaultDataSourceProperties.java @@ -12,20 +12,19 @@ @Getter public class DefaultDataSourceProperties extends DataSourceProperties { - private String driverClassName; - private String password; - private String url; - private String username; + private String driverClassName; + private String password; + private String url; + private String username; - public DefaultDataSourceProperties( - @Value("${spring.datasource.driver-class-name}") String driverClassName, - @Value("${spring.datasource.password}") String password, - @Value("${spring.datasource.url}") String url, - @Value("${spring.datasource.username}") String username - ) { - this.driverClassName = driverClassName; - this.password = password; - this.url = url; - this.username = username; - } + public DefaultDataSourceProperties( + @Value("${spring.datasource.driver-class-name}") String driverClassName, + @Value("${spring.datasource.password}") String password, + @Value("${spring.datasource.url}") String url, + @Value("${spring.datasource.username}") String username) { + this.driverClassName = driverClassName; + this.password = password; + this.url = url; + this.username = username; + } } diff --git a/src/main/java/io/chucknorris/api/configuration/HerokuDataSourceProperties.java b/src/main/java/io/chucknorris/api/configuration/HerokuDataSourceProperties.java index 8d8031b..4fbabfb 100644 --- a/src/main/java/io/chucknorris/api/configuration/HerokuDataSourceProperties.java +++ b/src/main/java/io/chucknorris/api/configuration/HerokuDataSourceProperties.java @@ -1,53 +1,49 @@ package io.chucknorris.api.configuration; +import java.net.URI; import lombok.Data; import lombok.Getter; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Configuration; -import java.net.URI; - @ConditionalOnProperty(prefix = "spring.datasource", name = "uri") @Configuration @Data @Getter public class HerokuDataSourceProperties extends DataSourceProperties { - private static final String SCHEMA_POSTGRESQL = "postgresql"; - - private String driverClassName; - private String password; - private String url; - private String username; - - public HerokuDataSourceProperties( - @Value("${spring.datasource.driver-class-name}") String driverClassName, - @Value("${spring.datasource.uri}") String uniformResourceIdentifier - ) { - URI uri = URI.create(uniformResourceIdentifier); - - String[] userInfo = uri.getUserInfo().split(":"); - - this.driverClassName = driverClassName; - this.password = userInfo[1]; - this.url = String.format( - "jdbc:%s://%s:%s/%s", - this.scheme(uri), - uri.getHost().replace("/", ""), - uri.getPort(), - uri.getPath().replace("/", "") - ); - this.username = userInfo[0]; + private static final String SCHEMA_POSTGRESQL = "postgresql"; + + private String driverClassName; + private String password; + private String url; + private String username; + + public HerokuDataSourceProperties( + @Value("${spring.datasource.driver-class-name}") String driverClassName, + @Value("${spring.datasource.uri}") String uniformResourceIdentifier) { + URI uri = URI.create(uniformResourceIdentifier); + + String[] userInfo = uri.getUserInfo().split(":"); + + this.driverClassName = driverClassName; + this.password = userInfo[1]; + this.url = + String.format( + "jdbc:%s://%s:%s/%s", + this.scheme(uri), + uri.getHost().replace("/", ""), + uri.getPort(), + uri.getPath().replace("/", "")); + this.username = userInfo[0]; + } + + private String scheme(URI uri) { + if ("postgres".compareToIgnoreCase(uri.getScheme()) == 0) { + return SCHEMA_POSTGRESQL; } - private String scheme(URI uri) { - if ("postgres".compareToIgnoreCase(uri.getScheme()) == 0) { - return SCHEMA_POSTGRESQL; - } - - throw new RuntimeException( - String.format("Unsupported schema %s given", uri.getScheme()) - ); - } + throw new RuntimeException(String.format("Unsupported schema %s given", uri.getScheme())); + } } diff --git a/src/main/java/io/chucknorris/api/configuration/LayoutConfig.java b/src/main/java/io/chucknorris/api/configuration/LayoutConfig.java index a622cf7..028b7ee 100644 --- a/src/main/java/io/chucknorris/api/configuration/LayoutConfig.java +++ b/src/main/java/io/chucknorris/api/configuration/LayoutConfig.java @@ -7,8 +7,8 @@ @Configuration public class LayoutConfig { - @Bean - public LayoutDialect layoutDialect() { - return new LayoutDialect(); - } + @Bean + public LayoutDialect layoutDialect() { + return new LayoutDialect(); + } } diff --git a/src/main/java/io/chucknorris/api/configuration/MailchimpConfig.java b/src/main/java/io/chucknorris/api/configuration/MailchimpConfig.java index 5462f05..b52e285 100644 --- a/src/main/java/io/chucknorris/api/configuration/MailchimpConfig.java +++ b/src/main/java/io/chucknorris/api/configuration/MailchimpConfig.java @@ -11,13 +11,9 @@ public class MailchimpConfig { @Value("${mailchimp.api_key}") private String apiKey; - /** - * Returns a new {@link MailchimpService} instance. - */ + /** Returns a new {@link MailchimpService} instance. */ public @Bean MailchimpService mailchimpService() { - String dataCenter = apiKey.substring( - apiKey.length() - 4 - ); + String dataCenter = apiKey.substring(apiKey.length() - 4); String baseUrl = "https://" + dataCenter + ".api.mailchimp.com"; return new MailchimpService(apiKey, baseUrl); diff --git a/src/main/java/io/chucknorris/api/configuration/RestTemplateConfig.java b/src/main/java/io/chucknorris/api/configuration/RestTemplateConfig.java index 1c040fb..3721d5f 100644 --- a/src/main/java/io/chucknorris/api/configuration/RestTemplateConfig.java +++ b/src/main/java/io/chucknorris/api/configuration/RestTemplateConfig.java @@ -7,7 +7,7 @@ @Configuration public class RestTemplateConfig { - public @Bean RestTemplate restTemplate() { - return new RestTemplate(); - } + public @Bean RestTemplate restTemplate() { + return new RestTemplate(); + } } diff --git a/src/main/java/io/chucknorris/api/feed/FeedController.java b/src/main/java/io/chucknorris/api/feed/FeedController.java index a4dacac..0282387 100644 --- a/src/main/java/io/chucknorris/api/feed/FeedController.java +++ b/src/main/java/io/chucknorris/api/feed/FeedController.java @@ -29,15 +29,12 @@ public class FeedController { @Value("${mailchimp.dailychuck.list_id}") private String dailyChuckListId; - /** - * Returns a new FeedController {@link FeedController} instance. - */ + /** Returns a new FeedController {@link FeedController} instance. */ public FeedController( DailyChuckService dailyChuckService, DateUtil dateUtil, EventService eventService, - MailchimpService mailchimpService - ) { + MailchimpService mailchimpService) { this.dailyChuckService = dailyChuckService; this.dateUtil = dateUtil; this.eventService = eventService; @@ -54,8 +51,7 @@ public FeedController( value = {"/feed/daily-chuck.json", "/feed/daily-chuck"}, method = RequestMethod.GET, headers = HttpHeaders.ACCEPT + "=" + MediaType.APPLICATION_JSON_VALUE, - produces = MediaType.APPLICATION_JSON_VALUE - ) DailyChuck dailyChuckJson() throws IOException { + produces = MediaType.APPLICATION_JSON_VALUE) DailyChuck dailyChuckJson() throws IOException { DailyChuck dailyChuck = dailyChuckService.getDailyChuck(); Date now = dateUtil.now(); @@ -63,8 +59,8 @@ public FeedController( return dailyChuck; } - DailyChuckIssue dailyChuckIssue = dailyChuckService - .composeDailyChuckIssue(dailyChuck.getIssues()); + DailyChuckIssue dailyChuckIssue = + dailyChuckService.composeDailyChuckIssue(dailyChuck.getIssues()); dailyChuck.addIssue(dailyChuckIssue); dailyChuckService.persist(dailyChuck); @@ -83,8 +79,7 @@ public FeedController( value = "/feed/daily-chuck/stats", method = RequestMethod.GET, headers = HttpHeaders.ACCEPT + "=" + MediaType.APPLICATION_JSON_VALUE, - produces = MediaType.APPLICATION_JSON_VALUE - ) MailingListStatistic dailyChuckStats() { + produces = MediaType.APPLICATION_JSON_VALUE) MailingListStatistic dailyChuckStats() { MailingListStatistic mailingListStatistic = mailchimpService.fetchListStats(dailyChuckListId); return mailingListStatistic; @@ -100,8 +95,7 @@ public FeedController( value = {"/feed/daily-chuck.xml", "/feed/daily-chuck"}, method = RequestMethod.GET, headers = HttpHeaders.ACCEPT + "=" + MediaType.TEXT_XML_VALUE, - produces = MediaType.APPLICATION_RSS_XML_VALUE - ) View dailyChuckRss() throws IOException { + produces = MediaType.APPLICATION_RSS_XML_VALUE) View dailyChuckRss() throws IOException { DailyChuck dailyChuck = dailyChuckService.getDailyChuck(); MailingListStatistic mailingListStatistic = mailchimpService.fetchListStats(dailyChuckListId); @@ -111,8 +105,8 @@ public FeedController( return dailyChuckService.toRss(dailyChuck); } - DailyChuckIssue dailyChuckIssue = dailyChuckService - .composeDailyChuckIssue(dailyChuck.getIssues()); + DailyChuckIssue dailyChuckIssue = + dailyChuckService.composeDailyChuckIssue(dailyChuck.getIssues()); dailyChuck.addIssue(dailyChuckIssue); dailyChuckService.persist(dailyChuck); diff --git a/src/main/java/io/chucknorris/api/feed/dailychuck/DailyChuck.java b/src/main/java/io/chucknorris/api/feed/dailychuck/DailyChuck.java index 9c81344..76ba12e 100644 --- a/src/main/java/io/chucknorris/api/feed/dailychuck/DailyChuck.java +++ b/src/main/java/io/chucknorris/api/feed/dailychuck/DailyChuck.java @@ -27,9 +27,7 @@ public void addIssue(DailyChuckIssue dailyChuckIssue) { issueNumber += 1; } - /** - * Finds an issue {@link DailyChuckIssue} by joke id. - */ + /** Finds an issue {@link DailyChuckIssue} by joke id. */ public DailyChuckIssue findIssueByJokeId(String jokeId) { for (DailyChuckIssue issue : issues) { if (issue.getJokeId().equals(jokeId)) { @@ -39,9 +37,7 @@ public DailyChuckIssue findIssueByJokeId(String jokeId) { return null; } - /** - * Finds an issue {@link DailyChuckIssue} by a given date. - */ + /** Finds an issue {@link DailyChuckIssue} by a given date. */ public DailyChuckIssue findIssueByDate(Date date) { Calendar cal1 = Calendar.getInstance(); cal1.setTime(date); @@ -50,8 +46,9 @@ public DailyChuckIssue findIssueByDate(Date date) { Calendar cal2 = Calendar.getInstance(); cal2.setTime(issue.getDate()); - boolean isSameDay = cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) - && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR); + boolean isSameDay = + cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) + && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR); if (isSameDay) { return issue; diff --git a/src/main/java/io/chucknorris/api/feed/dailychuck/DailyChuckRss.java b/src/main/java/io/chucknorris/api/feed/dailychuck/DailyChuckRss.java index 407bd43..d408930 100644 --- a/src/main/java/io/chucknorris/api/feed/dailychuck/DailyChuckRss.java +++ b/src/main/java/io/chucknorris/api/feed/dailychuck/DailyChuckRss.java @@ -20,9 +20,7 @@ public class DailyChuckRss extends AbstractRssFeedView { private DailyChuck dailyChuck; private JokeRepository jokeRepository; - /** - * Instantiates a new DailyChuckRss {@link DailyChuckRss}. - */ + /** Instantiates a new DailyChuckRss {@link DailyChuckRss}. */ public DailyChuckRss(String baseUrl, DailyChuck dailyChuck, JokeRepository jokeRepository) { this.baseUrl = baseUrl; this.dailyChuck = dailyChuck; @@ -30,28 +28,29 @@ public DailyChuckRss(String baseUrl, DailyChuck dailyChuck, JokeRepository jokeR } @Override - protected void buildFeedMetadata(Map model, Channel feed, - HttpServletRequest request) { + protected void buildFeedMetadata( + Map model, Channel feed, HttpServletRequest request) { feed.setTitle("The Daily Chuck"); feed.setDescription( "Get your daily dose of the best #ChuckNorrisFacts " - + "every morning straight into your inbox." - ); + + "every morning straight into your inbox."); feed.setLink("https://" + baseUrl + "/feed/daily-chuck.xml"); } @Override - protected List buildFeedItems(Map model, HttpServletRequest request, - HttpServletResponse response) { + protected List buildFeedItems( + Map model, HttpServletRequest request, HttpServletResponse response) { DailyChuckIssue[] dailyChuckIssues = dailyChuck.getIssues(); - Arrays.sort(dailyChuck.getIssues(), - Comparator.comparing(DailyChuckIssue::getDate).reversed()); + Arrays.sort(dailyChuck.getIssues(), Comparator.comparing(DailyChuckIssue::getDate).reversed()); DailyChuckIssue currentIssue = dailyChuckIssues[0]; - Joke joke = jokeRepository.findById(currentIssue.getJokeId()).orElseThrow( - () -> new EntityNotFoundException( - "Joke with id \"" + currentIssue.getJokeId() + "\" not found.") - ); + Joke joke = + jokeRepository + .findById(currentIssue.getJokeId()) + .orElseThrow( + () -> + new EntityNotFoundException( + "Joke with id \"" + currentIssue.getJokeId() + "\" not found.")); Long issueNumber = dailyChuck.getIssueNumber(); Item entry = new Item(); diff --git a/src/main/java/io/chucknorris/api/feed/dailychuck/DailyChuckService.java b/src/main/java/io/chucknorris/api/feed/dailychuck/DailyChuckService.java index 6226a56..e0a067d 100644 --- a/src/main/java/io/chucknorris/api/feed/dailychuck/DailyChuckService.java +++ b/src/main/java/io/chucknorris/api/feed/dailychuck/DailyChuckService.java @@ -103,12 +103,9 @@ public PutObjectResult persist(DailyChuck dailyChuck) throws IOException { metadata.setContentType(MediaType.APPLICATION_JSON_VALUE); metadata.setContentLength(fileContentBytes.length); - PutObjectRequest request = new PutObjectRequest( - bucketName, - keyName, - new ByteArrayInputStream(fileContentBytes), - metadata - ); + PutObjectRequest request = + new PutObjectRequest( + bucketName, keyName, new ByteArrayInputStream(fileContentBytes), metadata); return amazonS3.putObject(request); } diff --git a/src/main/java/io/chucknorris/api/home/HomeController.java b/src/main/java/io/chucknorris/api/home/HomeController.java index 4108c7f..00cfdb0 100644 --- a/src/main/java/io/chucknorris/api/home/HomeController.java +++ b/src/main/java/io/chucknorris/api/home/HomeController.java @@ -15,23 +15,18 @@ public class HomeController { private JokeRepository jokeRepository; private SlackService slackService; - /** - * Instantiates a new HomeController {@link HomeController}. - */ + /** Instantiates a new HomeController {@link HomeController}. */ public HomeController(JokeRepository jokeRepository, SlackService slackService) { this.jokeRepository = jokeRepository; this.slackService = slackService; } - /** - * Returns the model for the home view. - */ + /** Returns the model for the home view. */ public @RequestMapping( value = "/", method = RequestMethod.GET, headers = HttpHeaders.ACCEPT + "=" + MediaType.TEXT_HTML_VALUE, - produces = MediaType.TEXT_HTML_VALUE - ) ModelAndView view() { + produces = MediaType.TEXT_HTML_VALUE) ModelAndView view() { ModelAndView modelAndView = new ModelAndView("home"); modelAndView.addObject("joke", jokeRepository.getRandomJoke()); modelAndView.addObject("slack_authorize_url", slackService.composeAuthorizeUri()); diff --git a/src/main/java/io/chucknorris/api/joke/Joke.java b/src/main/java/io/chucknorris/api/joke/Joke.java index 14fb0d0..4e7fe8f 100644 --- a/src/main/java/io/chucknorris/api/joke/Joke.java +++ b/src/main/java/io/chucknorris/api/joke/Joke.java @@ -23,9 +23,7 @@ @JsonSerialize(using = JokeSerializer.class) @NoArgsConstructor @Table(name = "joke") -@TypeDefs({ - @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class) -}) +@TypeDefs({@TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)}) public class Joke implements Serializable { @Column(name = "categories", columnDefinition = "jsonb") @@ -36,7 +34,7 @@ public class Joke implements Serializable { private String createdAt; @Transient - final private String iconUrl = "https://assets.chucknorris.host/img/avatar/chuck-norris.png"; + private final String iconUrl = "https://assets.chucknorris.host/img/avatar/chuck-norris.png"; @Id @Column(name = "joke_id", updatable = false, nullable = false) @@ -45,8 +43,7 @@ public class Joke implements Serializable { @Column(name = "updated_at") private String updatedAt; - @Transient - private String url; + @Transient private String url; @Column(name = "value") private String value; diff --git a/src/main/java/io/chucknorris/api/joke/JokeController.java b/src/main/java/io/chucknorris/api/joke/JokeController.java index 5ae8e1d..b741586 100644 --- a/src/main/java/io/chucknorris/api/joke/JokeController.java +++ b/src/main/java/io/chucknorris/api/joke/JokeController.java @@ -24,9 +24,7 @@ public class JokeController { private JokeRepository jokeRepository; - /** - * Returns a new JokeController {@link JokeController} instance. - */ + /** Returns a new JokeController {@link JokeController} instance. */ public JokeController(JokeRepository jokeRepository) { this.jokeRepository = jokeRepository; } @@ -35,22 +33,17 @@ public JokeController(JokeRepository jokeRepository) { value = "/categories", method = RequestMethod.GET, headers = HttpHeaders.ACCEPT + "=" + MediaType.APPLICATION_JSON_VALUE, - produces = MediaType.APPLICATION_JSON_VALUE - ) - public @ResponseBody - String[] getCategories() { + produces = MediaType.APPLICATION_JSON_VALUE) + public @ResponseBody String[] getCategories() { return jokeRepository.findAllCategories(); } - /** - * Returns all joke categories delimited by a new line. - */ + /** Returns all joke categories delimited by a new line. */ public @ResponseBody @RequestMapping( value = "/categories", method = RequestMethod.GET, headers = HttpHeaders.ACCEPT + "=" + MediaType.TEXT_PLAIN_VALUE, - produces = MediaType.TEXT_PLAIN_VALUE - ) String getCategoryValues() { + produces = MediaType.TEXT_PLAIN_VALUE) String getCategoryValues() { StringBuilder stringBuilder = new StringBuilder(); for (String category : jokeRepository.findAllCategories()) { @@ -70,11 +63,10 @@ String[] getCategories() { value = "/{id}", method = RequestMethod.GET, headers = HttpHeaders.ACCEPT + "=" + MediaType.APPLICATION_JSON_VALUE, - produces = MediaType.APPLICATION_JSON_VALUE - ) Joke getJoke(@PathVariable String id) { - return jokeRepository.findById(id).orElseThrow( - () -> new EntityNotFoundException("Joke with id \"" + id + "\" not found.") - ); + produces = MediaType.APPLICATION_JSON_VALUE) Joke getJoke(@PathVariable String id) { + return jokeRepository + .findById(id) + .orElseThrow(() -> new EntityNotFoundException("Joke with id \"" + id + "\" not found.")); } /** @@ -87,30 +79,30 @@ String[] getCategories() { value = "/{id}", method = RequestMethod.GET, headers = HttpHeaders.ACCEPT + "=" + MediaType.TEXT_PLAIN_VALUE, - produces = MediaType.TEXT_PLAIN_VALUE - ) String getJokeValue(@PathVariable String id, HttpServletResponse response) { + produces = MediaType.TEXT_PLAIN_VALUE) String getJokeValue( + @PathVariable String id, HttpServletResponse response) { try { - return jokeRepository.findById(id).orElseThrow( - () -> new EntityNotFoundException("Joke with id \"" + id + "\" not found.") - ).getValue(); + return jokeRepository + .findById(id) + .orElseThrow(() -> new EntityNotFoundException("Joke with id \"" + id + "\" not found.")) + .getValue(); } catch (EntityNotFoundException e) { response.setStatus(HttpStatus.NOT_FOUND.value()); return ""; } } - /** - * Returns the model for the joke view. - */ + /** Returns the model for the joke view. */ public @RequestMapping( value = "/{id}", method = RequestMethod.GET, headers = HttpHeaders.ACCEPT + "=" + MediaType.TEXT_HTML_VALUE, - produces = MediaType.TEXT_HTML_VALUE - ) ModelAndView getJokeView(@PathVariable String id) { - Joke joke = jokeRepository.findById(id).orElseThrow( - () -> new EntityNotFoundException("Joke with id \"" + id + "\" not found.") - ); + produces = MediaType.TEXT_HTML_VALUE) ModelAndView getJokeView(@PathVariable String id) { + Joke joke = + jokeRepository + .findById(id) + .orElseThrow( + () -> new EntityNotFoundException("Joke with id \"" + id + "\" not found.")); String[] ids = jokeRepository.getJokeWindow(id).split(","); @@ -132,11 +124,9 @@ String[] getCategories() { value = "/random", method = RequestMethod.GET, headers = HttpHeaders.ACCEPT + "=" + MediaType.APPLICATION_JSON_VALUE, - produces = MediaType.APPLICATION_JSON_VALUE - ) Joke getRandomJoke( + produces = MediaType.APPLICATION_JSON_VALUE) Joke getRandomJoke( @RequestParam(value = "category", required = false) String categoryString, - @RequestParam(value = "name", required = false) String name - ) { + @RequestParam(value = "name", required = false) String name) { if (categoryString == null && name == null) { return jokeRepository.getRandomJoke(); } @@ -144,8 +134,7 @@ String[] getCategories() { if (categoryString == null && name != null) { Joke joke = jokeRepository.getRandomPersonalizedJoke(name); if (!(joke instanceof Joke)) { - throw new EntityNotFoundException( - "No personalized jokes for name \"" + name + "\" found."); + throw new EntityNotFoundException("No personalized jokes for name \"" + name + "\" found."); } return joke; } @@ -154,8 +143,7 @@ String[] getCategories() { List categories = Arrays.asList(categoryString.split(",")); for (String category : categories) { if (!Arrays.asList(availableCategories).contains(category)) { - throw new EntityNotFoundException( - "No jokes for category \"" + category + "\" found."); + throw new EntityNotFoundException("No jokes for category \"" + category + "\" found."); } } @@ -163,7 +151,9 @@ String[] getCategories() { Joke joke = jokeRepository.getRandomPersonalizedJokeByCategories(name, categoryString); if (!(joke instanceof Joke)) { throw new EntityNotFoundException( - "No personalized jokes for name \"" + name + "\" and category \"" + "No personalized jokes for name \"" + + name + + "\" and category \"" + categoryString + "\" found."); } @@ -184,12 +174,10 @@ String[] getCategories() { value = "/random", method = RequestMethod.GET, headers = HttpHeaders.ACCEPT + "=" + MediaType.TEXT_PLAIN_VALUE, - produces = MediaType.TEXT_PLAIN_VALUE - ) String getRandomJokeValue( + produces = MediaType.TEXT_PLAIN_VALUE) String getRandomJokeValue( @RequestParam(value = "category", required = false) final String categoryString, @RequestParam(value = "name", required = false) final String name, - HttpServletResponse response - ) { + HttpServletResponse response) { if (categoryString == null && name == null) { return jokeRepository.getRandomJoke().getValue(); } @@ -236,27 +224,19 @@ String[] getCategories() { value = "/search", method = RequestMethod.GET, headers = HttpHeaders.ACCEPT + "=" + MediaType.APPLICATION_JSON_VALUE, - produces = MediaType.APPLICATION_JSON_VALUE - ) JokeSearchResult search( - @RequestParam(value = "query") - @Size(min = 3, max = 120) final String query - ) { + produces = MediaType.APPLICATION_JSON_VALUE) JokeSearchResult search( + @RequestParam(value = "query") @Size(min = 3, max = 120) final String query) { Joke[] jokes = jokeRepository.searchByQuery(query); return new JokeSearchResult(jokes); } - /** - * Returns a search result delimited by a new line. - */ + /** Returns a search result delimited by a new line. */ public @ResponseBody @RequestMapping( value = "/search", method = RequestMethod.GET, headers = HttpHeaders.ACCEPT + "=" + MediaType.TEXT_PLAIN_VALUE, - produces = MediaType.TEXT_PLAIN_VALUE - ) String searchValues( - @RequestParam(value = "query") - @Size(min = 3, max = 120) final String query - ) { + produces = MediaType.TEXT_PLAIN_VALUE) String searchValues( + @RequestParam(value = "query") @Size(min = 3, max = 120) final String query) { Joke[] jokes = jokeRepository.searchByQuery(query); StringBuilder stringBuilder = new StringBuilder(); diff --git a/src/main/java/io/chucknorris/api/joke/JokeRepository.java b/src/main/java/io/chucknorris/api/joke/JokeRepository.java index d4782c4..a78f3de 100644 --- a/src/main/java/io/chucknorris/api/joke/JokeRepository.java +++ b/src/main/java/io/chucknorris/api/joke/JokeRepository.java @@ -11,98 +11,87 @@ import org.springframework.stereotype.Repository; @Repository -@TypeDefs({ - @TypeDef(name = "string-array", typeClass = StringArrayType.class) -}) +@TypeDefs({@TypeDef(name = "string-array", typeClass = StringArrayType.class)}) public interface JokeRepository extends JpaRepository { @Query( - value = "SELECT j.categories, j.created_at, j.joke_id, j.updated_at, j.value " - + "FROM joke AS j " - + "WHERE lower(j.value) LIKE CONCAT('%', lower(:query), '%')", - nativeQuery = true - ) + value = + "SELECT j.categories, j.created_at, j.joke_id, j.updated_at, j.value " + + "FROM joke AS j " + + "WHERE lower(j.value) LIKE CONCAT('%', lower(:query), '%')", + nativeQuery = true) Page findByValueContains(@Param("query") final String query, Pageable pageable); @Query( - value = "SELECT j.categories, j.created_at, j.joke_id, j.updated_at, j.value " - + "FROM find_by_by_value_contains_and_filter(:query, :categories) AS j", - countQuery = "SELECT count(*) " - + "FROM find_by_by_value_contains_and_filter(:query, :categories)", - nativeQuery = true - ) + value = + "SELECT j.categories, j.created_at, j.joke_id, j.updated_at, j.value " + + "FROM find_by_by_value_contains_and_filter(:query, :categories) AS j", + countQuery = + "SELECT count(*) " + "FROM find_by_by_value_contains_and_filter(:query, :categories)", + nativeQuery = true) Page findByValueContainsAndFilter( @Param("query") final String query, @Param("categories") final String categories, - Pageable pageable - ); + Pageable pageable); @Query( - value = "SELECT j.categories->>0 FROM joke j WHERE j.categories IS NOT NULL " - + "GROUP BY j.categories->>0 " - + "ORDER BY j.categories->>0 ASC", - nativeQuery = true - ) + value = + "SELECT j.categories->>0 FROM joke j WHERE j.categories IS NOT NULL " + + "GROUP BY j.categories->>0 " + + "ORDER BY j.categories->>0 ASC", + nativeQuery = true) String[] findAllCategories(); @Query( - value = "WITH joke AS( SELECT joke_id, ROW_NUMBER() " - + "OVER (ORDER BY joke.created_at ASC, joke.joke_id ASC) AS row_number FROM joke), " - + "current AS ( SELECT * FROM joke WHERE joke_id = :id LIMIT 1 ), " - + "prev AS ( " - + "SELECT (CASE WHEN (SELECT min(row_number) FROM joke) >= current.row_number - 1 " - + "THEN (SELECT joke_id FROM joke WHERE row_number = (SELECT max(row_number) FROM joke)) " - + "ELSE (SELECT joke_id FROM joke WHERE row_number = current.row_number - 1) END) " - + "AS joke_id FROM joke, current LIMIT 1 ), " - + "next AS ( " - + "SELECT (CASE WHEN (SELECT max(row_number) FROM joke) <= current.row_number + 1 " - + "THEN (SELECT joke_id FROM joke WHERE row_number = (SELECT min(row_number) FROM joke)) " - + "ELSE (SELECT joke_id FROM joke WHERE row_number = current.row_number + 1) END) " - + "AS joke_id FROM joke, current LIMIT 1 ) " - + "SELECT " - + "current.joke_id AS current_joke_id, " - + "next.joke_id AS next_joke_id, " - + "prev.joke_id AS prev_joke_id " - + "FROM current, prev, next;", - nativeQuery = true - ) + value = + "WITH joke AS( SELECT joke_id, ROW_NUMBER() OVER (ORDER BY joke.created_at ASC," + + " joke.joke_id ASC) AS row_number FROM joke), current AS ( SELECT * FROM" + + " joke WHERE joke_id = :id LIMIT 1 ), prev AS ( SELECT (CASE WHEN (SELECT" + + " min(row_number) FROM joke) >= current.row_number - 1 THEN (SELECT" + + " joke_id FROM joke WHERE row_number = (SELECT max(row_number) FROM" + + " joke)) ELSE (SELECT joke_id FROM joke WHERE row_number =" + + " current.row_number - 1) END) AS joke_id FROM joke, current LIMIT 1 )," + + " next AS ( SELECT (CASE WHEN (SELECT max(row_number) FROM joke) <=" + + " current.row_number + 1 THEN (SELECT joke_id FROM joke WHERE row_number" + + " = (SELECT min(row_number) FROM joke)) ELSE (SELECT joke_id FROM joke" + + " WHERE row_number = current.row_number + 1) END) AS joke_id FROM joke," + + " current LIMIT 1 ) SELECT current.joke_id AS current_joke_id," + + " next.joke_id AS next_joke_id, prev.joke_id AS prev_joke_id FROM" + + " current, prev, next;", + nativeQuery = true) String getJokeWindow(@Param("id") final String id); @Query( - value = "SELECT " - + "j.categories, j.created_at, j.joke_id, j.updated_at, j.value " - + "FROM joke AS j " - + "ORDER BY RANDOM() LIMIT 1;", - nativeQuery = true - ) + value = + "SELECT " + + "j.categories, j.created_at, j.joke_id, j.updated_at, j.value " + + "FROM joke AS j " + + "ORDER BY RANDOM() LIMIT 1;", + nativeQuery = true) Joke getRandomJoke(); @Query( - value = "SELECT j.categories, j.created_at, j.joke_id, j.updated_at, j.value " - + "FROM get_random_personalized_joke(:substitute, null) AS j;", - nativeQuery = true - ) - Joke getRandomPersonalizedJoke( - @Param("substitute") final String substitute - ); + value = + "SELECT j.categories, j.created_at, j.joke_id, j.updated_at, j.value " + + "FROM get_random_personalized_joke(:substitute, null) AS j;", + nativeQuery = true) + Joke getRandomPersonalizedJoke(@Param("substitute") final String substitute); @Query( - value = "SELECT j.categories, j.created_at, j.joke_id, j.updated_at, j.value " - + "FROM get_random_personalized_joke(:substitute, :categories) AS j;", - nativeQuery = true - ) + value = + "SELECT j.categories, j.created_at, j.joke_id, j.updated_at, j.value " + + "FROM get_random_personalized_joke(:substitute, :categories) AS j;", + nativeQuery = true) Joke getRandomPersonalizedJokeByCategories( - @Param("substitute") final String substitute, - @Param("categories") final String categories - ); + @Param("substitute") final String substitute, @Param("categories") final String categories); @Query( - value = "SELECT j.categories, j.created_at, j.joke_id, j.updated_at, j.value " - + "FROM joke AS j " - + "WHERE j.categories IS NOT NULL AND j.categories->>0 = :category " - + "ORDER BY RANDOM() LIMIT 1;", - nativeQuery = true - ) + value = + "SELECT j.categories, j.created_at, j.joke_id, j.updated_at, j.value " + + "FROM joke AS j " + + "WHERE j.categories IS NOT NULL AND j.categories->>0 = :category " + + "ORDER BY RANDOM() LIMIT 1;", + nativeQuery = true) Joke getRandomJokeByCategory(@Param("category") final String category); /** @@ -110,17 +99,17 @@ Joke getRandomPersonalizedJokeByCategories( * categories equals one of the provided categories. */ @Query( - value = "SELECT j.categories, j.created_at, j.joke_id, j.updated_at, j.value " - + "FROM get_joke_random_by_categories(:categories) AS j;", - nativeQuery = true - ) + value = + "SELECT j.categories, j.created_at, j.joke_id, j.updated_at, j.value " + + "FROM get_joke_random_by_categories(:categories) AS j;", + nativeQuery = true) Joke getRandomJokeByCategories(@Param("categories") final String categories); @Query( - value = "SELECT j.categories, j.created_at, j.joke_id, j.updated_at, j.value " - + "FROM joke AS j " - + "WHERE lower(j.value) LIKE CONCAT('%', lower(:query), '%');", - nativeQuery = true - ) + value = + "SELECT j.categories, j.created_at, j.joke_id, j.updated_at, j.value " + + "FROM joke AS j " + + "WHERE lower(j.value) LIKE CONCAT('%', lower(:query), '%');", + nativeQuery = true) Joke[] searchByQuery(@Param("query") final String query); -} \ No newline at end of file +} diff --git a/src/main/java/io/chucknorris/api/joke/JokeSerializer.java b/src/main/java/io/chucknorris/api/joke/JokeSerializer.java index 29a3835..8eb6b0e 100644 --- a/src/main/java/io/chucknorris/api/joke/JokeSerializer.java +++ b/src/main/java/io/chucknorris/api/joke/JokeSerializer.java @@ -24,9 +24,10 @@ public void serialize(Joke joke, JsonGenerator jsonGenerator, SerializerProvider throws IOException { jsonGenerator.writeStartObject(); - String[] categories = joke.getCategories() != null && joke.getCategories().length > 0 - ? joke.getCategories() - : new String[0]; + String[] categories = + joke.getCategories() != null && joke.getCategories().length > 0 + ? joke.getCategories() + : new String[0]; jsonGenerator.writeArrayFieldStart("categories"); for (String category : categories) { jsonGenerator.writeString(category); @@ -41,4 +42,4 @@ public void serialize(Joke joke, JsonGenerator jsonGenerator, SerializerProvider jsonGenerator.writeStringField("value", joke.getValue()); jsonGenerator.writeEndObject(); } -} \ No newline at end of file +} diff --git a/src/main/java/io/chucknorris/api/joke/JokeService.java b/src/main/java/io/chucknorris/api/joke/JokeService.java index 43ffa93..fc0ed79 100644 --- a/src/main/java/io/chucknorris/api/joke/JokeService.java +++ b/src/main/java/io/chucknorris/api/joke/JokeService.java @@ -12,47 +12,27 @@ public JokeService(JokeRepository jokeRepository) { this.jokeRepository = jokeRepository; } - /** - * Returns a random joke filtered by a given category. - */ + /** Returns a random joke filtered by a given category. */ public Joke randomJokeByCategory(final String category) { return jokeRepository.getRandomJokeByCategory(category); } - /** - * Returns a random joke filtered by a given array of categories. - */ + /** Returns a random joke filtered by a given array of categories. */ public Joke randomJokeByCategories(final String[] categories) { - return jokeRepository.getRandomJokeByCategories( - String.join(",", categories) - ); + return jokeRepository.getRandomJokeByCategories(String.join(",", categories)); } - /** - * Returns a random personalized joke filtered by a given array of categories. - */ + /** Returns a random personalized joke filtered by a given array of categories. */ public Joke randomPersonalizedJokeByCategories( - final String substitute, - final String[] categories - ) { + final String substitute, final String[] categories) { return jokeRepository.getRandomPersonalizedJokeByCategories( - substitute, - String.join(",", categories) - ); + substitute, String.join(",", categories)); } - /** - * Search jokes by query and with category filter. - */ + /** Search jokes by query and with category filter. */ public Page searchWithCategoryFilter( - final String query, - final String[] categories, - final Pageable pageable - ) { + final String query, final String[] categories, final Pageable pageable) { return jokeRepository.findByValueContainsAndFilter( - query, - String.join(",", categories), - pageable - ); + query, String.join(",", categories), pageable); } } diff --git a/src/main/java/io/chucknorris/api/postcard/PostcardController.java b/src/main/java/io/chucknorris/api/postcard/PostcardController.java index 7f8a099..f93c373 100644 --- a/src/main/java/io/chucknorris/api/postcard/PostcardController.java +++ b/src/main/java/io/chucknorris/api/postcard/PostcardController.java @@ -1,5 +1,3 @@ package io.chucknorris.api.postcard; -public class PostcardController { - -} +public class PostcardController {} diff --git a/src/main/java/io/chucknorris/api/privacy/PrivacyController.java b/src/main/java/io/chucknorris/api/privacy/PrivacyController.java index 992d15b..3159d21 100644 --- a/src/main/java/io/chucknorris/api/privacy/PrivacyController.java +++ b/src/main/java/io/chucknorris/api/privacy/PrivacyController.java @@ -9,15 +9,12 @@ @Controller public class PrivacyController { - /** - * Returns privacy view. - */ + /** Returns privacy view. */ public @RequestMapping( value = "/privacy", method = RequestMethod.GET, headers = HttpHeaders.ACCEPT + "=" + MediaType.TEXT_HTML_VALUE, - produces = MediaType.TEXT_HTML_VALUE - ) String get() { + produces = MediaType.TEXT_HTML_VALUE) String get() { return "privacy"; } } diff --git a/src/main/java/io/chucknorris/api/slack/AccessToken.java b/src/main/java/io/chucknorris/api/slack/AccessToken.java index fe64673..640bc5f 100644 --- a/src/main/java/io/chucknorris/api/slack/AccessToken.java +++ b/src/main/java/io/chucknorris/api/slack/AccessToken.java @@ -24,4 +24,4 @@ public class AccessToken implements Serializable { @JsonProperty("user_name") private String userName; -} \ No newline at end of file +} diff --git a/src/main/java/io/chucknorris/api/slack/CommandResponseAttachment.java b/src/main/java/io/chucknorris/api/slack/CommandResponseAttachment.java index 767de33..121f1e3 100644 --- a/src/main/java/io/chucknorris/api/slack/CommandResponseAttachment.java +++ b/src/main/java/io/chucknorris/api/slack/CommandResponseAttachment.java @@ -11,7 +11,7 @@ public class CommandResponseAttachment implements Serializable, SlackCommandResp private String fallback; @JsonProperty("mrkdwn_in") - private String[] mrkdownIn = new String[]{"text"}; + private String[] mrkdownIn = new String[] {"text"}; @JsonProperty("text") private String text; diff --git a/src/main/java/io/chucknorris/api/slack/Help.java b/src/main/java/io/chucknorris/api/slack/Help.java index 28b774e..0eda6f4 100644 --- a/src/main/java/io/chucknorris/api/slack/Help.java +++ b/src/main/java/io/chucknorris/api/slack/Help.java @@ -18,14 +18,14 @@ public class Help implements SlackCommandResponse { @JsonProperty("text") private String text = "*Available commands:*"; - /** - * Instantiates a new Help {@link Help}. - */ + /** Instantiates a new Help {@link Help}. */ public Help() { CommandResponseAttachment newsletter = new CommandResponseAttachment(); newsletter.setTitle("The Daily Chuck"); newsletter.setText( - ":facepunch: Sign up for *The Daily Chuck* and get your daily dose of the best #ChuckNorrisFacts every morning straight int your inbox! https://mailchi.mp/5a19a2898bf7/the-daily-chuck"); + ":facepunch: Sign up for *The Daily Chuck* and get your daily dose of the best" + + " #ChuckNorrisFacts every morning straight int your inbox!" + + " https://mailchi.mp/5a19a2898bf7/the-daily-chuck"); CommandResponseAttachment randomJoke = new CommandResponseAttachment(); randomJoke.setText("Type `/chuck` to get a random joke."); @@ -33,12 +33,13 @@ public Help() { CommandResponseAttachment search = new CommandResponseAttachment(); search.setText( - "Type `/chuck ? {search_term}` to search within tens of thousands Chuck Norris jokes."); + "Type `/chuck ? {search_term}` to search within tens of thousands Chuck Norris" + + " jokes."); search.setTitle("Free text search"); CommandResponseAttachment randomJokePersonalized = new CommandResponseAttachment(); - randomJokePersonalized - .setText("Type `/chuck @ {user_name}` to get a random personalized joke."); + randomJokePersonalized.setText( + "Type `/chuck @ {user_name}` to get a random personalized joke."); randomJokePersonalized.setTitle("Random personalized joke"); CommandResponseAttachment randomJokeFromCategory = new CommandResponseAttachment(); @@ -58,15 +59,16 @@ public Help() { help.setText("Type `/chuck help` to display a list of available commands."); help.setTitle("Help"); - attachments = new CommandResponseAttachment[]{ - newsletter, - randomJoke, - search, - randomJokePersonalized, - randomJokeFromCategory, - categories, - jokeById, - help - }; + attachments = + new CommandResponseAttachment[] { + newsletter, + randomJoke, + search, + randomJokePersonalized, + randomJokeFromCategory, + categories, + jokeById, + help + }; } } diff --git a/src/main/java/io/chucknorris/api/slack/Request.java b/src/main/java/io/chucknorris/api/slack/Request.java index b047796..7d5d904 100644 --- a/src/main/java/io/chucknorris/api/slack/Request.java +++ b/src/main/java/io/chucknorris/api/slack/Request.java @@ -29,9 +29,7 @@ public class Request implements Serializable { @JsonProperty("enterprise_name") private String enterpriseName; - /** - * A URL that you can use to respond to the command. - */ + /** A URL that you can use to respond to the command. */ @JsonProperty("enterprise_url") private String responseUrl; @@ -64,9 +62,7 @@ public class Request implements Serializable { @JsonProperty("trigger_id") private String triggerId; - /** - * The ID of the user who triggered the command. - */ + /** The ID of the user who triggered the command. */ @JsonProperty("user_id") private String userId; @@ -77,4 +73,3 @@ public class Request implements Serializable { @JsonProperty("user_name") private String userName; } - diff --git a/src/main/java/io/chucknorris/api/slack/RequestArgumentResolver.java b/src/main/java/io/chucknorris/api/slack/RequestArgumentResolver.java index 3bb74bf..4b7763d 100644 --- a/src/main/java/io/chucknorris/api/slack/RequestArgumentResolver.java +++ b/src/main/java/io/chucknorris/api/slack/RequestArgumentResolver.java @@ -14,7 +14,8 @@ public boolean supportsParameter(MethodParameter methodParameter) { } @Override - public Object resolveArgument(MethodParameter methodParameter, + public Object resolveArgument( + MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) { diff --git a/src/main/java/io/chucknorris/api/slack/SlackController.java b/src/main/java/io/chucknorris/api/slack/SlackController.java index 8d88855..6de0159 100644 --- a/src/main/java/io/chucknorris/api/slack/SlackController.java +++ b/src/main/java/io/chucknorris/api/slack/SlackController.java @@ -42,39 +42,33 @@ public class SlackController { private JokeService jokeService; private SlackService slackService; - /** - * Returns a new {@link SlackController} instance. - */ + /** Returns a new {@link SlackController} instance. */ public SlackController( EventService eventService, JokeRepository jokeRepository, JokeService jokeService, - SlackService slackService - ) { + SlackService slackService) { this.eventService = eventService; this.jokeRepository = jokeRepository; this.jokeService = jokeService; this.slackService = slackService; } - /** - * Returns the model for the connect/slack view. - */ + /** Returns the model for the connect/slack view. */ public @RequestMapping( value = "/connect/slack", method = RequestMethod.GET, headers = HttpHeaders.ACCEPT + "=" + MediaType.TEXT_HTML_VALUE, - produces = MediaType.TEXT_HTML_VALUE - ) ModelAndView connect( - @RequestParam(value = "code", required = false) final String code - ) throws JsonProcessingException { + produces = MediaType.TEXT_HTML_VALUE) ModelAndView connect( + @RequestParam(value = "code", required = false) final String code) + throws JsonProcessingException { AccessToken accessToken = slackService.requestAccessToken(code); ModelAndView model = new ModelAndView("connect/slack"); if (accessToken.getAccessToken() != null) { model.setStatus(HttpStatus.OK); - model.addObject("page_title", - "Congrats, the app was successfully installed for your Slack team!"); + model.addObject( + "page_title", "Congrats, the app was successfully installed for your Slack team!"); model.addObject("error", false); model.addObject("message", null); @@ -101,11 +95,10 @@ public SlackController( value = {"/integration/slack", "/jokes/slack"}, method = RequestMethod.POST, headers = { - HttpHeaders.ACCEPT + "=" + MediaType.APPLICATION_JSON_VALUE, - HttpHeaders.CONTENT_TYPE + "=" + MediaType.APPLICATION_FORM_URLENCODED_VALUE + HttpHeaders.ACCEPT + "=" + MediaType.APPLICATION_JSON_VALUE, + HttpHeaders.CONTENT_TYPE + "=" + MediaType.APPLICATION_FORM_URLENCODED_VALUE }, - produces = MediaType.APPLICATION_JSON_VALUE - ) SlackCommandResponse command(Request request) { + produces = MediaType.APPLICATION_JSON_VALUE) SlackCommandResponse command(Request request) { logger.info(request.toString()); if (request.getText() == null || request.getText().isEmpty()) { @@ -115,9 +108,7 @@ public SlackController( urlQueryParams.set("utm_term", request.getTeamDomain()); urlQueryParams.set("utm_campaign", "random+joke"); - Joke joke = jokeService.randomJokeByCategories( - slackService.getWhitelistedCategories() - ); + Joke joke = jokeService.randomJokeByCategories(slackService.getWhitelistedCategories()); return composeJokeResponse(joke, urlQueryParams); } @@ -135,8 +126,7 @@ public SlackController( stringBuilder.append(String.join("`, `", whitelistedCategories)); stringBuilder.append( "`. Type `/chuck {category_name}` to retrieve a " - + "random joke from within the given category." - ); + + "random joke from within the given category."); CommandResponse response = new CommandResponse(); response.setText(stringBuilder.toString()); @@ -177,17 +167,16 @@ public SlackController( String[] whitelistedCategories = slackService.filterNonWhitelistedCategories(categories); String substitute = request.getText().substring(1).trim(); - Joke joke = jokeService.randomPersonalizedJokeByCategories( - substitute, - whitelistedCategories - ); + Joke joke = jokeService.randomPersonalizedJokeByCategories(substitute, whitelistedCategories); if (joke == null) { CommandResponse response = new CommandResponse(); - response.setText("Your search for *\"" + substitute - + "\"* did not match any joke ¯\\_(ツ)_/¯. Make sure that all words are spelled " - + "correctly. Try different keywords. Try more general keywords." - ); + response.setText( + "Your search for *\"" + + substitute + + "\"* did not match any joke ¯\\_(ツ)_/¯. Make sure that all words" + + " are spelled correctly. Try different keywords. Try more general" + + " keywords."); response.setResponseType(ResponseType.EPHEMERAL); return response; } @@ -215,18 +204,17 @@ public SlackController( String[] categories = jokeRepository.findAllCategories(); String[] whitelistedCategories = slackService.filterNonWhitelistedCategories(categories); - Page jokes = jokeService.searchWithCategoryFilter( - query, - whitelistedCategories, - pageable - ); + Page jokes = + jokeService.searchWithCategoryFilter(query, whitelistedCategories, pageable); if (jokes.getContent().size() < 1) { CommandResponse response = new CommandResponse(); - response.setText("Your search for *\"" + query - + "\"* did not match any joke ¯\\_(ツ)_/¯. Make sure that all words are spelled " - + "correctly. Try different keywords. Try more general keywords." - ); + response.setText( + "Your search for *\"" + + query + + "\"* did not match any joke ¯\\_(ツ)_/¯. Make sure that all words" + + " are spelled correctly. Try different keywords. Try more general" + + " keywords."); response.setResponseType(ResponseType.EPHEMERAL); return response; @@ -238,20 +226,19 @@ public SlackController( urlQueryParams.set("utm_term", request.getTeamDomain()); urlQueryParams.set("utm_campaign", "search+joke"); - SlackCommandResponseAttachment[] attachments = new CommandResponseAttachment[ - jokes.getContent().size() - ]; + SlackCommandResponseAttachment[] attachments = + new CommandResponseAttachment[jokes.getContent().size()]; for (int i = 0; i < jokes.getContent().size(); i++) { Joke joke = jokes.getContent().get(i); - UriComponents uriComponents = UriComponentsBuilder - .newInstance() - .scheme("https") - .host(baseUrl) - .path("/jokes/" + joke.getId()) - .queryParams(urlQueryParams) - .build() - .encode(); + UriComponents uriComponents = + UriComponentsBuilder.newInstance() + .scheme("https") + .host(baseUrl) + .path("/jokes/" + joke.getId()) + .queryParams(urlQueryParams) + .build() + .encode(); SlackCommandResponseAttachment attachment = new CommandResponseAttachment(); attachment.setFallback(joke.getValue()); @@ -264,23 +251,28 @@ public SlackController( CommandResponse response = new CommandResponse(); if (!jokes.isLast()) { - response.setText("*Search results: " - + (page * itemsPerPage + 1) - + " - " - + (page * itemsPerPage + jokes.getContent().size()) - + " of " + jokes.getTotalElements() - + "*. " - + "Type `/chuck ? " - + query - + " --page " - + (page + 1 + 1) - + "` to see more results." - ); + response.setText( + "*Search results: " + + (page * itemsPerPage + 1) + + " - " + + (page * itemsPerPage + jokes.getContent().size()) + + " of " + + jokes.getTotalElements() + + "*. " + + "Type `/chuck ? " + + query + + " --page " + + (page + 1 + 1) + + "` to see more results."); } else { response.setText( - "*Search results: " + (page * itemsPerPage + 1) + " - " + (page * 5 + jokes - .getNumberOfElements()) + " of " + jokes.getTotalElements() + "*." - ); + "*Search results: " + + (page * itemsPerPage + 1) + + " - " + + (page * 5 + jokes.getNumberOfElements()) + + " of " + + jokes.getTotalElements() + + "*."); } response.setAttachments(attachments); @@ -294,9 +286,8 @@ public SlackController( response.setText( "Sorry dude ¯\\_(ツ)_/¯ , the given category (\"" + request.getText() - + "\") is not whitelisted. Type `/chuck -cat` to see available categories " - + "or search by query `/chuck ? {search_term}`" - ); + + "\") is not whitelisted. Type `/chuck -cat` to see available" + + " categories or search by query `/chuck ? {search_term}`"); response.setResponseType(ResponseType.EPHEMERAL); return response; @@ -309,9 +300,8 @@ public SlackController( response.setText( "Sorry dude ¯\\_(ツ)_/¯ , we've found no jokes for the given category (\"" + request.getText() - + "\"). Type `/chuck -cat` to see available categories or search by " - + "query `/chuck ? {search_term}`" - ); + + "\"). Type `/chuck -cat` to see available categories or search by" + + " query `/chuck ? {search_term}`"); response.setResponseType(ResponseType.EPHEMERAL); return response; @@ -332,17 +322,15 @@ public SlackController( } private SlackCommandResponse composeJokeResponse( - Joke joke, - MultiValueMap urlParams - ) { - UriComponents uriComponents = UriComponentsBuilder - .newInstance() - .scheme("https") - .host(baseUrl) - .path("/jokes/" + joke.getId()) - .queryParams(urlParams) - .build() - .encode(); + Joke joke, MultiValueMap urlParams) { + UriComponents uriComponents = + UriComponentsBuilder.newInstance() + .scheme("https") + .host(baseUrl) + .path("/jokes/" + joke.getId()) + .queryParams(urlParams) + .build() + .encode(); SlackCommandResponseAttachment attachment = new CommandResponseAttachment(); attachment.setFallback(joke.getValue()); @@ -351,9 +339,7 @@ private SlackCommandResponse composeJokeResponse( attachment.setTitleLink(uriComponents.toUriString()); CommandResponse response = new CommandResponse(); - response.setAttachments( - new SlackCommandResponseAttachment[]{attachment} - ); + response.setAttachments(new SlackCommandResponseAttachment[] {attachment}); return response; } diff --git a/src/main/java/io/chucknorris/api/slack/SlackService.java b/src/main/java/io/chucknorris/api/slack/SlackService.java index f4db6cc..8cecc5a 100644 --- a/src/main/java/io/chucknorris/api/slack/SlackService.java +++ b/src/main/java/io/chucknorris/api/slack/SlackService.java @@ -28,24 +28,20 @@ public class SlackService { @Value("${slack.oauth.redirect_uri}") private String redirectUrl; - @Autowired - private RestTemplate restTemplate; + @Autowired private RestTemplate restTemplate; @Value("${slack.content.whitelisted_categories}") private String whitelistedCategories; - /** - * Composes the authorize uri. - */ + /** Composes the authorize uri. */ public UriComponents composeAuthorizeUri() { - //@see https://api.slack.com/docs/oauth-scopes + // @see https://api.slack.com/docs/oauth-scopes MultiValueMap urlQueryParams = new LinkedMultiValueMap<>(); urlQueryParams.set("client_id", clientId); urlQueryParams.set("redirect_uri", redirectUrl); urlQueryParams.set("scope", "commands"); - return UriComponentsBuilder - .newInstance() + return UriComponentsBuilder.newInstance() .scheme("https") .host("slack.com") .path("/oauth/v2/authorize/") @@ -54,36 +50,24 @@ public UriComponents composeAuthorizeUri() { .encode(); } - /** - * Filters all non-whitelisted categories from array. - */ + /** Filters all non-whitelisted categories from array. */ public String[] filterNonWhitelistedCategories(String[] categories) { - return Arrays.stream(categories).filter( - category -> isWhitelistedCategory(category) - ).toArray(String[]::new); + return Arrays.stream(categories) + .filter(category -> isWhitelistedCategory(category)) + .toArray(String[]::new); } - /** - * Returns an array of whitelisted categories. - */ + /** Returns an array of whitelisted categories. */ public String[] getWhitelistedCategories() { - return whitelistedCategories != null - ? whitelistedCategories.split(",") - : new String[]{}; + return whitelistedCategories != null ? whitelistedCategories.split(",") : new String[] {}; } - /** - * Checks if a given category is whitelisted. - */ + /** Checks if a given category is whitelisted. */ public Boolean isWhitelistedCategory(String category) { - return Arrays.asList( - getWhitelistedCategories() - ).contains(category); + return Arrays.asList(getWhitelistedCategories()).contains(category); } - /** - * Requests an access token from Slack. - */ + /** Requests an access token from Slack. */ public AccessToken requestAccessToken(final String code) { HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE); @@ -96,12 +80,12 @@ public AccessToken requestAccessToken(final String code) { map.add("redirect_uri", redirectUrl); try { - ResponseEntity responseEntity = restTemplate.exchange( - "https://slack.com/api/oauth.v2.access", - HttpMethod.POST, - new HttpEntity<>(map, headers), - AccessToken.class - ); + ResponseEntity responseEntity = + restTemplate.exchange( + "https://slack.com/api/oauth.v2.access", + HttpMethod.POST, + new HttpEntity<>(map, headers), + AccessToken.class); return responseEntity.getBody(); } catch (RestClientException exception) { diff --git a/src/main/java/io/chucknorris/lib/event/EventService.java b/src/main/java/io/chucknorris/lib/event/EventService.java index 5646883..cd9d935 100644 --- a/src/main/java/io/chucknorris/lib/event/EventService.java +++ b/src/main/java/io/chucknorris/lib/event/EventService.java @@ -32,7 +32,7 @@ public EventService(AmazonSNSClient snsClient) { * @param event The event being published {@link Event} * @return publishResult * @throws JsonProcessingException Thrown in case of problems encountered when processing JSON - * content that are not pure I/O problems. + * content that are not pure I/O problems. */ public PublishResult publishEvent(Event event) throws JsonProcessingException { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); @@ -46,11 +46,12 @@ public PublishResult publishEvent(Event event) throws JsonProcessingException { logger.info( "[event_published] " - + - "event_message_id: \"" + publishResult.getMessageId() + "\" " - + - "event_message: \"" + message + "\"" - ); + + "event_message_id: \"" + + publishResult.getMessageId() + + "\" " + + "event_message: \"" + + message + + "\""); return publishResult; } diff --git a/src/main/java/io/chucknorris/lib/mailchimp/MailchimpService.java b/src/main/java/io/chucknorris/lib/mailchimp/MailchimpService.java index e28121a..08eeb93 100644 --- a/src/main/java/io/chucknorris/lib/mailchimp/MailchimpService.java +++ b/src/main/java/io/chucknorris/lib/mailchimp/MailchimpService.java @@ -13,8 +13,7 @@ public class MailchimpService { private String apiKey; private String baseUrl; - @Autowired - private RestTemplate restTemplate; + @Autowired private RestTemplate restTemplate; public MailchimpService(String apiKey, String baseUrl) { this.apiKey = apiKey; @@ -37,12 +36,12 @@ private MailingList fetchList(final String listId) { headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE); headers.add(HttpHeaders.AUTHORIZATION, "apikey " + this.apiKey); - ResponseEntity responseEntity = restTemplate.exchange( - baseUrl + "/3.0/lists/" + listId, - HttpMethod.GET, - new HttpEntity<>(null, headers), - MailingList.class - ); + ResponseEntity responseEntity = + restTemplate.exchange( + baseUrl + "/3.0/lists/" + listId, + HttpMethod.GET, + new HttpEntity<>(null, headers), + MailingList.class); return responseEntity.getBody(); } diff --git a/src/main/java/io/chucknorris/lib/mailchimp/MailingList.java b/src/main/java/io/chucknorris/lib/mailchimp/MailingList.java index d7f6a33..726a95e 100644 --- a/src/main/java/io/chucknorris/lib/mailchimp/MailingList.java +++ b/src/main/java/io/chucknorris/lib/mailchimp/MailingList.java @@ -1,7 +1,6 @@ package io.chucknorris.lib.mailchimp; import com.fasterxml.jackson.annotation.JsonProperty; -import io.chucknorris.lib.mailchimp.MailingListStatistic; import java.io.Serializable; import lombok.Data; diff --git a/src/test/java/io/chucknorris/api/configuration/HerokuDataSourcePropertiesTest.java b/src/test/java/io/chucknorris/api/configuration/HerokuDataSourcePropertiesTest.java index fa6ded2..42ce91d 100644 --- a/src/test/java/io/chucknorris/api/configuration/HerokuDataSourcePropertiesTest.java +++ b/src/test/java/io/chucknorris/api/configuration/HerokuDataSourcePropertiesTest.java @@ -1,26 +1,29 @@ package io.chucknorris.api.configuration; -import org.junit.Test; - import static org.junit.Assert.assertEquals; +import org.junit.Test; + public class HerokuDataSourcePropertiesTest { - @Test - public void testShouldCreateDataSourcePostgres() { - // given: - String driverClassName = "org.postgresql.Driver"; + @Test + public void testShouldCreateDataSourcePostgres() { + // given: + String driverClassName = "org.postgresql.Driver"; - // and: - String uri = "postgres://username:password@ec2-00-000-00-000.eu-west-1.compute.amazonaws.com:5432/d409qm4ujtafvk"; + // and: + String uri = + "postgres://username:password@ec2-00-000-00-000.eu-west-1.compute.amazonaws.com:5432/d409qm4ujtafvk"; - // when: - HerokuDataSourceProperties actual = new HerokuDataSourceProperties(driverClassName, uri); + // when: + HerokuDataSourceProperties actual = new HerokuDataSourceProperties(driverClassName, uri); - // then: - assertEquals("org.postgresql.Driver", actual.getDriverClassName()); - assertEquals("password", actual.getPassword()); - assertEquals("jdbc:postgresql://ec2-00-000-00-000.eu-west-1.compute.amazonaws.com:5432/d409qm4ujtafvk", actual.getUrl()); - assertEquals("username", actual.getUsername()); - } -} \ No newline at end of file + // then: + assertEquals("org.postgresql.Driver", actual.getDriverClassName()); + assertEquals("password", actual.getPassword()); + assertEquals( + "jdbc:postgresql://ec2-00-000-00-000.eu-west-1.compute.amazonaws.com:5432/d409qm4ujtafvk", + actual.getUrl()); + assertEquals("username", actual.getUsername()); + } +} diff --git a/src/test/java/io/chucknorris/api/feed/FeedControllerTest.java b/src/test/java/io/chucknorris/api/feed/FeedControllerTest.java index 93d5ddb..e5cb774 100644 --- a/src/test/java/io/chucknorris/api/feed/FeedControllerTest.java +++ b/src/test/java/io/chucknorris/api/feed/FeedControllerTest.java @@ -1,5 +1,8 @@ package io.chucknorris.api.feed; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.*; + import com.google.common.util.concurrent.AtomicDouble; import io.chucknorris.api.feed.dailychuck.DailyChuck; import io.chucknorris.api.feed.dailychuck.DailyChuckIssue; @@ -10,6 +13,12 @@ import io.chucknorris.lib.event.EventService; import io.chucknorris.lib.mailchimp.MailchimpService; import io.chucknorris.lib.mailchimp.MailingListStatistic; +import java.io.IOException; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Locale; +import java.util.concurrent.atomic.AtomicInteger; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -18,188 +27,156 @@ import org.mockito.junit.MockitoJUnitRunner; import org.springframework.test.util.ReflectionTestUtils; -import java.io.IOException; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Locale; -import java.util.concurrent.atomic.AtomicInteger; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.*; - @RunWith(MockitoJUnitRunner.class) public class FeedControllerTest { - private DailyChuck dailyChuck; + private DailyChuck dailyChuck; + + private DailyChuckIssue dailyChuckIssue; + + @Mock private DailyChuckService dailyChuckService; + + @Mock private DateUtil dateUtil; + + private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); + + @Mock private EventService eventService; + + @InjectMocks private FeedController feedController; + + @Mock private JokeRepository jokeRepository; + + @Mock private MailchimpService mailchimpService; + + private MailingListStatistic mailingListStatistic; + + private String mailingListId; + + @Before + public void setUp() throws ParseException { + dailyChuckIssue = new DailyChuckIssue(); + dailyChuckIssue.setDate(dateFormat.parse("2019-01-01")); + dailyChuckIssue.setJokeId("c5k7tulvqjs76evwb3brfg"); + + dailyChuck = new DailyChuck(); + dailyChuck.setIssues(new DailyChuckIssue[] {dailyChuckIssue}); + dailyChuck.setIssueNumber(Long.valueOf(1)); + + ReflectionTestUtils.setField(feedController, "dailyChuckListId", "xxxxxxxxxx"); + + mailingListId = "xxxxxxxxxx"; + mailingListStatistic = new MailingListStatistic(); + mailingListStatistic.setMemberCount(new AtomicInteger(228)); + mailingListStatistic.setUnsubscribeCount(new AtomicInteger(122)); + mailingListStatistic.setCleanedCount(new AtomicInteger(48)); + mailingListStatistic.setCampaignCount(new AtomicInteger(465)); + mailingListStatistic.setAvgSubRate(new AtomicInteger(23)); + mailingListStatistic.setAvgUnsubRate(new AtomicInteger(7)); + mailingListStatistic.setClickRate(new AtomicDouble(0.30748722)); + + when(mailchimpService.fetchListStats(mailingListId)).thenReturn(mailingListStatistic); + } - private DailyChuckIssue dailyChuckIssue; + @Test + public void testDailyChuckJsonReturnsDailyChuckWithoutComposingANewIssueIfItHasAlreadyBeenIssued() + throws IOException, ParseException { + when(dailyChuckService.getDailyChuck()).thenReturn(dailyChuck); + when(dateUtil.now()).thenReturn(dateFormat.parse("2019-01-01")); - @Mock - private DailyChuckService dailyChuckService; + assertEquals(dailyChuck, feedController.dailyChuckJson()); - @Mock - private DateUtil dateUtil; + verify(dailyChuckService, times(1)).getDailyChuck(); + verifyNoMoreInteractions(dailyChuckService); - private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); + verify(dateUtil, times(1)).now(); + verifyNoMoreInteractions(dateUtil); - @Mock - private EventService eventService; + verify(eventService, times(0)).publishEvent(any()); + verifyNoMoreInteractions(eventService); + } - @InjectMocks - private FeedController feedController; + @Test + public void testDailyChuckJsonReturnsDailyChuckWithComposingANewIssue() + throws IOException, ParseException { + DailyChuckIssue newDailyChuckIssue = new DailyChuckIssue(); - @Mock - private JokeRepository jokeRepository; + when(dailyChuckService.getDailyChuck()).thenReturn(dailyChuck); + when(dateUtil.now()).thenReturn(dateFormat.parse("2019-01-02")); + when(dailyChuckService.composeDailyChuckIssue(any())).thenReturn(newDailyChuckIssue); - @Mock - private MailchimpService mailchimpService; + assertEquals(dailyChuck, feedController.dailyChuckJson()); - private MailingListStatistic mailingListStatistic; + verify(dailyChuckService, times(1)).getDailyChuck(); + verify(dailyChuckService, times(1)).composeDailyChuckIssue(any()); + verify(dailyChuckService, times(1)).persist(dailyChuck); + verifyNoMoreInteractions(dailyChuckService); - private String mailingListId; + verify(dateUtil, times(1)).now(); + verifyNoMoreInteractions(dateUtil); - @Before - public void setUp() throws ParseException { - dailyChuckIssue = new DailyChuckIssue(); - dailyChuckIssue.setDate( - dateFormat.parse("2019-01-01") - ); - dailyChuckIssue.setJokeId("c5k7tulvqjs76evwb3brfg"); + verify(eventService, times(1)).publishEvent(any()); + verifyNoMoreInteractions(eventService); + } - dailyChuck = new DailyChuck(); - dailyChuck.setIssues(new DailyChuckIssue[]{dailyChuckIssue}); - dailyChuck.setIssueNumber(Long.valueOf(1)); + @Test + public void testDailyChuckRssReturnsDailyChuckWithoutComposingANewIssueIfItHasAlreadyBeenIssued() + throws IOException, ParseException { + DailyChuckRss dailyChuckRss = new DailyChuckRss("", dailyChuck, jokeRepository); - ReflectionTestUtils.setField(feedController, "dailyChuckListId", "xxxxxxxxxx"); + when(dailyChuckService.getDailyChuck()).thenReturn(dailyChuck); + when(dateUtil.now()).thenReturn(dateFormat.parse("2019-01-01")); + when(dailyChuckService.toRss(dailyChuck)).thenReturn(dailyChuckRss); - mailingListId = "xxxxxxxxxx"; - mailingListStatistic = new MailingListStatistic(); - mailingListStatistic.setMemberCount(new AtomicInteger(228)); - mailingListStatistic.setUnsubscribeCount(new AtomicInteger(122)); - mailingListStatistic.setCleanedCount(new AtomicInteger(48)); - mailingListStatistic.setCampaignCount(new AtomicInteger(465)); - mailingListStatistic.setAvgSubRate(new AtomicInteger(23)); - mailingListStatistic.setAvgUnsubRate(new AtomicInteger(7)); - mailingListStatistic.setClickRate( - new AtomicDouble(0.30748722) - ); + assertEquals(dailyChuckRss, feedController.dailyChuckRss()); - when(mailchimpService.fetchListStats(mailingListId)).thenReturn(mailingListStatistic); - } + verify(dailyChuckService, times(1)).getDailyChuck(); + verify(dailyChuckService, times(1)).toRss(dailyChuck); - @Test - public void testDailyChuckJsonReturnsDailyChuckWithoutComposingANewIssueIfItHasAlreadyBeenIssued() - throws IOException, ParseException { - when(dailyChuckService.getDailyChuck()).thenReturn(dailyChuck); - when(dateUtil.now()).thenReturn(dateFormat.parse("2019-01-01")); + verify(dateUtil, times(1)).now(); + verifyNoMoreInteractions(dateUtil); - assertEquals( - dailyChuck, - feedController.dailyChuckJson() - ); + verify(eventService, times(0)).publishEvent(any()); + verifyNoMoreInteractions(eventService); - verify(dailyChuckService, times(1)).getDailyChuck(); - verifyNoMoreInteractions(dailyChuckService); + verify(mailchimpService, times(1)).fetchListStats(mailingListId); + verifyNoMoreInteractions(mailchimpService); + } - verify(dateUtil, times(1)).now(); - verifyNoMoreInteractions(dateUtil); + @Test + public void testDailyChuckRssReturnsDailyChuckWithComposingANewIssue() + throws IOException, ParseException { + DailyChuckRss dailyChuckRss = new DailyChuckRss("", dailyChuck, jokeRepository); + DailyChuckIssue newDailyChuckIssue = new DailyChuckIssue(); - verify(eventService, times(0)).publishEvent(any()); - verifyNoMoreInteractions(eventService); - } + when(dailyChuckService.getDailyChuck()).thenReturn(dailyChuck); + when(dateUtil.now()).thenReturn(dateFormat.parse("2019-01-02")); + when(dailyChuckService.composeDailyChuckIssue(any())).thenReturn(newDailyChuckIssue); + when(dailyChuckService.toRss(dailyChuck)).thenReturn(dailyChuckRss); + + assertEquals(dailyChuckRss, feedController.dailyChuckRss()); - @Test - public void testDailyChuckJsonReturnsDailyChuckWithComposingANewIssue() - throws IOException, ParseException { - DailyChuckIssue newDailyChuckIssue = new DailyChuckIssue(); + verify(dailyChuckService, times(1)).getDailyChuck(); + verify(dailyChuckService, times(1)).composeDailyChuckIssue(any()); + verify(dailyChuckService, times(1)).persist(dailyChuck); + verify(dailyChuckService, times(1)).toRss(dailyChuck); + verifyNoMoreInteractions(dailyChuckService); - when(dailyChuckService.getDailyChuck()).thenReturn(dailyChuck); - when(dateUtil.now()).thenReturn(dateFormat.parse("2019-01-02")); - when(dailyChuckService.composeDailyChuckIssue(any())).thenReturn(newDailyChuckIssue); + verify(dateUtil, times(1)).now(); + verifyNoMoreInteractions(dateUtil); - assertEquals( - dailyChuck, - feedController.dailyChuckJson() - ); + verify(eventService, times(1)).publishEvent(any()); + verifyNoMoreInteractions(eventService); - verify(dailyChuckService, times(1)).getDailyChuck(); - verify(dailyChuckService, times(1)).composeDailyChuckIssue(any()); - verify(dailyChuckService, times(1)).persist(dailyChuck); - verifyNoMoreInteractions(dailyChuckService); + verify(mailchimpService, times(1)).fetchListStats(mailingListId); + verifyNoMoreInteractions(mailchimpService); + } - verify(dateUtil, times(1)).now(); - verifyNoMoreInteractions(dateUtil); + @Test + public void testDailyChuckStatsReturnsStats() { + MailingListStatistic response = feedController.dailyChuckStats(); + assertEquals(response, mailingListStatistic); - verify(eventService, times(1)).publishEvent(any()); - verifyNoMoreInteractions(eventService); - } - - @Test - public void testDailyChuckRssReturnsDailyChuckWithoutComposingANewIssueIfItHasAlreadyBeenIssued() - throws IOException, ParseException { - DailyChuckRss dailyChuckRss = new DailyChuckRss("", dailyChuck, jokeRepository); - - when(dailyChuckService.getDailyChuck()).thenReturn(dailyChuck); - when(dateUtil.now()).thenReturn(dateFormat.parse("2019-01-01")); - when(dailyChuckService.toRss(dailyChuck)).thenReturn(dailyChuckRss); - - assertEquals( - dailyChuckRss, - feedController.dailyChuckRss() - ); - - verify(dailyChuckService, times(1)).getDailyChuck(); - verify(dailyChuckService, times(1)).toRss(dailyChuck); - - verify(dateUtil, times(1)).now(); - verifyNoMoreInteractions(dateUtil); - - verify(eventService, times(0)).publishEvent(any()); - verifyNoMoreInteractions(eventService); - - verify(mailchimpService, times(1)).fetchListStats(mailingListId); - verifyNoMoreInteractions(mailchimpService); - } - - @Test - public void testDailyChuckRssReturnsDailyChuckWithComposingANewIssue() - throws IOException, ParseException { - DailyChuckRss dailyChuckRss = new DailyChuckRss("", dailyChuck, jokeRepository); - DailyChuckIssue newDailyChuckIssue = new DailyChuckIssue(); - - when(dailyChuckService.getDailyChuck()).thenReturn(dailyChuck); - when(dateUtil.now()).thenReturn(dateFormat.parse("2019-01-02")); - when(dailyChuckService.composeDailyChuckIssue(any())).thenReturn(newDailyChuckIssue); - when(dailyChuckService.toRss(dailyChuck)).thenReturn(dailyChuckRss); - - assertEquals( - dailyChuckRss, - feedController.dailyChuckRss() - ); - - verify(dailyChuckService, times(1)).getDailyChuck(); - verify(dailyChuckService, times(1)).composeDailyChuckIssue(any()); - verify(dailyChuckService, times(1)).persist(dailyChuck); - verify(dailyChuckService, times(1)).toRss(dailyChuck); - verifyNoMoreInteractions(dailyChuckService); - - verify(dateUtil, times(1)).now(); - verifyNoMoreInteractions(dateUtil); - - verify(eventService, times(1)).publishEvent(any()); - verifyNoMoreInteractions(eventService); - - verify(mailchimpService, times(1)).fetchListStats(mailingListId); - verifyNoMoreInteractions(mailchimpService); - } - - @Test - public void testDailyChuckStatsReturnsStats() { - MailingListStatistic response = feedController.dailyChuckStats(); - assertEquals(response, mailingListStatistic); - - verify(mailchimpService, times(1)).fetchListStats(mailingListId); - verifyNoMoreInteractions(mailchimpService); - } -} \ No newline at end of file + verify(mailchimpService, times(1)).fetchListStats(mailingListId); + verifyNoMoreInteractions(mailchimpService); + } +} diff --git a/src/test/java/io/chucknorris/api/feed/dailychuck/DailyChuckRssTest.java b/src/test/java/io/chucknorris/api/feed/dailychuck/DailyChuckRssTest.java index 3af1d35..f547b6e 100644 --- a/src/test/java/io/chucknorris/api/feed/dailychuck/DailyChuckRssTest.java +++ b/src/test/java/io/chucknorris/api/feed/dailychuck/DailyChuckRssTest.java @@ -1,3 +1 @@ -public class DailyChuckRssTest { - -} \ No newline at end of file +public class DailyChuckRssTest {} diff --git a/src/test/java/io/chucknorris/api/feed/dailychuck/DailyChuckTest.java b/src/test/java/io/chucknorris/api/feed/dailychuck/DailyChuckTest.java index 9b5a2e8..758222c 100644 --- a/src/test/java/io/chucknorris/api/feed/dailychuck/DailyChuckTest.java +++ b/src/test/java/io/chucknorris/api/feed/dailychuck/DailyChuckTest.java @@ -11,43 +11,37 @@ public class DailyChuckTest { - private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); - private DailyChuck dailyChuck; - private DailyChuckIssue dailyChuckIssue; - - @Before - public void setUp() throws ParseException { - dailyChuckIssue = new DailyChuckIssue(); - dailyChuckIssue.setDate( - dateFormat.parse("2019-01-01") - ); - dailyChuckIssue.setJokeId("c5k7tulvqjs76evwb3brfg"); - - dailyChuck = new DailyChuck(); - dailyChuck.setIssues(new DailyChuckIssue[]{dailyChuckIssue}); - } - - @Test - public void testFindIssueByJokeIdReturnsNullDoesNotExist() { - assertEquals(dailyChuck.findIssueByJokeId("does-not-exist"), null); - } - - @Test - public void testFindIssueByJokeIdReturnsDailyChuckIssueIfDoesExist() { - assertEquals(dailyChuck.findIssueByJokeId("c5k7tulvqjs76evwb3brfg"), dailyChuckIssue); - } - - @Test - public void testFindIssueByDateReturnsNullDoesNotExist() throws ParseException { - assertEquals(dailyChuck.findIssueByDate( - dateFormat.parse("2019-01-02") - ), null); - } - - @Test - public void testFindIssueByDateDailyChuckIssueIfDoesExist() throws ParseException { - assertEquals(dailyChuck.findIssueByDate( - dateFormat.parse("2019-01-01") - ), dailyChuckIssue); - } -} \ No newline at end of file + private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); + private DailyChuck dailyChuck; + private DailyChuckIssue dailyChuckIssue; + + @Before + public void setUp() throws ParseException { + dailyChuckIssue = new DailyChuckIssue(); + dailyChuckIssue.setDate(dateFormat.parse("2019-01-01")); + dailyChuckIssue.setJokeId("c5k7tulvqjs76evwb3brfg"); + + dailyChuck = new DailyChuck(); + dailyChuck.setIssues(new DailyChuckIssue[] {dailyChuckIssue}); + } + + @Test + public void testFindIssueByJokeIdReturnsNullDoesNotExist() { + assertEquals(dailyChuck.findIssueByJokeId("does-not-exist"), null); + } + + @Test + public void testFindIssueByJokeIdReturnsDailyChuckIssueIfDoesExist() { + assertEquals(dailyChuck.findIssueByJokeId("c5k7tulvqjs76evwb3brfg"), dailyChuckIssue); + } + + @Test + public void testFindIssueByDateReturnsNullDoesNotExist() throws ParseException { + assertEquals(dailyChuck.findIssueByDate(dateFormat.parse("2019-01-02")), null); + } + + @Test + public void testFindIssueByDateDailyChuckIssueIfDoesExist() throws ParseException { + assertEquals(dailyChuck.findIssueByDate(dateFormat.parse("2019-01-01")), dailyChuckIssue); + } +} diff --git a/src/test/java/io/chucknorris/api/joke/JokeControllerTest.java b/src/test/java/io/chucknorris/api/joke/JokeControllerTest.java index af07d09..58fea09 100644 --- a/src/test/java/io/chucknorris/api/joke/JokeControllerTest.java +++ b/src/test/java/io/chucknorris/api/joke/JokeControllerTest.java @@ -24,31 +24,22 @@ public class JokeControllerTest { private static String jokeId, jokeValue; private static Joke joke; - @InjectMocks - private JokeController jokeController; + @InjectMocks private JokeController jokeController; - @Mock - private JokeRepository jokeRepository; + @Mock private JokeRepository jokeRepository; - @Mock - private MockHttpServletResponse httpServletResponse; + @Mock private MockHttpServletResponse httpServletResponse; @Before public void setUp() { jokeId = "ys--0t_-rrifz5jtcparbg"; jokeValue = "Some people ask for a Kleenex when they sneeze, Chuck Norris asks for a body bag."; - joke = Joke.builder() - .categories(new String[]{"dev"}) - .id(jokeId) - .value(jokeValue) - .build(); + joke = Joke.builder().categories(new String[] {"dev"}).id(jokeId).value(jokeValue).build(); } @Test public void testGetCategories() { - when(jokeRepository.findAllCategories()).thenReturn( - new String[]{"dev", "animal"} - ); + when(jokeRepository.findAllCategories()).thenReturn(new String[] {"dev", "animal"}); String[] categories = jokeController.getCategories(); assertEquals("dev", categories[0]); @@ -61,7 +52,7 @@ public void testGetCategories() { @Test public void testGetCategoryValues() { - when(jokeRepository.findAllCategories()).thenReturn(new String[]{"dev", "animal"}); + when(jokeRepository.findAllCategories()).thenReturn(new String[] {"dev", "animal"}); String categoryValues = jokeController.getCategoryValues(); assertEquals("dev\nanimal\n", categoryValues); @@ -117,9 +108,8 @@ public void testGetJokeValueReturnsEmptyStringIfEntityNotFound() { @Test public void getJokeViewReturnsModelAndView() { when(jokeRepository.findById(jokeId)).thenReturn(Optional.of(joke)); - when(jokeRepository.getJokeWindow(jokeId)).thenReturn( - jokeId + ',' + "yvrhbpauspegla4pf7dxna" + ',' + "id4dTcDiRneK4btgOGpNNw" - ); + when(jokeRepository.getJokeWindow(jokeId)) + .thenReturn(jokeId + ',' + "yvrhbpauspegla4pf7dxna" + ',' + "id4dTcDiRneK4btgOGpNNw"); ModelAndView view = jokeController.getJokeView(jokeId); assertEquals(joke, view.getModel().get("joke")); @@ -146,7 +136,7 @@ public void testGetRandomJokeReturnsJoke() { @Test public void testGetRandomJokeReturnsJokeByCategory() { when(jokeRepository.getRandomJokeByCategory("dev")).thenReturn(joke); - when(jokeRepository.findAllCategories()).thenReturn(new String[]{"dev"}); + when(jokeRepository.findAllCategories()).thenReturn(new String[] {"dev"}); Joke joke = jokeController.getRandomJoke("dev", null); assertEquals(JokeControllerTest.joke, joke); @@ -158,7 +148,7 @@ public void testGetRandomJokeReturnsJokeByCategory() { @Test(expected = EntityNotFoundException.class) public void testGetRandomJokeReturnsJokeByCategoryThrowsException() { - when(jokeRepository.findAllCategories()).thenReturn(new String[]{}); + when(jokeRepository.findAllCategories()).thenReturn(new String[] {}); jokeController.getRandomJoke("dev", null); @@ -169,21 +159,19 @@ public void testGetRandomJokeReturnsJokeByCategoryThrowsException() { @Test public void testGetRandomJokeReturnsJokeByMultipleCategories() { when(jokeRepository.getRandomJokeByCategories("dev,movie")).thenReturn(joke); - when(jokeRepository.findAllCategories()).thenReturn(new String[]{"dev", "movie"}); + when(jokeRepository.findAllCategories()).thenReturn(new String[] {"dev", "movie"}); Joke joke = jokeController.getRandomJoke("dev,movie", null); assertEquals(JokeControllerTest.joke, joke); verify(jokeRepository, times(1)).findAllCategories(); - verify(jokeRepository, times(1)).getRandomJokeByCategories( - "dev,movie" - ); + verify(jokeRepository, times(1)).getRandomJokeByCategories("dev,movie"); verifyNoMoreInteractions(jokeRepository); } @Test(expected = EntityNotFoundException.class) public void testGetRandomJokeReturnsJokeByMultipleCategoriesThrowsException() { - when(jokeRepository.findAllCategories()).thenReturn(new String[]{}); + when(jokeRepository.findAllCategories()).thenReturn(new String[] {}); jokeController.getRandomJoke("dev,does-not-exist", null); @@ -193,9 +181,7 @@ public void testGetRandomJokeReturnsJokeByMultipleCategoriesThrowsException() { @Test public void testGetRandomPersonalisedJokeReturnsJoke() { - joke = joke.toBuilder() - .value(joke.getValue().replace("Chuck Norris", "Bob")) - .build(); + joke = joke.toBuilder().value(joke.getValue().replace("Chuck Norris", "Bob")).build(); when(jokeRepository.getRandomPersonalizedJoke("Bob")).thenReturn(joke); Joke joke = jokeController.getRandomJoke(null, "Bob"); @@ -207,42 +193,30 @@ public void testGetRandomPersonalisedJokeReturnsJoke() { @Test public void testGetRandomPersonalisedJokeByCategoryReturnsJoke() { - joke = joke.toBuilder().value( - joke.getValue().replace("Chuck Norris", "Bob") - ).build(); - when(jokeRepository.findAllCategories()).thenReturn(new String[]{"dev"}); - when(jokeRepository.getRandomPersonalizedJokeByCategories( - "Bob", "dev" - )).thenReturn(joke); + joke = joke.toBuilder().value(joke.getValue().replace("Chuck Norris", "Bob")).build(); + when(jokeRepository.findAllCategories()).thenReturn(new String[] {"dev"}); + when(jokeRepository.getRandomPersonalizedJokeByCategories("Bob", "dev")).thenReturn(joke); Joke joke = jokeController.getRandomJoke("dev", "Bob"); assertEquals(JokeControllerTest.joke, joke); verify(jokeRepository, times(1)).findAllCategories(); - verify(jokeRepository, times(1)).getRandomPersonalizedJokeByCategories( - "Bob", "dev" - ); + verify(jokeRepository, times(1)).getRandomPersonalizedJokeByCategories("Bob", "dev"); verifyNoMoreInteractions(jokeRepository); } @Test(expected = EntityNotFoundException.class) public void testGetRandomPersonalisedJokeByCategoryThrowsException() { - joke = joke.toBuilder().value( - joke.getValue().replace("Chuck Norris", "Bob") - ).build(); - when(jokeRepository.findAllCategories()).thenReturn(new String[]{"dev"}); - when(jokeRepository.getRandomPersonalizedJokeByCategories( - "Bob", "dev" - )).thenReturn(null); + joke = joke.toBuilder().value(joke.getValue().replace("Chuck Norris", "Bob")).build(); + when(jokeRepository.findAllCategories()).thenReturn(new String[] {"dev"}); + when(jokeRepository.getRandomPersonalizedJokeByCategories("Bob", "dev")).thenReturn(null); jokeController.getRandomJoke("dev", "Bob"); } @Test(expected = EntityNotFoundException.class) public void testGetRandomPersonalisedJokeThrowsException() { - joke = joke.toBuilder().value( - joke.getValue().replace("Chuck Norris", "Bob") - ).build(); + joke = joke.toBuilder().value(joke.getValue().replace("Chuck Norris", "Bob")).build(); when(jokeRepository.getRandomPersonalizedJoke("Bob")).thenReturn(null); jokeController.getRandomJoke(null, "Bob"); @@ -255,9 +229,7 @@ public void testGetRandomPersonalisedJokeThrowsException() { public void testGetRandomJokeReturnsJokeValue() { when(jokeRepository.getRandomJoke()).thenReturn(joke); - String jokeValue = jokeController.getRandomJokeValue( - null, null, this.httpServletResponse - ); + String jokeValue = jokeController.getRandomJokeValue(null, null, this.httpServletResponse); assertEquals(joke.getValue(), jokeValue); verify(jokeRepository, times(1)).getRandomJoke(); @@ -267,11 +239,9 @@ public void testGetRandomJokeReturnsJokeValue() { @Test public void testGetRandomJokeReturnsJokeValueByCategory() { when(jokeRepository.getRandomJokeByCategory("dev")).thenReturn(joke); - when(jokeRepository.findAllCategories()).thenReturn(new String[]{"dev"}); + when(jokeRepository.findAllCategories()).thenReturn(new String[] {"dev"}); - String jokeValue = jokeController.getRandomJokeValue( - "dev", null, this.httpServletResponse - ); + String jokeValue = jokeController.getRandomJokeValue("dev", null, this.httpServletResponse); assertEquals(joke.getValue(), jokeValue); verify(jokeRepository, times(1)).findAllCategories(); @@ -282,27 +252,23 @@ public void testGetRandomJokeReturnsJokeValueByCategory() { @Test public void testGetRandomJokeReturnsJokeValueByMultipleCategories() { when(jokeRepository.getRandomJokeByCategories("dev,movie")).thenReturn(joke); - when(jokeRepository.findAllCategories()).thenReturn(new String[]{"dev", "movie"}); + when(jokeRepository.findAllCategories()).thenReturn(new String[] {"dev", "movie"}); - String jokeValue = jokeController.getRandomJokeValue( - "dev,movie", null, this.httpServletResponse - ); + String jokeValue = + jokeController.getRandomJokeValue("dev,movie", null, this.httpServletResponse); assertEquals(joke.getValue(), jokeValue); verify(jokeRepository, times(1)).findAllCategories(); - verify(jokeRepository, times(1)).getRandomJokeByCategories( - "dev,movie" - ); + verify(jokeRepository, times(1)).getRandomJokeByCategories("dev,movie"); verifyNoMoreInteractions(jokeRepository); } @Test public void testGetRandomJokeValueReturnsEmptyStringIfCategoryDoesNotExist() { - when(jokeRepository.findAllCategories()).thenReturn(new String[]{}); + when(jokeRepository.findAllCategories()).thenReturn(new String[] {}); - String jokeValue = jokeController.getRandomJokeValue( - "does-not-exist", null, this.httpServletResponse - ); + String jokeValue = + jokeController.getRandomJokeValue("does-not-exist", null, this.httpServletResponse); assertEquals("", jokeValue); verify(jokeRepository, times(1)).findAllCategories(); @@ -312,14 +278,10 @@ public void testGetRandomJokeValueReturnsEmptyStringIfCategoryDoesNotExist() { @Test public void testGetRandomPersonalisedJokeValueReturnsJokeValue() { - joke = joke.toBuilder().value( - joke.getValue().replace("Chuck Norris", "Bob") - ).build(); + joke = joke.toBuilder().value(joke.getValue().replace("Chuck Norris", "Bob")).build(); when(jokeRepository.getRandomPersonalizedJoke("Bob")).thenReturn(joke); - String jokeValue = jokeController.getRandomJokeValue( - null, "Bob", this.httpServletResponse - ); + String jokeValue = jokeController.getRandomJokeValue(null, "Bob", this.httpServletResponse); assertEquals(joke.getValue(), jokeValue); verify(jokeRepository, times(1)).getRandomPersonalizedJoke("Bob"); @@ -328,14 +290,10 @@ public void testGetRandomPersonalisedJokeValueReturnsJokeValue() { @Test public void testGetRandomPersonalisedJokeValueEmptyStringIfNoJokeWasFound() { - joke = joke.toBuilder().value( - joke.getValue().replace("Chuck Norris", "Bob") - ).build(); + joke = joke.toBuilder().value(joke.getValue().replace("Chuck Norris", "Bob")).build(); when(jokeRepository.getRandomPersonalizedJoke("Bob")).thenReturn(null); - String jokeValue = jokeController.getRandomJokeValue( - null, "Bob", this.httpServletResponse - ); + String jokeValue = jokeController.getRandomJokeValue(null, "Bob", this.httpServletResponse); assertEquals("", jokeValue); verify(jokeRepository, times(1)).getRandomPersonalizedJoke("Bob"); @@ -345,15 +303,11 @@ public void testGetRandomPersonalisedJokeValueEmptyStringIfNoJokeWasFound() { @Test public void testGetRandomPersonalisedJokeValueByCategoryReturnsJokeValue() { - joke = joke.toBuilder().value( - joke.getValue().replace("Chuck Norris", "Bob") - ).build(); - when(jokeRepository.findAllCategories()).thenReturn(new String[]{"dev"}); + joke = joke.toBuilder().value(joke.getValue().replace("Chuck Norris", "Bob")).build(); + when(jokeRepository.findAllCategories()).thenReturn(new String[] {"dev"}); when(jokeRepository.getRandomPersonalizedJokeByCategories("Bob", "dev")).thenReturn(joke); - String jokeValue = jokeController.getRandomJokeValue( - "dev", "Bob", this.httpServletResponse - ); + String jokeValue = jokeController.getRandomJokeValue("dev", "Bob", this.httpServletResponse); assertEquals(joke.getValue(), jokeValue); verify(jokeRepository, times(1)).findAllCategories(); @@ -363,15 +317,11 @@ public void testGetRandomPersonalisedJokeValueByCategoryReturnsJokeValue() { @Test public void testGetRandomPersonalisedJokeValueByCategoryEmptyStringIfNoJokeWasFound() { - joke = joke.toBuilder().value( - joke.getValue().replace("Chuck Norris", "Bob") - ).build(); - when(jokeRepository.findAllCategories()).thenReturn(new String[]{"dev"}); + joke = joke.toBuilder().value(joke.getValue().replace("Chuck Norris", "Bob")).build(); + when(jokeRepository.findAllCategories()).thenReturn(new String[] {"dev"}); when(jokeRepository.getRandomPersonalizedJokeByCategories("Bob", "dev")).thenReturn(null); - String jokeValue = jokeController.getRandomJokeValue( - "dev", "Bob", this.httpServletResponse - ); + String jokeValue = jokeController.getRandomJokeValue("dev", "Bob", this.httpServletResponse); assertEquals("", jokeValue); verify(jokeRepository, times(1)).findAllCategories(); @@ -382,7 +332,7 @@ public void testGetRandomPersonalisedJokeValueByCategoryEmptyStringIfNoJokeWasFo @Test public void testSearch() { - when(jokeRepository.searchByQuery("Kleenex")).thenReturn(new Joke[]{joke}); + when(jokeRepository.searchByQuery("Kleenex")).thenReturn(new Joke[] {joke}); JokeSearchResult jokeSearchResult = jokeController.search("Kleenex"); assertEquals(jokeSearchResult.getTotal(), 1); @@ -394,14 +344,14 @@ public void testSearch() { @Test public void testSearchValues() { - when(jokeRepository.searchByQuery("Kleenex")).thenReturn(new Joke[]{joke}); + when(jokeRepository.searchByQuery("Kleenex")).thenReturn(new Joke[] {joke}); String searchValues = jokeController.searchValues("Kleenex"); assertEquals( - "Some people ask for a Kleenex when they sneeze, Chuck Norris asks for a body bag.\n", + "Some people ask for a Kleenex when they sneeze, Chuck Norris asks for a body" + " bag.\n", searchValues); verify(jokeRepository, times(1)).searchByQuery("Kleenex"); verifyNoMoreInteractions(jokeRepository); } -} \ No newline at end of file +} diff --git a/src/test/java/io/chucknorris/api/joke/JokeServiceTest.java b/src/test/java/io/chucknorris/api/joke/JokeServiceTest.java index 099607e..baf5080 100644 --- a/src/test/java/io/chucknorris/api/joke/JokeServiceTest.java +++ b/src/test/java/io/chucknorris/api/joke/JokeServiceTest.java @@ -22,28 +22,22 @@ public class JokeServiceTest { private static String jokeId, jokeValue; private static Joke joke; - @Mock - private JokeRepository jokeRepository; + @Mock private JokeRepository jokeRepository; - @InjectMocks - private JokeService jokeService; + @InjectMocks private JokeService jokeService; @Before public void setUp() throws Exception { jokeId = "ys--0t_-rrifz5jtcparbg"; jokeValue = "Some people ask for a Kleenex when they sneeze, Chuck Norris asks for a body bag."; - joke = Joke.builder() - .categories(new String[]{"dev"}) - .id(jokeId) - .value(jokeValue) - .build(); + joke = Joke.builder().categories(new String[] {"dev"}).id(jokeId).value(jokeValue).build(); } @Test public void testRandomJokeByCategoriesReturnsJoke() { when(jokeRepository.getRandomJokeByCategories("dev,movie")).thenReturn(joke); - Joke joke = jokeService.randomJokeByCategories(new String[]{"dev", "movie"}); + Joke joke = jokeService.randomJokeByCategories(new String[] {"dev", "movie"}); assertEquals(JokeServiceTest.joke, joke); verify(jokeRepository, times(1)).getRandomJokeByCategories("dev,movie"); @@ -53,43 +47,31 @@ public void testRandomJokeByCategoriesReturnsJoke() { @Test public void testRandomPersonalizedJokeByCategoriesReturnsJoke() { String substitute = "Bob"; - String[] categories = new String[]{"dev", "movie"}; + String[] categories = new String[] {"dev", "movie"}; joke.setValue(joke.getValue().replace("Chuck Norris", substitute)); - when( - jokeRepository.getRandomPersonalizedJokeByCategories( - substitute, - "dev,movie" - ) - ).thenReturn(joke); + when(jokeRepository.getRandomPersonalizedJokeByCategories(substitute, "dev,movie")) + .thenReturn(joke); Joke joke = jokeService.randomPersonalizedJokeByCategories(substitute, categories); assertEquals(JokeServiceTest.joke, joke); - verify(jokeRepository, times(1)).getRandomPersonalizedJokeByCategories( - substitute, - "dev,movie" - ); + verify(jokeRepository, times(1)).getRandomPersonalizedJokeByCategories(substitute, "dev,movie"); verifyNoMoreInteractions(jokeRepository); } @Test public void testSearchWithCategoryFilter() { String query = "Kleenex"; - String[] categories = new String[]{"dev", "movie"}; + String[] categories = new String[] {"dev", "movie"}; Pageable pageable = PageRequest.of(1, 5); - when( - jokeRepository.findByValueContainsAndFilter(query, "dev,movie", pageable) - ).thenReturn(Page.empty()); + when(jokeRepository.findByValueContainsAndFilter(query, "dev,movie", pageable)) + .thenReturn(Page.empty()); jokeService.searchWithCategoryFilter(query, categories, pageable); - verify(jokeRepository, times(1)).findByValueContainsAndFilter( - query, - "dev,movie", - pageable - ); + verify(jokeRepository, times(1)).findByValueContainsAndFilter(query, "dev,movie", pageable); verifyNoMoreInteractions(jokeRepository); } -} \ No newline at end of file +} diff --git a/src/test/java/io/chucknorris/api/slack/SlackControllerTest.java b/src/test/java/io/chucknorris/api/slack/SlackControllerTest.java index bc8b677..d0669be 100644 --- a/src/test/java/io/chucknorris/api/slack/SlackControllerTest.java +++ b/src/test/java/io/chucknorris/api/slack/SlackControllerTest.java @@ -1,10 +1,17 @@ package io.chucknorris.api.slack; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.*; + import com.fasterxml.jackson.core.JsonProcessingException; import io.chucknorris.api.joke.Joke; import io.chucknorris.api.joke.JokeRepository; import io.chucknorris.api.joke.JokeService; import io.chucknorris.lib.event.EventService; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -19,607 +26,585 @@ import org.springframework.test.util.ReflectionTestUtils; import org.springframework.web.servlet.ModelAndView; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Optional; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.*; - @RunWith(MockitoJUnitRunner.class) public class SlackControllerTest { - private static String iconUrl, jokeId, jokeValue; - private static Joke joke; - - @Mock - private EventService eventService; - - @Mock - JokeService jokeService; - - @Mock - private JokeRepository jokeRepository; - - @InjectMocks - private SlackController slackController; - - @Mock - private SlackService slackService; - - private String[] whiteListedCategories = new String[]{ - "career", - "dev", - "fashion", - "food", - "money", - "movie", - "travel" - }; - - @Before - public void setUp() { - ReflectionTestUtils.setField(slackController, "baseUrl", "localhost"); - - iconUrl = "https://assets.chucknorris.host/img/avatar/chuck-norris.png"; - jokeId = "bg_h3xursougaxzprcrl0q"; - jokeValue = "Chuck Norris programs do not accept input."; - joke = Joke.builder() - .categories(new String[]{"dev"}) - .id(jokeId) - .value(jokeValue) - .build(); - - when( - slackService.getWhitelistedCategories() - ).thenReturn( - whiteListedCategories - ); - - when( - slackService.filterNonWhitelistedCategories(new String[]{"dev", "fashion", "food"}) - ).thenReturn( - new String[]{"dev", "fashion", "food"} - ); - - when( - slackService.filterNonWhitelistedCategories(new String[]{"dev", "explicit", "fashion", "food"}) - ).thenReturn( - new String[]{"dev", "fashion", "food"} - ); - } - - @Test - public void testConnect() throws JsonProcessingException { - AccessToken accessToken = new AccessToken(); - accessToken.setAccessToken("23BE2D81-35B6-4B73-BCC9-8B6731D2540E"); - accessToken.setTeamName("ACME"); - - when(slackService.requestAccessToken("my-super-secret-code")).thenReturn(accessToken); - when(eventService.publishEvent(any(SlackConnectEvent.class))).thenReturn(null); + private static String iconUrl, jokeId, jokeValue; + private static Joke joke; - ModelAndView view = slackController.connect("my-super-secret-code"); - assertEquals(HttpStatus.OK, view.getStatus()); - assertEquals("Congrats, the app was successfully installed for your Slack team!", view.getModel().get("page_title")); - assertEquals(false, view.getModel().get("error")); - assertEquals(null, view.getModel().get("message")); + @Mock private EventService eventService; - verify(slackService, times(1)).requestAccessToken("my-super-secret-code"); - verifyNoMoreInteractions(slackService); + @Mock JokeService jokeService; - verify(eventService, times(1)).publishEvent(any(SlackConnectEvent.class)); - verifyNoMoreInteractions(eventService); - } - - @Test - public void testConnectSetsErrorIfAuthenticationTokenIsNull() throws JsonProcessingException { - AccessToken accessToken = new AccessToken(); - - when(slackService.requestAccessToken("my-super-secret-code")).thenReturn(accessToken); - - ModelAndView view = slackController.connect("my-super-secret-code"); - assertEquals(HttpStatus.UNAUTHORIZED, view.getStatus()); - assertEquals("Oops, an error has occurred.", view.getModel().get("page_title")); - assertEquals(true, view.getModel().get("error")); - assertEquals("Oops, an error has occurred. Please try again later!", view.getModel().get("message")); - - verify(slackService, times(1)).requestAccessToken("my-super-secret-code"); - verifyNoMoreInteractions(slackService); + @Mock private JokeRepository jokeRepository; - verify(eventService, times(0)).publishEvent(any()); - verifyNoMoreInteractions(eventService); + @InjectMocks private SlackController slackController; + + @Mock private SlackService slackService; + + private String[] whiteListedCategories = + new String[] {"career", "dev", "fashion", "food", "money", "movie", "travel"}; + + @Before + public void setUp() { + ReflectionTestUtils.setField(slackController, "baseUrl", "localhost"); + + iconUrl = "https://assets.chucknorris.host/img/avatar/chuck-norris.png"; + jokeId = "bg_h3xursougaxzprcrl0q"; + jokeValue = "Chuck Norris programs do not accept input."; + joke = Joke.builder().categories(new String[] {"dev"}).id(jokeId).value(jokeValue).build(); + + when(slackService.getWhitelistedCategories()).thenReturn(whiteListedCategories); + + when(slackService.filterNonWhitelistedCategories(new String[] {"dev", "fashion", "food"})) + .thenReturn(new String[] {"dev", "fashion", "food"}); + + when(slackService.filterNonWhitelistedCategories( + new String[] {"dev", "explicit", "fashion", "food"})) + .thenReturn(new String[] {"dev", "fashion", "food"}); + } + + @Test + public void testConnect() throws JsonProcessingException { + AccessToken accessToken = new AccessToken(); + accessToken.setAccessToken("23BE2D81-35B6-4B73-BCC9-8B6731D2540E"); + accessToken.setTeamName("ACME"); + + when(slackService.requestAccessToken("my-super-secret-code")).thenReturn(accessToken); + when(eventService.publishEvent(any(SlackConnectEvent.class))).thenReturn(null); + + ModelAndView view = slackController.connect("my-super-secret-code"); + assertEquals(HttpStatus.OK, view.getStatus()); + assertEquals( + "Congrats, the app was successfully installed for your Slack team!", + view.getModel().get("page_title")); + assertEquals(false, view.getModel().get("error")); + assertEquals(null, view.getModel().get("message")); + + verify(slackService, times(1)).requestAccessToken("my-super-secret-code"); + verifyNoMoreInteractions(slackService); + + verify(eventService, times(1)).publishEvent(any(SlackConnectEvent.class)); + verifyNoMoreInteractions(eventService); + } + + @Test + public void testConnectSetsErrorIfAuthenticationTokenIsNull() throws JsonProcessingException { + AccessToken accessToken = new AccessToken(); + + when(slackService.requestAccessToken("my-super-secret-code")).thenReturn(accessToken); + + ModelAndView view = slackController.connect("my-super-secret-code"); + assertEquals(HttpStatus.UNAUTHORIZED, view.getStatus()); + assertEquals("Oops, an error has occurred.", view.getModel().get("page_title")); + assertEquals(true, view.getModel().get("error")); + assertEquals( + "Oops, an error has occurred. Please try again later!", view.getModel().get("message")); + + verify(slackService, times(1)).requestAccessToken("my-super-secret-code"); + verifyNoMoreInteractions(slackService); + + verify(eventService, times(0)).publishEvent(any()); + verifyNoMoreInteractions(eventService); + } + + @Test + public void testReturnHelpIfTextEqualsHelp() { + Request request = new Request(); + request.setText("help"); + + SlackCommandResponse response = slackController.command(request); + assertEquals(iconUrl, response.getIconUrl()); + assertEquals("*Available commands:*", response.getText()); + assertEquals(ResponseType.EPHEMERAL, response.getResponseType()); + + SlackCommandResponseAttachment newsletter = response.getAttachments()[0]; + assertEquals(null, newsletter.getFallback()); + assertEquals( + ":facepunch: Sign up for *The Daily Chuck* and get your daily dose of the best" + + " #ChuckNorrisFacts every morning straight int your inbox!" + + " https://mailchi.mp/5a19a2898bf7/the-daily-chuck", + newsletter.getText()); + assertEquals("The Daily Chuck", newsletter.getTitle()); + assertEquals(null, newsletter.getTitleLink()); + assertArrayEquals(new String[] {"text"}, newsletter.getMrkdownIn()); + + SlackCommandResponseAttachment randomJoke = response.getAttachments()[1]; + assertEquals(null, randomJoke.getFallback()); + assertEquals("Type `/chuck` to get a random joke.", randomJoke.getText()); + assertEquals("Random joke", randomJoke.getTitle()); + assertEquals(null, randomJoke.getTitleLink()); + assertArrayEquals(new String[] {"text"}, randomJoke.getMrkdownIn()); + + SlackCommandResponseAttachment search = response.getAttachments()[2]; + assertEquals(null, search.getFallback()); + assertEquals( + "Type `/chuck ? {search_term}` to search within tens of thousands Chuck Norris" + " jokes.", + search.getText()); + assertEquals("Free text search", search.getTitle()); + assertEquals(null, search.getTitleLink()); + assertArrayEquals(new String[] {"text"}, search.getMrkdownIn()); + + SlackCommandResponseAttachment randomJokePersonalized = response.getAttachments()[3]; + assertEquals(null, randomJokePersonalized.getFallback()); + assertEquals( + "Type `/chuck @ {user_name}` to get a random personalized joke.", + randomJokePersonalized.getText()); + assertEquals("Random personalized joke", randomJokePersonalized.getTitle()); + assertEquals(null, randomJokePersonalized.getTitleLink()); + assertArrayEquals(new String[] {"text"}, randomJokePersonalized.getMrkdownIn()); + + SlackCommandResponseAttachment randomJokeFromCategory = response.getAttachments()[4]; + assertEquals(null, randomJokeFromCategory.getFallback()); + assertEquals( + "Type `/chuck {category_name}` to get a random joke from within a given category.", + randomJokeFromCategory.getText()); + assertEquals("Random joke from category", randomJokeFromCategory.getTitle()); + assertEquals(null, randomJokeFromCategory.getTitleLink()); + assertArrayEquals(new String[] {"text"}, randomJokeFromCategory.getMrkdownIn()); + + SlackCommandResponseAttachment categories = response.getAttachments()[5]; + assertEquals(null, categories.getFallback()); + assertEquals("Type `/chuck -cat` to retrieve a list of all categories.", categories.getText()); + assertEquals("Categories", categories.getTitle()); + assertEquals(null, categories.getTitleLink()); + assertArrayEquals(new String[] {"text"}, categories.getMrkdownIn()); + + SlackCommandResponseAttachment help = response.getAttachments()[6]; + assertEquals(null, help.getFallback()); + assertEquals( + "Type `/chuck : {joke_id}` to retrieve get a joke by a given `id`.", help.getText()); + assertEquals("Get joke by id", help.getTitle()); + assertEquals(null, help.getTitleLink()); + assertArrayEquals(new String[] {"text"}, help.getMrkdownIn()); + + SlackCommandResponseAttachment jokeById = response.getAttachments()[7]; + assertEquals(null, jokeById.getFallback()); + assertEquals("Type `/chuck help` to display a list of available commands.", jokeById.getText()); + assertEquals("Help", jokeById.getTitle()); + assertEquals(null, jokeById.getTitleLink()); + assertArrayEquals(new String[] {"text"}, jokeById.getMrkdownIn()); + + verifyNoMoreInteractions(jokeRepository); + } + + @Test + public void testReturnRandomJokeIfTextIsEmpty() { + when(jokeService.randomJokeByCategories(whiteListedCategories)).thenReturn(joke); + + Request request = new Request(); + request.setText(""); + request.setTeamDomain("ACME"); + + SlackCommandResponse response = slackController.command(request); + assertEquals(iconUrl, response.getIconUrl()); + assertEquals(null, response.getText()); + assertEquals(ResponseType.IN_CHANNEL, response.getResponseType()); + + SlackCommandResponseAttachment commandResponseAttachment = response.getAttachments()[0]; + assertEquals(jokeValue, commandResponseAttachment.getFallback()); + assertEquals(jokeValue, commandResponseAttachment.getText()); + assertEquals("[permalink]", commandResponseAttachment.getTitle()); + assertEquals( + "https://localhost/jokes/bg_h3xursougaxzprcrl0q?utm_source=slack&utm_medium=api&utm_term=ACME&utm_campaign=random+joke", + commandResponseAttachment.getTitleLink()); + + verify(slackService, times(1)).getWhitelistedCategories(); + verifyNoMoreInteractions(slackService); + } + + @Test + public void testReturnRandomJokeIfTextIsNull() { + when(jokeService.randomJokeByCategories(whiteListedCategories)).thenReturn(joke); + + Request request = new Request(); + request.setText(null); + request.setTeamDomain("ACME"); + + SlackCommandResponse response = slackController.command(request); + assertEquals(iconUrl, response.getIconUrl()); + assertEquals(null, response.getText()); + assertEquals(ResponseType.IN_CHANNEL, response.getResponseType()); + + SlackCommandResponseAttachment commandResponseAttachment = response.getAttachments()[0]; + assertEquals(jokeValue, commandResponseAttachment.getFallback()); + assertEquals(jokeValue, commandResponseAttachment.getText()); + assertEquals("[permalink]", commandResponseAttachment.getTitle()); + assertEquals( + "https://localhost/jokes/bg_h3xursougaxzprcrl0q?utm_source=slack&utm_medium=api&utm_term=ACME&utm_campaign=random+joke", + commandResponseAttachment.getTitleLink()); + + verify(slackService, times(1)).getWhitelistedCategories(); + verifyNoMoreInteractions(slackService); + } + + @Test + public void testReturnRandomJokeFromACategoryIfTextContainsCategory() { + String[] categories = new String[] {"dev"}; + + when(jokeRepository.findAllCategories()).thenReturn(categories); + when(jokeService.randomJokeByCategory("dev")).thenReturn(joke); + when(slackService.isWhitelistedCategory("dev")).thenReturn(true); + when(slackService.filterNonWhitelistedCategories(categories)).thenReturn(categories); + + Request request = new Request(); + request.setText("dev"); + request.setTeamDomain("ACME"); + + SlackCommandResponse response = slackController.command(request); + assertEquals(iconUrl, response.getIconUrl()); + assertEquals(null, response.getText()); + assertEquals(ResponseType.IN_CHANNEL, response.getResponseType()); + + SlackCommandResponseAttachment commandResponseAttachment = response.getAttachments()[0]; + assertEquals(jokeValue, commandResponseAttachment.getFallback()); + assertEquals(jokeValue, commandResponseAttachment.getText()); + assertEquals("[permalink]", commandResponseAttachment.getTitle()); + assertEquals( + "https://localhost/jokes/bg_h3xursougaxzprcrl0q?utm_source=slack&utm_medium=api&utm_term=ACME&utm_campaign=random+joke+category", + commandResponseAttachment.getTitleLink()); + + verify(slackService, times(1)).isWhitelistedCategory("dev"); + verify(slackService, times(1)).filterNonWhitelistedCategories(categories); + verifyNoMoreInteractions(slackService); + + verify(jokeRepository, times(1)).findAllCategories(); + verifyNoMoreInteractions(jokeRepository); + + verify(jokeService, times(1)).randomJokeByCategory("dev"); + verifyNoMoreInteractions(jokeService); + } + + @Test + public void testReturnErrorIfCategoryIsNotWhitelisted() { + when(slackService.isWhitelistedCategory("explicit")).thenReturn(false); + + Request request = new Request(); + request.setText("explicit"); + + SlackCommandResponse response = slackController.command(request); + assertArrayEquals(null, response.getAttachments()); + assertEquals(iconUrl, response.getIconUrl()); + assertEquals( + "Sorry dude ¯\\_(ツ)_/¯ , the given category (\"explicit\") is not whitelisted. Type" + + " `/chuck -cat` to see available categories or search by query `/chuck ?" + + " {search_term}`", + response.getText()); + assertEquals(ResponseType.EPHEMERAL, response.getResponseType()); + + verify(slackService, times(1)).isWhitelistedCategory("explicit"); + verifyNoMoreInteractions(slackService); + } + + @Test + public void testReturnErrorIfCategoryDoesNotExist() { + String[] categories = new String[] {"dev"}; + + when(slackService.isWhitelistedCategory("does-not-exist")).thenReturn(true); + when(jokeRepository.findAllCategories()).thenReturn(categories); + when(slackService.filterNonWhitelistedCategories(categories)).thenReturn(categories); + + Request request = new Request(); + request.setText("does-not-exist"); + + SlackCommandResponse response = slackController.command(request); + assertEquals(null, response.getAttachments()); + assertEquals(iconUrl, response.getIconUrl()); + assertEquals( + "Sorry dude ¯\\_(ツ)_/¯ , we've found no jokes for the given category" + + " (\"does-not-exist\"). Type `/chuck -cat` to see available categories or" + + " search by query `/chuck ? {search_term}`", + response.getText()); + assertEquals(ResponseType.EPHEMERAL, response.getResponseType()); + + verify(jokeRepository, times(1)).findAllCategories(); + verifyNoMoreInteractions(jokeRepository); + + verify(slackService, times(1)).isWhitelistedCategory("does-not-exist"); + verify(slackService, times(1)).filterNonWhitelistedCategories(categories); + verifyNoMoreInteractions(slackService); + } + + @Test + public void testReturnListOfCategories() { + when(jokeRepository.findAllCategories()).thenReturn(new String[] {"dev", "fashion", "food"}); + + Request request = new Request(); + request.setText("-cat"); + request.setTeamDomain("ACME"); + + SlackCommandResponse response = slackController.command(request); + assertEquals(null, response.getAttachments()); + assertEquals(iconUrl, response.getIconUrl()); + assertEquals( + "Available categories are: `dev`, `fashion`, `food`. Type `/chuck {category_name}`" + + " to retrieve a random joke from within the given category.", + response.getText()); + assertEquals(ResponseType.EPHEMERAL, response.getResponseType()); + } + + @Test + public void testReturnListOfCategoriesWhitelisted() { + when(jokeRepository.findAllCategories()) + .thenReturn(new String[] {"dev", "explicit", "fashion", "food"}); + + Request request = new Request(); + request.setText("-cat"); + request.setTeamDomain("ACME"); + + SlackCommandResponse response = slackController.command(request); + assertEquals(null, response.getAttachments()); + assertEquals(iconUrl, response.getIconUrl()); + assertEquals( + "Available categories are: `dev`, `fashion`, `food`. Type `/chuck {category_name}`" + + " to retrieve a random joke from within the given category.", + response.getText()); + assertEquals(ResponseType.EPHEMERAL, response.getResponseType()); + } + + @Test + public void testReturnJokeByItsId() { + when(jokeRepository.findById(jokeId)).thenReturn(Optional.of(joke)); + + Request request = new Request(); + request.setText(": " + jokeId); + request.setTeamDomain("ACME"); + + SlackCommandResponse response = slackController.command(request); + assertEquals(iconUrl, response.getIconUrl()); + assertEquals(null, response.getText()); + assertEquals(ResponseType.IN_CHANNEL, response.getResponseType()); + + SlackCommandResponseAttachment commandResponseAttachment = response.getAttachments()[0]; + assertEquals(jokeValue, commandResponseAttachment.getFallback()); + assertEquals(jokeValue, commandResponseAttachment.getText()); + assertEquals("[permalink]", commandResponseAttachment.getTitle()); + assertEquals( + "https://localhost/jokes/bg_h3xursougaxzprcrl0q?utm_source=slack&utm_medium=api&utm_term=ACME&utm_campaign=joke+by+id", + commandResponseAttachment.getTitleLink()); + + verify(jokeRepository, times(1)).findById(jokeId); + verifyNoMoreInteractions(jokeRepository); + } + + @Test + public void testReturnErrorIfJokeDoesNotExist() { + when(jokeRepository.findById("does-not-exist")).thenReturn(Optional.empty()); + + Request request = new Request(); + request.setText(": does-not-exist"); + + SlackCommandResponse response = slackController.command(request); + assertEquals(null, response.getAttachments()); + assertEquals(iconUrl, response.getIconUrl()); + assertEquals( + "Sorry dude ¯\\_(ツ)_/¯ , no joke with id (\"does-not-exist\") found.", response.getText()); + assertEquals(ResponseType.EPHEMERAL, response.getResponseType()); + + verify(jokeRepository, times(1)).findById("does-not-exist"); + verifyNoMoreInteractions(jokeRepository); + } + + @Test + public void testReturnRandomPersonalizedJoke() { + String substitute = "Bob"; + String[] categories = new String[] {"dev", "explicit", "fashion", "food"}; + + joke = joke.toBuilder().value(joke.getValue().replace("Chuck Norris", "Bob")).build(); + + when(jokeRepository.findAllCategories()).thenReturn(categories); + when(jokeService.randomPersonalizedJokeByCategories( + substitute, new String[] {"dev", "fashion", "food"})) + .thenReturn(joke); + + Request request = new Request(); + request.setText("@Bob"); + request.setTeamDomain("ACME"); + + SlackCommandResponse response = slackController.command(request); + assertEquals(iconUrl, response.getIconUrl()); + assertEquals(null, response.getText()); + assertEquals(ResponseType.IN_CHANNEL, response.getResponseType()); + + SlackCommandResponseAttachment commandResponseAttachment = response.getAttachments()[0]; + assertEquals("Bob programs do not accept input.", commandResponseAttachment.getFallback()); + assertEquals("Bob programs do not accept input.", commandResponseAttachment.getText()); + assertEquals("[permalink]", commandResponseAttachment.getTitle()); + assertEquals( + "https://localhost/jokes/bg_h3xursougaxzprcrl0q?utm_source=slack&utm_medium=api&utm_term=ACME&utm_campaign=random+personalized+joke", + commandResponseAttachment.getTitleLink()); + + verify(jokeRepository, times(1)).findAllCategories(); + verifyNoMoreInteractions(jokeRepository); + + verify(slackService, times(1)) + .filterNonWhitelistedCategories(new String[] {"dev", "explicit", "fashion", "food"}); + verifyNoMoreInteractions(slackService); + + verify(jokeService, times(1)) + .randomPersonalizedJokeByCategories("Bob", new String[] {"dev", "fashion", "food"}); + verifyNoMoreInteractions(jokeService); + } + + @Test + public void testReturnSearchResultWithLessThanFiveJokes() { + String query = "Kleenex"; + String[] categories = new String[] {"dev", "movie"}; + + Pageable pageable = PageRequest.of(0, 5, Sort.unsorted()); + + when(jokeRepository.findAllCategories()).thenReturn(categories); + when(slackService.filterNonWhitelistedCategories(categories)).thenReturn(categories); + when(jokeService.searchWithCategoryFilter(query, categories, pageable)) + .thenReturn(new PageImpl<>(Arrays.asList(joke, joke, joke))); + + Request request = new Request(); + request.setText("? " + query); + request.setTeamDomain("ACME"); + + SlackCommandResponse response = slackController.command(request); + assertEquals(iconUrl, response.getIconUrl()); + assertEquals("*Search results: 1 - 3 of 3*.", response.getText()); + assertEquals(ResponseType.IN_CHANNEL, response.getResponseType()); + + for (int i = 0; i < response.getAttachments().length; i++) { + SlackCommandResponseAttachment commandResponseAttachment = response.getAttachments()[i]; + assertEquals(jokeValue, commandResponseAttachment.getFallback()); + assertEquals(jokeValue, commandResponseAttachment.getText()); + assertEquals("(" + (i + 1) + ")", commandResponseAttachment.getTitle()); + assertEquals( + "https://localhost/jokes/bg_h3xursougaxzprcrl0q?utm_source=slack&utm_medium=api&utm_term=ACME&utm_campaign=search+joke", + commandResponseAttachment.getTitleLink()); } - @Test - public void testReturnHelpIfTextEqualsHelp() { - Request request = new Request(); - request.setText("help"); - - SlackCommandResponse response = slackController.command(request); - assertEquals(iconUrl, response.getIconUrl()); - assertEquals("*Available commands:*", response.getText()); - assertEquals(ResponseType.EPHEMERAL, response.getResponseType()); - - SlackCommandResponseAttachment newsletter = response.getAttachments()[0]; - assertEquals(null, newsletter.getFallback()); - assertEquals(":facepunch: Sign up for *The Daily Chuck* and get your daily dose of the best #ChuckNorrisFacts every morning straight int your inbox! https://mailchi.mp/5a19a2898bf7/the-daily-chuck", newsletter.getText()); - assertEquals("The Daily Chuck", newsletter.getTitle()); - assertEquals(null, newsletter.getTitleLink()); - assertArrayEquals(new String[]{"text"}, newsletter.getMrkdownIn()); - - SlackCommandResponseAttachment randomJoke = response.getAttachments()[1]; - assertEquals(null, randomJoke.getFallback()); - assertEquals("Type `/chuck` to get a random joke.", randomJoke.getText()); - assertEquals("Random joke", randomJoke.getTitle()); - assertEquals(null, randomJoke.getTitleLink()); - assertArrayEquals(new String[]{"text"}, randomJoke.getMrkdownIn()); - - SlackCommandResponseAttachment search = response.getAttachments()[2]; - assertEquals(null, search.getFallback()); - assertEquals("Type `/chuck ? {search_term}` to search within tens of thousands Chuck Norris jokes.", search.getText()); - assertEquals("Free text search", search.getTitle()); - assertEquals(null, search.getTitleLink()); - assertArrayEquals(new String[]{"text"}, search.getMrkdownIn()); - - SlackCommandResponseAttachment randomJokePersonalized = response.getAttachments()[3]; - assertEquals(null, randomJokePersonalized.getFallback()); - assertEquals("Type `/chuck @ {user_name}` to get a random personalized joke.", randomJokePersonalized.getText()); - assertEquals("Random personalized joke", randomJokePersonalized.getTitle()); - assertEquals(null, randomJokePersonalized.getTitleLink()); - assertArrayEquals(new String[]{"text"}, randomJokePersonalized.getMrkdownIn()); - - SlackCommandResponseAttachment randomJokeFromCategory = response.getAttachments()[4]; - assertEquals(null, randomJokeFromCategory.getFallback()); - assertEquals("Type `/chuck {category_name}` to get a random joke from within a given category.", randomJokeFromCategory.getText()); - assertEquals("Random joke from category", randomJokeFromCategory.getTitle()); - assertEquals(null, randomJokeFromCategory.getTitleLink()); - assertArrayEquals(new String[]{"text"}, randomJokeFromCategory.getMrkdownIn()); - - SlackCommandResponseAttachment categories = response.getAttachments()[5]; - assertEquals(null, categories.getFallback()); - assertEquals("Type `/chuck -cat` to retrieve a list of all categories.", categories.getText()); - assertEquals("Categories", categories.getTitle()); - assertEquals(null, categories.getTitleLink()); - assertArrayEquals(new String[]{"text"}, categories.getMrkdownIn()); - - SlackCommandResponseAttachment help = response.getAttachments()[6]; - assertEquals(null, help.getFallback()); - assertEquals("Type `/chuck : {joke_id}` to retrieve get a joke by a given `id`.", help.getText()); - assertEquals("Get joke by id", help.getTitle()); - assertEquals(null, help.getTitleLink()); - assertArrayEquals(new String[]{"text"}, help.getMrkdownIn()); - - SlackCommandResponseAttachment jokeById = response.getAttachments()[7]; - assertEquals(null, jokeById.getFallback()); - assertEquals("Type `/chuck help` to display a list of available commands.", jokeById.getText()); - assertEquals("Help", jokeById.getTitle()); - assertEquals(null, jokeById.getTitleLink()); - assertArrayEquals(new String[]{"text"}, jokeById.getMrkdownIn()); - - verifyNoMoreInteractions(jokeRepository); - } - - @Test - public void testReturnRandomJokeIfTextIsEmpty() { - when(jokeService.randomJokeByCategories(whiteListedCategories)).thenReturn(joke); - - Request request = new Request(); - request.setText(""); - request.setTeamDomain("ACME"); - - SlackCommandResponse response = slackController.command(request); - assertEquals(iconUrl, response.getIconUrl()); - assertEquals(null, response.getText()); - assertEquals(ResponseType.IN_CHANNEL, response.getResponseType()); - - SlackCommandResponseAttachment commandResponseAttachment = response.getAttachments()[0]; - assertEquals(jokeValue, commandResponseAttachment.getFallback()); - assertEquals(jokeValue, commandResponseAttachment.getText()); - assertEquals("[permalink]", commandResponseAttachment.getTitle()); - assertEquals("https://localhost/jokes/bg_h3xursougaxzprcrl0q?utm_source=slack&utm_medium=api&utm_term=ACME&utm_campaign=random+joke", commandResponseAttachment - .getTitleLink()); - - verify(slackService, times(1)).getWhitelistedCategories(); - verifyNoMoreInteractions(slackService); + verify(jokeRepository, times(1)).findAllCategories(); + verifyNoMoreInteractions(jokeRepository); + + verify(slackService, times(1)).filterNonWhitelistedCategories(categories); + verifyNoMoreInteractions(slackService); + + verify(jokeService, times(1)).searchWithCategoryFilter(query, categories, pageable); + verifyNoMoreInteractions(jokeService); + } + + @Test + public void testReturnSearchResultWithMoreThanFiveJokes() { + String query = "Kleenex"; + String[] categories = new String[] {"dev", "movie"}; + + Pageable pageable = PageRequest.of(0, 5, Sort.unsorted()); + + when(jokeRepository.findAllCategories()).thenReturn(categories); + when(slackService.filterNonWhitelistedCategories(categories)).thenReturn(categories); + when(jokeService.searchWithCategoryFilter(query, categories, pageable)) + .thenReturn(new PageImpl(Arrays.asList(joke, joke, joke, joke, joke), pageable, 6)); + + Request request = new Request(); + request.setText("? " + query); + request.setTeamDomain("ACME"); + + SlackCommandResponse response = slackController.command(request); + assertEquals(iconUrl, response.getIconUrl()); + assertEquals( + "*Search results: 1 - 5 of 6*. Type `/chuck ? " + query + " --page 2` to see more results.", + response.getText()); + assertEquals(ResponseType.IN_CHANNEL, response.getResponseType()); + + for (int i = 0; i < response.getAttachments().length; i++) { + SlackCommandResponseAttachment commandResponseAttachment = response.getAttachments()[i]; + assertEquals(jokeValue, commandResponseAttachment.getFallback()); + assertEquals(jokeValue, commandResponseAttachment.getText()); + assertEquals("(" + (i + 1) + ")", commandResponseAttachment.getTitle()); + assertEquals( + "https://localhost/jokes/bg_h3xursougaxzprcrl0q?utm_source=slack&utm_medium=api&utm_term=ACME&utm_campaign=search+joke", + commandResponseAttachment.getTitleLink()); } - @Test - public void testReturnRandomJokeIfTextIsNull() { - when(jokeService.randomJokeByCategories(whiteListedCategories)).thenReturn(joke); - - Request request = new Request(); - request.setText(null); - request.setTeamDomain("ACME"); - - SlackCommandResponse response = slackController.command(request); - assertEquals(iconUrl, response.getIconUrl()); - assertEquals(null, response.getText()); - assertEquals(ResponseType.IN_CHANNEL, response.getResponseType()); - - SlackCommandResponseAttachment commandResponseAttachment = response.getAttachments()[0]; - assertEquals(jokeValue, commandResponseAttachment.getFallback()); - assertEquals(jokeValue, commandResponseAttachment.getText()); - assertEquals("[permalink]", commandResponseAttachment.getTitle()); - assertEquals("https://localhost/jokes/bg_h3xursougaxzprcrl0q?utm_source=slack&utm_medium=api&utm_term=ACME&utm_campaign=random+joke", commandResponseAttachment - .getTitleLink()); - - verify(slackService, times(1)).getWhitelistedCategories(); - verifyNoMoreInteractions(slackService); + verify(slackService, times(1)).filterNonWhitelistedCategories(categories); + verifyNoMoreInteractions(slackService); + + verify(jokeService, times(1)).searchWithCategoryFilter(query, categories, pageable); + verifyNoMoreInteractions(jokeService); + } + + @Test + public void testReturnSearchResultWithMoreThanFiveJokesSecondPage() { + String query = "Kleenex"; + String[] categories = new String[] {"dev", "movie"}; + Pageable pageable = PageRequest.of(1, 5, Sort.unsorted()); + + when(jokeRepository.findAllCategories()).thenReturn(categories); + when(slackService.filterNonWhitelistedCategories(categories)).thenReturn(categories); + when(jokeService.searchWithCategoryFilter(query, categories, pageable)) + .thenReturn(new PageImpl(Arrays.asList(joke, joke, joke, joke, joke), pageable, 15)); + + Request request = new Request(); + request.setText("? " + query + " --page 2"); + request.setTeamDomain("ACME"); + + SlackCommandResponse response = slackController.command(request); + assertEquals(iconUrl, response.getIconUrl()); + assertEquals( + "*Search results: 6 - 10 of 15*. Type `/chuck ? " + + query + + " --page 3` to see more results.", + response.getText()); + assertEquals(ResponseType.IN_CHANNEL, response.getResponseType()); + + for (int i = 0; i < response.getAttachments().length; i++) { + SlackCommandResponseAttachment commandResponseAttachment = response.getAttachments()[i]; + assertEquals(jokeValue, commandResponseAttachment.getFallback()); + assertEquals(jokeValue, commandResponseAttachment.getText()); + assertEquals("(" + (i + 1 + 5) + ")", commandResponseAttachment.getTitle()); + assertEquals( + "https://localhost/jokes/bg_h3xursougaxzprcrl0q?utm_source=slack&utm_medium=api&utm_term=ACME&utm_campaign=search+joke", + commandResponseAttachment.getTitleLink()); } - @Test - public void testReturnRandomJokeFromACategoryIfTextContainsCategory() { - String[] categories = new String[]{"dev"}; - - when(jokeRepository.findAllCategories()).thenReturn(categories); - when(jokeService.randomJokeByCategory("dev")).thenReturn(joke); - when(slackService.isWhitelistedCategory("dev")).thenReturn(true); - when(slackService.filterNonWhitelistedCategories(categories)).thenReturn(categories); + verify(jokeRepository, times(1)).findAllCategories(); + verifyNoMoreInteractions(jokeRepository); - Request request = new Request(); - request.setText("dev"); - request.setTeamDomain("ACME"); + verify(slackService, times(1)).filterNonWhitelistedCategories(categories); + verifyNoMoreInteractions(slackService); - SlackCommandResponse response = slackController.command(request); - assertEquals(iconUrl, response.getIconUrl()); - assertEquals(null, response.getText()); - assertEquals(ResponseType.IN_CHANNEL, response.getResponseType()); + verify(jokeService, times(1)).searchWithCategoryFilter(query, categories, pageable); + verifyNoMoreInteractions(jokeService); + } - SlackCommandResponseAttachment commandResponseAttachment = response.getAttachments()[0]; - assertEquals(jokeValue, commandResponseAttachment.getFallback()); - assertEquals(jokeValue, commandResponseAttachment.getText()); - assertEquals("[permalink]", commandResponseAttachment.getTitle()); - assertEquals("https://localhost/jokes/bg_h3xursougaxzprcrl0q?utm_source=slack&utm_medium=api&utm_term=ACME&utm_campaign=random+joke+category", commandResponseAttachment - .getTitleLink()); + @Test + public void testReturnErrorIfSearchResultIsEmpty() { + String query = "poop"; + String[] categories = new String[] {"dev", "movie"}; - verify(slackService, times(1)).isWhitelistedCategory("dev"); - verify(slackService, times(1)).filterNonWhitelistedCategories(categories); - verifyNoMoreInteractions(slackService); + Pageable pageable = PageRequest.of(0, 5, Sort.unsorted()); - verify(jokeRepository, times(1)).findAllCategories(); - verifyNoMoreInteractions(jokeRepository); + when(jokeRepository.findAllCategories()).thenReturn(categories); + when(slackService.filterNonWhitelistedCategories(categories)).thenReturn(categories); + when(jokeService.searchWithCategoryFilter(query, categories, pageable)) + .thenReturn(new PageImpl<>(new ArrayList<>())); - verify(jokeService, times(1)).randomJokeByCategory("dev"); - verifyNoMoreInteractions(jokeService); - } + Request request = new Request(); + request.setText("? " + query); - @Test - public void testReturnErrorIfCategoryIsNotWhitelisted() { - when(slackService.isWhitelistedCategory("explicit")).thenReturn(false); + SlackCommandResponse response = slackController.command(request); + assertArrayEquals(null, response.getAttachments()); + assertEquals(iconUrl, response.getIconUrl()); - Request request = new Request(); - request.setText("explicit"); + assertEquals( + "Your search for *\"" + + query + + "\"* did not match any joke ¯\\_(ツ)_/¯. Make sure that all words are" + + " spelled correctly. Try different keywords. Try more general keywords.", + response.getText()); + assertEquals(ResponseType.EPHEMERAL, response.getResponseType()); - SlackCommandResponse response = slackController.command(request); - assertArrayEquals(null, response.getAttachments()); - assertEquals(iconUrl, response.getIconUrl()); - assertEquals("Sorry dude ¯\\_(ツ)_/¯ , the given category (\"explicit\") is not whitelisted. Type `/chuck -cat` to see available categories or search by query `/chuck ? {search_term}`", response.getText()); - assertEquals(ResponseType.EPHEMERAL, response.getResponseType()); + verify(jokeRepository, times(1)).findAllCategories(); + verifyNoMoreInteractions(jokeRepository); - verify(slackService, times(1)).isWhitelistedCategory("explicit"); - verifyNoMoreInteractions(slackService); - } + verify(slackService, times(1)).filterNonWhitelistedCategories(categories); + verifyNoMoreInteractions(slackService); - @Test - public void testReturnErrorIfCategoryDoesNotExist() { - String[] categories = new String[]{"dev"}; - - when(slackService.isWhitelistedCategory("does-not-exist")).thenReturn(true); - when(jokeRepository.findAllCategories()).thenReturn(categories); - when(slackService.filterNonWhitelistedCategories(categories)).thenReturn(categories); - - Request request = new Request(); - request.setText("does-not-exist"); - - SlackCommandResponse response = slackController.command(request); - assertEquals(null, response.getAttachments()); - assertEquals(iconUrl, response.getIconUrl()); - assertEquals("Sorry dude ¯\\_(ツ)_/¯ , we've found no jokes for the given category (\"does-not-exist\"). Type `/chuck -cat` to see available categories or search by query `/chuck ? {search_term}`", response.getText()); - assertEquals(ResponseType.EPHEMERAL, response.getResponseType()); - - verify(jokeRepository, times(1)).findAllCategories(); - verifyNoMoreInteractions(jokeRepository); - - verify(slackService, times(1)).isWhitelistedCategory("does-not-exist"); - verify(slackService, times(1)).filterNonWhitelistedCategories(categories); - verifyNoMoreInteractions(slackService); - } - - @Test - public void testReturnListOfCategories() { - when(jokeRepository.findAllCategories()).thenReturn(new String[]{"dev", "fashion", "food"}); - - Request request = new Request(); - request.setText("-cat"); - request.setTeamDomain("ACME"); - - SlackCommandResponse response = slackController.command(request); - assertEquals(null, response.getAttachments()); - assertEquals(iconUrl, response.getIconUrl()); - assertEquals("Available categories are: `dev`, `fashion`, `food`. Type `/chuck {category_name}` to retrieve a random joke from within the given category.", response.getText()); - assertEquals(ResponseType.EPHEMERAL, response.getResponseType()); - } - - @Test - public void testReturnListOfCategoriesWhitelisted() { - when(jokeRepository.findAllCategories()).thenReturn(new String[]{"dev", "explicit", "fashion", "food"}); - - Request request = new Request(); - request.setText("-cat"); - request.setTeamDomain("ACME"); - - SlackCommandResponse response = slackController.command(request); - assertEquals(null, response.getAttachments()); - assertEquals(iconUrl, response.getIconUrl()); - assertEquals("Available categories are: `dev`, `fashion`, `food`. Type `/chuck {category_name}` to retrieve a random joke from within the given category.", response.getText()); - assertEquals(ResponseType.EPHEMERAL, response.getResponseType()); - } - - @Test - public void testReturnJokeByItsId() { - when(jokeRepository.findById(jokeId)).thenReturn(Optional.of(joke)); - - Request request = new Request(); - request.setText(": " + jokeId); - request.setTeamDomain("ACME"); - - SlackCommandResponse response = slackController.command(request); - assertEquals(iconUrl, response.getIconUrl()); - assertEquals(null, response.getText()); - assertEquals(ResponseType.IN_CHANNEL, response.getResponseType()); - - SlackCommandResponseAttachment commandResponseAttachment = response.getAttachments()[0]; - assertEquals(jokeValue, commandResponseAttachment.getFallback()); - assertEquals(jokeValue, commandResponseAttachment.getText()); - assertEquals("[permalink]", commandResponseAttachment.getTitle()); - assertEquals("https://localhost/jokes/bg_h3xursougaxzprcrl0q?utm_source=slack&utm_medium=api&utm_term=ACME&utm_campaign=joke+by+id", commandResponseAttachment - .getTitleLink()); - - verify(jokeRepository, times(1)).findById(jokeId); - verifyNoMoreInteractions(jokeRepository); - } - - @Test - public void testReturnErrorIfJokeDoesNotExist() { - when(jokeRepository.findById("does-not-exist")).thenReturn(Optional.empty()); - - Request request = new Request(); - request.setText(": does-not-exist"); - - SlackCommandResponse response = slackController.command(request); - assertEquals(null, response.getAttachments()); - assertEquals(iconUrl, response.getIconUrl()); - assertEquals("Sorry dude ¯\\_(ツ)_/¯ , no joke with id (\"does-not-exist\") found.", response.getText()); - assertEquals(ResponseType.EPHEMERAL, response.getResponseType()); - - verify(jokeRepository, times(1)).findById("does-not-exist"); - verifyNoMoreInteractions(jokeRepository); - } - - @Test - public void testReturnRandomPersonalizedJoke() { - String substitute = "Bob"; - String[] categories = new String[]{"dev", "explicit", "fashion", "food"}; - - joke = joke.toBuilder().value( - joke.getValue().replace("Chuck Norris", "Bob") - ).build(); - - when(jokeRepository.findAllCategories()).thenReturn(categories); - when(jokeService.randomPersonalizedJokeByCategories( - substitute, - new String[]{"dev", "fashion", "food"} - )).thenReturn(joke); - - Request request = new Request(); - request.setText("@Bob"); - request.setTeamDomain("ACME"); - - SlackCommandResponse response = slackController.command(request); - assertEquals(iconUrl, response.getIconUrl()); - assertEquals(null, response.getText()); - assertEquals(ResponseType.IN_CHANNEL, response.getResponseType()); - - SlackCommandResponseAttachment commandResponseAttachment = response.getAttachments()[0]; - assertEquals("Bob programs do not accept input.", commandResponseAttachment.getFallback()); - assertEquals("Bob programs do not accept input.", commandResponseAttachment.getText()); - assertEquals("[permalink]", commandResponseAttachment.getTitle()); - assertEquals("https://localhost/jokes/bg_h3xursougaxzprcrl0q?utm_source=slack&utm_medium=api&utm_term=ACME&utm_campaign=random+personalized+joke", commandResponseAttachment - .getTitleLink()); - - verify(jokeRepository, times(1)).findAllCategories(); - verifyNoMoreInteractions(jokeRepository); - - verify(slackService, times(1)).filterNonWhitelistedCategories( - new String[]{"dev", "explicit", "fashion", "food"} - ); - verifyNoMoreInteractions(slackService); - - verify(jokeService, times(1)).randomPersonalizedJokeByCategories( - "Bob", - new String[]{"dev", "fashion", "food"} - ); - verifyNoMoreInteractions(jokeService); - } - - @Test - public void testReturnSearchResultWithLessThanFiveJokes() { - String query = "Kleenex"; - String[] categories = new String[]{"dev", "movie"}; - - Pageable pageable = PageRequest.of( - 0, - 5, - Sort.unsorted() - ); - - when(jokeRepository.findAllCategories()).thenReturn(categories); - when(slackService.filterNonWhitelistedCategories(categories)).thenReturn(categories); - when(jokeService.searchWithCategoryFilter(query, categories, pageable)).thenReturn( - new PageImpl<>(Arrays.asList(joke, joke, joke)) - ); - - Request request = new Request(); - request.setText("? " + query); - request.setTeamDomain("ACME"); - - SlackCommandResponse response = slackController.command(request); - assertEquals(iconUrl, response.getIconUrl()); - assertEquals("*Search results: 1 - 3 of 3*.", response.getText()); - assertEquals(ResponseType.IN_CHANNEL, response.getResponseType()); - - for (int i = 0; i < response.getAttachments().length; i++) { - SlackCommandResponseAttachment commandResponseAttachment = response.getAttachments()[i]; - assertEquals(jokeValue, commandResponseAttachment.getFallback()); - assertEquals(jokeValue, commandResponseAttachment.getText()); - assertEquals("(" + (i + 1) + ")", commandResponseAttachment.getTitle()); - assertEquals("https://localhost/jokes/bg_h3xursougaxzprcrl0q?utm_source=slack&utm_medium=api&utm_term=ACME&utm_campaign=search+joke", commandResponseAttachment - .getTitleLink()); - } - - verify(jokeRepository, times(1)).findAllCategories(); - verifyNoMoreInteractions(jokeRepository); - - verify(slackService, times(1)).filterNonWhitelistedCategories(categories); - verifyNoMoreInteractions(slackService); - - verify(jokeService, times(1)).searchWithCategoryFilter( - query, - categories, - pageable - ); - verifyNoMoreInteractions(jokeService); - } - - @Test - public void testReturnSearchResultWithMoreThanFiveJokes() { - String query = "Kleenex"; - String[] categories = new String[]{"dev", "movie"}; - - Pageable pageable = PageRequest.of( - 0, - 5, - Sort.unsorted() - ); - - when(jokeRepository.findAllCategories()).thenReturn(categories); - when(slackService.filterNonWhitelistedCategories(categories)).thenReturn(categories); - when(jokeService.searchWithCategoryFilter(query, categories, pageable)).thenReturn( - new PageImpl( - Arrays.asList(joke, joke, joke, joke, joke), - pageable, - 6 - ) - ); - - Request request = new Request(); - request.setText("? " + query); - request.setTeamDomain("ACME"); - - SlackCommandResponse response = slackController.command(request); - assertEquals(iconUrl, response.getIconUrl()); - assertEquals("*Search results: 1 - 5 of 6*. Type `/chuck ? " + query + " --page 2` to see more results.", response.getText()); - assertEquals(ResponseType.IN_CHANNEL, response.getResponseType()); - - for (int i = 0; i < response.getAttachments().length; i++) { - SlackCommandResponseAttachment commandResponseAttachment = response.getAttachments()[i]; - assertEquals(jokeValue, commandResponseAttachment.getFallback()); - assertEquals(jokeValue, commandResponseAttachment.getText()); - assertEquals("(" + (i + 1) + ")", commandResponseAttachment.getTitle()); - assertEquals("https://localhost/jokes/bg_h3xursougaxzprcrl0q?utm_source=slack&utm_medium=api&utm_term=ACME&utm_campaign=search+joke", commandResponseAttachment - .getTitleLink()); - } - - verify(slackService, times(1)).filterNonWhitelistedCategories(categories); - verifyNoMoreInteractions(slackService); - - verify(jokeService, times(1)).searchWithCategoryFilter(query, categories, pageable); - verifyNoMoreInteractions(jokeService); - } - - @Test - public void testReturnSearchResultWithMoreThanFiveJokesSecondPage() { - String query = "Kleenex"; - String[] categories = new String[]{"dev", "movie"}; - Pageable pageable = PageRequest.of(1, 5, Sort.unsorted()); - - when(jokeRepository.findAllCategories()).thenReturn(categories); - when(slackService.filterNonWhitelistedCategories(categories)).thenReturn(categories); - when(jokeService.searchWithCategoryFilter(query, categories, pageable)).thenReturn( - new PageImpl( - Arrays.asList(joke, joke, joke, joke, joke), - pageable, - 15 - ) - ); - - Request request = new Request(); - request.setText("? " + query + " --page 2"); - request.setTeamDomain("ACME"); - - SlackCommandResponse response = slackController.command(request); - assertEquals(iconUrl, response.getIconUrl()); - assertEquals("*Search results: 6 - 10 of 15*. Type `/chuck ? " + query + " --page 3` to see more results.", response.getText()); - assertEquals(ResponseType.IN_CHANNEL, response.getResponseType()); - - for (int i = 0; i < response.getAttachments().length; i++) { - SlackCommandResponseAttachment commandResponseAttachment = response.getAttachments()[i]; - assertEquals(jokeValue, commandResponseAttachment.getFallback()); - assertEquals(jokeValue, commandResponseAttachment.getText()); - assertEquals("(" + (i + 1 + 5) + ")", commandResponseAttachment.getTitle()); - assertEquals("https://localhost/jokes/bg_h3xursougaxzprcrl0q?utm_source=slack&utm_medium=api&utm_term=ACME&utm_campaign=search+joke", commandResponseAttachment - .getTitleLink()); - } - - verify(jokeRepository, times(1)).findAllCategories(); - verifyNoMoreInteractions(jokeRepository); - - verify(slackService, times(1)).filterNonWhitelistedCategories(categories); - verifyNoMoreInteractions(slackService); - - verify(jokeService, times(1)).searchWithCategoryFilter(query, categories, pageable); - verifyNoMoreInteractions(jokeService); - } - - @Test - public void testReturnErrorIfSearchResultIsEmpty() { - String query = "poop"; - String[] categories = new String[]{"dev", "movie"}; - - Pageable pageable = PageRequest.of( - 0, - 5, - Sort.unsorted() - ); - - when(jokeRepository.findAllCategories()).thenReturn(categories); - when(slackService.filterNonWhitelistedCategories(categories)).thenReturn(categories); - when(jokeService.searchWithCategoryFilter(query, categories, pageable)).thenReturn( - new PageImpl<>(new ArrayList<>()) - ); - - Request request = new Request(); - request.setText("? " + query); - - SlackCommandResponse response = slackController.command(request); - assertArrayEquals(null, response.getAttachments()); - assertEquals(iconUrl, response.getIconUrl()); - - assertEquals("Your search for *\"" + query + "\"* did not match any joke ¯\\_(ツ)_/¯. Make sure that all words are spelled correctly. Try different keywords. Try more general keywords.", response.getText()); - assertEquals(ResponseType.EPHEMERAL, response.getResponseType()); - - verify(jokeRepository, times(1)).findAllCategories(); - verifyNoMoreInteractions(jokeRepository); - - verify(slackService, times(1)).filterNonWhitelistedCategories(categories); - verifyNoMoreInteractions(slackService); - - verify(jokeService, times(1)).searchWithCategoryFilter( - query, - categories, - pageable - ); - verifyNoMoreInteractions(jokeService); - } -} \ No newline at end of file + verify(jokeService, times(1)).searchWithCategoryFilter(query, categories, pageable); + verifyNoMoreInteractions(jokeService); + } +} diff --git a/src/test/java/io/chucknorris/api/slack/SlackServiceTest.java b/src/test/java/io/chucknorris/api/slack/SlackServiceTest.java index eb4a527..15b6d1c 100644 --- a/src/test/java/io/chucknorris/api/slack/SlackServiceTest.java +++ b/src/test/java/io/chucknorris/api/slack/SlackServiceTest.java @@ -30,116 +30,93 @@ @RunWith(MockitoJUnitRunner.class) public class SlackServiceTest { - @InjectMocks - private SlackService slackService = new SlackService(); - - @Mock - private RestTemplate restTemplate; - - @Before - public void setUp() { - ReflectionTestUtils.setField(slackService, "whitelistedCategories", "career,celebrity,dev,fashion,food,money,movie,travel"); - ReflectionTestUtils.setField(slackService, "clientId", "slack.oauth.client_id"); - ReflectionTestUtils.setField(slackService, "clientSecret", "slack.oauth.client_secret"); - ReflectionTestUtils.setField(slackService, "redirectUrl", "slack.oauth.redirect_uri"); - } - - @Test - public void testComposeAuthorizeUri() { - UriComponents authorizeUri = slackService.composeAuthorizeUri(); - - assertEquals( - "https://slack.com/oauth/v2/authorize/?client_id=slack.oauth.client_id&redirect_uri=slack.oauth.redirect_uri&scope=commands", - authorizeUri.toUriString() - ); - } - - @Test - public void testFilterNonWhitelistedCategories() { - assertArrayEquals( - slackService.filterNonWhitelistedCategories( - new String[]{ - "career", - "celebrity", - "dev", - "explicit", - "fashion", - "food", - "money", - "movie", - "travel" - } - ), - new String[]{ - "career", - "celebrity", - "dev", - "fashion", - "food", - "money", - "movie", - "travel" - } - ); - } - - @Test - public void testGetWhitelistedCategoriesReturnsArrayOfCategories() { - assertArrayEquals( - slackService.getWhitelistedCategories(), - new String[]{ - "career", - "celebrity", - "dev", - "fashion", - "food", - "money", - "movie", - "travel" - } - ); - } - - @Test - public void testIfGivenCategoryIsWhitelisted() { - assertFalse(slackService.isWhitelistedCategory("explicit")); - assertFalse(slackService.isWhitelistedCategory("religion")); - assertTrue(slackService.isWhitelistedCategory("dev")); - } - - @Test - public void testRequestAccessTokenSendsRequestAndRetunsToken() { - String code = "my-super-secret-code"; - AccessToken accessToken = new AccessToken(); - - HttpHeaders headers = new HttpHeaders(); - headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE); - headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE); - - MultiValueMap map = new LinkedMultiValueMap<>(); - map.add("client_id", "slack.oauth.client_id"); - map.add("client_secret", "slack.oauth.client_secret"); - map.add("code", code); - map.add("redirect_uri", "slack.oauth.redirect_uri"); - - when(restTemplate.exchange( + @InjectMocks private SlackService slackService = new SlackService(); + + @Mock private RestTemplate restTemplate; + + @Before + public void setUp() { + ReflectionTestUtils.setField( + slackService, + "whitelistedCategories", + "career,celebrity,dev,fashion,food,money,movie,travel"); + ReflectionTestUtils.setField(slackService, "clientId", "slack.oauth.client_id"); + ReflectionTestUtils.setField(slackService, "clientSecret", "slack.oauth.client_secret"); + ReflectionTestUtils.setField(slackService, "redirectUrl", "slack.oauth.redirect_uri"); + } + + @Test + public void testComposeAuthorizeUri() { + UriComponents authorizeUri = slackService.composeAuthorizeUri(); + + assertEquals( + "https://slack.com/oauth/v2/authorize/?client_id=slack.oauth.client_id&redirect_uri=slack.oauth.redirect_uri&scope=commands", + authorizeUri.toUriString()); + } + + @Test + public void testFilterNonWhitelistedCategories() { + assertArrayEquals( + slackService.filterNonWhitelistedCategories( + new String[] { + "career", + "celebrity", + "dev", + "explicit", + "fashion", + "food", + "money", + "movie", + "travel" + }), + new String[] {"career", "celebrity", "dev", "fashion", "food", "money", "movie", "travel"}); + } + + @Test + public void testGetWhitelistedCategoriesReturnsArrayOfCategories() { + assertArrayEquals( + slackService.getWhitelistedCategories(), + new String[] {"career", "celebrity", "dev", "fashion", "food", "money", "movie", "travel"}); + } + + @Test + public void testIfGivenCategoryIsWhitelisted() { + assertFalse(slackService.isWhitelistedCategory("explicit")); + assertFalse(slackService.isWhitelistedCategory("religion")); + assertTrue(slackService.isWhitelistedCategory("dev")); + } + + @Test + public void testRequestAccessTokenSendsRequestAndRetunsToken() { + String code = "my-super-secret-code"; + AccessToken accessToken = new AccessToken(); + + HttpHeaders headers = new HttpHeaders(); + headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE); + headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE); + + MultiValueMap map = new LinkedMultiValueMap<>(); + map.add("client_id", "slack.oauth.client_id"); + map.add("client_secret", "slack.oauth.client_secret"); + map.add("code", code); + map.add("redirect_uri", "slack.oauth.redirect_uri"); + + when(restTemplate.exchange( "https://slack.com/api/oauth.v2.access", HttpMethod.POST, new HttpEntity>(map, headers), - AccessToken.class - )).thenReturn( - new ResponseEntity(accessToken, HttpStatus.OK) - ); + AccessToken.class)) + .thenReturn(new ResponseEntity(accessToken, HttpStatus.OK)); - AccessToken response = slackService.requestAccessToken(code); - assertEquals(accessToken, response); + AccessToken response = slackService.requestAccessToken(code); + assertEquals(accessToken, response); - verify(restTemplate, times(1)).exchange( + verify(restTemplate, times(1)) + .exchange( "https://slack.com/api/oauth.v2.access", HttpMethod.POST, new HttpEntity>(map, headers), - AccessToken.class - ); - verifyNoMoreInteractions(restTemplate); - } -} \ No newline at end of file + AccessToken.class); + verifyNoMoreInteractions(restTemplate); + } +} diff --git a/src/test/java/io/chucknorris/lib/event/EventServiceTest.java b/src/test/java/io/chucknorris/lib/event/EventServiceTest.java index 4c379ef..291d0d7 100644 --- a/src/test/java/io/chucknorris/lib/event/EventServiceTest.java +++ b/src/test/java/io/chucknorris/lib/event/EventServiceTest.java @@ -8,10 +8,8 @@ @RunWith(MockitoJUnitRunner.class) public class EventServiceTest { - @InjectMocks - private EventService eventService; + @InjectMocks private EventService eventService; - @Test - public void testPublish() { - } -} \ No newline at end of file + @Test + public void testPublish() {} +}