Weird behavior. I've got a vanilla spring boot project I made with initializr. The build.gradle is below and as you can see it loaded up the test dependency for spring boot starter test, which includes the assertj package.
plugins {
id 'org.springframework.boot' version '2.5.4'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.acme'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-webflux'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'io.projectreactor:reactor-test'
}
test {
useJUnitPlatform()
}
However, I have my first test component here
package com.foretold.astrocalc.app.controllers;
import org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
#SpringBootTest
public class ChartControllerTest {
#Autowired
private ChartController controller;
#Test
public void contextLoads() throws Exception{
assertThat(controller).isNotNull();
}
}
And IJ is telling me that it cannot resolve the symbol assertThat. It loads up to Assertions in the import statement and that's in. When I click into the Assertions class I see the public method assertThat. Is there some IJ setting that's screwing up the static import?
It does work to just import Assertions and use the method with dot notation, but why won't the static import work?
When we want to write assertions in AssertJ, we have to use static assertThat method instead.
This means that you have to import it like following instead:
import static org.assertj.core.api.Assertions.assertThat;
Related
I have tried to implement the 'cucumber.api.cli.Main' but I get the following error: "No backends were found. Please make sure you have a backend module on your CLASSPATH." Does this mean I am missing a dependency? My Gradle and java code is below.
java code
package cucumber;
import cucumber.api.cli.Main;
import java.io.PrintStream;
public class CucumberRunEngine {
public static void main(String[] args) {
try {
Main.main(
new String[]{
"CLASSPATH:src.main.groovy.cucumber.features.addDeal",
//"-t", "#Daily",
"-g", "cucumber.stepDefinitions",
"-p", "pretty",
"-p", "html:target/HTMLReports/report.html",
"-p", "junit:target/JUNITReports/report.xml",
"-p", "json:target/JSONReports/report.json",
"-m"
}
);
} catch (Exception e) {
PrintStream printer =System.out;
printer.println(e);
for (int element=0;element<e.getStackTrace().length;element++) {
printer.println(e.getStackTrace()[element]);
}
}
}
}
Gradle code
plugins {
id 'groovy'
id 'java-library'
id 'application'
id "se.thinkcode.cucumber-runner" version "0.0.8"
}
dependencies {
//Standard
api "org.codehaus.groovy:groovy-all:${groovyVersion}"
api "com.reuters:corejavalib:${coreJavaLibVersion}"
api "com.oracle:ojdbc7:${ojdbc7Version}"
implementation "commons-io:commons-io:${commonsIoVersion}"
implementation "commons-lang:commons-lang:${commonLangVersion}"
//JUnit
implementation "junit:junit:${jUnitVersion}"
// implementation("org.junit.platform:junit-platform-suite")
compileOnly "org.testng:testng:${testNGVersion}"
//Cucumber
compileOnly "io.cucumber:cucumber-java:${cucumberVersion}"
compileOnly "io.cucumber:cucumber-java8:${cucumberVersion}"
compileOnly "io.cucumber:cucumber-junit:${cucumberVersion}"
compileOnly "io.cucumber:cucumber-groovy:${cucumberGroovyVersion}"
compileOnly "io.cucumber:cucumber-gherkin:${cucumberVersion}"
compileOnly "io.cucumber:cucumber-jvm-groovy:${cucumberGroovyVersion}"
compileOnly "io.cucumber:cucumber-junit-platform-engine:${cucumberVersion}"
implementation "io.cucumber:cucumber-core:${cucumberVersion}"
}
application{
mainClass="cucumber.CucumberRunEngine"
}
repositories {
}
Gradle.properties
# versions of dependencies used in this project defined here
groovyVersion=2.5.7
commonCliVersion=1.3.1
commonsIoVersion=2.6
commonLangVersion=2.6
#JUnit
jUnitVersion=4.8
testNGVersion=7.4.0
jUnitPlatformSuiteVersion=1.9.0
#Cucumber
cucumberVersion=7.4.0
cucumberGroovyVersion=6.10.4
ojdbc7Version=12.1.0.2
coreJavaLibVersion=3.5.21.9
Thank you for any help in advance :)
Your project setup is a bit peculiar. There are too many parts that simply don't belong. For example as a result of using compileOnly you're not including the code you need at runtime. And so Cucumber complains it can't find cucumber-java (a backend).
Now you may have already noticed this and scoped cucumber-core to implementation for this reason. But this suggests you're fixing one error at a time rather then building a fundamental understanding of the tools you use.
So it's worth reading how Gradle does dependency management for you:
https://docs.gradle.org/5.3.1/userguide/java_plugin.html#sec:java_plugin_and_dependency_management
A minimal example can be found in the skeleton project. It is not tailored to your needs, but it should be a good starting point.
https://github.com/cucumber/cucumber-java-skeleton
plugins {
java
}
dependencies {
testImplementation(platform("org.junit:junit-bom:5.9.0"))
testImplementation(platform("io.cucumber:cucumber-bom:7.6.0"))
testImplementation("io.cucumber:cucumber-java")
testImplementation("io.cucumber:cucumber-junit-platform-engine")
testImplementation("org.junit.platform:junit-platform-suite")
testImplementation("org.junit.jupiter:junit-jupiter")
}
repositories {
mavenLocal()
mavenCentral()
}
tasks.withType<Test> {
useJUnitPlatform()
// Work around. Gradle does not include enough information to disambiguate
// between different examples and scenarios.
systemProperty("cucumber.junit-platform.naming-strategy", "long")
}
I built an Android application with a service account on it to upload files on Google Drive, which works perfectly on the emulator and Android Nougat. Now, I tried it on a Samsung Galaxy Tab A with Android 8.1 and before implementing the service account everything worked fine. Now, when I try to save a file on google Drive from it, I get the error:
java.lang.NoSuchMethodError: No static method decodeBase64(Ljava/lang/String;)[B in class Lorg/apache/commons/codec/binary/Base64; or its super classes (declaration of 'org.apache.commons.codec.binary.Base64' appears in /system/framework/org.apache.http.legacy.boot.jar)
The problematic code is where I log in, in particular in the fromStream method:
private Credential authorize () throws IOException {
InputStream in = getAssets().open("credentials.json");
return GoogleCredential.fromStream(in)
.createScoped(Collections.singleton(DriveScopes.DRIVE_FILE));
}
These are the new libraries implemented, I add commons-codec:commons-codec:1.15 since I read that it can be caused by it but it still doesn't work:
//API Google Drive
implementation 'com.google.android.gms:play-services-auth:19.0.0'
implementation('com.google.api-client:google-api-client-android:1.26.0') {
exclude group: 'org.apache.httpcomponents'
exclude module: 'guava-jdk5'
}
// https://mvnrepository.com/artifact/com.google.apis/google-api-services-drive
implementation('com.google.apis:google-api-services-drive:v3-rev136-1.25.0') {
exclude group: 'org.apache.httpcomponents'
exclude module: 'guava-jdk5'
}
implementation 'com.google.http-client:google-http-client-gson:1.26.0'
implementation 'commons-codec:commons-codec:1.15'
How can I solve it?
Edit: these are the only apaches' libraries that I used in the whole project, but they have been used to write the .xlsx file in local and never gave me any kind of problem on the Galaxt Tab A before implementing the service credentials:
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
This is a known issue with the version of google-api-client-android you're using. The solution is to upgrade the version from 1.26 to 1.28 (or downgrade it to 1.25, see this comment).
I was able to reproduce the issue using an Empty Activity project and a virtual device with an API Level 26 and a Target Android 8.0 (Google APIs)
Build.gradle content :
plugins {
id 'com.android.application'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.0"
defaultConfig {
applicationId "com.example.myapplication"
minSdkVersion 23
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
useProguard false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation 'com.google.android.gms:play-services-auth:19.0.0'
//changing the version here from 1.26.0 to 1.28.0 resolves the issue
implementation('com.google.api-client:google-api-client-android:1.26.0') {
exclude group: 'org.apache.httpcomponents'
exclude module: 'guava-jdk5'
}
implementation('com.google.apis:google-api-services-drive:v3-rev136-1.25.0') {
exclude group: 'org.apache.httpcomponents'
exclude module: 'guava-jdk5'
}
implementation 'commons-codec:commons-codec:1.15'
}
MainActivity.java content:
package com.example.myapplication;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.services.drive.DriveScopes;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
authorize();
} catch (Exception e) {
e.printStackTrace();
}
}
private Credential authorize () throws IOException {
InputStream in = getAssets().open("credentials.json");
return GoogleCredential.fromStream(in)
.createScoped(Collections.singleton(DriveScopes.DRIVE_FILE));
}
}
I have a common library that is published as a jar to maven local, which is then used by a set of very thin client applications. These applications basically feed their own configuration to the common library and initializes themselves as Spring applications.
This common library uses spring boot and a bunch of other dependencies. My question is, is it possible for me to not define spring boot as a dependency in the applications, and simply use the common library's spring version as a transitive dependency in all the applications?
I feel like this should be possible, but when I tried doing it, the springframework.org.boot classes are not being resolved (eg: #SpringBootApplication annotation).
These are my build.gradle files:
build.gradle from the common library
plugins {
id 'java-library'
id 'maven-publish'
}
group 'com.my.group'
version '1.0-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenLocal()
}
publishing {
publications {
mavenJava(MavenPublication) {
groupId = 'com.my.group'
artifactId = 'common-lib'
version = '0-alpha.1'
from components.java
}
}
}
configurations {
springBom
compileOnly.extendsFrom(springBom)
annotationProcessor.extendsFrom(springBom)
implementation.extendsFrom(springBom)
}
dependencies {
springBom enforcedPlatform('org.springframework.boot:spring-boot-dependencies:2.3.5.RELEASE')
api 'org.springframework.boot:spring-boot-starter'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
implementation 'org.springframework.cloud:spring-cloud-aws-messaging'
annotationProcessor 'org.springframework.boot:spring-boot-autoconfigure-processor'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
// a few other non-spring dependencies
}
build.gradle from a sample application
plugins {
id 'java'
}
group = 'com.my.group'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenLocal()
}
dependencies {
implementation group: 'com.my.group', name: 'common-lib', version: '0-alpha.1'
}
Example application initialization
package com.my.group.Core;
// none of the below are resolved
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
#SpringBootApplication(scanBasePackages = {"com.my.group"})
public class ConsumerApplication implements ApplicationRunner {
#Autowired
Core core;
public ConsumerApplication() {
}
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
#Override
public void run(ApplicationArguments args) {
try {
core.processEvents();
} catch (ConfigurationException | InitializationException e) {
e.printStackTrace();
}
}
}
If I add in the following dependencies to my applications, everything works as expected.
springBom enforcedPlatform('org.springframework.boot:spring-boot-dependencies:2.3.5.RELEASE')
implementation 'org.springframework.boot:spring-boot-starter'
I found the issue. I have not included api in the configurations and as a result, the application could not resolve the version. Fixed by updating the build.gradle in my common library like so:
configurations {
springBom
compileOnly.extendsFrom(springBom)
annotationProcessor.extendsFrom(springBom)
implementation.extendsFrom(springBom)
api.extendsFrom(springBom)
}
The error message I receive:
java.lang.IllegalStateException: Could not initialize plugin:
interface org.mockito.plugins.MockMaker
The code in question:
List<String> mockList = mock(List.class);
The build.gradle dependency:
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
def mockito_version = 'latest.release'
// For local unit tests on your development machine
testCompile "org.mockito:mockito-core:$mockito_version"
}
I have tried looking at other people with the same issue and I keep getting references to PowerMock. I have no idea what that means, so if this is a duplicate I apologize. It just seems like no other question had a solution that resolved my issue. The library is imported properly, as I do not have any compilation errors. Any help would be greatly appreciated.
i tried to create a new project and test this out. below is how my depdencies in gradle file looks:
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
testCompile "org.mockito:mockito-core:2.+"
}
below is my test class:
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class TestList {
#Test
public void Test(){
List<String> myList = mock(List.class);
when(myList.get(0)).thenReturn("hello world");
Assert.assertEquals("hello world",myList.get(0));
}
}
this works.
I want to use elasticSearch repository inside a spring boot application .
I have a local running instance of elastic search 5.5.2
I've search for a while, tried so many combinations of the several sources but nothing yield a working solution , and right now I'm stuck with error :
Error creating bean with name 'elasticsearchTemplate'
what am i doing wrong ?
This is my main class
#SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class Application {
public static void main(String[] args) {
Logger logger = LoggerFactory.getLogger("chapters.introduction.HelloWorld1");
try
{
SpringApplication.run(Application.class, args);
}
catch(Exception e)
{
logger.info("caught an exception",e);
}
}
}
config class
#Configuration
#EnableElasticsearchRepositories(basePackages = "hello")
#ComponentScan(basePackages = {"hello"})
public class config {
#Bean
public NodeBuilder nodeBuilder() {
return new NodeBuilder();
}
#Bean
public ElasticsearchOperations elasticsearchTemplate() {
Settings.Builder elasticsearchSettings =
Settings.settingsBuilder()
.put("http.enabled", "false") // 1
.put("path.data", "/home/nad/elasticsearch_data") // 2
.put("path.home", "/home/nad/Downloads/elasticsearch-5.5.2"); // 3
return new ElasticsearchTemplate(nodeBuilder()
.local(true)
.settings(elasticsearchSettings.build())
.node()
.client());
}
}
my build.gradle file
group 'FirstWebServer'
version '1.0-SNAPSHOT'
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.8.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
jar {
baseName = 'gs-spring-boot'
version = '0.1.0'
}
repositories {
maven { url "http://repo.spring.io/milestone" }
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
// tag::jetty[]
compile("org.springframework.boot:spring-boot-starter-web") {
exclude module: "spring-boot-starter-tomcat"
}
compile("org.springframework.boot:spring-boot-starter-jetty")
// end::jetty[]
// tag::actuator[]
compile("org.springframework.boot:spring-boot-starter-actuator")
// end::actuator[]
//compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-elasticsearch', version: '1.2.5.RELEASE'
compile group: 'org.springframework.data', name: 'spring-data-elasticsearch', version: '3.0.1.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-parent', version: '2.0.0.M6', ext: 'pom'
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile group: 'org.projectlombok', name: 'lombok', version: '1.16.18'
testCompile("junit:junit")
}
what is the proper way of configuration ? some examples shows application.properties configuration , some dont .
What about compatability , some shows that only elasticsearch 2. * or lower, some said that 5
Its really confusing :(
Thank you very much for your help
To use Elasticsearch 5.x you need Spring Data release Kay (already released), which is only part of Spring Boot 2 (to be released soon). Right now your only option really is to use the latest Spring Boot 2 build and wait for a stable release.
Some people tried using Spring Data Kay with Spring boot 1.5, but ended up in dependency hell. Probably not worth the pain with Spring Boot 2 just around the corner.