I made two classes:
Main class with embedded Tomcat(8.5.20)
ServerEndpoint of Websocket
I run the main class on IntelliJ IDEA
and run this JavaScript: new WebSocket('ws://localhost:8080/ws')
in the console of Google Chrome.
I expected the response code is 200, but actually it is 404.
How can I fix this?
Main class:
package webapp;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import javax.servlet.ServletException;
import java.io.File;
public class Main {
private static final String STATIC_DIR = "src/main/static/";
public static void main(String[] args) throws ServletException, LifecycleException {
Tomcat tomcat = new Tomcat();
tomcat.setPort(8080);
File staticDir = new File(STATIC_DIR);
tomcat.addWebapp("/", staticDir.getAbsolutePath());
tomcat.start();
tomcat.getServer().await();
}
}
ServerEndpoint:
package webapp.websocket;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/ws")
public class SampleWebSocket {
#OnOpen
public void onOpen(Session session) {
System.out.println("open");
}
#OnClose
public void onClose(Session session) {
System.out.println("close");
}
#OnMessage
public String onMessage(String text) {
System.out.println("message:" + text);
return "Server:" + text;
}
}
Thank you.
I found a solution.
This question is dupricated.
I read Got 404 error on tomcat 7.0.47 websocket and editted my pom.xml.
Following is the whole of my pom.xml.
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>websocket-sample</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>websocket-sample</name>
<properties>
<java.version>1.8</java.version>
<maven.compiler.target>${java.version}</maven.compiler.target>
<maven.compiler.source>${java.version}</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>8.5.20</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-websocket</artifactId>
<version>8.5.20</version>
</dependency>
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
</dependency>
</dependencies>
</project>
Just add the following dependency to pom.xml
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-websocket</artifactId>
<version>8.5.20</version>
</dependency>
What solved the issue for me was switching from the javax.websocket-api dependency to the Tomcat-specific tomcat-embed-websocket dependency instead and switching all my imports (ServerEndpoint, onMessage, etc.) to the Tomcat-specific jakarta.websocket.* packages instead of the javax.websocket.x packages.
Here is the endpoint code that worked for me -- notice that there are no javax.websocket imports and instead I have jakarta.websocket imports:
import java.io.IOException;
import jakarta.websocket.EncodeException;
import jakarta.websocket.OnMessage;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;
#ServerEndpoint("/echo")
public class EchoEndpoint {
// Implementation.
#OnMessage
public void onMessage(
Session session,
String message)
throws
IOException,
EncodeException {
// Send the same message back.
session.getBasicRemote().sendText(message);
}
}
And my pom.xml file dependencies:
<!-- https://mvnrepository.com/artifact/org.apache.tomcat.embed/tomcat-embed-core -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>10.1.0-M8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat.embed/tomcat-embed-websocket -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-websocket</artifactId>
<version>10.1.0-M8</version>
</dependency>
As far as I can tell, the pom.xml should not contain the javax.websocket dependency at all, to ensure there are no collisions/clashes between that one and the Tomcat-specific tomcat-embed-websocket dependency.
Related
I'm creating an application with spring boot and I want to authenticate my application using JWT but it is in microservice. In the JWT service it runs normally but I want to authenticate all the microservice services so I put the JWT service code for the api-gateway but because it uses spring-cloud-starter-gateway I can't use spring-boot-starter-web so far everything well. My big problem is that when I run some service, a login page appears. I wanted to remove this page does anyone have any idea how to do this?
Here is my application code below:
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>routing</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>routing</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
<spring-cloud.version>2021.0.4</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>3.1.4</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<version>3.1.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties:
server.port=8080
spring.application.name=routing
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
eureka.instance.hostname=localhost
spring.cloud.gateway.discovery.locator.enabled=true
rsa.publickey=classpath:carts/public.pem
rsa.privatekey=classpath:carts/private.pem
#spring.main.web-application-type=reactive
spring.cloud.gateway.enabled=true
spring.cloud.gateway.routes[0].id=user
spring.cloud.gateway.routes[0].uri=lb://USER
spring.cloud.gateway.routes[0].predicates=Path=/user/**
spring.cloud.gateway.routes[1].id=testes
spring.cloud.gateway.routes[1].uri=lb://TESTES
spring.cloud.gateway.routes[1].predicates=Path=/testes/**
spring.cloud.gateway.routes[2].id=user-create
spring.cloud.gateway.routes[2].uri=lb://USER-CREATE
spring.cloud.gateway.routes[2].predicates=Path=/user-create/**
spring.cloud.gateway.routes[3].id=jwt
spring.cloud.gateway.routes[3].uri=lb://JWT
spring.cloud.gateway.routes[3].predicates=Path=/**
RsaKeyPropreties.java:
package com.example.routing.config;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import org.springframework.boot.context.properties.ConfigurationProperties;
#ConfigurationProperties(prefix = "rsa")
public record RsaKeyPropreties(RSAPublicKey publickey,RSAPrivateKey privatekey) {
}
SecurityConfig.java:
package com.example.routing.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import com.nimbusds.jose.proc.SecurityContext;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.nimbusds.jose.jwk.source.JWKSource;
import static org.springframework.security.config.Customizer.withDefaults;
import org.springframework.boot.autoconfigure.AutoConfiguration;
#Configuration
#AutoConfiguration
#EnableWebSecurity
public class SecurityConfig {
private final RsaKeyPropreties Rsakeys;
public SecurityConfig(RsaKeyPropreties Rsakeys) {
this.Rsakeys = Rsakeys;
}
#Bean
public InMemoryUserDetailsManager user(){
return new InMemoryUserDetailsManager(
User.withUsername("username")
.password("{noop}password")
.authorities("read")
.build()
);
}
#Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
return http
.csrf(csrf->csrf.disable())
//.authorizeRequests(auth->auth.antMatchers("/user**").authenticated())
.authorizeRequests(auth->auth.anyRequest().authenticated())
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
.sessionManagement(session->session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.httpBasic(withDefaults()).build();
}
#Bean
JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withPublicKey(Rsakeys.publickey()).build();
}
#Bean
JwtEncoder jwtEncoder() {
JWK jwk = new RSAKey.Builder(Rsakeys.publickey()).privateKey(Rsakeys.privatekey()).build();
JWKSource<SecurityContext> jws = new ImmutableJWKSet<>(new JWKSet(jwk));
return new NimbusJwtEncoder(jws);
}
}
RoutingApplication.java:
package com.example.routing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import com.example.routing.config.RsaKeyPropreties;
#EnableConfigurationProperties(RsaKeyPropreties.class)
#SpringBootApplication
#EnableDiscoveryClient
public class RoutingApplication {
public static void main(String[] args) {
SpringApplication.run(RoutingApplication.class, args);
}
}
Thanks!
For Servlet app, this will return 401 (unauthorized) instead of 302 (redirect to login) when authorization is missing or invalid:
http.exceptionHandling().authenticationEntryPoint((request, response, authException) -> {
response.addHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"Restricted Content\"");
response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());
});
For a reactive app, you can provide a ServerAccessDeniedHandler bean instead:
#Bean
ServerAccessDeniedHandler serverAccessDeniedHandler() {
return (var exchange, var ex) -> exchange.getPrincipal().flatMap(principal -> {
final var response = exchange.getResponse();
response.setStatusCode(principal instanceof AnonymousAuthenticationToken ? HttpStatus.UNAUTHORIZED : HttpStatus.FORBIDDEN);
response.getHeaders().setContentType(MediaType.TEXT_PLAIN);
final var dataBufferFactory = response.bufferFactory();
final var buffer = dataBufferFactory.wrap(ex.getMessage().getBytes(Charset.defaultCharset()));
return response.writeWith(Mono.just(buffer)).doOnError(error -> DataBufferUtils.release(buffer));
});
}
Spring-boot starters I maintain here (which are thin wrappers arround spring-boot-starter-oauth2-resource-server) are doing that by default plus a few other usefull things:
map authorities from a list of claims of your choice (giving you hand on case and prefix)
stateless session-management (like you do)
disabled CSRF (only if session-management is left stateless)
fine grained CORS config from properties
multi-tenancy (accept more than just one JWT issuer)
As a side note, what about having your gateway being a pass-through for OAuth2 (just forward requests authorization header and responses HTTP status) and implement resources access-control (spring-security .authorizeRequests() and #PreAuthorize rules) on resource-server, where you can unit-test it?
I have a test project where I'm trying to setup e2e api tests using rest-assured. Tests run fine if I run them from the feature files, however, when I try to run them with maven, 0 tests run. I believe there is something funky with my pom.xml but I can't figure it out...
My project structure looks like:this
My pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.0</version>
</parent>
<artifactId>qa-automation-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<groupId>com</groupId>
<packaging>jar</packaging>
<properties>
<java.version>17</java.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-bom</artifactId>
<version>7.2.3</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-suite</artifactId>
<version>1.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-junit-platform-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-spring</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-path</artifactId>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>xml-path</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<properties>
<configurationParameters>
cucumber.junit-platform.naming-strategy=long
</configurationParameters>
</properties>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
My Application.java
package com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
#PropertySources({
#PropertySource("classpath:application.properties")
})
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
My CucumberSpringConfiguration.class
import io.cucumber.spring.CucumberContextConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import com.Application;
#CucumberContextConfiguration
#SpringBootTest(classes = Application.class)
public class CucumberSpringConfiguration {
}
My CucumberTest.java
import org.junit.platform.suite.api.ConfigurationParameter;
import org.junit.platform.suite.api.IncludeEngines;
import org.junit.platform.suite.api.SelectClasspathResource;
import org.junit.platform.suite.api.Suite;
import static io.cucumber.junit.platform.engine.Constants.GLUE_PROPERTY_NAME;
#Suite
#IncludeEngines("cucumber")
#SelectClasspathResource("src/test/resources/example")
#ConfigurationParameter(key = GLUE_PROPERTY_NAME, value = "com.example")
public class CucumberTest {
}
I'm not really familiar with Spring though so I'm pretty sure I'm not using it correctly in my ApiTestStepDef.java
package com.example;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import io.cucumber.java.en.Given;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Assertions;
import org.springframework.beans.factory.annotation.Autowired;
import com.client.RestAssuredClient;
import com.model.User;
import com.utils.Helper;
import static io.restassured.RestAssured.given;
public class ApiTestStepDef {
private Response response;
private RequestSpecification request;
private User user;
private User responseBody;
#Autowired
private RestAssuredClient restAssuredClient;
#Given("{string} endpoint")
public void setBaseUsersURI(String url){
request =
given().log().all().
spec(restAssuredClient.createReqSpec(url));
}
#When("user posts request with details {string} {string} {string}")
public void sendRequest(String name, String gender, String status){
user = new User(name, gender, Helper.createRandomEmail(), status);
response =
request.given().log().all().
body(user).
when().
post().
then().log().all().
extract().response();
}
#Then("response status code is {int} and response contains correct user details")
public void checkResponseStatusCode(int statusCode){
response.then().spec(restAssuredClient.createResSpec(statusCode));
responseBody = response.getBody().as(User.class);
Assertions.assertEquals(user.getGender(), responseBody.getGender());
Assertions.assertEquals(user.getStatus(), responseBody.getStatus());
Assertions.assertEquals(user.getEmail(), responseBody.getEmail());
Assertions.assertEquals(user.getName(), responseBody.getName());
}
}
And RestAssuredClient.java
package com.client;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.builder.ResponseSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import io.restassured.specification.ResponseSpecification;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import static io.restassured.RestAssured.oauth2;
#Component
public class RestAssuredClient {
#Value("${access.token}")
private String accessToken;
#Value("${base.uri}")
private String baseUri;
public ResponseSpecification createResSpec(int statusCode){
return
new ResponseSpecBuilder()
.expectStatusCode(statusCode)
.expectContentType(ContentType.JSON)
.build();
}
public RequestSpecification createReqSpec(String url){
return new RequestSpecBuilder()
.setBaseUri(baseUri)
.setContentType(ContentType.JSON)
.setAuth(oauth2(accessToken))
.setBasePath(url)
.build();
}
}
#SelectClasspathResource("src/test/resources/example")
Typically src/test/resources is not part of the classpath.
After running mvn test have a look at target/test-classes to understand the structure of what is on the classpath.
I'm trying to run spring boot with spring data as basically as possible with swing.
However, even though all seems to be properly configured, when I try to run it, I get an error message saying it couldn't find my Service bean.
package db.westworld.dao;
import db.westworld.entities.RobotEntity;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface RobotRepository extends CrudRepository<RobotEntity, Integer> {
}
package db.westworld.service;
import db.westworld.entities.RobotEntity;
import java.util.Optional;
public interface IRobotService {
Optional<RobotEntity> findById(int id);
}
package db.westworld.service;
import db.westworld.dao.RobotRepository;
import db.westworld.entities.RobotEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
#Service
public class RobotService implements IRobotService {
private final RobotRepository robotRepository;
#Autowired
RobotService(RobotRepository robotRepository) {
this.robotRepository = robotRepository;
}
#Override
public Optional<RobotEntity> findById(int id) {
return robotRepository.findById(id);
}
public void saveRobot(RobotEntity robot) {
robotRepository.save(robot);
}
}
package db.westworld;
import db.westworld.view.RegisterRobot;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import java.awt.*;
#SpringBootApplication
public class WestworldApplication {
public static void main(String[] args) {
var ctx = new SpringApplicationBuilder(RegisterRobot.class).headless(false).run(args);
EventQueue.invokeLater(() -> {
var ex = ctx.getBean(RegisterRobot.class);
ex.setVisible(true);
});
}
}
package db.westworld.view;
import db.westworld.entities.RobotEntity;
import db.westworld.service.RobotService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import javax.swing.*;
import java.awt.event.*;
import java.util.Date;
#Controller
public class RegisterRobot extends JDialog {
private RobotService robotService;
#Autowired
public void setRobotService (RobotService robotService) {
this.robotService = robotService;
}
private void onOK() {
RobotEntity robot = new RobotEntity();
robot.setCreatedAt(new Date());
robot.setId(1);
robotService.saveRobot(robot);
dispose();
}
}
Error message:
Parameter 0 of method setRobotService in db.westworld.view.RegisterRobot required a bean of type 'db.westworld.service.RobotService' that could not be found.
Action:
Consider defining a bean of type 'db.westworld.service.RobotService' in your configuration.
(the JDialog implementation just includes the basics)
The same also happens when I try to autowire the repository.
Also, in case needed, here's my pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <groupId>db</groupId>
<artifactId>westworld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>westworld</name>
<description>westworldSpringBoot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
The parameter to new SpringApplicationBuilder() must be the class annotate with #SpringBootApplication, as shown in every Spring Boot example I've ever seen, e.g. Create an Application class in the "Getting Started - Building an Application with Spring Boot" guide.
It is a spring boot 2.0.0 application which was running earlier, but this error started after I added dependencies for spring-cloud-stream.I tried removing spring-fox dependency but it only removed the nested exception.
The complete error after removing spring-fox dependency:
ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.ArrayStoreException: sun.reflect.annotation.TypeNotPresentExceptionProxy
The complete pom.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.foo.bar.application</groupId>
<artifactId>application-reviews-manager</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>generic-name</name>
<description>Manager</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<application.utils.version>1.0.0</application.utils.version>
<application.utils.build.number>SNAPSHOT</application.utils.build.number>
<application.rnr.repositories.version>1.0.0</application.rnr.repositories.version>
<application.rnr.repositories.build.number>SNAPSHOT</application.rnr.repositories.build.number>
<dcp.config.version>0.0.1</dcp.config.version>
<dcp.config.build.number>SNAPSHOT</dcp.config.build.number>
<aspectj.version>1.8.9</aspectj.version>
</properties>
<dependencies>
<dependency>
<groupId>com.foo.bar.application</groupId>
<artifactId>application-rnr-repositories</artifactId>
<version>${application.rnr.repositories.version}-${application.rnr.repositories.build.number}</version>
</dependency>
<dependency>
<groupId>com.foo.bar.application</groupId>
<artifactId>application-utils</artifactId>
<version>${application.utils.version}-${application.utils.build.number}</version>
</dependency>
<dependency>
<groupId>com.foo.dcp.commons.config</groupId>
<artifactId>dcp-config-client</artifactId>
<version>${dcp.config.version}-${dcp.config.build.number}</version>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>5.6.3</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>5.6.3</version>
</dependency>
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock</artifactId>
<version>1.58</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.elasticsearch.test</groupId>
<artifactId>framework</artifactId>
<version>5.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-kafka</artifactId>
<version>1.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream</artifactId>
<version>1.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
I'm just a starter in spring-cloud-stream, so any help would be appreciated.
Edit:
We found out that the mistake is in the way or place the annotation
#EnableBinding is used.
The relevant pieces of codes are:
Application.java
package com.foo.bar;
import com.foo.bar.configuration.FooStreams;
import com.foo.bar.configuration.BarStreams;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.context.annotation.Bean;
import com.externalpackage.config.client.AppConfiguration;
import com.foo.bar.storage.repository.CustomElasticRestClient;
#SpringBootApplication
#EnableBinding({FooStreams.class, BarStreams.class})
public class FooApplication {
public static void main(String[] args) {
SpringApplication.run(FooApplication.class, args);
}
#Bean
public AppConfiguration appConfiguration() {
return AppConfiguration.instance();
}
#Bean
public CustomElasticRestClient highLevelElasticClient(AppConfiguration appConfiguration) throws Exception {
return new CustomElasticRestClient(appConfiguration);
}
}
FooStreams.java
package com.foo.bar.configuration;
import org.springframework.cloud.stream.annotation.Input;
import org.springframework.cloud.stream.annotation.Output;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.SubscribableChannel;
public interface FooStreams {
String OUTPUT = "foo-out";
#Output(value = OUTPUT)
MessageChannel postFooToOutChanel();
}
BarStreams.java
package com.tesco.foo.bar.configuration;
import org.springframework.cloud.stream.annotation.Output;
import org.springframework.messaging.MessageChannel;
public interface BarStreams {
String OUTPUT = "bar-out";
#Output(value = OUTPUT)
MessageChannel postBarToOutChanel();
}
KafkaPublisherService.java:
package com.foo.bar.service;
import com.foo.bar.configuration.FooStreams;
import com.foo.bar.configuration.BarStreams;
import com.foo.bar.domain.Foo;
import com.foo.bar.domain.Bar;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.MimeTypeUtils;
#Service
#Slf4j
public class KafkaPublisherService {
#Autowired
private BarStreams barStreams;
#Autowired
private FooStreams fooStreams;
public void sendBar(final Bar bar) {
log.info("Publishing bar to kafka {}", bar);
MessageChannel messageChannel = barStreams.postBarToOutChanel();
messageChannel.send(MessageBuilder
.withPayload(bar)
.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON)
.build());
}
public void sendFoo(final Foo foo) {
log.info("Publishing foo to kafka {}", foo);
MessageChannel messageChannel = fooStreams.postFooToOutChanel();
messageChannel.send(MessageBuilder
.withPayload(foo)
.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON)
.build());
}
}
application.properties
spring.cloud.stream.kafka.binder.brokers=localhost:9092
spring.cloud.stream.bindings.foo-out.destination=feedback
spring.cloud.stream.bindings.foo-out.contentType=application/json
spring.cloud.stream.bindings.bar-out.destination=review
spring.cloud.stream.bindings.bar-out.contentType=application/json
it is my first post here, till now I finally always found the solution for my dev problem, but now I am really exchausted. Maybe you can help me.
I am trying to setup simple Rest get web app basing on vaadin + spring boot +
maven on tomcat. In some combinations in .pom i received the get response : "sth else" but in such case the vaadin ui wasnt loaded. In such configuration I paste below I cannot obtain the get response:
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.drzinks</groupId>
<artifactId>site</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Site</name>
<description>CRUD Vaadin Spring App</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<vaadin.version>7.7.3</vaadin.version>
<vaadin.plugin.version>7.7.3</vaadin.plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-spring-boot-starter</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<!-- in order to have hot deploy in tomcat -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-bom</artifactId>
<version>7.7.3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
web.xml:
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<!-- Servlet declaration can be omitted in which case
it would be automatically added by Jersey -->
<servlet>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
</servlet>
<servlet-mapping>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
WelcomeController.java:
package com.drzinks;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.springframework.stereotype.Component;
#Component
#Path("/sth")
public class WelcomeController {
#GET
#Produces("text/plain")
public String getSthElse(){
return "sth elese";
}
}
SiteApplication:
package com.drzinks;
import javax.ws.rs.ApplicationPath;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SiteApplication {
public static void main(String[] args) {
SpringApplication.run(SiteApplication.class, args);
}
}
SiteUI.java:
package com.drzinks;
import org.springframework.beans.factory.annotation.Autowired;
import com.vaadin.annotations.Theme;
import com.vaadin.server.VaadinRequest;
import com.vaadin.spring.annotation.SpringUI;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
#SpringUI
#Theme("valo")
public class SiteUI extends UI {
#Autowired
private RestClient restClient;
private VerticalLayout layout;
#Override
protected void init(VaadinRequest request) {
setupLayout();
addHeader();
}
private void setupLayout() {
layout = new VerticalLayout(); //alt shift l extr local var
setContent(layout);
}
private void addHeader() {
// Label label1 = new Label(welcomeController.returnSth());
// layout.addComponent(label1);
Label label2 = new Label(restClient.getSthFromServer());
// Label label2 = new Label("restClient.getSthFromServer()");
layout.addComponent(label2);
}
}
RestClient.java:
package com.drzinks;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import org.springframework.stereotype.Component;
import com.vaadin.spring.annotation.UIScope;
#UIScope
#Component
public class RestClient {
private Client client = ClientBuilder.newClient();
private WebTarget webtarget = client.target("http://localhost:8080");
public String getSthFromServer() {
String response;
response = webtarget.path("sth")
.request().get(String.class);
return response;
}
}
folder_structure
If anyone could help, I would be very appreciated as I spent on this more than 12 hrs, breaking all night..