Request method of type post not recognized by Spring Rest Api - spring

This Code work fine :
#RestController
#RequestMapping("/api/post")
public class PostController {
#Autowired
private PostService postService;
public PostService getPostService() {
return postService;
}
public void setPostService(PostService postService) {
this.postService = postService;
}
#RequestMapping(value = "/userPost", method = RequestMethod.GET)
#ResponseBody
public String userPost(String username) {
try {
List<Validation> validations = new ArrayList<Validation>();
ValidationHandeler.rejectIfEmptyOrWhitespace(validations, username, "username is requierd");
if (validations.isEmpty()) {
List<Post> followers = getPostService().findUserPost(username);
return new Message(followers, MessageSuccesStatusEnum.SUCCESS).toString();
}
return new Message(validations, MessageSuccesStatusEnum.FAILED).toString();
} catch (Exception ex) {
return new Message("Error retriving follower list : " + ex.toString(), MessageSuccesStatusEnum.FAILED)
.toString();
}
}
and this is the output :
{"result":"0","info":["username is requierd"]}
but when ever I change the RequestMethod type to post it give me the following output :
{"timestamp":1492948640973,"status":404,"error":"Not Found","message":"No message available","path":"/api/post/userPost"}
does any body know how to fix this problem?

Looks like you are using GET instead of POST as a request method.
#RequestMapping(value = "/userPost", method = RequestMethod.GET)

<dependencies>
<!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>4.1.2</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.0.0</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/io.rest-assured/json-schema-validator -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>4.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
</dependencies>
TestClass TestNG
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import static io.restassured.RestAssured.*;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
public class basics {
#Test
public void getPlaceAPI()
{
RestAssured.baseURI = "https://maps.googleapis.com";
given().param("location", "42.3675294,-71.186966").param("radius",
"10000").param("key", "").when()
.get("/maps/api/place/textsearch/json").then().assertThat().statusCode(200);
}
}

Related

Powermock calling actual private method instead of mocking

I want to mock the private method "downloadFromNexus" but instead of mocking, actual method gets called while trying to mock here PowerMockito.doReturn("").when(spy, "downloadFromNexus", "", "");
#Component(value = "DownloadXFile")
#Order(1)
#Slf4j
public class DownloadXFile implements DownloadJarFiles {
#Value("${path}")
private String path;
#Override
public void download() throws IOException {
....
downloadFromNexus(path, outputFilePath);
log.info("jar {} downloaded", jar);
}
private void downloadFromNexus(final String url, final String outputFilePath) throws IOException {
FileUtils.copyURLToFile(
new URL(url),
new File(outputFilePath),
2000,
2000);
}
}
Test
#RunWith(PowerMockRunner.class)
#PrepareForTest(DownloadXFile.class)
#SpringBootTest(classes = DownloadXFile.class)
class DownloadXTest {
#Autowired
DownloadXFile downloadXFile;
#Test
public void test() throws Exception {
final DownloadXFilespy = PowerMockito.spy(downloadXFile);
PowerMockito.doReturn("").when(spy, "downloadFromNexus", "", "");
downloadXFile.download();
PowerMockito.verifyPrivate(spy, Mockito.times(1)).invoke("downloadFromNexus");
}
}
pom.xml
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.7.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>1.6.6</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mockito/mockito-all -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.0.42-beta</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
You called downloadXFile.download(); on original object instead of the spy.

#Valid annotation not working on Dto class - Spring Boot

I want validate my CustomerDTO using #Valid annotation.but also being validated at the same time using the #Valid annotation but it doesn't work, please help me.
This is my controller:
import lk.navishka.loginWithSecuruty.dto.CustomerDto;
import lk.navishka.loginWithSecuruty.entity.Customer;
import lk.navishka.loginWithSecuruty.service.CustomerService;
import lk.navishka.loginWithSecuruty.util.StandradResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
#RestController
#CrossOrigin
public class CustomerController {
#Autowired
CustomerService customerService;
#RequestMapping(value = {"/register"})
public ResponseEntity saveCustomer(#Valid #RequestBody CustomerDto customer){
customerService.saveCustomer(customer);
StandradResponse success = new StandradResponse(200, "success", null);
return new ResponseEntity(success, HttpStatus.OK);
}
}
this is My CustomerDTO class
import lombok.*;
import javax.persistence.Column;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.ArrayList;
#AllArgsConstructor
#NoArgsConstructor
#Getter
#Setter
#ToString
public class CustomerDto {
#NotNull
#Size(min = 9, message = "Nic have at least 9 characters ")
private String nic;
private String address;
#NotNull
#Size(min = 5, message = "FirstName have at least 5 characters ")
private String firstName;
#NotNull
#Size(min = 5, message = "LastName have at least 5 characters ")
private String lastName;
private ArrayList<UserDto> user = new ArrayList<>();
}
this is my ErrorDetails class
import java.util.Date;
public class ErrorDetails {
private Date timestamp;
private String message;
private String details;
public ErrorDetails(Date timestamp, String message, String details) {
super();
this.timestamp = timestamp;
this.message = message;
this.details = details;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
}
this my ExceptionHandler class
import lk.navishka.loginWithSecuruty.util.ErrorDetails;
import lk.navishka.loginWithSecuruty.util.StandradResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import java.util.Date;
#ControllerAdvice
public class ExceptionHandler {
//handling custom validation error
#ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<?> customValidationErrorHandling(MethodArgumentNotValidException exception){
ErrorDetails errorDetails = new ErrorDetails(new Date(),"Validator Error", exception.getBindingResult().getFieldError().getDefaultMessage());
return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST);
}
}
i use meven this is Pom.xml file
<?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>lk.navishka</groupId>
<artifactId>LoginWithSecuruty</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.2</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.4.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.4.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.4.2</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.18</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.modelmapper/modelmapper -->
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.3.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>7.0.1.Final</version>
</dependency>
<!--security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
This is the JSON value that i use with postman
{
"nic" : "656v",
"address" : "polpitiya",
"firstName" : "nn",
"lastName" : "",
"user": [{
"userName":"username1",
"email":"sample#gmail.com",
"password":"1234"
}]
}
Try the 6.2.0.final version of hibernate-validator, it will work.
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.2.0.Final</version>
</dependency>

Spring Security - Facebook

I want to login to my web app by facebook. I have a form with normal login and i want to add login with facebook. I've added my app to developers facebook by link http://localhost:8080/. I followed the example of
Using Spring Security 5 to integrate with OAuth 2-secured services such as Facebook and GitHub
I wrote following files
SocialConfig.java
package pl.java.learning.todolist.infrastructure.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.web.context.annotation.RequestScope;
import pl.java.learning.todolist.infrastructure.social.Facebook;
#Configuration
public class SocialConfig {
#Bean
#RequestScope
public Facebook facebook(OAuth2AuthorizedClientService clientService) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String accessToken = null;
if (authentication.getClass().isAssignableFrom(OAuth2AuthenticationToken.class)) {
OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
String clientRegistrationId = oauthToken.getAuthorizedClientRegistrationId();
if (clientRegistrationId.equals("facebook")) {
OAuth2AuthorizedClient client = clientService.loadAuthorizedClient(clientRegistrationId, oauthToken.getName());
accessToken = client.getAccessToken().getTokenValue();
}
}
return new Facebook(accessToken);
}
}
ApiBinding.java
package pl.java.learning.todolist.infrastructure.social;
import java.io.IOException;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.RestTemplate;
public abstract class ApiBinding {
protected RestTemplate restTemplate;
public ApiBinding(String accessToken) {
this.restTemplate = new RestTemplate();
if (accessToken != null) {
this.restTemplate.getInterceptors().add(getBearerTokenInterceptor(accessToken));
} else {
this.restTemplate.getInterceptors().add(getNoTokenInterceptor());
}
}
private ClientHttpRequestInterceptor getBearerTokenInterceptor(String accessToken) {
return new ClientHttpRequestInterceptor() {
#Override
public ClientHttpResponse intercept(HttpRequest request, byte[] bytes, ClientHttpRequestExecution execution) throws IOException {
request.getHeaders().add("Authorization", "Bearer " + accessToken);
return execution.execute(request, bytes);
}
};
}
private ClientHttpRequestInterceptor getNoTokenInterceptor() {
return new ClientHttpRequestInterceptor() {
#Override
public ClientHttpResponse intercept(HttpRequest request, byte[] bytes, ClientHttpRequestExecution execution) throws IOException {
throw new IllegalStateException("Can't access the Facebook API without an access token");
}
};
}
}
Facebook.java
package pl.java.learning.todolist.infrastructure.social;
public class Facebook extends ApiBinding {
private static final String GRAPH_API_BASE_URL = "https://graph.facebook.com/v2.12";
public Facebook(String accessToken) {
super(accessToken);
}
public Profile getProfile() {
return restTemplate.getForObject(GRAPH_API_BASE_URL + "/me", Profile.class);
}
}
Profile.java
package pl.java.learning.todolist.infrastructure.social;
import lombok.Data;
#Data
public class Profile {
private String id;
private String name;
}
In the file index.html i added following link to facebook
<img src="/image/facebook.png" class="imgsize img-fluid m-10 " margin="10px" alt="">
The file 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>pl.java.learning</groupId>
<artifactId>todo-list</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>todo-list</name>
<description>To-do list project</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.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>
<swagger.version>2.9.2</swagger.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</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-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>3.1.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>4.1.3</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-client</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
But it doesn't work and not redirect to facebook, maybe someone know how to fix this?
Regards
MyUserPrincipal
package pl.java.learning.todolist.infrastructure.security;
import java.util.Collection;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import pl.java.learning.todolist.domain.user.User;
#RequiredArgsConstructor
public class MyUserPrincipal implements UserDetails {
private final User user;
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return user.getRoles();
}
public Long getUserId() {
return user.getId();
}
#Override
public String getPassword() {
return user.getPassword();
}
#Override
public String getUsername() {
return user.getLogin();
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return user.getEnabled();
}
}

How to Log all the methods public method calls in AOP

I have some issue in Logging all the methods when a service calls. Code is like this:
package com.myproject.controller;
#RestController(/person)
public class Controller{
public Person getpersonInfo(){
......
getValidPerson();
}
}
public Person getValidPerson() {
isPersonValid(Person person);
....
}
Person class Methods :
package com.myproject.dao;
public class Dao{
public boolean isPersonValid(){
//Checks for the person is Valid
}
}
Aspect Class :
package com.myproject;
#Component
#Aspect
public class Logging{
#Before("execution(* com.myproject..*.*(..)))")
public void beforeServiceCall(Jointpoint jp) {
//Some Logging function
}
}
Main class like this
package com.myproject;
#SpringBootApplication
#EnableAutoConfiguration
#EnableLoadTimeWeaving(aspectjWeaving = EnableLoadTimeWeaving.AspectJWeaving.ENABLED)
#EnableAspectJAutoProxy()
public class Main implements LoadTimeWeavingConfigurer{
public static void main(String[] args){
......
}
}
Pom file :
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-instrument -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.1</version>
</dependency>
When I call the service http://localhost:8080/person - GET
getpersonInfo() is only Logged in this case, I have also tried
LTW , but do not solve
I need to log all internal methods to the service like is getValidPerson(),isPersonValid() mentioning all arguments to those invoked method.

Arquillian TomEE embedded test with web sockets

I' trying to write a test of a serverendpoint using websockets in an arquillian test. I get an error saying
Caused by: org.glassfish.tyrus.core.HandshakeException: Response code was not 101: 404.
When deploying, I get a warning in the log of the tomee:
WARNING: Can't set TomEE ServerEndpointConfig$Configurator
java.lang.NoSuchFieldException: defaultImpl
at java.lang.Class.getDeclaredField(Class.java:2070)
at org.apache.tomee.catalina.TomcatWebAppBuilder.forceEEServerEndpointConfigurator(TomcatWebAppBuilder.java:338)
at org.apache.tomee.catalina.TomcatWebAppBuilder.<init>(TomcatWebAppBuilder.java:284)
at org.apache.tomee.catalina.TomcatLoader.initialize(TomcatLoader.java:222)
at org.apache.tomee.embedded.Container.start(Container.java:293)
....
The endpoints are defined like this:
#ServerEndpoint("/games")
public class GameEndPoint {
#Inject
GameManager gameManager;
#Inject
private GameSessionHandler sessionHandler;
#OnOpen
public void open(Session session) {
}
#OnClose
public void close(Session session) {
}
#OnError
public void onError(Throwable error) {
}
#OnMessage
public void handleMessage(String payload, Session session) {
}
}
#ClientEndpoint
public class SocketClient {
#OnOpen
public void onOpen(Session session) {
}
#OnMessage
public void onMessage(String message, Session session) {
}
#OnClose
public void onClose(Session session, CloseReason closeReason) {
LOGGER.info(String.format("Session %s close because of %s", session.getId(), closeReason));
}
public void openConnection(URL url) {//URL injected arquillian resource, where url is for http connection..
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
try {
URI uri = URI.create(url.toString().replace("http", "ws") + "games");
container.connectToServer(this, uri);
} catch (DeploymentException | IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
throw new RuntimeException(ex);
}
}
}
My test is written in spock, which fails in setup
#RunWith(ArquillianSputnik)
class GameServiceSocketIT extends Specification {
#Deployment
public static Archive archive() {
return createDeployment();//shrinkwrap stuff
}
#ArquillianResource
URL url;
#Inject
SocketClient client;
def Game currentGame = null
def setup() { // run before every feature method
client.openConnection(url);
}
def 'init new game' () {
given: 'blabla'
blabla
when: 'blalba'
blabla
then: 'blabla'
blablabla...
}
}
My pom dependencies:
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.spock</groupId>
<artifactId>arquillian-spock-container</artifactId>
<version>1.0.0.Beta3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-core</artifactId>
<version>0.7-groovy-2.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.1.8</version>
<scope>test</scope>
</dependency>
<!-- For Arquillian Integration tests in TOMEE -->
<dependency>
<groupId>org.apache.openejb</groupId>
<artifactId>arquillian-tomee-embedded</artifactId>
<version>1.7.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.openejb</groupId>
<artifactId>tomee-embedded</artifactId>
<version>1.7.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-container-jdk-client</artifactId>
<version>1.8.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
Edit:
my createDeployment method:
return ShrinkWrap.create(WebArchive.class, "test.war")
.addAsWebInfResource(EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml"))
.addPackages(true, Filters.exclude(".*IT.class"), "engine")
.addPackages(true, Filters.exclude(".*IT.class"), "socket")
.addPackages(true, Filters.exclude(".*IT.class"), "persistence");
Replacing the dependency:
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
with the dependency:
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat7-websocket</artifactId>
<version>7.0.59</version>
<scope>provided</scope>
</dependency>
Fixes the problem and I now get the client to connect to my server, hower now I'm having problems with CDI injection in my ServerEndPoint. That seems to be another issue..

Resources